Dart中的List.shuffle()? [英] List.shuffle() in Dart?

查看:605
本文介绍了Dart中的List.shuffle()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在网上寻找每个地方(飞镖网站,stackoverflow,论坛等),但找不到答案.

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 print a random sort of a list, witch is provided as an argument. : In dart as well.

我尝试使用地图,集合,列表...我尝试使用assert方法,使用sort方法,以及在Dart librabry上使用Math来研究随机方法...什么都做不了我想做的事.

I try with maps, with Sets, with list ... I try the method with assert, with sort, I look at random method with Math on dart librabry ... nothing can do what I wana do.

有人可以帮我吗?

以下是一些草稿:

var element03 = query('#exercice03');
  var uneliste03 = {'01':'Jean', '02':'Maximilien', '03':'Brigitte', '04':'Sonia', '05':'Jean-Pierre', '06':'Sandra'};
  var alluneliste03 = new Map.from(uneliste03);
  assert(uneliste03 != alluneliste03);
  print(alluneliste03);

  var ingredients = new Set();
  ingredients.addAll(['Jean', 'Maximilien', 'Brigitte', 'Sonia', 'Jean-Pierre', 'Sandra']);
  var alluneliste03 = new Map.from(ingredients);
  assert(ingredients != alluneliste03);
  //assert(ingredients.length == 4);

  print(ingredients);

  var fruits = <String>['bananas', 'apples', 'oranges'];
  fruits.sort();
  print(fruits);

推荐答案

这是基本的shuffle函数.请注意,由此产生的混洗在密码学上不强.它使用Dart的Random类,该类会生成不适合密码使用的伪随机数据.

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));
}

这篇关于Dart中的List.shuffle()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