139
1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

Embed Size (px)

Citation preview

Page 1: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

1

Intro to Computer Science I

Chapter 8Array Data Types

Processing Collections of Objects

Page 2: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

2BGA

Where do arrays arise?

Representation of a mathematical sequence such as or

x is called a subscripted variable Each subscript is called an index Sometimes we can process a sequence

sequentially without storing all elements If all members of the sequence must be

saved then an array data type can be used

nxxx ,,, 21 nxxx ,,, 10

Page 3: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

3BGA

Summation example

Sum and average of a sequence

Here we do not need to save all the elements in the sequence in order to calculate their sum.

n

kk

n xnn

xxx

1

21 1

Page 4: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

4BGA

Vertex sequence

In graphics we might define a polygon by specifying its sequence of vertices.

Each vertex is a point

The sequence of points defining the polygon can be expressed as an array of points (vertex sequence)

kkk yxv ,

110 ,,, nvvv

Page 5: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

5BGA

Matrix multiplication

Example: 3 by 3 two-dimensional arrays

To compute the product matrix we use the formulas

333231

232221

131211

aaa

aaa

aaa

A

ABC

kjk

ikjijijiij babababac

3

1332211

333231

232221

131211

bbb

bbb

bbb

B

333231

232221

131211

ccc

ccc

ccc

C

Page 6: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

6BGA

Arrays of primitive type in java

Declare score as a reference to an int array int[] score;

Construct an array for 5 elements score = new int[5];

Can be all be done in one step int[] score = new int[5]; this allocates space for score[0], score[1], ..., score[4](indices always begin at 0 in Java)

Page 7: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

7BGA

Assign values to array elements

score[0] = 1000;score[1] = 3250;score[2] = 2104;score[3] = 675;score[4] = 1454;

For an int array its a 3 step process:1: declare a reference to the array (give it a name)2: construct array of integers (int[5] for example)3: assign integer values to array elements

Page 8: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

8BGA

Other primitive types

There are array types for each of the primitive types: For example int[] double[] float[] char[] boolean[]

to make anarray type put

[] after the type name

Page 9: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

9BGA

Pictorial representation

?????

1000

1350

2104

675

1454

score[0]

score[1]

score[2]

score[3]

score[4]

score[0]

score[1]

score[2]

score[3]

score[4]

createreferenceto array Create the array give values to the

array elements

score score score

Page 10: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

10BGA

Array initializer

Define an array using an array initializer

This is shorthand for

Compiler will figure out the array size for us

final int[] FACTORIAL = { 1,1,2,6,24,120,720,5040,40320,362880, 3628800,39916800,479001600 };

final int[] FACTORIAL = new int[] { 1,1,2,6,24,120,720,5040,40320,362880, 3628800,39916800,479001600 };

By using an array we avoid the calculation of n! every timewe need it: FACTORIAL[5] is 5! for example.

Page 11: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

11BGA

DaysInMonthCalculatorpublic class DaysInMonthCalculator{ private static final int[] DAYS_IN_MONTH = {31,28,31,30,31,30,31,31,30,31,30,31}; public int daysInMonth(int year, int month) { int days = DAYS_IN_MONTH[month-1]; if (isLeapYear(year) && month == 2) days++; return days; } public boolean isLeapYear(int year) { return (year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0); }}

Page 12: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

12BGA

DaysInMonthRunner (1)

import java.util.Scanner;public class DaysInMonthRunner{ public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter year"); int year = input.nextInt(); input.nextLine(); System.out.println("Enter month (1-12"); int month = input.nextInt(); input.nextLine(); DaysInMonthCalculator calculator = new DaysInMonthCalculator();

Page 13: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

13BGA

DaysInMonthRunner (2)

if (calculator.isLeapYear(year)) System.out.println(year + " is a leap year"); System.out.println("Days in month is " + calculator.daysInMonth(year,month)); } // end main} // end class

Page 14: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

14BGA

Declaring size at run-time

Array sizes can be declared at compile time or run-time. At run-time we can use

However, arrays are not dynamic: once the size of an array is specified it cannot be changed.

System.out.println("Enter array size");int size = input.nextInt();input.nextLine();int[] v = new int[size];

Page 15: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

15BGA

Length of an array

Ihe number of elements in an array is called the length of the array

If x is the name of an array of n elements then the elements are denoted by x[0], x[1], ..., x[n-1]

The length of the array is given by x.length

Compare with x.length() for strings

Page 16: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

16BGA

Sequential array processing

The elements of an arrays can easily be processed sequentially (one element at a time) using a for loop

The last element of the array a is a[a.length - 1]

for (int k = 0; k < a.length; k++){ // process element a[k] here}

Page 17: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

17BGA

Sum and average of elements

// assume array score has been defined

double sum = 0.0; // initialize

for (int k = 0; k < score.length; k++){ sum = sum + score[k];}double average = sum / (double) score.length;

Page 18: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

18BGA

Displaying an array

for (int k = 0; k < FACTORIAL.length; k++){ System.out.println(k + "! = " + FACTORIAL[k]);}

Page 19: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

19BGA

Reading array interactively

// Read size of array and declare arraySystem.out.println("Enter number of elements");int size = input.nextInt();input.nextLine();double[] score = new double[size];

// read elements and store in array

for (int k = 0; k < score.length; k++){ System.out.println("Enter element " + k); score[k] = input.nextDouble(); input.nextLine();}

Page 20: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

20BGA

Arrays of object type

Each array element is now a reference to an object of the array type.

1. Declare an array reference variable 2. Construct an array of references 3. Construct some objects and assign

their references to the array elements NOTE: new is used at two levels here.

Once to construct array and once for each object

Page 21: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

21BGA

BankAccount array example

BankAccount[] b;b = new BankAccount[3];

b[0] = new BankAccount(123,"Fred",150.50);b[1] = new BankAccount(345,"Mary",375.00);b[2] = new BankAccount(987,"Bill",75.50);

can be done

in one step

Page 22: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

22BGA

Pictorial representation

.

.

.b[0]

b[1]

b[2]

createreferenceto array

Create the arrayof references

assign objectreferences toarray elements

b b b

123Fred150.50

345Mary375.00

987Bill75.50

Page 23: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

23BGA

Array initializers for objects

BankAccount[] b ={ new BankAccount(123,"Fred",150.50), new BankAccount(345,"Mary",375.00), new BankAccount(987,"Bill",75.50)};

The semi-colon is

necessary here

Page 24: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

24BGA

Bank balance sum, average

double totalBalance = 0.0;for (int k = 0; k < b.length; k++){ totalBalance = totalBalance + b[k].getBalance();}double averageBalance = totalBalance / b.length;

Page 25: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

25BGA

Array of Point2D objects

Point2D.Double[] p = new Point2D.Double[3];p[0] = new Point2D.Double(0,0);p[1] = new Point2D.Double(1,2);p[2] = new Point2D.Double(2,4);

An array initializer could also be used in this case

Page 26: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

26BGA

Drawing line segments

for (int k = 0; k <= p.length - 2; k++){ g2D.draw(new Line2D.Double(p[k],p[k+1]));}

p[0]

p[1]

p[n-1]

p[n-2]n is p.length

Note that last value of k is n-2 = p.length-2

Page 27: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

27BGA

String array of month names

final String[] MONTH_NAMES = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };

Recall: Strings are special so new is not needed here

Now we can easily look up the name of the month givenits value month in the range 1 to 12String monthName = MONTH_NAMES[month-1];

Page 28: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

28BGA

String array of day names

final String[] DAY_NAMES = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday };

