【问题标题】:iOS Programming: Making an arc4_random not repeat itself using a do while loop [duplicate]iOS编程:使用do while循环使arc4_random不会重复[重复]
【发布时间】:2014-11-30 00:40:36
【问题描述】:

在此代码中,第二行遍历数组并输出它接收到的内容及其随机数。但有时我会两次得到相同的东西,就像它会说“Straub”,然后是“Straub”,然后是“Rusher”之类的其他东西。我试图做一个“做while循环”,但我不知道如何在不重复的地方设置它。顺便说一下,这是一种快速的编程语言。

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

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

println(type)

如果您有任何问题,请在 cmets 部分发布

【问题讨论】:

  • 当您掷骰子时,有机会连续两次获得相同的数字...
  • 你能发布更多你的代码吗?
  • @SteveRosenberg 这就是我想要显示名称的所有代码,但我不想重复。我希望它们都是随机的,但没有重复。
  • 哦,您是否因为随机运气会导致重复而遭受重复?
  • 您要查找的是随机洗牌,而不是随机数。这已在 SO 上多次回答。

标签: ios swift arc4random


【解决方案1】:

这避免了直接重复:

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

【讨论】:

  • 这段代码会生成一个几次,它会说 Alex Alex Alex Alex 然后 Straub 我需要它,这样它就不会重复自己,但仍然有点随机
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
  • 2015-11-01
  • 2016-05-15
相关资源
最近更新 更多