Replies: 2 comments 1 reply
-
Hello! This would be a better stack exchange ETH question since it doesn't apply to this course. Could you make this question there? |
Beta Was this translation helpful? Give feedback.
-
Although @PatrickAlphaC asked that you send this question on stack exchange ETH, I still have an answer for you. @yashm001, could you provide the link to your renewed question on stack exchange so that I can answer there too? What you are asking for is weighted uniform sampling. Let's look at a small example in order to understand our problem, starting with symbolic math and then ending with some code. We have 4 addresses,
Now, in Solidity, we try not to work with floating point numbers, to avoid rounding numbers inadvertently. There are two ways to approach this. Either you bring your probabilities In the first case, you could do the following (not gas optimal and hard coded, but for the sake of clarity): function wSampling(uint256 randomWord) internal view returns (address) {
address x1 = 0x//someaddress;
// ...
address x4 = 0x//someOtheraddress;
// Our 2 ** 256 - 1.
uint256 MAX_INT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; // "f"*64 ;)
// Here, we have to understand that by dividing by 4 or 10, we are losing some precision,
// since it's a uint division and 2 ** 256 - 1 is not divisible by 2.
uint256 p1 = MAX_INT/10; // 0.10
uint256 p2 = MAX_INT/4; // 0.25
uint256 p3 = (MAX_INT/10)*4; // 0.40
uint256 p4 = MAX_INT/4; // 0.25
if( randomWord <= p1) { return x1; }
if( randomWord <= p1 + p2) { return x2; }
if( randomWord <= p1 + p2 + p3) { return x2; }
else { return x4;}
} It's important to note here that since |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hey everyone!
I am working on a smart contract which involves selecting a random address from an array. I am using Chainlink VRF for generating random number and select the address at that particular index.
But the twist here is that, there is a selection probability associated with every address.
I read the chainlink VRF docs but couldn't find a work around. Can anybody please help me out here?
Beta Was this translation helpful? Give feedback.
All reactions