# University of Washington, CSE 142

## Lab 6: Random, arrays

Except where otherwise noted, the contents of this document are Copyright 2012 Stuart Reges and Marty Stepp.

lab document created by Marty Stepp, Stuart Reges, Whitaker Brand and Hélène Martin

# Basic lab instructions

• Talk to your classmates for help. You can even work on the lab with a partner if you like.
• You may want to bring your textbook to future labs to look up syntax and examples.
• Stuck? Confused? Have a question? Ask a TA for help, or look at the book or past lecture slides.
• Complete as many problems as you can within the allotted time. You don't need to keep working on these exercises after you leave the lab.
• Feel free to complete problems in any order.
• Before you leave today, make sure to check in with one of the TAs in the lab to get credit for your work.

# Today's lab

Goals for today:

• practice using pseudorandom numbers
• use arrays for storing lists of data
• practice using `for` loops to traverse and process array data
• pass arrays as parameters and returns from methods
• Where you see this icon, you can click it to check the problem in Practice-It! # `Random` methods

To use these methods, you need a variable of type `Random` in scope:

```Random randy = new Random();
int aRandomNumber = randy.nextInt(10);  // 0-9
```
Method name Returns...
`nextInt()` a random integer
`nextInt(max)` a random integer between 0 (inclusive) and max (exclusive)
`nextDouble()` a random real number between 0.0 and 1.0
`nextBoolean()` a random `boolean` value: `true` or `false`

# Exercise : Random expressions

Fill in the boxes to produce expressions that will generate random numbers in the provided ranges. Assume that the following `Random` variable has been declared:

```Random rand = new Random();
```
 Example: a random integer from 1 to 5 inclusive: ```rand.nextInt(5) + 1 ``` a random integer from 0 to 3 inclusive: `rand.nextInt(4)` a random integer from 5 to 10 inclusive: ```rand.nextInt(6) + 5 ``` a random integer from -4 to 4 inclusive: ```rand.nextInt(9) - 4 ``` a random even integer from 16 to 28 inclusive: (Hint: To get only even numbers, scale up.) ```rand.nextInt(7) * 2  + 16 ```

# Exercise : makeGuesses Write a method named `makeGuesses` that will output random numbers between 1 and 50 inclusive until it outputs one of at least 48. Output each guess and the total number of guesses made. Below is a sample execution:

```guess = 43
guess = 47
guess = 45
guess = 27
guess = 49
total guesses = 5
```

Try solving this problem in Practice-It! from the link above.

# Exercise : flip Write a method `flip` that takes a `Random` object as a parameter and that prints information about a coin-flipping simulation.

Your method should use the `Random` object to produce a sequence of simulated coin flips, printing whether each flip comes up "heads" or "tails". Each outcome should be equally likely. Your method should stop flipping when you see three heads in a row.

Solve this problem in Practice-It by clicking on the check-mark above.

# Exercise : Array declaration syntax Which of the following choices is the correct syntax for declaring/initializing an array of integers?

# Exercise : Quick initialization syntax Which of the following choices is the correct syntax for quickly declaring/initializing an array of integers to store a particular list of values? We didn't get to this in lecture -- check the slides or chapter 7 in the book.

# Exercise : Array code tracing Fill in the array with the values that would be stored after the code executes:

```int[] data = new int;
data = 3;
data = -18;
data = 5;
data = data;

int x = data;
data = 6;
data[x] = data * data;
```
index 0 1 2 3 4 5 6 7
value 3 3 0 0 6 9 0 -18

# Exercise : Array code tracing 2 Fill in the array with the values that would be stored after the code executes:

```int[] list = {2, 18, 6, -4, 5, 1};
for (int i = 0; i < list.length; i++) {
list[i] = list[i] + (list[i] / list);
}
```
index 0 1 2 3 4 5
value 3 24 8 -5 6 1

# Exercise : PromptNumbers • Download the following file PromptNumbers.java to your machine and open it with jGrasp.
• The program is supposed to prompt the user to enter several integers, store them into an array, then print those integers back out in forwards and backwards order. Finish the program so that it runs properly. Use an array to make your program flexible enough that it will work no matter how many integers the user wants to type.

