Fisher-Yates shuffleで配列シャッフル [js/ts/php]
2022-06-196 min read
目次
概要
ts/js/php で配列をシャッフルする際の実装メモです。
配列のシャッフルにはFisher-Yates shuffleを利用しました。
ソース
typescript
const shuffleArr = (src: number[]): number[] => {
const dst = src.slice();
let i = src.length;
while (i > 0) {
i--;
const j = Math.floor(Math.random() * (i + 1));
[dst[i], dst[j]] = [dst[j], dst[i]];
}
return dst;
};
console.log(shuffleArr([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
// [ 4, 8, 6, 0, 2, 1, 9, 7, 3, 5 ]
js
const shuffleArr = (src) => {
const dst = src.slice();
let i = src.length;
while (i > 0) {
i--;
const j = Math.floor(Math.random() * (i + 1));
[dst[i], dst[j]] = [dst[j], dst[i]];
}
return dst;
};
php
function shuffleArr(array $src)
{
$i = count($src);
while ($i > 0) {
$i--;
$j = random_int(0, $i + 1);
[$src[$i], $src[$j]] = [$src[$j], $src[$i]];
}
return $src;
}
echo(implode(",", shuffleArr([0,1,2,3,4,5,6,7,8,9])));
参考にしたサイト
Recommends
New Posts
Hot posts!
Date
Tags
(110)
(54)
(54)
(47)
(45)
(36)
(30)
(29)
(24)
(24)
(22)
(21)
(21)
(20)
(19)
(17)
(16)
(16)
(15)
(14)
(12)
(12)
(12)
(12)
(12)
(12)
(11)
(10)
(10)
(10)
(10)
(10)
(9)
(9)
(8)
(8)
(8)
(8)
(7)
(7)
(6)
(6)
(6)
(6)
(6)
(5)
(5)
(5)
(5)
(4)
Author