2

In this code 2nd line goes through the array and output what it receives and its random. But sometimes I get the same thing twice, like it would say "Straub", and then "Straub" and then something else like "Rusher". I've tried to do a "do while loop" but I don't know how to set it up where it doesn't repeat itself. By the way this the swift programming language.

let types = ["Alex", "Straub", "Rusher", "Graser"]

let type = types[Int(arc4random_uniform(UInt32(types.count)))]

println(type)

If you have any questions please post them in the comments section

alex
  • 1,746
  • 6
  • 19
  • 34
  • When you roll a dice there is a chance to get the same number twice in a row... – zisoft Oct 05 '14 at 16:27
  • Can you post more of your code? – Steve Rosenberg Oct 05 '14 at 16:28
  • @SteveRosenberg that is all the code I have I want the names to display but, I don't want one to repeat. I want all of them to be random but none repeating. – alex Oct 05 '14 at 16:35
  • Oh, are you suffering from repeats simply because random luck will lead to repeats? – Steve Rosenberg Oct 05 '14 at 16:49
  • @TheCampingRusher 'All of them to be random but none repeating' is an oxymoron. If you can make predictions about the forthcoming output based on the current output, it's not random. – Ideasthete Oct 05 '14 at 16:50
  • 1
    What you're looking for is a random shuffle, not a random number. This has been answered many times on SO. – Rob Napier Oct 05 '14 at 16:54
  • I would take a copy of your array, and remove the items as they are selected. Like this: let types = ["Alex", "Straub", "Rusher", "Graser"] var unselected = types var selection = Int(arc4random_uniform(UInt32(unselected.count))) var type = unselected[selection] unselected.removeAtIndex(selection) println(type) selection = Int(arc4random_uniform(UInt32(unselected.count))) type = unselected[selection] unselected.removeAtIndex(selection) println(type) What you do once you have exhausted the list is up to you. – pbasdf Oct 05 '14 at 17:05

1 Answers1

1

This avoids a direct repetition:

var lastIndex = -1
var index = -1

let types = ["Alex", "Straub", "Rusher", "Graser"]

do {
    index = Int(arc4random_uniform(UInt32(types.count)))
} while index == lastIndex

println(types[index])
lastIndex = index
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
zisoft
  • 22,770
  • 10
  • 62
  • 73
  • This code generates one a couple times, it would say Alex Alex Alex Alex Alex then Straub I need it so that it doesnt repeat itself but is still somewhat random – alex Oct 05 '14 at 16:54