Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate 6 different numbers from 1 to 10 in Java

Tags:

java

I wrote down my code at first and then it cannot ensure that it is 6 different number.

public class JavaTest{
public static void main(String[] args){
    int[] list = new int[6];
    int number = (int)(Math.random() * 10 + 1);

    for (int i = 0; i < list.length; i++){
        list[i] = number;
        number = (int)(Math.random() * 10 + 1);
        for (int j = 1; j < i; j++){
            number = (int)(Math.random() * 10 + 1);
            if (number == list[j])
                number = (int)(Math.random() * 10 + 1);
        }
    }

    for (int i = 0; i < list.length; i++){
        System.out.print(list[i] + " ");
    }
}
}

I think something wrong with my inner for loop j, but I don't know how to improve it. Can anyone help me modify it? Thanks a lot!!

like image 429
yolam Avatar asked Dec 14 '22 15:12

yolam


1 Answers

You could possibly do something like:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Collections.shuffle(list);

And then take the 6 first numbers.

Without using collections:

int[] list = new int[6];
boolean[] used = new boolean[10];
for (int i = 0; i < 6; i++) {
    int number = (int) ((10 - i) * Math.random());
    for (int a = 0; a <= number; a++) {
        if (used[a]) {
            number++;
        }
    }
    list[i] = number + 1;
    used[number] = true;
}
like image 120
Bubletan Avatar answered Jan 09 '23 01:01

Bubletan