admin管理员组文章数量:1401623
I'm trying to create a JavaScript card game and want to pick 5 cards without repetition:
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)]
How can I make sure that there is no repetition if I pick 5 cards?
I'm trying to create a JavaScript card game and want to pick 5 cards without repetition:
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)]
How can I make sure that there is no repetition if I pick 5 cards?
Share Improve this question edited Sep 19, 2013 at 12:06 Harsh Baid 7,2496 gold badges50 silver badges92 bronze badges asked Sep 19, 2013 at 11:54 Floor DreesFloor Drees 1185 bronze badges3 Answers
Reset to default 10Prepare an array of all 48 cards (are you missing Aces?)
Every time you pick a card, remove it from the array.
The next draw will be from the reduced array, so there can be no duplicates.
Alternative:
Start with the same array, then shuffle it. Take the first five cards.
You could also create a markerlist, where you put in the already used card!
var myGivenCards = {}
repeat that for every card:
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;
}
As others said, use a Fisher-Yates-Shuffle, then pick the first five:
var colors = ["hearts", "spades", "diamonds", "clubs"];
var values = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"];
// from http://jsfromhell./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));
本文标签: How to mix values in a JavaScript array without repetitionStack Overflow
版权声明:本文标题:How to mix values in a JavaScript array without repetition? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744309745a2599971.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论