如何生成6个唯一的java数字

时间:2013-01-04 14:15:20

标签: java

  

可能重复:
  Generating Unique Random Numbers in Java

代码将从一个范围生成6个随机数,但需要它们是独一无二的,融化我的大脑任何指针都将非常感激

import java.util.Random;
import java.util.Arrays;
public class numbers
{
private int[] lottoNumbers;
private int nextInt;
private Random r;

public numbers()
{
    lottoNumbers = new int [6];
    r = new Random();
    nextInt();
}
public void nextInt()
{
    System.out.print("***     ");
    for (int i = 0; i < lottoNumbers.length; i++)
    {
        lottoNumbers[i] = r.nextInt(49) +1;
        System.out.print(" " + lottoNumbers[i]);
    }
    System.out.println("     ***");
}
}

7 个答案:

答案 0 :(得分:6)

对于六个数字中的每一个,您需要将其与已生成的数字进行比较。如果它们与其中任何一个相同,你需要继续尝试。

答案 1 :(得分:4)

你可以简单地使用shuffle方法并在改组后返回6个第一个元素:

// Create the list of possible numbers
List<Integer> numbers = new ArrayList<Integer>(50);
for(int i = 1 ; i <= 50 ; ++i) {
    numbers.add(i); 
}
// Shuffle the list
Collections.shuffle(numbers);

// Print the numbers
int count = 0;
for(int number : numbers) {
    System.out.println("Random number " + count + ": " + number);
    ++count; // break if count == 6?
}

这种方法的优点是它以线性时间(shuffle所用的时间)运行。您可以避免选择x次(x可能非常大)一个元素,并检查它是否已被选中!

答案 2 :(得分:2)

您需要添加一个循环,检查您已添加的项目中是否存在数字。定义boolean变量,将其设置为false,然后通过循环将现有数字与新生成的数字进行比较。如果您看到重复内容,请将boolean设置为true。循环结束后,请检查boolean以查看是否必须添加新号码。

int i = 0;
do {
    int next = r.nextInt(49) + 1;
    boolean seen = false;
    for (int j = 0 ; j != i ; j++) {
        if (lottoNumbers[j] == next) {
            seen = true;
            break;
        }
    }
    if (!seen) {
        lottoNumbers[i++] = next;
        System.out.print(" " + next);
    }
} while (i != lottoNumbers.length);

更好的解决方案是使用Set<Integer>,但这可能是现阶段的一个高级主题。

答案 3 :(得分:1)

只需使用Set(感谢@dty改进版本!):

private static final Random RND = new Random();
private static final int COUNT = 6;

public int[] getRandomNumbers()
{
    final Set<Integer> set = new HashSet<Integer>(COUNT);

    /*
     * This works: .add() will not add the same element twice. As such, we just
     * need to check that the set has the expected size.
     */
    while (set.size() < COUNT)
        set.add(RND.nextInt());

    return set.toArray(new int[COUNT]);
}

答案 4 :(得分:0)

public void nextInt()
{
    System.out.print("***     ");
    for (int i = 0; i < lottoNumbers.length; i++)
    {
        int temp;

        // check random int doesn't already exist (embedded assignment below)           
        // NOTE: while loop has empty body, note {} in line below
        while (Arrays.asList(lottoNumbers).contains(temp = r.nextInt(49)+1)){}

        lottoNumbers[i] = temp;
        System.out.print(" " + lottoNumbers[i]);
    }
    System.out.println("     ***");
}

答案 5 :(得分:0)

我喜欢set方法,但是这个例子可以有点拉伸

private static final Random RND = new Random();

public static Set<Integer> getRandomNumbers(int count) {
    final Set<Integer> set = new HashSet<>(count);
    while (set.size() < count) {
      set.add(RND.nextInt());
    }
    return set;
}

答案 6 :(得分:0)

这样怎么样?

package rabdomnumbers;

    import java.util.ArrayList;
    import java.util.List;

    public class RabdomNumbers {
    public static int SIZE = 6;

      public static void main(String[] args) {
        Number[] numbers = new Number[SIZE];
        // set an array
    for (int x = 0; x < SIZE; x++) {
      numbers[x] = new Number();
    }
    // sort an array
    for (int x = 0; x < SIZE-1; x++) {
      for (int y = x + 1; y < SIZE; y++) {
        if (numbers[x].getNumber() > numbers[y].getNumber()) {
          Number buf = numbers[x];
          numbers[x] = numbers[y];
          numbers[y] = buf;
        }
      }
    }
    // print an array
    for (int x = 0; x < SIZE; x++) {
      System.out.println("" + numbers[x].getIndex());
    }
  }
}

Number是一个简单的类:

package rabdomnumbers;

import java.util.Random;

public class Number {
  private int index = 0;
  private int number = 0;
  private static int count = 0;
  private final static Random RND = new Random();

  public int getIndex() {
    return index;
  } 

  public int getNumber() {
    return number;
  }

  public Number() {
    index = count++;
    number = RND.nextInt();
  }
}