Created
October 15, 2019 09:22
-
-
Save alexpaul/5403e38feb13e954cb1b58856fda73e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
// Questions review | |
// dictionary question | |
// given an array of integers write a function that returns a dictionary of | |
// occurences of each integer | |
// input: [1, 3, 1, 1, 3, 4, 1, 8, 2, 7, 8] | |
// output: [7: 1, 1: 4, 3: 2, 8: 2, 2: 1, 4: 1] | |
func occurencesOfInteger(arr: [Int]) -> [Int: Int] { | |
var frequencyDictionary = [Int: Int]() | |
for number in arr { | |
// using optional binding to unwrap the value at the given key in our | |
// frequencyDictionary | |
// enter the if let statement if we have seen the number before and | |
// increment count by 1 | |
if let count = frequencyDictionary[number] { | |
frequencyDictionary[number] = count + 1 | |
} else { | |
// first time visiting a number we want to set the count of | |
// occurences to 1 | |
// appending of an element in the dictionary happens here | |
// e.g first time | |
// [:] | |
frequencyDictionary[number] = 1 | |
// first adding the first element from the array our dictionary looks like below | |
// [1: 2, 3: 2, 4: 1, 8: 2, 2: 1, 7: 1] | |
} | |
} | |
return frequencyDictionary | |
} | |
let results = occurencesOfInteger(arr: [1, 3, 1, 1, 3, 4, 1, 8, 2, 7, 8]) | |
print(results) // [4: 1, 2: 1, 3: 2, 1: 4, 7: 1, 8: 2] - will be unordered as is the definition of a dictionary | |
// closure question | |
// write a function called largestValue(in: ) that finds the largest Int in an array of Ints. Use reduce to | |
// solve this exercise. | |
func largestValue(in numbers: [Int]) -> Int { | |
// using guard to ensure an array is not empty | |
// guard numbers.count > 0 else { return -1 } | |
// using guard to get the first element | |
guard let first = numbers.first else { return -1 } | |
// if let first = numbers.first { | |
// // ONLY has access to first inside if let statement | |
// print(first) | |
// } else { | |
// //first - DOES NOT COMPILE | |
// } | |
// using trailing closure syntax to solve reduce exercise | |
let result = numbers.reduce(first) { prevResult, currentValue in | |
if prevResult > currentValue { | |
return prevResult | |
} else { | |
return currentValue | |
} | |
} | |
// 1. numbers.reduce(0, +) | |
/* 2. numbers.reduce(0) { prevResult, currentValue in | |
// code here | |
} | |
*/ | |
return result | |
} | |
let largestResult = largestValue(in: [56, 100, -56, 0, 208]) | |
print(largestResult) // 208 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment