CSCI 201: Intro to Programming (Java)

Assignment 5.    Due: Fri, Nov 3

Please put your work in directory cs201 on your Linux account before 11:59pm of the day above.

  1. (25 points)   Write a Java application that asks the user for an integer n and generates a random array of integers of length n. The array must be passed into a custom method reverse() that reverses the order of elements in the original array. Print the original and reversed arrays.

    Name the project Hw5_1
    Solution

  2. (25 points)   Write a Java application containing the method
    int[] removeDuplicates(int a[])

    that takes an array of integers, removes duplicates from this array, and returns the resulting array with no duplicates. For example, if this method gets the following array

    1 4 9 16 9 7 4 9 11

    then the returned array should be

    1 4 9 16 7 11

    The output of the program must be the original array (with duplicates) and the resulting one (with duplicates removed).

    Your method must work not only with the array above, but with ANY array of length at most 50. The program should load the array from the command-line parameters.

    Name the project Hw5_2
    Solution

  3. (25 points)   Write a Java application that takes a set of n2 numbers from standard input (keyboard) for some n not known in advance, and composes a 2-dim array from them. For example, if the input numbers were
    2 45 16 22 17 21 67 29 45 67 97 35 68 34 90 72

    they have to be arranged in a 2-dim array as follows:

    2 45 16 22
    17 21 67 29
    45 67 97 35
    68 34 90 72

    Your program has to check if the number of input numbers is a square of an integer and report an error and terminate if this is not the case. You can assume that at most 100 numbers will be entered.

    If the input numbers can be arranged in an nxn table, the program has to iprint out the resulting table and compute the sum of numbers on each of the diagonals and print them out. For the above example the following sums have to be computed:

    diag1 = 2 + 21 + 97 + 72
    diag2 = 22 + 67 + 67 + 68

    Your program should work for any set of numbers, not just for the one above.

    Name the project Hw5_3
    Solution

  4. (25 points)   Write a Java application containing the method
    int[] merge(int a[], int b[])

    that merges two arrays, alternating elements from both arrays. If one array is shorter than the other one, then alternate as long as you can and then append the remaining elements from the longer array in their order. For example, if

    a = {1 4 9 16}
    b = {9 7 4 9 11 20 5}

    then merge returns the array

    1 9 4 7 9 4 16 9 11 20 5

    Initialize both arrays in your code (at least 5 elements in each array). You should not assume that the second array is always longer.
    Your program should display the original arrays and the merged array on the screen.

    Name the project Hw5_4
    Solution