Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplified and a bit more optimized solution #154

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 5 additions & 24 deletions epi_judge_java_solutions/epi/RandomSubset.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,32 +17,13 @@ public class RandomSubset {

// Returns a random k-sized subset of {0, 1, ..., n - 1}.
public static List<Integer> randomSubset(int n, int k) {

Map<Integer, Integer> changedElements = new HashMap<>();
Random randIdxGen = new Random();
for (int i = 0; i < k; ++i) {
// Generate random int in [i, n - 1].
int randIdx = i + randIdxGen.nextInt(n - i);
Integer ptr1 = changedElements.get(randIdx);
Integer ptr2 = changedElements.get(i);
if (ptr1 == null && ptr2 == null) {
changedElements.put(randIdx, i);
changedElements.put(i, randIdx);
} else if (ptr1 == null && ptr2 != null) {
changedElements.put(randIdx, ptr2);
changedElements.put(i, randIdx);
} else if (ptr1 != null && ptr2 == null) {
changedElements.put(i, ptr1);
changedElements.put(randIdx, i);
} else {
changedElements.put(i, ptr1);
changedElements.put(randIdx, ptr2);
}
}

List<Integer> result = new ArrayList<>(k);
HashMap<Integer,Integer> changedElements = new HashMap<>();
Random randIdxGen = new Random();
for (int i = 0; i < k; ++i) {
result.add(changedElements.get(i));
int randIdx = i + randIdxGen.nextInt(n-i);
result.add(changedElements.getOrDefault(randIdx,randIdx));
changedElements.put(randIdx,changedElements.getOrDefault(i,i));
}
return result;
}
Expand Down