I need a very fast mechanism for iterating in random order through the entries in a Hashtable. The number of entries in the table will typically be around 10 and will never be more than 20. Presently I'm doing the following code to randomize the order of the keys by picking 16 random, unique Doubles and sorting on that, but am thinking it isn't the most efficient solution:
TreeMap<Double, String> seeds = new TreeMap<Double, String>();
// These go in random order
Enumeration<String> keys = content.keys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
Double seedKey = new Double(Math.random());
while (seeds.get(seedKey) != null)
seedKey = new Double(Math.random());
seeds.put(seedKey, key);
}
// Now enumerate through the seeds
Set<Double> keys2 = seeds.keySet();
for (Double d : keys2) {
String key = seeds.get(d);
String value = content.get( key );
..................
One suggestion I was given was to iterate over the key array from 0 to size-2 and swap element i with element random(from i+1 to size-1). It's linear at least. Looking forward to suggestions!
Aucun commentaire:
Enregistrer un commentaire