user2375038 - 1 year ago 86

Java Question

I'm trying to create a method that takes in 3 int arrays and prints out one element from each array until all the elements of all three arrays have been printed at least once. The first array has 10 elements, the second has 7, and the third has 2. The elements are selected and printed at random. Any help would be appreciated. The idea is to see how many iterations it would take to print out all the elements at least once. I don't know the conditions to set for

a large scale iteration like this. My code so far (with just one array as a parameter):

`import java.util.*;`

public class calculateAverage{

private static int[] x = new int[]{1,2,3,4,5,6,7,8,9,10};

private static int[] y = new int[]{1,2,3,4,5,6,7};

private static int[] z = new int[]{1,2};

public static void main(String[] args){

calculate(x);

}

public static void calculate(int a[]){

Random random = new Random();

for(int i = 0;i < a.length; i++){

System.out.print(a[random.nextInt(a.length)] + " ");

}

System.out.println();

}

}

code output:

7 2 4 1 8 10 3 10 7 3

Answer Source

Solution for one array:

```
public static int calculate(int a[]){
Random random = new Random();
HashSet<Integer> remaining = new HashSet<Integer>();
for (int i = 0; i < a.length; i++) {
remaining.add(i);
}
int i = 0;
while (!remaining.isEmpty()) {
int index = random.nextInt(a.length);
System.out.print(a[index] + " ");
remaining.remove(index);
i++;
}
System.out.println();
System.out.println("Finished after " + i + " iterations.");
return i;
}
```