@jonathanbell/Solving the watermelon problem
JavaScript

Trying to solve the watermelon problem. See: https://thatsmaths.com/2013/11/14/the-watermelon-puzzle/ for the original problem

fork
loading
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function stripFloat(number) {
  // https://stackoverflow.com/a/3644302/1171790
  return (parseFloat(number).toPrecision(12));
}

/**
 * Given a shipment start weight and a final water content (percentage), 
 * calcs the final weight of a shipment after water evaporation.
 *
 * @param {number} startWeight Total starting weight (lbs, kg, etc) of the 
 *   shipment (before transport).
 * @param {float} endWaterPercentage Water content represented as a
 *   percentage post-shipment.
 * @return {float} The total weight of the shipment upon arrival (post
 *   shipment) and post water evaporation.
 */
function getFinalWatermelonWeight(
  startWeight = 100, 
  endWaterPercentage = 0.98
) {
  const endPithPercentage = 1 - endWaterPercentage;
  const endWeight = startWeight / (endPithPercentage * 100);

  // Handle floating point percision
  return stripFloat(endWeight);
}

console.log(getFinalWatermelonWeight()); // watermelons weigh half of their original weight
console.log(getFinalWatermelonWeight(200, 0.98));
console.log(getFinalWatermelonWeight(200, 0.99));
console.log(getFinalWatermelonWeight(123, 0.95)); // 24.6 kg, or whatever
Native Browser JavaScript