Created
September 3, 2018 22:35
-
-
Save thexande/db8bef591ecbf7b05da4afa9c1b2b01d to your computer and use it in GitHub Desktop.
Element Frequency: Find the values in an array with a given frequency
This file contains hidden or 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
/// Find the values in an array with a given frequency | |
/// | |
/// - Parameters: | |
/// - array: the array to search through | |
/// - k: the frequency value | |
/// - Returns: an array of values with the corresponding frequency | |
func frequency(for array: [Int], k: Int) -> [Int] { | |
var bucket: [[Int]] = [] | |
var frequency: [Int:Int] = [:] | |
array.enumerated().forEach { offset, element in | |
if let val = frequency[element] { | |
frequency[element] = val + 1 | |
} else { | |
frequency[element] = 1 | |
} | |
bucket.insert([], at: offset) | |
} | |
frequency.forEach { key, value in | |
bucket[value].append(key) | |
} | |
print(frequency) | |
return bucket[k] | |
} | |
let input = [1, 3, 4, 4, 3, 5, 6, 2, 1, 1, 5] | |
let bucket = frequency(for: input, k: 2) | |
print("bucket here \(bucket)") | |
// bucket here [4, 5, 3] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment