2

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?

Community
  • 1
  • 1
Legato
  • 609
  • 17
  • 24
  • interesting question which remind me of hashtable? have u done any code? – Kick Buttowski Jun 15 '14 at 22:54
  • Do you know upfront how many elements you'll need? – NPE Jun 15 '14 at 23:00
  • I don't actually have a specific number, I just noticed the aforementioned shortcomings of the way I was doing it, and was wondering, but for the sake of a response feel free to pick an arbitrary value. – Legato Jun 15 '14 at 23:07
  • @KickButtowski I wrote the code that reversed the array, as per the link given. Would you like that posted? I used images in the test. – Legato Jun 15 '14 at 23:23

2 Answers2

1

This is a known algorithm. What you need is a variation of the Knuth-Fisher–Yates shuffle http://en.wikipedia.org/wiki/Knuth_shuffle.

Add all the numbers to a collection. If all the numbers are sequential then just populate the collection with a for-loop

Repeat this until there's only one number in the collection:
    generate a random number using the length of the collection.
    remove the number from the collection.  

At this point there's only one element in the collection. So remove the only number from the collection.
Alexandre Santos
  • 8,170
  • 10
  • 42
  • 64
1

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:

Collections.shuffle(Arrays.asList(stack_ex));


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.

Legato
  • 609
  • 17
  • 24