1.4 Arrays "... By the way, we rank 10 th among the industrialized world in broadband technology and its availability. That’s not good enough for America.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Chapter 10 Introduction to Arrays
Coupon collector’s problem CS658 Po-Ching Liu. Question A person trying to collect each of b different coupons must acquire approximately x randomly obtained.
Week 6: Arrays 1.  Loops are great  But, without a way to talk about a group of values, we can’t get the full potential out of a loop  Enter: the array.
Lecture 05 - Arrays. Introduction useful and powerful aggregate data structure Arrays allow us to store arbitrary sized sequences of primitive values.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
Chapter 8 Arrays and Strings
 Pearson Education, Inc. All rights reserved Arrays.
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 8 Objects & Classes. Definition of Object-Oriented Programming (OOP) Object-Oriented Programming (OOP) uses the analogy of real objects as a template.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
EMB1006 JAVA Part 2 Arrays and onwards Jonathan-Lee Jones.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
A First Book of ANSI C Fourth Edition
Chapter 8 Arrays and Strings
A Semantic Error in Google last weekend! Someone in Google typed an extra ‘/’ character into their URL List Link to CNN video report posted on Collab.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
ArrayList, Multidimensional Arrays
1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008.
 Pearson Education, Inc. All rights reserved Arrays.
 Pearson Education, Inc. All rights reserved Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Chapter 7 Arrays. A 12-element array Declaring and Creating Arrays Arrays are objects that occupy memory Created dynamically with keyword new int c[]
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
1 Arrays An array is a collection of data values, all of which have the same type. The size of the array is fixed at creation. To refer to specific values.
Multidimensional Arrays. 2 Two Dimensional Arrays Two dimensional arrays. n Table of grades for each student on various exams. n Table of data for each.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
CompSci 100E 3.1 Random Walks “A drunk man wil l find his way home, but a drunk bird may get lost forever”  – Shizuo Kakutani Suppose you proceed randomly.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Heads-Up – Programming Quiz This Week Announcement will be made via You will be provided with a login to the password-protected website You will.
1 Lecture 12 Pointers and Strings Section 5.4, ,
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
The median again The steps of our algorithm: Read the size of the list, N. Declare and instantiate an array of integers, "list". Read the elements of list.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
UniMAP Sem2-10/11 DKT121: Fundamental of Computer Programming1 Arrays.
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
1 Arrays of Arrays Quick review … arrays Arrays of arrays ≡ multidimensional array Example: times table Representation in memory Ragged arrays Example:
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
Introducing Arrays. Too Many Variables?  Remember, a variable is a data structure that can hold a single value at any given time.  What if I want to.
Comparing ArrayLists and Arrays. ArrayLists ArrayLists are one type of flexible-size collection classes supported by Java –ArrayLists increase and decrease.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Chapter 8: Arrays Gator Engineering One-dimensional array Copyright © 2008 W. W. Norton & Company. All rights reserved. 1 Move the first element to the.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
ARRAYS Multidimensional realities Image courtesy of
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
 2005 Pearson Education, Inc. All rights reserved Arrays.
CS 112 Introduction to Programming Array Reference Semantics; 2D Arrays Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
Chapter 9 Introduction to Arrays Fundamentals of Java.
Single Dimensional Arrays
Computer Programming BCT 1113
Multidimensional Arrays
Exam 2 Review 1.
Multidimensional Arrays
int [] scores = new int [10];
1.4 Arrays Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 · 2/6/11 12:33.
Introduction to Computer Science I.
Loops CGS3416 Spring 2019 Lecture 7.
Presentation transcript:

1.4 Arrays "... By the way, we rank 10 th among the industrialized world in broadband technology and its availability. That’s not good enough for America. Tenth is 10 spots too low as far as I’m concerned. " - George W. Bush

2 Arrays This lecture. Store and manipulate huge quantities of data. Array. Indexed sequence of values of the same type. Examples. n 52 playing cards in a deck. n 14 thousand undergrads at UVa. n 1 million characters in a book. n 10 million audio samples in an MP3 file. n 4 billion nucleotides in a DNA strand. horton0 humphrey1 soffa2 knuth3 billg4 rms5 mst3k6 alvin7 indexvalue

3 Many Variables of the Same Type Goal. 10 variables of the same type. // tedious and error-prone double a0, a1, a2, a3, a4, a5, a6, a7, a8, a9; a0 = 0.0; a1 = 0.0; a2 = 0.0; a3 = 0.0; a4 = 0.0; a5 = 0.0; a6 = 0.0; a7 = 0.0; a9 = 0.0; double x = a4 + a8;

4 Arrays in Java Java has special language support for arrays. n To make an array: declare, create, and initialize it. To access element i of array named a, use a[i]. Array indices start at 0. int N = 10; double[] a; // declare the array a = new double[N]; // create the array for (int i = 0; i < N; i++) // initialize the array a[i] = 0.0; // all to 0.0

