Search code examples
arraysswiftdictionaryenumeration

Filtering Dictionary with an array of random Ints to make a new dict


So I have this method to get an array of random ints between 1-9, a random number of times between 1 and 7.

let n = arc4random_uniform(7) + 1
var arr: [UInt32] = []
for _ in 0 ... n {
    var temp = arc4random_uniform(9) + 1
    while arr.contains(temp) {
        temp = arc4random_uniform(9) + 1
    }
    print(temp)
    arr.append(temp)
}
print(arr)

So that gets me an array like [1,4,2] or [5,7,3,4,6]. And I have a method to turn another array of strings into a enumerated dictionary.

    var someArray: [String] = ["War", "Peanuts", "Cats", "Dogs", "Nova", "Bears", "Pigs", "Packers", "Mango", "Turkey"]

extension Collection  {
    var indexedDictionary: [Int: Element] {
        return enumerated().reduce(into: [:]) { $0[$1.offset] = $1.element }
    }
}
let dict1 = someArray.indexedDictionary
print(dict1)

giving me the indexed dictionary

[1:"War", 2:"Peanuts",..etc]

MY question is using the Ints of the random array how do I create a new dictionary that only includes those keys and their values?

So for example if arr = [3,1,5] how do I get a new dictionary of

[3:"dogs", 1:"Peanuts",5:"Bears"].


Solution

  • This should do it:

    let finalDict = dict1.filter { arr.contains($0.key) }
    

    Update:

    You can even go a step further and skip the whole strings to array mapping. So remove

    extension Collection  {
        var indexedDictionary: [Int: Element] {
            return enumerated().reduce(into: [:]) { $0[$1.offset] = $1.element }
        }
    }
    let dict1 = someArray.indexedDictionary
    print(dict1)
    

    and just use this:

    Swift 4:

    let finalArray = someArray.enumerated().flatMap { arr.contains($0.offset) ? $0.element : nil }
    

    Swift 4.1:

    let finalArray = someArray.enumerated().compactMap { arr.contains($0.offset) ? $0.element : nil }
    

    Update 2:

    If you need a dictionary and not an array in the end use this:

    Swift 4:

    let finalDict = someArray.enumerated().flatMap { randomInts.contains($0.offset) ? ($0.offset, $0.element) : nil }.reduce(into: [:]) { $0[$1.0] = $1.1 }
    

    Swift 4.1:

    let finalDict = someArray.enumerated().compactMap { randomInts.contains($0.offset) ? ($0.offset, $0.element) : nil }.reduce(into: [:]) { $0[$1.0] = $1.1 }