1 Traversal algorithms. 2 Array traversal traversal: An examination of each element of an array. Traversal algorithms often takes the following form:

Slides:



Advertisements
Similar presentations
1 Various Methods of Populating Arrays Randomly generated integers.
Advertisements

CS110 Programming Language I Lab 10: Arrays I Computer Science Department Spring 2014.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 7: Arrays.
1 11/27/06CS150 Introduction to Computer Science 1 Searching Arrays.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 7: Arrays.
Building Java Programs Chapter 7 Arrays. 2 Can we solve this problem? Consider the following program (input underlined): How many days' temperatures?
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Tallying and Traversing Arrays reading: 7.1 self-checks: #1-9 videos:
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
Multi-Dimensional Arrays Rectangular & Jagged Plus: More 1D traversal.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Tallying and Traversing Arrays reading: 7.1 self-checks: #1-9 videos:
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 4.3, 7.6.
1 Reference semantics. 2 A swap method? Does the following swap method work? Why or why not? public static void main(String[] args) { int a = 7; int b.
Part 2. Searching Arrays Looking for a specific element in an array E.g., whether a certain score (85) is in a list of scores Linear search Binary search.
1 Chapter 7 Single-Dimensional Arrays. 2 Arrays Array is a data structure that represents a collection of the same types of data elements. A single-dimensional.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
CSc2310 tutoring session, week 8 Fall, 2012 Haidong Xue 5:30pm—8:30pm 10/23/2012 and 10/24/2012 -Using Exceptions -Homework 4.
1 Chapter 8 Multi-Dimensional Arrays. 2 1-Dimentional and 2-Dimentional Arrays In the previous chapter we used 1-dimensional arrays to model linear collections.
Programming Fundamentals I (COSC-1336), Lecture 8 (prepared after Chapter 7 of Liang’s 2011 textbook) Stefan Andrei 4/23/2017 COSC-1336, Lecture 8.
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 Pepper. What is an Array A box that holds many of the exact same type in mini-boxes A number points to the mini-box The number starts at 0 String.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
1 BUILDING JAVA PROGRAMS CHAPTER 7 LECTURE 7-3: ARRAYS AS PARAMETERS; FILE OUTPUT.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays as Parameters; File Output reading: 7.1, 4.3, 3.3 self-checks:
Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 7.6, 4.3.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Building Java Programs Chapter 7
1 Array basics. Data Structures Sometimes, we have data that have some natural structure to them  A few examples: Texts are sequences of characters Images.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 7: Arrays.
Catie Welsh April 20,  Program 4 due Wed, April 27 th by 11:59pm  Final exam, comprehensive ◦ Friday, May 6th, 12pm  No class Friday - Holiday.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 7.1, 4.4 self-checks: #1-9.
Array - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 12/19/20151.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Review :chapters What is an algorithm? A step by step description of how to accomplish a task. For example, Adding 3 numbers N1, N2 and N3 Add.
Introduction to array: why use arrays ?. Motivational example Problem: Write a program that reads in and stores away 5 double numbers After reading in.
BUILDING JAVA PROGRAMS CHAPTER 7: ARRAYS 1. 2 OUT-OF-BOUNDS INDEXES The indexes that are legal to access in an array are those in the range of 0 to the.
int [] scores = new int [10];
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 17: Arrays for Tallying; Text Processing reading: 4.3, 7.6 (Slides adapted.
Topic 23 arrays - part 3 (tallying, text processing) Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays as Parameters; File Output reading: 7.1, 4.3, 3.3 self-checks:
1 Building Java Programs Chapter 7: Arrays. 2 Chapter outline array basics declaring and initializing an array getting and setting values of elements.
Lecture 7: Arrays Michael Hsu CSULA 3 Opening Problem Read one hundred numbers, compute their average, and find out how many numbers are above the average.
Building Java Programs Chapter 7 Arrays Copyright (c) Pearson All rights reserved.
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. System.out.println(“Please enter grade.
Building Java Programs
CSc 110, Autumn 2017 Lecture 24: Lists for Tallying; Text Processing
Building Java Programs
Array traversals, text processing
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Lecture 7-3: Arrays for Tallying; Text Processing
Topic 23 arrays - part 3 (tallying, text processing)
Building Java Programs
Building Java Programs
int [] scores = new int [10];
Building Java Programs
Array basics Readings: 7.1.
Suggested self-checks: Section 7.11 #1-11
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Why are arrays useful? We can use arrays to store a large amount of data without declaring many variables. Example: Read in a file of 1000 numbers, then.
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

1 Traversal algorithms

2 Array traversal traversal: An examination of each element of an array. Traversal algorithms often takes the following form: for (int i = 0; i.length; i++) { do something with [i]; } Examples:  printing out the elements  searching for a specific value  rearranging the elements  computing a value based on the elements

3 Example: Printing array elements int[] list = { 4, 1, 9, 7 }; for (int i = 0; i < list.length; i++) { System.out.println(i + ": " + list[i]); } Output: 0: 4 1: 1 2: 9 3: 7 How could we change the code to print the following? 4, 1, 9, 7

4 Example: Searching an array int[] list = { 4, 1, 2, 7, 6, 3, 2, 4, 0, 9 }; int largestEven = 0; for (int i = 0; i < list.length; i++) { if (list[i] % 2 == 0 && list[i] > largestEven) { largestEven = list[i]; } } System.out.println("Largest even: " + largestEven); Output: Largest even: 6 What assumptions does this code make?

5 Shifting elements in an array

6 Array insertion How would you insert a number into an array of sorted integers? Assume that the largest number gets bumped off the array value 410index value 410index

7 Array insertion: Solution public static void insertInOrder(int[] array, int num) { int insertionIndex = findInsertionIndex(array, num); if (insertionIndex < array.length) { for (int i = array.length - 1; i >= insertionIndex + 1; i--) { array[i] = array[i-1]; } array[insertionIndex] = num; } public static int findInsertionIndex(int[] array, int num) { for (int i = 0; i < array.length; i++) { if (num < array[i]) { return i; } return array.length; }

8 Rotating elements left value 410index value 410index

9 Rotating elements left: Solution public static void rotateLeft(int[] array) { int first = array[0]; for (int i = 0; i < array.length - 1; i++) { array[i] = array[i + 1]; } array[array.length - 1] = first; } What assumptions does this code make?

10 Exercise: Random elements Write a method named printRandomNumbers that accepts an array of integers as one parameter, and n, how many numbers to print, as a second parameter. The method will print out n random elements with repetition from the array. Write a method named printRandomNumbers that accepts an array of integers as one parameter, and n, how many numbers to print, as a second parameter. The method will print out n random elements without repetition from the array.

11 Solution: Random elements public static void printRandomNumbers(int[] numbers, int n) { Random rand = new Random(); int numNumbers = numbers.length; for (int i = 1; i <= n; i++) { int index = rand.nextInt(numNumbers); System.out.println(numbers[index]); // shift elements to the left for (int j = index; j < numNumbers - 1; j++) { numbers[j] = numbers[j + 1]; } numNumbers--; } } What happens to the array after this method finishes?  How could you preserve the contents of the array?

12 String traversal String s are like arrays of char s. We can write algorithms to traverse strings to compute information. What useful information might the following string have? “ADRARRADRRADGADARRRARARAADADDRDDRRDADAAD" 's''r''e''t' 'e''l' value index

13 String traversal: Example // string stores voters' votes // (R)EPUBLICAN, (D)EMOCRAT, (A)LEX, (G)IORGIO String votes = “ADRARRADRRADGADARRRARARAADADDRDDRRDADAAD“; int[] counts = new int[4]; // R -> 0, D -> 1, B -> 2, M -> 3 for (int i = 0; i < votes.length(); i++) { char c = votes.charAt(i); if (c == 'R') { counts[0]++; } else if (c == 'D') { counts[1]++; } else if (c == ‘A') { counts[2]++; } else { // c == ‘G' counts[3]++; } } System.out.println(Arrays.toString(counts)); Output: [13, 12, 14, 1]

14 Example data: Class attendance Consider the following dataset which represents attendance for three sections of five students: week1 week2 week3 week4 week5 week6 week7 week8 week student1 student2 student3 student4 student

15 Data transformations Sometimes we will use data in one form to compute new data in another form.  Often each transformation is stored into its own array. Transformations require a mapping between the original data and array indices.

16 Typical mappings Tally “If the input value is the integer i, do something with array index i.” Based on the position in the data “Store the i th value we read into index i.” Explicit mappings “Count occurrences of 'R' into index 0 and occurrences of 'D' into index 1.”

17 Exercise: Section attendance Write a program that reads the preceding section data and produces output such as the following: Section #1: Sections attended: [9, 6, 7, 4, 3] Student scores: [20, 20, 20, 16, 12] Student grades: [100.0, 100.0, 100.0, 80.0, 60.0] Section #2: Sections attended: [4, 6, 2, 2, 3] Student scores: [16, 20, 8, 8, 12] Student grades: [80.0, 100.0, 40.0, 40.0, 60.0] Section #3: Sections attended: [5, 4, 2, 5, 3] Student scores: [20, 16, 8, 20, 12] Student grades: [100.0, 80.0, 40.0, 100.0, 60.0]

18 Solution: Section attendance // This program reads data representing which students attended // which discussion sections and produces output of the students' // section attendance and scores. import java.util.*; public class Sections { public static void main(String[] args) { Scanner input = new Scanner(System.in); int section = 1; // used to count sections while(true) { System.out.println(“Enter attendance (blank to quit): ”); String line = input.nextLine(); // one section's data if(””.equals(line)) { break; } processSection(section, line); section++; }

19 Solution: Section attendance public static void processSection(int sectionNum, String line) { System.out.println("Section #" + sectionNum + ":"); int[] attended = new int[5]; // count sections attended for (int i = 0; i < line.length(); i++) { char c = line.charAt(i); if (c == '1') { // student attended section attended[i % 5]++; } System.out.println("Sections attended: " + Arrays.toString(attended));...

20 Solution: Section attendance // compute section score out of 20 points int[] scores = new int[5]; for (int i = 0; i < scores.length; i++) { scores[i] = Math.min(4 * attended[i], 20); } System.out.println("Student scores: " + Arrays.toString(scores)); // compute section grade out of 100% double[] grades = new double[5]; for (int i = 0; i < scores.length; i++) { grades[i] = * scores[i] / 20; } System.out.println("Student grades: " + Arrays.toString(grades)); System.out.println(); }