Search code examples
javascriptrandomprobability

Chance of obtaining fish element Probability


I'm trying to get the percentage of getting some fish. X is the unique number here, it's between 0-99, but in my example code it's 70, for test purposes.

But currently it returns really wrong results, so I'm doing something wrong here.

Current output:

[-0.17142857142857143, 0.04285714285714286, 0.2571428571428571, 0.2714285714285714]

Which means

  • -17% to get fish1,
  • 4.2% for fish2,
  • 25.7% fish3,
  • 27% fish4.

The correct math is as follows:

If X number is 82+, it will get fish 1. If X number is 67+, it's fish 2 (unless 82+ etc). If x number is 52+ it's fish 3. if it's 51 or less, it's fish 4.

So, in theory, with a x of 85, its a 3/85 chance of obtaining it.

Then I need the probability by the current X of getting that specific fish. What am I doing wrong here?

function fishesPercentage(X) {
  var NumberSelected = RandomNumber(0,X-1);
  NumberSelected = 70;
  console.log("RANDOOM NUMBER IS : ",NumberSelected);
  let Fish1 = NumberSelected - 82;
  let Fish2 = NumberSelected - 67;
  let Fish3 = NumberSelected - 52;
  let Fish4 = NumberSelected - 51;

  return [
    Fish1/ NumberSelected,
    Fish2/ NumberSelected,
    Fish3/ NumberSelected,
    Fish4/ NumberSelected
  ];
}

Solution

  • You want the probabilities of obtaining fishes 1 to 4 for a given number X, and a series of ranges. The total number of fishes is:

    Fish 4) 51 or X (if X is lower)

    Fish 3) 68-51 o X-51 (if X is lower than 68)

    etc.

    If any of these X-N is negative, that means that there are no fishes of that type.

    This could be achieved with any of the two functions below:

    function fishProb(x) {
        let fish4 = Math.max(Math.min(x, 51),0)
        let fish3 = Math.max(Math.min(x-51, 68-51),0)
        let fish2 = Math.max(Math.min(x-68, 82-68),0)
        let fish1 = Math.max(Math.min(x-82, 99-82),0)
        return([fish1, fish2, fish3, fish4].map(f => f/x))
    }
    
    function fishProb2(x) {
        var allFishes = x
        var fishType = [51, 68-51, 82-68, 99-82]
        var fishes = []
        for (const currentFishes of fishType) {
            fishes.push( Math.max(Math.min(allFishes, currentFishes), 0) )
            allFishes -= currentFishes
        }
       return(fishes.map(f => f/x).reverse())
    }
    

    Both functions return the same thing. The second one I think expresses the problem in a simpler way.

    If you have X=70 then you have 51 Fish4, from the remaining 70-51 you have (68-51) of Fish3, and the other 3 remaining are Fish2. No Fish1 are in the lot.

    //X = 70
    [0, 0.02857142857142857, 0.24285714285714285, 0.7285714285714285]
    
    //X = 85
    [0.03529411764705882, 0.16470588235294117, 0.2, 0.6]
    
    //X = 20. In this case you only have 20 Fish4 and none of the others.
    [0, 0, 0, 1]