|
| 1 | +package com.thealgorithms.randomized; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.*; |
| 4 | + |
| 5 | +import java.util.Arrays; |
| 6 | +import java.util.List; |
| 7 | +import org.junit.jupiter.api.Test; |
| 8 | + |
| 9 | +public class ReservoirSamplingTest { |
| 10 | + |
| 11 | + @Test |
| 12 | + public void testSampleSizeEqualsStreamLength() { |
| 13 | + int[] stream = {1, 2, 3, 4, 5}; |
| 14 | + int sampleSize = 5; |
| 15 | + |
| 16 | + List<Integer> result = ReservoirSampling.sample(stream, sampleSize); |
| 17 | + |
| 18 | + assertEquals(sampleSize, result.size()); |
| 19 | + assertTrue(Arrays.stream(stream).allMatch(result::contains)); |
| 20 | + } |
| 21 | + |
| 22 | + @Test |
| 23 | + public void testSampleSizeLessThanStreamLength() { |
| 24 | + int[] stream = {10, 20, 30, 40, 50, 60}; |
| 25 | + int sampleSize = 3; |
| 26 | + |
| 27 | + List<Integer> result = ReservoirSampling.sample(stream, sampleSize); |
| 28 | + |
| 29 | + assertEquals(sampleSize, result.size()); |
| 30 | + for (int value : result) { |
| 31 | + assertTrue(Arrays.stream(stream).anyMatch(x -> x == value)); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + @Test |
| 36 | + public void testSampleSizeGreaterThanStreamLengthThrowsException() { |
| 37 | + int[] stream = {1, 2, 3}; |
| 38 | + |
| 39 | + Exception exception = assertThrows(IllegalArgumentException.class, () -> { |
| 40 | + ReservoirSampling.sample(stream, 5); |
| 41 | + }); |
| 42 | + |
| 43 | + assertEquals("Sample size cannot exceed stream size.", exception.getMessage()); |
| 44 | + } |
| 45 | +} |
0 commit comments