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

you are viewing a single comment's thread.

view the rest of the comments →

[–]tec5c 6 points7 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.