import UIKit
import GameKit
class ViewController: UIViewController {
let poolBalls = [Int](1...8)
var shuffledPoolBalls = [Int]()
@IBOutlet weak var numLab1: UILabel!
@IBOutlet weak var numLab2: UILabel!
@IBOutlet weak var numLab3: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func hitBalls(_ sender: UIButton) {
generateNumbers()
}
func generateNumbers() {
shuffledPoolBalls = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: poolBalls) as! [Int]
numLab1.text = String(shuffledPoolBalls[0])
numLab2.text = String(shuffledPoolBalls[1])
numLab3.text = String(shuffledPoolBalls[2])
}
}
我无法在此处添加屏幕截图,抱歉。重点是;当我运行此代码时,我在屏幕上看到随机且不重复的3个数字。多数民众赞成,但他们没有从最低到最高排序。想想第一个生成的数字是7(在numLab1上),第二个生成的数字是4(在numLab2上),第三个生成的数字是1(在numLab3上)。我在屏幕上看到数字为" 7-4-1"但我希望将它们视为" 1-4-7"。我该如何管理?
我用Duncan的答案解决了这个问题。多数民众赞成我如何写我的功能;
func generateNumbers() {
shuffledPoolBalls = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: poolBalls) as! [Int]
let firstThree = shuffledPoolBalls.prefix(3).sorted()
numLab1.text = String(firstThree[0])
numLab2.text = String(firstThree[1])
numLab3.text = String(firstThree[2])
}
答案 0 :(得分:0)
正如Duncan C所说,对整个阵列进行洗牌是没有意义的,只保留前3个元素并对其进行排序,更好的解决方案是从阵列中获取N个随机元素(并确保它们是唯一的)然后,对它们进行排序。
这应该有效
var shuffledPoolBalls : [Int] = []
while shuffledPoolBalls.count < 3 {
let randomIndex = Int(arc4random_uniform(UInt32(poolBalls.count)))
if !shuffledPoolBalls.contains(poolBalls[randomIndex]) {
shuffledPoolBalls.append(randomIndex)
}
}
shuffledPoolBalls = shuffledPoolBalls.sorted()
numLab1.text = String(shuffledPoolBalls[0])
numLab2.text = String(shuffledPoolBalls[1])
numLab3.text = String(shuffledPoolBalls[2])
答案 1 :(得分:0)
shuffledPoolBalls = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: poolBalls) as! [Int]
let firstThree = shuffledPoolBalls.prefix(3).sorted()
顺便说一句,改组阵列并不难:
func shuffled(_ array: [Int]) -> [Int] {
var result = array
for i in 0 ..< array.count {
let index = Int(arc4random_uniform(UInt32(array.count)))
result.swapAt(i, index)
}
return(result)
}
通过更多的工作,您可以使用Generics将上述任意类型的数组变为shuffle。