Chapter 12: Arrays - Tom Reboldtomrebold.com/csis10a/ch12/lec12.pdf · 2016-04-25 · Chapter 12:...

63
Think Java: How to Think Like a Computer Scientist 5.1.2 by Allen B. Downey Chapter 12: Arrays

Transcript of Chapter 12: Arrays - Tom Reboldtomrebold.com/csis10a/ch12/lec12.pdf · 2016-04-25 · Chapter 12:...

Think Java:

How to Think Like a Computer

Scientist

5.1.2

by Allen B. Downey

Chapter 12:

Arrays

Current Options for Storing Data

1) You need to store the room temperature, such as 62.5, in a variable. What would you use?

2) You need to store all the attributes for an automobile (such as color, mileage, engine type, cost) in a variable. What would you use?

a variable of type double, such as

double roomTempF = 62.5;

an object of class Car, such as:

Car auto = new Car(Color.red,42,"hybrid", 20000);you would have to define the Car class yourself

1-2

A new need, storing many of one type

3) You need to store the high temperature every day for the last year, what would you use?

4) You need to store the inventory of all 1200 cars you're trying to sell, what would you use?

an array of double, such as

double [] dailyHigh = new double[365];

an array of class Car, such as:

Car [] inventory = new Car[1200];

1-3

Review: Two Ways of Representing Information in Java

• Primitive types – a single quantity

– int x = 6;

• Object types – a single entity with multiple attributes

– Point center= new Point(1,8);

6

x

1-4

Arrays: a third way of representing information

• An array is a set of values where each value is identified by an index.

int size = 6;

array elements

array index

1-5

Access Array Elements using the [ ] operator

Note: as with String, elements go from 0 to 3count[4] = 2; ArrayOutOfBounds Execption

What does this do? count[ count[2] ] = 5; 1-6

Using a Loop (Traversal) to print all the items

• Standard while loop

• i goes from 0 to 3

• When i gets to 4, loop condition fails, exit

– count[4] is not accessed

1-7

For Loops

• Has same components as while loop

• More compact, all control info in header

• The general syntax looks like this:

• Equivalent to this while loop:

1-8

Example: For vs While Loop

• This for loop

• Works the same as this while loop

1-9

Array Length

• All arrays have one named instance variable: length

• Holds the size of the array –

– how many items it can store

– better to use length field as upper bound of loop

– last time body of loop is executed is when i = count.length – 1 (position of last element)

1-10

8-11

Array Initialization

• When relatively few items need to be initialized, an initialization list can be used to initialize the array.

int[] highs = {65, 69, 72, 78, 61 };

• The numbers in the list are stored in the array in order:– highs[0] is assigned 65,

– highs[1] is assigned 69,

– highs[2] is assigned 72,

– highs[3] is assigned 78,

– highs[4] is assigned 61.

2-12

Review: The Scanner Class

• To read input from the keyboard we can use the Scanner class.

• The Scanner class is defined in java.util, so we will use the following statement at the top of our programs:

import java.util.Scanner;

• To create a Scanner object:Scanner keyboard = new Scanner(System.in);

2-13

Read from keyboard with Scanner

• Examples

– read the next word (til next white space) as String

•String word = keyboard.next();

– read to the end of the line as a String•String line = keyboard.nextLine();

– read the next number as an int•int x = keyboard.nextInt();

– read the next number as a double•double y = keyboard.nextDouble();

Do Lab 12 Part A (Problems 1 through 5)

1-14

Checkpoint

Checkpoint

int [] employeeNumbers = new int[100];

double [] payRates = new double[25];

0 to 3

1

2

3

4

5

Checkpoint

Checkpoint

result = numbers1[0]*numbers2[3];

for (int k=0; k<array.length; k++)

array[k]=-1;

Copying Arrays – wrong way

• Creates one array of three doubles

• Copies reference to array from variable a to b

