0

I have a game that displays patterns on the screen based off order. I don't want this order to be very strict to one order like 1 2 3 4 5 6 I would like the order to be more random. So I am trying to create a method that will generate a random order from 1-6. I tried to create a method that would do so but I failed. Could anyone help me out with that.

P.s. This is in java btw.

public static Random rand = new Random();

public static int[] array = new int[]{0,0,0,0,0,0};

public static void main(String[] args)
{
    for(int i =0;i<6;i++)
    {
        for (int a =0;a<6;a++)
        {
            array[i] = rand.nextInt(6)+1;
            while(array[i] == array[a])
            {
                array[i] = rand.nextInt(6)+1;
            }
        }
    }
}
Rikupika
  • 3
  • 2
  • 2
    Step 1. Post relevant code you wrote. – Sterling Archer Dec 24 '13 at 05:59
  • Why do you need so many loops? – PakkuDon Dec 24 '13 at 06:03
  • I did it to check and see if the number i just generated is equal to another number already in the array – Rikupika Dec 24 '13 at 06:03
  • @user3131533 You're looking for a permutation. http://stackoverflow.com/q/4240080/279982 might help. – atoMerz Dec 24 '13 at 06:10
  • 1
    I will tell you an issue with your approach... how do you ensure that the new random number you generated is not already in the list... you loop again... but you cannot keep on doing it all the time.. Hence, better approach is to use collections – AurA Dec 24 '13 at 06:13

3 Answers3

3
  1. create a list of 1-6
  2. use Collections.shuffle() on it
  3. use this list

Sample code:

final List<Integer> list16 = Lists.newArrayList(1,2,3,4,5,6); // guava Lists
Collections.shuffle(list16);
// use list16

or without guava:

final List<Integer> list16 = new ArrayList<Integer>();
for (int i = 1; i < 7; i++) {
    list16.add(i);
}
Collections.shuffle(list16);
// use list16
0
//your no.array say a[6]={0,0,0,0,0,0}

 boolean flag=true;
 int temp=0;
 for(int i=0;i<6;i++)
 {
   while(flag==true)
   {
    temp=rand.nextInt(6);
    if(a[temp]==0)
     {
      array[i] = temp+1; 
      a[temp]=1;
      flag=false;
     }


   }
   flag=true;
  }
amit_183
  • 961
  • 3
  • 19
  • 36
0
int num = 6;
    ArrayList<Integer> randomList = new ArrayList<Integer>(); 
    Random rand = new Random();
    for (int i = 0; i < 6; i++) {
        randomList.add(rand.nextInt(6));
    }
     for (int i = 0; i < randomList.size(); i++) {
        System.out.println("numbers  "+randomList.get(i));
    }
Amit
  • 391
  • 3
  • 15