在数组随机播放后没有重复结果

时间:2017-02-07 02:22:58

标签: arrays swift string for-loop append

基本上,我有一个洗牌的数组。阵列是一副卡片:

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♥,2♦,2♣。

任何帮助表示赞赏!谢谢!

1 个答案:

答案 0 :(得分:0)

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

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)
}

这可以快速计算,并且相当公平,但不是无偏见的。我怀疑可能很难产生一个公平的洗牌&#34;你的约束快速运行。