• Doesn't make a separate copy

• A form of aliasing

• Change in one array

show up in the other

x

1-19

Side effects of Aliasing

a[1] = 8.1;

System.out.println( b[1] ) // prints 8.1

b[2] = 3.4;

System.out.println( a[2] ) // prints 3.4

8.1 3.4

1-20

Copying Arrays – Right Way

1-21

• For loop that uses the length of a as the size:

Using a For Loop to do the same

1-22

Arrays and Objects

• In many ways, arrays behave like objects:

– When you declare an array variable, you get a reference to an array.

– You have to use new to create the array itself.

– When you pass an array as an argument, you pass a reference, which means that the invoked method can change the contents of the array.

1-23

Difference between a Rectangleand an Array of 4 int ?

• A Rectangle object

• Change first value in Rectanglebox.x = 25; // fields referred to by name

1-24

Difference between a Rectangle and an Array of 4 int ?

• An Array of 4 int elements:

int [] box = {0,0,100,100};

• Change first value in box array:

box[0] = 25; // elements referred to by index

1-25

Another difference:Array elements must all have same type

• Objects of class Tile have a char and an int

class Tile {

char letter;

int value;

}

• An array can only hold all char data or all intdata, not both, so this could not be represented using an array.

1-26

Do Lab 12 Part B (Problems 6-8)

1-27

Random Numbers

• Most computer programs are deterministic

– do the same thing each time they run

– usually a good thing

• same calculation should give the same result

• Some applications need to be unpredictable

– Games, modeling complicated systems (weather)

• Sources of truly random numbers: http://qrng.anu.edu.au/

1-28

Assignment 12

• The following slides are to help you visualize the goal of the code you are writing in assignment 12.

1-29

Pseudorandom Numbers

• We can make computers seem nondeterministic

– generate numbers using a math formula

– built into Math.random method

– code to print 10 pseudorandom numbers:

1-30

Math.random method

1-31

Arithmetic with Random Numbers

• What if you print

– x *10 ?

– 10 + x ?

– (int) (x*6) + 1;

1-32

Assignment 12 problem 2

• Write a method randomInt(int low, int high)

– returns a random number between low (inclusive)

– and high (exclusive). Math notation: [low, high)

– randomInt(15, 20) produces 15 … 19 randomly

1-33

Method to create a random array

// in main:

int [] arr = randomArray(8);

1-34

Method to print an array

// in main:

int [] arr = randomArray(8);

printArray( arr );

1-35

Counting

• Suppose the array arr contains test scores:

98 86 79 90 89 88 88 97 92 90 87 69 66 60 86 85 84 77 53 90 79 90 87 74

• How many A's were there? How many B's ?

int countA = 0;

for (int i = 0; i < arr.length; i++) {

if (arr[i] >= 90)

countA++;

}

1-36

A method that counts how many values an array has in a given range

// in main

int numAs = inRange( arr, 90, 101);

int numBs = inRange( arr, 80, 90);1-37

notice, no {} needed when only 1 statement in if statement true block

Histogram of Test 2 Scores

• int [ ] scores = {98, 86, 79, 90, 89, 88, 88, 97, 92, 90, 87, 69, 66, 60, 86, 85, 84, 77, 53, 90, 79, 90, 87, 74};

• process scores array into a second array that holds the counts for each possible test score

Nu

mb

er o

f T

ests

Test Score

1-38

One way to create a Histogram

• Make a separate variable for each count ?

• painful! How about an array to hold all the counts?

int count0 = inRange(scores, 0, 1);

int count1 = inRange(scores, 1, 2);

int count2 = inRange(scores, 2, 3);

...

int count99 = inRange(scores, 99, 100);

1-39

Better way to create a Histogram

• Make an array to hold all the counts!

• Note variable i being used to index countsAND provide limits to inRange

• How many times do we have to traverse the scores array?

int[] counts = new int[100];

