重複しないランダム整数の作成
code:html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>タイトル</title>
<!-- JQuaryの追加 -->
<style>
/* カード設定 CSS */
.card{
/* boxのサイズを指定 */
width: 8em;
height: 10em;
/* boxの色をskyblueに指定 */
background:skyblue;
/* boxの上のカーソルを指マークに指定 */
cursor: pointer;
/* boxの外側の余白を指定 */
margin: 1em 1em;
/* 中央にテキストを表示 */
text-align: center;
/* 行の高さを設定 */
line-height: 10;
}
/*要素を横並びにする*/
.flexset{
display: flex;
}
</style>
</head>
<body>
<div class = "flexset">
<div class = "card" id="card4">card1</div> <div class = "card" id="card5">card2</div> <div class = "card" id="cardtest">card3</div> <div class = "card" id="card7">card4</div>
</div>
<script>
window.onload = function () {
/**
* @brief 配列をFisher-Yatesアルゴリズムを使ってシャッフルします。
*
* @param array シャッフルする配列
* @return シャッフルされた配列
*/
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arrayi, arrayj] = [arrayj, arrayi]; }
return array;
}
/**
* @brief 指定された範囲内で重複しない乱数をシャッフルにより生成します。
*
* @param min 乱数の最小値
* @param max 乱数の最大値
* @param count 生成する乱数の個数
* @return 指定された範囲内で重複しない乱数の配列
* @throws エラー 範囲内のユニークな数が十分でない場合にスローされます
*/
function generateUniqueRandomNumbersUsingShuffle(min, max, count) {
const array = Array.from({ length: max - min + 1 }, (_, i) => i + min);
const shuffledArray = shuffleArray(array);
return shuffledArray.slice(0, count);
}
// 使用例
const uniqueRandomNumbersUsingShuffle = generateUniqueRandomNumbersUsingShuffle(1, 10, 10);
console.log(uniqueRandomNumbersUsingShuffle);
}
</script>
</body>
</html>
解説(AI)