programing

어레이의 랜덤 전환

itsource 2022. 8. 17. 21:42
반응형

어레이의 랜덤 전환

다음 어레이를 랜덤으로 셔플해야 합니다.

int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};

그것을 할 수 있는 기능이 있나요?

컬렉션을 사용하여 여러 원시 유형을 섞는 것은 좀 오버킬입니다.

예를 들어 Fisher-Yates 셔플을 사용하면 함수를 직접 구현할 수 있습니다.

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

class Test
{
  public static void main(String args[])
  {
    int[] solutionArray = { 1, 2, 3, 4, 5, 6, 16, 15, 14, 13, 12, 11 };

    shuffleArray(solutionArray);
    for (int i = 0; i < solutionArray.length; i++)
    {
      System.out.print(solutionArray[i] + " ");
    }
    System.out.println();
  }

  // Implementing Fisher–Yates shuffle
  static void shuffleArray(int[] ar)
  {
    // If running on Java 6 or older, use `new Random()` on RHS here
    Random rnd = ThreadLocalRandom.current();
    for (int i = ar.length - 1; i > 0; i--)
    {
      int index = rnd.nextInt(i + 1);
      // Simple swap
      int a = ar[index];
      ar[index] = ar[i];
      ar[i] = a;
    }
  }
}

요.ArrayList:

List<Integer> solution = new ArrayList<>();
for (int i = 1; i <= 6; i++) {
    solution.add(i);
}
Collections.shuffle(solution);

다음은 작동 중인 효율적인 Fisher-Yates 셔플 어레이 기능입니다.

private static void shuffleArray(int[] array)
{
    int index;
    Random random = new Random();
    for (int i = array.length - 1; i > 0; i--)
    {
        index = random.nextInt(i + 1);
        if (index != i)
        {
            array[index] ^= array[i];
            array[i] ^= array[index];
            array[index] ^= array[i];
        }
    }
}

또는

private static void shuffleArray(int[] array)
{
    int index, temp;
    Random random = new Random();
    for (int i = array.length - 1; i > 0; i--)
    {
        index = random.nextInt(i + 1);
        temp = array[index];
        array[index] = array[i];
        array[i] = temp;
    }
}

컬렉션 클래스에는 의존하지 않도록 복사할 수 있는 효율적인 셔플링 방법이 있습니다.

/**
 * Usage:
 *    int[] array = {1, 2, 3};
 *    Util.shuffle(array);
 */
public class Util {

    private static Random random;

    /**
     * Code from method java.util.Collections.shuffle();
     */
    public static void shuffle(int[] array) {
        if (random == null) random = new Random();
        int count = array.length;
        for (int i = count; i > 1; i--) {
            swap(array, i - 1, random.nextInt(i));
        }
    }

    private static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

수업 내용을 자세히 보세요.shuffle(...).

하다, 이렇게 하다, 하다, 하다, 하다, 하다, 하다를 한 완전한 .Collections.shuffle★★★★★★★★★★★★★★★★★★:

public static void shuffleArray(int[] array) {
  List<Integer> list = new ArrayList<>();
  for (int i : array) {
    list.add(i);
  }

  Collections.shuffle(list);

  for (int i = 0; i < list.size(); i++) {
    array[i] = list.get(i);
  }    
}

""를 할 수 때문에 가 발생한다는 하십시오.int[] ★★★★★★★★★★★★★★★★★」Integer[])int[] ★★★★★★★★★★★★★★★★★」List<Integer>를 참조해 주세요.

여기에는 몇 가지 옵션이 있습니다.shuffling에 관해서는 리스트는 배열과 조금 다릅니다.

아래 그림과 같이 배열은 목록보다 빠르고 기본 배열은 개체 배열보다 빠릅니다.

샘플 지속 시간

List<Integer> Shuffle: 43133ns
    Integer[] Shuffle: 31884ns
        int[] Shuffle: 25377ns

