FRQs - Methods and Control Structures

public class CheckDigit {
    /** Returns the number of digits in num. */
    public static int getNumberOfDigits(int num) {
        if (num == 0) {
            return 1;
        }
        int count = 0;
        while (num != 0) {
            count++;
            num /= 10;
        }
        return count;
    }

    /** Returns the nth digit of num.
     * Precondition: n >= 1 and n <= the number of digits in num
     */
    public static int getDigit(int num, int n) {
        int numDigits = getNumberOfDigits(num);
        int index = numDigits - n;
        for (int i = 0; i < index; i++) {
            num /= 10;
        }
        return num % 10;
    }

    /**
     * Multiply the first digit by 7,
     *   the second digit (if one exists) by 6,
     *   the third digit (if one exists) by 5, and so on.
     *   The length of the method's int parameter is at most six; therefore, the last digit of a six-digit number will be multiplied by 2.
     * 
     * Add the products calculated in the previous step.
     * 
     * Extract the check digit, which is the rightmost digit of the sum calculated in the previous step.
     * 
     * (2x7)+(8x6)+(3x5)+(4x4)+(1x3)+(5x2) = 
     * 14+48+15+16+3+10 = 
     * 106
     */

    ////////////////////          Part A          \\\\\\\\\\\\\\\\\\\\
    public static int getCheck(int num) {
        int sum = 0;
        int multiplier = 7;
        
        while (num > 0) {
            int digit = num % 10;
            sum += digit * multiplier;
            multiplier--;
            if (multiplier < 2) {
                multiplier = 2;
            }
            num /= 10;
        }
        
        int checkDigit = sum % 10;
        return checkDigit;
    }    

    /**
     * The method returns true if its parameter numWithCheckDigit, which represents a number containing a check digit, is valid, and false otherwise.
     * The check digit is always the rightmost digit of numWithCheckDigit
     * 
     * Returns true if numWithCheckDigit is valid, or false otherwise, as described in part (b).
     * Precondition: The number of digits in numWithCheckDigit is between two and seven, inclusive.
     * numWithCheckDigit >= 0
     */
    ////////////////////          Part B          \\\\\\\\\\\\\\\\\\\\
    public static boolean isValid(int numWithCheckDigit) {
        int num = numWithCheckDigit / 10; // Get rid of the check digit
        int checkDigit = numWithCheckDigit % 10; // Get the check digit
    
        return getCheck(num) == checkDigit; // Check if the computed check digit matches the given check digit
    }    
    
    public static void main(String[] args) {        
        int num1 = 283415;
        int check1 = getCheck(num1);
        System.out.println("Check digit for " + num1 + " is " + check1);
        // expected output: "Check digit for 123456 is 2"
    
        int num2 = 159;
        int check2 = getCheck(num2);
        System.out.println("Check digit for " + num2 + " is " + check2);
        // expected output: "Check digit for 9876543 is 4"
    
        int numWithCheck1 = 123455;
        boolean isValid1 = isValid(numWithCheck1);
        System.out.println(numWithCheck1 + " is " + (isValid1 ? "valid" : "invalid"));
        // expected output: "123455 is invalid"
    
        int numWithCheck2 = 111119;
        boolean isValid2 = isValid(numWithCheck2);
        System.out.println(numWithCheck2 + " is " + (isValid2 ? "valid" : "invalid"));
        // expected output: "111119 is invalid"
    }
}

CheckDigit.main(null);
Check digit for 283415 is 1
Check digit for 159 is 8
123455 is valid
111119 is invalid

FRQs - Classes

/**
 * This question involves the implementation of the AdditionPattern class, which generates a number pattern. The AdditionPattern object is constructed with two positive integer parameters, as described below.
 *   The first positive integer parameter indicates the starting number in the pattern.
 *   The second positive integer parameter indicates the value that is to be added to obtain each subsequent number in the pattern.
 * 
 * The AdditionPattern class also supports the following methods.
 *   currentNumber ===> returns current number
 *        next     ===> returns next number in the pattern
 *        prev     ===> returns the previous number in the pattern
 */

