0

So I wanted to make an array and then print the elements from the array in a random order. But I want each element of the array to be printed once, or the number of times it occurs in the original array.

public class ShufflingAList {

/**
 * @param args the command line arguments
 */
    public static void main(String[] args) {
        int [] array = {1, 2, 3, 4, 5, 6, 7, 8 ,9, 0};

        for (int i = 0; i < array.length-1; i++){
                if (array[i]>array[i + 1]^array[i]<array[i+1]){
                    array[i] = array[(int)(Math.random() * 10)];
                }
            }
        for (int i = 0; i < array.length; i++){
            System.out.print(array[i] + " ");
        }
    }
} 

I got this as output, which is not what I wanted:

3 3 4 6 9 9 9 3 9 0

What do I do to print each element of the array only once? Store it in another array and check for duplicates in that array?

Gary Theurpe
  • 63
  • 1
  • 5

2 Answers2

0

You can adopt the idea from Fisher–Yates shuffle (it's considered to be true shuffle and works even if you generate same random everytime). Once you print the element move it to the end of the array and generate next random number between 0 and n-1.

Random random = new Random();
for (int i = array.length - 1; i > 0; i--)
{
  int index = random.nextInt(i + 1);
  System.out.println(a[index]);
  int a = ar[index];
  ar[index] = ar[i];
  ar[i] = a;
}
Karthik
  • 4,950
  • 6
  • 35
  • 65
0

I know of a few differnt way to do shuffle up an array.
Simplest way is Java Collection.shuffle() method

    // Create an array
    //int[] array = new int[]{1, 2, 3, 4}; does not work, must be Integer[] 
    Integer[] array = new Integer[]{1, 2, 3, 4};

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

Second way is to code a method to do the shuffle

 public static int[] ShuffleArray(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;
        }

enter image description here

Andrew Kralovec
  • 491
  • 4
  • 13