다음은 셔플의 3가지 구현입니다.컬렉션만 사용해야 합니다.컬렉션을 취급하고 있는 경우는, 셔플 해 주세요.어레이를 정렬하기 위해 어레이를 컬렉션으로 정리할 필요는 없습니다.다음 방법은 구현이 매우 간단합니다.

Shuffle Util 클래스

import java.lang.reflect.Array;
import java.util.*;

public class ShuffleUtil<T> {
    private static final int[] EMPTY_INT_ARRAY = new int[0];
    private static final int SHUFFLE_THRESHOLD = 5;

    private static Random rand;

주요 방법

    public static void main(String[] args) {
        List<Integer> list = null;
        Integer[] arr = null;
        int[] iarr = null;

        long start = 0;
        int cycles = 1000;
        int n = 1000;

        // Shuffle List<Integer>
        start = System.nanoTime();
        list = range(n);
        for (int i = 0; i < cycles; i++) {
            ShuffleUtil.shuffle(list);
        }
        System.out.printf("%22s: %dns%n", "List<Integer> Shuffle", (System.nanoTime() - start) / cycles);

        // Shuffle Integer[]
        start = System.nanoTime();
        arr = toArray(list);
        for (int i = 0; i < cycles; i++) {
            ShuffleUtil.shuffle(arr);
        }
        System.out.printf("%22s: %dns%n", "Integer[] Shuffle", (System.nanoTime() - start) / cycles);

        // Shuffle int[]
        start = System.nanoTime();
        iarr = toPrimitive(arr);
        for (int i = 0; i < cycles; i++) {
            ShuffleUtil.shuffle(iarr);
        }
        System.out.printf("%22s: %dns%n", "int[] Shuffle", (System.nanoTime() - start) / cycles);
    }

범용 리스트의 shuffling

    // ================================================================
    // Shuffle List<T> (java.lang.Collections)
    // ================================================================
    @SuppressWarnings("unchecked")
    public static <T> void shuffle(List<T> list) {
        if (rand == null) {
            rand = new Random();
        }
        int size = list.size();
        if (size < SHUFFLE_THRESHOLD || list instanceof RandomAccess) {
            for (int i = size; i > 1; i--) {
                swap(list, i - 1, rand.nextInt(i));
            }
        } else {
            Object arr[] = list.toArray();

            for (int i = size; i > 1; i--) {
                swap(arr, i - 1, rand.nextInt(i));
            }

            ListIterator<T> it = list.listIterator();
            int i = 0;

            while (it.hasNext()) {
                it.next();
                it.set((T) arr[i++]);
            }
        }
    }

    public static <T> void swap(List<T> list, int i, int j) {
        final List<T> l = list;
        l.set(i, l.set(j, l.get(i)));
    }

    public static <T> List<T> shuffled(List<T> list) {
        List<T> copy = copyList(list);
        shuffle(copy);
        return copy;
    }

범용 어레이의 쉐이핑

    // ================================================================
    // Shuffle T[]
    // ================================================================
    public static <T> void shuffle(T[] arr) {
        if (rand == null) {
            rand = new Random();
        }

        for (int i = arr.length - 1; i > 0; i--) {
            swap(arr, i, rand.nextInt(i + 1));
        }
    }

    public static <T> void swap(T[] arr, int i, int j) {
        T tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static <T> T[] shuffled(T[] arr) {
        T[] copy = Arrays.copyOf(arr, arr.length);
        shuffle(copy);
        return copy;
    }

프리미티브 어레이 셰이핑

    // ================================================================
    // Shuffle int[]
    // ================================================================
    public static <T> void shuffle(int[] arr) {
        if (rand == null) {
            rand = new Random();
        }

        for (int i = arr.length - 1; i > 0; i--) {
            swap(arr, i, rand.nextInt(i + 1));
        }
    }

    public static <T> void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }

    public static int[] shuffled(int[] arr) {
        int[] copy = Arrays.copyOf(arr, arr.length);
        shuffle(copy);
        return copy;
    }

유틸리티 방법

어레이를 목록으로 복사 및 변환하는 심플한 유틸리티 방법, 또는 그 반대입니다.