# Exercise : jGRASP Debugger

• Download the file TriangleCount.java to your machine and open it with jGrasp.
• This program explores patterns of digits for what are called the triangle numbers. The program counts how many times a triangle number ends in a particular 2-digit sequence. For example, the 15th triangle number is 120, which ends in the 2-digit sequence 20.
• Run the program and you will see a pattern: Most counts are 0 and most of the rest are exactly 200. Which 2-digit sequences have a count of 500?  3 28 53 78
• continued on the next slide...

# Exercise - jGRASP Debugger

• The program prints a progress dot every 200 iterations. Set a breakpoint on the `System.out.print` inside the `if` on line 23 and debug the program. • Once the program pauses, click and drag the array at left named `count`, and drop it on the main code window. This will show a view of its contents.  • What are the first eight element values stored in the `count` array?
index 0 1 2 3 4 5 6 7
value 4 4 0 10 0 4 4 0

continued on the next slide...

# Exercise - jGRASP Debugger

• Leave the array viewer open and click the Resume button . (This runs until the second time the `System.out.print` is about to execute, then stops.)
• What values do the first 8 array elements have now?
index 0 1 2 3 4 5 6 7
value 8 8 0 20 0 8 8 0
• This is a very long array with 100 total values.
Scroll to the far right in the array viewer. What values do the last 8 elements have?
index 92 93 94 95 96 97 98 99
value 0 0 0 8 8 0 0 0

# Arrays as parameter/return (declare)

```public static type name(type[] name) {   // pass array parameter
```
```public static type[] name(parameters) {   // return array
```
• Arrays can be passed as parameters and returned from methods.
• This method takes an array of `double`s, and returns a new array of rounded `int`s:
```public static int[] roundAll(double[] realNums) {
int[] roundedNums = new int[realNums.length];
for (int i = 0; i < realNums.length; i++) {
roundedNums[i] = (int) Math.round(realNums[i]);
}
return roundedNums;
}
```

# Arrays as parameter/return (call)

• Below is an example usage of the `roundAll` method from the previous slide:
```import java.util.*; // to use Arrays

public class MyProgram {
public static void main(String[] args) {
double[] realNumbers = {5.5, 7.31, 8.09, -3.234234, 2.0, 0.0};
int[] roundedNumbers = roundAll(realNumbers);
System.out.println(Arrays.toString(roundedNumbers));
}
...
}

// Output: [5, 7, 8, -3, 2, 0]
```

# Exercise : array mystery Suppose that each array at right were passed as a parameter to the `mystery` method below. Fill in the boxes with the array contents after each method call.

```public static void mystery(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] < a[i + 1]) {
a[i] = a[i + 1];
}
}
}
```
 ```int[] a1 = {2, 4};mystery(a1);``` `{4, 4}` `[^0-9,]+` ```int[] a2 = {1, 3, 6};mystery(a2);``` `{3, 6, 6}` `[^0-9,]+` ```int[] a3 = {7, 2, 8, 4};mystery(a3);``` `{7, 8, 8, 4}` `[^0-9,]+` ```int[] a4 = {5, 2, 7, 2, 4};mystery(a4);``` `{5, 7, 7, 4, 4}` `[^0-9,]+` ```int[] a5 = {2, 4, 6, 3, 7, 9};mystery(a5);``` `{4, 6, 6, 7, 9, 9}` `[^0-9,]+`

# Exercise : max errors ``` 1 2 3 4 5 6 7 8 9 10 ``` ```// Returns the largest value in the given array. public static int max(int data) { int max = 0; for (int i = 0; i < data[].length(); i++) { if (array[i] > max) { max = array[i]; } } return max[]; } ```

The above attempted solution to Practice-It problem "`max`" has 7 problems. Open Practice-It from the link above, copy/paste this code into it, and fix the errors. Complete the code so that it passes the test cases.

