CSA Blog

Ian Wu

FRQ - 2D Array Homework

public static boolean isNonZeroRow(int[][] array2D, int r) {
    boolean hasZero = false;
    for (int i = 0; i < array2D[r].length(); i++) {
        if (array2D[r][i] == 0) {
            hasZero = true;
        }
    }
    return hasZero;
}

b)

public static int[][] resize(int[][] array2D) {
   int[][] toReturn = new int[numNonZeroRows(array2D)][array2D[0].length];
   int k = 0;
   for (int i = 0; i < array2D.length; i++) {
      if (isNonZeroRow(array2D, r)) {
         k++;
         for (int j = 0; j < array2D[0].length; j++) {
            toReturn[k - 1][j] = array2D[i][j]
         }
      }
   }
   return toReturn;   
}

FRQ - Methods Homework

public int getScore() { 
    //  initialize score as 0
    int score = 0; 
    // check if each level has been reached. 
    // if statements are nested to ensure that points in a level can only be attained if all previous levels' goals have been reached
    if (levelOne.goalReached()) { 
        score = levelOne.getPoints(); 
        if (levelTwo.goalReached()) { 
            score += levelTwo.getPoints(); 
            if (levelThree.goalReached()) { 
                score += levelThree.getPoints();
            }
        }
    } 
    // if bonus, multiply by 3
    if (isBonus()) { 
        score *= 3;
    } 
    return score;
}

b)

public int playManyTimes(int num) { 
    int highestScore = 0; 
    // iterate as many times as requested
    for (int i = 0; i < num; i++) { 
        // simulate and check if simulation is greater than the already existing maximum
        play();
        int score = getScore();
        if (score > highestScore) { 
            highestScore = score;
        }
    } 
    // return result
    return highestScore;
}