public class AdditionPattern {
    private int current;
    private final int start;
    private final int increment;

    public AdditionPattern(int start, int increment) {
        this.start = start;
        this.increment = increment;
        this.current = start;
    }
    
    public int currentNumber() {
        return current;
    }
    
    public void next() {
        current += increment;
    }
    
    public void prev() {
        if (current - increment >= start) {
            current -= increment;
        }
    }
}

public class AdditionPatternTester {
    public static void main(String[] args) {
        AdditionPattern pattern = new AdditionPattern(3, 7);
        System.out.println("Current number: " + pattern.currentNumber()); // Expected output: 3
        
        pattern.next();
        System.out.println("Current number: " + pattern.currentNumber()); // Expected output: 10
        
        pattern.next();
        System.out.println("Current number: " + pattern.currentNumber()); // Expected output: 17
        
        pattern.next();
        System.out.println("Current number: " + pattern.currentNumber()); // Expected output: 24
        
        pattern.prev();
        System.out.println("Current number: " + pattern.currentNumber()); // Expected output: 17
    }
}

AdditionPatternTester.main(null);
Current number: 3
Current number: 10
Current number: 17
Current number: 24
Current number: 17

FRQs - Arrays and ArrayLists

import java.util.ArrayList;

public class RepairSchedule {
    /** Each element represents a repair by an individual mechanic in a bay. */
    private ArrayList<CarRepair> schedule;

    /** Number of mechanics available in this schedule. */
    private int numberOfMechanics;
    private int mechanicNum;
    private int bayNum;

    /** Constructs a RepairSchedule object.
     * Precondition: n >= 0
     */
    public RepairSchedule(int n, int m, int b) {
        schedule = new ArrayList<CarRepair>();
        this.numberOfMechanics = n;
        this.mechanicNum = m;
        this.bayNum = b;
    }
    
    public int getMechanicNum() {
        return mechanicNum;
    }
    
    public int getBayNum() {
        return bayNum;
    }

    /**
     * Write the addRepair method. The method attempts to schedule a repair by the mechanic with identifier m in the bay with identifier b.
     * The repair can be scheduled if mechanic m and bay b are both available.
     * A mechanic is available if the given mechanic number does not appear in an element of schedule.
     * A bay is available if the given bay number does not appear in an element of schedule.
     * If the mechanic and bay are both available, the addRepair method adds the repair to schedule and returns true.
     * If either the mechanic or the bay are not available, the addRepair method returns false.
     */
    ////////////////////          Part A          \\\\\\\\\\\\\\\\\\\\
    public boolean addRepair(int m, int b) {
        for (CarRepair repair : schedule) {
            if (repair.getMechanicNum() == m || repair.getBayNum() == b) {
                return false;
            }
        }
        schedule.add(new CarRepair(m, b));
        return true;
    }

    /**
     * Write the availableMechanics method, which returns an ArrayList containing the mechanic numbers of all available mechanics.
     * If there is no available mechanic, an empty list is returned.
     * A mechanic is available if the mechanic’s identifier does not appear in schedule
     */
    ////////////////////          Part B          \\\\\\\\\\\\\\\\\\\\
    public ArrayList<Integer> availableMechanics() {
        ArrayList<Integer> availableMechanics = new ArrayList<Integer>();
        for (int i = 2; i <= 5; i++) { // iterate over all mechanic numbers
            boolean isAvailable = true;
            for (CarRepair repair : schedule) { // iterate over all repairs in schedule
                if (repair.getMechanicNum() == i) { // if the mechanic is already assigned to a repair
                    isAvailable = false;
                    break; // exit inner loop as soon as a mechanic is not available
                }
            }
            if (isAvailable) {
                availableMechanics.add(i); // add the available mechanic to the list
            }
        }
        return availableMechanics; // return the list of available mechanics
    }

    /** Removes an element from schedule when a repair is complete. */
    public void carOut(int b) {
        for (int i = 0; i < schedule.size(); i++) {
            if (schedule.get(i).getBayNum() == b) {
                schedule.remove(i);
                break;
            }
        }
    }

