如何在 JavaScript 数组中混合值而不重复?

8
我正在尝试创建一款JavaScript纸牌游戏,并希望在没有重复的情况下选择5张牌:
var colors = ["hearts", "spades", "diamonds", "clubs" ];
var values = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

color = colors[parseInt(Math.random()*colors.length,10)]
value = values[parseInt(Math.random()*values.length,10)]

如何确保在抽取5张牌时不出现重复的情况?
3个回答

10

准备一个包含所有48张牌的数组(是否缺少A?)

每次抽取一张牌后,将其从数组中移除。

下一次抽牌将从已经减少的数组中进行,因此不会有重复的牌。

另一种方法:

从同样的数组开始,然后打乱顺序。选出前五张牌。


我会选择第二种方法(洗牌数组)- Fisher-Yates-Shuffle可以解决这个问题。http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle - Gregor

3
您可以创建一个标记列表,在其中输入已经使用的卡片!
var myGivenCards = {}

对每张卡都重复上述步骤:

color = colors[parseInt(Math.random()*colors.length,10)]
value = values[parseInt(Math.random()*values.length,10)]
if (typeof(myGivenCards[color+values])==='undefined') {
  //not used
  myGivenCards[color+values] = true;
}

你为什么要使用 parseInt?将浮点数转换为整数的正常方法是使用 Math.floor(或 ceilround),而不是将其转换为字符串并解析它。请不要这样做,这是一种不好的做法。 - AJMansfield

2

正如其他人所说,使用Fisher-Yates-Shuffle算法,然后选择前五个:

 var colors = ["hearts", "spades", "diamonds", "clubs"];
 var values = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];

 // from http://jsfromhell.com/array/shuffle by Jonas Raoni Soares Silva
 function shuffle(o) { //v1.0
     for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
     return o;
 };

 var cards = [];
 for (var j = 0; j < colors.length; j++) {
     for (var i = 0; i < values.length; i++) {
         cards.push(colors[j] + values[i]);
     }
 }
 shuffle(cards);
 console.log(cards.slice(0, 5));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接