Page 29: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

29BGA

Command line arguments

public static void main(String[] args){ ...}

The main method has a string array as its argument

This String array is used by the java interpreter to provideany command line arguments to the program as an array ofstrings

Page 30: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

30BGA

CommandLineArguments class

public class CommandLineArguments{ public static void main(String[] args) { for (int k = 0; k < args.length; k++) { System.out.println("Argument " + k + " is " + args[k]); } }}

Page 31: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

31BGA

Example output

java CommandLineArguments zero one twoArgument 0 is zeroArgument 1 is oneArgument 2 is twojava CommandLineArguments "zero one two"Argument 0 is zero one two

Note: if you want a command line argument to containspaces enclose it on double quotes.

Page 32: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

32BGA

LoanRepaymentTableRunner

public class LoanRepaymentTableRunner{ public static void main(String[] args) { if (args.length == 4) { double a = Double.parseDouble(args[0]); int y = Integer.parseInt(args[1]); int p = Integer.parseInt(args[2]); double r = Double.parseDouble(args[3]); LoanRepaymentTable table = new LoanRepaymentTable(a,y,p,r); System.out.println(table); } else { // display syntax error}} }

Page 33: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

33BGA

Supplying the arguments

java LoanRepaymentTableRunner 10000 5 2 10

Command line arguments

Page 34: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

34BGA

InvestmentTableRunner (1)

public class InvestmentTableRunner{ public static void main(String[] args) { if (args.length == 6) // should be 7 { double minRate = Double.parseDouble(args[0]); double maxRate = Double.parseDouble(args[1]); double rateStep = Double.parseDouble(args[2]); int minYears = Integer.parseInt(args[3]); ...

Page 35: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

35BGA

InvestmentTableRunner (2)

int maxYears = Integer.parseInt(args[4]); int yearStep = Integer.parseInt(args[5]); InvestmentTable table = new InvestmentTable(minRate, maxRate, rateStep, inYears, maxYears, yearStep, amount); System.out.println(table); } else { // display syntax }}}

Page 36: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

36BGA

Supplying the arguments

java InvestmentTableRunner 2 5 0.5 1 5 1 1000

Command line arguments

Page 37: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

37BGA

Arrays as method arguments

Array references can be used as a method arguments when such a method is called a reference

to the array becomes a local variable inside the method.

This reference can be used to modify array elements in the case of an array of primitive types or of objects of some mutable type.

Page 38: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

38BGA

Arrays as return values

Arrays references can also be used as method return values.

This means that the caller of the method can use the reference to access the array elements

Page 39: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

39BGA

An array sum method

public double sum(double[] a){ double s = 0.0; for (int k = 0; k < a.length; k++) { s = s + a[k]; } return s;}

double theSum = sum(a);calling the

method

Page 40: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

40BGA

An array display method

public void printArray(int[] a){ System.out.print("<" + a[0]); for (int k = 1; k < a.length; k++) { System.out.print("," + a[k]); } System.out.print(">");}

printArray(a);calling the

method

Page 41: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

41BGA

Connecting an array of points

public void drawLines(Graphics2D g2D, Point2D.Double[] p){ for (int k = 0; k < p.length - 1; k++) { g2D.draw(new Line2D.Double(p[k],p[k+1])); }}

drawLines(g2D, p);calling the

method

Page 42: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

42BGA

Modifying array elements (1)

public void timesTwo(int[] a){ for (int k = 0; k < a.length; k++) { a[k] = 2 * a[k]; }}

The integer array elements referenced by a will all bemultiplied by 2

Page 43: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

43BGA

Modifying array elements (2)

int[] myArray = {1,2,3,4,5}; // initializertimesTwo(myArray);for (int k = 0; k < myArray.length; k++){ System.out.println(myArray[k]);}

The following statements show that the arrayelements in myArray really are multiplied by 2.

Page 44: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

44BGA

Returning an array reference

public int[] readArray(){ Scanner input = new Scanner(System.in); System.out.println("Enter size of array:"); int size = input.nextInt(); input.nextLine(); int[] a = new int[size]; for (int k = 0; k < a.length; k++) { System.out.print("Enter element " + k + ": "); a[k] = input.nextInt(); input.nextLine(); } return a;}

read an array and return areference to it

Page 45: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

45BGA

Arrays and BlueJ

public class Average{ public double average(double[] a) { double s = 0; for (int k = 0; k < a.length; k++) s = s + a[k]; return s / (double) a.length; }}

1. Construct an Average object called avg2. From its method menu choose average3. Enter an array initializer such as {1,2,3,4,5}4. Average will be shown in method result window

Page 46: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

46BGA

Testing from command line

public class AverageRunner{ public static void main(String[] args) { double[] a = new double[args.length]; for (int k = 0; k < args.length; k++) a[k] = Double.parseDouble(args[k]); Average avg = new Average(); System.out.println("Average is " + avg.average(a)); }}

java AverageRunner 1 2 3 4 5try it fromcommand

line

Page 47: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

47BGA

Maximum array element

index

kindex

aa

nk

index

aaa

indexk

n

1 1

0

),,,(mFindMaximu 110

RETURN

FOR END

IF END

THENIF

DOTOFOR

ALGORITHM

Page 48: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

48BGA

MaxFinder class

public class MaxFinder{ public int findMaximum(double[] a) { int index = 0; for (int k = 1; k <= a.length - 1; k++) { if (a[k] > a[index]) index = k; } return index; }}

Page 49: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

49BGA

MaxFinder with BeanShell

addClassPath("c:/book-projects/chapter8/ array-algorithms");MaxFinder f = new MaxFinder();double[] a = {1,2,5,4,3};int maxIndex = f.findMaximum(a);print(maxIndex);2print(a[maxIndex');5

Page 50: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

50BGA

Testing from command line

public class MaxFinderRunner{ public static void main(String[] args) { double[] a = new double[args.length]; for (int k = 0; k < args.length; k++) a[k] = Double.parseDouble(args[k]); MaxFinder finder = new MaxFinder(); int indexMax = finder.findMaximum(a); System.out.println( "Index of maximum is " + indexMax); System.out.println( "Maximum value is " + a[indexMax]); }} java MaxFinderRunner 1 2 5 4 3

Page 51: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

51BGA

Maximum account balance

public int findMaximum(BankAccount[] a){ int index = 0; for (int k = 1; k <= a.length - 1; k++) { if (a[k].getBalance() > a[index].getBalance()) index = k; } return index;}

Page 52: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

52BGA

lexigraphically largest string

public int findMaximum(String[] a){ int index = 0; for (int k = 1; k <= a.length - 1; k++) { if (a[k].compareTo(a[index]) > 0) index = k; } return index;}

Page 53: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

53BGA

Linear search

Problem Given the array and a

value x to find, determine the index i such that and . If such an index cannot be found let the index be -1.

110 ,,, naaa

xai 10 ni

Page 54: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

54BGA

Linear search algorithm

IF END

RETURN

ELSE

RETURN

IF

WHILEEND

DOWHILE

ALGORITHM

index

nindex

indexindex

xanindex

index

x,a,,aa

index

n

1

THEN 1

1

)()1(

0

, ch LinearSear 110

Page 55: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

55BGA

LinearSearcher class

public class LinearSearcher{ public int search(double[] a, double x) { int index = 0; int n = a.length; while (index < n && a[index] != x) { index = index + 1; } if (index > n-1) return -1; else return index; }}

Page 56: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

56BGA

Testing with BeanShell

addClassPath("c:/book-projects/chapter8/ array-algorithms");LinearSearcher searcher = new LinearSearcher();int index = searcher.search(new double[]{1,2,3,4,5},1);print(index);0int index = searcher.search(new double[]{1,2,3,4,5},2);print(index);1int index = searcher.search(new double[]{1,2,3,4,5},7);print(index);-1

Page 57: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

57BGA

LinearSearcherRunner

public class LinearSearcherRunner{ public static void main(String[] args) { double[] a = new double[args.length-1]; for (int k = 0; k < args.length - 1; k++) { a[k] = Double.parseDouble(args[k]); } // last argument is x double x = Double.parseDouble(args[args.length-1]);

LinearSearcher searcher = new LinearSearcher(); int index = searcher.search(a,x); System.out.println("Index of element is " + index); }}

Page 58: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

58BGA

Bubble sort algorithm

Sort array in increasing order: Pass 1: Process the array elements to

exchanging elements that are out of order: if swap them, if swap them,...,

if swap them . At end of this pass the largest array element will be in the last position, its correct position.

Pass 2: process to in the same way Pass n-1: process to

110 ,,, naaa

0a 1na

10 aa 21 aa

12 nn aa

0a 2na

0a 1a

Page 59: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

59BGA

Pseudo-code loop for passes

FOR END

DOTOFOR

order ofout are that elements swapping

),1(,),2,1(),1,0( positionsat pairs Compare

1 1

pnpn

np

)1,0( positionsat elements Compare )1(

...

),1(,),2,1(),1,0( positonsat elements Compare )(

...

)3,4(,),2,1(),1,0( positionsat elements Compare )3(

)2,3(,),3,2(),2,1(),1,0( postionsat elements Compare (2)

)1,2(,),3,2(),2,1(),1,0( positionsat elements Compare (1)

n

pnpnp

nn

nn

nn

Page 60: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

60BGA

Example

Pass

Start of pass 1 44 55 12 42 94 18 6 67 Start of pass 2 44 12 42 55 18 6 67 94Start of pass 3 12 42 44 18 6 55 67 94Start of pass 4 42 12 18 6 44 55 67 94Start of pass 5 12 18 6 42 44 55 67 94Start of pass 6 12 6 18 42 44 55 67 94Start of pass 7 6 12 18 42 44 55 67 94 End of pass 7 6 12 18 42 44 55 67 94

0a 1a 2a 3a 4a 5a 6a 7a

Page 61: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

61BGA

Bubble sort algorithm

FOR END

FOR END

IF END

THENIF

DOTOFOR

DOTOFOR

ALGORITHM

),swap(

1 0

1 1

,,, bubbleSort

1

1

110

jj

jj

n

aa

aa

pnj

np

aaa

Page 62: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

62BGA

BubbleSorter class

public class BubbleSorter{ public double[] bubbleSort(double[] a) { int n = a.length; for (int p = 1; p <= n - 1; p++) { for (int j = 0; j <= n-1-p; j++) { if (a[j] > a[j + 1]) { double temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } } return a; // so we can test in BlueJ } }

Page 63: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

63BGA

Testing in BlueJ

Create a BubbleSorter object Select its bubbleSort method In the resulting method call window

enter an array such as {5,4,1,6,2} You will get a "Method Result" window

showing the array as <object-reference>

Click on it and use "Inspect" to see the sorted array or use "Get"

Page 64: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

64BGA

Testing with BeanShell

addClassPath("c:/book-projects/chapter8/array-algorithms");BubbleSorter sorter = new BubbleSorter();double[] a = {44,55,12,42,94,18,6,67};sorter.bubbleSort(a);print(a);double[]: {6.0,12.0,18.0,42.0,44.0,55.0,67.0,94.0}

Page 65: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

65BGA

BubbleSorterRunner (1)

public class BubbleSorterRunner{ public static void main(String[] args) { double[] a = new double[args.length]; for (int k = 0; k < args.length; k++) { a[k] = Double.parseDouble(args[k]); } BubbleSorter sorter = nerw BubbleSorter(); System.out.println("Array to sort is " + arrayToString(a)); sorter.bubbleSort(a); System.out.println("Sorted array is " + arrayToString(a)); }

Page 66: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

66BGA

BubbleSorterRunner (2)

public static String arrayToString(double[] a) { String s = "<" + a[0]; for (int k = 1; k < a.length; k++) s = s + "," + a[k]; s = s + ">"; }} // end of BubbleSorterRunner class

java BubbleSorterRunner 44 55 12 42 94 18 6 67Array to sort is <44.0,55.0,12.0,42.0,94.0,18.0,6.0,67.0>Sorted array is <6.0,12.0,18.0,42.0,44.0,55.0,67.0,94.0>

Try it from the command line

Page 67: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

67BGA

Sorting an array of strings

public void bubbleSort(String[] a){ int n = a.length; for (int p = 1; p <= n - 1; p++) { for (int j = 0; j <= n - 1 - p; j++) { if(a[j].compareTo(a[j+1]) > 0) { String temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } }}

Note thatwe are notswappingstring objectshere.

We areswapping thereferences tothe strings

Page 68: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

68BGA

Inefficient polynomial evaluation

A polynomial of degree n in the variable x is

It is defined by the coefficients

nnxaxaxaaxp 2

210)(110 ,,, naaa

FOR END

DOTOFORk

k xasumsum

nk

asum

1 0

2

)1(1)1(

nnnn

This is an inefficient algorithm.The number of multiplications is

Page 69: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

69BGA

Horner's algorithm (1)

))))((((

))((

)()(

12210

2210

1210

nnn

nn

nn

xaaxaxaxaxa

xaaxaxa

xaxaaxaxp

This is called the nested form of the polynomial andit can be evaluated using only n multiplications asindicated by the arrows

1 2 n-2 n-1 n

Page 70: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

70BGA

Horner's algorithm (2)

100

211

1

12122

111

...

...

)(

xpap

xpap

xpap

xpaxaaxap

xpaxaap

ap

kkk

nnnnnn

nnnnn

nn

p

xpap

nk

ap

xaaa

k

n

n

1 0 1

) ,,,, ( lynomialEvaluatePo 10

RETURN

FOR END

DOBYTOFOR

ALGORITHM

Page 71: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

71BGA

Polynomial objects

public class Polynomial{ private double[] a; // internal rep of polynomial public Polynomial(double[] coefficients) { a = coefficients; }

public double eval(double x) { int n = x.length - 1; double p = a[n]; for (int k = n-1; k >= 0; k--) { p = a[k] + x*p; } return p; }

public String toString() { ... } // next slide

Page 72: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

72BGA

Displaying a polynomial

public String toString(){ String p = (a[0] == 0) ? "" : "" + a[0]; for (int k = 1; k < a.length; k++) { String term = (k == 1) ? "x" : "x^" + k; if (p.equals("") && a[k] != 0) p = a[k] + term; else { if (a[k] > 0) p = p + " + " + a[k] + term; else if (a[k] < 0) p = p + " - " + Math.abs(a[k]) + term; } } if (p.equals("")) = p = "0"; return p;}

Page 73: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

73BGA

Example

double[] coeff = new double[] {1,2,3};Polynomial p = new Polynomial(coeff);

2321)( xxxp

Polynomial p = new Polynomial(new double[] (1,2,3});

Can do it in one line

double val = p.eval(3.5);

Evaluate the polynomial at x = 3.5

Page 74: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

74BGA

BlueJ example

Construct a polynomial object and enter an array such as {1, 0, 3, 0, 5}

Select the eval method and enter 1.5 In the "Method Result" window the

value 33.0625 is shown Select the toString method to see the

string

"1.0 + 3.0x^2 + 5.0x^4"

Page 75: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

75BGA

BeanShell example

addClassPath("c:/book-projects/chapter8/polynomial");Polynomial p = new Polynomial(new double[]{1,0,3,0,5});print(p.eval(1.5));33.065print(p);1.0 + 3.0x^2 + 5.0x^4

Page 76: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

76BGA

PolynomialRunner

public class PolynomialRunner{ public static void main(String[] args) { int n = args.length; if (args.length >= 2) { // first n-1 args are coefficients double[] coeff = new double[n-1]; for (int k = 0; k < n-1; k++) coeff[k] = Double.parseDouble(args[k]); Polynomial p = new Polynomial(coeff); System.out.println("p(x) = " + p); double x = Double.parseDouble(args[n-1]); System.out.println("p("+x+") = " + p.eval(x)); } else System.out.println("args: a0 a1 ... an x"); } }

Page 77: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

77BGA

PolynomialRunner output

java PolynomialRunner 1 0 30 0 5 1.5p(x) = 1.0 + 3.0x^2 + 5.0x^4p(1.5) = 33.0625

java PolynomialRunner 1 0 30 0 5 3.5p(x) = 1.0 + 3.0x^2 + 5.0x^4p(1.5) = 788.0625

5.1at 531)( 42 xxxxp

5.3at 531)( 42 xxxxp

Page 78: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

78BGA

Line graph example (1)

Problem: Draw a line graph given the array of n vertices specified in order of increasing x coordinate

110 ,,, nvvv ),( kk yx

),( 00 yx ),( 66 yx

),( minmin yx

),( maxmax yx

bounding box

Page 79: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

79BGA

Line graph example

Page 80: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

80BGA

LineGraph class specification

public class LineGraph extends JPanel{ private Point2D.Double[] v; // vertices // specify the bounding box private double xMin, xMax, yMin, yMax;

public LineGraph(Point2D.Double[] p) {...} public void paintComponent(Graphics g) {...} private void computeBoundingBox() {...}

private AffineTransform worldTransform( double xMin, double xMax, double yMin, double yMax, int w. int h) {...}}

Page 81: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

81BGA

Compute the bounding boxprivate void computeBoundingBox(){ xMin = v[0].getX(); xMax = v[0].getX(); yMin = v[0].getY(); yMax = v[0].getY(); for (int k = 1; k < v.length; k++) { double x = v[k].getX(); double y = v[k].getY(); if (x < xMin) xMin = x; if (x > xMax) xMax = x; if (y < yMin) yMin = y; if (y > yMax) yMax = y; }}

Page 82: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

82BGA

Coordinate transformation

int w = getWidth();int h = getHeight();double bx = (xMax - xMin) * 0.05; // borderdouble by = (yMax - yMin) * 0.05;AffineTransform world = new worldTransform(xMin - bx, xMax + bx, yMin - by, yMax + by, w, h);g2D.transform(world);g2D.setStroke(new BasicStroke(0.0f)); // 1 pixel

these statements gointo paintComponent

Page 83: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

83BGA

General way to set stroke.

double pixelWidth = Math.abs(1 / world.getScaleX());double pixelHeight = Math.abs(1 / world.getScaleY());float thickness = (float) Math.min(pixelWidth, pixelHeight);g2D.setStroke(new BasicStroke(thickness));

Here pixelWidth and pixelHeight represent thewidth and height of one pixel in the user coordinatesystem.

Page 84: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

84BGA

Drawing the axes

g2D.setPaint(Color.blue);

if (yMin <= 0.0 && 0.0 <= yMax) // draw x-axis{ g2D.draw(new Line2D.Double(xMin, 0, xMax, 0);}if (xMin <= 0.0 && 0.0 <= xMax) // draw y-axis{ g2D.draw(new Line2D.Double(0, yMin, 0, yMax);}

Page 85: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

85BGA

Drawing the line segments

g2D.setPaint(Color.black);for (int k = 0; k < v.length; k++){ double x1 = v[k].getX(); double y1 = v[k].getY(); double x2 = v[k+1].getX(); double y2 = v[k+1].getY(); g2D.draw(new Line2D.Double(x1,y1,x2,y2));}

Page 86: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

86BGA

Drawing circles at each vertex

double xr = 3 * pixelWidth;double yr = 3 * pixelHeight;g2D.setPaint(Color.red);for (int k = 0; k < v.length; k++){ double x = v[k].getX(); double y = v[k].getY(); Ellipse2D.Double ellipse = new Ellipse2D.Double(x-xr, y-yr, 2*xr, 2*yr); g2D.fill(ellipse);}

We want the circles to have a radius of 3 pixels indevice space so their radius in user space is givenby xr and yr:

Page 87: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

87BGA

LineGraph constructor

public class LineGraph extends JPanel{ private Point2D.Double[] v; private double xMin, xMax, yMin, yMax;

public LineGraph(Point2D.Double[] p) { v = p; computeBoundingBox(); } ... ...}

see BlueJ project book-projects/chapter8/line-graph

this class canbe used byother classesto draw a linegraph

Page 88: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

88BGA

Tester class for LineGraphimport libary.GraphicsFrame;import java.awt.geom.*;public class SimpleTester{ public void runTest() { Point2D.Double[] v = new Point2D.Double[8]; v[0] = new Point2D.Double(-4,-1); ... v[7] = new Point2D.Double(6, 0.6); new GraphicsFrame("A Simple Line Graph", new LineGraph(v), 401, 301); } public static void main(String[] args) { new SimpleTester().runTest(); }}

see BlueJ project book-projects/chapter8/line-graph

Page 89: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

89BGA

Tester output

Page 90: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

90BGA

Random line graph

Problem: Use the LineGraph class to draw a random line graph:

(1) Generate a random array of Point2D.Double objects using Math.random()

(2) Use bubble sort to sort them in order of increasing x coordinate

(3) Use LineGraph class to draw the line graph

Page 91: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

91BGA

Random line graph example

Page 92: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

92BGA

Generating random vertices

int numVertices = (int) (96.0 * Math.random()) + 5;

Generate the number of vertices in the range 5 to 100

for (int k = 0; k < v.length; k++){ double x = 20.0 * Math.random() - 10.0; double y = 20.0 * Math.random() - 10.0; v[k] = new Point2D.Double(x, y);}

Now generate vertices with x and y coordinates in therange -10 to 10

Page 93: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

93BGA

bubble sort the points

private void bubbleSort(Point2D.Double[] a){ int n = a.length; for (int p = 1; p <= n - 1; p++) { for (int j = 0; j <= n - 1 - p; j++) { if (a[j].getX() > a[j+1].getX()) { Point2D.Double temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; } } }}

Page 94: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

94BGA

RandomTester class

import library.GraphicsFrame;import java.awt.geom.*;public class RandomTester{ public void runTest() { // generate random array v here bubbleSort(v); new GraphicsFrame("A Random Line Graph", new LineGraph(v), 401, 301); } private void bubbleSort(Point2D.Double[] a) {...} public static void main(String[] args) { new RandomTester().runTest(); }}

see BlueJ project book-projects/chapter8/line-graph

Page 95: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

95BGA

Converting array to GeneralPath

GeneralPath p = new GeneralPath();p.movetTo((float) v[0].getX(), (float) v[0].getY());for (int k = 1; k < v.length; k++){ p.lineTo((float)v[k].getX(), (float) v[k].getY());}g2D.draw(p);

It is easy to convert an array of points to a GeneralPathobject:

This technique could have been used in the LineGraphclass

Page 96: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

96BGA

Two-dimensional arrays (1)

Two-dimensional arrays often occur in problems where data is structured as a table with rows and columns.

Matrices are represented in programming languages as two-dimensional arrays.

Two-dimensional arrays represent doubly subscripted variables in mathematics

Page 97: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

97BGA

Two-dimensional arrays (2)

Mathematical notation (m rows, n columns)

Pseudo-code notation

Java notation

njmiaij 1 ,1

mnaa ,,11

10 ,10 ]][[ njmijiaaij

subscriptsbegin at 0

in Java

Page 98: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

98BGA

2 by 2 matrix in Java

A 2 by 2 array using assignment statements

double[][] a = new double[2][2];

a[0][0] = 1.0; // row 0 column 0;

a[0][1] = 2.0; // row 0 column 1;

a[1][0] = 4.0; // row 1 column 0;

a[1][1] = 5.0; // row 1 column 1;

Try it in BeanShell

0.40.3

0.20.1

number of rows number of columns

Page 99: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

99BGA

Using an array initializer

For constant arrays an array initializer is more convenient (matrix of rows)

double[][] a = { {1.0, 2.0}, {3.0, 4.0} };

A two dimensional array is a onedimensional array of rows

row 0 is a[0]

row 1 is a[1]

Page 100: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

100BGA

One dimensional array of rows

int[][] a = new int[][] { {1}, {3,4,5}, {6,7,8,9} };

Here we have an array of three rows.The rows have different lengthsAn array with unequal row lengths is called a ragged array Number if rows: a.lengthLength of row 0: a[0].length (1 in above example)Length of row 1: a[1].length (3 in above example)Length of row 2: a[2].length (4 in above example)

Page 101: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

101BGA

Example: display row lengths

int[][] a = new int[][] { {1}, {3,4,5}, {6,7,8,9} }; for (int r = 0; r < a.length; r++){ System.out.println("Row " + r + " has " + a[r].length + " elements");}

The following loop prints the number of array elements in each row

Try it with BeanShell

Page 102: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

102BGA

Construct array a row at a time

int[][] a = new int[3][]; // array of refs to 3 rows a[0] = new int[] {1}; // construct row 0a[1] = new int[] {3,4,5}; // construct row 1a[2] = new int[] {6,7,8,9}; // construct row 2

The following statements construct the array a one row at a time

Try it with BeanShell

Page 103: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

103BGA

Picture of 2D array (1)

int[][] a = new int[3][];

a[0]

a[1]

a[2] ?

?

?

a.length is 3

don't need tospecify lengths of

rows

Page 104: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

104BGA

Picture of 2D array (2)

int[][] a = new int[3][];

a[0] = new int[1];

a[1] = new int[3];

a[2] = new int[4];

// can now use initializers or statements like

// a[0][0] = 1;

?

? ? ?

? ? ? ?

a[0].length is 1

a[1].length is 3

a[2].length is 4

a[0]

a[1]

a[2]

Page 105: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

105BGA

Picture of 2D array (3)

int[][] a = new int[3][];

a[0] = new int[] {1};

a[1] = new int[] {3,4,5};

a[2] = new int[] {6,7,8,9};

1

3 4 5

6 7 8 9

a[0].length is 1

a[1].length is 3

a[2].length is 4

a[0]

a[1]

a[2]

Page 106: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

106BGA

Multiplying 3 by 3 matrices

for (int i = 0; i <= 2; i++) { for (int j = 0; j <= 2; j++) { double sum = 0.0; for (int k = 0; k <= 2; k++) { sum = sum + a[i][k] * b[k][j]; } c[i][j] = sum; } }

jijijiij bababac

bbb

bbb

bbb

aaa

aaa

aaa

ccc

ccc

ccc

221100

222120

121110

020100

222120

121110

020100

222120

121110

020100

Page 107: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

107BGA

General case

10

10

matrix product

matrix

matrix

1

0,11,1100

nj

mi

babababac

ABCnmC

npB

pmA

p

kkjikjppijijiij

Page 108: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

108BGA

Algorithm

int m = a.length; // number of rows in Aint n = b[0].length; // number of columns in Bfor (int i = 0; i <= m-1; i++){ for (int j = 0; j <= n-1; j++) { // calculate c[i][j] here }

double sum = 0.0;int p = b.length; // number of rows in Bfor (int k = 0; k <= p-1; k++){ sum = sum + a[i][k] * b[k][j];}c[i][j] = sum;

Page 109: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

109BGA

Class MatrixMultiplier

public class MatrixMultiplier{ public double[][] multiply(double[][] a, double[][] b) { int m = a.length; // rows in A int n = b[0].length; // columns in B int p = b.length; // rows in B double[][] c = new double[m][n]; for (int i = 0; i <= m-1; i++) { for (int j = 0; j <= n-1; j++) { double sum = 0.0; for (int k = 0; k <= p-1; k++) sum = sum + a[i][k] + b[k][j]; c[i][j] = sum; } } return c; }}

Page 110: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

110BGA

Testing in BlueJ (1)

Try the example

Create a MatrixMultiplier object Select multiply method and enter

{{1,2,3},{4,5,6}} for a {{1,2,3,4},{5,6,7,8},{4,3,2,1}} for b

62595653

23232323

1234

8765

4321

654

321ABC

Page 111: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

111BGA

Testing in BlueJ (2)

Result is <object-reference> so click the "Get" button and give the object the name c

This gives an array object on the work bench so you can inspect it

See textbook for further instructions on how to see the rows and matrix elements of the product matrix c

Page 112: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

112BGA

Testing in BeanShell

addClassPath("c:/book-projects/chapter8/2d-arrays");MatrixMultiplier mult = new MatrixMultiplier();double[][] a = {{1,2,3},{4,5,6}};double[][] b = {{1,2,3,4},{5,6,7,8},{4,3,2,1}};double[][] c = mult.multiply(a,b);print(c.length);2print(c[0]);double[]: {23.0,23.0,23.0,}print(c[1]);double[]: {53.0,56.0,59.0,62.0,}

Page 113: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

113BGA

Command line testing

See class MatrixMultiplierRunnerin project book-projects/chapter8/2d-arrays

java MatrixMultiplier 2 3 4 1 2 3 4 5 6 1 2 3 4 5 6 7 8 4 3 2 1

Command line arguments arem, p, n, a[0], ..., b[0], ...

Page 114: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

114BGA

Board games

In board games the board can be represented by a two-dimensional array of type int[][]

Tic-tac-toe (X's and O's) example uses a 3 by 3 board defined by int[][] board = new int[3][3];

Value at board[i][j] is either 0,1,2 0 means the square is unoccupied 1 means square is occupied by x 2 means square is occupied by O

X O X

X O

O X

0

1

2

0 1 2

Page 115: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

115BGA

Initialize board

int size = board.length;for (int row = 0; row < size; row++){ for (int col = 0; col < size; col++) { board[row][col] = 0; }}

Loop through all the squares and store zero in eachsquare to indicate that initially all squares areunoccupied

0 0 0

0 0 0

0 0 0

0

1

2

0 1 2

Page 116: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

116BGA

Determine if a move is legal

public boolean isLegalMove(int row, int column){ return board[row][col] == 0;}

A move is legal if the requested square has a zeroin it so we can write a boolean valued method totest this:

Note: this method is an instance method.

Page 117: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

117BGA

Determine if board is full

public boolean isBoardFull(){ int size = board.length(); for (int row = 0; row < size; row++) { for (int col = 0; col < size; col++) { if (board[row][col] == 0) return false; } } return true; // didn't find an empty square}

The board is full when there are no zero's in any ofits squares.

Note: this method is an instance method.

Page 118: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

118BGA

Determine if there is a winner

public boolean isWinner(int player){ ...}

The first player to occupy a complete row, column, or diagonal is the winner. There are three rows, three columns, and two diagonals so there are 8 ways to win.

Page 119: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

119

A card game application

Representing deck of cardsCard class

CardDeck classTesting the classes

Page 120: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

120BGA

Representations

0 1 2 3 4 5 6 7 8 9 10 11 12 0 to 12 AC 2C 3C 4C 5C 6C 7C 8C 9C TC jC QC KC 013 to 25 AD 2D 3D 4D 5D 6D 7D 8D 9D TD JD QD KD 126 to 38 AH 2H 3H 4H 5H 6H 7H 8H 9H TH JH QH KH 239 to 51 AS 2S 3S 4S 5S 6S 7S 8S 9S YS JS QS KS 3

Clubs

Diamonds

Hearts

Spades

card index in range 0 to 510

Symbol Suit name index

1

2

3

ordered pair (rank,suit)0 <= rank <= 120 <= suit <= 3

Two ways to represent card

Page 121: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

121BGA

Converting representations

Converting from index (0 <= index <= 51) to pair

Converting from pair (rank,suit) to index

rank = index mod 13suit = index div 13

index = 13 * suit + rank

Page 122: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

122BGA

Card class design

public class Card{ public Card(int rank, int suit) {...} public Card(int index) {...} public String getRankName() {...} public String getSuitName() {...} public String getCardName() {...} public String toString() {...}}

Rank name: "Ace", "Two", ..., "King"Suit name: "Clubs", "Diamonds", "Hearts", "Spades"Card name: "A-C", ..., "K-S"

Page 123: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

123BGA

Card class implementation (1)

public class Card{ private static String[] ranks = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };

private static String rankLetter = "A23456789TJQK"; private static String suitLetter = "CDHS";

private static String[] suits = { "Clubs", "Diamonds", "Hearts", "Spades" };

private int rank; // 0 to 12 private int suit; // 0 to 3 private int index; // 0 to 51

Page 124: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

124BGA

Card class implementation (2)

private String rankName; // "Ace", ... private String suitName; // "Clubs", ... private String cardName; // e.g., "A-C"

public Card(int rank, int suit) { this.rank = rank; this.suit = suit; index = 13*suit + rank; rankName = ranks[rank]; suitName = suits[suit]; cardName = rankLetter.substring(rank,rank+1) + "-" + suitLetter.substring(suit,suit+1); }

Page 125: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

125BGA

Card class implementation (3)

public Card(int index) { this.index = index this.rank = this.index % 13; this.suit = this.index / 13; rankName = ranks[rank]; suitName = suits[suit]; cardName = rankLetter.substring(rank,rank+1) + "-" + suitLetter.substring(suit,suit+1); }

Page 126: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

126BGA

Card class implementation (4)

public String getRankName() { return rankName; } public String getSuitName() { return suitName; } public String getCardName() { return cardName; } public String toString() { return cardName; }

Could also include get methods for index, rank and suit

Page 127: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

127BGA

BeanShell test

addClassPath("c:/book-projects/chapter8/card-deck");Card c = new Card(35); // TH from tableprint(c.getCardName());T-Hprint(c.getRankName());Tenprint(c.getSuitName());Heartsprint(c);T-H

Page 128: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

128BGA

CardDeck implementation (1)

Two ways to represent a deck of cards

Use a two-dimensional array:

Use a one-dimensional array:

Card[][] deck = new Card[4][13];

Card[] deck = new Card[52];

lets usethis one

Page 129: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

129BGA

CardDeck implementation (2)

public class CardDeck{ private static final int DECK_SIZE = 52; private Card[] deck; private int topCardIndex;

public CardDeck() { deck = new Card[DECK_SIZE]; initialize(); }

private void initialize() { topCardIndex = 0; for (int k = 0; k < DECK_SIZE; k++) deck[k] = new Card(k); }

standard orderindex = 0,...,51

Page 130: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

130BGA

CardDeck implementation (3)

public class CardDeck{ private static final int DECK_SIZE = 52; private Card[] deck; private int topCardIndex;

public CardDeck() { deck = new Card[DECK_SIZE]; initialize(); }

private void initialize() { topCardIndex = 0; for (int k = 0; k < DECK_SIZE; k++) deck[k] = new Card(k); }

Page 131: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

131BGA

CardDeck implementation (4)

The shuffle algorithmStep random index operation0 r in range 0 to 51 swap element at index 0

with element at index r1 r in range 1 to 51 swap element at index 1

with element at index rk r in range k to 51 swap element at index k

with element at index r50 r in range 50, 51 swap element at index 50

Page 132: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

132BGA

CardDeck implementation (5)

Generating random index in range k to 51

Random rand = new Random();

Make random number generator:

int index = rand.nextInt(51-k+1) + k;

Get random integer in range 0 to 51-k, add k

int index = rand.nextInt(DECK_SIZE - k) + k;

Page 133: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

133BGA

CardDeck implementation (6)

public void shuffle() { Random rand = new Random(); initialize(); for (int k = 0; k <= DECK_SIZE - 2; k++) { int index = rand.nextInt(DECK_SIZE - k) + k; Card temp = deck[k]; deck[k] = deck[index]; deck[index] = temp; } }

Page 134: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

134BGA

CardDeck implementation (7)

public Card deal() { if (topCardIndex == DECK_SIZE) return null; Card topCard = deck[topCardIndex]; topCardIndex++; return topCard; }

public int cardsInDeck() { return DECK_SIZE - topCardIndex; }

public boolean empty() { return topCardIndex == DECK_SIZE; }

Page 135: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

135BGA

CardDeck implementation (8)

// string rep of cards remaining in deck public String toString() { StringBuffer b = new StringBuffer(215); for (int k = topCardIndex; k < DECK_SIZE; k++) { Card card = deck[k]; b.append(card.getCardName()); if ( (k+1) % 13 == 0) b.append("\n"); else b.append(" "); } return b.toString(); }} // end of CardDeck class

Page 136: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

136BGA

Test using BeanShell

addClassPath("c:/book-projects/chapter8/card-deck");CardDeck deck = new CardDeck();deck.shuffle();print(deck);7-S J-S 4-D 5-D A-H J-C 7-H 9-D 3-C 5-H T-H 9-H 3-D4-H Q-S 6-H 7-C 2-D A-S Q-H 8-S 6-C T-S K-C 7-D Q-D6-S 6-D A-C 2-C 8-D J-D Q-C 5-C T-C 3-S 8-H A-D 8-C5-S 9-C K-D 2-H 2-S 4-S J-H T-D 4-C 3-H K-S 9-S K-HCard top = deck.deal();print(top);7-Sprint(deck.cardsInDeck());51

Page 137: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

137BGA

CardDeckTester class (1)

public class CardDeckTester{ public void run() { // Construct, initialize and shuffle deck

CardDeck deck = new CardDeck(); System.out.println("Initialized deck:"); System.out.println(deck); System.out.println("Shuffled deck:"); deck.shuffle(); System.out.println(deck); // Now deal a few cards

Page 138: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

138BGA

CardDeckTester class (2)

// Now deal a few cards

Card card; card = deck.deal(); System.out.println("dealing " + card.getCardName()); card = deck.deal(); System.out.println("dealing " + card.getCardName());

Page 139: 1 Intro to Computer Science I Chapter 8 Array Data Types Processing Collections of Objects

139BGA

CardDeckTester class (3)

// Deal entire deck and display it without // using toString method

int count = 0; while (! deck.empty()) { Card c = deck.deal(); count++; System.out.print(c.getCardName()); if (count == 13) { System.out.println(); count = 0; } else System.out.println(" "); } if (count != 0) System.out.println(); }// end run} // end class