    public static void main(String[] args) {
        // Create a new repair schedule with 3 mechanics
        RepairSchedule schedule = new RepairSchedule(3, 4, 4);
    
        // Add some repairs to the schedule
        schedule.addRepair(0, 0);
        schedule.addRepair(1, 1);
        schedule.addRepair(2, 2);
        schedule.addRepair(0, 3);
        schedule.addRepair(1, 4);
    
        // Print out the schedule
        System.out.println("Current schedule:");
        for (CarRepair repair : schedule.schedule) {
            System.out.println(repair.getMechanicNum() + " " + repair.getBayNum());
        }
    
        // Print out the available mechanics
        ArrayList<Integer> availableMechanics = schedule.availableMechanics();
        System.out.println("Available mechanics:");
        for (int i : availableMechanics) {
            System.out.print(i + " ");
        }
    
        // Mark a repair as complete
        schedule.carOut(1);
    
        // Print out the updated schedule
        System.out.println("\nUpdated schedule:");
        for (CarRepair repair : schedule.schedule) {
            System.out.println(repair.getMechanicNum() + " " + repair.getBayNum());
        }
    }    
}

RepairSchedule.main(null);
|   
|   
|   public class RepairSchedule {
|       /** Each element represents a repair by an individual mechanic in a bay. */
|       private ArrayList<CarRepair> schedule;
|   
|       /** Number of mechanics available in this schedule. */
|       private int numberOfMechanics;
|       private int mechanicNum;
|       private int bayNum;
|   
|       /** Constructs a RepairSchedule object.
|        * Precondition: n >= 0
|        */
|       public RepairSchedule(int n, int m, int b) {
|           schedule = new ArrayList<CarRepair>();
|           this.numberOfMechanics = n;
|           this.mechanicNum = m;
|           this.bayNum = b;
|       }
|       
|       public int getMechanicNum() {
|           return mechanicNum;
|       }
|       
|       public int getBayNum() {
|           return bayNum;
|       }
|   
|       /**
|        * Write the addRepair method. The method attempts to schedule a repair by the mechanic with identifier m in the bay with identifier b.
|        * The repair can be scheduled if mechanic m and bay b are both available.
|        * A mechanic is available if the given mechanic number does not appear in an element of schedule.
|        * A bay is available if the given bay number does not appear in an element of schedule.
|        * If the mechanic and bay are both available, the addRepair method adds the repair to schedule and returns true.
|        * If either the mechanic or the bay are not available, the addRepair method returns false.
|        */
|       ////////////////////          Part A          \\\\\\\\\\\\\\\\\\\\
|       public boolean addRepair(int m, int b) {
|           for (CarRepair repair : schedule) {
|               if (repair.getMechanicNum() == m || repair.getBayNum() == b) {
|                   return false;
|               }
|           }
|           schedule.add(new CarRepair(m, b));
|           return true;
|       }
|   
|       /**
|        * Write the availableMechanics method, which returns an ArrayList containing the mechanic numbers of all available mechanics.
|        * If there is no available mechanic, an empty list is returned.
|        * A mechanic is available if the mechanic’s identifier does not appear in schedule
|        */
|       ////////////////////          Part B          \\\\\\\\\\\\\\\\\\\\
|       public ArrayList<Integer> availableMechanics() {
|           ArrayList<Integer> availableMechanics = new ArrayList<Integer>();
|           for (int i = 2; i <= 5; i++) { // iterate over all mechanic numbers
|               boolean isAvailable = true;
|               for (CarRepair repair : schedule) { // iterate over all repairs in schedule
|                   if (repair.getMechanicNum() == i) { // if the mechanic is already assigned to a repair
|                       isAvailable = false;
|                       break; // exit inner loop as soon as a mechanic is not available
|                   }
|               }
|               if (isAvailable) {
|                   availableMechanics.add(i); // add the available mechanic to the list
|               }
|           }
|           return availableMechanics; // return the list of available mechanics
|       }
|   
|       /** Removes an element from schedule when a repair is complete. */
|       public void carOut(int b) {
|           for (int i = 0; i < schedule.size(); i++) {
|               if (schedule.get(i).getBayNum() == b) {
|                   schedule.remove(i);
|                   break;
|               }
|           }
|       }
|   
|       public static void main(String[] args) {
|           // Create a new repair schedule with 3 mechanics
|           RepairSchedule schedule = new RepairSchedule(3, 4, 4);
|       
|           // Add some repairs to the schedule
|           schedule.addRepair(0, 0);
|           schedule.addRepair(1, 1);
|           schedule.addRepair(2, 2);
|           schedule.addRepair(0, 3);
|           schedule.addRepair(1, 4);
|       
|           // Print out the schedule
|           System.out.println("Current schedule:");
|           for (CarRepair repair : schedule.schedule) {
|               System.out.println(repair.getMechanicNum() + " " + repair.getBayNum());
|           }
|       
|           // Print out the available mechanics
|           ArrayList<Integer> availableMechanics = schedule.availableMechanics();
|           System.out.println("Available mechanics:");
|           for (int i : availableMechanics) {
|               System.out.print(i + " ");
|           }
|       
|           // Mark a repair as complete
|           schedule.carOut(1);
|       
|           // Print out the updated schedule
|           System.out.println("\nUpdated schedule:");
|           for (CarRepair repair : schedule.schedule) {
|               System.out.println(repair.getMechanicNum() + " " + repair.getBayNum());
|           }
|       }    
|   }
Unresolved dependencies:
   - class CarRepair

