Created
November 4, 2021 11:27
-
-
Save zwongeer/d03cc6f5de9803d80ecc397ec5c66741 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Iterator; | |
import java.util.Map; | |
import java.util.Random; | |
class UniqueInts implements Iterable<Integer> { | |
private int imin; | |
private int emax; | |
private Random rand; | |
private Map<Integer, Integer> trans; | |
private int dictsize; | |
private int num; | |
public UniqueInts(int imin, int emax, int num, Random rand) { | |
dictsize = num; | |
int half = (emax - imin + 1) / 2; | |
if (half < dictsize) | |
dictsize = (int)half; | |
trans = new HashMap<>(dictsize); | |
this.imin = imin; | |
this.emax = emax; | |
this.rand = rand; | |
this.num = num; | |
} | |
public UniqueInts(int imin, int emax, int num) { | |
this(imin, emax, num, new Random()); | |
} | |
@Override | |
public Iterator<Integer> iterator() { | |
return new Iterator<Integer>(){ | |
private int i = 0; | |
@Override | |
public boolean hasNext() { | |
return i < num; | |
} | |
@Override | |
public Integer next() { | |
int current = imin + i; | |
int r = rand.nextInt(emax - current) + current; | |
int right; | |
if (!trans.containsKey(r)) | |
right = r; | |
else | |
right = trans.get(r); | |
int left; | |
if (trans.containsKey(current)) { | |
left = trans.get(current); | |
trans.remove(current); | |
} | |
else | |
left = current; | |
if (r > current) | |
trans.put(r, left); | |
++i; | |
return right; | |
} | |
@Override | |
public void remove() { | |
throw new UnsupportedOperationException(); | |
} | |
}; | |
} | |
} | |
public class UniqueRandomInts { | |
public static void main(String[] args) { | |
UniqueInts iter = new UniqueInts(0, 10, 9); | |
for (int v : iter) { | |
System.out.print(v + " "); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment