0

I'm trying to figure out this one, but NSSet(array: x).allObjects works only with [Int].

How to get Generating Random non repeatable array?

var x = map(1...5) { _ in arc4random_uniform(15)}
let xNonRepating = NSSet(array: x).allObjects
if x.count != xNonRepating.count {
    //do nothing
} else {
    x = map(1...5) { _ in arc4random_uniform(15)}
    println(x)
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
ra45
  • 3
  • 1

2 Answers2

0

It isn't very clear what you are asking.

If you want to be able to fetch objects out of an array with no repeats, use something like this:

var seedArray = ["one", "two", "three", "four", "five"]
var randomArray = Array()


func randomString -> String
{
  if randomArray.count = 0
  {
    randomArray += seedArray
  }
  return randomArray.removeAtIndex(arc4random_uniform(randomArray.count))
}

You could adapt the above approach to hold an array of any kind of object, or change it to a generic so you could manage arrays of any type of object you want.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
0

First you have to convert the result from arc4random_uniform to Int:

var draw = map(1...5) { _ in Int(arc4random_uniform(15))}

Then you need to create a while loop that will only execute if the numbers of unique elements contained in your NSSet array is less than the draw count.

var badDrawCounter = 0
while NSSet(array: draw).count < draw.count {
    //it will only enter here if there was a repeated number in your draw
    badDrawCounter++
    println("bad draw = \(draw)")
    // lets draw it again and if the result is not ok it will stay looping until you get a good draw (no repeating numbers)
    draw = map(1...5) { _ in Int(arc4random_uniform(15))}
}

println(draw)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • Could you please [edit] your answer to give an explanation of why this code answers the question? Code-only answers are [discouraged](http://meta.stackexchange.com/questions/148272), because they don't teach the solution. – DavidPostill Apr 05 '15 at 05:23
  • Thank you that was really helpful :) @Duncun, sorry for not defining my question properly – ra45 Apr 05 '15 at 22:07