diff --git a/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift b/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift index 13cc14e..6b83816 100644 --- a/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift +++ b/HWFrom1-17-16(Lists and Sorts).playground/Contents.swift @@ -11,16 +11,182 @@ Work on your solutions here. Link: https://docs.google.com/document/d/1INvOynuggw69yLRNg3y-TPwBiYb3lQZQiFUOxZKBwsY/edit#heading=h.za36ai6n5fth -1) - - - -2) - +1) +*/ +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]] + + +func getNumbersInRow(sudokuBoard:[[Int]], row: Int) -> Set { + var numbersInRow = [Int]() + + for i in sudokuBoard[row] { + if i != 0 { + numbersInRow.append(i) + } + } + + return Set(numbersInRow) +} + +func getNumbersInColumn(sudokuBoard:[[Int]], col: Int) -> Set { + var numbersInColumn = [Int]() + + for i in 0.. Set { + var numbersInGrid = [Int]() + + let coordinateOfSquare = checkForTopLeftCoordinates(row, col: col) + + for i in coordinateOfSquare.row...coordinateOfSquare.row + 2 { + for j in coordinateOfSquare.col...coordinateOfSquare.col + 2 { + if sudokuBoard[i][j] != 0 { + numbersInGrid.append(sudokuBoard[i][j]) + } + } + } + + return Set(numbersInGrid) +} + +func checkForTopLeftCoordinates(row: Int, col: Int) -> (row: Int, col: Int) { + let topLeftRowCoordinateOfSquare = (row / 3) * 3 + let topLeftColCoordinateOfSquare = (col / 3) * 3 + + return (topLeftRowCoordinateOfSquare, topLeftColCoordinateOfSquare) +} + +func getNumbers1to9NotInSet(set: Set) -> [Int] { + var numbersAvailable = [Int]() + + for i in 1...9 { + if set.contains(i) == false { + numbersAvailable.append(i) + } + } + return numbersAvailable +} + + +func getValidNumbers(sudokuBoard:[[Int]], row: Int, col: Int) -> [Int] { + + + let numbersUsedInRow = getNumbersInRow(sudokuBoard, row: row) + let numbersUsedInColumn = getNumbersInColumn(sudokuBoard, col: col) + let numbersUsedInSquare = getNumbersInSquare(sudokuBoard, row: row, col: col) + + let numbersUsed = numbersUsedInRow.union(numbersUsedInColumn).union(numbersUsedInSquare) + + let numbersAvailable = getNumbers1to9NotInSet(numbersUsed) + + return numbersAvailable +} + +getValidNumbers(sudokuBoard, row: 4, col: 4) + + +// 2) +let array = [ + [1,2,3,4,5], + [5,6,7,8,9], + [9,0,1,2,16], + [3,4,5,6,20], + [5,19,29,102,2]] + +func rotateArray90Degrees(arrayToRotate: [[Int]]) -> [[Int]] { + var newArray = arrayToRotate + + for i in 0.. [Int] { + var temp: Int + + if arr[0] > arr[1] { + temp = arr[0] + arr[0] = arr[1] + arr[1] = temp + } + + if arr[2] > arr[3] { + temp = arr[2] + arr[2] = arr[3] + arr[3] = temp + } + + if arr[0] > arr[2] { + temp = arr[0] + arr[0] = arr[2] + arr[2] = temp + } + + if arr[1] > arr[3] { + temp = arr[1] + arr[1] = arr[3] + arr[3] = temp + } + + if arr[1] > arr[2] { + temp = arr[1] + arr[1] = arr[2] + arr[2] = temp + } + + + return arr +} + +sortArray(&unSortedArray) + + + +<<<<<<< HEAD +======= */ +>>>>>>> 73de515ec342afcee5a0edcbce4663c779ecf94b diff --git a/HWFrom1-28-16(Merge Sort).playground/Contents.swift b/HWFrom1-28-16(Merge Sort).playground/Contents.swift index afdc1b6..1bce1a4 100644 --- a/HWFrom1-28-16(Merge Sort).playground/Contents.swift +++ b/HWFrom1-28-16(Merge Sort).playground/Contents.swift @@ -4,3 +4,36 @@ //Insert code here: +func selectionSort(inout values: [Int]) -> [Int] { + + recursiveLoop(&values, index: 0) + + return values +} + +func recursiveLoop(inout values: [Int], index: Int){ + if index < values.count { + var minimumIndex = index + innerRecursiveLoop(&values, index: index + 1, minimumIndex: &minimumIndex) + + if minimumIndex != index { + swap(&values[index], &values[minimumIndex]) + } + recursiveLoop(&values, index: index + 1) + } + +} + +func innerRecursiveLoop(inout values: [Int], index: Int, inout minimumIndex: Int) { + if index < values.count { + + if values[index] < values[minimumIndex] { + minimumIndex = index + } + + innerRecursiveLoop(&values, index: index + 1, minimumIndex: &minimumIndex) + } +} + +var array = [50, 46, 82, 19, 33, 35, 99, 2, 5, 1009] +selectionSort(&array) diff --git a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift index bcf8eda..0ba5ad7 100644 --- a/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift +++ b/HWFrom1-30-16(QuickSort+Lists+Queues).playground/Contents.swift @@ -3,14 +3,130 @@ //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. -//2) +// Bubble Sort = O(n^2) ... Because you have to iterate through n elements n times. -//3) +// Insertion Sort = O(n^2) ... Because, in the worst case, aside from looping through the unsorted array to grab the element to be compared, if the number being inserted is less than every element in the sorted list you will have to make a comparison with every element already sorted. -//4) +// Selection Sort = O(n^2) ... Because after looping through the whole array to grab the minimum element and looping through the array minus 1 each time until everything is sorted, the run time is O(n^2)/2 which means the time complexity is still O(n^2) because when it comes to Big Oh complexitiy, we disregard the constant. -//5) +// Merge Sort = O(n log n) ... Because it divides the input in half recursively and has to make n comparisons each time. +// Quick Sort = O(n log n) ... Because you have to do n-1 comparisons on each iteration and log n becuase you have to divide the elements log n times + +//2) What is the advantage of partitioning quicksort in place? +// No need to create another array and deal with merging them. + +//3) Without looking, implement quicksort. * I looked. Couldn't do it and it was taking too long.* + +func quickSort(inout arr: [Int]) { + quickSort(&arr, firstIdx: 0, lastIdx: arr.count-1) +} + +func quickSort(inout arr: [Int], firstIdx: Int, lastIdx: Int) { + // base case + if firstIdx - lastIdx >= 1 { return } + + // partition + let splitPoint = partition(&arr, firstIdx: firstIdx, lastIdx: lastIdx) + + // quickSort on leftHalf + quickSort(&arr, firstIdx: firstIdx, lastIdx: splitPoint - 1) + + // quickSort on rightHalf + quickSort(&arr, firstIdx: splitPoint + 1, lastIdx: lastIdx) +} + +func partition(inout arr: [Int], firstIdx: Int, lastIdx: Int) -> Int { + // set pivotValue to firstElement + let pivotValue = arr[firstIdx] + // set leftMark + var leftMark = firstIdx + 1 + // set rightMark + var rightMark = lastIdx + + /* + as leftMark and rightMark close in on each other, + swap the items that are greater than the pivot value + on the left side with the items that are less than the pivot + value on the right side. Stop when rightMark crosses leftMark + */ + while leftMark <= rightMark { + while arr[leftMark] < pivotValue { + leftMark += 1 + } + while arr[rightMark] > pivotValue { + rightMark -= 1 + } + + if leftMark < rightMark { + swap(&arr[leftMark], &arr[rightMark]) + } + } + // set the correct value at the splitPoint + if firstIdx != rightMark { + swap(&arr[firstIdx], &arr[rightMark]) + } + return rightMark // return the splitPoint +} + +var arrayForQuickSort = [22, 15, 38, 93, 95, 0, 34, 58, 72, 59] + + +quickSort(&arrayForQuickSort) + +//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? +// For quicksort, the sorting happens as the recursive calls are being pushed onto the stack as opposed to mergesort which is sorted "on the way up" or as the stack is being popped off. + +//6) Given an array of strings containing “[“,”]”,”{“,”}”,”(“,”)”. Output whether or not the parentheses are balanced. +//Good examples: () [] () ([]()[]) +//Bad examples: ( ( ] ([)] + +func samePair(element1: String?, element2: String) -> Bool { + + if element1 == "{" && element2 == "}" { + return true + } else if element1 == "[" && element2 == "]" { + return true + } else if element1 == "(" && element2 == ")" { + return true + } else { + return false + } + +} + +func isBalanced(paren: [String]) -> Bool { + + guard paren.count < 2 || paren.isEmpty || paren.count % 2 == 0 else { + return false + } + + var emptyArray = [String]() + let openingSet = Set(["(", "[", "{"]) + + for i in 0.. String { + + return "id\(input)" +} +hash(2) +hash(102) +hash(305) +// Simple hash. Always returns the same hash for the same input and avoids collisions because, assuming every input is unique, every hash value will be different seeing as it's only appending the input the prefix "id" -//b) +// b) +struct Point { + let x, y: Int +} -//c) +func hashStruct(structure: Point) -> String { + let xPoint = structure.x + let yPoint = structure.y + + let hashPoints = ((xPoint * (xPoint + 1)/2)) + yPoint + 32 + + return String(hashPoints) +} + +var structure = Point(x: 2, y: 10) +var structure1 = Point(x: 41, y: 4) +var structure2 = Point(x: 4, y: 6) +var structure3 = Point(x: 5, y: 12) +var structure4 = Point(x: 12, y: 32) +hashStruct(structure) +hashStruct(structure1) +hashStruct(structure3) +hashStruct(structure4) + +// Hash that takes the sum of all integers from 1 to x adds yPoint. + + +//c) Array //2) +func moderate(input: String) -> Bool { + let blockedWords = Set(["crapple", "fandroids", "fandroid", "m$", "micro$oft"]) + let separators = NSCharacterSet(charactersInString: "!, ") + let inputOfWords = Set(input.lowercaseString.componentsSeparatedByCharactersInSet(separators)) + let setOfBlockedWordsInInput = blockedWords.intersect(inputOfWords) + let inputIsApproved = setOfBlockedWordsInInput.isEmpty + + return inputIsApproved + +} + +moderate("I would never use a crAPPLE product!") // false +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) + + +//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 phoneBook = [String: String]() + + func addPerson(name: String, phoneNumber: String) { + phoneBook[name] = phoneNumber + } + + func removePerson(name: String) { + phoneBook.removeValueForKey(name) + } + + func importFrom(oldPhonebook: [(String, String)]) { + for i in 0.. String { + + guard let phoneNumber = phoneBook[name] else { + return "Person not found" + } + + return phoneNumber + } +} + +var phoneBook = PhoneBook() +phoneBook.addPerson("Jovanny", phoneNumber: "860-478-8872") +print(phoneBook.phoneBook) +phoneBook.importFrom([("Caleb", "501-555-1234"), ("Mike", "212-555-4321"), ("Jenny", "345-867-5309")]) +print(phoneBook.phoneBook) +phoneBook.findPerson("Harold") +phoneBook.removePerson("Jovanny") +print(phoneBook.phoneBook) + -//3) \ 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..946d38b 100644 --- a/HWfrom1-09-16(SwiftIntro).playground/Contents.swift +++ b/HWfrom1-09-16(SwiftIntro).playground/Contents.swift @@ -9,15 +9,72 @@ 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) -2) +func findMissingNumber(n: Int, arr: [Int]) -> Int { + let numberFrom1toN = n * (n + 1)/2 + var totalSumOfNumbersInArray = 0 + + for x in arr { + totalSumOfNumbersInArray += x + } -3) + return numberFrom1toN - totalSumOfNumbersInArray +} -4) +let number = 5 +let arrayOfNumbers = [4, 2, 1, 5] + +findMissingNumber(5, arr: arrayOfNumbers) + + + +// 2) Given a list of size N containing numbers 1 - N (inclusive). return true if there are duplicates, false if not + +func hasDuplicates(firstList: [Int]) -> Bool { + let set = Set(firstList) + + return set.count != firstList.count +} + +let arrayOfDuplicates = [1,5,3,6,2,2,5,7,8,244] +let arrayOfUniqueValues = [1,2,3,4,5,6,7,8] + +hasDuplicates(arrayOfUniqueValues) + +// 3) Given two lists, find the smallest value that exists in both lists. +// L1 = [1,2,5,9] +// L2 = [9, 20 , 5] + + +func findSmallestValueInTwoLists(firstList: [Int], secondList: [Int]) -> Int? { + let firstListSet = Set(firstList) + let secondListSet = Set(secondList) + + let smallestValueInSet = firstListSet.intersect(secondListSet).minElement() + + return smallestValueInSet +} + +// 4) Check to see if an integer is a palindrome don’t use casting +func isPalindrome(var num: Int) -> Bool { + + let originalNumber = num + var alteredNumber = 0 + + while (num > 0) { + alteredNumber = alteredNumber * 10 + alteredNumber = alteredNumber + (num % 10) + num = num / 10 + } + + return alteredNumber == originalNumber + +} + +isPalindrome(9000009) -*/ diff --git a/HWfrom1-10-016(BigO).playground/Contents.swift b/HWfrom1-10-016(BigO).playground/Contents.swift index 2040d38..300d8c9 100644 --- a/HWfrom1-10-016(BigO).playground/Contents.swift +++ b/HWfrom1-10-016(BigO).playground/Contents.swift @@ -11,20 +11,98 @@ 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) +a. 424,009,011 Picoseconds // n x m.. 10 + 9(n) + 10(n) + 212(m)(n) + 1 +b. O(n^2) +c. O(n^4) 2) +a. O(n^4) +b. O(n) +c. O(nlogn) +d. O(n) + 3) +a. Tree +b. Stack +c. Tree +*/ + +// 4) +func factorial(n: Int) -> Int { + + guard n >= 1 else { + return 1 +} + + var product = 1 + for x in 0...n { + product *= x + } + + return product +} + + +// 5) O(n) +func multiplication(x: Int, y: Int) -> Int { + + guard x != 0 || y != 0 else { + return 0 + } + + return x + multiplication(x, y: y-1) + +} + +// 6) O(n) + +func russianPeasantMultiplication(firstNumber: Int, secondNumber: Int) -> Int{ + + var increasingArray = [firstNumber] + var decreasingArray = [secondNumber] + + while true { + decreasingArray.append(decreasingArray.last! / 2) + increasingArray.append(increasingArray.last! * 2) + + if decreasingArray.last! == 1 { + break + } + + } + + for var x = 0 ; x < decreasingArray.count; { + + if decreasingArray[x] % 2 == 0 { + + decreasingArray.removeAtIndex(x) + increasingArray.removeAtIndex(x) + + continue + } + + x++ + } + + var sumOfIncreasingArray = 0 + for i in increasingArray { + sumOfIncreasingArray += i + } + + return sumOfIncreasingArray +} + + +// 7) + + + -4) -5) -6) -7) -*/ diff --git a/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift b/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift index bc0df91..38ba4b9 100644 --- a/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift +++ b/HWfrom1-14-16(Logic+Discrete_Math).playground/Contents.swift @@ -1,29 +1,64 @@ //: Playground - noun: a place where people can play - +import Foundation import UIKit var str = "Hello, playground" -/* -Question 1: https://www.hackerrank.com/challenges/minimum-draws -Copy and paste your code: +// Question 1: https://www.hackerrank.com/challenges/minimum-draws + +func maximumDraws(testCases: Int) { + var numberOfPairs = 0 + var draws = 0 + + for _ in 1...testCases { + numberOfPairs = Int(readLine(stripNewline: true)!)! + draws = numberOfPairs + 1 + + print(draws) + } +} + +let testCases = Int(readLine(stripNewline: true)!)! +maximumDraws(testCases) + + + +// What is the big O runtime of your code?: O(n) + +// Question 2: https://www.hackerrank.com/challenges/handshake + + +func numberOfHandShakes(testCase: Int){ + var numberOfBoardDirectors = 0 + var handshakes = 0 + + for _ in 1...testCases { + numberOfBoardDirectors = Int(readLine(stripNewline: true)!)! + handshakes = numberOfBoardDirectors * (numberOfBoardDirectors - 1)/2 + + print(handshakes) + } +} + +let testCases = Int(readLine(stripNewline: true)!)! +numberOfHandShakes(testCases) + + + +// What is the big O runtime of your code?: O(n) + +// Question 3: https://www.hackerrank.com/challenges/connecting-towns + -What is the big O runtime of your code?: -Question 2: https://www.hackerrank.com/challenges/handshake +// What is the big O runtime of your code?: -Copy and paste your code: -What is the big O runtime of your code?: -Question 3: https://www.hackerrank.com/challenges/connecting-towns -Copy and paste your code: -What is the big O runtime of your code?: -*/