gpt4 book ai didi

arrays - 数组洗牌后不会出现重复的结果

转载 作者:行者123 更新时间:2023-11-30 12:42:23 26 4
gpt4 key购买 nike

基本上,我有一个已打乱的数组。该数组是一副纸牌,如下所示:

var rank = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
var suit = ["♠", "♥","♦","♣"]
var deck = [String]()

我有一个 for 循环来创建牌组

    for t in suit {
for r in rank {
deck.append("\(r)\(t)")
}
}

然后,我在一个函数中调用一个我创建的扩展来洗牌。 (这让我带回 52 张随机分类的卡片)

        deck.shuffle()

唯一的事情是,虽然结果是随机的,但我不希望卡片重复。例如,如果结果是 2♠,我不希望在打印列表中出现 2♥、2Check、2♣。

感谢任何帮助!谢谢!

最佳答案

我认为最好的方法是使用改进的 Knuth shuffle。下面的代码是一个完整的示例。将内容保存在 customshuffle.swift 中后,只需在 shell 中使用 swiftc -o customshuffle customshuffle.swift && ./customshuffle 运行即可。

import Foundation

let decksize = 52


let rankStrings = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
let suitStrings = ["♠", "♥","♦","♣"]

struct card : Hashable, Equatable, CustomStringConvertible {
var rank: Int //1,2...,11,12,13
var suit: Int // 1,2,3,4

var hashValue: Int {
return rank + suit
}
static func == (lhs: card, rhs: card) -> Bool {
return lhs.rank == rhs.rank && lhs.suit == rhs.suit
}

var description: String {
return rankStrings[self.rank - 1] + suitStrings[self.suit - 1]
}
}

// seems like Swift still lacks a portable random number generator
func portablerand(_ max: Int)->Int {
#if os(Linux)
return Int(random() % (max + 1)) // biased but I am in a hurry
#else
return Int(arc4random_uniform(UInt32(max)))
#endif
}

// we populate a data structure where the
// cards are partitioned by rank and then suit (this is not essential)

var deck = [[card]]()
for i in 1...13 {
var thisset = [card]()
for j in 1...4 {
thisset.append(card(rank:i,suit:j))
}
deck.append(thisset)
}

// we write answer in "answer"
var answer = [card]()
// we pick a card at random, first card is special
var rnd = portablerand(decksize)
answer.append(deck[rnd / 4].remove(at: rnd % 4))

while answer.count < decksize {
// no matter what, we do not want to repeat this rank
let lastrank = answer.last!.rank
var myindices = [Int](deck.indices)
myindices.remove(at: lastrank - 1)
var totalchoice = 0
var maxbag = -1
for i in myindices {
totalchoice = totalchoice + deck[i].count
if maxbag == -1 || deck[i].count > deck[maxbag].count {
maxbag = i
}
}
if 2 * deck[maxbag].count >= totalchoice {
// we have to pick from maxbag
rnd = portablerand(deck[maxbag].count)
answer.append(deck[maxbag].remove(at: rnd))
} else {
// any bag will do
rnd = portablerand(totalchoice)
for i in myindices {
if rnd >= deck[i].count {
rnd = rnd - deck[i].count
} else {
answer.append(deck[i].remove(at: rnd))
break
}
}
}
}


for card in answer {
print(card)
}

这可以快速计算,并且相当公平,但遗憾的是并非公正。我怀疑可能很难在运行速度快的约束下生成“公平洗牌”。

关于arrays - 数组洗牌后不会出现重复的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42080624/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com