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.util;
018
019import java.io.Serializable;
020import java.io.IOException;
021import java.io.ObjectOutputStream;
022import java.io.ObjectInputStream;
023import org.apache.commons.math4.exception.MathIllegalArgumentException;
024import org.apache.commons.rng.RestorableUniformRandomProvider;
025import org.apache.commons.rng.simple.RandomSource;
026import org.apache.commons.rng.core.RandomProviderDefaultState;
027
028/**
029 * A strategy of selecting random index between begin and end indices.
030 *
031 * @since 3.4
032 */
033public class RandomPivotingStrategy implements PivotingStrategyInterface, Serializable {
034    /** Serializable UID. */
035    private static final long serialVersionUID = 20160517L;
036    /** Source of randomness. */
037    private final RandomSource randomSource;
038    /** Random generator to use for selecting pivot. */
039    private transient RestorableUniformRandomProvider random;
040
041    /**
042     * Simple constructor.
043     *
044     * @param randomSource RNG to use for selecting pivot.
045     * @param seed Seed for initializing the RNG.
046     *
047     * @since 4.0
048     */
049    public RandomPivotingStrategy(RandomSource randomSource,
050                                  long seed) {
051        this.randomSource = randomSource;
052        random = RandomSource.create(randomSource, seed);
053    }
054
055    /**
056     * {@inheritDoc}
057     *
058     * A uniform random pivot selection between begin and end indices.
059     *
060     * @return The index corresponding to a random uniformly selected
061     * value between first and the last indices of the array slice
062     * @throws MathIllegalArgumentException when indices exceeds range
063     */
064    @Override
065    public int pivotIndex(final double[] work, final int begin, final int end)
066        throws MathIllegalArgumentException {
067        MathArrays.verifyValues(work, begin, end-begin);
068        return begin + random.nextInt(end - begin - 1);
069    }
070
071    /**
072     * @param out Output stream.
073     * @throws IOException if an error occurs.
074     */
075    private void writeObject(ObjectOutputStream out)
076        throws IOException {
077        // Write non-transient fields.
078        out.defaultWriteObject();
079
080        // Save current state.
081        out.writeObject(((RandomProviderDefaultState) random.saveState()).getState());
082   }
083
084    /**
085     * @param in Input stream.
086     * @throws IOException if an error occurs.
087     * @throws ClassNotFoundException if an error occurs.
088     */
089    private void readObject(ObjectInputStream in)
090        throws IOException,
091               ClassNotFoundException {
092        // Read non-transient fields.
093        in.defaultReadObject();
094
095        // Recreate the "delegate" from serialized info.
096        random = RandomSource.create(randomSource);
097        // And restore its state.
098        final RandomProviderDefaultState state = new RandomProviderDefaultState((byte[]) in.readObject());
099        random.restoreState(state);
100    }
101}