我正在慢慢地通过JavaScript工作,并遇到了Math.random()的问题。 我在MDN上读到,Math.random()总是以当前日期播种 - 我“相信”发生的事情是我的两个Math.random()调用发生得如此之快以至于它们返回的值基本相同。这是代码,这是纸牌游戏的开始。
var cards = new Array(null);
cards[0] = new Array("Ace of Spades","ace","A","spades","black");
cards[1] = new Array("Two of Spades","two","2","spades","black");
cards[2] = new Array("Three of Spades","three","3","spades","black");
// you get the idea ... full code on the JSFiddle below
cards[51] = new Array("King of Hearts","king","K","hearts","red");
// initialize variables
var cardsInHand = 5;
// variables to make the card drawing decrement work without touching original array
var restOfDeck = new Array(null);
restOfDeck = cards;
// initialize hands as a doubly-nested Arrays
var player1Hand = new Array(null);
var player2Hand = new Array(null);
// function to randomly "draw" the cards, decrementing the deck each time
for (var k = 0; k < cardsInHand; k++) {
player1Hand[k] = restOfDeck[(Math.floor(Math.random() * restOfDeck.length))];
restOfDeck.splice(restOfDeck.indexOf(player1Hand[k]), 1);
console.log((k + 1) + ' cards to Player 1');
player2Hand[k] = restOfDeck[(Math.floor(Math.random() * restOfDeck.length))];
restOfDeck.splice(restOfDeck.indexOf(player2Hand[k]), 1);
console.log((k + 1) + ' cards to Player 2');
}
// display hand
document.write('Player 1\'s Hand\: <br />');
for (var i = 0; i < cardsInHand; i++) {
document.write(player1Hand[i][0] + "<br />");
}
document.write('<br /><br />Player 2\'s Hand\: <br />');
for (var j = 0; j < cardsInHand; j++) {
document.write(player2Hand[j][0] + "<br />");
}
发生的事情是,在10张“发牌”牌中,总有两张牌“按顺序”(两张牌,然后是三张牌)。总是。我相信它与draw / decrement函数中的两个Math.random()调用有关,但我不确定如何返工。提前谢谢!
JSFiddle:http://jsfiddle.net/bjVCL/
答案 0 :(得分:0)
这只是工作中的简单概率。您不会看到相邻对的唯一时间是卡片值是否分布为......
因此,获得 no 相邻值的手的几率为(13/13)*(11 * 13)*(9 * 13)*(7/13)*(5 / 13)=微不足道的 12%
(注意:'我的stastics有点生疏,所以我可能没有这么正确,但它足够接近,让你感觉到你所看到的效果。)