|
| 1 | +package com.thealgorithms.randomized; |
| 2 | + |
| 3 | +import java.util.Random; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.List; |
| 6 | + |
| 7 | +/** |
| 8 | + * Reservoir Sampling Algorithm |
| 9 | + * |
| 10 | + * Use Case: |
| 11 | + * - Efficient for selecting k random items from a stream of unknown size |
| 12 | + * - Used in streaming systems, big data, and memory-limited environments |
| 13 | + * |
| 14 | + * Time Complexity: O(n) |
| 15 | + * Space Complexity: O(k) |
| 16 | + * |
| 17 | + * Author: Michael Alexander Montoya (@cureprotocols) |
| 18 | + */ |
| 19 | +public class ReservoirSampling { |
| 20 | + |
| 21 | + /** |
| 22 | + * Selects k random elements from a stream using reservoir sampling. |
| 23 | + * |
| 24 | + * @param stream The input stream as an array of integers. |
| 25 | + * @param sampleSize The number of elements to sample. |
| 26 | + * @return A list containing k randomly selected elements. |
| 27 | + */ |
| 28 | + public static List<Integer> sample(int[] stream, int sampleSize) { |
| 29 | + List<Integer> reservoir = new ArrayList<>(sampleSize); |
| 30 | + Random rand = new Random(); |
| 31 | + |
| 32 | + for (int i = 0; i < stream.length; i++) { |
| 33 | + if (i < sampleSize) { |
| 34 | + reservoir.add(stream[i]); |
| 35 | + } else { |
| 36 | + int j = rand.nextInt(i + 1); |
| 37 | + if (j < sampleSize) { |
| 38 | + reservoir.set(j, stream[i]); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return reservoir; |
| 44 | + } |
| 45 | + |
| 46 | + // Demo usage |
| 47 | + public static void main(String[] args) { |
| 48 | + int[] streamData = new int[1000]; |
| 49 | + for (int i = 0; i < 1000; i++) { |
| 50 | + streamData[i] = i + 1; |
| 51 | + } |
| 52 | + |
| 53 | + List<Integer> result = ReservoirSampling.sample(streamData, 10); |
| 54 | + System.out.println("Random sample of 10 items:"); |
| 55 | + for (int value : result) { |
| 56 | + System.out.print(value + " "); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments