Computer Science 15-100 (Sections T & U), Spring 2008
Class Notes:  Using Arrays


Logistics

  1. Schedule
    1. Bonus projects from Bonus Lecture #1 due today!
    2. Bonus lecture on Thursday:  How to write simple 2d board games (Connect4, WordSearch)
    3. Test 1 returned in recitation on Friday
    4. No hw due this week
    5. No quiz this week
    6. Hw8 due next Friday (available later this week)
  2. Reading:
    1. L&L Chapter on Arrays

Topic Outline:

public class ArraysSamples {

    public static java.util.Scanner scanner = new java.util.Scanner(System.in);
    public static java.util.Random random = new java.util.Random();

    public static void example00_load_and_print_an_array() {
        int[] a = new int[10]; // 10 element array
        int i;
        // load the array
        for (i=0; i<a.length; i++)  // a.length equals 10 here
            a[i] = 2*i;  // so a[0]=0, a[1]=2, a[2]=4,...
        // print the array
        for (i=0; i<a.length; i++)
            System.out.println("a[" + i + "] = " + a[i]);
    }

    public static void example01_load_and_print_an_array_with_randoms() {
        int[] a = new int[10]; // 10 element array
        int i;
        // load the array
        for (i=0; i<a.length; i++)  // a.length equals 10 here
            a[i] = random.nextInt(100);
        // print the array
        for (i=0; i<a.length; i++)
            System.out.println("a[" + i + "] = " + a[i]);
    }
    
    public static void example02_load_and_print_an_array_with_methods() {
        // public static java.util.Random random = new java.util.Random();
        int[] a = new int[10]; // 10 element array
        loadArray(a);
        printArray(a);
        printArrayAnotherWay(a);
        printArrayYetAnotherWay(a);
    }

    public static void example03_another_way_to_write_a_load_method() {
        int[] a = makeArray(10);
        printArray(a);
        printArrayAnotherWay(a);
        printArrayYetAnotherWay(a);
    }
    
    public static void loadArray(int[] a) {
        // load the array
        int i;
        for (i=0; i<a.length; i++)  // a.length equals 10 here
            a[i] = random.nextInt(100);
    }

    public static void printArray(int[] a) {
        System.out.print("a[] = {");
        int i;
        for (i=0; i<a.length; i++) {
            if (i > 0) System.out.print(", ");
            System.out.print(a[i]);
        }
        System.out.println("}");
    }
    
    public static void printArrayAnotherWay(int[] a) {
        int i;
        for (i=0; i<a.length; i++)
            System.out.println("a[" + i + "] = " + a[i]);
    }

    public static void printArrayYetAnotherWay(int[] a) {
        int i;
        for (i=0; i<a.length; i++) {
            System.out.printf("a[%2d]=%2d  ",i,a[i]);
            if (i % 5 == 4) System.out.println();
        }
        // print a newline unless we just did so!
        if (a.length % 5 != 0) System.out.println();
    }
        
    public static int[] makeArray(int size) {
        int[] result = new int[size];
        loadArray(result);
        return result;
    }

    public static void example04_make_a_variable_sized_array() {
        int size;
        do {
            System.out.print("Enter size of array: ");
            size = scanner.nextInt();
            if (size < 0) System.out.println("Size must be non-negative");
        } while (size < 0);        
        int[] a = makeArray(size);
        printArray(a);
        printArrayAnotherWay(a);
        printArrayYetAnotherWay(a);
    }

    public static void example05_use_a_statically_allocated_array() {
        System.out.println("Here we set the array 'a' to { 1, 3, 5, 7, 9 }");
        int[] a = { 1, 3, 5, 7, 9 };
        printArray(a);
    }

    public static void example06_find_max_value_in_an_array() {
        int[] a = makeArray(10); // 10 random elements in the array
        printArray(a);
        int max = getMax(a);
        System.out.println("Max value in a: " + max);
    }

    public static void example07_find_index_of_max_value() {
        int[] a = makeArray(10); // 10 random elements in the array
        printArray(a);
        int max = getMax(a);
        int maxIndex = getIndexOfMax(a);
        System.out.println("Max value in a: " + max + " at " + maxIndex);
    }
    
    public static int getMax(int[] x) {
        if ((x == null) || (x.length == 0))
            return -1;
        int i, max = x[0];
        for (i=1; i<x.length; i++)
            max = Math.max(max,x[i]);
        return max;
    }
    
    public static int getIndexOfMax(int[] x) {
        if ((x == null) || (x.length == 0))
            return -1;
        int i, maxIndex = 0;
        for (i=1; i<x.length; i++)
            if (x[i] > x[maxIndex])
                maxIndex = i;
        return maxIndex;
    }

