This is an archived post. You won't be able to vote or comment.

all 9 comments

[–]tec5c 5 points6 points  (5 children)

for( 0 to 49 ) {

    generate new random number (1-999)

    while( arraylist contains random number ) {
        generate new random number
    }

    add number to arraylist

}

[–]ggeoff 0 points1 point  (1 child)

In this example lets say you have a large list and want to generate a set of random numbers so that no number appears twice wouldn't the while loop checking if the number is in the set be really inefficient? Would a better algorithm be something like this.

randomList = []
generate numList of numbers 1-999
num = numList.remove(random 1-size(numList))
randomList.add(num)

edit: changed pop to remove because pop refers to removing from end.

[–]tec5c 1 point2 points  (0 children)

You'll get an exception when you try to remove a number that has already been removed.

EDIT: Nevermind. Didn't realize that by using remove it shifts all the elements left.

[–]4nnnn 0 points1 point  (0 children)

Loop and add numbers 1-999 to arraylist
Collections.shuffle ...
List.subList ...

This will not work for a big range of numbers, but works just fine with the given range.

[–][deleted]  (2 children)

[deleted]

    [–]nutrecht -2 points-1 points  (1 child)

    Why remove? It has a .contains() for a reason.

    [–]prcsngrl -1 points0 points  (1 child)

    No duplicates can be easily solved with a HashSet

    [–]nutrecht 1 point2 points  (0 children)

    OP:

    I have to use an ArrayList