0

I begin with java and I hit a problem

I need to create 2 array with the same random value but these values have to be in different order, like this:

int[] firstArray= {5, 12, 7, 10, 6, 8};
int[] secondArray= {12, 7, 8, 5, 10, 6};

But I want this with random numbers. How can I do this ? Thanks

Simon M.
  • 2,244
  • 3
  • 17
  • 34

3 Answers3

1

There's a library provided shuffle method you can use, in case you don't want to define your own.

String[] alpha = { "A", "E", "I", "O", "U" };
List list = new ArrayList(alpha);
Collections.shuffle(list);
String[] shuffledAlpha = list.toArray();
Raman Shrivastava
  • 2,923
  • 15
  • 26
0

Try this

public static int[] RandArray(int[] array){
    Random rand = new Random();         

    for (int i=0; i<array.length; i++) {
        int randomPosition = rand.nextInt(array.length);
        int temp = array[i];
        array[i] = array[randomPosition];
        array[randomPosition] = temp;
    }

    return array;
}

In the main add this

int[] firstArray = {5, 12, 7, 10, 6, 8};
int[] secondArray = RandArray(firstArray);
    for (int i = 0; i < secondArray.length; i++)
    {
      System.out.print(secondArray[i] + " ");
    }
    System.out.println();

and this is output:

7 8 10 6 12 5

To randomize firstArray add this code:

public static int[] RandFirstArray(int arraySize, int min, int max){
    Random rand = new Random();         
     int[] firstArray = new int[arraySize];
    for (int i=0; i<arraySize; i++) {
        firstArray[i] = rand.nextInt((max - min) + 1) + min;
    }
    return firstArray;
}

Than in the main:

    //Use RandFirstArray(ArrayLength, MinValue, MaxValue)
    int[] firstArray = RandFirstArray(6, 0 , 20);
    System.out.println("First Array\n");
    for (int i = 0; i < firstArray.length; i++)
    {
      System.out.print(firstArray[i] + " ");
    }
    System.out.println("\n\nSecond Array\n");
    int[] secondArray = RandArray(firstArray);
    for (int i = 0; i < secondArray.length; i++)
    {
      System.out.print(secondArray[i] + " ");
    }
    System.out.println();

New output:

First Array

3 20 5 13 8 11

Second Array

8 13 11 20 3 5

Michele Lacorte
  • 5,323
  • 7
  • 32
  • 54
0

Use this method, using a Fisher-Yates shuffle.

Fisher Yates shuffle

Algorithm

public int[] 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];
        }
    }
    return array;
}
Community
  • 1
  • 1