I've created a list of 8 items, and I want Java to pick one at (psuedo)random and then remove it from the list. After that, I want it to repeat the process until it gets down to one item.
Here's the code
package randomlist;
import java.util.Random;
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.concurrent.ThreadLocalRandom;
public class output {
public static void main(String[] args) throws InterruptedException, AWTException {
// TODO Auto-generated method stub
for (int i = 0; i <1 ; i++) {
Random generate = ThreadLocalRandom.current();
String[] color = {"Black", "White", "Red", "Blue", "Green", "Mint", "Rose", "Purple" };
String colorsprint = colors[generate.nextInt(colors.length)];
System.out.println(colorsprint);}}}
Currently, it outputs its choice as expected. What I want it to do is to output its choice and then move on to another list with the 7 remaining items, but I don't want to have to manually code 256 different lists to nest it with "if a then pick from b, etc.
So far, all the code I've tried has resulted in a compiler error or the program simply not running. I've even gotten it to work as a nested list, outputting from another list based on its first choice, but that's not working here.
I'm sure it's something I've already tried and just messed up, but I've run out of my own knowledge.
EDIT: I guess I should clarify; I know how to solve the issue, I just am hoping there's a more efficient way than doing it all manually with CTRL-C/CTRL-V; it'll make for extremely unwieldy code if I have to make 256 lists for the permutations of 8.
Instead of implementing the picking as described in the question, it is more efficient to shuffle the array and then print the elements.
String[] colors = {"Black", "White", "Red", "Blue", "Green", "Mint", "Rose", "Purple" };
Collections.shuffle(Arrays.asList(colors));
for (var color : colors) {
System.out.println(color);
}
The algorithm described could be implemented with a List
, though.
List<String> colors = new ArrayList<>(List.of("Black", "White", "Red", "Blue", "Green", "Mint", "Rose", "Purple"));
while (!colors.isEmpty()) {
System.out.println(colors.remove(
ThreadLocalRandom.current().nextInt(colors.size())));
}
To print the remaining elements after removing instead:
List<String> colors = new ArrayList<>(List.of("Black", "White", "Red", "Blue", "Green", "Mint", "Rose", "Purple"));
while (colors.size() > 1) {
colors.remove(ThreadLocalRandom.current().nextInt(colors.size()));
System.out.println(colors);
}