for (int i = 0; i < counts.length; i++){

counts[i] = inRange(scores, i, i+1);

}

1-40

More efficiently create a Histogram

• Use the test score itelf as the index to counts!

• only makes one pass through scores array

• runs much faster: O(n) vs O(n2)

int[] counts = new int[100];

for (int i = 0; i < scores.length; i++){

int index = scores[i];

counts[index]++;

}

1-41

Draw a Histogram bar chart• int [] arr = { 4,2,4,2,1,2,0,3,0,0,1,2,2};

• int [] counts; < make a histogram of arr >

• After you've processed data from arr into counts

• Make a for loop that repeats the number of elements in counts array

– print the index, then on same line,

– call bar on counts[index] to print row of X's1-42

[0] XXX

[1] XX

[2] XXXXX

[3] X

[4] XX

A method that prints a horizontal bar

• bar(5); // prints XXXXX

• bar(8); // prints XXXXXXXX

pseudocode:

method bar, takes parameter length

loop that repeats length times

print 1 "X" to console

after loop, go to new line (println)

1-43

44

Sorting Arrays [Optional]

• Computer scientists often need to sort arrays –Why?

• Because it’s easier to find things in the array when it is sorted

• Most data looks better displayed in sorted form (phone books, employee records, Lacrosse games)

• How can we sort an array? What is the algorithm? A: There are several!!

45

Bubble Sort

• Bubble sort is one of the simplest sorting

algorithms

• It proceeds through a sequence of

iterations, each time moving the next

largest item into its correct position

• On each iteration, it compares each pair

of consecutive elements, moving the

larger element up

46

Bubble Sort

55 22 99 66

55

data

0 1 2 3

47

Bubble Sort

55 22 99 66

> 55 ?

data

0 1 2 3

if (data[k] > data[k+1])

48

Bubble Sort

55 22 99 66

swap

data

0 1 2 3

swap(data, k, k+1);

49

Bubble Sort

22 55 99 66

55

data

0 1 2 3

50

Bubble Sort

22 55 99 66

> 55 ?

data

0 1 2 3

51

Bubble Sort

22 55 99 66

99

data

0 1 2 3

52

Bubble Sort

22 55 99 66

> 99 ?

data

0 1 2 3

53

Bubble Sort

22 55 99 66

swap

data

0 1 2 3

54

Bubble Sort

22 55 66 99

Notice how the data “bubbles up” through the array

moving slowly, one bin at a time

After N-1 “Passes” or “Sweeps”, the final array is

guaranteed to be sorted in ascending order, no matter what

input data

data

0 1 2 3

55

Selection Sort

• Another way of sorting is the selection sort

• The main idea is to keep finding the smallest (and next smallest) items in the array

• And move them into correct position (swap)

56

Selection Sort

55 22 99 66

55 < smallest? F

55

smallest

0 1 2 3

0

small_pos

0

k

data

57

Selection Sort

55 22 99 66

22 < smallest?

T

55

smallest

0

small_pos

0 1 2 3

0

k

data

58

Selection Sort

55 22 99 66

22 < smallest?

T

22

smallest

1

small_pos

0 1 2 3

0

k

data

59

Selection Sort

55 22 99 66

99 < smallest? F

22

smallest

0 1 2 3

1

small_pos

0

k

data

60

Selection Sort

55 22 99 66

66 < smallest? F

22

smallest

0 1 2 3

1

small_pos

0

k

data

61

Selection Sort—SWAP

55 22 99 66

swap(data, k, small_pos);

22

smallest

0 1 2 3

1

small_pos

0

k

data

62

Selection Sort—Repeat

22 55 99 66

55 < smallest ?

F

55

smallest

0 1 2 3

1

small_pos

1

k

Swapping two array elements

public static void swap( int [] arr, int j, int k)

{

int temp = arr[j];

arr[j] = arr[k];

arr[k] = temp;

}

1-63