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+" ");
}
    }
    }
4
  • 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. Commented Oct 18, 2018 at 15:02
  • 2
    Consider using a Set instead of an array. Inserting a duplicate into a set will not change it. Commented Oct 18, 2018 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. docs.oracle.com/javase/8/docs/api/java/util/HashSet.html Commented Oct 18, 2018 at 15:02
  • side bar: make sure the size of the array is <= range of the random values. Commented Oct 18, 2018 at 15:05

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.