5 Arrays in Java Java has special language support for arrays. n To make an array: declare, create, and initialize it. To access element i of array named a, use a[i]. Array indices start at 0. Compact alternative. n Declare, create, and initialize in one statement. n Default initialization: all numbers automatically set to zero. int N = 10; double[] a; // declare the array a = new double[N]; // create the array for (int i = 0; i < N; i++) // initialize the array a[i] = 0.0; // all to 0.0 int N = 10; double[] a = new double[N]; // declare, create, init

6 Vector Dot Product Dot product. Given two vectors x[] and y[] of length N, their dot product is the sum of the products of their corresponding components. double[] x = { 0.3, 0.6, 0.1 }; double[] y = { 0.5, 0.1, 0.4 }; double sum = 0.0; for (int i = 0; i < N; i++) { sum += x[i]*y[i]; // same as sum = sum + x[i]*y[i]; }

7 An array’s length Each array keeps track of how many items it contains n In length field. Example: int[] list = { 3, -1, 0, 7, 5 } list.length == 5 // is true n Note use of “.” notation. More on this later, but for now think of it as “something inside of” the thing on the left n Important: an array’s length cannot change (grow, shrink) – Must know how many items will be stored when it’s created! int target = Integer.parseInt(args[0]); int[] list = { -3, -1, 0, 3, 5, 9 }; // Find index of first occurrence of target in array int i = 0; while ( i < list.length && list[i] != target ) i = i + 1; if ( i != list.length ) System.out.println("Found at index " + i );

Auto-increment and arrays Auto-increment and auto-decrement operators used with arrays. n ++i means “add one to i’s value and use the updated value” n i++ means “use i’s value now and then add one to the old value” n Can use on line by itself as a single statement – In which case they do exactly the same thing! n Can be part of an expression: y = 0; x = y++; // x is 0 and y is 1 y = 0; z = ++y; // x is 1 and y is 1 8 int target = Integer.parseInt(args[0]); int[] list = { -3, -1, 0, 3, 5, 9 }; int i = 0; while ( i < list.length && list[i++] != target ) // ++i wrong ; // “null statement” -- empty loop body! if ( i != list.length ) System.out.println("Found at index " + (i-1) );

9 Array Processing Code

Shuffling a Deck

11 Setting Array Values at Compile Time Ex. Print a random card. String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" }; String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" }; int i = (int) (Math.random() * 13); // between 0 and 12 int j = (int) (Math.random() * 4); // between 0 and 3 System.out.println(rank[i] + " of " + suit[j]);

12 Setting Array Values at Run Time Ex. Create a deck of playing cards and print them out. Q. What does it output? String[] deck = new String[52]; for (int i = 0; i < 13; i++) for (int j = 0; j < 4; j++) deck[4*i + j] = rank[i] + " of " + suit[j]; for (int i = 0; i < 52; i++) System.out.println(deck[i]);

13 Shuffling Goal. Given an array, rearrange its elements in random order. Shuffling algorithm. In iteration i, pick random card from deck[i] through deck[N-1], with each card equally likely. Exchange it with deck[i]. int N = deck.length; for (int i = 0; i < N; i++) { int r = i + (int) (Math.random() * (N-i)); String t = deck[r]; deck[r] = deck[i]; deck[i] = t; } between i and N-1 swap idiom

14 Shuffling a Deck of Cards public class Deck { public static void main(String[] args) { String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" }; String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" }; int SUITS = suit.length; int RANKS = rank.length; int N = SUITS * RANKS; String[] deck = new String[N]; for (int i = 0; i < RANKS; i++) for (int j = 0; j < SUITS; j++) deck[SUITS*i + j] = rank[i] + " of " + suit[j]; for (int i = 0; i < N; i++) { int r = i + (int) (Math.random() * (N-i)); String t = deck[r]; deck[r] = deck[i]; deck[i] = t; } for (int i = 0; i < N; i++) System.out.println(deck[i]); } avoid "hardwired" constants build the deck shuffle print shuffled deck

15 Shuffling a Deck of Cards % java Deck 5 of Clubs Jack of Hearts 9 of Spades 10 of Spades 9 of Clubs 7 of Spades 6 of Diamonds 7 of Hearts 7 of Clubs 4 of Spades Queen of Diamonds 10 of Hearts 5 of Diamonds Jack of Clubs Ace of Hearts... 5 of Spades % java Deck 10 of Diamonds King of Spades 2 of Spades 3 of Clubs 4 of Spades Queen of Clubs 2 of Hearts 7 of Diamonds 6 of Spades Queen of Spades 3 of Spades Jack of Diamonds 6 of Diamonds 8 of Spades 9 of Diamonds of Spades

Coupon Collector

17 Coupon Collector Problem Coupon collector problem. Given N different card types, how many do you have to collect before you have (at least) one of each type? Simulation algorithm. Repeatedly choose an integer i between 0 and N-1. Stop when we have at least one card of every type. Q. How to check if we've seen a card of type i ? A. Maintain a boolean array so that found[i] is true if we've already collected a card of type i. assuming each possibility is equally likely for each card that you collect

