生成唯一的随机整数集

时间:2012-02-15 15:19:25

标签: java random duplicates

这是我第一次构建应用程序而且我遇到了问题。我制作此应用程序只生成随机数,有时它会向我显示两次数字。这不是我的目标,所以如何编程它会显示随机数而不重复?

这是我的代码btw:

    package rando.mizer;

    import java.util.Random;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;

    public class RandomizerFinalActivity extends Activity {
        /** Called when the activity is first created. */   
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Button buttonGenerate = (Button)findViewById(R.id.button1);
            final EditText aantalT= (EditText)findViewById(R.id.editText1);
            final EditText laagsteT = (EditText)findViewById(R.id.editText2);
            final EditText hoogsteT = (EditText)findViewById(R.id.editText3);
            final EditText uitvoerT = (EditText)findViewById(R.id.editText4); 



            buttonGenerate.setOnClickListener(new Button.OnClickListener(){

               public void onClick(View arg0) {
                    final int aantal = Integer.parseInt(aantalT.getText().toString());
                    final int laagste = Integer.parseInt(laagsteT.getText().toString());
                    final int hoogste = Integer.parseInt(hoogsteT.getText().toString());

                    uitvoerT.setText("");
                    Random r = new Random();

                    int aNumber;
                    String build = "";


                for(int i = 0; i < aantal; i++) {
                    aNumber = laagste + r.nextInt(hoogste + 1 - laagste);
                    build += aNumber + ",\n";
                }

                    uitvoerT.setText(build);


              }

            });
        }
    }

5 个答案:

答案 0 :(得分:1)

使用Collections.shuffle是一个好主意,但您不需要随机播放所有数字。使用起来会更有效:

// return nNumbers distinct values from low to (high - 1)
public List<Integer> getRandoms(int low, int high, int nNumbers) {
    int range = high - low;
    List<Integer> workArray = new ArrayList(range);
    for (Integer i = low; i < high; i++)
        workArray.add(i);

    // Put the chosen values at the start of the array one by one 
    // (and then do not touch the start of the array).
    int pseudoStartIndex = 0;
    while (pseudoStartIndex < nNumbers) {
        int randomIndex = pseudoStartIndex + 
                          random.nextInt(range - pseudoStartIndex); 
        Integer tempSwap = workArray.get(pseudoStartIndex);
        workArray.set(pseudoStartIndex, workArray.get(randomIndex));
        workArray.set(randomIndex, tempSwap);
        pseudoStartIndex++;
    }
    return workArray.subList(0, nNumbers);
}

它基本上是Fisher-Yates shuffle,但仅适用于少数元素。

答案 1 :(得分:0)

你的问题在于你总是使用相同的种子,因此生成相同数字的机会非常高,首先你需要了解生成一个纯随机数是不可能的,Java给你的是一个漂亮的体面的机制,但依赖种子。

通常的做法是使用当前日期时间(以毫秒为单位),如果你这样做:

new Random(System.currentTimeMillis())

你会发现你没有重复。您可以使用以下代码进行尝试:

public static void main (String... args){
   for (int i=0; i<10000; i++){
       try {
        Thread.sleep(100);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
       Random random = new Random(System.currentTimeMillis());
       System.out.println(random.nextInt());

   }
}

答案 2 :(得分:0)

您似乎正在尝试随机选择数字而不重复已知集合,例如在彩票中。如果集合不是太大,这种方法会起作用(请注意,如果计数大于数字量,它将失败)。

/** Will pick `count` numbers randomly from the set of numbers between
 * startNumber (included) and endNumber (excluded). */
public static Collection<Integer> randomPick(int startNumber, int endNumber, int count) {
    // Generate a list of all numbers from start to endNumber
    List<Integer> numbers = new ArrayList<Integer>();
    for(int i = startNumber; i < endNumber; i++) {
        numbers.add(i);
    }

    // Shuffle them
    Collections.shuffle(numbers);

    // Pick count items.
    return numbers.subList(0, count);
}

答案 3 :(得分:0)

如果您使用Random对象创建并初始化(使用种子)一次,而不是在每次调用Listener时创建随机数,那么它将不太可能有重复的数字。

答案 4 :(得分:-2)

import java.util.Set;

Set<Integer> mySet = new HashSet<Integer>(10); // do you know how many elements do you need?
boolean elementNotThere;
do {
    int myInt = r.nextInt(hoogste + 1 - laagste);
    elementNotThere = mySet.add(myInt);
} while ( ! elementNotThere );