随机数不是很随机

随机数不是很随机

本文介绍了Android:随机数不是很随机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 android 编写一个单词学习应用程序.

I am writing a word-learning application for android.

我使用的随机词:

Random rnd = new Random();
final int rnd.nextInt(WordsNumber);

为了获得随机方向(显示单词或显示翻译),我使用:

To get random direction (show word or show translation) I use:

Random rnd = new Random();
final boolean dir.nextBoolean();

但我看到,一个词不是均匀分布的.我正在用 17 个单词测试该应用程序.有些单词显示 10 次,有些单词只显示一次.同样的问题是方向.经常发生,连续第五个时间方向相同.

But I see, that a words are not uniformly distributed.I'm testing the application with 17 words.Some words are shown 10 times, some are shown only once.The same problem is with direction. It often happens, for the fifth consecutive time direction is the same.

也许有人知道,如何让词的分布更均等?

Maybe someone know, how to make distribution of words more equal?

UPD:我写了一个测试应用程序.它在按钮点击时生成新号码:

UPD:I've written a test application. It generates new number on button click:

public class About extends Activity
{
  final int N = 10;
  int[] results;
  Random rnd;
  int total;

  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_about);

    results = new int[N];
    for (int i = 0; i < N; i++)
    {
      results[i] = 0;
    }

    rnd = new Random();
    total = 0;
  }

  public void GenerateNumber(View view)
  {
    int number = rnd.nextInt(N);
    results[number]++;
    total++;

    String output = new String();
    TextView txt = (TextView)findViewById(R.id.text1);

    output += "Total numbers: " + String.valueOf(total) + "\n";
    for (int i = 0; i < N; i++)
    {
      output += String.valueOf(i) + ": " + String.valueOf(results[i]) + "\n";
    }
    txt.setText(output);
  }
}

测试结果如下:

也许,当 N=10000 时,它会相等......但对于我的应用程序来说,这是一个可怜的安慰.

Maybe, with N=10000 it will be equal... But for my application it's a poor consolation.

推荐答案

A shuffling algorithm,Geobits 提出了一个很好的解决方案.

A shuffling algorithm, proposed by Geobits is good solution.

但这是更简单的方法.我决定制作一系列最近的单词.存储 6-8 个最后的话足以解决这个问题.

But it is more simple way.I've decided to make array of recent words. Store 6-8 last words is enough for fixing this problem.

这篇关于Android:随机数不是很随机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:57