如何制作随机数模式生成器?

时间:2015-10-18 08:06:35

标签: java arrays random numbers generator

我的情况是我正在尝试找一个随机数模式生成器代码,但我似乎无法找到它。我需要使用“1”,“2”,“3”,“4”,“5”和“6”来创建一个随机模式,有4个数字,如1111,1264,2564等。我试过这个,但它不是工作

public static void computer() {
    List<Integer> template = Arrays.asList(1, 2, 3, 4, 5, 6);
    for (int i = 0; i < 10; ++i) {
        List<Integer> items = new ArrayList<Integer>(template);
            Collections.shuffle(items);
            System.out.println(items);

    }
}

3 个答案:

答案 0 :(得分:1)

试试这个:

Random r = new Random();
int number = 0;
int d = 1;

while (number < 1000) {

    // generate number between 1-6
    int num = r.nextInt(6) + 1;

    number += num * d;
    // increase the digit (units, tens, hundreds, thousands)
    d *= 10;
}

System.out.println(number);

答案 1 :(得分:0)

public static void computer() {
    List<Integer> template = Arrays.asList(1, 2, 3, 4, 5, 6);
    Random r = new Random();
    StringBuilder random = new StringBuilder();
    for (int i = 0; i < 4; ++i) {
       int create = r.nextInt(6);
       // find in array between 1-6 index
       int find = template.get(create);
       random.append(String.valueOf(find));
    }
    System.out.println(random);
}

答案 2 :(得分:0)

  Random r = new Random();
  String s = "";
  while(s.length() < 4)
  {
     int numpick = r.nextInt() % 6;
     if(numpick > 0)
        s += numpick;
  }

  return Integer.parseInt(s);

显然可以稍微刷一下,但我认为这是制定数字的最佳策略。