diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..026eb20 Binary files /dev/null and b/.DS_Store differ diff --git a/20160124 Homework.playground/Contents.swift b/20160124 Homework.playground/Contents.swift new file mode 100644 index 0000000..d53efd4 --- /dev/null +++ b/20160124 Homework.playground/Contents.swift @@ -0,0 +1,9 @@ +//: Playground - noun: a place where people can play + +import UIKit + +var str = "Hello, playground" + +/* + +/* diff --git a/20160124 Homework.playground/contents.xcplayground b/20160124 Homework.playground/contents.xcplayground new file mode 100644 index 0000000..5da2641 --- /dev/null +++ b/20160124 Homework.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/20160124 Homework.playground/playground.xcworkspace/contents.xcworkspacedata b/20160124 Homework.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/20160124 Homework.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/20160124 Homework.playground/timeline.xctimeline b/20160124 Homework.playground/timeline.xctimeline new file mode 100644 index 0000000..bf468af --- /dev/null +++ b/20160124 Homework.playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + + diff --git a/20160124-homework-recursion.playground/Contents.swift b/20160124-homework-recursion.playground/Contents.swift new file mode 100644 index 0000000..c7778f6 --- /dev/null +++ b/20160124-homework-recursion.playground/Contents.swift @@ -0,0 +1,147 @@ +// Exercises from: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3lQZQiFUOxZKBwsY/edit# + +import UIKit +import Foundation + +/* 1) Write an iterative (not recursive) fibonacci function that calculates the nth fibonacci number. How does its performance compare with the non-memoized recursive one (see Appendix A below), based on the number of iterations that Swift says it takes in the right margin? + +Note: In the Fibonacci sequence, each number is the sum of the two previous numbers. +ie: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] */ + +//Appendix A: Recursive Fibonacci from class (non-memoized) +func fib1(n: Int) -> Int { + if (n == 0 || n == 1) { + return 1 + } + return fib1(n - 1) + fib1(n - 2) +} +print(fib1(10)) +(0...5).map { i in fib1(i) } // create map + +// Answer: this non recursive method is waaay faster. + +var fibNo = 1 +var index = 0 + +func fib2(numbers: Int) -> Int { + +for number in 1...numbers { // loop through numbers 1...10 + print("index \(number): \(fibNo)") + let temp = fibNo + index + index = fibNo + fibNo = temp + } +return fibNo +} + + + +print(fib2(10)) // Note: this is actually returning the 11th fib no because the function is starting with a 0 indexed number + +/* 2) The engineers have been hard at work on the clumsy robot project, and have released a new API with a new tryStep method (see Appendix B). Now it returns an Int, which is -1 if the robot fell down a step, 0 if the robot stayed on the same step, or 1 if the robot went to the next step. Write a new stepUp method using this new tryStep method that works the same as before. */ + +// Original Program: +/* +var stepNum = 0 +func tryStep() -> Bool { + let success = Int(arc4random_uniform(2)) > 0 // generate rando number + if (success) { + stepNum++ + print("Yay! \(stepNum)") + } else { + stepNum--; + print("Ow! \(stepNum)") + } + return success +} + +func stepUp() { + if tryStep() { + // We’re done! + return + } + // Now we’re two steps below where we want to be :-( + stepUp() + stepUp() +} +print(stepUp()) +*/ + +// Appendix B: +var steppNum = 0 + +func tryStepp() -> Int { + let stepCount = Int(arc4random_uniform(3)) - 1 // generate rando number + steppNum += stepCount; + + switch(stepCount) { + case -1: print("Ouch \(steppNum)") + case 1: print("Yay \(steppNum)") + default: print("Beep \(steppNum)") + } + return stepCount +} + +//// My code: +//func steppUp(var stepsTaken: Int = 0) { +// stepsTaken += tryStepp() +// if stepsTaken == 1 { +// // we're done! +// return +// } +// steppUp(stepsTaken) +//} +//steppUp() + +// Cameron's Code: +func stepUp() { + switch tryStepp() { + case 1: + return + case -1: + stepUp() + stepUp() + default: + stepUp() + } +} +stepUp() + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/20160124-homework-recursion.playground/contents.xcplayground b/20160124-homework-recursion.playground/contents.xcplayground new file mode 100644 index 0000000..5da2641 --- /dev/null +++ b/20160124-homework-recursion.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/20160124-homework-recursion.playground/playground.xcworkspace/contents.xcworkspacedata b/20160124-homework-recursion.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/20160124-homework-recursion.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/20160124-homework-recursion.playground/timeline.xctimeline b/20160124-homework-recursion.playground/timeline.xctimeline new file mode 100644 index 0000000..bf468af --- /dev/null +++ b/20160124-homework-recursion.playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + + diff --git a/20160128-homework-merge-sort.playground/Contents.swift b/20160128-homework-merge-sort.playground/Contents.swift new file mode 100644 index 0000000..d823335 --- /dev/null +++ b/20160128-homework-merge-sort.playground/Contents.swift @@ -0,0 +1,159 @@ +//: Playground - noun: a place where people can play + +import Foundation + +var str = "Hello, playground" + +/* + +Use recursion to implement Insertion Sort in Swift: + +Requirements: +You may not use loops +Your implementations should be in-place (try not to create additional arrays) +You should implement and use additional helper functions + +Tips: +Add additional parameters to your helper functions to pass information between recursive calls +You can use the swap function to exchange two values in a mutable (var) array: + +var array = [1, 2] +swap(&array[0], &array[1]) +array // [2, 1] + +// Insertion Sort from Stack Overflow: +public static int[] RecursiveInsertionSort(int[] array, int n) { +int i; +if (n > 1) +RecursiveInsertionSort(array, n - 1); +else { +int k = array[n]; +i = n - 1; +while (i >= 0 & & array[i] > k) { +array[i + 1] = array[i]; +i = i - 1; +} +array[i + 1] = k; +} +return array; +} +*/ + +// regular insertion sort: +func exchange(inout data: [T], i:Int, j:Int) { + let temp:T = data[i] + data[i] = data[j] + data[j] = temp +} + +func insertionSort(var unsortedArray:Array)->Array{ + if(unsortedArray.count<2) { + return unsortedArray + } + for var j = 1; j < unsortedArray.count; j++ { + var i = j + while i>0 && unsortedArray[i-1]>unsortedArray[i] { + exchange(&unsortedArray, i: i-1, j: i) + i--; + } + } + return unsortedArray; +} +insertionSort([3, 4, 5, 1, 2]) + +// Cameron's notes for homework: +func printAllElements(values: [Int]) { + for value in values { + print(value) + } +} + +func printAllElementsRecursive(values: [Int]) { + printElementsHelper(values, index: 0) +} + +func printElementsHelper(values: [Int], index: Int) { + if index < values.count { + print(values[index]) + printElementsHelper(values, index: index + 1) + } +} + +func setValue(inout array: [Int], value: Int, atIndex index: Int) { + array[index] = value +} + +var values = [10, 20, 30] +printAllElements(values) + +setValue(&values, value: 100, atIndex: 1) +values + + + +func reverse(inout array: [Int]) { + for i in 0.. = ["crapple", "fandroid", "m$"] + +func moderate(message: String) -> Bool { + + let words = (message as NSString).componentsSeparatedByString(" ") + for word in words { + if blacklist.contains(word.lowercaseString) { + return false + } + } + return true +} +moderate("I would never use a crApple product!") +moderate("something else") + +// 3) + +protocol PhoneBookProtocol { + mutating func addPerson(name: String, phoneNumber: String) + mutating func removePerson(name: String) + mutating func importFrom(oldPhonebook: [(String, String)]) + func findPerson(name: String) -> String? // Return phone # +} + +class PhoneBook: PhoneBookProtocol { + var storage: [String : String] = [:] // @{} + //var storage = Dictionary() + func addPerson(name: String, phoneNumber: String) { + storage[name] = phoneNumber + } + + func removePerson(name: String) { + storage.removeValueForKey(name) + } + + func findPerson(name: String) -> String? { + return storage[name] + } + + func importFrom(oldPhonebook: [(String, String)]) { + for entry in oldPhonebook { + addPerson(entry.0, phoneNumber: entry.1) + } + } +} + + +let oldData = [("Caleb", "501-555-1234"), ("Mike", "212-555-4321"), ("Jenny", "345-867-5309")] + +let phoneBook = PhoneBook() +phoneBook.importFrom(oldData) + +phoneBook.findPerson("Jenny") + diff --git a/20160128-homework-merge-sort.playground/contents.xcplayground b/20160128-homework-merge-sort.playground/contents.xcplayground new file mode 100644 index 0000000..5da2641 --- /dev/null +++ b/20160128-homework-merge-sort.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/20160128-homework-merge-sort.playground/playground.xcworkspace/contents.xcworkspacedata b/20160128-homework-merge-sort.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/20160128-homework-merge-sort.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/20160128-homework-merge-sort.playground/timeline.xctimeline b/20160128-homework-merge-sort.playground/timeline.xctimeline new file mode 100644 index 0000000..bf468af --- /dev/null +++ b/20160128-homework-merge-sort.playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + + diff --git a/20160130-quicksort-stacks-queues-homework.playground/Contents.swift b/20160130-quicksort-stacks-queues-homework.playground/Contents.swift new file mode 100644 index 0000000..a71763d --- /dev/null +++ b/20160130-quicksort-stacks-queues-homework.playground/Contents.swift @@ -0,0 +1,168 @@ +//: Playground - noun: a place where people can play + +import Foundation + +/* +1) Without looking at the Big O Cheatsheet, write down the average time and space complexity for bubble sort, insertion sort, selection sort, mergesort, and quicksort. + +Bubble Sort: O(n^2) +Insertion Sort: O(n^2) +Selection Sort: O(n^2) +Merge Sort: O(n log n) +Quick Sort: O(n log n) + +2) What is the advantage of partitioning quicksort in place? + +you don't need to take up additional memory when creating additional storage arrays (like in mergesort) + +3) Without looking, implement quicksort. + +var randomNumbers = [42, 12, 88, 62, 63, 56, 1, 77, 88, 97, 97, 20, 45, 91, 62, 2, 15, 31, 59, 5] + +func partition(v: [Int], left: Int, right: Int) -> [Int] { + var i = left + for j in (left + 1)..(right + 1) { + if v[j] < v[left] { + i += 1 + (v[i], v[j]) = (v[j], v[i]) + } + } + (v[i], v[left]) = (v[left], v[i]) + return i +} + +func quicksort(v: Int[], left: Int, right: Int) { + if right > left { + let pivotIndex = partition(v, left, right) + quicksort(v, left, pivotIndex - 1) + quicksort(v, pivotIndex + 1, right) + } +} + +quicksort(randomNumbers, left: 0, right: randomNumbers.count-1) + +4) Write a function to generate an array of random numbers bounded between 1..<10,000 of size 10,000. + +Int(arc4random_uniform(UInt32(10000))) +*/ + +func makeList(n: Int, max: Int) -> [Int] { + var result: [Int] = [] // create storage variable + for _ in 0..())) { + let start = NSDate() + block() + let end = NSDate() + print(end.timeIntervalSinceDate(start)) +} + +//run your function/code inside the block below +profile({ + +}) + +/* +6) Describe the algorithmic difference between mergesort and quicksort. Where does the sorting happen? As the recursive calls are being pushed onto the stack or as they are being popped off? + +with Merge sort, the sorting happens in subarrays that are sorted and merged together at the end. Quicksort happens in the main array. + +7) Given an array of strings containing “[“,”]”,”{“,”}”,”(“,”)”. Output whether or not the parentheses are balanced. +Good examples: () [] () ([]()[]) +Bad examples: ( ( ] ([)] + +func isBalanced(paren: [String]) -> Bool { + +} +*/ + +// add first item to array +// add second item to array +// if second item matches first item, remove both items +// else +// add third item to array +// if third item matches second/first item, remove both items + +var holdingStack: [String] = [] + + +func keyCheck(var holdingStack: [String], i: String) { + + if (holdingStack[0] == "(" && i == ")") { + holdingStack.removeAtIndex(0) + } + if (holdingStack[0] == "{" && i == "}") { + holdingStack.removeAtIndex(0) + } + if (holdingStack[0] == "[" && i == "]") { + holdingStack.removeAtIndex(0) + } else { + print("holding stack: \(holdingStack)") + print("i: \(i)") + } +} + +func isBalanced(var paren: [String]) -> Bool { + + if paren.count % 2 != 0 { + return false + } + for i in paren { + holdingStack.insert(paren[0], atIndex: 0) + paren.removeFirst() + keyCheck(holdingStack, i: i) + } + return true +} + +var brackets = ["(", ")", "{", "}", "[", "]"] +isBalanced(brackets) + + + + + + + +// make a STACK! + +struct Stack { + var items:[T] + + //push + mutating func push(element:T) { + items.append(element) + } + + //pop + mutating func pop() -> T? { + if items.count == 0 { return nil} + return items.removeLast() // remove from end + } + + //peek + func peek() -> T? { + return items.last + } + + //size + func size() -> Int { + return items.count + } +} + + + + diff --git a/20160130-quicksort-stacks-queues-homework.playground/contents.xcplayground b/20160130-quicksort-stacks-queues-homework.playground/contents.xcplayground new file mode 100644 index 0000000..5da2641 --- /dev/null +++ b/20160130-quicksort-stacks-queues-homework.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/20160130-quicksort-stacks-queues-homework.playground/playground.xcworkspace/contents.xcworkspacedata b/20160130-quicksort-stacks-queues-homework.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/20160130-quicksort-stacks-queues-homework.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/20160130-quicksort-stacks-queues-homework.playground/timeline.xctimeline b/20160130-quicksort-stacks-queues-homework.playground/timeline.xctimeline new file mode 100644 index 0000000..bf468af --- /dev/null +++ b/20160130-quicksort-stacks-queues-homework.playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + + diff --git a/20160204-trees-homework.playground/Contents.swift b/20160204-trees-homework.playground/Contents.swift new file mode 100644 index 0000000..9675b7b --- /dev/null +++ b/20160204-trees-homework.playground/Contents.swift @@ -0,0 +1,48 @@ +// trees homework: https://docs.google.com/document/d/1te7mLS06MEYwETFSbVBqMrIzJ43GTEo5uuCiWdB0fyE/edit#heading=h.za36ai6n5fth + +import Foundation + +/* Build and return the binary tree representation of the expression. The following characters should be treated as operators: + - * / + + You may use additional data structures—as suggested in the link above, you will at least want to use a stack. This can be done using the Array type in Swift. + +Test your tree by checking to see if the string returned by postorderDescription is equal to the input string. */ + +// Binary tree implementation: + +class Node { + let value: T + var left: Node? + var right: Node? + init(value: T) { + self.value = value + } +} + +extension Node: CustomStringConvertible { + var description: String { + return "\(value)" + } + var postorderDescription: String { + let lt = left?.postorderDescription ?? "" + let rt = right?.postorderDescription ?? "" + return lt + rt + description + } +} + +// template code: + +func parseExpression(input: String) -> Node? { + // Your implementation here! + + let operators: Set = ["+", "-", "*", "/"] + var stack: [Node] = [] + for character in input.characters { + // Do something for each character + + } + return nil +} + +let sampleImput = "ab+cde+**" +parseExpression(sampleImput) diff --git a/20160204-trees-homework.playground/contents.xcplayground b/20160204-trees-homework.playground/contents.xcplayground new file mode 100644 index 0000000..5da2641 --- /dev/null +++ b/20160204-trees-homework.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/20160204-trees-homework.playground/playground.xcworkspace/contents.xcworkspacedata b/20160204-trees-homework.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/20160204-trees-homework.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/20160204-trees-homework.playground/timeline.xctimeline b/20160204-trees-homework.playground/timeline.xctimeline new file mode 100644 index 0000000..bf468af --- /dev/null +++ b/20160204-trees-homework.playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + + diff --git a/HWfrom1-09-16(SwiftIntro).playground/Contents.swift b/HWfrom1-09-16(SwiftIntro).playground/Contents.swift index 488e9ed..71340ab 100644 --- a/HWfrom1-09-16(SwiftIntro).playground/Contents.swift +++ b/HWfrom1-09-16(SwiftIntro).playground/Contents.swift @@ -5,19 +5,74 @@ import UIKit var str = "Hello, playground" /* - Use the link here to get the questions. Then code your solutions below. If it does not require code, just write your answer in comments. - https://docs.google.com/document/d/1DQ2aCJ_yUZtazzCfb0PaS81bg61V2ZOSxpABh981xSo/edit +*/ -1) +// * VERY EXCITING DISCOVERY * +// Here are some other helpful functions that can be performed on two sets: +let array1 = ["a", "b", "c"] +let array2 = ["a", "b", "d"] -2) +let set1 = Set(array1) // create set +let set2 = Set(array2) -3) +set1.union(set2) // {"a", "b", "c", "d"} +set1.intersect(set2) // {"a", "b"} +set1.subtract(set2) // {"c"} +set1.exclusiveOr(set2) // {"c", "d"} -4) -*/ +// 1) Given an integer N, there is a list of size N-1 that is missing one number from 1 - N(inclusive). Find that number. +func findMissingValue(list1: [Int], list2: [Int]) -> Int? { + let set1 = Set(list1) // create set, remove duplicates + let set2 = Set(list2) + let matches = set1.exclusiveOr(set2) // gather items that aren't in both arrays + return matches.minElement() //return the smallest one +} +findMissingValue([1, 2, 4, 5, 6, 7, ], list2: [1, 2, 3, 4, 5, 6, 7]) + + + +// 2) Given a list of size N containing numbers 1 - N (inclusive). return true if there are duplicates, false if not. +func hasDuplicates(arr: [Int]) -> Bool { + + let noDoublesSet = Set(arr) // convert array into a set (this removes duplicates) + if noDoublesSet.count != arr.count { + return true + } + return false +} +hasDuplicates([5, 3, 2, 1, 1]) // test it! + + + +// 3) Given two lists, find the smallest value that exists in both lists. +// create two sets and intersect them to get common elements. +func smallestCommonNum(list1: [Int], list2: [Int]) -> Int? { + let set1 = Set(list1) // create set, remove duplicates + let set2 = Set(list2) + return set1.intersect(set2).minElement() // intersect() pulls common numbers from two sets! +} +smallestCommonNum([1, 2, 5, 9], list2: [9, 20, 5]) // test it + + + +// 4) Check to see if an integer is a palindrome don’t use casting. +// divide each digit and rebuild number again then compare with original: +func isPalindrome(var num: Int) -> Bool { + let originalNum = num + var finalNum = 0 + + while(num > 0) { + finalNum *= 10 + finalNum += num % 10 + num /= 10 + } + return finalNum == originalNum // return true if is palindrome +} +isPalindrome(134543) // test it + + diff --git a/HWfrom1-10-016(BigO).playground/Contents.swift b/HWfrom1-10-016(BigO).playground/Contents.swift index 2040d38..dd644f9 100644 --- a/HWfrom1-10-016(BigO).playground/Contents.swift +++ b/HWfrom1-10-016(BigO).playground/Contents.swift @@ -11,20 +11,240 @@ Use the link here to get the questions. Then code your solutions below. If it https://docs.google.com/document/d/1aF1imJUVahCSJAuN1OEm5lQXwpSFaAmVmAETKMM6PLQ/edit#heading=h.za36ai6n5fth -1) +1) With my new top of the line XJ452 supercomputer, memory access takes 1 picosecond, math operations take 3 picoseconds, and storing data in memory takes 10 picoseconds. My friend wrote a filter that makes a pixel more awesome, and takes 200 picoseconds to run. -2) +a) How long would my computer take to execute the following code if the input image is 1000px wide by 2000px tall? What if it’s n by m? -3) +Pixel **awesomeFilter(Pixel image[][], int width, int height) { +for (int i = 0; i < width; i++) { +for (int j = 0; j < height; j++) { +[image[i][j] makeMoreAwesome]; + } +} +return image; // access memory = +1 +} -4) +Notes: -5) +// memory access = 1 +// math operation = 3 +// storing data = 10 +// run program = 200 -6) +Pixel **awesomeFilter(Pixel image[][], int width, int height) { +// do we access memory when declaring function parameters? -7) +for (int i = 0; i < width; i++) { +go through the line -> int i = 0 (store data +10); i (memory acess +1) < (math operation +3) width (memory +1); i (memory +1) ++ (math +3). +total for this line of code = 10 + 1 + 3 + 1 + 1 + 3 = 19 picoseconds +N = 1000 +1000 * 19 = 19000 = time for this line? +for (int j = 0; j < height; j++) { +go through the line -> int j = 0 (store data +10); j (memory access +1) < (math op +3) height (memory access +1); j (memory +1) ++ (math +3). +total of line = 10 + 1 + 3 + 1 + 1 + 3 = 19 picoseconds + +M = 2000 +2000 * 19 = 38000 = time for this line? + +[image[i][j] makeMoreAwesome]; +go through the line -> image[i] (memory access +1) image[j] (memory access) makeMoreAwesome (runprogram +200) +total of line = 1 + 1 + 200 = 202 picoseconds + +return image; +go through line -> image (memory access +1) +total of line = 1 + +so: 19000 + 38000 + 202 + 1 = 57203 picoseconds? + +answer: I'm not 100% sure how to allocate numbers to each element. My guess is 57203 picoseconds. + +answer from class: run time is 200 picoseconds + additional operations. This question is a little bit vague. + +b) What is the time complexity of this method, expressed in big O notation? Assume the image is square, and both dimensions are ‘n’. + +answer: O(N^2) - Performance is proportional to the square of the size of the input data (N and M and N*M = N^2) and there are two loops (three loops would = O(N^3)) + +c) My friend sends me an improved version of his algorithm, makeEvenMoreAwesome, that takes into account the pixels around the image. He says it’s O(n2) in the amount of pixels in the image. What is the new time complexity of the method? + +answer: O(N^2) If we are thinking about the worst case scenrio, this is equal to the existing run time. + +answer from class: O(N^2) * O(N^2) = O(N^4) + +(makeMoreAwesome * makeEvenMoreAwesome) + +2) If foo(xs) is a function with time complexity n (where n is the size of the input array), and bar(xs) is a function with time complexity n2, what is the time complexity of each of the following snippets of code or algorithms? + +a) for (int i = 0; i < n; i++) { +for (int j = 0; j < n; j++) { // O(N^2) +foo(xs); + } +} +for (int i = 0; i < n; i++) { +for (int j = 0; j < n; j++) { // O(N^2) +bar(xs); + } +} +for (int i = 0; i < n; i++) { +for (int j = 0; j < n; j++) { +// do cool stuff + } +} + +Notes: + +when performance is proportional to the square of the size of the input data (and for loops are involved) the run time is often O(N^2). Deeper nested loops result in higher exponents. + +O(N^2) + O(N^2) = O(N^4) + +Answer: O(N^4) + +b) Calculate the time complexity of the following: + +int frobnicate(ys, m) { +if (m == 0) { +return 0; +} +return ys[m] + frobnicate(ys, m - 1); +} +frobnicate(xs, n); + +Tip: Write down a table with n from 0 to 5 and trace through to find out how many times frobnicate is called with each value of n. + +Notes: + +number counts down so O(N) + +Answer: O(N) + +c) An algorithm that takes as its input a list of friends of length n, filters out duplicates using a method similar to our hasDuplicates method, sorts the list using merge sort (see bigocheatsheet.com), then prints each item to the screen. + +Notes: + +loop through to filter out duplicates = binary search = O(N^2) +merge sort = O(N log N) +Print to screen = O(N) + +Answer: O(N^2) (largest value only) + +d) An algorithm that searches the now-sorted list of friends for a specific friend (not including the time it takes to sort). + +Notes: + +sorted array search = linear search = O(N) +N is the max number of items in the array + +Answer: O(N) + +3) Look at the complexities for some common data structures at bigocheatsheet.com. Pick a good data structure for each of the following scenarios (there are sometimes multiple answers): + +a) You get a large dataset of points of interest from an API when your app first runs. You build it once at the beginning, and then have to search it many times while the user pans around a map. + +Notes: This sounds like a tree or hash table (less efficient for search) + +Answer: tree / hash table + +b) You get a small dataset of points of interest from an API every time the user pans the map. You construct the data set many times and only render it once, then you discard it and do another API search. + +Tip: Constructing a dataset of size n means you have to call the data structure’s insert method n times. So if the data structure has an insert method that takes O(n2), the time to build it all from scratch is O(n3). + +Notes: you could save the points of interest in a set or array. + +Answer: set or array + +c) You used a linked list for your music app’s playlist feature, but now when people search their playlist, there’s a noticeable lag before loading results. Your competitor’s app is buttery smooth when searching, even showing results as you type. What data structure would allow you to more quickly search without compromising too much on the speed of inserting and deleting tracks, even in the worst case? + +Notes: A tree is fast when inserting, deleting and searching items + +Answer: Tree + +4) Write an algorithm using one of the methods from exercise 1 (your choice) to calculate the factorial of a number n. What is the time complexity of your method in terms of the input value? */ +// answer: + +let userNames = ["cheekymonkey56", "007brenda", "hippydude"] + +if userNames.contains("geniushacker202") { + print("ACCESS GRANTED") +} +else { + print("INVALID USERNAME...") +} + +// so: the Big O run time is O(N) because the run time corresponds to userNames.count + +/* +5) Write an Objective C or Swift function to multiply two numbers without using the * operator. Use the grade school method of multiplying by doing repeated addition. For instance, 5 * 8 = 5 + 5 + 5 + 5 + 5 + 5 + 5 + 5 = 40. Find the big O of your function in terms of n and m (the two operands). +*/ + +// answer: + +func multiplyTwoNumbers(num1: Int, num2: Int) -> Int { + var product = 0 + + for _ in 1...num2 { // loop through 1 through num2 + product += num1 // each time add num1 to the product + } + return product +} + +print(multiplyTwoNumbers(3, num2: 4)) // test it + +// BIG O = O(N) growth is linear + + +/* +6) Look up Russian Peasant Multiplication. It’s a faster way to multiply numbers, especially on a binary computer (like yours!). Implement a new multiplication function using this technique and find the big O of your method. If you have trouble with implementing this, write a flow chart and find the big O based on that. (But it’s more satisfying to implement it and run it) + +Tip: Run through the method by hand a few times to see how it works and verify to yourself that it does. It’s a non-intuitive algorithm. This will hopefully also make the time complexity more clear. +*/ + +// answer: + +// Steps: +// pass two mutable integers into function +// create a counter variable to hold the product +// while n1 is greater than 1 +// double n1 +// divide n2 by half +// if n1 is odd +// add num2 to the existing product +// if num1 = 1, break +// return the product + +func peasantMultiplication(var num1: Int, var num2: Int) -> Int { + + var product = 0 + + while(num1 > 1) { + num2 = num2 * 2 + num1 = num1 / 2 + + if(num1 % 2 != 0) { + product += num2 + } + } +return product +} + +print(peasantMultiplication(14, num2: 36)) + +// Answer from class: This is a O(log N) algorithm (if you can double the input and then add something it is log n) + +/* +7) Using the technique from exercise 4, profile the built in sorting method in objective C (use an NSMutableArray and google how to sort an array of numbers in objective C). Graph the result. Use spreadsheet formulas to add graph lines for n, n2, and n*log(n). (You’ll have to modify the factors to make them fit in the graph window and to be close to the graph of method execution time). Show that the sort method best fits n * log(n). +*/ + +// answer: look at zovfrellia's github acct for example of graphs +// take time stamps for start and end times: +// NSDate *startTime = [NSDate date]; +// NSDate *endTime = [NSDate date]; +// use google sheets to graph numbers + + + + + + diff --git a/HWfrom1-14-16(discrete-math).playground/Contents.swift b/HWfrom1-14-16(discrete-math).playground/Contents.swift new file mode 100644 index 0000000..01a89a2 --- /dev/null +++ b/HWfrom1-14-16(discrete-math).playground/Contents.swift @@ -0,0 +1,46 @@ +//: Playground - noun: a place where people can play + +import Cocoa + +var str = "Hello, playground" + +/* Question 1: https://www.hackerrank.com/challenges/minimum-draws +Copy and paste your code: */ + +// this follows the pigeon hole rule: N socks will always require N+1 draws to find a match. +// kaira helped with this code: + +func userInput() -> Int { + let input = readLine() // this is necessary for hacker rank input :( + let num = Int(input!) + return num! +} + +let testNum : Int = userInput() +for i in 0.. + + + \ No newline at end of file diff --git a/HWfrom1-14-16(discrete-math).playground/playground.xcworkspace/contents.xcworkspacedata b/HWfrom1-14-16(discrete-math).playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/HWfrom1-14-16(discrete-math).playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/HWfrom1-14-16(discrete-math).playground/timeline.xctimeline b/HWfrom1-14-16(discrete-math).playground/timeline.xctimeline new file mode 100644 index 0000000..bf468af --- /dev/null +++ b/HWfrom1-14-16(discrete-math).playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + + diff --git a/HWfrom1-17-16(Lists And Sorts).playground/Contents.swift b/HWfrom1-17-16(Lists And Sorts).playground/Contents.swift new file mode 100644 index 0000000..24db079 --- /dev/null +++ b/HWfrom1-17-16(Lists And Sorts).playground/Contents.swift @@ -0,0 +1,314 @@ +//: Playground - noun: a place where people can play + +import UIKit + +var str = "Hello, playground" + +/* +Work on your solutions here. +Link: https://docs.google.com/document/d/1XioaEqk6VqUPA-ccQhkqP3eAoDthxYyOM9vSPB7fDkg/edit#heading=h.uopysoy45zmw +1) Given a partially filled in Sudoku board and a set of coordinates in that board pointing to an empty square, write a function that returns a list containing all numbers that the empty square could be. +2) Rotate a matrix by ninety degrees +3) Design an optimal algorithm for sorting four elements A, B, C, and D. By optimal, I mean one that sorts using the minimum number of comparisons. Hint: you may want to start by putting the first two items in order and the last two items in order... that takes two comparisons. How many more comparisons do you need to find the minimum element? The maximum? Once you’ve found the min and max, what if any additional comparisons are needed? +*/ + +// 1) review the rules of Sudoku: Each row, column and square (9 spaces each) needs to be filled out with the numbers 1-9, without repeating any numbers within the row, column or square +// 2) grab all numbers from the row and save them in an array +// 3) grab all numbers from that column and save them in an array +// 4) grab all numbers from square and save in an array +// 5) loop through arrays, if number is not in 1...9, save it in an array +// 6) return those numbers - these are your potential answers + +var sudokuBoard = [ + [5, 0, 8, 0, 7, 3, 1, 9, 0], + [9, 0, 0, 6, 0, 0, 4, 0, 8], + [0, 0, 0, 9, 0, 8, 0, 3, 5], + [0, 7, 0, 0, 0, 0, 0, 6, 0], + [0, 0, 2, 0, 0, 0, 9, 0, 0], + [0, 1, 0, 0, 0, 0, 0, 8, 0], + [1, 9, 0, 3, 0, 6, 0, 0, 0], + [2, 0, 3, 0, 0, 7, 0, 0, 9], + [0, 8, 7, 1, 9, 0, 3, 0, 4]] + + +print(sudokuBoard[0][1]) // coordinates for 1, 2 + +var rowNumbers = [Int]() +var columnNumbers = [Int]() +var boxNumbers = [Int]() + +func getRowNumbers(sudokuBoard: [[Int]], row: Int, column: Int) -> [Int] { + for i in sudokuBoard[row] { + if i > 0 { + rowNumbers.append(i) + } + } +return rowNumbers +} + +func getColumnNumbers(sudokuBoard: [[Int]], row: Int, column: Int) -> [Int] { + for i in sudokuBoard { + if i[column] > 0 { + columnNumbers.append(i[column]) + } + } + return columnNumbers // should be [5, 9, 1, 2] +} + +func returnPotentialNumbers(rowNumbers: [Int], columnNumbers: [Int]) -> Set { + + let allNumbers = rowNumbers + columnNumbers + let setOfAllNumbers = Set(allNumbers) + let setCompare = Set([1, 2, 3, 4, 5, 6, 7, 8, 9]) + + return setOfAllNumbers.exclusiveOr(setCompare) +} + +getRowNumbers(sudokuBoard, row: 1, column: 0) // test it! +getColumnNumbers(sudokuBoard, row: 1, column: 0) +returnPotentialNumbers(rowNumbers, columnNumbers: columnNumbers) // <--- here are the potential numbers!! + +// 1b) get numbers from specific quadrants +// This code is way too long, see refactored version below. + +func getQuadrantNumbers(sudokuBoard: [[Int]], row: Int, column: Int) -> [Int] { + + let point = (x: row, y: column) + + switch point { + case let q1 where (point.x >= 0 && point.x <= 2) && (point.y >= 0 && point.y <= 2): + print("\(q1) is in quadrant 1") + + for i in sudokuBoard[0][0...2] { + if i > 0 { + boxNumbers.append(i) + } + } + for i in sudokuBoard[1][0...2] { + if i > 0 { + boxNumbers.append(i) + } + } + for i in sudokuBoard[2][0...2] { + if i > 0 { + boxNumbers.append(i) + } + } + + case let q2 where (point.x >= 0 && point.x <= 2) && (point.y >= 3 && point.y <= 5): + print("\(q2) is in quadrant 2") + + for i in sudokuBoard[0][3...5] { + if i > 0 { + boxNumbers.append(i) + } + } + for i in sudokuBoard[1][3...5] { + if i > 0 { + boxNumbers.append(i) + } + } + for i in sudokuBoard[2][3...5] { + if i > 0 { + boxNumbers.append(i) + } + } + + case let q3 where (point.x >= 0 && point.x <= 2) && (point.y >= 6 && point.y <= 8): + print("\(q3) is in quadrant 3") + + for i in sudokuBoard[0][6...8] { + if i > 0 { + boxNumbers.append(i) + } + } + for i in sudokuBoard[1][6...8] { + if i > 0 { + boxNumbers.append(i) + } + } + for i in sudokuBoard[2][6...8] { + if i > 0 { + boxNumbers.append(i) + } + } + + case let q4 where (point.x >= 3 && point.x <= 5) && (point.y >= 0 && point.y <= 2): + print("\(q4) is in quadrant 4") + + for i in sudokuBoard[3][0...2] { + if i > 0 { + boxNumbers.append(i) + } + } + for i in sudokuBoard[4][0...2] { + if i > 0 { + boxNumbers.append(i) + } + } + for i in sudokuBoard[5][0...2] { + if i > 0 { + boxNumbers.append(i) + } + } + + case let q5 where (point.x >= 3 && point.x <= 5) && (point.y >= 3 && point.y <= 5): + print("\(q5) is in quadrant 5") + + case let q6 where (point.x >= 3 && point.x <= 5) && (point.y >= 6 && point.y <= 8): + print("\(q6) is in quadrant 6") + + case let q7 where (point.x >= 6 && point.x <= 8) && (point.y >= 0 && point.y <= 2): + print("\(q7) is in quadrant 7") + + case let q8 where (point.x >= 6 && point.x <= 8) && (point.y >= 3 && point.y <= 5): + print("\(q8) is in quadrant 8") + + case let q9 where (point.x >= 6 && point.x <= 8) && (point.y >= 6 && point.y <= 8): + print("\(q9) is in quadrant 9") + + default: + print("coordinates unknown.") + } + return boxNumbers +} +getQuadrantNumbers(sudokuBoard, row: 1, column: 4) // test it! +// Note: alternately, if you divide quadrants by 3, you will get the coordinate. + + + +// HOMEWORK REVIEW NOTES: + +let sampleInput: [[Int?]] = +[[5,0,8,9,0,0,0,0,0], + [0,7,3,6,0,0,9,0,8], + [1,9,0,4,0,8,0,3,5], + [0,7,0,0,0,2,0,1,0], + [0,0,0,0,0,0,0,0,0], + [0,6,0,9,0,0,0,8,0], + [1,9,0,2,0,3,0,8,7], + [3,0,6,0,0,7,1,9,0], + [0,0,0,0,0,9,3,0,4]] + +func getValidNumbers(sudokuBoard:[[Int?]], row:Int, col:Int) -> [Int] { + var valid: Set = [1, 2, 3, 4, 5, 6, 7, 8, 9] + + for c in 0..(valid) +} +getValidNumbers(sampleInput, row: 0, col: 1) + + +// 2. +let matrix = [[1,2,3,4], // this is a 4X4 array + [5,6,7,8], + [9,0,1,2], + [3,4,5,6]] + +func rotate(matrix: [[Int]]) -> [[Int]] { + let n = matrix.count + + var result: [[Int]] = [] // start with empty array + + for _ in 0.. [Int] { + var left = values[0...1] + if left[0] > left[1] { + let t = left[0] + left[0] = left[1] + left[1] = t + } + + var right = values[2...4] + if right[0] > right[1] { + let t = right[1] + right[0] = right[1] + right[1] = t + } + + // 1 3 + // 2 4 + + return [] +} + +// n x n matrix + +// 4 - 0 - 1 = 3 +// +// 0, 0 -> 0, n - 1 +// r, c -> r, n - c - 1 +// 0, n - 1 -> n - 1, n - 1 +// r, c -> n - r - 1, c +// n - 1, n - 1 -> n - 1, 0 +// r, c -> n - r - 1 +// n - 1, 0 -> 0, 0 + +/* +------------ +fib(5) +a = 3 +b = 4 +------------ +fib(3) +a = 1 +b = 2 +------------ +fib(2) +a = 0 +b = 1 +------------ +fib(0) 1 +*/ \ No newline at end of file diff --git a/HWfrom1-17-16(Lists And Sorts).playground/contents.xcplayground b/HWfrom1-17-16(Lists And Sorts).playground/contents.xcplayground new file mode 100644 index 0000000..5da2641 --- /dev/null +++ b/HWfrom1-17-16(Lists And Sorts).playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/HWfrom1-17-16(Lists And Sorts).playground/playground.xcworkspace/contents.xcworkspacedata b/HWfrom1-17-16(Lists And Sorts).playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/HWfrom1-17-16(Lists And Sorts).playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/HWfrom1-17-16(Lists And Sorts).playground/timeline.xctimeline b/HWfrom1-17-16(Lists And Sorts).playground/timeline.xctimeline new file mode 100644 index 0000000..bf468af --- /dev/null +++ b/HWfrom1-17-16(Lists And Sorts).playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + + diff --git a/multi-dimensional-arrays.playground/Contents.swift b/multi-dimensional-arrays.playground/Contents.swift new file mode 100644 index 0000000..320b9c3 --- /dev/null +++ b/multi-dimensional-arrays.playground/Contents.swift @@ -0,0 +1,3 @@ +//: Playground - noun: a place where people can play + +import Cocoa diff --git a/multi-dimensional-arrays.playground/contents.xcplayground b/multi-dimensional-arrays.playground/contents.xcplayground new file mode 100644 index 0000000..06828af --- /dev/null +++ b/multi-dimensional-arrays.playground/contents.xcplayground @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/multi-dimensional-arrays.playground/playground.xcworkspace/contents.xcworkspacedata b/multi-dimensional-arrays.playground/playground.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/multi-dimensional-arrays.playground/playground.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/multi-dimensional-arrays.playground/timeline.xctimeline b/multi-dimensional-arrays.playground/timeline.xctimeline new file mode 100644 index 0000000..bf468af --- /dev/null +++ b/multi-dimensional-arrays.playground/timeline.xctimeline @@ -0,0 +1,6 @@ + + + + +