1. line 2: should not write `` after parameter name; should write `[]` (without length) after `int`
2. line 3: starting `max` at `0` won't work if the array is all negative. Should initialize `max` variable to be `data` and start `for` loop at index `1`
3. line 4: should not write `[]` after `data` here
4. line 4: should not write `()` after `length` here
5. line 5: `array` should be `data`
6. line 6: `array` should be `data`
7. line 9: should not write `[]` after `max` here

# Exercise - solution

 ``` 1 2 3 4 5 6 7 8 9 10 ``` ```// Returns the largest value in the given array. public static int max(int[] data) { int max = data; for (int i = 1; i < data.length; i++) { if (data[i] > max) { max = data[i]; } } return max; } ```

# Exercise : PromptNumbers2 • Modify your `PromptNumbers.java` program from a previous exercise.
• Add a method that accepts an array as a parameter and prints the elements of that array in forward order.
• Then add a second method that accepts an array as a parameter and prints the elements of that array in backward order.

```public class PromptNumbers2 {
public static void main(String[] args) {
int count = console.nextInt();
int[] nums = new int[count];
...
printForward(nums);

printBackward(nums);
}

// Prints the elements of the given array in forward order.
public static void printForward(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
// Prints the elements of the given array in backward order.
public static void printBackward(int[] a) {
for (int i = a.length - 1; i >= 0; i--) {
System.out.println(a[i]);
}
}
}
```

# Exercise : `minGap` Write a method named `minGap` that accepts an integer array as a parameter and returns the minimum 'gap' between adjacent values in the array. The gap between two adjacent values in a array is defined as the second value minus the first value. For example, suppose a variable called `array` is an array of integers that stores the following sequence of values:

```int[] array = {1, 3, 6, 7, 12};
```

The first gap is 2 (3 - 1), the second gap is 3 (6 - 3), the third gap is 1 (7 - 6) and the fourth gap is 5 (12 - 7). Thus, the call of `minGap(array)` should return `1` because that is the smallest gap in the array. If you are passed an array with fewer than 2 elements, you should return `0`.

Click on the check-mark above to try out your solution in Practice-it!

# Exercise : `percentEven` Write a method named `percentEven` that accepts an array of integers as a parameter and returns the percentage of even numbers in the array as a real number. For example, if a variable named `nums` refers to an array of the elements `{6, 2, 9, 11, 3}`, then the call of `percentEven(nums)` should return `40.0`. If the array contains no even elements or no elements at all, return `0.0`.

Click on the check-mark above to try out your solution in Practice-it!

# Exercise : `stretch` Write a method named `stretch` that accepts an array of integers as a parameter and returns a new array twice as large as the original, replacing every integer from the original array with a pair of integers, each half the original. If a number in the original array is odd, then the first number in the new pair should be one higher than the second so that the sum equals the original number.

For example, if a variable named `list` refers to an array storing the values `{18, 7, 4, 24, 11}`, the call of `stretch(list)` should return a new array containing `{9, 9, 4, 3, 2, 2, 12, 12, 6, 5}`. (The number 18 is stretched into the pair 9, 9, the number 7 is stretched into 4, 3, the number 4 is stretched into 2, 2, the number 24 is stretched into 12, 12 and the number 11 is stretched into 6, 5.)

Click on the check-mark above to try out your solution in Practice-it!

# Exercise : `equals` Write a method named `equals` that accepts two arrays of integers as parameters and returns `true` if they contain exactly the same elements in the same order, and `false` otherwise. Note that the arrays might not be the same length; if the lengths differ, return `false`. Do not call `Arrays.equals` in your solution.

For example, if the following arrays are declared:

```int[] a1 = {10, 20, 30, 40, 50, 60};
int[] a2 = {10, 20, 30, 40, 50, 60};
int[] a3 = {20, 3, 50, 10, 68};
```

The call `equals(a1, a2)` returns `true` but the call `equals(a1, a3)` returns `false`.

# If you finish them all...

If you finish all the exercises, try out our Practice-It web tool. It lets you solve Java problems from our Building Java Programs textbook.

You can view an exercise, type a solution, and submit it to see if you have solved it correctly.

Choose some problems from the book and try to solve them!