How to swap values of two variables without tmp? However, this naive algorithm is biased. 1

Similar documents
Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

1 class Lecture5 { 2 3 "Arrays" 4. Zheng-Liang Lu Java Programming 136 / 174

Cloning Arrays. In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example,

1 class Lecture6 { 2 3 "Methods" // keywords: 8 return. Zheng-Liang Lu Java Programming 186 / 244

1 class Lecture6 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 10 / Zheng-Liang Lu Java Programming 185 / 248

Variable Scope. The variable scope is the range of the program where the variable can be referenced.

Example. Password generator

ˆ Note that we often make a trade-off between time and space. ˆ Time complexity ˆ Space complexity. ˆ Unlike time, we can reuse memory.

Exercise: Sorting 1. ˆ Let A be any array. ˆ Write a program which outputs the sorted array of A (in ascending order).

Jump Statements. ˆ The break statement exits a for or while loop completely.

Arithmetic Compound Assignment Operators

The return Statement

1 class Lecture5 { 2 3 "Methods" / References 8 [1] Ch. 5 in YDL 9 [1] Ch. 20 in YDL 0 / Zheng-Liang Lu Java Programming 176 / 199

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Module 7: Arrays (Single Dimensional)

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Inf1-OP. Arrays 1. Timothy Hospedales, adapting earlier version by Perdita Stevens and Ewan Klein. January 30, School of Informatics

Inf1-OOP. Arrays. Many Variables of the Same Type. Arrays Introduction to Arrays Arrays in Java Shuffling a Deck Multidimensional Arrays Summary/Admin

Inf1-OOP. Arrays 1. Perdita Stevens, adapting earlier version by Ewan Klein. January 11, School of Informatics

Announcements. PS 4 is ready, due next Thursday, 9:00pm. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Opening Problem EXAMPLE. 1. Read one hundred numbers, 2. compute their average, and 3. find out how many numbers are above the average.

Arrays. Inf1-OP. Arrays. Many Variables of the Same Type. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein

Inf1-OP. Arrays 1. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. February 26, School of Informatics

! 52 playing cards in a deck. ! 5 thousand undergrads at Princeton. ! 1 million characters in a book. ! 10 million audio samples in an MP3 file.

1.4 Arrays. A Foundation for Programming. Arrays. Many Variables of the Same Type. This lecture. Store and manipulate huge quantities of data.

Chapter 7: Single-Dimensional Arrays. Declaring Array Variables. Creating Arrays. Declaring and Creating in One Step.

Debugging [continued]

Debugging [continued]

1.4 Arrays. A Foundation for Programming. Many Variables of the Same Type. Arrays. !!! any program you might want to write

CS 112 Introduction to Programming

COMPUTER SCIENCE. 4. Arrays. Section 1.4.

Chapter 6 Single-Dimensional Arrays. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved.

Lecture #8-10 Arrays

Lecture 6 Sorting and Searching

Pearson Education Limited Edinburgh Gate Harlow Essex CM20 2JE England and Associated Companies throughout the world

Example: Fibonacci Numbers

Recursion 1. Recursion is the process of defining something in terms of itself.

Method Invocation. Zheng-Liang Lu Java Programming 189 / 226

Nested Loops. A loop can be nested inside another loop.

Lecture 2. Two-Dimensional Arrays

Arrays. Introduction to OOP with Java. Lecture 06: Introduction to OOP with Java - AKF Sep AbuKhleiF - 1

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lab #10 Multi-dimensional Arrays

CS 223: Data Structures and Programming Techniques. Exam 2

Arrays and ArrayLists. Ananda Gunawardena

Object Oriented Programming. Java-Lecture 6 - Arrays

Chapter 7 Single-Dimensional Arrays

Example: Monte Carlo Simulation 1

ESC101 : Fundamental of Computing

Exercise. Write a program which allows the user to enter the math grades one by one (-1 to exit), and outputs a histogram.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved

Computer Science is...

Chapter 6 Arrays. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Lecture 5: Methods CS2301

CS61B Lecture #6: Arrays

Introduction to Programming (Java) 4/12

( &% class MyClass { }

CS115 Principles of Computer Science

Arrays. myints = new int[15];

1 class Lecture4 { 2 3 "Loops" / References 8 [1] Ch. 5 in YDL 9 / Zheng-Liang Lu Java Programming 125 / 207

Computer Science & Engineering 150A Problem Solving Using Computers

Exercise (Revisited)

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

CPSC 327, Spring 2019 Sample Answers to Homework #3

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II

CIS November 14, 2017

Public-Service Announcement

Arithmetic Compound Assignment Operators

COS 226 Algorithms and Data Structures Fall Midterm Solutions

The Warhol Language Reference Manual

Scope of this lecture

2/3/2018 CS313D: ADVANCED PROGRAMMING LANGUAGE. Lecture 3: C# language basics II. Lecture Contents. C# basics. Methods Arrays. Dr. Amal Khalifa, Spr17

1.4 Arrays. A Foundation for Programming. Many Variables of the Same Type. Arrays. Many Variables of the Same Type. Many Variables of the Same Type

Textbooks. Programming II Introduction to Imperative Programming. Declarative vs Imperative Languages. Java Software. No textbook is required.

Personal SE. Functions & Arrays

1 Short Answer (10 Points Each)

Exam 2. CSC 121 MW Class. Lecturer: Howard Rosenthal. April 26, 2017

Solutions Manual. Data Structures and Algorithms in Java, 5th edition International Student Version. M. T. Goodrich and R.

Structured programming

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

CIS 110 Introduction to Computer Programming Spring 2016 Midterm

Unit #2: Recursion, Induction, and Loop Invariants

Unit #3: Recursion, Induction, and Loop Invariants

One Dimension Arrays 1

ComS 207: Programming I Homework 7 Out: Wed. Oct 11, 2006 Due: Fri. Oct 20, 2006 (Online submission *ONLY*) Student Name: Recitation Section:

Functions Overview. Functions (aka procedures, subroutines, or methods) are the unit of code decomposition and abstraction

Methods. Bok, Jong Soon

CIS November 14, 2017

CIS 1068 Netflix Challenge New assignment posted soon Lab grades November 14, 2017

University of Waterloo CS240, Winter 2010 Assignment 2

CSC-140 Assignment 5

Q1 Q2 Q3 Q4 Q5 Total 1 * 7 1 * 5 20 * * Final marks Marks First Question

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

CS1150 Principles of Computer Science Arrays

It is a constructor and is called using the new statement, for example, MyStuff m = new MyStuff();

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Fundamentals of Programming. Lecture 12: C Structures, Unions, Bit Manipulations and Enumerations

Example. Generating random numbers. Write a program which generates 2 random integers and asks the user to answer the math expression.

Transcription:

Shuffling over array elements 1... 2 for (int i = 0; i < A.length; ++i) { 3 // choose j randomly 4 int j = (int) (Math.random() A.length); 5 // swap 6 int tmp = A[i]; 7 A[i] = A[j]; 8 A[j] = tmp; 9 } 10... How to swap values of two variables without tmp? However, this naive algorithm is biased. 1 1 See https://blog.codinghorror.com/the-danger-of-naivete/. Zheng-Liang Lu Java Programming 167 / 194

Exercise Deck of Cards Write a program which picks first 5 cards at random from a deck of 52 cards. 4 suits: Spade, Heart, Diamond, Club 13 ranks: 3,..., 10, J, Q, K, A, 2 Label 52 cards by 0, 1,, 51 Shuffle the numbers Deal the first 5 cards Zheng-Liang Lu Java Programming 168 / 194

1... 2 String[] suits = {"Spade", "Heart", "Diamond", "Club"}; 3 String[] ranks = {"3", "4", "5", "6", "7", 4 "8", "9", "10", "J", "Q", "K", 5 "A", "2"}; 6 7 int size = 52; 8 int[] deck = new int[size]; 9 for (int i = 0; i < deck.length; i++) 10 deck[i] = i; 11 12 // shuffle over deck; correct version 13 for (int i = 0; i < size 1; i++) { 14 int j = (int) (Math.random() (size i)) + i; 15 int z = deck[i]; 16 deck[i] = deck[j]; 17 deck[j] = z; 18 } 19 20 for (int i = 0; i < 5; i++) { 21 String suit = suits[deck[i] / 13]; 22 String rank = ranks[deck[i] % 13]; 23 System.out.printf("%8s%3s\n", suit, rank); 24 } 25... Zheng-Liang Lu Java Programming 169 / 194

Cloning Arrays In practice, one might duplicate an array for some reason. One could attempt to use the assignment statement (=), for example, 1... 2 T[] A = {...}; // assume A is an array 3 T[] B = A; // shallow copy; you don t have a new array 4... However, this is impossible to make two distinct arrays. Recall that the array variables are simply references to the arrays in the heap. Zheng-Liang Lu Java Programming 170 / 194

Moreover, all the reference variables share this property! For example, Zheng-Liang Lu Java Programming 171 / 194

Use a loop to copy individual elements one by one. 1... 2 int[] A = {2, 1, 3, 5, 10}; 3 int[] B = new int[a.length]; 4 // deep copy 5 for (int i = 0; i < A.length; ++i) { 6 B[i] = A[i]; 7 } 8... Alternatively, you may use the arraycopy method in the System class. 1... 2 int[] A = {2, 1, 3, 5, 10}; 3 int[] B = new int[a.length]; 4 System.arraycopy(A, 0, B, 0, A.length); 5... Zheng-Liang Lu Java Programming 172 / 194

for-each Loops 2 A for-each loop is designed to iterate over a collection of objects, such as arrays and other data structures, in strictly sequential fashion, from start to finish. For example, 1... 2 T[] A = {...}; // assume some T type array 3 for (T element: A) { 4 // body 5 } 6... Note that the type T should be compatible to the element type of A. 2 Beginning with JDK5. Now we have JDK9. Zheng-Liang Lu Java Programming 173 / 194

Example 1... 2 int[] A = {1, 2, 3}; 3 int sum = 0; 4 for (int i = 0; i < A.length; ++i) 5 sum += A[i]; 6... Not only is the syntax streamlined, but it also prevents boundary errors. 1... 2 int[] A = {1, 2, 3}; 3 int sum = 0; 4 for (int x: A) 5 sum += x; 6... Zheng-Liang Lu Java Programming 174 / 194

Short Introduction to Data Structures A data structure is a particular way of organizing data in a program so that it can be used efficiently. Data structures can implement one or more particular abstract data types (ADT), which specify the operations that can be performed on a data structure and the computational complexity of those operations. In comparison, a data structure is a concrete implementation of the specification provided by some ADT. Different kinds of data structures are suited to different kinds of applications, and some are highly specialized to specific tasks. 3 3 See http://bigocheatsheet.com/. Zheng-Liang Lu Java Programming 175 / 194

Common Operations on Data A specific data structure is chosen in one problem. Then the operations are implemented accordingly. The Arrays class contains useful methods for common array operations such as sorting and searching. For example, 1 import java.util.arrays; 2 3... 4 int[] A = {5, 2, 8}; 5 Arrays.sort(A); // sort the whole array 6 7 char[] B = { A, r, t, h, u, r }; 8 Arrays.sort(B, 1, 3); // sort the array partially 9... Zheng-Liang Lu Java Programming 176 / 194

Selection Sort 1... 2 // selection sort 3 for (int i = 0; i < A.length; i++) { 4 int k = i; // the position of min starting from i 5 for (int j = i + 1; j < A.length; j++) { 6 if (A[k] > A[j]) 7 k = j; 8 } 9 // swap(a[i], A[k]) 10 int tmp = A[k]; 11 A[k] = A[i]; 12 A[i] = tmp; 13 } 14... Time complexity: O(n 2 ) You can find more sorting algorithms. 4 4 See http://visualgo.net/. Zheng-Liang Lu Java Programming 177 / 194

Linear Search Write a program which searches for the index associated with the key. For convenience, assume that there is no duplicate key. The linear search approach compares the key with each element in the array sequentially. Zheng-Liang Lu Java Programming 178 / 194

1... 2 // assume A is an array 3 // linear search 4 for (int i = 0; i < A.length; i++) { 5 if (A[i] == key) { 6 System.out.printf("%3d", i); 7 } 8 } 9... Time complexity: O(n) Zheng-Liang Lu Java Programming 179 / 194

Alternative: Binary Search Time complexity: O(log n) Overall time complexity (sorting + searching): still O(log n)? Zheng-Liang Lu Java Programming 180 / 194

1... 2 int index = 1; // why? 3 int high = A.length 1, low = 0, mid; 4 while (high > low) { 5 mid = (high + low) / 2; 6 if (A[mid] == key) { 7 index = mid; 8 break; 9 } else if (A[mid] > key) 10 high = mid 1; 11 else 12 low = mid + 1; 13 } 14 15 if (index > 1) 16 System.out.printf("%d: %d\n", key, index); 17 else 18 System.out.printf("%d: does not exist\n", key); 19... Zheng-Liang Lu Java Programming 181 / 194

Beyond 1-Dimensional Arrays 2D or high-dimensional arrays are widely used. For example, a colorful image is represented by three 2D arrays (R, G, B). We can create a 2D T-type array with 4 rows and 3 columns as follows: 1... 2 int rowsize = 4; // row size 3 int colsize = 3; // column size 4 T[][] x = new T[rowSize][colSize]; 5... Zheng-Liang Lu Java Programming 182 / 194

Case (c) shows that we can create a 2D array by enumeration. Zheng-Liang Lu Java Programming 183 / 194

Reality Zheng-Liang Lu Java Programming 184 / 194

Example 5 1... 2 int[][] A = {{1, 2, 3}, {4, 5}, {6}}; 3 4 // conventional for loop 5 for (int i = 0; i < A.length; i++) { 6 for (int j = 0; j < A[i].length; j++) 7 System.out.printf("%2d", A[i][j]); 8 System.out.println(); 9 } 10 11 // for each loop 12 for (int[] B: A) { 13 for (int item: B) 14 System.out.printf("%2d", item); 15 System.out.println(); 16 } 17... 5 Thanks to a lively discussion on January 31, 2016. Zheng-Liang Lu Java Programming 185 / 194

Exercise: Matrix Multiplication Write a program which determines C = A B for the input matrices A m n and B n q for m, n, q N. You may use the formula c ij = n a ik b kj k=1 where a ik, i = 1, 2,..., m is a shorthand for A and b kj, j = 1, 2,..., q for B. Time complexity: O(n 3 ) (Why?) Zheng-Liang Lu Java Programming 186 / 194

1 class Lecture6 { 2 3 "Methods" 4 5 } 6 7 // keywords: 8 return Zheng-Liang Lu Java Programming 187 / 194

Methods 7 Methods can be used to define reusable code, and organize and simplify code. The idea of function originates from math, that is, y = f (x), where x is the input parameter 6 and y is the function value. In computer science, each input parameter should be declared with a specific type, and a function should be assigned with a return type. 6 Recall the multivariate functions. The input can be a vector, say the position vector (x, y, z). 7 Aka procedures and functions. Zheng-Liang Lu Java Programming 188 / 194

Example: max Zheng-Liang Lu Java Programming 189 / 194

1... 2 modifier returntype methodname(listofparameters) { 3 // method body 4 } 5... The modifier could be static and public (for now). The returntype could be primitive types and reference types. If the method does not return any value, then the return type is void. The listofparameters is the input of the method, separated by commas if there are multiple items. Note that a method could have no input. 8 The method name and the parameter list together are called the method signature. 9 8 For example, Math.random(). 9 Method overloading depends this. We will see it soon. Zheng-Liang Lu Java Programming 190 / 194

More Observations There are alternatives to the method max(): 1... 2 public static int max(int x, int y) { 3 if (x > y) { 4 return x; 5 } else { 6 return y; 7 } 8 } 9... 1... 2 public static int max(int x, int y) { 3 return x > y? x : y; 4 } 5... Zheng-Liang Lu Java Programming 191 / 194

All roads lead to Rome. Anonymous 但如你根本並無招式, 敵人如何來破你的招式? 風清揚, 笑傲江湖 第十回 傳劍 Zheng-Liang Lu Java Programming 192 / 194

The return Statement The return statement is the end point of the method. A callee is a method invoked by a caller. The callee returns to the caller if the callee completes all the statements (w/o a return statement, say main()); reaches a return statement; throws an exception (introduced later). As you can see, the return statement is not necessarily at the bottom of the method. 10 Once one defines the return type (except void), the method should guarantee to return a value or an object of that type. 10 Thanks to a lively discussion on November 22, 2015. Zheng-Liang Lu Java Programming 193 / 194

Bad Exampls 1... 2 public static int fun1() { 3 while (true); 4 return 0; // unreachable code 5 } 6 7 public static int fun2(int x) { 8 if (x > 0) { 9 return x; 10 } 11 // what if x < 0? 12 } 13... Zheng-Liang Lu Java Programming 194 / 194