tbaldw02
tbaldw02

Reputation: 163

Get random element occurrence from Swift array

I have an array of 7 elements: var myArray = [0, 0, 0, 0, 0, 0, 0]

I randomly flip these 0's to 1's during processing: var myArray = [1, 0, 0, 1, 0, 1, 1]

My question is, how do I get one of the elements that are still zero at random? For example, I want the system to be able to take that second array above and randomly choose index 1, 2, or 4.

This has had me stumped for hours, any help would be appreciated!

Upvotes: 1

Views: 129

Answers (2)

Cœur
Cœur

Reputation: 38667

You can filter your array for indices where the elements equal to zero, then randomly pick one of them.

Swift 4.2

let randomZeroIndice = myArray.enumerated()
                              .compactMap { $0.element == 0 ? $0.offset : nil }
                              .randomElement()

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236370

You can enumerate your array, filter the elements equal to zero and map the element offset. Then you just need to use arc4random_uniform to randomly pick one of them:

let myArray = [1, 0, 0, 1, 0, 1, 1]

let myZeroIndices = myArray.enumerated()
                           .filter{ $0.element == 0 }
                           .map{ $0.offset }           // [1, 2, 4]

let randomIndice = myZeroIndices[Int(arc4random_uniform(UInt32(myZeroIndices.count)))]   // 4

Upvotes: 1

Related Questions