0

I have an array that contains the int values 1, 2, and 3 and I want to randomly assign all of those values to three different variables (without repeating any of the values). This is what I've gotten so far, but when I tested it, it would sometimes duplicate one of the values.

Question: How can I randomly distribute all of the elements of an array to several different variables?

//method     
    public static double calculate(int randomVal[]){
            Random random = new Random();
            double randomAnswer = 0;
            for(int i = 0;i < randomVal.length; i++){
              randomAnswer = (randomVal[random.nextInt(randomVal.length)]);
            }
            return randomAnswer;   



//create array
 int[] randomVal = new int[] {1,2,3};

double solution1 = MathGame.calculate(randomVal);
double solution2 = MathGame.calculate(randomVal);
double solution3 = MathGame.calculate(randomVal);
  • see [this answer](http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array). After shuffling then you can assign to variables – Brandon Feb 20 '15 at 05:09

3 Answers3

1

If you can use an Integer[] then you might use Collections.shuffle(List<?>) and Arrays.asList(T...) and then Arrays.toString(Object[]) to display it like

Integer[] randomVal = new Integer[] { 1, 2, 3 };
Collections.shuffle(Arrays.asList(randomVal));
System.out.println(Arrays.toString(randomVal));
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • So after I do Collections.shuffle(Arrays.asList(randomVal)); I could then assign those three variables and it would work? –  Feb 20 '15 at 05:20
  • @Jordan `randomVal` is an array. You could read the three distinct values like `int a = randomVal[0]; int b = randomVal[1]; int c = randomVal[2];` (the interface you've defined doesn't appear to access the array with an index), also it's an array of `int`(s) not `double`(s). – Elliott Frisch Feb 20 '15 at 05:23
0

This is how you can shuffle an array of ints

void shuffle(int[] a) {
    Random rnd = new Random();
    for (int i = a.length; i > 1; i--) {
        int r = rnd.nextInt(i);
        int t = a[i - 1];
        a[i - 1] = a[r];
        a[r] = t;
    }
}

then just use its elements

    int[] a = { 1, 2, 3 };
    shuffle(a);
    double solution1 = a[0];
    double solution2 = a[1];
    double solution3 = a[2];
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

If you want to just let Java handle it and using a set as described here

Set<T> mySet = new HashSet<T>(Arrays.asList(someArray));

Iterator<T> it=mySet.iterator();

//assign variables using it.next();
Community
  • 1
  • 1
Droidekas
  • 3,464
  • 2
  • 26
  • 40