zashii-1434

Stats of My Life(おいしい人生を味わうために、コツコツとチャレンジしたことを書くブログ)

Java Script-Fisher-Yates shuffle

自分用メモです。

 

<!DOCTYPE html>
<html>
<head>
 
<script>
Array.prototype.shuffle = function () {

/*Fisher-Yatesというアルゴリズム*/
var i = this.length;
while (i) {
var j = Math.floor(Math.random() * i);
var t = this[--i];
this[i] = this[j];
this[j] = t;
}
return this;
}


function shuffle() {
var cards = [1,1,2,2,3,3,4,4,5,5,6,6];
cards.shuffle();

document.getElementById("result").textContent = cards.join(",");


}
</script>
</head>
<body>
<button onclick="shuffle()">shuffle</button>
<p id="result"></p>
</body>
</html>