## Computing Concepts with Java Essentials Laboratory Notebook Chapter 9 - Arrays, Vectors and Matrices

### Cay S. Horstmann Geof Pawlicki

Once this form has been customized for your institution, you can use this button to send your lab work. Be sure to read the instructions before starting your work.

#### Lab Objectives

To gain experience with

• using arrays and vectors to collect objects
• accessing vector elements and resizing vectors
• passing arrays and vectors to functions
• common array algorithms
• building classes containing arrays and vectors
• using matrices for two-dimensional collections

### P1. Array Subscripts

In the text, we have frequently used the Numeric.randomInt function to generate random integers. For example, Numeric.randomInt(1, 6) generates random numbers between 1 and 6, simulating the throw of a die. In this lab assignment, you will use an array to test whether the random generator is fair, that is, whether each possible value is generated approximately equally often.

• how many random numbers should be generated
• what is the lowest number in the range (e.g. 1)
• what is the highest number in the range (e.g. 6)

Make an array with high - low + 1 elements, one for each possible outcome. Set each element to 0. Then keep calling the random number generator. If it returns a value v, then increment the counter belonging to v. There is just one catch. The random numbers are generated in the range low...high. The array subscripts fall in the range 0...high - low. Therefore, you need to shift the ranges: the array element corresponding to the random value v has subscript v - low.

After all numbers have been generated, print the counters. Here is a typical program run:

```How many numbers do you want to generate? 1000
What is the low value? 1
What is the high value? 10
1    78
2   101
3   118
4    97
5   103
6   102
7   112
8    91
9    94
10  104```

### P2. Using Arrays to Collect Objects

Arrays can hold objects, not just numbers. In the following lab program, you will generate random circle objects and store them in an array. If a circle does not intersect any of the previously stored circles, you will add it to the array. Finally, display all circles that you collected in the array. The result should look something like this: (Note that none of the circles intersect.)

Use the code of the circleIntersect function that is given below to test whether two circles intersect. To randomly generate a circle, simply pick random x- and y- positions between -10 and 10 for the center and a random radius between 0 and 1. You need to compare each newly generated circle with all other circles before you can add it. If the new circle passes the test, add it to the end of the array. Note that the array will have fewer elements than the number of generated circles since you are rejecting sme of the circles. You will need to keep track of the actual number of circles in the array.

```import ccj.*;

public class Circles extends GraphicsApplet
{  /**
* Test if two circles intersect
* (distance between centers is less than sum of radii)
* @param c1 the first circle
* @param c2 the second circle
*/

boolean circleIntersect(Circle c1, Circle c2)
Math.sqrt(Math.pow((c2.getCenter().getX() -
c1.getCenter().getX()),2) +
Math.pow((c2.getCenter().getY() -
c1.getCenter().getY()),2)))
return false;
else
return true;
}

/**
* Program to plot a finite number of non-overlapping,
*           randomly sized circles.
*/

public void run()
{  int nCircles = 0; /* the actual number of circles in the array */
int maxCircles = readInt("How many random circles would you like to see ? ");
Circle[] randCircles;

/*
*/

}
}```

Using the debugger or a print statement, find out what percentage of circles was rejected.

Since you don't know the exact number of circles that need to be stored, and the upper bound--the total number of random circles--is higher than the actual requirements, it would make sense to use a Vector to store the circles instead. Rewrite the program to use a Vector to hold the circles instead. Whenever a circle passes the test, call addElement to add it to the end of the vector.

### P3. Return Parameters and Return Values

Here is a function that receives an array of integers and creates a new array, with the entries reversed. For example, if the input array contains 1 2 3 4, the output array contains 4 3 2 1. Note that this function has an array parameter and an array return value.

```/**
* compute the reverse of an array
* @param intValues an array of integer values
* @return a copy of the array, with the elements reversed
*/
public static int[] reverse(int[] intValues)
{  int[] result = new int[intValues.length];

int i;
for(i = 0 ; i < intValues.length; i++)
result[intValues.length - i - 1] = intValues[i];

return result;
}
```

Note that this function does not change the intValues array. Rewrite this function so that it reverses the intValues array in place, without computing a new array. Supply a program that tests your function.

### P4. Simple Array Algorithms

Consider finding an average grade from a sequence of 7 grades where the lowest and highest scores are discarded. Using the methods for Finding a Value, Counting, Collecting Matches and Deleting and Element given in the text, write a program to locate the max and min values in 87, 95, 90, 76, 43, 80, 84, discard them, and compute the average of the remaining scores.

How does your program handle duplicate grades ? For example, how would it process 95, 95, 95, 80, 78, 68, 68? What do you think it should do?

### P5. Avoiding Parallel Arrays

Write a program that reads in the names and scores of students and displays the names of the students with the highest and lowest score.

A simple method of carrying out this task would be to have two parallel vectors

```String[] names;
int[] scores;```

However, you should avoid parallel vectors in your solution.

### P6. Arrays as Object Data

Modify PolygonTest.java to allow the interactive drawing of an irregular polygon. Supply a read method of the Polygon class that does the following:

1. Ask the user how many points the polygon will have
2. Set corners to an array of the appropriate size
3. Keep calling readMouse to collect mouse clicks
4. Immediately after each mouse click, draw vertex points
5. Add each point to the array
6. When enough points are collected, call draw to display the entire polygon, like this:
```public class Polygon
{  public Polygon() {}
{  /* your work here */
}
public void draw()
{  /* as in book */
}
private Point[] corners;
}
```

Supply a test program that constructs a polygon and calls read.

### P7. Defining and Using Matrices

Arrays store a linear arrangement of values, accessed by a single index. Two-dimensional arrays or matrices store a tabular arrangement of values, accessed by two indexes, for example matrix[i][j], where i is the row index, and j is the column index..

Crosswords are a type of puzzle which have letters in common. For example,

```          d
across
w
n
```

share the letter 'o'.

Write a program that will accept a list of words into a vector of strings, then make a 20 x 20 matrix (of strings of length 1) that contains a crossword puzzle with these words.

For example, your program when given the list addle, apple, clowning, incline, plan, burr it displays it as:

```   addle
p
p
clowning
e   n
c
l
i
plan
e
```

That is, use the following method: Place the first word horizontally in the center of the top row. Place the next word vertically. Check if there is a common letter with the preceding word, and if all the squares into which you want to place that word are still empty. (If you can't place it, skip the word.) Then switch back to horizontal, place the next word if possible, and so on.