Legato Legato - 1 year ago 83
Java Question

retrieving random elements in an array without duplicating positions

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?

Answer Source

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

import java.util.Collections;

Iterate your array, call the shuffle method then simply invoke indexes normally, here's an example using 4 Icons:

ImageIcon[] stack_ex = new ImageIcon[11];
for (int i = 1; i < 12; i++)     
     stack_ex[i - 1] = new ImageIcon("C:/Image_directory/" + i + ".jpg");

Shuffle the array:


JButton alpha = new JButton(stack_ex[0]);
JButton beta = new JButton(stack_ex[1]);
JButton gamma = new JButton(stack_ex[2]);
JButton delta = new JButton(stack_ex[3]);

The four icon positions are always random and discrete.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download