    // ================================================================
    // Utility methods
    // ================================================================
    protected static <T> List<T> copyList(List<T> list) {
        List<T> copy = new ArrayList<T>(list.size());
        for (T item : list) {
            copy.add(item);
        }
        return copy;
    }

    protected static int[] toPrimitive(Integer[] array) {
        if (array == null) {
            return null;
        } else if (array.length == 0) {
            return EMPTY_INT_ARRAY;
        }
        final int[] result = new int[array.length];
        for (int i = 0; i < array.length; i++) {
            result[i] = array[i].intValue();
        }
        return result;
    }

    protected static Integer[] toArray(List<Integer> list) {
        return toArray(list, Integer.class);
    }

    protected static <T> T[] toArray(List<T> list, Class<T> clazz) {
        @SuppressWarnings("unchecked")
        final T[] arr = list.toArray((T[]) Array.newInstance(clazz, list.size()));
        return arr;
    }

범위 클래스

Python과 합니다.range★★★★★★ 。

    // ================================================================
    // Range class for generating a range of values.
    // ================================================================
    protected static List<Integer> range(int n) {
        return toList(new Range(n), new ArrayList<Integer>());
    }

    protected static <T> List<T> toList(Iterable<T> iterable) {
        return toList(iterable, new ArrayList<T>());
    }

    protected static <T> List<T> toList(Iterable<T> iterable, List<T> destination) {
        addAll(destination, iterable.iterator());

        return destination;
    }

    protected static <T> void addAll(Collection<T> collection, Iterator<T> iterator) {
        while (iterator.hasNext()) {
            collection.add(iterator.next());
        }
    }

    private static class Range implements Iterable<Integer> {
        private int start;
        private int stop;
        private int step;

        private Range(int n) {
            this(0, n, 1);
        }

        private Range(int start, int stop) {
            this(start, stop, 1);
        }

        private Range(int start, int stop, int step) {
            this.start = start;
            this.stop = stop;
            this.step = step;
        }

        @Override
        public Iterator<Integer> iterator() {
            final int min = start;
            final int max = stop / step;

            return new Iterator<Integer>() {
                private int current = min;

                @Override
                public boolean hasNext() {
                    return current < max;
                }

                @Override
                public Integer next() {
                    if (hasNext()) {
                        return current++ * step;
                    } else {
                        throw new NoSuchElementException("Range reached the end");
                    }
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException("Can't remove values from a Range");
                }
            };
        }
    }
}

다음 코드는 어레이에서 랜덤 순서를 실행합니다.

// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(array));

출처 : http://www.programcreek.com/2012/02/java-method-to-shuffle-an-int-array-with-random-order/

「」를 사용합니다.ArrayList<Integer>로직을 많이 사용하지 않고 시간을 단축하지 않고 셔플링 문제를 해결할 수 있습니다.츠키다

ArrayList<Integer> x = new ArrayList<Integer>();
for(int i=1; i<=add.length(); i++)
{
    x.add(i);
}
Collections.shuffle(x);

이제 Java 8을 사용할 수 있습니다.

Collections.addAll(list, arr);
Collections.shuffle(list);
cardsList.toArray(arr);
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
  int index = rnd.nextInt(i + 1);
  // Simple swap
  int a = ar[index];
  ar[index] = ar[i];
  ar[i] = a;
}

이 에서는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★.ar.length - 1요소 수를 지정합니다.따라서 어레이에 5개의 요소가 있는 경우 새로운 쉐이핑된 어레이에는 4개의 요소가 있습니다.은 For 가 For For(포루프)로 되어 있기 합니다.i>0 to로 했을 i>=0모든 요소를 섞습니다.

어레이용 Generics 버전은 다음과 같습니다.

import java.util.Random;

public class Shuffle<T> {

    private final Random rnd;

    public Shuffle() {
        rnd = new Random();
    }

