When Swift met classic algorithms and data structures. Caveats & Tips

Size: px
Start display at page:

Download "When Swift met classic algorithms and data structures. Caveats & Tips"

Transcription

1 When Swift met classic algorithms and data structures Caveats & Tips

2 Given an array of numbers, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements. *Should not use extra space Example:

3 - Implementation in Objective-C - Time: O(n) - Space: O(1) - (void)movezeros:(nsmutablearray<nsnumber *> *)nums { NSUInteger nozero = 0; for (NSUInteger i=0; i<nums.count; i++) { if ([nums[i] integervalue]!= 0) { // swap id tmp = nums[nozero]; nums[nozero] = nums[i]; nums[i] = tmp; // move to next no zero position nozero ++; NSMutableArray *nums @0] mutablecopy]; [self movezero:nums]; // nums: [1, 2, 3, 0, 0, 0]

4 Now do we achieve O(1) space complexity - Implementation in Swift without using any extra space? func movezeros(_ nums: inout [Int]) { var nozero = 0 for i in 0..<nums.count nums.indices where { nums[i]!= 0 { (nums[i], let if i tmp!= = nozero nums[nozero])!= 0 {{ = (nums[nozero], nums[i]) nums[nozero] nozero let swap(&nums[i], += tmp 1 = = nums[nozero] nums[i] &nums[nozero]) nums[i] nums[nozero] = tmp = nums[i] nozero nums[i] += 1 = tmp nozero += 1 nozero += 1 var nums = [0, 1, 0, 2, 3, 0] movezeros(&nums) // nums: [1, 2, 3, 0, 0, 0]

5 func movezeros(_ nums: inout [Int]) { // Copied var nozero = In-Out 0 parameters: for i in 0..<nums.count where nums[i]!= 0 { (nums[i], copy-in nums[nozero]) copy-out = (nums[nozero], nums[i]) nozero += 1

6 How to deal with it? - NSMutableArray func movezeros(_ nums: NSMutableArray) - UnsafeMutableBufferPointer var nums = [0, 1, 0, 2, 3, 0] nums.withunsafemutablebufferpointer { (buffer) in var nozero = 0 for i in buffer.indices where buffer[i]!= 0 { (buffer[i], buffer[nozero]) = (buffer[nozero], buffer[i]) nozero += 1 // nums: [1, 2, 3, 0, 0, 0]

7 var nums = [1, 2, 3] for n in nums { For-in loop: Iterate nums.append(100 with indices + n) :) iterate with copied array print(nums) // nums: [1, 2, 3, 101, 102, 103]

8 Ready for the next one?

9 Given an array of strings, we want to group the anagrams together. cat tac gat tag gta eat Example: cat tac gat tag gta eat

10 - Implementation in Swift - Time: O(nlogn) -> O(n 2 ) - Space: O(n) func groupanagrams(_ words: [String]) -> [[String]] { var anagrams = [String: [String]]() for word in words { let sortedword = String(word.characters.sorted()) if anagrams[sortedword] == nil { anagrams[sortedword] = [] anagrams[sortedword]?.append(word) // copy the whole array everytime return Array(anagrams.values) return Array(anagrams.values)

11 func groupanagrams(_ words: [String]) -> [[String]] { var anagrams = [String: Copy [String]]() on Write for word in words { let could sortedword = be String(word.characters.sorted()) triggered if anagrams[sortedword] == nil { anagrams[sortedword] = [] accidentally anagrams[sortedword]?.append(word) // copy the whole array everytime return Array(anagrams.values)

12 How to deal with it? - Use reference semantic final class ReferenceBox<Value> { var value: Value init(_ value: Value) { self.value = value // anagrams[sortedword]?.value.append(word) // O(1) - It probably will be improved in the future Swift release

13 Follow up: what if we now want to do something more whenever a word contains some specific characters? func groupanagrams(_ words: [String]) [String], -> _ char: [[String]] Character) { -> [[String]] var { anagrams = [String: [String]]() for var word anagrams in words = [String: { [String]]() for let word sortedword in words { = String(word.characters.sorted()) if let anagrams[sortedword] sortedword = String(word.characters.sorted()) == nil { if word.characters.contains(char) anagrams[sortedword] = [] { // O(n) // do something anagrams[sortedword]?.append(word) if anagrams[sortedword] == nil { return Array(anagrams.values) anagrams[sortedword] = [] anagrams[sortedword]?.append(word) return Array(anagrams.values)

14 func binarysearch(_ s: String, _ t: Character) -> Bool { var start = s.startindex, end = s.index(before: s.endindex) while start <= end { let mid = s.index(s.startindex, offsetby: s.distance(from: s.startindex, to: start) + s.distance(from: start, to: end)/2) // start + (end - start) / 2 // O(n) instead of O(1) if s[mid] == t { return true else if s[mid] < t { start = s.index(after: mid) else { end = s.index(before: mid) s.distance(from: s.startindex, to: start) + s.distance(from: start, Use binary search return false // -> O(n*logn)

15 Without random access: - Calculate distance between two characters - Swap between two characters - Access nth character - Substring from x to y Linear Complexity

16 How to deal with it? - Convert into Array<Character> func binarysearch(_ s: [Character], _ t: Character) -> Bool { var start = 0, end = s.count - 1 while start <= end { let mid = start + (end - start)/2 if s[mid] == t { return true else if s[mid] < t { start = mid + 1 else { end = mid - 1 return false // -> O(logn)

17 Follow up: what if now we know that input will be only ASCII value? - Convert into NSString - Use counting sort O(nlogn) -> O(n) func groupanagrams(_ words: [String]) -> [[String]] { var anagrams = [String: [String]]() for word in words { let sortedword = String(word.characters.sorted()) let sortedword = sortbycounting(nsstring(string: word)) if anagrams[sortedword] == nil { anagrams[sortedword] = [] anagrams[sortedword]?.append(word) return Array(anagrams.values)

18 How we choose? Swift.String NSString/ String.utf16 Array <Character> Unicode Friendly How we choose? Memory Usage Random Access

19 Recap Don t need to worry, Value semantic. Copy on Write. Swift String. it ll just work

20 Where to go from here Open the playground and try something yourself. Follow the future release of Swift: Swift 4 this fall. Thinking in Swift when implement algorithm. More Swift features: generic, closure, extension, enum

21 Thank you. Victor Wang github: wangshengjia

Functional Reactive Programming on ios

Functional Reactive Programming on ios Functional Reactive Programming on ios Functional reactive programming introduction using ReactiveCocoa Ash Furrow This book is for sale at http://leanpub.com/iosfrp This version was published on 2016-05-28

More information

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall

Stanford CS193p. Developing Applications for ios. Fall CS193p. Fall Stanford Developing Applications for ios Today Mostly more Swift but some other stuff too Quick demo of mutating protocols String NSAttributedString Closures (and functions as types in general) Data Structures

More information

iphone Application Programming Lecture 3: Swift Part 2

iphone Application Programming Lecture 3: Swift Part 2 Lecture 3: Swift Part 2 Nur Al-huda Hamdan RWTH Aachen University Winter Semester 2015/2016 http://hci.rwth-aachen.de/iphone Review Type aliasing is useful! Escaping keywords could be useful! If you want

More information

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++

switch case Logic Syntax Basics Functionality Rules Nested switch switch case Comp Sci 1570 Introduction to C++ Comp Sci 1570 Introduction to C++ Outline 1 Outline 1 Outline 1 switch ( e x p r e s s i o n ) { case c o n s t a n t 1 : group of statements 1; break ; case c o n s t a n t 2 : group of statements 2;

More information

Unit #2: Recursion, Induction, and Loop Invariants

Unit #2: Recursion, Induction, and Loop Invariants Unit #2: Recursion, Induction, and Loop Invariants CPSC 221: Algorithms and Data Structures Will Evans 2012W1 Unit Outline Thinking Recursively Recursion Examples Analyzing Recursion: Induction and Recurrences

More information

C/C++ Programming Lecture 18 Name:

C/C++ Programming Lecture 18 Name: . The following is the textbook's code for a linear search on an unsorted array. //***************************************************************** // The searchlist function performs a linear search

More information

CS21: INTRODUCTION TO COMPUTER SCIENCE. Prof. Mathieson Fall 2017 Swarthmore College

CS21: INTRODUCTION TO COMPUTER SCIENCE. Prof. Mathieson Fall 2017 Swarthmore College CS21: INTRODUCTION TO COMPUTER SCIENCE Prof. Mathieson Fall 2017 Swarthmore College Outline Oct 25: Recap reading files String and List methods TDD: Top Down Design word_guesser.py Notes Lab 6 due Saturday

More information

lecture 1 hello, swift cs : spring 2018

lecture 1 hello, swift cs : spring 2018 lecture 1 hello, swift cs198-001 : spring 2018 today s lecture course logistics introduction to swift facilitators Nithi Narayanan Daniel Phiri Chris Zielinski Teaching Assistants Sarah Chin Marisa Wong

More information

CS261 Data Structures. Ordered Array Dynamic Array Implementation

CS261 Data Structures. Ordered Array Dynamic Array Implementation CS261 Data Structures Ordered Array Dynamic Array Implementation Recall Arrays Operations Add O(1+) for dynamic array Contains O(n) Remove O(n) What if our application needs to repeatedly call Contains

More information

Data Structures and Algorithms for Engineers

Data Structures and Algorithms for Engineers 0-630 Data Structures and Algorithms for Engineers David Vernon Carnegie Mellon University Africa vernon@cmu.edu www.vernon.eu Data Structures and Algorithms for Engineers 1 Carnegie Mellon University

More information

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return

Algorithm for siftdown(int currentposition) while true (infinite loop) do if the currentposition has NO children then return 0. How would we write the BinaryHeap siftdown function recursively? [0] 6 [1] [] 15 10 Name: template class BinaryHeap { private: int maxsize; int numitems; T * heap;... [3] [4] [5] [6] 114 0

More information

ITP 342 Mobile App Dev. Strings

ITP 342 Mobile App Dev. Strings ITP 342 Mobile App Dev Strings Strings You can include predefined String values within your code as string literals. A string literal is a sequence of characters surrounded by double quotation marks (").

More information

CS159. Nathan Sprague. November 9, 2015

CS159. Nathan Sprague. November 9, 2015 CS159 Nathan Sprague November 9, 2015 Recursive Definitions Merriam Websters definition of Ancestor: Ancestor One from whom a person is descended [...] Here is a recursive version: Ancestor One s parent.

More information

COMP327 Mobile Computing Session:

COMP327 Mobile Computing Session: COMP327 Mobile Computing Session: 2018-2019 Lecture Set 5a - + Comments on Lab Work & Assignments [ last updated: 22 October 2018 ] 1 In these Slides... We will cover... Additional Swift 4 features Any

More information

Algorithm Design and Recursion. Search and Sort Algorithms

Algorithm Design and Recursion. Search and Sort Algorithms Algorithm Design and Recursion Search and Sort Algorithms Objectives To understand the basic techniques for analyzing the efficiency of algorithms. To know what searching is and understand the algorithms

More information

SWIFT BASICS

SWIFT BASICS SWIFT BASICS jhkim@dit.ac.kr www.facebook.com/jhkim3217 2014. 7. 19 Reference Swift Guide, 2014 AppCode.com Swift Tutorial: A Quick Start, Ray Wenderlich background new programming language for ios, OS

More information

Collections. Fall, Prof. Massimiliano "Max" Pala

Collections. Fall, Prof. Massimiliano Max Pala Collections Fall, 2012 Prof. Massimiliano "Max" Pala pala@nyu.edu Overview Arrays Copy and Deep Copy Sets Dictionaries Examples Arrays Two Classes NSArray and NSMutableArray (subclass of NSArray) int main(int

More information

PLUX ios Application Programming Interface. Documentation - ios API

PLUX ios Application Programming Interface. Documentation - ios API PLUX ios Application Programming Interface Documentation - ios API 1. Introduction The PLUX ios Application Programming Interface brings to ios applications all the functionalities of PLUX devices. The

More information

Introductory ios Development

Introductory ios Development Introductory ios Development 152-164 Unit 2 - Basic Objective-C Syntax Quick Links & Text References Console Application Pages Running Console App Pages Basic Syntax Pages Variables & Types Pages Sequential

More information

2

2 Trees 1 2 Searching 3 Suppose we want to search for things in a list One possibility is to keep the items in a 'randomly' ordered list, so insertion is O(1), but then a search takes O(n) time Or, we could

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Unit #3: Recursion, Induction, and Loop Invariants

Unit #3: Recursion, Induction, and Loop Invariants Unit #3: Recursion, Induction, and Loop Invariants CPSC 221: Basic Algorithms and Data Structures Jan Manuch 2017S1: May June 2017 Unit Outline Thinking Recursively Recursion Examples Analyzing Recursion:

More information

From Bing.com on Nov

From Bing.com on Nov Functions From Bing.com on Nov 8. 017 We re going to look at some common patterns / algorithms for using an array The idea is that you first understand these Then you can apply them elsewhere And modify

More information

Divide and Conquer Sorting Algorithms and Noncomparison-based

Divide and Conquer Sorting Algorithms and Noncomparison-based Divide and Conquer Sorting Algorithms and Noncomparison-based Sorting Algorithms COMP1927 16x1 Sedgewick Chapters 7 and 8 Sedgewick Chapter 6.10, Chapter 10 DIVIDE AND CONQUER SORTING ALGORITHMS Step 1

More information

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators Objectives Chapter 4: Control Structures I (Selection) In this chapter, you will: Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Issue with Implementing PrimeSieve() in Go

Issue with Implementing PrimeSieve() in Go Slices 02-201 Issue with Implementing PrimeSieve() in Go func PrimeSieve(n int) [n+1]bool { var iscomposite [n+1]bool //ERROR! biggestprime := 2 for biggestprime < n for i:=2; i

More information

Priority Queues (Heaps)

Priority Queues (Heaps) Priority Queues (Heaps) 1 Priority Queues Many applications require that we process records with keys in order, but not necessarily in full sorted order. Often we collect a set of items and process the

More information

ITP 342 Mobile App Dev. Fundamentals

ITP 342 Mobile App Dev. Fundamentals ITP 342 Mobile App Dev Fundamentals Object-oriented Programming Object-oriented programming (OOP) is a programming paradigm based on the concept of objects. Classes A class can have attributes & actions

More information

ENGI 1020 Introduction to Computer Programming J U L Y 5, R E Z A S H A H I D I

ENGI 1020 Introduction to Computer Programming J U L Y 5, R E Z A S H A H I D I ENGI 1020 Introduction to Computer Programming J U L Y 5, 2 0 1 0 R E Z A S H A H I D I Passing by value Recall that it is possible to call functions with variable names different than the parameters in

More information

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d. Chapter 4: Control Structures I (Selection) In this chapter, you will: Objectives Learn about control structures Examine relational and logical operators Explore how to form and evaluate logical (Boolean)

More information

Stanford CS193p. Developing Applications for ios. Winter CS193p! Winter 2015

Stanford CS193p. Developing Applications for ios. Winter CS193p! Winter 2015 Stanford CS193p Developing Applications for ios Today More Swift & the Foundation Framework Optionals and enum Array, Dictionary, Range, et. al. Data Structures in Swift Methods Properties Initialization

More information

Porting Objective-C to Swift. Richard Ekle

Porting Objective-C to Swift. Richard Ekle Porting Objective-C to Swift Richard Ekle rick@ekle.org Why do we need this? 1.2 million apps in the ios App Store http://www.statista.com/statistics/276623/numberof-apps-available-in-leading-app-stores/

More information

iphone Application Programming Lab 3: Swift Types and Custom Operator + A02 discussion

iphone Application Programming Lab 3: Swift Types and Custom Operator + A02 discussion Lab 3: Swift Types and Custom Operator + A02 discussion Nur Al-huda Hamdan RWTH Aachen University Winter Semester 2015/2016 http://hci.rwth-aachen.de/iphone Learning Objectives Discuss A02 Another implementation

More information

Softwaretechnik. Program verification. Albert-Ludwigs-Universität Freiburg. June 28, Softwaretechnik June 28, / 24

Softwaretechnik. Program verification. Albert-Ludwigs-Universität Freiburg. June 28, Softwaretechnik June 28, / 24 Softwaretechnik Program verification Albert-Ludwigs-Universität Freiburg June 28, 2012 Softwaretechnik June 28, 2012 1 / 24 Road Map Program verification Automatic program verification Programs with loops

More information

Sorting. Sorting. 2501ICT/7421ICTNathan. René Hexel. School of Information and Communication Technology Griffith University.

Sorting. Sorting. 2501ICT/7421ICTNathan. René Hexel. School of Information and Communication Technology Griffith University. 2501ICT/7421ICTNathan School of Information and Communication Technology Griffith University Semester 1, 2012 Outline 1 Sort Algorithms Many Sort Algorithms Exist Simple, but inefficient Complex, but efficient

More information

Questions. Exams: no. Get by without own Mac? Why ios? ios vs Android restrictions. Selling in App store how hard to publish? Future of Objective-C?

Questions. Exams: no. Get by without own Mac? Why ios? ios vs Android restrictions. Selling in App store how hard to publish? Future of Objective-C? Questions Exams: no Get by without own Mac? Why ios? ios vs Android restrictions Selling in App store how hard to publish? Future of Objective-C? Grading: Lab/homework: 40%, project: 40%, individual report:

More information

SORTING AND SEARCHING

SORTING AND SEARCHING SORTING AND SEARCHING Today Last time we considered a simple approach to sorting a list of objects. This lecture will look at another approach to sorting. We will also consider how one searches through

More information

COMP-520 GoLite Tutorial

COMP-520 GoLite Tutorial COMP-520 GoLite Tutorial Alexander Krolik Sable Lab McGill University Winter 2019 Plan Target languages Language constructs, emphasis on special cases General execution semantics Declarations Types Statements

More information

Conditionals & Loops /

Conditionals & Loops / Conditionals & Loops 02-201 / 02-601 Conditionals If Statement if statements let you execute statements conditionally. true "then" part condition a > b false "else" part func max(a int, b int) int { var

More information

iphone Application Programming Lecture 3: Swift Part 2

iphone Application Programming Lecture 3: Swift Part 2 Lecture 3: Swift Part 2 Nur Al-huda Hamdan RWTH Aachen University Winter Semester 2015/2016 http://hci.rwth-aachen.de/iphone Properties Properties are available for classes, enums or structs Classified

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Outline. Data Definitions and Templates Syntax and Semantics Defensive Programming

Outline. Data Definitions and Templates Syntax and Semantics Defensive Programming Outline Data Definitions and Templates Syntax and Semantics Defensive Programming 1 Data Definitions Question 1: Are both of the following data definitions ok? ; A w-grade is either ; - num ; - posn ;

More information

Analyzing Complexity of Lists

Analyzing Complexity of Lists Analyzing Complexity of Lists Operation Sorted Array Sorted Linked List Unsorted Array Unsorted Linked List Search( L, x ) O(logn) O( n ) O( n ) O( n ) Insert( L, x ) O(logn) O( n ) + O( 1 ) O( 1 ) + O(

More information

6. Pointers, Structs, and Arrays. 1. Juli 2011

6. Pointers, Structs, and Arrays. 1. Juli 2011 1. Juli 2011 Einführung in die Programmierung Introduction to C/C++, Tobias Weinzierl page 1 of 50 Outline Recapitulation Pointers Dynamic Memory Allocation Structs Arrays Bubble Sort Strings Einführung

More information

CMU /618 Exam 2 Practice Problems

CMU /618 Exam 2 Practice Problems CMU 15-418/618 Exam 2 Practice Problems Miscellaneous Questions A. You are working on parallelizing a matrix-vector multiplication, and try creating a result vector for each thread (p). Your code then

More information

COMP520 - GoLite Type Checking Specification

COMP520 - GoLite Type Checking Specification COMP520 - GoLite Type Checking Specification Vincent Foley February 26, 2015 1 Declarations Declarations are the primary means of introducing new identifiers in the symbol table. In Go, top-level declarations

More information

SWIFT - CLOSURES. Global Functions Nested Functions Closure Expressions. Have a name. Capture values from enclosing function

SWIFT - CLOSURES. Global Functions Nested Functions Closure Expressions. Have a name. Capture values from enclosing function http://www.tutorialspoint.com/swift/swift_closures.htm SWIFT - CLOSURES Copyright tutorialspoint.com Closures in Swift are similar to that of self-contained functions organized as blocks and called anywhere

More information

Introduction to Computers and Programming

Introduction to Computers and Programming 16.070 Introduction to Computers and Programming April 11 Recitation 9 Spring 2002 Topics: Function Review Sorting and Searching Recursion Big O Notation Serial I/O Other Function Review f(x) = (x) f =

More information

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Abstract Data Types CS 234, Fall 2017 Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples Data Types Data is stored in a computer as a sequence of binary digits:

More information

ICS 311, Fall 2017, Problem Set 04, Topics 7 & 8

ICS 311, Fall 2017, Problem Set 04, Topics 7 & 8 ICS 311, Fall 2017, Problem Set 04, Topics 7 & 8 Due by midnight Tuesday 2/16. 35 points. #1. Peer Credit Assignment 1 Point Extra Credit for replying Please list the names of the other members of your

More information

Assignment II: Calculator Brain

Assignment II: Calculator Brain Assignment II: Calculator Brain Objective You will start this assignment by enhancing your Assignment 1 Calculator to include the changes made in lecture (i.e. CalculatorBrain, etc.). This is the last

More information

The University Of Michigan. EECS402 Lecture 07. Andrew M. Morgan. Sorting Arrays. Element Order Of Arrays

The University Of Michigan. EECS402 Lecture 07. Andrew M. Morgan. Sorting Arrays. Element Order Of Arrays The University Of Michigan Lecture 07 Andrew M. Morgan Sorting Arrays Element Order Of Arrays Arrays are called "random-access" data structures This is because any element can be accessed at any time Other

More information

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc. Searching & Sorting Week 11 Gaddis: 8, 19.6,19.8 CS 5301 Fall 2014 Jill Seaman 1 Definitions of Search and Sort! Search: find a given item in a list, return the position of the item, or -1 if not found.!

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

More information

EE 109 Lab 8a Conversion Experience

EE 109 Lab 8a Conversion Experience EE 109 Lab 8a Conversion Experience 1 Introduction In this lab you will write a small program to convert a string of digits representing a number in some other base (between 2 and 10) to decimal. The user

More information

ITP 342 Mobile App Dev. Code

ITP 342 Mobile App Dev. Code ITP 342 Mobile App Dev Code Comments Variables Arithmetic operators Format specifiers if - else Relational operators Logical operators Constants Outline 2 Comments For a single line comment, use // The

More information

Collections & Memory Management. Lecture 2

Collections & Memory Management. Lecture 2 Collections & Memory Management Lecture 2 Demo: Accessing Documentation Collections NSArray a list of objects in order [array objectatindex:0] [array objectatindex:3] Counting starts at zero, not one NSSet

More information

CS 31: Intro to Systems C Programming. Kevin Webb Swarthmore College September 13, 2018

CS 31: Intro to Systems C Programming. Kevin Webb Swarthmore College September 13, 2018 CS 31: Intro to Systems C Programming Kevin Webb Swarthmore College September 13, 2018 Reading Quiz Agenda Basics of C programming Comments, variables, print statements, loops, conditionals, etc. NOT the

More information

ITEC2620 Introduction to Data Structures

ITEC2620 Introduction to Data Structures ITEC2620 Introduction to Data Structures Lecture 5a Recursive Sorting Algorithms Overview Previous sorting algorithms were O(n 2 ) on average For 1 million records, that s 1 trillion operations slow! What

More information

Iterative Searching and Sorting

Iterative Searching and Sorting B B Chapter 1 Iterative Searching and Sorting Probably the most important algorithms in all of computer science are the searching and sorting algorithms. They are important because they are so common.

More information

2/5/2018. Learn Four More Kinds of C Statements. ECE 220: Computer Systems & Programming. C s if Statement Enables Conditional Execution

2/5/2018. Learn Four More Kinds of C Statements. ECE 220: Computer Systems & Programming. C s if Statement Enables Conditional Execution 2/5/218 University of Illinois at Urbana-Champaign Dept. of Electrical and Computer Engineering ECE 22: Computer Systems & Programming Control Constructs in C (Partially a Review) Learn Four More Kinds

More information

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion

Two Approaches to Algorithms An Example (1) Iteration (2) Recursion 2. Recursion Algorithm Two Approaches to Algorithms (1) Iteration It exploits while-loop, for-loop, repeat-until etc. Classical, conventional, and general approach (2) Recursion Self-function call It exploits

More information

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic.

Coding Workshop. Learning to Program with an Arduino. Lecture Notes. Programming Introduction Values Assignment Arithmetic. Coding Workshop Learning to Program with an Arduino Lecture Notes Table of Contents Programming ntroduction Values Assignment Arithmetic Control Tests f Blocks For Blocks Functions Arduino Main Functions

More information

This is CS50. Harvard University Fall Quiz 0 Answer Key

This is CS50. Harvard University Fall Quiz 0 Answer Key Quiz 0 Answer Key Answers other than the below may be possible. Binary Bulbs. 0. Bit- Sized Questions. 1. Because 0 is non- negative, we need to set aside one pattern of bits (000) for it, which leaves

More information

Outline: Search and Recursion (Ch13)

Outline: Search and Recursion (Ch13) Search and Recursion Michael Mandel Lecture 12 Methods in Computational Linguistics I The City University of New York, Graduate Center https://github.com/ling78100/lectureexamples/blob/master/lecture12final.ipynb

More information

What s New in Swift #WWDC18. Ted Kremenek, Languages & Runtimes Manager Slava Pestov, Swift Compiler Engineer

What s New in Swift #WWDC18. Ted Kremenek, Languages & Runtimes Manager Slava Pestov, Swift Compiler Engineer Session #WWDC18 What s New in Swift 401 Ted Kremenek, Languages & Runtimes Manager Slava Pestov, Swift Compiler Engineer 2018 Apple Inc. All rights reserved. Redistribution or public display not permitted

More information

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/

CS61C Machine Structures. Lecture 4 C Pointers and Arrays. 1/25/2006 John Wawrzynek. www-inst.eecs.berkeley.edu/~cs61c/ CS61C Machine Structures Lecture 4 C Pointers and Arrays 1/25/2006 John Wawrzynek (www.cs.berkeley.edu/~johnw) www-inst.eecs.berkeley.edu/~cs61c/ CS 61C L04 C Pointers (1) Common C Error There is a difference

More information

Computational Geometry

Computational Geometry Windowing queries Windowing Windowing queries Zoom in; re-center and zoom in; select by outlining Windowing Windowing queries Windowing Windowing queries Given a set of n axis-parallel line segments, preprocess

More information

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration)

while for do while ! set a counter variable to 0 ! increment it inside the loop (each iteration) Week 7: Advanced Loops while Loops in C++ (review) while (expression) may be a compound (a block: {s) Gaddis: 5.7-12 CS 1428 Fall 2015 Jill Seaman 1 for if expression is true, is executed, repeat equivalent

More information

CS1004: Intro to CS in Java, Spring 2005

CS1004: Intro to CS in Java, Spring 2005 CS1004: Intro to CS in Java, Spring 2005 Lecture #16: Java conditionals/loops, cont d. Janak J Parekh janak@cs.columbia.edu Administrivia Midterms returned now Weird distribution Mean: 35.4 ± 8.4 What

More information

Review (Basic Objective-C)

Review (Basic Objective-C) Classes Header.h (public) versus Implementation.m (private) @interface MyClass : MySuperclass... @end (only in header file) @interface MyClass()... @end (only in implementation file) @implementation...

More information

Arrays. Week 4. Assylbek Jumagaliyev

Arrays. Week 4. Assylbek Jumagaliyev Arrays Week 4 Assylbek Jumagaliyev a.jumagaliyev@iitu.kz Introduction Arrays Structures of related data items Static entity (same size throughout program) A few types Pointer-based arrays (C-like) Arrays

More information

CSC324 Principles of Programming Languages

CSC324 Principles of Programming Languages CSC324 Principles of Programming Languages http://mcs.utm.utoronto.ca/~324 November 14, 2018 Today Final chapter of the course! Types and type systems Haskell s type system Types Terminology Type: set

More information

Objective-C. Deck.m. Deck.h. Let s look at another class. This one represents a deck of cards. #import <Foundation/Foundation.h> #import "Deck.

Objective-C. Deck.m. Deck.h. Let s look at another class. This one represents a deck of cards. #import <Foundation/Foundation.h> #import Deck. Deck.h #import @interface Deck : NSObject @interface Deck() @implementation Deck Deck.m Let s look at another class. This one represents a deck of cards. Deck.h #import

More information

Repetition Structures

Repetition Structures Repetition Structures Chapter 5 Fall 2016, CSUS Introduction to Repetition Structures Chapter 5.1 1 Introduction to Repetition Structures A repetition structure causes a statement or set of statements

More information

COMP4128 Programming Challenges

COMP4128 Programming Challenges Multi- COMP4128 Programming Challenges School of Computer Science and Engineering UNSW Australia Table of Contents 2 Multi- 1 2 Multi- 3 3 Multi- Given two strings, a text T and a pattern P, find the first

More information

Lecture 7. Memory in Python

Lecture 7. Memory in Python Lecture 7 Memory in Python Announcements For This Lecture Readings Reread Chapter 3 No reading for Thursday Lab Work on Assignment Credit when submit A Nothing else to do Assignment Moved to Fri, Sep.

More information

Language Reference Manual

Language Reference Manual TAPE: A File Handling Language Language Reference Manual Tianhua Fang (tf2377) Alexander Sato (as4628) Priscilla Wang (pyw2102) Edwin Chan (cc3919) Programming Languages and Translators COMSW 4115 Fall

More information

Functions & Variables !

Functions & Variables ! Functions & Variables 02-201! What Is Programming? Programming is clearly, correctly telling a computer what to do. Programming Executable Program Algorithm: (English) instructions to the computer Programming

More information

Why embedded systems?

Why embedded systems? MSP430 Intro Why embedded systems? Big bang-for-the-buck by adding some intelligence to systems. Embedded Systems are ubiquitous. Embedded Systems more common as prices drop, and power decreases. Which

More information

CODING CHALLENGES M A. Prepare for ios interviews, E. test yourself against friends, and level up your skills. HACKING WITH SWIFT

CODING CHALLENGES M A. Prepare for ios interviews, E. test yourself against friends, and level up your skills. HACKING WITH SWIFT HACKING WITH SWIFT SWIFT CODING CHALLENGES REAL PROBLEMS, REAL SOLUTIONS Prepare for ios interviews, E L P test yourself against friends, M A S and level up your skills. E E Paul Hudson FR Chapter 1 Strings

More information

Sorting Algorithms. + Analysis of the Sorting Algorithms

Sorting Algorithms. + Analysis of the Sorting Algorithms Sorting Algorithms + Analysis of the Sorting Algorithms Insertion Sort What if first k elements of array are already sorted? 4, 7, 12, 5, 19, 16 We can shift the tail of the sorted elements list down and

More information

GaE Graphs Ain t Easy. Andrew Jones (adj2129) Kevin Zeng (ksz2109) Samara Nebel (srn2134)

GaE Graphs Ain t Easy. Andrew Jones (adj2129) Kevin Zeng (ksz2109) Samara Nebel (srn2134) GaE Graphs Ain t Easy Andrew Jones (adj2129) Kevin Zeng (ksz2109) Samara Nebel (srn2134) Introduction Graphs Complex data structure Ubiquitous and fundamental Goal: We want to provide the end user a streamlined

More information

COSC$4355/6355$ $Introduction$to$Ubiquitous$Computing$ Exercise$3$ September!17,!2015!

COSC$4355/6355$ $Introduction$to$Ubiquitous$Computing$ Exercise$3$ September!17,!2015! COSC4355/6355 IntroductiontoUbiquitousComputing Exercise3 September17,2015 Objective Inthisexercise,youwilllearnhowtowriteunittestsforyourapplicationandalsohowtouse NSUserDefaults.WewillalsoimplementObjectiveCCcategories*welearntlastweek.

More information

The Go Programming Language. Frank Roberts

The Go Programming Language. Frank Roberts The Go Programming Language Frank Roberts frank.roberts@uky.edu - C++ (1983), Java (1995), Python (1991): not modern - Java is 18 years old; how has computing changed in 10? - multi/many core - web programming

More information

CS 1110: Introduction to Computing Using Python Loop Invariants

CS 1110: Introduction to Computing Using Python Loop Invariants CS 1110: Introduction to Computing Using Python Lecture 21 Loop Invariants [Andersen, Gries, Lee, Marschner, Van Loan, White] Announcements Prelim 2 conflicts due by midnight tonight Lab 11 is out Due

More information

Understanding Undefined Behavior

Understanding Undefined Behavior Session Developer Tools #WWDC17 Understanding Undefined Behavior 407 Fred Riss, Clang Team Ryan Govostes, Security Engineering and Architecture Team Anna Zaks, Program Analysis Team 2017 Apple Inc. All

More information

Softwaretechnik. Program verification. Software Engineering Albert-Ludwigs-University Freiburg. June 30, 2011

Softwaretechnik. Program verification. Software Engineering Albert-Ludwigs-University Freiburg. June 30, 2011 Softwaretechnik Program verification Software Engineering Albert-Ludwigs-University Freiburg June 30, 2011 (Software Engineering) Softwaretechnik June 30, 2011 1 / 28 Road Map Program verification Automatic

More information

Go Tutorial. Arjun Roy CSE 223B, Spring 2017

Go Tutorial. Arjun Roy CSE 223B, Spring 2017 Go Tutorial Arjun Roy arroy@eng.ucsd.edu CSE 223B, Spring 2017 Administrative details TA Office Hours: EBU3B B250A, Tuesday 5-7PM TA Email: arroy@eng.ucsd.edu All labs due by 2359 PDT. Lab 1 due: 4/13/2017.

More information

QuickSort. CIS 15 : Spring 2007

QuickSort. CIS 15 : Spring 2007 QuickSort CIS 15 : Spring 2007 Functionalia TEA! HW 1 is DUE FRIDAY 23rd, 11:59 PM Do the BASIC Program First! Turn in Basic Program and Challenges Seperately Today: Binary Search Example QuickSort Submitting

More information

Search and Sorting Algorithms

Search and Sorting Algorithms Fundamentals of Programming (Python) Search and Sorting Algorithms Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

REPETITION CONTROL STRUCTURE LOGO

REPETITION CONTROL STRUCTURE LOGO CSC 128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING REPETITION CONTROL STRUCTURE 1 Contents 1 Introduction 2 for loop 3 while loop 4 do while loop 2 Introduction It is used when a statement or a block of

More information

CMSC 330: Organization of Programming Languages. Rust Basics

CMSC 330: Organization of Programming Languages. Rust Basics CMSC 330: Organization of Programming Languages Rust Basics CMSC330 Spring 2018 1 Organization It turns out that a lot of Rust has direct analogues in OCaml So we will introduce its elements with comparisons

More information

Announcements. Lab 11 is due tomorrow. Quiz 6 is on Monday. Ninja session tonight, 7-9pm. The final is in two weeks!

Announcements. Lab 11 is due tomorrow. Quiz 6 is on Monday. Ninja session tonight, 7-9pm. The final is in two weeks! Linked Lists Announcements Lab 11 is due tomorrow Quiz 6 is on Monday - Emphasis on sorting and recursion Ninja session tonight, 7-9pm The final is in two weeks! - Will cover class definitions and linked

More information

Recap: Functions as first-class values

Recap: Functions as first-class values Recap: Functions as first-class values Arguments, return values, bindings What are the benefits? Parameterized, similar functions (e.g. Testers) Creating, (Returning) Functions Iterator, Accumul, Reuse

More information

Arrays. COMS W1007 Introduction to Computer Science. Christopher Conway 10 June 2003

Arrays. COMS W1007 Introduction to Computer Science. Christopher Conway 10 June 2003 Arrays COMS W1007 Introduction to Computer Science Christopher Conway 10 June 2003 Arrays An array is a list of values. In Java, the components of an array can be of any type, basic or object. An array

More information

Lecture 6 Sorting and Searching

Lecture 6 Sorting and Searching Lecture 6 Sorting and Searching Sorting takes an unordered collection and makes it an ordered one. 1 2 3 4 5 6 77 42 35 12 101 5 1 2 3 4 5 6 5 12 35 42 77 101 There are many algorithms for sorting a list

More information

Lecture 15 CIS 341: COMPILERS

Lecture 15 CIS 341: COMPILERS Lecture 15 CIS 341: COMPILERS Announcements HW4: OAT v. 1.0 Parsing & basic code generation Due: March 28 th No lecture on Thursday, March 22 Dr. Z will be away Zdancewic CIS 341: Compilers 2 Adding Integers

More information

Exam 1. CSC 121 Spring Lecturer: Howard Rosenthal. March 1, 2017

Exam 1. CSC 121 Spring Lecturer: Howard Rosenthal. March 1, 2017 Exam 1. CSC 121 Spring 2017 Lecturer: Howard Rosenthal March 1, 2017 Your Name: Key 1. Fill in the following table for the 8 primitive data types. Spell the types exactly correctly. (16 points total) Data

More information

CS 115 Exam 3, Spring 2014

CS 115 Exam 3, Spring 2014 Your name: Rules You may use one handwritten 8.5 x 11 cheat sheet (front and back). This is the only resource you may consult during this exam. Explain/show work if you want to receive partial credit for

More information