Hi! I'm a beginner in Java and I have a question regarding `Arrays`

Viewed 123

I'm a beginner in Java and I have a question regarding Arrays. I've been struggling with this task where it says: Write a program that produces ten random permutations of the numbers 1 to 10. To generate a random permutation, you need to fill an array with the numbers 1 to 10 so that no two entries of the array have the same contents. Make a second array and fill it with the numbers 1 to 10. Repeat 10 times, Pick a random element from the second array. Remove it and append it to the permutation array. I am not allowed to use Arraylist to solve this task.

This is what I have done so far and my issue right now is that it prints out some zeroes while the rest of the numbers are all different like it should be: [2, 4, 10, 3, 9, 0, 0, 7, 5, 0].

What am I doing wrong, Am I even on the right way? Any help would be appreciated!

    int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int[] myArray2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int[] permutation = new int[10];


    for (int i = 0; i < myArray2.length - 1; i++) {

        int ranIndex = (int) (Math.random() * 10 - 1) + 1;

        if (myArray2[ranIndex] == 0) {
            ranIndex = (int) (Math.random() * 9);
        }
        if (myArray2[ranIndex] > 0) {
            permutation[i] = myArray2[ranIndex];
            myArray2[ranIndex] = 0;
        }
    }
    System.out.println(Arrays.toString(permutation));
1 Answers

You were close :)

import java.util.Arrays;

public class Permutation {
    public static void main(String[] args) {
        int[] myArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] myArray2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] permutation = new int[10];


        for (int i = 0; i < myArray2.length ; i++) {

            int ranIndex = (int) (Math.random() * 10 - 1) + 1;

            while (myArray2[ranIndex] == 0) {
                ranIndex = (int) (Math.random() * 10);
            }
            if (myArray2[ranIndex] > 0) {
                permutation[i] = myArray2[ranIndex];
                myArray2[ranIndex] = 0;
            }
        }
        System.out.println(Arrays.toString(permutation));
    }
}

Problems were :

  • i < length is enough, i < length - 1 discard the last element
  • Math.random() is included >=0 and <1 if you multiply it by 9, you can't get the last element of myArray2 and thus have an infinite loop.
  • if (myArray2[ranIndex] == 0) { should be replaced by while (myArray2[ranIndex] == 0) {. It was your main issue : in case the second attempt failed to find a new number in myArray2, it would leave 0 there. Replacing the if by while allows the code to try until it founds a new not used item !
Related