I want to create 12 instantiations of a class and pass a random value as its parameter. The random values should only range from 1 to 6 BUT I need each value from the range to be distributed twice among the 12 instances of the class.
The constructor of the Class is as follows:
Die(int numSide){
this.numside = numSide;
}
Basically, I want to create 12 instances of dice with 2 of each side, sort of, as a result of a tossing.
CodePudding user response:
Add the numbers 1 to 6, twice to an ArrayList. Now pick a random index from that last and pass that to your Die constructor. Remove that index from the pool so it doesn't get used again.
Something like:
public static void main( String [] args) {
List<Die> dice = new ArrayList<Die>();
List<Integer> pool = new ArrayList<Integer>();
for(int i=1; i<=2; i ) {
for(int num=1; num<=6; num ) {
pool.add(num);
}
}
while (pool.size() > 0) {
int index = (int)(Math.random() * pool.size());
dice.add(new Die(pool.get(index)));
pool.remove(index);
}
for(Die d : dice) {
System.out.println(d.numside);
}
}
My output:
2
3
3
1
4
6
5
6
4
5
2
1
An alternative approach would be to add the Die instances directly to the Dice arraylist from the nested for loops, then simply pull a random instance from that list and remove it. Same concept as the pool, just depends on whether you need to use and/or keep that random order of Die instances for something else.
CodePudding user response:
Your Question is confused. So I will focus on:
pass a random value
…
range from 1 to 6 BUT I need each value from the range to be distributed twice
IntStream
You can use IntStream
to generate numbers.
Put together two streams of 1-6 inclusive. Generate an array from their output. Shuffle that array. Loop that array to get each int
value.
int[] oneThruSixTwice =
IntStream.concat
(
IntStream.rangeClosed( 1 , 6 ) ,
IntStream.rangeClosed( 1 , 6 )
)
.toArray() ;
Collections.shuffle( oneThruSixTwice ) ;
for( int x : oneThruSixTwice )
{
…
}