    public static void example08_find_sum_of_values_in_array() {
        int[] a = makeArray(3); // 3 random elements in the array
        printArray(a);
        int sum = getSum(a);
        System.out.println("Sum of values in a: " + sum);
    }
    
    public static int getSum(int[] a) {
        int i, result = 0;
        for (i=0; i<a.length; i++)
            result += a[i];
        return result;
    }

    public static void example09_count_the_odd_elements_in_the_array() {
        int[] a = makeArray(10); // 10 random elements in the array
        printArray(a);
        int odds = countOdds(a);
        System.out.println("# of odd values in a: " + odds);
    }
    
    public static int countOdds(int[] a) {
        int i, result = 0;
        for (i=0; i<a.length; i++)
            if (a[i] % 2 == 1)
                result++;
        return result;
    }

    public static void example10_swap_two_elements_in_an_array() {
        int[] a = makeArray(10); // 10 random elements in the array
        printArray(a);
        System.out.println("Swapping element 0 with element 1");
        swap(a,0,1);
        printArray(a);
    }
    
    public static void swap(int[] a, int i, int j) {
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }

    public static void example11_test_if_arrays_are_equal() {
        int[] a1 = { 1, 2, 3 };
        int[] a2 = { 1, 2 };
        int[] a3 = { 1, 2, 3 };
        System.out.println(arraysAreEqual(a1,a1));
        System.out.println(arraysAreEqual(a1,a2));
        System.out.println(arraysAreEqual(a1,a3));
        System.out.println(arraysAreEqual(a1,null));
    }
    
    public static boolean arraysAreEqual(int[] a1, int[] a2) {
        // return a2.equals(a1);  // NO GOOD!
        // return java.util.Arrays.equals(a1,a2); // WORKS, but....
        // handle the null
        if ((a1 == null) || (a2 == null))
            return ((a1 == null) && (a2 == null));
        // not in the null case
        if (a1.length != a2.length)
            return false;
        // non-null and same length
        int i;
        for (i=0; i<a1.length; i++)
            if (a1[i] != a2[i])
                return false;
        return true;
    }
    
    public static void example12_use_arrays_to_test_for_anagrams() {
        System.out.print("Enter two strings: ");
        String s1 = scanner.next();
        String s2 = scanner.next();
        System.out.println("isAnagram(" + s1 + "," + s2 + ") = " +
                           isAnagram(s1,s2));
    }
    
    public static int[] charCounts(String s) {
        s = s.toUpperCase();
        int[] counts = new int[26];
        int i;
        for (i=0; i<s.length(); i++) {
            char c = s.charAt(i);
            if ((c >= 'A') && (c <= 'Z'))
                ++counts[(c - 'A')];
        }
        return counts;
    }
    
    public static boolean isAnagram(String s1, String s2) {
        int[] counts1 = charCounts(s1);
        int[] counts2 = charCounts(s2);
        int i;
        for (i=0; i<26; i++)
            if (counts1[i] != counts2[i])
                return false;
        return true;
    }

    // The Locker Problem
    public static void example13_the_locker_problem() {
        System.out.print("How many lockers: ");
        int lockers = scanner.nextInt();
        boolean[] isOpen = new boolean[lockers+1];
        int student, locker;
        for (student=1; student<=lockers; student++) {
            for (locker=student; locker<=lockers; locker += student)
                isOpen[locker] = !isOpen[locker];
        }
        System.out.println("Open lockers:");
        for (locker=1; locker<=lockers; locker++)
            if (isOpen[locker])
                System.out.println(locker);
    }

    ////////////////////////////////
    // Helper code
    ////////////////////////////////
        
    public static void main(String[] args) {
        java.util.ArrayList<String> examples = new java.util.ArrayList<String>();
        try {
            Class c = Class.forName("ArraysSamples");
            java.lang.reflect.Method[] methods = c.getMethods();
            for (java.lang.reflect.Method method : methods) {
                if (method.getName().startsWith("example"))
                    examples.add(method.getName());
            }
            java.util.Collections.sort(examples);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        while (true) {
            System.out.println("\n--------------------------");
            System.out.println("Choose from these examples:");
            for (int i=0;i<examples.size();i++)
                System.out.println("    " + examples.get(i));
            System.out.print("\nWhich example: [<0 to exit] ");
            int choice = scanner.nextInt();
            System.out.println("\n--------------------------");
            if (choice < 0) break;
            else if (choice >= examples.size())
                System.out.println("No such example");
            else try {
                Class c = Class.forName("ArraysSamples");
                java.lang.reflect.Method m = c.getMethod(examples.get(choice));
                m.invoke(null);
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }    
}

carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem   -   carpe diem