    /**
     * Fisher–Yates shuffle.
     */
    public void shuffle(T[] ar) {
        for (int i = ar.length - 1; i > 0; i--) {
            int index = rnd.nextInt(i + 1);
            T a = ar[index];
            ar[index] = ar[i];
            ar[i] = a;
        }
    }
}

ArrayList는 기본적으로 배열일 뿐이므로 명시적 배열 대신 ArrayList를 사용하여 Collections를 사용하는 것이 좋습니다.섞다단, 퍼포먼스 테스트에서는 위의 Collections.sort()와 큰 차이는 나타나지 않습니다.

Shuffe<Integer>.shuffle(...) performance: 576084 shuffles per second
Collections.shuffle(ArrayList<Integer>) performance: 629400 shuffles per second
MathArrays.shuffle(int[]) performance: 53062 shuffles per second

Apache Commons 구현 MathArrays입니다.shuffle은 int[]로 제한되며 성능 저하가 발생하는 것은 난수 생성기가 사용되기 때문일 수 있습니다.

다음은 Apache Commons Math 3.x를 사용한 해결 방법입니다(int[] 어레이 전용).

MathArrays.shuffle(array);

http://commons.apache.org/proper/commons-math/javadocs/api-3.6.1/org/apache/commons/math3/util/MathArrays.html#shuffle(int [ ]

3은 Apache Commons Lang 3.6에 했습니다.ArrayUtils클래스(오브젝트 및 임의의 프리미티브타입용).

ArrayUtils.shuffle(array);

http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#shuffle-int:A-

몇 가지 답변에서 누락된 정보를 보고 새로 추가하기로 했습니다.

Arrays T Java "Arrays.asList"의를 취합니다.(T ...) 배열)을 asList가 추론되어 asList가 List<int[]>이것은 단일 요소 목록입니다(하나의 요소는 원시 배열입니다).이 요소 목록 하나를 섞어도 아무것도 바뀌지 않습니다.

라고 하는 은, 포장지라고 하는 을 쓸 수 있어요.ArrayUtils.toObjectapache를 사용하여 하고 apache.commons.lang에서 thatmethod를 마지막으로 .을 사용하여 생성된 배열을 목록으로 전달하고 마지막으로 셔플합니다.

  int[] intArr = {1,2,3};
  List<Integer> integerList = Arrays.asList(ArrayUtils.toObject(array));
  Collections.shuffle(integerList);
  //now! elements in integerList are shuffled!

여기 목록을 섞는 다른 방법이 있습니다.

public List<Integer> shuffleArray(List<Integer> a) {
    List<Integer> b = new ArrayList<Integer>();
    while (a.size() != 0) {
        int arrayIndex = (int) (Math.random() * (a.size()));
        b.add(a.get(arrayIndex));
        a.remove(a.get(arrayIndex));
    }
    return b;
}

원래 목록에서 임의의 번호를 선택하여 다른 목록에 저장합니다.그런 다음 원래 목록에서 번호를 제거합니다.모든 요소가 새 목록으로 이동될 때까지 원래 목록의 크기는 계속 1씩 감소합니다.

Groovy를 위한 심플한 솔루션:

solutionArray.sort{ new Random().nextInt() }

이렇게 하면 어레이 목록의 모든 요소가 랜덤으로 정렬되고 모든 요소의 shuffling에서 원하는 결과가 아카이브됩니다.

Guava의 사용은 다음과 같이 간단합니다.

Collections.shuffle(Ints.asList(array));

랜덤 클래스 사용

  public static void randomizeArray(int[] arr) {

      Random rGenerator = new Random(); // Create an instance of the random class 
      for (int i =0; i< arr.length;i++ ) {
          //Swap the positions...

          int rPosition = rGenerator.nextInt(arr.length); // Generates an integer within the range (Any number from 0 - arr.length)
          int temp = arr[i]; // variable temp saves the value of the current array index;
          arr[i] = arr[rPosition];  // array at the current position (i) get the value of the random generated 
          arr[rPosition] = temp; // the array at the position of random generated gets the value of temp

      }

      for(int i = 0; i<arr.length; i++) {
          System.out.print(arr[i]); //Prints out the array
      } 

  }

