-3

Requirement: I need to perform a task T, N times, within a game that is played for 500 rounds.

I have a loop that runs certain game related tasks 500 times. Within this, I would like to execute task T randomly, N times. Also, N<500.

How does one achieve this?

I know how to execute T within a loop, N times. But, I would like to randomize and execute it N times within 500 rounds of the game.

a_jelly_fish
  • 478
  • 6
  • 21

3 Answers3

1

inside your loop of 500. don't forget to do import random

for i in range (random.randrange(500)):
    your T task
0

What's the problem? Just implement randomization within a loop:

# Very simple example

from random import randint
for x in range(500):
    for y in range(randint(0,500)):
        for z in range(randint(0,y)):
            # Do something
Alec
  • 8,529
  • 8
  • 37
  • 63
0

I assume you want, of course, your N executions of T to be correctly distributed along your 500 rounds, and each execution to be different.

If you're fine with an approximation of N, an on-place solution would be to have a probability of N/500 to run your task each round.

import random

roundNb = 500
N = 10

for i in range(roundNb):
  if random.random() < N / roundNb:
    T()

If it's important for you to have this task performed exactly N times, then it's better to generate N different random numbers < 500 and use them to determinate whether or not your task should be performed this round.

import random

roundNb = 500
N = 10

# random.sample takes N elements of range(roundNb), so N valid roundNumbers
# Convert it to a set so `i in doTaskOn` runs in constant time
doTaskOn = set(random.sample(range(roundNb), N))

for i in range(roundNb):
  if i in doTaskOn:
    T()
qcampos
  • 28
  • 3