PermutationSampler.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.apache.commons.rng.sampling;

  18. import org.apache.commons.rng.UniformRandomProvider;

  19. /**
  20.  * Class for representing <a href="https://en.wikipedia.org/wiki/Permutation">permutations</a>
  21.  * of a sequence of integers.
  22.  *
  23.  * <p>Sampling uses {@link UniformRandomProvider#nextInt(int)}.</p>
  24.  *
  25.  * <p>This class also contains utilities for shuffling an {@code int[]} array in-place.</p>
  26.  */
  27. public class PermutationSampler implements SharedStateObjectSampler<int[]> {
  28.     /** Domain of the permutation. */
  29.     private final int[] domain;
  30.     /** Size of the permutation. */
  31.     private final int size;
  32.     /** RNG. */
  33.     private final UniformRandomProvider rng;

  34.     /**
  35.      * Creates a generator of permutations.
  36.      *
  37.      * <p>The {@link #sample()} method will generate an integer array of
  38.      * length {@code k} whose entries are selected randomly, without
  39.      * repetition, from the integers 0, 1, ..., {@code n}-1 (inclusive).
  40.      * The returned array represents a permutation of {@code n} taken
  41.      * {@code k}.</p>
  42.      *
  43.      * @param rng Generator of uniformly distributed random numbers.
  44.      * @param n Domain of the permutation.
  45.      * @param k Size of the permutation.
  46.      * @throws IllegalArgumentException if {@code n <= 0} or {@code k <= 0}
  47.      * or {@code k > n}.
  48.      */
  49.     public PermutationSampler(UniformRandomProvider rng,
  50.                               int n,
  51.                               int k) {
  52.         SubsetSamplerUtils.checkSubset(n, k);
  53.         domain = natural(n);
  54.         size = k;
  55.         this.rng = rng;
  56.     }

  57.     /**
  58.      * @param rng Generator of uniformly distributed random numbers.
  59.      * @param source Source to copy.
  60.      */
  61.     private PermutationSampler(UniformRandomProvider rng,
  62.                                PermutationSampler source) {
  63.         // Do not clone the domain. This ensures:
  64.         // 1. Thread safety as the domain may be shuffled during the clone
  65.         //    and an incomplete shuffle swap step can result in duplicates and
  66.         //    missing elements in the array.
  67.         // 2. If the argument RNG is an exact match for the RNG in the source
  68.         //    then the output sequence will differ unless the domain is currently
  69.         //    in natural order.
  70.         domain = natural(source.domain.length);
  71.         size = source.size;
  72.         this.rng = rng;
  73.     }

  74.     /**
  75.      * @return a random permutation.
  76.      *
  77.      * @see #PermutationSampler(UniformRandomProvider,int,int)
  78.      */
  79.     @Override
  80.     public int[] sample() {
  81.         return SubsetSamplerUtils.partialSample(domain, size, rng, true);
  82.     }

  83.     /**
  84.      * {@inheritDoc}
  85.      *
  86.      * @since 1.3
  87.      */
  88.     @Override
  89.     public PermutationSampler withUniformRandomProvider(UniformRandomProvider rng) {
  90.         return new PermutationSampler(rng, this);
  91.     }

  92.     /**
  93.      * Shuffles the entries of the given array.
  94.      *
  95.      * @see #shuffle(UniformRandomProvider,int[],int,boolean)
  96.      *
  97.      * @param rng Random number generator.
  98.      * @param list Array whose entries will be shuffled (in-place).
  99.      */
  100.     public static void shuffle(UniformRandomProvider rng,
  101.                                int[] list) {
  102.         shuffle(rng, list, list.length - 1, true);
  103.     }

  104.     /**
  105.      * Shuffles the entries of the given array, using the
  106.      * <a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm">
  107.      * Fisher-Yates</a> algorithm.
  108.      * The {@code start} and {@code towardHead} parameters select which part
  109.      * of the array is randomized and which is left untouched.
  110.      *
  111.      * <p>Sampling uses {@link UniformRandomProvider#nextInt(int)}.</p>
  112.      *
  113.      * @param rng Random number generator.
  114.      * @param list Array whose entries will be shuffled (in-place).
  115.      * @param start Index at which shuffling begins.
  116.      * @param towardHead Shuffling is performed for index positions between
  117.      * {@code start} and either the end (if {@code false}) or the beginning
  118.      * (if {@code true}) of the array.
  119.      */
  120.     public static void shuffle(UniformRandomProvider rng,
  121.                                int[] list,
  122.                                int start,
  123.                                boolean towardHead) {
  124.         if (towardHead) {
  125.             // Visit all positions from start to 0.
  126.             // Do not visit 0 to avoid a swap with itself.
  127.             for (int i = start; i > 0; i--) {
  128.                 // Swap index with any position down to 0
  129.                 SubsetSamplerUtils.swap(list, i, rng.nextInt(i + 1));
  130.             }
  131.         } else {
  132.             // Visit all positions from the end to start.
  133.             // Start is not visited to avoid a swap with itself.
  134.             for (int i = list.length - 1; i > start; i--) {
  135.                 // Swap index with any position down to start.
  136.                 // Note: i - start + 1 is the number of elements remaining.
  137.                 SubsetSamplerUtils.swap(list, i, rng.nextInt(i - start + 1) + start);
  138.             }
  139.         }
  140.     }

  141.     /**
  142.      * Creates an array representing the natural number {@code n}.
  143.      *
  144.      * @param n Natural number.
  145.      * @return an array whose entries are the numbers 0, 1, ..., {@code n}-1.
  146.      * If {@code n == 0}, the returned array is empty.
  147.      */
  148.     public static int[] natural(int n) {
  149.         final int[] a = new int[n];
  150.         for (int i = 0; i < n; i++) {
  151.             a[i] = i;
  152.         }
  153.         return a;
  154.     }
  155. }