0
0

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 3 years have passed since last update.

Flutter(Dart)で重複のない乱数を生成する

Last updated at Posted at 2020-12-09

##Flutter(Dart)で重複のない乱数を生成する
「ダステンフェルドのアルゴリズム」とか「フィッシャーイェーツのシャッフル」と言われているランダムシャッフル処理です。

[1,2,3,4,5] => [3,5,2,1,4] のような感じ

import 'dart:math';

class NumberShuffle {
  final rand = new Random();

  List<int> getShuffleList(int inputNum) {
    //順に格納された配列を用意
    List<int> list = List.generate(inputNum, (index) => index);

    for (int rest = inputNum - 1; rest >= 0; rest--) {
      //ランダムに選択
      int selectIndex = rand.nextInt(rest + 1);

      //一番最後と入れ替え
      int temp = list[selectIndex];
      list[selectIndex] = list[rest];
      list[rest] = temp;
    }

    return list;
  }
}

もしかしてライブラリがあったら教えていただけるとうれしいです。
 

##追記
これだけのことでしたね。

var list = [1,2,3,4,5];
list.shuffle();
print(list);

ライブラリではなかった…

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?