Hi,
I think there is a couple of bugs in this step of the project.
-
Difference between prompt and test
The prompt is: “Add arandom
property which takes the first two numbers from an array and returns a random number between them. Use theMath.random()
function to help.”
My first try was:
random: nums => Math.random() * (nums[1] - nums[0]) + nums[0]
My code didn’t pass and the hint was: " Yourrandom
function should return a whole number (integer).
But the prompt doesn’t say anything about whole numbers. -
The tests accept incorrect code.
I updated my function to:
Math.floor(Math.random() * (nums[1] - nums[0]) + nums[0])
My code passed the tests but it shouldn’t.
e.g.
If you type =random(0.5, 4) into one of the cells and hit enter, the result can be zero, which is not between 0.5 and 4.
If you type =random(2, 4) into one of the cells, the result will be 2 or 3 but never a 4.
If you type =random(4, 2) into one of the cells, the result will be 2 or 3 or 4. But it will be 4 only when Math.random() returns exactly zero, which almost never happens. But the main point is that if you input 2 and 4 as parameters to the function it can return different results, which seems wrong. -
Suggestion
The best I was able to come up with is the following code:
random: nums => {
const minCeil = Math.ceil(Math.min(nums[0], nums[1]));
const maxFloor = Math.floor(Math.max(nums[0], nums[1]));
return Math.floor(Math.random() * (maxFloor - minCeil + 1)) + minCeil;}
If I’m correct, this should solve the problem with the order of the input values and all possible return values should be represented with the same probability.
-
Negative values
When I was trying to test the function I noticed that I can’t use negative values. Not only for the random function but for any of them.
e.g. When I tried=sum(-1, 2)
in a cell and hit enter, the text in the cell changed tosum(-1,2)
.
So it seems that one of the functions that evaluates the content of the cells can’t handle negative values. -
Random function in the next step
When you submit the code and go to the next step, your function changes to:
random: ([x, y]) => Math.floor(Math.random() * y + x)
This is just wrong because if you type =random(5, 7) into a cell, the function will return values between 5 and 11.