0

I want to generate random coordinates from 0-5 (Row,Col) without any duplicates using for loops. Basically if the numbers (3,2), (3,4), (1,4), (3,4) are generated then (3,4) will not be utilized and a new random set will be looked for.

These are the methods that generate two random numbers and loads them into the array shootP[ ]

    int[] shootP = new int[2];

public static int shootRowP(int[] shootP)
{
    Random rn = new Random();
    shootP[0] = rn.nextInt(5)+1;//loads into ROW
    System.out.print("Row:"+(shootP[0]));
    return shootP[0]--;
}

public static int shootColP(int[] shootP,int[][]boardP)
{
    Random rn = new Random();
    shootP[1] = rn.nextInt(5)+1;//loads into Col
    System.out.print(" Column:"+(shootP[1])+"/n");
    return shootP[1]--;
}

I then want to have another method read in the values of shootP[0] and shootP[1] and check to see if those values were already used. Any suggestions?

  • Eclipse is just the development environment you are using - it is **not** a programming language. This question is nothing to do with using Eclipse. – greg-449 Dec 08 '16 at 08:00

1 Answers1

0

Since the number of possible coordinates (X,Y) is not too large, first build a list of all possible coordinates. Then, at each random pick, choose a random element in this list (i.e. rn.nextInt(current_list_length)), remove the element from the list and return it.

Notes:

  • You must do something (exception?) when the list is empty
  • You can also shuffle your list at initialization and at each draw, you pick and delete the first (or last) element. See here how to shuffle an array, for example.
  • Instead of a list, a stack (an array + an element counter) can do the trick.
Community
  • 1
  • 1
xhienne
  • 5,738
  • 1
  • 15
  • 34