Java Array Shuffle shuffleSublist(List objects, int start, int end)

Here you can find the source of shuffleSublist(List objects, int start, int end)

Description

Shuffle the elements between the specified start and end index both inclusive.

License

Open Source License

Parameter

Parameter Description
objects a parameter
start a parameter
end a parameter

Declaration

public static <T> void shuffleSublist(List<T> objects, int start, int end) 

Method Source Code

//package com.java2s;
/**/*from ww w  .  j a  va  2 s.co  m*/
 * Random Pipes: Java application based on the game Pipe Dream
 *
 * Copyright (C) 2015 Zdravko Petkov
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.List;
import java.util.Random;

public class Main {
    private static final Random random = new Random();

    /**
     * Shuffle the elements between the specified start and end index both
     * inclusive. The rest of the elements have unchanged order.<br>
     * Shuffle is based on Fisher-Yates algorithm.
     *
     * @param objects
     * @param start
     * @param end
     */
    public static <T> void shuffleSublist(List<T> objects, int start, int end) {
        for (int index = start; index <= end; index++) {
            T current = objects.get(index);
            int randomIndex = nextInt(start, end);
            T randomObject = objects.get(randomIndex);
            objects.set(index, randomObject);
            objects.set(randomIndex, current);
        }
    }

    /**
     * Returns a randomly generated integer between 0 inclusive and max
     * exclusive.<br>
     * <code>[0, max)</code>
     *
     * @param max
     * @return randomInt
     */
    public static int nextInt(int max) {
        int randomInt = random.nextInt(max);
        return randomInt;
    }

    /**
     * Returns a random integer between min and max inclusive.
     *
     * @param min
     * @param max
     * @return
     */
    public static int nextInt(int min, int max) {
        int rand = random.nextInt((max + 1) - min);
        int result = rand + min;
        return result;
    }
}

Related

  1. shuffleInPlace(int[] toShuffle, Random random)
  2. shuffleIntArray(int[] arr)
  3. shuffleIntArray(int[] array)
  4. shuffleList(List list)
  5. shuffleList(List list)