1

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!

0

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly - You sir, are a gentleman and a scholar, thank you!
1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.