440 likes | 632 Views
Week 6: Arrays. CS 177. What good is a loop without something to loop over?. 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. Definition of an array. An array is a homogeneous , static data structure
E N D
Week 6: Arrays CS 177
What good is a loop without something to loop over? • 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
Definition of an array • An array is a homogeneous, static data structure • homogeneous means that everything in the array is the same type: int, double, String, etc. • static (in this case) means that the size of the array is fixed when you create it
Where have you seen arrays before? • The args variable passed into the main() method is an array of type String • This array has a set number of Strings (maybe zero) that you can use as input to your program • Now, we are giving you the ability to create and manipulate your own arrays
Declaration of an array • To declare an array of a specified type with a given name: • Example with a list of type int: • Just like any variable declaration, but with [] type[] name; int[] list;
Instantiation of an array • When you declare an array, you are only creating a variable that can reference an array • At first, it references nothing, also known as null • To use it, you have to create an array, supplying a specific size: • This code creates an array of 100 ints int[] list; list = newint[100];
Accessing elements of an array • As you have seen with args, you can access an element of an array by an index into it, using square brackets and a number • Once you have indexed into an array, that variable behaves exactly like any other variable of that type • You can get values from it and store values into it • Indexing starts at 0 and stops at 1 less than the length list[9] = 142; System.out.println(list[9]);
Length of an array • When you instantiate an array, you specify the length • Sometimes (like in the case of args) you are given an array of unknown length • You can use its length member to find out int[]list = new int[42]; int size = list.length; System.out.println(“List has “ + size + “ elements”); //prints 42
Automatic initialization • When you create an int, double, char, or boolean array, the array is automatically filled with certain values • For other types, including Strings, each index in the array must be filled explicitly
Explicit initialization • Explicit initialization can be done with a list: • Or, a loop could be used to set all the values: String[] days = {“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”, “Saturday”, “Sunday”}; int[] numbers = newint[100]; for(inti = 0; i < numbers.length;i++) numbers[i] = i + 1;
Memory • An array takes up the size of each element times the length of the array • Each array starts at some point in computer memory • The index used for the array is actually an offset from that starting point • That’s why the first element is at index 0
A look at memory • Suppose that we have an array of type int of length 10 • Java decides what address in memory is going to be used, but let’s say it starts at 524 524 528 532 536 540 544 548 552 556 560 12 43 -9 6 789 0 -23 23 10 6 0 1 2 3 4 5 6 7 8 9 Addresses Indexes
for loops + arrays = power • Arrays are a fixed size list of a single kind of data • A for loop is ideal for iterating over every item and performing some operation • for loops and arrays will crop up again and again • Of course, a while loop can be used with an array, but it is not used as often
for loop for summing an array • Imagine that we have an array of ints called list • Let’s use a for loop to sum up those ints • Super easy! • We don’t even need to know how big the array is ahead of time intsum = 0; for(inti = 0; i < list.length; i++ ) sum += list[i];
Statistics • Last week, we showed you how to add a set of numbers together as they were input by a user • Although this is a useful technique, not every operation is possible • We can find the sum or the average of the numbers because we only need to see the numbers once • What operation needs to see the numbers more than once?
Variance • Variance is a measurement of how spread out numbers are from their mean • To calculate it, you have to calculate the mean first • The formula is: • Where N is the number of elements, xi is the ith element, and is the mean
Code for variance • Given an array of doubles called number, here’s the code for finding their variance double average = 0; double variance = 0; double temp; for( inti = 0; i < number.length; i++ ) average += number[i]; average /= number.length; • for( inti = 0; i < number.length; i++ ) • { • temp = number[i] – average; • variance += temp*temp; • } • variance /= number.length;
Cards • We can represent a deck of cards as an array of 52 items • One easy way is to make each item a String giving the name of the card
Array swap • Swapping the values of two variables is a fundamental operation in programming • It is going to become more important in arrays because the order of values could be important • The simplest way to swap two variables involves using a third variable as a temporary location
Swap code • Here is an example of swapping two Strings indexed i and j in an array of Strings called moniker inti = StdIn.readInt(); • int j = StdIn.readInt(); • String temp; temp = moniker[i]; moniker[i] = moniker[j]; moniker[j] = temp;
Shuffling Cards • Using the swap code, we can do a random shuffling of a deck • To do so, we go through each element of the array, and randomly swap it with any of the later elements • for( inti = 0; i < n; i++ ) • { • exchange = i + (int)(Math.random() * (n - i)); • temp = deck[i]; • deck[i] = deck[exchange]; • deck[exchange] = temp; • }
Searching • Searching through an array is an important operation • The simplest way to do so is just linear search: check every element in the array • Searching and sorting are really keys to all kinds of problems • We’ll cover both topics in depth in a few weeks
Uninitialized Arrays • Remember, you get no initialization with arrays of Strings • If you try to access a non-existent element, the world will explode String[] stuff = new String[50]; String s = stuff[42]; // works fine int size = s.length(); // destroys world
Array Index Errors • Accessing an element of an array that doesn’t exist will also kill your program int[] numbers = new int[100]; numbers[103] = 5; //crash • System.out.println( numbers[-3]);//crash • System.out.println( numbers[99]);//okay for( inti = 0; i <= 100; i++ ) numbers[i] = i;//crashes when i = 100
2D arrays • Just as it is possible to make a one-dimensional list out of a single data type, it is also possible to make a table out of one data type • We can extend the arrays you know to have two dimensions with very similar syntax
Declaration • To declare a two dimensional array, we just use two sets of square brackets ([][]): • Doing so creates a variable that can hold a 2D array of ints • As before, we still need to instantiate the array to have a specific size: int [][] table; table = new int[5][10];
Visualization of 2D arrays • Like matrices, we usually visualize the first dimension as the rows and the second dimension as the columns Second Dimension 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 First Dimension
Visualization of 2D arrays • Let’s write a little code to put data into the table int [][] table = newint[5][10]; int label = 1; for( inti = 0; i < 5; i++ ) • for( int j = 0; j < 10; j++ ) • { • table[i][j] = label; • label++; • }
Visualization of 2D arrays • The result of that code is: Second Dimension 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 First Dimension
All kinds of things to represent • The ability to represent 2D data opens up lots of possibilities • We could store: • A chessboard • An image (where each number represents the color of a pixel) • A game of battleship • Or something even more interesting… • A matrix!
What is the matrix? • I’m sure you’ve seen matrices before • Still, here’s a refresher: n columns m rows
Matrix operations • Addition can be done between two m x n matrices but not between matrices with mismatching dimensions • Just add the corresponding locations • You can also multiply an m x k matrix called A by a k x n matrix called B: only the common dimension must match • The result is an m x n matrix where the element in row i, column j is
Chessboard • We could represent a chessboard as an 8 x 8 array of chars • Use the following encoding: • ‘P’ = pawn • ‘N’ = knight • ‘B’ = bishop • ‘R’ = rook • ‘Q’ = queen • ‘K’ = king • Use upper case characters for black pieces and lower case characters for white ones
Checking a pawn for danger • Imagine there is a pawn randomly set on the board and a queen of the opposite color on the board • Write a program to see if the queen can capture the pawn in the next move
Algorithm for chess problem • Find the row and column location of both the queen and the pawn • The pawn is in danger if: • The queen and the pawn have the same row • The queen and the pawn have the same column • The queen and the pawn are on the same diagonal
Multidimensional arrays don’t exist • I lied to you • There are no such things as multidimensional arrays • They are all actually just arrays of arrays (of arrays…) • You are not required to create all of the dimensions at one time
Ragged arrays • You could create each dimension separately and even specify different sizes • For example: int [][] pharma = newint[5][]; for( inti = 0; i < 5; i++ ) pharma[i] = new int[i + 1];
What will happen then? • The resulting array will look like this: Columns 0 1 2 3 4 0 1 2 3 4 Rows
Why would you do that? • First of all, be warned that if you access an element that an array doesn’t have, your program will still crash • Ragged arrays do allow you to save some space • Imagine if some rows needed 10 elements and others needed 1,000,000 • Usually, there’s no good reason to use ragged arrays, but sometimes there is….
3 dimensions … and more • It doesn’t have to stop at 2 dimensions! • You can have 3 or more • Here’s an example with 3 dimensions: int [][][] rubiksCube = newint[3][3][3]; int count = 1; for( inti = 0; i < rubiksCube.length; i++ ) • for( int j = 0; j < rubiksCube[i].length; j++ ) • for( int k = 0; j < rubiksCube[i][j].length; k++ ) • { • rubiksCube[i][j][k] = count; • count++; • }
What does a 3D array look like? • It looks like whatever you want it to • You can visualize it in 3D if you want • There are other techniques • It’s just a way to store data • It doesn’t actually look like anything inside the computer
Why use a high dimensional array? • Sometimes you have data categorized in several different ways • For example, Purdue might keep some statistics according to Year, Gender, and Race • 0 – Freshman • 1 – Sophomore • 2 – Junior • 3 – Senior • Perfect candidate for a 3D array • 0 – Male • 1 – Female • 0 – African American • 1 – Asian • 2 – Caucasian • 3 – Other
Why not use a high dimensional array • Too many brackets • Too much stuff • Total size used is the product of the length of all the dimensions • 100 x 100 x 100 = 1,000,000 • Hard to visualize, hard to imagine • Up as high as 4 is sometimes useful • Don’t go beyond 3 on a regular basis