Java Array Shuffle shuffle(int[] input)

Here you can find the source of shuffle(int[] input)

Description

Weirdly java doesn't seem to have Arrays.shuffle(), this terrible hack does that.

License

Apache License

Return

A shuffled copy of the input

Declaration

public static int[] shuffle(int[] input) 

Method Source Code

//package com.java2s;
/*/*w  w w .  jav  a2  s .  co m*/
 * Copyright 2008-2009 LinkedIn, Inc
 * Copyright (c) 2013 Big Switch Networks, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

import java.util.ArrayList;

import java.util.Collections;

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

public class Main {
    public static final Random SEEDED_RANDOM = new Random(19873482374L);

    /**
     * Weirdly java doesn't seem to have Arrays.shuffle(), this terrible hack
     * does that.
     *
     * @return A shuffled copy of the input
     */
    public static int[] shuffle(int[] input) {
        List<Integer> vals = new ArrayList<Integer>(input.length);
        for (int i = 0; i < input.length; i++)
            vals.add(input[i]);
        Collections.shuffle(vals, SEEDED_RANDOM);
        int[] copy = new int[input.length];
        for (int i = 0; i < input.length; i++)
            copy[i] = vals.get(i);
        return copy;
    }
}

Related

  1. shuffle(int[] array)
  2. shuffle(int[] array, Random rand)
  3. shuffle(int[] array, Random rand)
  4. shuffle(int[] array, Random rnd)
  5. shuffle(int[] ary)
  6. shuffle(int[] list, Random rnd)
  7. Shuffle(int[] v)
  8. shuffle(Integer[] data)
  9. shuffle(List list)