1

I'm using xcode 7, and I am wondering how to create a randomized dictionary from two similar arrays. For example

var array1 = ["apple", "banana", "orange", "strawberry", "cherry"]
var array2 = ["apple", "banana", "orange", "strawberry", "cherry"]

I then want the code to create a random dictionary like so:

var dict = ["apple": "banana", "banana": "apple", "orange": "cherry", "strawberry": "orange", "cherry": "strawberry"]

Also, I don't want to have both value and key to be the same, ie no "apple": "apple".

I'm relatively new to coding. Any help would be greatly appreciated :)

2 Answers2

2

You can use shuffle function from Nate Cook's answer to shuffle values array and then simply fill dictionary with keys and values:

var keys = ["apple", "banana", "orange", "strawberry", "cherry"]
var values = keys

values.shuffle()

var d = [String: String]()

for (index, item) in keys.enumerate() {
    d[item] = values[index]
}

The advantage of this solution that it's O(n) (execution time and consumed memory linearly depends from number of items).

Community
  • 1
  • 1
mixel
  • 25,177
  • 13
  • 126
  • 165
1

Your particular example is a bit contrived as there is really no point in dealing with two identical arrays, you can simply use one. I guess something like this should do the trick:

var fruits = ["apple", "banana", "orange", "strawberry", "cherry"]
var dict = [String: String]()

for (keyIndex, key) in fruits.enumerate() {
    var valueIndex: Int {
        var index: Int
        repeat {
            index = Int(arc4random_uniform(UInt32(fruits.count)))
        } while index == keyIndex || dict.values.contains(fruits[index])
        return index
    }
    dict[key] = fruits[valueIndex]
}
T. Benjamin Larsen
  • 6,373
  • 4
  • 22
  • 32
  • Thank you very much for your response, and helping me get rid of some redundancy. One thing, though. I was hoping it would use every string in the array once for a key, and once for an index. With this code, it's using every string once for a key, but maybe multiple times for and index. – Brandon Jones Dec 03 '15 at 07:43
  • Just make an additional check in the while statement: `while index == keyIndex || dict.values.contains(fruits[index])` – T. Benjamin Larsen Dec 03 '15 at 08:42
  • Thank you very much. This works perfectly. I really appreciate it. Hopefully these things kind of things will come easily to me in time – Brandon Jones Dec 04 '15 at 03:06
  • Your welcome, and I'm sure it will. The more you code the easier it becomes. :-) – T. Benjamin Larsen Dec 04 '15 at 11:49