Skip to main content

APIzation: Replication Package

[Q#15196363][A#15196438] java - How do I create an int array with randomly shuffled numbers in a given range

https://stackoverflow.com/q/15196363

Basically, let's say I have an int array that can hold 10 numbers. Which mean I can store 0-9 in each of the index.(each number only once). If I run the code below: my array would look like this: [0],[1],…..,[8],[9] But how do I randomize the number assignment each time I run the code? For example, I want the array to look something like: [8],[1],[0]…..[6],[3]

Answer

https://stackoverflow.com/a/15196438

Make it a List<Integer> instead of an array, and use Collections.shuffle() to shuffle it. You can build the int[] from the List after shuffling. If you really want to do the shuffle directly, search for "Fisher-Yates Shuffle". Here is an example of using the List technique:

APIzation

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
  public static void main(String args[]) {
    List<Integer> dataList = new ArrayList<Integer>();
    for (int i = 0; i < 10; i++) {
      dataList.add(i);
    }
    Collections.shuffle(dataList);
    int[] num = new int[dataList.size()];
    for (int i = 0; i < dataList.size(); i++) {
      num[i] = dataList.get(i);
    }

    for (int i = 0; i < num.length; i++) {
      System.out.println(num[i]);
    }
  }
}
package com.stackoverflow.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Human15196438 {

  public static int[] shuffleNumbers(int begin, int end) {
    List<Integer> dataList = new ArrayList<Integer>();
    for (int i = begin; i < end; i++) {
      dataList.add(i);
    }
    Collections.shuffle(dataList);
    int[] num = new int[dataList.size()];
    for (int i = 0; i < dataList.size(); i++) {
      num[i] = dataList.get(i);
    }
    return num;
  }
}

package com.stackoverflow.api;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * java - How do I create an int array with randomly shuffled numbers in a given range
 *
 * @author APIzator
 * @see <a href="https://stackoverflow.com/a/15196438">https://stackoverflow.com/a/15196438</a>
 */
public class APIzator15196438 {

  public static void createArray() {
    List<Integer> dataList = new ArrayList<Integer>();
    for (int i = 0; i < 10; i++) {
      dataList.add(i);
    }
    Collections.shuffle(dataList);
    int[] num = new int[dataList.size()];
    for (int i = 0; i < dataList.size(); i++) {}
    for (int i = 0; i < num.length; i++) {
      System.out.println(num[i]);
    }
  }
}