xXAASXx / FASTPAGES2

Apache License 2.0
0 stars 0 forks source link

# Unit 8 Homework - 2D Arrays #13

Open xXAASXx opened 1 year ago

xXAASXx commented 1 year ago

Homework Hacks

import java.util.*;
import java.lang.Math.*;

public class Learning {

    private int[][] arr = new int[3][3];
    private int[][] reversed_arr = new int[3][3];

    public static void main(String[] args) {
        Learning l = new Learning();
        l.origInit(); l.reversedArray(); 
        System.out.println("Value of 1,1: " + l.valueOf(1, 1));
        System.out.println("Sum of products of rows: " + l.productSum());

        Learning w = new Learning();
        w.origInit(); w.reversedArray(); 
        System.out.println("Value of 2,1: " + w.valueOf(2, 1)); 
        System.out.println("Sum of products of rows: " + w.productSum());
    }

    public void origInit() {

        System.out.println("\nOriginal array:");
        // Assign a random value to the 2D array and print it
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                // Assign a random value to the 2D array using math.random()
                arr[i][j] = (int) (Math.random() * 10);
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }

    public void reversedArray() {

        System.out.println("\nReversed array:");

        // Reverse the 2D array and print it
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                // Reverses array by going backwards through the original array
                reversed_arr[i][j] = arr[arr.length - 1 - i][arr[i].length - 1 - j];
                System.out.print(reversed_arr[i][j] + " ");
            }
            System.out.println();
        }
    }

    public int productSum() {
        int product = 1;
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                // multiply product by value at this array index
                product *= arr[i][j];
            }
            // add product to sum after all in row were multiplied, then reset product back to 1
            sum += product;
            product = 1;
        }
        return sum;
    }

    public int valueOf(int a, int b) {
        // try to get array value, return exception if can't
        try {
            return arr[a][b];
        }
        catch (Exception e) {
            System.out.println("Error: " + e);
            return -1;
        }
    }

}

Learning.main(null);

Code Printed:

Original array: 7 1 2 4 9 2 0 8 5

Reversed array: 5 8 0 2 9 4 2 1 7 Value of 1,1: 9 Sum of products of rows: 86

Original array: 5 2 8 5 5 5 1 8 2

Reversed array: 2 8 1 5 5 5 8 2 5 Value of 2,1: 8 Sum of products of rows: 221