0

I want to generate a random number array that have no duplicates. My array have a fixed rage. I will generate random numbers (0-4), So i want array like this (0,3,1,4,2) or (3,2,4,0,1) like somthing in random order in that range. My code have no errors. But i am not getting the output i want.

import java.util.Random;

public class randNumArr {

    public static void main(String[] args) {
        int arr[] = {-1, -1, -1, -1, -1};

        Random rd = new Random();
        int i = 0;
        int val;
        while (i < 5) {
            if (arr[i] == -1) {
                val = rd.nextInt(4);
                for (int d = 0; d < arr.length; d++) {

                    if (arr[i] == val) {
                        // break;
                    } else {
                        arr[i] = val;
                        break;
                    }
                }
                i++;
            }


        }

        /*Printing the array*/
        for (int n = 0; n < arr.length; n++) {
            System.out.print(arr[n] + " ");
        }

    }

}
Rahman
  • 3,755
  • 3
  • 26
  • 43
Dhanuka Perera
  • 1,395
  • 3
  • 19
  • 29

1 Answers1

0

Try replacing the i with a d in the line

if (arr[d]==val) {

That should do the trick!