Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

So I have this,

    func doStuff() {
       //blahblahblah
    }

    var randomNumber = arc4random() % 4
    randomNumber += 1

    switch(randomNumber) {

    case 1:
    doStuff()
    break

    case 2:
    doStuff()
    break

    case 3:
    doStuff()
    break

    case 4:
    doStuff()
    break
    }

Now I need it to do something like this

    func doStuff() {
       //blahblahblah
    }

    var alreadyUsed = [""]

    var randomNumber = arc4random() % 4
    randomNumber += 1

    if randomNumber is not inside alreadyUsed {

    switch(randomNumber) {

    case 1:
    doStuff()
    alreadyUsed.append("1")
    break

    case 2:
    doStuff()
    alreadyUsed.append("2")
    break

    case 3:
    doStuff()
    alreadyUsed.append("3")
    break

    case 4:
    doStuff()
    alreadyUsed.append("4")
    break
    }
    }

Essentially, I am trying to have something that will randomly select a case, then won't select the same case again the next time the function is run. I am using that first chunk of code as a function. After a case has been used in that function, I do not want the function to use it again. I hope this makes sense.

Thanks guys!

EDIT: Though I'd find it more useful, It doesn't even have to be an array, as long as it gets the job done.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
129 views
Welcome To Ask or Share your Answers For Others

1 Answer

var someArray = [1,2,3,4]

let index = Int(arc4random_uniform(UInt32(someArray.count)))
let randomNumber = someArray[index]

someArray.removeAtIndex(index)

This should do what you want.

  • First you create an array with the available numbers
  • Let it randomly pick a number for the index
  • Remove the number in the array

I've changed the conversion of UInt32 to Int because according to this post:

Int(arc4random()) will crash 50% of the time it's executed on a 32-bit platform because a UInt32 won't fit in an Int32


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...