001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.commons.math4.legacy.stat.descriptive.rank; 018 019import org.apache.commons.math4.legacy.core.MathArrays; 020import org.apache.commons.rng.RestorableUniformRandomProvider; 021import org.apache.commons.rng.simple.RandomSource; 022 023/** 024 * A strategy of selecting random index between begin and end indices. 025 * 026 * @since 3.4 027 */ 028public class RandomPivotingStrategy implements PivotingStrategy { 029 /** Source of randomness. */ 030 private final RandomSource randomSource; 031 /** Random generator to use for selecting pivot. */ 032 private transient RestorableUniformRandomProvider random; 033 034 /** 035 * Simple constructor. 036 * 037 * @param randomSource RNG to use for selecting pivot. 038 * @param seed Seed for initializing the RNG. 039 * 040 * @since 4.0 041 */ 042 public RandomPivotingStrategy(RandomSource randomSource, 043 long seed) { 044 this.randomSource = randomSource; 045 random = randomSource.create(seed); 046 } 047 048 /** 049 * {@inheritDoc} 050 * 051 * A uniform random pivot selection between begin and end indices. 052 * 053 * @return The index corresponding to a random uniformly selected 054 * value between first and the last indices of the array slice 055 * @throws org.apache.commons.math4.legacy.exception.MathIllegalArgumentException MathIllegalArgumentException when indices exceeds range 056 */ 057 @Override 058 public int pivotIndex(final double[] work, final int begin, final int end) { 059 MathArrays.verifyValues(work, begin, end - begin); 060 return begin + random.nextInt(end - begin - 1); 061 } 062}