18 Coupon Collector: Java Implementation public class CouponCollector { public static void main(String[] args) { int N = Integer.parseInt(args[0]); int cardcnt = 0; // number of cards collected int valcnt = 0; // number of distinct cards // do simulation boolean[] found = new boolean[N]; while (valcnt < N) { int val = (int) (Math.random() * N); cardcnt++; if (!found[val]) valcnt++; found[val] = true; } System.out.println(cardcnt); } type of next card (between 0 and N-1)

19 Coupon Collector: Debugging Debugging. Add code to print contents of all variables. Challenge. Debugging with arrays requires tracing many variables.

20 Coupon Collector: Mathematical Context Coupon collector problem. Given N different possible cards, how many do you have to collect before you have (at least) one of each type? Fact. About N (1 + 1/2 + 1/3 + … + 1/N). Ex. N = 30 baseball teams. Expect to wait  120 years before all teams win a World Series. under idealized assumptions

21 Coupon Collector: Scientific Context Q. Given a sequence from nature, does it have same characteristics as a random sequence? A. No easy answer - many tests have been developed. Coupon collector test. Compare number of elements that need to be examined before all values are found against the corresponding answer for a random sequence.

22

23 Things to Note in the Textbook Precomputed Values (pp. 95-6). Arrays are useful for computing and storing a sequence of values that will be used over and over. Space-time tradeoff. (Avoid re-computing but must store them all.) Simplifying Repetitive Code (p. 96). See example in book where long if-else-if sequence replaced by “array lookup”. Copying vs. Assignment (pp ). Assigning one array to another does not do what you probably expect! array1 = array2; Two names for the one array (one sequence of memory cells). Want array2 to be separate array where array2[i]==array1[i]? Must copy element-by-element with a loop! Also: == doesn’t compare two arrays’ contents!

Multidimensional Arrays

25 Two Dimensional Arrays Two dimensional arrays. n Table of data for each experiment and outcome. n Table of grades for each student and assignments. n Table of grayscale values for each pixel in a 2D image. Mathematical abstraction. Matrix. Java abstraction. 2D array. Reference: Botstein & Brown group Gene 1 Gene n gene expressed gene not expressed

26 Two Dimensional Arrays in Java Array access. Use a[i][j] to access element in row i and column j. Zero-based indexing. Row and column indices start at 0. int M = 10; int N = 3; double[][] a = new double[M][N]; for (int i = 0; i < M; i++) { for (int j = 0; j < N; j++) { a[i][j] = 0.0; }

27 Setting 2D Array Values at Compile Time Initialize 2D array by listing values, row after row. double[][] p = { {.02,.92,.02,.02,.02 }, {.02,.02,.32,.32,.32 }, {.02,.02,.02,.92,.02 }, {.92,.02,.02,.02,.02 }, {.47,.02,.47,.02,.02 }, };

28 Matrix Addition Matrix addition. Given two N-by-N matrices a and b, define c to be the N-by-N matrix where c[i][j] is the sum a[i][j] + b[i][j]. double[][] c = new double[N][N]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) c[i][j] = a[i][j] + b[i][j];

29 Matrix Multiplication Matrix multiplication. Given two N-by-N matrices a and b, define c to be the N-by-N matrix where c[i][j] is the dot product of the i th row of a and the j th row of b. double[][] c = new double[N][N]; for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) for (int k = 0; k < N; k++) c[i][j] += a[i][k] * b[k][j]; all values initialized to 0

Self-Avoiding Walk

31 Self-Avoiding Walk Model. n N-by-N lattice. n Start in the middle. n Randomly move to a neighboring intersection, avoiding all previous intersections. Applications. Polymers, statistical mechanics, etc. Q. What fraction of time will you escape in an 5-by-5 lattice? Q. In an N-by-N lattice? Q. In an N-by-N-by-N lattice?

32 Self-Avoiding Walk: Implementation public class SelfAvoidingWalk { public static void main(String[] args) { int N = Integer.parseInt(args[0]); // lattice size int T = Integer.parseInt(args[1]); // number of trials int deadEnds = 0; // trials resulting in dead end for (int t = 0; t < T; t++) { boolean[][] a = new boolean[N][N]; // intersections visited int x = N/2, y = N/2; // current position while (x > 0 && x 0 && y < N-1) { if (a[x-1][y] && a[x+1][y] && a[x][y-1] && a[x][y+1]) { deadEnds++; break; } a[x][y] = true; // mark as visited double r = Math.random(); if (r < 0.25 && !a[x+1][y]) x++; else if (r < 0.50 && !a[x-1][y]) x--; else if (r < 0.75 && !a[x][y+1]) y++; else if (r < 1.00 && !a[x][y-1]) y--; } System.out.println(100*deadEnds/T + "% dead ends"); } take a random unvisited step dead end

33 Self-Avoiding Walks

34 Summary Arrays. n Organized way to store huge quantities of data. n Almost as easy to use as primitive types. n Can directly access an element given its index. Ahead. Reading in large quantities of data from a file into an array.