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

Similar documents
Functional Reactive Programming on ios

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

iphone Application Programming Lecture 3: Swift Part 2

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

Unit #2: Recursion, Induction, and Loop Invariants

C/C++ Programming Lecture 18 Name:

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

lecture 1 hello, swift cs : spring 2018

CS261 Data Structures. Ordered Array Dynamic Array Implementation

Data Structures and Algorithms for Engineers

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

ITP 342 Mobile App Dev. Strings

CS159. Nathan Sprague. November 9, 2015

COMP327 Mobile Computing Session:

Algorithm Design and Recursion. Search and Sort Algorithms

SWIFT BASICS

Collections. Fall, Prof. Massimiliano "Max" Pala

PLUX ios Application Programming Interface. Documentation - ios API

Introductory ios Development

2

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

Unit #3: Recursion, Induction, and Loop Invariants

From Bing.com on Nov

Divide and Conquer Sorting Algorithms and Noncomparison-based

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

Issue with Implementing PrimeSieve() in Go

Priority Queues (Heaps)

ITP 342 Mobile App Dev. Fundamentals

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

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

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

Porting Objective-C to Swift. Richard Ekle

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

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

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

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?

SORTING AND SEARCHING

COMP-520 GoLite Tutorial

Conditionals & Loops /

iphone Application Programming Lecture 3: Swift Part 2

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

Outline. Data Definitions and Templates Syntax and Semantics Defensive Programming

Analyzing Complexity of Lists

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

CMU /618 Exam 2 Practice Problems

COMP520 - GoLite Type Checking Specification

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

Introduction to Computers and Programming

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

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

Assignment II: Calculator Brain

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

! 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.

CS558 Programming Languages

EE 109 Lab 8a Conversion Experience

ITP 342 Mobile App Dev. Code

Collections & Memory Management. Lecture 2

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

ITEC2620 Introduction to Data Structures

Iterative Searching and Sorting

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

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

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

This is CS50. Harvard University Fall Quiz 0 Answer Key

Outline: Search and Recursion (Ch13)

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

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

Computational Geometry

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

CS1004: Intro to CS in Java, Spring 2005

Review (Basic Objective-C)

Arrays. Week 4. Assylbek Jumagaliyev

CSC324 Principles of Programming Languages

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.

Repetition Structures

COMP4128 Programming Challenges

Lecture 7. Memory in Python

Language Reference Manual

Functions & Variables !

Why embedded systems?

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

Sorting Algorithms. + Analysis of the Sorting Algorithms

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

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

The Go Programming Language. Frank Roberts

CS 1110: Introduction to Computing Using Python Loop Invariants

Understanding Undefined Behavior

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

Go Tutorial. Arjun Roy CSE 223B, Spring 2017

QuickSort. CIS 15 : Spring 2007

Search and Sorting Algorithms

REPETITION CONTROL STRUCTURE LOGO

CMSC 330: Organization of Programming Languages. Rust Basics

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

Recap: Functions as first-class values

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

Lecture 6 Sorting and Searching

Lecture 15 CIS 341: COMPILERS

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

CS 115 Exam 3, Spring 2014

Transcription:

When Swift met classic algorithms and data structures Caveats & Tips

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. 0 1 0 2 3 0 Example: 1 2 3 0 0 0

- 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, @1, @0, @2, @3, @0] mutablecopy]; [self movezero:nums]; // nums: [1, 2, 3, 0, 0, 0]

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]

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

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]

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]

Ready for the next one?

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

- 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)

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)

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

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)

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)

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

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)

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)

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

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

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

Thank you. Victor Wang email: wangshengjia01@gmail.com github: wangshengjia twitter: @wangshengjia