0

I have a method that creates an array with a length decided by a parameter in Main. The numbers are created by math random. How do I avoid duplicated by checking the created random number before putting it inside the array each time?

Is it possible to check an unfinished array?

class Test{
        public int[] numberArray;
        public int length;


    public Test(int lengthArray){
        this.numberArray=new int[lengthArray];
        this.length=lengthArray;
    }


    public boolean checkArray(int checknumber){
    inArray=false;

             //what code can I write here to find duplicate

        return inArray;
    }


    public void fillArray(){
        int highest = 1000;
        int lowest = 100;
        int randomNumber = 0;
        int counter=0;


        for(int i=0;i<length;i++){
            randomNumber=lowest + (int)(Math.random() * ((highest - lowest) + 1));
            numberArray[counter]=randomNumber;
            counter++;



          }
}

public class testing {
    public static void main(String[] args) {

    Test test1 = new Test(9);
    test1.fillArray();
            for(int value: test1.numberArray){
        System.out.print(value+" ");
}
    }
    }
revl
  • 3
  • 6
  • Store the random number in a dynamic variable. Use an `if` conditional to check against the new number against the previous and `if` it's the same, then remove it, or generate a new number. –  Oct 18 '18 at 15:02
  • 2
    Consider using a `Set` instead of an array. Inserting a duplicate into a set will not change it. – jsheeran Oct 18 '18 at 15:02
  • A good way would be to check each element in the array. or if you want to get fancy look into Sets. https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html – Charles Oct 18 '18 at 15:02
  • side bar: make sure the size of the array is <= range of the random values. – Andrew S Oct 18 '18 at 15:05

1 Answers1

2

You could first create all the numbers you need and store in a Set data structure till size equals the number of numbers you want. Later, transfer all the numbers in the Set to an array of the same size

mettleap
  • 1,390
  • 8
  • 17