static DoubleSupplier createSampler()

in commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/KolmogorovSmirnovTest.java [986:1018]


    static DoubleSupplier createSampler(double[] x, double[] y,
                                        UniformRandomProvider rng,
                                        int maxArraySize) {
        final int n = x.length;
        final int m = y.length;
        final int len = n + m;
        // Overflow safe: len > maxArraySize
        if (len - maxArraySize > 0) {
            // Support sampling with maximum length arrays
            // (where a concatenated array is not possible)
            // by choosing one or the other.
            // - generate i in [-n, m)
            // - return i < 0 ? x[n + i] : y[i]
            // The sign condition is a 50-50 branch.
            // Perform branchless by extracting the sign bit to pick the array.
            // Copy the source data.
            final double[] xx = x.clone();
            final double[] yy = y.clone();
            final IntToDoubleFunction nextX = i -> xx[n + i];
            final IntToDoubleFunction nextY = i -> yy[i];
            // Arrange function which accepts the negative index at position [1]
            final IntToDoubleFunction[] next = {nextY, nextX};
            return () -> {
                final int i = rng.nextInt(-n, m);
                return next[i >>> 31].applyAsDouble(i);
            };
        }
        // Concatenate arrays
        final double[] z = new double[len];
        System.arraycopy(x, 0, z, 0, n);
        System.arraycopy(y, 0, z, n, m);
        return () -> z[rng.nextInt(len)];
    }