Rikupika
Rikupika

Reputation: 3

How can I get this random method to work?

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;
            }
        }
    }
}

Upvotes: 0

Views: 75

Answers (3)

Amit
Amit

Reputation: 381

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));
    }

Upvotes: 0

amit_183
amit_183

Reputation: 981

//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;
  }

Upvotes: 0

user180100
user180100

Reputation:

  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

Upvotes: 3

Related Questions