# How to design a random algorithm?

I’m gonna design a random algorithm to draw a random number from an array.

In the others advanced language, there is a random function of math to achieve this goal(like Math. random () function). But I’m not sure that solidity has the same function. I didn’t find any from the safemath contract at least.

I know maybe it is not smart to deal with math in a smart contract. But I’m just considering the possibilities. So,

• can anyone help design a random algorithm to pick a number from an array?
• Or design a random array instead of picking a random number from a fixed array.
1 Like

As a matter of fact, it is difficult to generate a random number on the ethereum, because the miner can manipulate some variable, such as timestamp, and block number. I think you can have a look at this article: how-to-safely-generate-random-numbers-in-solidity-contracts, and a tool of the chainlink: Chainlink VRF

2 Likes

hi, @Skyge
Thank you so much for telling me the message which is useful. And I’ve reconsidered another idea base on understanding this message. Hope to get your suggestions.

I’m gonna develop a random purchase contract. The main function like:
get a random number just following the
`uint randomnuber = unit(keccak256(abi.encodepacked(now,msg.sender,nonce)));`
`nonce` is a number from the front-end calculated by a random algorithm outside the ethereum.
use openzeppelin’s safemath contract to calculate the other randomnumber:
`uint purchasenumber = safemath.mod(randomnumber, N)`
the N is total number of goods and it is dynamically changed.

I thought this kind of method is still risky that the randomnumber is still easily manipulated. But it may be safer than before.

How do you think?

1 Like

For the variable `N`, how to change it dynamically?
And it still doesn’t sound like a good idea, cause the miner can get all values to calculate, but as a pseudo random, it is ok.

2 Likes

I will make a modifier to update the queue of goods and update the queue.length to `N`. Whenever the goods are added or deleted, the length will be changed dynamically.
Agree with your view of miners can get all values to calculate. It’s enough temporarily as a pseudo-random.
Thanks for your replying

1 Like

Hi @uua,

Anything generated onchain is deterministic so I would avoid calling it pseudo-random, even if this is enough for your use case.

You could look at how other projects do randomness:

1 Like

Thanks for your suggestion! I’m totally sure Chainlink VRF will be the next step action to improve my contract security. Thanks again @abcoathup @Skyge

1 Like