アルゴリズム関数

文字列ランダム並べ替え

文字列をランダムに並べ替えます。
→文字列の並べ替えはこちら
文字列並べ替え
文字列逆順並べ替え
文字列ランダム並べ替え

ソースコード公開

<form>
<textarea id="before" placeholder="ちびまるこちゃん"></textarea>
<input type="button" id="button" value="並べ替える">
<input type="reset" id="reset" value="クリア">
<textarea id="after" placeholder="ちんこびちゃまる" readonly></textarea>
</form>
<script>
const button = document.getElementById('button');
button.addEventListener('click', function() {
  let array = document.getElementById("before").value.split('');
  let result = getFisherYatesShuffle(array).join('');
  document.getElementById("after").value = result;
});

/// <summary>
/// ランダム並べ替え
/// </summary>
/// <params name="arr">配列</params>
/// <returns>結果</returns>
function getFisherYatesShuffle(arr) {
  for (let i = arr.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
  return arr;
}
</script>

アルゴリズム解説

乱数を生成する方法は複数あります。

まず、最もシンプルに記述できるのが、ランダム関数を使用する方法。

<script>
button.addEventListener('click', function() {
  let str = document.getElementById("before").value;
  let result = str.split('').sort(function() {
    return Math.random() - 0.5;
  }).join('');
  document.getElementById("after").value = result;
});
</script>

ワンラインでコーディングすることもできます。

document.getElementById("after").value = document.getElementById("before").value.split('').sort(function() { return Math.random() - 0.5; }).join('');
小技:文字列の文字をランダムに並び替える - Qiita
非実用的でとてもどうでもいい小技'文字列'.split('').sort(() => .5 - Math.random() ).join('')example> 'L知っているか、死神はリンゴ…

ただし、結果には確率の偏りが生じます。

このページでは、よりランダム性の高い、Fisher-Yatesアルゴリズムを採用しました。

<script>
/// <summary>
/// ランダム並べ替え
/// </summary>
/// <params name="array">配列</params>
/// <returns>結果</returns>
function shuffle(array) {
  for (let i = array.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}
</script>
配列のシャッフル



コメント