2

I know that the topic of random number has been discussed tremendous amount of times already but I have one small question.

I need to get a pseudo random number (not ungamealbe), as simply as possible. The problem is that I need the number to be either 1 or 0 and I want the value to be able to be odd or even in every loop iteration.

If I use something like:

while(x < 10) {
uint randomNumberBetween0And1 = uint(keccak256(abi.encodePacked(block.difficulty, now))) % 2;
x++;
}

this value will be either 10 times 0 (0 in each iteration because random number is even) or 10 x 1 (because random number will be odd every single time). How can I make the random differ between the iterations?

3
  • 1
    Hi there. If I'm understanding your question correctly, you could use the x variable as a nonce (as well as a loop counter), and incorporate it into what you pass to the keccak() call. Oct 8, 2018 at 17:57
  • Hey, thanks for anwser. In my case it's actually a while(true) kind of loop so I don't have x. Is there any way without the counter?
    – lemme
    Oct 8, 2018 at 18:27
  • 1
    just replace x<10 with true, but don't forget a break. However, you'll have to keep the counter, but that shouldn't be a problem?
    – ivicaa
    Oct 8, 2018 at 18:29

1 Answer 1

1

Try this:

while(x < 10) {
    uint rnd = uint(keccak256(block.difficulty, now, x)) & uint(0x1);
    x++;
}

or if you have a while(true) as you wrote above:

uint x = 0;
while(true) {
    uint rnd = uint(keccak256(block.difficulty, now, x++)) & uint(0x1);

    ...YOUR CODE HERE hopefully with a condition for break...
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.