Doing a While/Loop to Get 10 Random Results

Doing a while / loop to get 10 random results

Note, read before the real answer: for the ones that keep downvoting this answer. Read the title (that starts with "Doing a while") and the final part, the question ("Is there anyway i can add a while to that so it does it 10 times ?"). This answer is about iterating the result set, not about the usage of the RAND function! The query doesn't even appear in my answer, and I am also suggesting a different approach at the end:


you just need to wrap your call to mysql_fetch_object in a loop

$result = mysql_query($sql);

while ($row = mysql_fetch_object($result))
{
echo "<a href='index.php'>" .$row->tagname. " </a>";
}

Later edit
Other considerations would be:

  • if the table hold a very big amount of data (but it doesn't seem that it will) order by rand() can have a bad effect on the performance
  • consider using pdo (or at least mysqli)
  • you should have some error handling even if the query seems to be
    perfect, at least

    if (!$result)
    {
    echo mysql_error();
    die;
    }

Generating random numbers inside while loop until desired number is generated

Ideally you would exclude the invalid possibilities before calling the random. Eventually one random call over the two axis (-> 10x10 possiblities) minus the invalid ones.

But if this becomes over-complicated, I consider your approach as ok, no bad practice. How critical is your mission? For examples, if human lifes are concerned, that would be too much risks. If it is for a game or a shop, something the user can re-try, it is sufficient.

Do you really want this endless loop? Perhaps limit to 100 or 1000 times. If over, log and abort. Then monitor your log, if possible. You can then re-consider your algorithm if the error rate goes up (perhaps if walls get longer or matrix get smaller, you would have more invalid combinations).

Is there a way to store the result of a while loop (using the random module) inside a new variable - to be reused?

You can greatly simplify your code if you separate out the logic that choose the random flashcards from the loop that presents them to the user. The former can be really easy using random.sample!

import random

flashcards = {"flash_0" : {"vecka (n)": "week"},
"flash_1" : {"år (n)": "year"},
"flash_2" : {"idag (adv)": "today"},
"flash_3" : {"imorgon (adv)": "tomorrow"},
"flash_4" : {"igår (adv)": "yesterday"},
"flash_5" : {"kalender (n)": "calendar"},
}

sample = random.sample(flashcards.values(), 5) # pick 5 random values without repeating

for value in sample: # loop over the values in the sample
print()
time.sleep(3)
print(value)

You can then reuse the same sample for other code if you want.

As a final note, the flashcards dictionary would problable be better as a list, since the keys are not very meaningful (just a fixed string followed by an integer, where a list would just be indexed by the integer directly). Similarly, the values might be better as 2-tuples, rather than as one-element dictionaries. Dictionaries are great, but they're not ideal everywhere!

R: Stopping a Loop When a Condition is Met

I hope these comments help to follow how it works. It mainly makes use of repeat which is just an infinite loop. It can be stopped using the break keyword.

results <- list()

for (i in 1:10){

# do until break
repeat {

# repeat many random numbers
a = rnorm(1000,10,1)
b = rnorm(1000,10,1)

# does any pair meet the requirement
if (any(a > 10 & b > 10)) {

# put it in a data.frame
d_i = data.frame(a,b)

# end repeat
break
}
}

# select all rows until the first time the requirement is met
# it must be met, otherwise the loop would not have ended
d_i <- d_i[1:which(d_i$a > 10 & d_i$b > 10)[1], ]

# prep other variables
d_i$index = seq_len(nrow(d_i))
d_i$iteration = as.factor(i)

results[[i]] <- d_i

}

How to make random numbers in a while loop independent from each other?

The basic problem is that rand is not generating real random numbers: In computing, to generate random numbers is a very complex problem, and the solution is (generally) to use pseudo-random number, which seem random but each number is built based on the previous one:

e.g.

n0 = 5 (seed = 5)

n1 = ((n0*10+1) % 7) = 2

n2 = ((n1*10+1) % 7) = 0

n3 = ((n2*10+1) % 7) = 1

n4 = ((n3*10+1) % 7) = 4
...

Where the 10, 7 and 1 have to be carefully selected to get seemingly
random numbers.

https://en.wikipedia.org/wiki/Linear_congruential_generator

srand set the first seed value, and each new random use the previously generated random value as seed.

Setting a specific value to srand will generate the exact random numbers serie again and again which is useful for testing. To make something more "random" the seed is usually set to the current time, which is expected to change over time.

The problem in your code is: your loop is too fast in order to get different time values each loop, that mean you set several times the seem value to the seed, generating the same random result.

As suggested, you need to set the seed outside the loop, so each random take the previous random result as seed and generate a seemingly new random number.

srand((unsigned int) time(NULL));   // Seed
while(1) {
double chance = random() / (double) RAND_MAX;
if (chance <= 0.95)
printf("All ok.\n");
else
printf("ERROR\n");
}


Related Topics



Leave a reply



Submit