나는 이 매우 인기 있는 질문에 무게를 두고 있다. 왜냐하면 아무도 셔플 카피 버전을 쓰지 않았기 때문이다. Arrays.java왜냐하면 요즘 자바 테크놀로지를 약탈하지 않는 사람은 누구입니까?범용 및int구현이 포함되어 있습니다.

   /**
    * Shuffles elements from {@code original} into a newly created array.
    *
    * @param original the original array
    * @return the new, shuffled array
    * @throws NullPointerException if {@code original == null}
    */
   @SuppressWarnings("unchecked")
   public static <T> T[] shuffledCopy(T[] original) {
      int originalLength = original.length; // For exception priority compatibility.
      Random random = new Random();
      T[] result = (T[]) Array.newInstance(original.getClass().getComponentType(), originalLength);

      for (int i = 0; i < originalLength; i++) {
         int j = random.nextInt(i+1);
         result[i] = result[j];
         result[j] = original[i];
      }

      return result;
   }


   /**
    * Shuffles elements from {@code original} into a newly created array.
    *
    * @param original the original array
    * @return the new, shuffled array
    * @throws NullPointerException if {@code original == null}
    */
   public static int[] shuffledCopy(int[] original) {
      int originalLength = original.length;
      Random random = new Random();
      int[] result = new int[originalLength];

      for (int i = 0; i < originalLength; i++) {
         int j = random.nextInt(i+1);
         result[i] = result[j];
         result[j] = original[i];
      }

      return result;
   }

이것은 knuth shuffle 알고리즘입니다.

public class Knuth { 

    // this class should not be instantiated
    private Knuth() { }

    /**
     * Rearranges an array of objects in uniformly random order
     * (under the assumption that <tt>Math.random()</tt> generates independent
     * and uniformly distributed numbers between 0 and 1).
     * @param a the array to be shuffled
     */
    public static void shuffle(Object[] a) {
        int n = a.length;
        for (int i = 0; i < n; i++) {
            // choose index uniformly in [i, n-1]
            int r = i + (int) (Math.random() * (n - i));
            Object swap = a[r];
            a[r] = a[i];
            a[i] = swap;
        }
    }

    /**
     * Reads in a sequence of strings from standard input, shuffles
     * them, and prints out the results.
     */
    public static void main(String[] args) {

        // read in the data
        String[] a = StdIn.readAllStrings();

        // shuffle the array
        Knuth.shuffle(a);

        // print results.
        for (int i = 0; i < a.length; i++)
            StdOut.println(a[i]);
    }
}

또 다른 방법도 있어 아직 투고하지 말고

//that way, send many object types diferentes
public anotherWayToReciveParameter(Object... objects)
{
    //ready with array
    final int length =objects.length;
    System.out.println(length);
    //for ready same list
    Arrays.asList(objects);
}

그렇게 하면 문맥에 따라 좀 더 쉽게

어레이 내 랜덤 셔플링의 가장 심플한 솔루션.

String location[] = {"delhi","banglore","mathura","lucknow","chandigarh","mumbai"};
int index;
String temp;
Random random = new Random();
for(int i=1;i<location.length;i++)
{
    index = random.nextInt(i+1);
    temp = location[index];
    location[index] = location[i];
    location[i] = temp;
    System.out.println("Location Based On Random Values :"+location[i]);
}

가장 간단한 셔플 코드:

import java.util.*;
public class ch {
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        ArrayList<Integer> l=new ArrayList<Integer>(10);
        for(int i=0;i<10;i++)
            l.add(sc.nextInt());
        Collections.shuffle(l);
        for(int j=0;j<10;j++)
            System.out.println(l.get(j));       
    }
}
  1. 다음에서 상자int[]로.List<Integer>
  2. 와 섞다Collections.shuffle방법
