Initial Question

This question involves a two-dimensional array of integers that represents a collection of randomly generated data. A partial declaration of the Data class is shown. You will write two methods of the Data class.

public class Data {
    public static final int MAX = /* value not shown */;
    private int[][] grid;
    /** Fills all elements of "grid" with randomly generted values, as described in part a
     * Precondition: :"grid" is not null
     * "grid" had at least one element
     */
    public void repopulate(){
        /* to be implemented in part a */
    }
    /** Returns the number of columns in "grid" that are in increasing order, as described
     * in part b
     * Precondition: "grid" is not null
     * "grid" has at least one element
     */
    public int countIncreasingCols(){
        /* to be implemented in part b */
    }
    // there may be instances variables, constructors, and methods not shown.
}


Part A

Write the repopulate method, which assigns a newly generated random value to each element of grid. Each value is computed to meet all of the following criteria, and all valid values must have an equal chance of being generated.

  • The value is between 1 and MAX, inclusive.
  • The value is divisible by 10.
  • The value is not divisible by 100. Complete the repopulate method

    Part B

  • Write the countIncreasingCols method, which returns the number of columns in grid that are in increasing order. A column is considered to be in increasing order if the element in each row after the first row is greater than or equal to the element in the previous row. A column with only one row is considered to be in increasing order. The following examples show the countIncreasingCols return values for possible contents of grid. The return value for the following contents of grid is 1, since the first column is in increasing order but the second and third columns are not.

Answer

  • The first thing I see is the “grid” variable being assigned to a 2D integer list
  • generate random values –> import java.util.Random;
    • Random rand = new Random(); int randomNum = rand.nextInt(max – min + 1) + min;
import java.util.Random; // The code asks for a random number to be genrated. so I use hte Random class. Can also use Math.random()

public class Data { // initializing the class 
    public static final int MAX = 100; // set to 100 for better understanding
    private int[][] grid; // 
    public void repopulate(int rows, int columns){ // added two variables. These variables decide how many rows and columns the grid will have
        this.grid = new int[rows][columns]; // as the grid is a privae variable of the class, have to use "this.grid" when calling it
        int max = this.MAX; // initalizing a class variable to a method variable for easier use
        int min = 1;
        Random rand = new Random(); // creating a new object from the Random class to get random ints
        /*
         * Iterating through the grid length to get the rows
         * then iterating through the the 2D array to get the columns (numbers)
         * Getting a random int that is divisible by 10 but not by 100
         * assigning that int to the position of hte respective row and column
         */
        for (int i = 0; i < this.grid.length; i++){ 
            for (int j = 0; j < this.grid[i].length; j++){
                int num = 0;
                while (!(num >= min && num <= max && num % 10 == 0 && num % 100 != 0)){
                    num = rand.nextInt(max - min + 1) + min;
                }
                this.grid[i][j] = num;
            }
        }
        
    }
    // Contructor for the Class. When a new class is created with an object, this is the first function called
    public Data(int rows, int columns){
        this.repopulate(rows, columns);
    }

    /*
     * Calculating if the values are in increasing order for any of these columns. 
     * Iterates through each row and then checks if the row before in the same column had a smaller number or not
     * return 0 if none and otherwise number of columns with the increasing order
     */
    public int countIncreasingCols(){
        /* to be implemented in part b */
        int count = 0;
        for (int col = 0; col < this.grid[0].length; col ++){
            boolean Ascending = true;
            for (int row = 1; row < this.grid.length; row ++){
             if(this.grid[row][col] < grid[row -1][col]){
                Ascending = false;
             }   
            }
            if (Ascending){
                count ++;
            }
        }
        return count;
    }

    // Getter method to display the output
    public int[][] getter(){
        return this.grid;
    }

