I want to retrieve elements from an array, but make it so if an element position was already chosen it wouldn't be duplicated. What would be the best and/or most readable way to do this?
The method I had in mind only works for numbers, and is limited when an element has a duplicate in another position. The closest I found was this: Java - generate Random range of specific numbers without duplication of those numbers - how to? but it didn't apply since I don't need all the elements in the array. Though it made me realize a possible 'solution' would be to shuffle and then iterate through the array for the amount I require, but I was wondering how else this could be done?
I didn't realize it immediately since it came to me while writing the OP, but the method I thought up actually meets all prerequesites:
First make sure to
Iterate your array, call the shuffle method then simply invoke indexes normally, here's an example using 4 Icons:
ImageIcon stack_ex = new ImageIcon; for (int i = 1; i < 12; i++) stack_ex[i - 1] = new ImageIcon("C:/Image_directory/" + i + ".jpg"); }
Shuffle the array:
Collections.shuffle(Arrays.asList(stack_ex)); JButton alpha = new JButton(stack_ex); JButton beta = new JButton(stack_ex); JButton gamma = new JButton(stack_ex); JButton delta = new JButton(stack_ex);
The four icon positions are always random and discrete.