-1

I need to get the numbers 0-11 in a random order and make sure each number is only gotten once. It is still sending same numbers into my Line2 class though. How do I make sure that the int variable lineChoice is completely different every time? My problem is the if/else is not properly making sure that I don't send an already selected lineChoice to my Line2 class.

for(int i = 0; i < 12; i++){
        //get a random line choice 0-11
        lineChoice = (int)(Math.random() * 11); //0-11;
        //if that number was already chosen
        //get a new random number and add it to the array
        if(randomNumbers.contains(lineChoice)){
            lineChoice = (int)(Math.random() * 11); //0-11;
            randomNumbers.add(lineChoice);
        }else{
            //if not already in array, add to array
            randomNumbers.add(lineChoice);
        } 
        //make a Line based on the random lineChoice number
        line = new Line2(lineChoice);
        //add the line to the string poem
        poem += "\n" + line + "\n\n\n";                        
    } 

3 Answers3

0

You can create a List of Int from 1 to 11, and then randomize it.

 List<Integer> ints = IntStream.range(1,12).boxed().collect(Collectors.toList());
        Collections.shuffle(ints);
        System.out.println(ints);

ggr
  • 294
  • 1
  • 9
0

Here is the recommended way of doing it.

int [] nums = {0,1,2,3,4,5,6,7,8,9,10,11};

for (int i = nums.length-1; i >= 0; i--) {
    int s = (int)(Math.random()*(i+1));
    System.out.println(nums[s]); // here is where you get your number
    nums[s] = nums[i];
}  

or if you just want to shuffle the array.

 for (int i = nums.length-1; i >= 0; i--) {
    int s = (int)(Math.random()*(i+1));
    int t = nums[s];
    nums[s] = nums[i];
    nums[i] = t;
}

WJS
  • 36,363
  • 4
  • 24
  • 39
0

You need an array to do so,

Follow the following code, you just need to generate 11 (out of 12) random numbers in total. The last number will be selected automatically.

int[] rn = new int[12];

for(int i=0; i<12; i++) rn[i]=i;   // 0 to 11

Random rNumber = new Random();

int t, z;

for(int i=11; i>0; i--) {

    z = rNumber.nextInt(i+1);

    t = rn[i];
    rn[i] = rn[z];
    rn[z] = t;

}

System.out.println(Arrays.toString(rn)); 
abhimanyue
  • 196
  • 1
  • 12