FRQs - 2D Arrays

public class ArrayResizer {
    /**
     * Write the method isNonZeroRow
     *     which returns true if and only if all elements in row r of a two-dimensional array array2D are not equal to zero
     */
    ////////////////////          Part A          \\\\\\\\\\\\\\\\\\\\
    public static boolean isNonZeroRow(int[][] array2D, int r) {
        for (int col = 0; col < array2D[r].length; col++) {
            if (array2D[r][col] == 0) {
                return false;
            }
        }
        return true;
    }

    public static int numNonZeroRows(int[][] array2D) {
        int count = 0;
        for (int i = 0; i < array2D.length; i++) {
            if (isNonZeroRow(array2D, i)) {
                count++;
            }
        }
        return count;
    }    

    /**
     * Write the method resize
     *     which returns a new two-dimensional array containing only rows from array2D with all non-zero values.
     *     The elements in the new array should appear in the same order as the order in which they appeared in the original array
     */
    ////////////////////          Part B          \\\\\\\\\\\\\\\\\\\\
    public static int[][] resize(int[][] array2D) {
        // count the number of non-zero rows in the original array
        int numNonZeroRows = numNonZeroRows(array2D);
        
        // create a new 2D array with the same number of columns as the original array
        // and the number of rows equal to the count of non-zero rows
        int[][] resizedArray = new int[numNonZeroRows][array2D[0].length];
        
        // iterate over each row in the original array
        // if it is a non-zero row, copy it to the new array
        int row = 0;
        for (int i = 0; i < array2D.length; i++) {
            if (isNonZeroRow(array2D, i)) {
                for (int j = 0; j < array2D[0].length; j++) {
                    resizedArray[row][j] = array2D[i][j];
                }
                row++;
            }
        }
        
        // return the new array
        return resizedArray;
    }

    public static void main(String[] args) {
        int[][] array = {
            {0, 0, 0},
            {1, 2, 3},
            {0, 0, 0},
            {4, 5, 6},
            {0, 0, 0}
        };

        // test isNonZeroRow
        System.out.println(isNonZeroRow(array, 0)); // false
        System.out.println(isNonZeroRow(array, 1)); // true

        // test resize
        int[][] resizedArray = resize(array);

        // print original array
        System.out.println("Original array:");
        for (int[] row : array) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }

        // print resized array
        System.out.println("Resized array:");
        for (int[] row : resizedArray) {
            for (int val : row) {
                System.out.print(val + " ");
            }
            System.out.println();
        }
    }
}

ArrayResizer.main(null);
false
true
Original array:
0 0 0 
1 2 3 
0 0 0 
4 5 6 
0 0 0 
Resized array:
1 2 3 
4 5 6