List.shuffle() in Dart?

后端 未结 2 1402
天命终不由人
天命终不由人 2020-12-17 08:26

I\'m looking every where on the web (dart website, stackoverflow, forums, etc), and I can\'t find my answer.

So there is my problem: I need to write a function, that

相关标签:
2条回答
  • 2020-12-17 09:13

    Here is a basic shuffle function. Note that the resulting shuffle is not cryptographically strong. It uses Dart's Random class, which produces pseudorandom data not suitable for cryptographic use.

    import 'dart:math';
    
    List shuffle(List items) {
      var random = new Random();
    
      // Go through all elements.
      for (var i = items.length - 1; i > 0; i--) {
    
        // Pick a pseudorandom number according to the list length
        var n = random.nextInt(i + 1);
    
        var temp = items[i];
        items[i] = items[n];
        items[n] = temp;
      }
    
      return items;
    }
    
    main() {
      var items = ['foo', 'bar', 'baz', 'qux'];
    
      print(shuffle(items));
    }
    
    0 讨论(0)
  • 2020-12-17 09:14

    There is a shuffle method in the List class. The methods shuffles the list in place. You can call it without an argument or provide a random number generator instance:

    var list = ['a', 'b', 'c', 'd'];
    
    list.shuffle();
    
    print('$list');
    

    The collection package comes with a shuffle function/extension that also supports specifying a sub range to shuffle:

    void shuffle (
    List list,
    [int start = 0,
    int end]
    )
    
    0 讨论(0)
提交回复
热议问题