Learn Functional Programming by Building a Spreadsheet - Step 100 (Random Property)

Hi,
I think there is a couple of bugs in this step of the project.

  1. Difference between prompt and test
    The prompt is: “Add a random property which takes the first two numbers from an array and returns a random number between them. Use the Math.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: " Your random function should return a whole number (integer).
    But the prompt doesn’t say anything about whole numbers.

  2. 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.

  3. 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.

  1. 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 to sum(-1,2).
    So it seems that one of the functions that evaluates the content of the cells can’t handle negative values.

  2. 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.

Would you mind opening a github issue for this?

I opened the issue. I hope :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.