Skip to content Skip to sidebar Skip to footer

Generate Random Non Repeating Samples From An Array Of Numbers

I made a battleships game and I now need to make sure that the computer doesn't attack at the same spot twice. My idea of it is storing each shot's co-ordinates in a variable which

Solution 1:

I first answer in a language agnostic way.

A very efficient way would be to keep a sequential list of all the possible positions (in your case 5x5=25 positions), use a single random choice in that list and then removes the position from the list. This saves you from the what to do when I hit a position I've already hitted

Python implementation :

First generate the list of positions :

positions = [ (i, j) for i in range(1,6) for j in range(1,6) ]

Then get a random position and remove it from the list

index = random.randrange(len(positions))
shotX, shotY = positions[index]
del positions[index]

Edit :

As a prove it should fork :

>>>import random>>>positions = [ (i, j) for i inrange(1,6) for j inrange(1,6)]>>>for i inrange(25):
    index = random.randrange(len(positions))
    print positions[index]
    del positions[index]


(5, 5)
(5, 4)
(1, 4)
(1, 2)
(3, 3)
(1, 1)
(4, 1)
(4, 4)
(5, 1)
(4, 2)
(2, 2)
(2, 4)
(2, 3)
(2, 1)
(3, 2)
(3, 5)
(1, 5)
(5, 3)
(5, 2)
(4, 3)
(4, 5)
(1, 3)
(3, 4)
(2, 5)
(3, 1)
>>>print positions
[]

Solution 2:

You could keep a log of all the shots fired:

# during initialization
fired = set()
# ... skipping to the interesting part ...
eg.msgbox("The computer will now attack!")
whileTrue:
    shotX = random.randint(1,5)
    shotY = random.randint(1,5)
    if (shotX, shotY) notin fired:
        break# OK, no need to look any further# else try another shot...
eg.msgbox ("The computer shot at {0}, {1}".format(shotX, shotY))
fired.add((shotX, shotY))

I've also kept shotX and shotY as integers (you might need them that way later if you want to look up indices in a matrix, for example.

Solution 3:

U can use a random permutation of n targets and shoot a target from this randomly permuted list. Use random.shuffle for this like below. I have shown a sample output for non-repetitive randomly generated in range of 5. Use this shuffled list to target without having to check if you have already taken this shot.

>>>s=list(range(5))>>>s
    [0, 1, 2, 3, 4]
>>>random.shuffle(s)>>>s
    [3, 4, 2, 1, 0]
>>>s
    [3, 4, 2, 1, 0]
>>>random.shuffle(s)>>>s
    [4, 0, 2, 1, 3]
>>>random.shuffle(s)>>>s
    [2, 1, 3, 0, 4]

Post a Comment for "Generate Random Non Repeating Samples From An Array Of Numbers"