Omputer Cience: 3. Arrays
Omputer Cience: 3. Arrays
Omputer Cience: 3. Arrays
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
Computer Science
Computer 3. Arrays
Science
An Interdisciplinary Approach
ROBERT SEDGEWICK
1.4 K E V I N WAY N E
http://introcs.cs.princeton.edu
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
3. Arrays
• Basic concepts
• Typical array-processing code
• Two-dimensional arrays
CS.3.A.Arrays.Basics
Basic building blocks for programming
objects
arrays
Ability to store and process
conditionals and loops huge amounts of data
3
Your first data structure
double a0 = 0.0;
double a1 = 0.0;
double a2 = 0.0; 10 values, with an array 1 million values, with an array
double a3 = 0.0;
double a4 = 0.0; double[] a; double[] a;
double a5 = 0.0; a = new double[10]; a = new double[1000000];
double a6 = 0.0; ... ...
double a7 = 0.0; a[4] = 3.0; a[234567] = 3.0;
double a8 = 0.0; ... ...
double a9 = 0.0; a[8] = 8.0; a[876543] = 8.0;
... ... ...
a4 = 3.0; double x = a[4] + a[8]; double x = a[234567] + a[876543];
...
a8 = 8.0;
...
double x = a4 + a8; scales to handle huge amounts of data
an easy alternative
5
Memory representation of an array
A computer's memory is also an indexed sequence of memory locations. stay tuned for many details
a for simplicity in this lecture, think of a as the memory address of the first location
the actual implementation in Java is just slightly more complicated.
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
Critical concepts
• Indices start at 0.
• Given i, the operation of accessing the value a[i] is extremely efficient.
• The assignment b = a makes the names b and a refer to the same array.
it does not copy the array,
as with primitive types
(stay tuned for details)
6
Java language support for arrays
Initialization options
no need to use a loop like
for (int i = 0; i < 1000; i++)
a[i] = 0.0;
operation typical code
To copy an array, create a new array , then copy all the values.
a i b i
0.3 0.6 0.99 0.01 0.5 0.3 0.6 0.99 0.01 0.5
Important note: The code b = a does not copy an array (it makes b and a refer to the same array).
a b
8
Programming with arrays: typical examples
Access command-line args in system array For brevity, N is a.length and b.length in all this code.
int stake = Integer.parseInt(args[0]);
int goal = Integer.parseInt(args[1]); Copy to another array
int trials = Integer.parseInt(args[2]); double[] b = new double[N];
for (int i = 0; i < N; i++)
b[i] = a[i];
Compute the average of array values Find the maximum of array values
double sum = 0.0; double max = a[0];
for (int i = 0; i < N; i++) for (int i = 1; i < N; i++)
sum += a[i]; if (a[i] > max) max = a[i];
double average = sum / N;
9
Pop quiz 1 on arrays
b = a;
for (int i = 1; i < b.length; i++)
b[i] = i;
10
Pop quiz 1 on arrays
11
Programming with arrays: typical bugs
12
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
Image sources
http://commons.wikimedia.org/wiki/File:CERN_Server_03.jpg
CS.3.A.Arrays.Basics
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
3. Arrays
• Basic concepts
• Examples of array-processing code
• Two-dimensional arrays
CS.3.B.Arrays.Examples
Example of array use: create a deck of cards
Define three arrays String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
Use nested for loops to put all the cards in the deck.
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...
deck 2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣ Q♣ K♣ A♣ 2♦ 3♦ 4♦ 5♦ 6♦ 7♦ 8♦ 9♦ ...
15
Example of array use: create a deck of cards
16
Pop quiz 2 on arrays
17
Pop quiz 2 on arrays
A. The array is filled in a different order, but the output is the same. j
0 1 2 3
suit ♣ ♦ ♥ ♠
i
0 1 2 3 4 5 6 7 8 9 10 11 12
rank 2 3 4 5 6 7 8 9 10 J Q K A
18
Pop quiz 3 on arrays
% java Deck
2♣ 2♦ 2♥ 2♠ 3♣ 3♦ 3♥ 3♠ 4♣ 4♦ 4♥ 4♠ 5♣ 5♦ 5♥ 5♠ 6♣ 6♦ 6♥ 6♠ 7♣ 7♦ 7♥ 7♠ 8♣ 8♦ 8♥ 8♠ 9♣ 9♦ 9♥ 9♠
10♣ 10♦ 10♥ 10♠ J♣ J♦ J♥ J♠ Q♣ Q♦ Q♥ Q♠ K♣ K♦ K♥ K♠ A♣ A♦ A♥ A♠
%
19
Pop quiz 3 on arrays
% java Deck
2♣ 2♦ 2♥ 2♠ 3♣ 3♦ 3♥ 3♠ 4♣ 4♦ 4♥ 4♠ 5♣ 5♦ 5♥ 5♠ 6♣ 6♦ 6♥ 6♠ 7♣ 7♦ 7♥ 7♠ 8♣ 8♦ 8♥ 8♠ 9♣ 9♦ 9♥ 9♠
10♣ 10♦ 10♥ 10♠ J♣ J♦ J♥ J♠ Q♣ Q♦ Q♥ Q♠ K♣ K♦ K♥ K♠ A♣ A♦ A♥ A♠
%
i
0 1 2 3 4 5 6 7 8 9 10 11 12
rank 2 3 4 5 6 7 8 9 10 J Q K A
0 1 2 3 4 5 6 7 8 9 10 11 12 ...
deck 2♣ 2♦ 2♥ 2♠ 3♣ 3♦ 3♥ 3♠ 4♣ 4♦ 4♥ 4♠ 5♣ ...
20
21
Array application: take a card, any card
Algorithm
Take N from the command line and do the following N times
• Calculate a random index r between 0 and 51.
• Print deck[r].
for (int i = 0; i < N; i++) each value between 0 and 51 equally likely
{
int r = (int) (Math.random() * 52);
System.out.println(deck[r]);
}
Note: Same method is effective for printing a random sequence from any data collection.
22
Array application: random sequence of cards
String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9","10", "J", "Q", "K", "A" };
String[] suit = { "♣", "♦", "♥", "♠" };
Note: Sample is with replacement (same card can appear multiple times). appears twice
23
Array application: shuffle and deal from a deck of cards
24
Array application: shuffle a deck of 10 cards (trace)
deck
i r
for (int i = 0; i < 10; i++) 0 1 2 3 4 5 6 7 8 9
{
int r = i + (int) (Math.random() * (10-i)); 2♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 9♣ 10♣ J♣
String t = deck[r];
0 7 9♣ 3♣ 4♣ 5♣ 6♣ 7♣ 8♣ 2♣ 10♣ J♣
deck[r] = deck[i];
deck[i] = t; 1 3 9♣ 5♣ 4♣ 3♣ 6♣ 7♣ 8♣ 2♣ 10♣ J♣
}
2 9 9♣ 5♣ J♣ 3♣ 6♣ 7♣ 8♣ 2♣ 10♣ 4♣
9 9 9♣ 5♣ J♣ 4♣ 8♣ 3♣ 10♣ 7♣ 6♣ 2♣
Note: Same method is effective for randomly rearranging any type of data.
25
Array application: shuffle and deal from a deck of cards
String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
String[] suit = { "♣", "♦", "♥", "♠" };
Sequence
Collection
2 3 4 5 6 7 8 9 10 J Q K A
28
Array application: coupon collector (trace for M = 6)
found
r distinct cards
0 1 2 3 4 5
F F F F F F 0 0
0 T T T F T T 5 8
1 T T T F T T 5 9
3 T T T T T T 6 10
29
Simulation, randomness, and analysis (revisited)
type M M ln M + .57721M
% java CouponCollector 4 1000000
playing card suits 4 8 8
Image sources
http://www.vis.gr.jp/~nazoya/cgi-bin/catalog/img/CARDSBIC809_red.jpg
http://www.alegriphotos.com/Shuffling_cards_in_casino-photo-deae1081e5ebc6631d6871f8b320b808.html
http://iveypoker.com/wp-content/uploads/2013/09/Dealing.jpg
http://upload.wikimedia.org/wikipedia/commons/b/bf/Pierre-Simon,_marquis_de_Laplace_(1745-1827)_-_Guérin.jpg
CS.3.B.Arrays.Examples
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
3. Arrays
• Basic concepts
• Examples of array-processing code
• Two-dimensional arrays
CS.3.C.Arrays.2D
Two-dimensional arrays
grade
Examples 0 1 2 3 4 5 ...
0 A A C B A C
• Matrices in math calculations.
1 B B B B A A
student ID
• Grades for students in an online class. 2 C D D B C A
• Outcomes of scientific experiments. 3 A A A A A A
4 C C B C B B
• Transactions for bank customers.
5 A A A B A A
• Pixels in a digital image. ...
• Geographic data
• ...
y-coordinate
Main purpose. Facilitate storage and manipulation of data.
x-coordinate 35
Java language support for two-dimensional arrays (basic support)
can be different
Refer to the number of columns a[i].length;
for each row
a[][]
a[0][0] a[0][1] a[0][2] a[0][3] a[0][4] a[0][5] a[0][6] a[0][7] a[0][8] a[0][9]
a[1] a[1][0] a[1][1] a[1][2] a[1][3] a[1][4] a[1][5] a[1][6] a[1][7] a[1][8] a[1][9]
a[2][0] a[2][1] a[2][2] a[2][3] a[2][4] a[2][5] a[2][6] a[2][7] a[2][8] a[2][9]
a 3-by-10 array
36
Java language support for two-dimensional arrays (initialization)
double[][] p =
{
{ .92, .02, .02, .02, .02 },
{ .02, .92, .32, .32, .32 },
Initialize to literal values
{ .02, .02, .02, .92, .02 },
{ .92, .02, .02, .02, .02 },
{ .47, .02, .47, .02, .02 },
};
37
Application of arrays: vector and matrix calculations
38
Application of arrays: vector and matrix calculations
end-of-loop trace
39
Pop quiz 4 on arrays
1. N
2. N 2
3. N 3
4. N 4
40
Pop quiz 4 on arrays
1. N
2. N 2
4. N 4
41
Self-avoiding random walks
escape
Model: a random process in an N-by-N lattice
• Start in the middle.
• Move to a random neighboring intersection
but do not revisit any intersection.
• Outcome 1 (escape): reach edge of lattice.
• Outcome 2 (dead end): no unvisited neighbors.
Approach: Use Monte Carlo simulation, recording visited positions in an N-by-N array.
42
Self-avoiding random walks
43
Application of 2D arrays: self-avoiding random walks
while (x > 0 && x < N-1 && y > 0 && y < N-1) % java SelfAvoidingWalker 70 100000
96% dead ends
{
if (a[x-1][y] && a[x+1][y] && a[x][y-1] && a[x][y+1]) % java SelfAvoidingWalker 80 100000
98% dead ends
{ deadEnds++; break; }
% java SelfAvoidingWalker 90 100000
99% dead ends
a[x][y] = true;
double r = Math.random(); % java SelfAvoidingWalker 100 100000
if (r < 0.25) { if (!a[x+1][y]) x++; } 99% dead ends
else if (r < 0.50) { if (!a[x-1][y]) x--; }
100%
else if (r < 0.75) { if (!a[x][y+1]) y++; }
else if (r < 1.00) { if (!a[x][y-1]) y--; }
75%
}
}
50%
System.out.println(100*deadEnds/trials + "% dead ends");
}
25%
}
0%
10 20 30 40 50 60 70 80 90 100
44
Simulation, randomness, and analysis (revisited again)
Applications
• Model the behavior of solvents and polymers.
• Model the physics of magnetic materials.
• (many other physical phenomena)
Paul Flory
1910-1985
Q. What is the probability of reaching a dead end? Nobel Prize 1974
Mathematicians and
A. Nobody knows (despite decades of study). physics researchers
cannot solve the problem.
Computational models play
A. 99+% for N >100 (clear from simulations). YOU can! an essential role in modern
scientific research.
Remark: Computer simulation is often the only effective way to study a scientific phenomenon.
45
Your first data structure
LFSR
digital audio
46
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
Image sources
http://en.wikipedia.org/wiki/Airedale_Terrier#mediaviewer/File:Airedale_Terrier.jpg
http://www.nobelprize.org/nobel_prizes/chemistry/laureates/1974/flory_postcard.jpg
CS.3.C.Arrays.2D
COMPUTER SCIENCE
S E D G E W I C K / W A Y N E
PA R T I : P R O G R A M M I N G I N J AVA
Computer Science
Computer 3. Arrays
Science
An Interdisciplinary Approach
ROBERT SEDGEWICK
1.4 K E V I N WAY N E
http://introcs.cs.princeton.edu