Question 1 FRQ
Methods and Control Structures FRQ's
public boolean simulate() {
int start = 0;
int numOfHops = 0;
while(start >= 0 && numOfHops < maxHops && start < goalDistance) {
start += hopDistance();
numOfHops++;
}
return start >= goalDistance;
}
- Run
num
simulations and returns the proportion of simulations in which the frog successfully reached or passed the goal
public double runSimulations(int num) {
int count = 0;
for (int i = 0; i < num; i++) {
if (simulate() == true) {
count++;
}
}
return double (count) / num;
}
public static int numberOfLeapYears(int year1, int year2) {
int count = 0;
for (int i = year1; i < year2 +1; i++) {
if(isLeapYear(i)) {
count++;
}
}
return count;
}
- Write the static method
dayOfWeek
, which returns the integer value representing the day of the week for the given date (month, day, year)
public static int dayOfWeek(int month, int day, int year) {
int firstDay = firstDayOfYear(year);
int day = dayOfYear(month, day, year);
return (firstDay + day - 1) % 7;
}
public static int arraySum(int[] arr) {
int sum = 0;
for (int i =0; i < arr.length; i++) {
sum += arr[i];
}
return sum;
}
- Write a static method
rowSums
that calculates the sums of each of the rows in a given two-dimensional array and returns these sums in a one dimensional array
public static int[] rowSums(int[][] arr2D) {
int[] arr;
for (int i =0; i < arr2D.length; i++) {
arr[i] = arraySum(arr2D[i]);
}
return arr;
}
- Initialize array with number of rows in arr2D, so
int[] arr = new int[arr2D.length];
public static boolean isDiverse(int[][] arr2D) {
int[] arr = rowSums(arr2D);
// Couldn't figure out rest
}
// Answer
public static boolean isDiverse( int[][] arr2D ) {
// gets sums of each row from method created in part b
int[] check = rowSums(arr2D);
// Creates two loops to check position 0 and 1 and so on
for (int i=0; i<check.length; i++) {
for (int j=i+1; j<check.length; j++) {
if (check[i] == check[j])
return false;
}
}
return true;
}