CS 121 – Intro to Programming:Java - Lecture 9 Announcements Two new Owl assignments up - they’re a bit more challenging. Programming assignment 5 is due.

Slides:



Advertisements
Similar presentations
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
Advertisements

 Variables  What are they?  Declaring and initializing variables  Common uses for variables  Variables you get “for free” in Processing ▪ Aka: Built-in.
1 Various Methods of Populating Arrays Randomly generated integers.
CS324e - Elements of Graphics and Visualization A Little Java A Little Python.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Sorting CMSC 201. Sorting In computer science, there is often more than one way to do something. Sorting is a good example of this!
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Variables Pepper. Variable A variable –box –holds a certain type of value –value inside the box can change Example –A = 2B+1 –Slope = change in y / change.
CSE 373: Data Structures and Algorithms
Arrays Chapter 6 Chapter 6.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner 1 2D Arrays, Sorting Lecture 16, Tue Mar
1 Arrays b An array is an ordered list of values An array of size N is indexed from zero to N-1 scores.
1 Data types, operations, and expressions Overview l Format of a Java Application l Primitive Data Types l Variable Declaration l Arithmetic Operations.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 2D Arrays, Sorting Lecture 23, Fri Mar
Unit 271 Searching and Sorting Linear Search Binary Search Selection Sort Insertion Sort Bubble (or Exchange) Sort Exercises.
Jan Art of Programming Yangjun Chen Dept. Business Computing University of Winnipeg.
A simple program: Area of a circle Problem statement: Given the radius of a circle, display its area Algorithm: 4. Display area To store values, we need.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Methods: a first introduction Two ways to make tea: 1: boil water; put teabag into cup;... etc : tell your younger brother: makeTea(1 milk, 0 sugar);
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Chapter 8 ARRAYS Continued
CS 121 – Intro to Programming:Java - Lecture 3 Announcements Course home page: Owl due Friday;
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
CS 121 – Intro to Programming:Java - Lecture 6 Announcements Fourth programming assignment now up, due in Friday. OWL assignments due as indicated MidTerm:
CS 121 – Intro to Programming:Java - Lecture 10 Announcements Two Owl assignments up, due 17th, 22nd Another up today, due 11/30 Next programming assignment.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
Week 2 - Monday.  What did we talk about last time?  Exceptions  Threads  OOP  Interfaces.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
Recursion A method is recursive if it makes a call to itself. A method is recursive if it makes a call to itself. For example: For example: public void.
Computer Science Searching & Sorting.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
Chapter 9 Searching and Sorting
CS100Lecture 101 Announcements Assignment P2 is due on Thursday Assignment P3 is handed out today Prelim on Monday the 19th. Coming soooooooooon.
Arrays The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with.
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.
CS 112 Department of Computer Science George Mason University CS 112 Department of Computer Science George Mason University Final Review Lecture 14.
CSE 373 Data Structures and Algorithms
CSE 373: Data Structures and Algorithms Lecture 6: Sorting 1.
CS 121 – Intro to Programming:Java - Lecture 7 Announcements A new Owl assignment is available. Programming assignment 4 is due on Thursday - hand in on.
CS 112 Introduction to Programming Arrays; Loop Patterns (break) Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
CS 121 – Intro to Programming:Java - Lecture 5 Announcements Course home page: Owl due Thursday at 11; another one up today. Third programming assignment.
Comparison-Based Sorting & Analysis Smt Genap
CS161 Topic #16 1 Today in CS161 Lecture #16 Prepare for the Final Reviewing all Topics this term Variables If Statements Loops (do while, while, for)
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 13 October 13, 2009.
CS 121 – Intro to Programming:Java - Lecture 8 Announcements Current Owl assignment is due Wednesday. Next Owl assignment - arrays I - will be up by tomorrow.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 13: Queues Announcements.
CS 106 Introduction to Computer Science I 10 / 29 / 2007 Instructor: Michael Eckmann.
Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Searching When we maintain a collection of data,
M180: Data Structures & Algorithms in Java Sorting Algorithms Arab Open University 1.
CS 121 – Intro to Programming:Java - Lecture 12 Announcements New Owl assignment up soon (today?) For this week: read Ch 8, sections 0 -3 Programming assignment.
CSCI 51 Introduction to Programming March 10, 2009.
1 Lecture # 2. * Introducing Programming with an Example * Identifiers, Variables, and Constants * Primitive Data Types * Byte, short, int, long, float,
CS 121 – Intro to Programming:Java - Lecture 4 Announcements Course home page: Owl due soon; another.
CS 121 – Intro to Programming:Java - Lecture 11 Announcements Inheritance Owl assignment due 11/30 at 11 am Programming assignment six due Friday 12/3.
Introduction to Arrays
CSC 222: Object-Oriented Programming
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Computer Programming Methodology Introduction to Java
Topic 14 Searching and Simple Sorts
Last Class We Covered Data representation Binary numbers ASCII values
CS 200 Primitives and Expressions
Topic 14 Searching and Simple Sorts
CSE 373: Data Structures & Algorithms
Introduction to Arrays
CS Week 2 Jim Williams, PhD.
Presentation transcript:

CS 121 – Intro to Programming:Java - Lecture 9 Announcements Two new Owl assignments up - they’re a bit more challenging. Programming assignment 5 is due this week. Visit office hours this week to strut your stuff (Friday, 10-12, or 230ish-5, in LGRT or come see me Friday afternoon). Late rules in effect - late programs reduced in value by half. Preregistration coming - what should you take? (191B? 187? Math 513?)

