5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Typescript で配列をシャッフルする

Last updated at Posted at 2019-03-20

Typescript で配列をシャッフルしたかったので Fisher–Yates shuffle を実装した話。

調べても ts 版がなかったのでメモ的な。

実装と言っても関数を書いただけ…(簡単だからわざわざ記事とか無いのかも)

shuffle.ts
export default function shuffle<T>(array: T[]) {
  const out = Array.from(array);
  for (let i = out.length - 1; i > 0; i--) {
    const r = Math.floor(Math.random() * (i + 1));
    const tmp = out[i];
    out[i] = out[r];
    out[r] = tmp;
  }
  return out;
}

swap の部分は es6 だと 1 行で書ける

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?