What is there in code, Just Explanation;

So, Really good question, but sorry for making this much big post.
For those who all are asking question how Leetcode is judging answer to question. Or saying their code is generating random numbers between 1 to 10, but then also their answer is wrong.
Let me start with my expanation,
There are a lot of ways of thinking of this question, but question is not about randomness of your number, IT IS ONLY ABOUT PROBABILITY OF EACH NUMBER IN YOUR FUNCTION.
First of all thoughts that come in mind, one of them is generating a number x between 1 to 7 and y between 1 to 3 and return an answer adding them. But see that your function is never going to generate number '1' and neither probability of each number is same.
Or generating two number between 1 to 5 and return sum of both numbers.
So Probability of numbers is much important their randomness.
Here are some attached images which tells about wrong probabilty in both the approach.
image
image

And then comes an question, what is correct way of thinking.
So the answer is think something about 1,
First of all, you know that this is not possible with one number. so, you need atleast two values.
So, If you generate a number '1' then somehow other number should be there as 0 to keep its probability on track.
So we can converse our first number let it be x to produce value between 1 to 5 by using simple while loop.

int x=6;
        while(x>5)
            x=rand7();

Now, how can we produce 0 and which is not possible using only rand7, but ya, there is "remainder" which we can use to produce zero.
so if we get a number as 0 or 1.
we can add or subtract it from something 2*x which produce a number which is even that is 2,4,,8,10.
and then we can do simple thing be subtracting zero or one from each even number to get probabilty to each number same.
See the picture.
image
IF you like my explanation, upvote so that everybody can get help.
And if you didn't like
COMMENT what is missing or wrong Here.

Comments (0)