    // This is here to show the output on to a terminal in jupyter. Not needed to answer the question or part of the answer.
    public static void main(String[] args){
        Data new_obj = new Data(3, 3);

        int[][] grid = new_obj.getter();
        int max = Data.MAX;
        int min = 1;
        Random rand = new Random();
        for (int i = 0; i < grid.length; i++){
            for (int j = 0; j < grid[i].length; j++){
                System.out.print(grid[i][j] + " ");
            }
            System.out.println();
        }
        int increasing_cols = new_obj.countIncreasingCols();
        System.out.println(increasing_cols);
    }
}

Data.main(null)
70 50 80 
70 60 90 
30 60 40 
1

Detailed Summary

  • import java.util.Random;: The code begins by importing the Random class from the java.util package. This class will be used to generate random numbers.

  • public class Data { ... }: The Data class is defined. It encapsulates functionality related to a 2D grid of integers. The class includes the following components:

    • public static final int MAX = 100;: A constant integer named MAX is declared with a value of 100. This constant is marked as static and final, making it a class-level constant that cannot be changed.

    • private int[][] grid;: An instance variable grid is declared as a 2D array of integers. This variable is private, meaning it can only be accessed within the class.

    • public void repopulate(int rows, int columns) { ... }: This method is responsible for filling the grid with random numbers that meet specific criteria. It takes rows and columns as arguments to determine the size of the grid.

    • public Data(int rows, int columns) { ... }: The constructor of the class. It initializes a new Data object by calling the repopulate method.

    • public int countIncreasingCols() { ... }: This method calculates the number of columns in grid that have values in increasing order. It iterates through each column and checks if the values in the column are in ascending order.

    • public int[][] getter() { ... }: A getter method that allows external classes to access the grid.

    • public static void main(String[] args) { ... }: The main method is defined. It serves as a test harness for the Data class. It creates a new Data object, prints out the grid, and counts the number of increasing columns.

    • Data.main(null): A call to the main method, which starts the execution of the program.

Overall, this Java code defines a class (Data) for managing a 2D grid of integers. It provides methods for populating the grid with random numbers, counting the number of increasing columns, and retrieving the grid itself. The main method serves as a test harness for the class.

Grading:

|Criteria|Score| Reason | |-|-|-| |Traverses grid (no bounds errors) | 1| uses this.grid| |Generates a random integer in a range based on MAX. assume or verify that MAX >= 10 | 1 | assumes MAX as 100 | | Ensures that all produced values are divisible by 10 but not by 100 | 1 | seen in the while loop in the repopulate method| | Assigns appropriate values to all elements of grid (algorithm) | 1 | I successfully assign as the this.grid[i][j] = num; | |Traverses grid in column major order (no loop header bounds errors) | 1 | The first for loop in the increaseingcols method is based on columns this.grid[0]| |Compares two elements in the same column of grid | 1 | I compare this.grid[row][col] < grid[row -1][col] query in a if loop | | Determines whether a single column is in increasing order (algorithm) | 1 | if the previous row in the column is smaller than the current and so forth for all rows count ++ | | Counts all columns that are identified as increasing (algorithm) | 1 | as the count variable is in the first for loop, all columns are counted | | Returns calculated count of increasing columns | 1 | This is seen in the return count; command line |

Total Score: 9 / 9

Takeaways

The Java code effectively utilizes the Random class for generating random integers. The Data class, with its constant MAX set to 100, dynamically creates a 2D array based on provided parameters. Noteworthy is the repopulate method, where random numbers are generated, adhering to specific criteria such as divisibility by 10 and non-divisibility by 100. The countIncreasingCols method intelligently analyzes column order, employing nested loops for precise evaluation. Moreover, the code emphasizes the value of informed assumptions, exemplified by the MAX constant, streamlining complex scenarios. This approach, coupled with methodical problem analysis, lays a robust foundation for effective code development.

Assumuming values can help solve these problems ans also creating tester methods and constant checking can also help solve these problems. I missed alot of “;” which became better.

Notes on other Students

  • Started with 2D arrays, Had some understanding with the 2D arrays
  • Copied the answer from answer
  • Manny