diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..16035a4 Binary files /dev/null and b/.DS_Store differ diff --git a/Graph_Ex.3.jpg b/Graph_Ex.3.jpg new file mode 100644 index 0000000..7d0dd89 Binary files /dev/null and b/Graph_Ex.3.jpg differ diff --git a/Graph_Ex.4.jpg b/Graph_Ex.4.jpg new file mode 100644 index 0000000..3e8c9cb Binary files /dev/null and b/Graph_Ex.4.jpg differ diff --git a/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift b/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift index 13cc14e..f23dda7 100644 --- a/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift +++ b/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift @@ -11,16 +11,113 @@ Work on your solutions here. Link: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3lQZQiFUOxZKBwsY/edit#heading=h.za36ai6n5fth -1) - - - -2) - - - -3) - - - -*/ +1) */ + +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) +} + +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]] +getValidNumbers(sampleInput, row: 0, col: 1) + + + +// 2) + +func rotate(matrix: [[Int]]) -> [[Int]] { + let n = matrix.count + + var result: [[Int]] = [] + + 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 [] +} diff --git a/HWFrom1-24(Recursion).playground/Contents.swift b/HWFrom1-24(Recursion).playground/Contents.swift index 1c44504..4c395fa 100644 --- a/HWFrom1-24(Recursion).playground/Contents.swift +++ b/HWFrom1-24(Recursion).playground/Contents.swift @@ -1,3 +1,5 @@ +import Foundation +import UIKit /* @@ -11,15 +13,49 @@ Homework link: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3l //Question 1 +func fibnoacci(n: Int) -> Int { + var result = [1,1] + if n < 2 { + return n + } + for i in 2...n { + result.insert(result[i-1] + result[i-2], atIndex: i) + } + return result[n] +} +// The iterative version is much more efficient and faster, because it doesn't have to iterate through the array several times //Question 2 +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 + } +func steppUp(var steps: Int = 0) { + steps += tryStepp() + if steps == 1 { + return + } + steppUp(steps) +} +//Test +steppUp() -//Question 3 \ No newline at end of file + + +//Question 3 diff --git a/HWFrom1-28-16(Merge Sort).playground/Contents.swift b/HWFrom1-28-16(Merge Sort).playground/Contents.swift index afdc1b6..1b63acd 100644 --- a/HWFrom1-28-16(Merge Sort).playground/Contents.swift +++ b/HWFrom1-28-16(Merge Sort).playground/Contents.swift @@ -4,3 +4,34 @@ //Insert code here: + +func insertionSort(var array:[Int], index:Int) -> [Int]{ + + if index == array.count{ + return array + } + else{ + + var tempArray = array[index], + i = 0, + j = 0, + maxIter = index - 1 + + while (i <= maxIter && array[i] < tempArray) { + i++ + } + while j<=maxIter{ + array[maxIter-j+1] = array[maxIter-j] + j++ + } + + array[i] = tempArray; + + return insertionSort(array, index: index+1) + } + +} + +//Test +insertionSort([44, 7, 2, 25, 0], index: 1) + diff --git a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift index bcf8eda..ec2e41a 100644 --- a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift +++ b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift @@ -1,16 +1,128 @@ //: Playground - noun: a place where people can play +import Foundation //Answer the questions in the homework below //https://docs.google.com/document/d/1KlK3PmRMybmHS5db_AP11uHXIcbIeM5vHuuAZOV3xME/edit# -//1) +//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 - T: O(n^2), S: O(1) +// Insertion sort - T: O(n^2), S: O(1) +// Selection sort - O(n^2), S: O(1) +// Mergesort - T: O(n log n), S: O(n) +// Quicksort - O(n log n), S: O(log n) + + +//2) What is the advantage of partitioning quicksort in place? + // Wouldn't need to crate another array, so the space complexity would be smaller + +//3) Without looking, implement quicksort. + + func partition(inout array: [Int], first: Int, last: Int) -> Int { + let pivot = array[first] + var leftMark = first + 1 + var rightMark = last + + while leftMark <= rightMark { + while leftMark <= rightMark && array[leftMark] < pivot { + leftMark = leftMark + 1 + } + while leftMark <= rightMark && array[rightMark] > pivot { + rightMark = rightMark - 1 + } + if leftMark < rightMark { + swap(&array[leftMark], &array[rightMark]) + } + } + if first != rightMark { + swap(&array[first], &array[rightMark]) + } + return rightMark + } + + + func quickSort(inout array: [Int], first: Int, last: Int) { + if first >= last { return } + let splitPoint = partition(&array, first: first, last: last) + quickSort(&array, first: first, last: splitPoint - 1) + quickSort(&array, first: splitPoint + 1, last: last) + } + func quickSort(inout arr: [Int]){ + quickSort(&arr, first: 0, last: arr.count - 1) + } + + //Test + var numberList = [4, 1, 35, 22, 66, 12] + quickSort(&numberList) + + +/*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))) + +Compare the time it takes to run mergesort, quicksort, and quicksort with the median. +https://gist.github.com/gummibeatz/8ff29bcec54d7e3ef683 +*/ + + + func randomNumbers(size: Int, highestValue: Int) -> [Int] { + + var array = Array(count: size, repeatedValue: 0) + + for i in 0.. Bool { + if (paren.count%2 != 0) { + return false + } + + var i = 0 + var j = paren.count + + while (i = ["hi", "hey"] -//b) +func moderate(message: String) -> Bool { + let words = (message as NSString).componentsSeparatedByString(" ") + for word in words { + if blacklist.contains(word.lowercaseString){ + return false + + } + } + return true +} +//Test +moderate("hi, how are you") -//c) -//2) +//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") -//3) \ No newline at end of file diff --git a/HWFrom2-05-16(Trees).playground/Contents.swift b/HWFrom2-05-16(Trees).playground/Contents.swift index ca035a2..c4119b1 100644 --- a/HWFrom2-05-16(Trees).playground/Contents.swift +++ b/HWFrom2-05-16(Trees).playground/Contents.swift @@ -1,10 +1,87 @@ //https://docs.google.com/document/d/1te7mLS06MEYwETFSbVBqMrIzJ43GTEo5uuCiWdB0fyE/edit?usp=drivesdk +/* +Using the Swift binary tree implementation below (the Node class), +implement a function that takes in: a string containing a simple postfix mathematical expression, +and returns: a binary tree representing that expression, +using the process described here: https://en.wikipedia.org/wiki/Binary_expression_tree#Example. +Required: +Build and return the binary tree representation of the expression. +The following characters should be treated as operators: +-*/ + +/* +Tips: +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. +Sample input: +"ab+cde+**" + + +//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 + } +} + +//Printing +extension Node { + + func printInorder() { + left?.printInorder() + print(self) + right?.printInorder() + } + +} + + + //1 +//Template for the function you should implement: + +func parseExpression(input: String) -> [Node] { + + let operators: Set = ["+", "-", "*", "/"] + var stack: [Node] = [] + for character in input.characters { + let nodeChar = Node(value: character) + if !operators.contains(character) { + stack.append(nodeChar) + } else { + nodeChar.right = stack.removeLast() + nodeChar.left = stack.removeLast() + stack.append(nodeChar) + } +} + + + stack.first?.printInorder() + + return stack +} + +let expTree = "ab+cde+**" + +parseExpression(expTree) -//Bonus1 -//Bonus2 \ No newline at end of file diff --git a/HWfrom1-09-16(SwiftIntro).playground/Contents.swift b/HWfrom1-09-16(SwiftIntro).playground/Contents.swift index 488e9ed..a2104ee 100644 --- a/HWfrom1-09-16(SwiftIntro).playground/Contents.swift +++ b/HWfrom1-09-16(SwiftIntro).playground/Contents.swift @@ -5,19 +5,106 @@ 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) Given an integer N, there is a list of size N-1 that is missing one number from 1 - N(inclusive). Find that number. -1) +func missingNumber(N: Int, list:[Int]) -> Int { + + var sumOfNArray = 0 + var sumOfList = 0 + var missingNumber : Int + + for i in 1...N { + sumOfNArray += i + } + + for i in list { + sumOfList += i + } + + missingNumber = sumOfNArray - sumOfList + return missingNumber + +} -2) -3) -4) +// 2) Given a list of size N containing numbers 1 - N (inclusive). return true if there are duplicates, false if not + +func hasDuplicates(list: [Int]) -> Bool { + + for i in 0.. Int? { + var commonArray = [Int]() + var smallestCommonNumber: Int + + for i in list1 { + for j in list2 { + if i == j { + commonArray.append(i) + } + } + } + + if commonArray.count == 0 { + return nil + } + else { + smallestCommonNumber = commonArray[0] + + for i in commonArray{ + + if (i < smallestCommonNumber) { + smallestCommonNumber = i + } + } + return smallestCommonNumber + } +} + +// 4) Check to see if an integer is a palindrome don’t use casting + +func isPalindrome(number: Int) -> Bool { + let convertedToString = String(number) + return String (convertedToString.characters.reverse()) == convertedToString +} + + + + + +// Test 1 + let array1 = [1,4,6,3,2] + let N = 6 + print(missingNumber(N, list: array1)) + +// Test 2 + let array2 = [10, 4, 6, 7, 2, 9, 4, 0] + print(hasDuplicates(array2)) + +// Test 3 + print(findTheSmallestNumberInBothLists(array1, list2: array2)) + +// Test 4 + print(isPalindrome(12321)) -*/ diff --git a/HWfrom1-10-016(BigO).playground/Contents.swift b/HWfrom1-10-016(BigO).playground/Contents.swift index 2040d38..01fa53f 100644 --- a/HWfrom1-10-016(BigO).playground/Contents.swift +++ b/HWfrom1-10-016(BigO).playground/Contents.swift @@ -5,26 +5,223 @@ 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/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. + 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? -2) + 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; + } -3) + b) What is the time complexity of this method, expressed in big O notation? Assume the image is square, and both dimensions are ‘n’. + 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? -4) -5) +---Answers--- -6) +a) Total Image px = 1000 * 2000 = 2.000.000 px + 1 + 3 + 10 + 200 = 214 picoseconds for one pixel + Total time = 2.000.000px * 214 picoseconds/px = 428.000.000 picoseconds -7) + If it's n by m, it would take n * m * 214 picoseconds +b) O(n^2) +c) O(n^4) */ + + /********************************************************************/ + +/* + +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++) { + foo(xs); + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + bar(xs); + } + } + + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + // do cool stuff + } + } + +b) 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. + +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. + + +d) An algorithm that searches the now-sorted list of friends for a specific friend (not including the time it takes to sort). + + +---Answers--- + +a) Algorithm 1 : + First for loop - n + Second foor loop - n + foo(xs) - n + Time complexity = O(n^3) + + Algorithm 2 : + First for loop - n + Second loop - n + bar(xs) - n^2 + Time complexity = O(n^4) + + Algorithm 3 : + First for loop - n + Second loop - n + Time complexity = O(n^2) + + O(n^3) + O(n^4) + O(n^2) = O(n^4) + +b) O(n) because this is a straight recursion from m to m-1, m-2... + +c) Filtering friends takes O(n^2) time + Sorting using merge sort, takes O(n log(n)) time + Printing takes O(n) time + Time complexity = O(n^2) + O(n log(n)) + O(n) = O(n^2) + +d) 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. + + + 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). + + + 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? + + +---Answers--- + +a) Binary Search Tree + +b) Hash Table + +c) Tree - O(n) for search, insert, delete + + + + /********************************************************************/ + + +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? */ + + func factorial( n : Int) -> Int { + + if n < 0 { + return -1 + } + else if n == 0 { + return 1 + } + else { + return n * factorial( n - 1 ) + } + } + + print(factorial(4)) + + // Time complexity O(n) + +/* + +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). */ + + func multiplicationOfTwoNumbers( n : Int, m: Int) -> Int { + var multiplication = 0; + + for _ in 1...n { + multiplication += m + } + return multiplication + } + +// Test + print(multiplicationOfTwoNumbers(3, m: 6)) + +// Time complexity : O(n) + + +/* + +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. */ + + + func russianPeasantMultiplication( var n : Int, var m: Int) -> Int { + var multiplication = 0 + + while(n > 1) { + m = m * 2 + n = n / 2 + + if(n % 2 != 0) { + multiplication += m + } + } + + return multiplication + } + + print(russianPeasantMultiplication(24, m: 16)) + + // Time complexity : O(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). + + + + + + + + + + + + + + + + diff --git a/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift b/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift index bc0df91..60c874d 100644 --- a/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift +++ b/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift @@ -1,29 +1,61 @@ //: Playground - noun: a place where people can play import UIKit +import Foundation var str = "Hello, playground" /* - + Question 1: https://www.hackerrank.com/challenges/minimum-draws Copy and paste your code: +*/ + func matchingSocks(n: Int) { + var nextLine = 0 + + for _ in 0.. Int{ + return (n-1)*(n)/2 + } + + handshakes(4) + +/* +What is the big O runtime of your code?: + + O(1) -What is the big O runtime of your code?: Question 3: https://www.hackerrank.com/challenges/connecting-towns -Copy and paste your code: +Copy and paste your code: */ -What is the big O runtime of your code?: + func travelling (n : [Int]) -> Int { + var total = 0 + + for f in n { + total = (total * f) + } + return total + } -*/ +// What is the big O runtime of your code?: + + // O(n) diff --git a/HWfrom1-23-16(Recursion).playground/Contents.swift b/HWfrom1-23-16(Recursion).playground/Contents.swift index f7c3b5c..55f7fed 100644 --- a/HWfrom1-23-16(Recursion).playground/Contents.swift +++ b/HWfrom1-23-16(Recursion).playground/Contents.swift @@ -10,12 +10,66 @@ var str = "Hello, playground" //1 +func printBinaryRepresentation(number:Int) -> Int{ + if (number == 0) + { + return 0; + } + else + { + return (number % 2 + 10 * printBinaryRepresentation(number / 2)) + } +} +// Test +print(printBinaryRepresentation(13)) //2 +var swappedArray = [Int]() +func swapAdjacentElements(var array:[Int]) -> [Int]{ + swap(&array[0], &array[1]) + swappedArray.append(array[0]) + swappedArray.append(array[1]) + array .removeAtIndex(0) + array .removeAtIndex(0) + if (array.count == 0) { + return swappedArray + } + return swapAdjacentElements(array) +} -//3 +//Test +print(swapAdjacentElements([1,2,3,4,5,6])) + + + + + +//3 + +func binarySearch(var array:[Int], number:Int) -> Bool{ + + let midIndex = array.count / 2 + + if number == array[midIndex] { + + return true + } + if number < midIndex { + array[0.. midIndex { + array[midIndex...array.count] +// binarySearch(array, number: number) + } + return false +} + +//Test +print(binarySearch([23, 45, 2, 27], number: 2)) +