Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

ios - Using an Array to prevent cases from being used?

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

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

1 Reply

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...