Arrays of ints in Java (exercise)

Write a program that initializes an array of 50 integers to random numbers between 0 and 199. Write a method smooth that takes the array and replaces each element with a weighted average of itself (with weight 1/2) and its two neighbors (with weight 1/4 each). The edge cases compute the average of itself and its only neighbor with weights 1/2.
Note that the method will need another array as a temporary storage.
Also write a method disturb that sets 3 randomly chosen elements in the array to random numbers.
Write a loop that performs some number of smooth calls and one call to disturb. Use the method delay to pause between the calls. Watch "waves' created in the array.


import java.util.Random;

public class Waves {

    private static Random rand = new Random();

    public static void main(String [] args) {
	int [] numbers = new int[50];

	//initialize(numbers);

	printIntArray(numbers);

	//delay(1000);



    }

    /**
    * 
    * The method prints its argument <code>arr</code>
    * element by element on one line, separated by commas,
    * with [ before the first element and ] after the last one 
    *
    */

    public static void printIntArray(int [] arr) {
	 System.out.print("[");
	 for (int i = 0; i < arr.length; ++i) {
	    System.out.print(arr[i]);
	    if (i != arr.length - 1)
	       System.out.print(", ");
	    }
	    System.out.println("]");	
   }

    /**
       the method produces a time delay for the given 
       number of milliseconds
    **/
    public static void delay(int millisec) {
	try {
	    Thread.sleep(millisec); // do nothing 
	}
	catch(InterruptedException e) {
	    System.out.println("The program has been interrupted");
	} 
    }


}

CSci 2101 course web site.

The views and opinions expressed in this page are strictly those of the page author. The contents of this page have not been reviewed or approved by the University of Minnesota.