diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000..565faff Binary files /dev/null and b/.DS_Store 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..7ce8276 100644 --- a/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift +++ b/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift @@ -9,18 +9,272 @@ var str = "Hello, playground" Work on your solutions here. -Link: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3lQZQiFUOxZKBwsY/edit#heading=h.za36ai6n5fth +Link: https://docs.google.com/document/d/1XioaEqk6VqUPA-ccQhkqP3eAoDthxYyOM9vSPB7fDkg/edit#heading=h.uopysoy45zmw -1) +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 + + Input: sudokuBoard:[[Int?]]. (Each location on the board will be either be an Int from 1-9 or nil(empty cell)) + row: Int + col: Int +*/ + +let 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]] + + +func booleanArr (arr:[Int]) -> [Bool]{ + + //create an array of false bools to match the input array + + let booleanArr = Array(count: arr.count+1, repeatedValue: false) + + return booleanArr + +} -2) +func possibleNumbers(arr:[Int], inout booleanArr: [Bool]) -> [Bool] { + + + //loop through the input arr and change + //the bool of the same index as the integer + //in the corresponding array + + for num in arr { + + //Change (the input num)index of the boolean arr + //to true + + booleanArr[num] = true + } + + + + + return booleanArr +} +func allPossibleNumbers(booleanArr: [Bool]) -> [Int] +{ + + var possibleNums = [Int]() + + //If the bool in our boolean arr is false + //add that index num to our availableNum arr + + for i in 1.. [Int] +{ + + var validNums = [Int]() + + + // create row array + let rowArr = sudokuBoard[row] + print("row \(rowArr)") + + var columnArr: [Int] = [] + var square: [Int] = [] + + for i in 0..[[Int]] +{ + let temp = Array(count: grid.count, repeatedValue: 0) + var tempGrid = Array(count: grid.count, repeatedValue:temp) + let count = grid.count + + for i in 0..[Int] +{ + let maxIndex = arr.count - 1 + let midIndex = maxIndex / 2 + + for _ in midIndex...maxIndex { + + if arr[midIndex] arr[maxIndex-1] { + + (arr[midIndex], arr[maxIndex-1]) = (arr[maxIndex-1], arr[midIndex]) + } + } + + + + + return arr +} + +sortFourElements(&fourElementArr) +sortFourElements(&anotherFourElementArr) + + +//With single char strings +let I = "I" +let J = "J" +let K = "K" +let L = "L" +var fourStringArr = [I, L, K, J] + +let M = "Monopoly" +let N = "Neuron" +let O = "Ocean" +let P = "Polar Bear" +var anotherFourStringArr = [P, O, M, N] + +var mArr = ["Monkey", "Mission", "Marmalade", "Mars"] + + +func sortFourStrings(inout arr:[String]) ->[String] +{ + let maxIndex = arr.count - 1 + let midIndex = maxIndex / 2 + + for _ in midIndex...maxIndex { + + if arr[midIndex] arr[maxIndex-1] { + + (arr[midIndex], arr[maxIndex-1]) = (arr[maxIndex-1], arr[midIndex]) + } + } + + + + + return arr +} + +sortFourStrings(&fourStringArr) +sortFourStrings(&anotherFourStringArr) +sortFourStrings(&mArr) diff --git a/HWFrom1-17-16(Lists and Sorts).playground/contents.xcplayground b/HWFrom1-17-16(Lists and Sorts).playground/contents.xcplayground index 5da2641..9f5f2f4 100644 --- a/HWFrom1-17-16(Lists and Sorts).playground/contents.xcplayground +++ b/HWFrom1-17-16(Lists and Sorts).playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/HWFrom1-24(Recursion).playground/Contents.swift b/HWFrom1-24(Recursion).playground/Contents.swift index 1c44504..00cfe34 100644 --- a/HWFrom1-24(Recursion).playground/Contents.swift +++ b/HWFrom1-24(Recursion).playground/Contents.swift @@ -1,3 +1,6 @@ +import Foundation + + /* @@ -8,18 +11,184 @@ Homework link: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3l */ +/* +***********Question 1 +Write an iterative (not recursive) fibonacci function +that calculates the nth fibonacci number. +*/ + +let fibSeq = [1, 1, 2, 3, 5, 8, 13, 21] +// 0 1 2 3 4 5 6 + +func fibIterative(n: Int) -> Int +{ + if n == 1 || n == 0 { + + return 1 + } + + var fibNumArr = [1,1] + var tempSum = 0 + + for i in 1...n-1 { + + tempSum = fibNumArr[i] + fibNumArr[i-1] + fibNumArr.append(tempSum) + } + + return tempSum +} + +fibIterative(9) +fibIterative(1) + + +//Non-memoized fibREcursive +//func fib(n: Int) -> Int { +// +// if (n == 0 || n == 1) { +// return 1 +// } +// return fib(n - 1) + fib(n - 2) +//} +// +//fib(9) +//fib(1) + +/* +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? -//Question 1 + - Wow. The recursive function runs over 10 times the number of times the iterative function runs. +*/ +/* +***********Question 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. -//Question 2 +Write a new stepUp method using this new tryStep method that works the same as before. +*/ +func tryStep() -> Int { + + let step = Int(arc4random_uniform(3)) + + switch step { + + case 0 : + print("Stepped Down") + return -1 + + case 1 : + print("Stayed on the same step") + return 0 + + case 2 : + print("Stepped up!") + return 1 + + default: + + return 0 + + } + +} + +tryStep() + +func stepUp(var stepCounter: Int = 0) { + + stepCounter += tryStep() + print(stepCounter) + if stepCounter == 1 { + + return + } + + stepUp(stepCounter) + +} + +stepUp() + +func stepUpUp() { + + switch tryStep() { + + case 1: + return + + case -1: + stepUpUp() + stepUpUp() + + default: + stepUpUp() + } +} + +stepUpUp() +/* +***********Question 3 +Using the code in Appendix C as a starting point, +create a Swift command line project to find files on your computer by name. +Your solution should use recursion. +Your method should return “NOT FOUND” if it couldn’t find the file, +otherwise it should return the full path to that file. +*/ -//Question 3 \ No newline at end of file +//func findFile(name: String, atPath: String) -> String { +// let fileManager = NSFileManager.defaultManager() +// let contents = +// try! fileManager.contentsOfDirectoryAtPath(atPath) +// for fileOrDir in contents { +// var isDir = ObjCBool(false); +// let fullPath = atPath + "/" + fileOrDir +// let exists = fileManager.fileExistsAtPath(fullPath, isDirectory: &isDir) +// if exists && Bool(isDir) { +// +// print("DIR: " + fileOrDir + "Path: " + fullPath) +// +// let found = findFile(name, atPath: fullPath) +// +// if found != "NOT FOUND" { +// +// return found +// } +// +// +// } else if exists { +// +// if fileOrDir == name { +// +// return ("Found file: " + name + " At Path: " + fullPath) +// +// }else { +// +// print("FILE: " + fileOrDir) +// +// } +// +// } else { +// print("NEITHER: " + fileOrDir) +// +// } +// } +// return "NOT FOUND" +//} +// +//print(findFile("PriceList.docx", atPath: "/Users/justinegartner/Documents")) diff --git a/HWFrom1-24(Recursion).playground/contents.xcplayground b/HWFrom1-24(Recursion).playground/contents.xcplayground index 5da2641..9f5f2f4 100644 --- a/HWFrom1-24(Recursion).playground/contents.xcplayground +++ b/HWFrom1-24(Recursion).playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/HWFrom1-28-16(Merge Sort).playground/Contents.swift b/HWFrom1-28-16(Merge Sort).playground/Contents.swift index afdc1b6..c4e1c2e 100644 --- a/HWFrom1-28-16(Merge Sort).playground/Contents.swift +++ b/HWFrom1-28-16(Merge Sort).playground/Contents.swift @@ -1,6 +1,101 @@ //: Playground - noun: a place where people can play //https://docs.google.com/document/d/1rlQ3lstnNb3fOR58EwGDysMQ0FSDkUGykcCoU14B9Go/edit#heading=h.za36ai6n5fth +/* +Use recursion to implement at least one of the following sorting algorithms in Swift: +Insertion sort OR Selection sort +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] + +*/ //Insert code here: + + + +//*******Insertion Sort********* + + +//**** First Solution **** + +func insertionSort(inout values: [Int]) +{ + + func insertHelper(inout values: [Int], index: Int) { + + if index < values.count - 1 { + + let lastIndex = values.removeLast() + print("last index: \(lastIndex)") + + if lastIndex < values[index] { + + values.insert(lastIndex, atIndex: index) + print("newValues: \(values)") + + insertHelper(&values, index: 0) + + }else { + + values.append(lastIndex) + insertHelper(&values, index: index + 1) + } + + + } + } + + insertHelper(&values, index: 0) + +} + +var values = [46, 45, 3, 23, 1, 9] +insertionSort(&values) + + +//***** Solution 2 - Using Swap **** + +func insertionSort2(inout values: [Int]) +{ + print("*****InsertionSort2******") + func swapHelper(inout values: [Int], index: Int) { + + if index > 0 { + + print("last index: \(values[index])") + + if values[index] < values[index - 1] { + + swap(&values[index], &values[index - 1]) + print("newValues: \(values)") + + swapHelper(&values, index: values.count - 1) + + }else { + + swapHelper(&values, index: index - 1) + } + + + } + } + + swapHelper(&values, index: values.count - 1) + +} + +var values2 = [46, 45, 3, 23, 1, 9] +insertionSort2(&values2) diff --git a/HWFrom1-28-16(Merge Sort).playground/contents.xcplayground b/HWFrom1-28-16(Merge Sort).playground/contents.xcplayground index 5da2641..9f5f2f4 100644 --- a/HWFrom1-28-16(Merge Sort).playground/contents.xcplayground +++ b/HWFrom1-28-16(Merge Sort).playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift index bcf8eda..8ec91a6 100644 --- a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift +++ b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift @@ -2,15 +2,114 @@ //Answer the questions in the homework below //https://docs.google.com/document/d/1KlK3PmRMybmHS5db_AP11uHXIcbIeM5vHuuAZOV3xME/edit# - +/* //1) +Without looking at the Big O Cheatsheet, write down the average time and space complexity for + +-bubble sort: + TIME: O(n^2) + SPACE: + +-insertion sort: + TIME: O(n) + SPACE: + +-selection sort: + TIME: O(n) + SPACE: + +-mergesort: + TIME: O(n log(n)) + SPACE: + +-quicksort: + TIME: O(n log(n)) + SPACE: + + //2) +What is the advantage of partitioning quicksort in place? + + -We save memory (Space complexity) because we don't have to create new arrays with every split. + + //3) +Without looking, implement quicksort. + + + //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 + + + //5) +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? + + + + +//6) +Given an array of strings containing “[“,”]”,”{“,”}”,”(“,”)”. Output whether or not the parentheses are balanced. +Good examples: () [] () ([]()[]) +Bad examples: ( ( ] ([)] +*/ +func isBalanced(paren: [String]) -> Bool { + + var pStack = [String]() + + for str in paren { + + + switch str { + + case "(": + pStack.append(str) + + case "{": + pStack.append(str) + + case "[": + pStack.append(str) + + default: + if pStack.count != 0 { + + pStack.removeLast() + + }else { + + pStack.append(str) + } + + } + + print(pStack) + } + + + + return pStack.count == 0 +} + +let pStr = ["(","(",")",")"] +let pStr2 = ["{","}","{","}","}"] +let pStr3 = [")","(",")","(",")","(","(",")","("] +let pStr4 = ["(",")","{","}","[","]"] +let pStr5 = ["(","]","{",")","[","}"] + +isBalanced(pStr) +isBalanced(pStr2) +isBalanced(pStr3) +isBalanced(pStr4) +isBalanced(pStr5) -//6) \ No newline at end of file diff --git a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/contents.xcplayground b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/contents.xcplayground index 5da2641..9f5f2f4 100644 --- a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/contents.xcplayground +++ b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ No newline at end of file diff --git a/HWFrom1-31-16(Sets and HashMaps).playground/Contents.swift b/HWFrom1-31-16(Sets and HashMaps).playground/Contents.swift index c5841b0..332d707 100644 --- a/HWFrom1-31-16(Sets and HashMaps).playground/Contents.swift +++ b/HWFrom1-31-16(Sets and HashMaps).playground/Contents.swift @@ -1,20 +1,188 @@ -//: https://docs.google.com/document/d/1T7tYRqpDPWoxarfmXqfRCHB-YqvA8-Qx_mEyy5smtfc +import UIKit +//: https://docs.google.com/document/d/1T7tYRqpDPWoxarfmXqfRCHB-YqvA8-Qx_mEyy5smtfc +/* //1) -//a) +Write good hash functions for the following data types. Justify your choices and how they avoid collisions. +a) +Int -//b) -//c) +b) +struct Point: Hashable { +let x, y: Int +} +c) +Array + //2) +You moderate a popular mobile device discussion forum. +You want to cut down on the vitriol and make your work easier, +so you decide to implement a blacklist based system +to automatically reject or approve posts. + +For example: + +moderate("I would never use a crApple product!") // false (reject) +moderate("I wish all these FANDROIDS would just shut up!") // false +moderate("M$ is the worst, Linux rules!") // false +moderate("Can’t we all just get along?") // true (approve) + +Write moderate(message: String) -> Bool, using a built-in Swift Set to manage your blacklist. +Make your method case insensitive; it should block the word no matter what combination of upper and lowercase letters is used. +*/ + + +var blacklist = Set() + +for word in ["crApple", "FANDROIDS", "M$"] { + blacklist.insert(word.lowercaseString) +} + +blacklist + +let msg1 = "I would never use a crApple product!" +let msg2 = "I wish all these FANDROIDS would just shut up!" +let msg3 = "M$ is the worst, Linux rules!" +let msg4 = "Can’t we all just get along?" + +let msg2b = "I wish all these fandroids would just shut up!" + +func moderate(message: String) -> Bool +{ + + var msgSet = Set() + + for word in message.componentsSeparatedByString(" ") { + + msgSet.insert(word.lowercaseString) + + } + + return msgSet.isDisjointWith(blacklist) +} + +moderate(msg1) +moderate(msg2) +moderate(msg3) +moderate(msg4) +moderate(msg2b) + + +//*********Also found out about this built in "spellcheck" object UITextChecker******************* +//func wordIsReal(word: String) -> Bool { +// let checker = UITextChecker() +// let range = NSMakeRange(0, word.characters.count) +// let misspelledRange = checker.rangeOfMisspelledWordInString(word, range: range, startingAt: 0, wrap: false, language: "en") +// +// return misspelledRange.location == NSNotFound +//} +// +//func moderate(message: String) -> Bool +//{ +// for word in message.componentsSeparatedByString(" ") { +// +// if !wordIsReal(word) { +// +// return false +// } +// } +// +// return true +//} +// +//moderate(msg1) +//moderate(msg2) +//moderate(msg3)//doesn't work with this one! +//moderate(msg4) + + + +/* +//3) +Your company makes a phonebook app, and your users have been complaining +about how long it takes to look people’s numbers up. You decide +to upgrade your archaic array-based system to a sleek, modern hash map. + +Write a phonebook class that uses either our HashMap from class +or the built in Swift dictionary (your choice). + +It should implement the protocol below. + +It needs to support importing from the old array based format +which used an array of tuples, like: +[(“Caleb”, “501-555-1234”), (“Mike”, “212-555-4321”), (“Jenny”, “345-867-5309”)] + +*/ +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 # +} + + + +struct PhoneBook:PhoneBookProtocol, CustomStringConvertible { + + var phonebookDict = [String:String]() + + mutating func addPerson(name: String, phoneNumber: String) { + + phonebookDict[phoneNumber] = name + + } + + mutating func removePerson(name: String) { + + phonebookDict.removeValueForKey(name) + } + + mutating func importFrom(oldPhonebook: [(String, String)]) { + + for i in 0.. String? { + + + return phonebookDict[name] + } + + //Custom String Convertible + var description: String { + + return "{\(phonebookDict)}" + } +} + +let oldPhoneBook = [("Caleb", "501-555-1234"), ("Mike", "212-555-4321"), ("Jenny", "345-867-5309")] +var newPhonebook = PhoneBook() +newPhonebook.importFrom(oldPhoneBook) -//3) \ No newline at end of file +newPhonebook.description diff --git a/HWFrom1-31-16(Sets and HashMaps).playground/contents.xcplayground b/HWFrom1-31-16(Sets and HashMaps).playground/contents.xcplayground index 5da2641..9f5f2f4 100644 --- a/HWFrom1-31-16(Sets and HashMaps).playground/contents.xcplayground +++ b/HWFrom1-31-16(Sets and HashMaps).playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ 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..d6f07ed 100644 --- a/HWFrom2-05-16(Trees).playground/Contents.swift +++ b/HWFrom2-05-16(Trees).playground/Contents.swift @@ -1,10 +1,106 @@ + +import UIKit + //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) + + } + } + + //Bonus1 + stack.first?.printInorder() + + return stack +} + +let expTree = "ab+cde+**" + +parseExpression(expTree) + -//Bonus1 -//Bonus2 \ No newline at end of file +//Bonus2 diff --git a/HWFrom2-05-16(Trees).playground/contents.xcplayground b/HWFrom2-05-16(Trees).playground/contents.xcplayground index 5da2641..9f5f2f4 100644 --- a/HWFrom2-05-16(Trees).playground/contents.xcplayground +++ b/HWFrom2-05-16(Trees).playground/contents.xcplayground @@ -1,4 +1,4 @@ - + \ 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..b2d506f 100644 --- a/HWfrom1-09-16(SwiftIntro).playground/Contents.swift +++ b/HWfrom1-09-16(SwiftIntro).playground/Contents.swift @@ -9,15 +9,114 @@ 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. +func findMissing (N: Int, list: [Int]) -> Int { + + var totalSumOfArray = 0 + var totalSumOfList = 0 + + for i in 1...N { + + totalSumOfArray += i + } + + for i in list { + + totalSumOfList += i + } + + return totalSumOfArray - totalSumOfList + +} -1) -2) -3) +//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 { + + for i in 0.. Int? { + + let sortedList1 = list1.sort() + let sortedList2 = list2.sort() + + for numInList1 in sortedList1 { + + for numInList2 in sortedList2 { + + if numInList1 == numInList2 { + + return numInList1 + } + } + } + + return nil +} + +let list4 = [56, 23, 7, 78] +let list5 = [78, 79, 101, 23] +getSmallestCommonValue(list4, list2: list5) + +let list6 = [34, 1, 7, 78] +let list7 = [78, 7, 101, 23] +getSmallestCommonValue(list6, list2: list7) + + + +//4) +//Check to see if an integer is a palindrome don’t use casting +func isPalindrome(var num: Int) -> Bool { + + let orgNum = num + var newNum = 0 + + while(num > 0) { + + newNum *= 10 + newNum += num % 10 + num /= 10 + } + + return newNum == orgNum + +} + +let number = 12321 +let number2 = 134543 +isPalindrome(number) +isPalindrome(number2) + -4) -*/ diff --git a/HWfrom1-10-016(BigO).playground/Contents.swift b/HWfrom1-10-016(BigO).playground/Contents.swift index 2040d38..93bdb09 100644 --- a/HWfrom1-10-016(BigO).playground/Contents.swift +++ b/HWfrom1-10-016(BigO).playground/Contents.swift @@ -11,20 +11,103 @@ 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) +1a) +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) + 1000px by 2000px = 3 + 15 + 15 + 202 = 237 = O(1) (Right? Because the algorithm doesn’t depend on the input) + + n by m = 3 + 15n + 15n^2 + 202n^2 = 217n^2 => O(n^2 x m) + + +1b) +What is the time complexity of this method, expressed in big O notation? Assume the image is square, and both dimensions are ‘n’. + + O(n^3) + (Because n by m = O(n^2 x m) so n by n would be O(n^2 x n) = O(n^3), yes?) + + +1c) +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? + + It stays the same. O(n^2 x m) + + +2a) +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? + + n + n^2 + n^3 + n + n^2 + n^4 + n + n^2 = n^4 =>>> O(n^4) + + +2b) + O(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. + (Not really sure how to do this) + + +2c) +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. + + If hasDuplicates = O(n^2) + And if mergeSort = O(n log(n)) + Then… + I’m not quite sure how to add them together... + + +2d) +An algorithm that searches the now-sorted list of friends for a specific friend (not including the time it takes to sort). + + O(n) + + +3a) + Array + + +3b) + Stack or List + + +3c) + Hash Table -3) 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? + + For any number “n”, multiply all numbers 1 through n. The product is the factorial of n. + 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 multiplyByAddition(let numA: Int, let numB: Int) -> Int{ + + var sum = 0 + + for _ in 0...numB { + + sum += numA + } + + return sum +} +/* + + + 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. + 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). + + +Here's a link to my notes: +https://docs.google.com/document/d/1LkEgzBhDxOQqecoH4CyhOqCKsCn6XpPyO7e47a8hnik/edit?usp=sharing */ diff --git a/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift b/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift index bc0df91..6f711ab 100644 --- a/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift +++ b/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift @@ -10,20 +10,115 @@ var str = "Hello, playground" Question 1: https://www.hackerrank.com/challenges/minimum-draws Copy and paste your code: +*/ + +//Maximum number of draws will always equal the number of pairs + 1. + +func maxDraws(let n:Int) -> Int +{ + return n + 1 +} + +let numOfPairs = 3 +maxDraws(numOfPairs) +/* What is the big O runtime of your code?: + 0(1) + + Question 2: https://www.hackerrank.com/challenges/handshake Copy and paste your code: +*/ + +//Total number of Handshakes (Combinations) +// C(n,2) +// n! / 2! * (n-2)! + +func factorial(var n: Int) -> Int +{ + var num = n - 1 + + for _ in 1.. Int +{ + + return factorial(n) / (factorial(2) * factorial(n - 2)) +} + +handshakes(3) +handshakes(5) + + +//Second solution +//Break down the C(n,2) formula +//so that factorials are not necessary + +func handshakes2(let n: Int) -> Int +{ + + return n * (n-1) / 2 +} + +handshakes2(3) +handshakes2(5) + + +/* What is the big O runtime of your code?: + + First solution + 0(n^2) + + Second solution + O(n^2) + Question 3: https://www.hackerrank.com/challenges/connecting-towns +For x number of towns there are an array of [a, b, c, ...] numbers of routes between each pair of towns. +We are given x and [a, b, c, ...] +You can find the number of routes by multiplying each number of routes together + Copy and paste your code: +*/ + +func totalRoutes(let routes: [Int]) -> Int +{ + var productOfRoutes = 1 + + for i in 0.. - + \ No newline at end of file diff --git a/images/image00.png b/images/image00.png new file mode 100755 index 0000000..092dc91 Binary files /dev/null and b/images/image00.png differ diff --git a/images/image01.png b/images/image01.png new file mode 100755 index 0000000..97159f4 Binary files /dev/null and b/images/image01.png differ diff --git a/images/image02.png b/images/image02.png new file mode 100755 index 0000000..4586896 Binary files /dev/null and b/images/image02.png differ diff --git a/images/image03.png b/images/image03.png new file mode 100755 index 0000000..45f29aa Binary files /dev/null and b/images/image03.png differ