Skip to content

Commit 3ea012b

Browse files
author
cureprotocols
committed
Fix: add validation for sampleSize exceeding stream length
1 parent 57863bb commit 3ea012b

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

Diff for: src/main/java/com/thealgorithms/randomized/ReservoirSampling.java

+4
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ public class ReservoirSampling {
2626
* @return A list containing k randomly selected elements.
2727
*/
2828
public static List<Integer> sample(int[] stream, int sampleSize) {
29+
if (sampleSize > stream.length) {
30+
throw new IllegalArgumentException("Sample size cannot exceed stream size.");
31+
}
32+
2933
List<Integer> reservoir = new ArrayList<>(sampleSize);
3034
Random rand = new Random();
3135

0 commit comments

Comments
 (0)