We’ve seen Java at two levels: the statement level - mechanisms for getting specific, often low-level jobs, done, e.g. assignment stmts, println, etc. the (class and) object level - mechanisms for modeling things (objects) according to an” Objects served by methods ” scheme: (objects: repositories of state) (methods: machinery for realizing behaviors) Now we’re back to a new and very important idea in statement-level thinking: arrays. Basically, arrays give us a new way to think about variables.

Think about: students in a classroom; seats on an airplane, rooms in a motel, positions in the deli line at a super-market. In all cases: Many variables required for representation There’s an indexing scheme for locating / identifying the variables in question Student 7 Seat 23B Room 201 Deli-line position 77 some indexing schemes are more natural than others some are two-dimensional

public class ArrayTest1{ public static void main(String[] args) { int[] firstArray = new int[10]; for(int j = 0; j < firstArray.length; j++) firstArray[j] = j*j; System.out.println("here they come"); for(int j = 0; j < firstArray.length; j++) System.out.println(firstArray[j]); } }

We’re going to write an application that rolls a pair of dice times and reports the results profile of the rolls (e.g. how many 2,3, etc came up. public class DiceTester{ public static void main(String[] args){ Dice d = new Dice(); d.multiToss(10000); d.showScoreboard(); } }

import java.util.Random; public class Dice{ Random r; int[] scoreboard = new int[13]; public Dice(){ r = new Random(); initializeScoreboard(); } public void initializeScoreboard(){ for(int j = 0; j < 13; j++) scoreboard[j] = 0;}

public int tossDie(){ return (1+r.nextInt(6)); } public int throwDice(){ return(tossDie() + tossDie()); } public void multiToss(int tossCount){ int score; for (int j = 0; j < tossCount; j++){ score = throwDice(); scoreboard[score]++; } }

public void showScoreboard(){ for(int j = 2; j < 13; j++) System.out.println("toss of " + j + " " + scoreboard[j]); }

Now suppose that we would like to see a bar graph of the contents of scoreboard. How should we proceed? This is big Tossing dice is a totally different activity from drawing a bar graph -- so we should capture this separation of functionality by creating a new class (a BarGraph class) that makes bar graphs when passed an integer array, Then we “marry” the two activites in a “master” class - here, a driver class.

public class DiceTester{ public static void main(String[] args){ Dice d = new Dice(); d.multiToss(10000); d.showScoreboard(); BarGraph b = new BarGraph(d.getScoreboard(),150,500,200); b.drawData(); } }

Problems how many bars? How wide? How far apart? how tall? -- That pesky scale factor -If the bars are to appear on a baseline at y = 150 in the drawing window, and the largest data item in the data is 1500, then the scaling factor is.1 = 1/10: -Every unit in the data array accounts for 1/10 of a pixel. -Yikes -Not as bad as it sounds: we’ll multiply every data element in the array by this scale factor, and then cast as an integer. -Example: if some other data item in the array is 955, then it will produce a rectangle of height (int) 95.5 = 95.

public class BarGraph{ int[] data; DrawingWindow d; float scaleFactor; // how tall should bars be? int base; // the floor of the bars int barWidth = 4; int spacer = 10; int windowWidth; Rect bar; public BarGraph(int[] data, int base, int width, int height){ d = new DrawingWindow(width,height,"graphing"); this.data = data; this.base = base; windowWidth = width; scaleFactor = (float)base / arrayMax(); }

public void drawData(){ int nwX,nwY,ht; for(int j =0; (j < data.length); j++){ nwX = (1 + j)*(barWidth + spacer); nwY = (int)(base - data[j]*scaleFactor); ht = (int)(data[j]*scaleFactor); bar = new Rect(nwX,nwY,barWidth,ht); bar.drawOn(d); } }

Palindromes are words, phrases, sentences that are the same forward and backward: Madam I’m Adam A man a plan a canal, Panama Live dirt up a side track carted is a putrid evil Able was I ere I saw Elba Remarkable was I ere I saw Elba, Kramer Doc note I dissent: a fast never prevents a fatness. I diet on cod. … And so forth [notice: we’re ignoring capitals, blanks, punctuation]

import element.*; public class PalTester{ public static void main(String[] args){ ConsoleWindow c = new ConsoleWindow(); c.out.println("enter a word or phrase"); String s = c.input.readLine(); Palindrome p = new Palindrome(s); System.out.println(" s a palindrome? " + p.palCheck()); } }

public class Palindrome{ String s; char[] letters; public Palindrome(String s){ letters = s.toCharArray(); } public boolean palCheck(){ int left, right; boolean ok = true; // innocent until proven guilty for (left = 0, right = letters.length-1; ok && (left < right); left++, right--) if (letters[left] != letters[right])ok = false; return ok; } }

Palindrome2 - handles upper/lower case, blanks.. public class Palindrome2{ String s; char[] letters; final char BLANK = ' '; public Palindrome2(String s){ letters = s.toLowerCase().toCharArray(); } Last statement 1)makes all letters lower case; then 2) turns the string into an array of chars.

public boolean palCheck(){ int left = 0; int right = letters.length-1;; boolean ok = true; // innocent until proven guilty while(ok && left < right){ if ( letters[left] == BLANK) left++; else if ( letters[right] == BLANK) right--; else if ( letters[left] == letters[right]){ left++; right--;} else ok = false; } return ok; }

Sorting Perhaps the single most important operation in computer science - includes alphabetizing, arranging by height, salary, years of service, and so forth. There’s a vast collection of sorting algorithms. We’ll talk about a particularly simple one. An upcoming Owl assignment discusses a fancy sorting technique embryonically.

static void selectionSort(int[] nums){ int min, temp; for(int index = 0; index < nums.length-1; index++){ min = index; for(int scan = index+1; scan < nums.length; scan++) if (nums[scan] < nums[min]) min = scan; temp = nums[min]; // swap smallest to index position nums[min] = nums[index]; nums[index] = temp; }