int[] solutionArray = { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1 };

List<Integer> list = Arrays.stream(solutionArray).boxed().collect(Collectors.toList());
Collections.shuffle(list);

System.out.println(list.toString());
// [1, 5, 5, 4, 2, 6, 1, 3, 3, 4, 2, 6]

를 사용해 주세요.Collections.shuffle()그러나 원시 유형의 배열을 직접 조작할 수는 없으므로 래퍼 클래스를 만들어야 합니다.

이거 먹어봐.

public static void shuffle(int[] array) {
    Collections.shuffle(new AbstractList<Integer>() {
        @Override public Integer get(int index) { return array[index]; }
        @Override public int size() { return array.length; }
        @Override public Integer set(int index, Integer element) {
            int result = array[index];
            array[index] = element;
            return result;
        }
    });
}

그리고.

int[] solutionArray = {1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1};
shuffle(solutionArray);
System.out.println(Arrays.toString(solutionArray));

출력:

[3, 3, 4, 1, 6, 2, 2, 1, 5, 6, 5, 4]
public class ShuffleArray {
public static void shuffleArray(int[] a) {
    int n = a.length;
    Random random = new Random();
    random.nextInt();
    for (int i = 0; i < n; i++) {
        int change = i + random.nextInt(n - i);
        swap(a, i, change);
    }
}

private static void swap(int[] a, int i, int change) {
    int helper = a[i];
    a[i] = a[change];
    a[change] = helper;
}

public static void main(String[] args) {
    int[] a = new int[] { 1, 2, 3, 4, 5, 6, 6, 5, 4, 3, 2, 1 };
    shuffleArray(a);
    for (int i : a) {
        System.out.println(i);
    }
}
}
import java.util.ArrayList;
import java.util.Random;
public class shuffle {
    public static void main(String[] args) {
        int a[] =  {1,2,3,4,5,6,7,8,9};
         ArrayList b = new ArrayList();
       int i=0,q=0;
       Random rand = new Random();

       while(a.length!=b.size())
       {
           int l = rand.nextInt(a.length);
//this is one option to that but has a flaw on 0
//           if(a[l] !=0)
//           {
//                b.add(a[l]);
//               a[l]=0;
//               
//           }
//           
// this works for every no. 
                if(!(b.contains(a[l])))
                {
                    b.add(a[l]);
                }



       }

//        for (int j = 0; j <b.size(); j++) {
//            System.out.println(b.get(j));
//            
//        }
System.out.println(b);
    }

}

솔루션 중 하나는 치열을 사용하여 모든 치열을 미리 계산하고 Array List에 저장하는 것입니다.

Java 8은 java.util에 새로운 메서드 ints()를 도입했습니다.랜덤 클래스ints() 메서드는 pseudorandom int 값의 스트림을 무제한으로 반환합니다.최소값과 최대값을 제공하여 지정된 범위 사이의 난수를 제한할 수 있습니다.

Random genRandom = new Random();
int num = genRandom.nextInt(arr.length);

난수를 생성하면 루프를 반복하고 난수를 사용하여 현재 인덱스와 스왑할 수 있습니다.이렇게 하면 O(1) 공간의 복잡성을 가진 난수를 생성할 수 있습니다.

랜덤 솔루션 없음:

   static void randomArrTimest(int[] some){
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < some.length; i++) {
            long indexToSwap = startTime%(i+1);
            long tmp = some[(int) indexToSwap];
            some[(int) indexToSwap] = some[i];
            some[i] = (int) tmp;
        }
        System.out.println(Arrays.toString(some));
    }

자바에서는 컬렉션을 사용할 수 있습니다.목록의 항목을 무작위로 정렬하는 셔플 메서드.

Groovy 3.0.0은 Shuffle 메서드와 Shuffle 메서드를 목록 또는 배열에 직접 추가합니다.

언급URL : https://stackoverflow.com/questions/1519736/random-shuffling-of-an-array

반응형