alexthefourth
alexthefourth

Reputation: 137

Java insert random integers into binary search tree

Im trying to insert random integers into a binary search tree.

this is what ive tried

for(i = 0; i <= insertAmount; i++)
        {
            myTree.insert((int)Math.random()*1000000+1);
        }

I think im just inserting the same number. doesnt the + 1 change the value?

Upvotes: 0

Views: 1275

Answers (4)

Rais Alam
Rais Alam

Reputation: 7016

Try below code.

Random rndm = new Random();
            int min =1;
            int max = 10;
            for(int i = 0; i <= 10; i++)
            {
                System.out.println(rndm.nextInt(max - min + 1));
            }

Upvotes: 0

Jayamohan
Jayamohan

Reputation: 12924

This may not be the reply to your query, but you can consider Using Random class.

new Random().nextInt(1000000)

Upvotes: 2

ggcodes
ggcodes

Reputation: 2909

Have this..

 for(i = 0; i <= insertAmount; i++)
    {
        myTree.insert((int)Math.random()*1000000)+i;
    }

You must replace the +1 with i.

hope it helps.

Upvotes: 0

Rahul
Rahul

Reputation: 45070

it should be like this:-

(int)(Math.random()*100000)+1

The reason being your (int)Math.random() is giving 0 always and multiplication with 100000 has no effect. Hence, you're always getting 1 thanks to your +1.

Upvotes: 2

Related Questions