[Programming Pearls] Column 1 – Non Dup Random Numbers

Source:
Problem 4

Problem:
Generate k random numbers with no duplicates

Solution 1:

def prog_1_4_gen_list(max, count):
    # TODO: avoid dead loop....
    i = 0
    v = prog_1_2_bitvec(max)
    l = []
    while (i < count):
        num = random.randint(0, max - 1)
        if not v.has(num):
            v.set(num)
            i += 1
            l.append(num)
    return l

Solution 2:
In each cycle of the loop:
- numbers[i + 1 :] is non-dup number pool
- numbers[i] will be a number that randomly chosen from number pool

def prog_1_4_gen_list_2(max, count):
    numbers = [n for n in range(0, max)]
    for i in range(0, count):
        randnum = random.randint(0, max - 1)
        numbers[i], numbers[randnum] = numbers[randnum], numbers[i]
    return numbers[: count]

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>