ratio-chain.js 869 B

123456789101112131415161718192021222324
  1. /*
  2. Given the ratio a : b : c = 2 : 3 : 4
  3. What is c, given a = 40?
  4. A general ratio chain is a_1 : a_2 : a_3 : ... : a_n = r_1 : r2 : r_3 : ... : r_n.
  5. Now each term can be expressed as a_i = r_i * x for some unknown proportional constant x.
  6. If a_k is known it follows that x = a_k / r_k. Substituting x into the first equation yields
  7. a_i = r_i / r_k * a_k.
  8. Given an array r and a given value a_k, the following function calculates all a_i:
  9. */
  10. function calculateRatios(r, a_k, k) {
  11. const x = Fraction(a_k).div(r[k]);
  12. return r.map(r_i => x.mul(r_i));
  13. }
  14. // Example usage:
  15. const r = [2, 3, 4]; // Ratio array representing a : b : c = 2 : 3 : 4
  16. const a_k = 40; // Given value of a (corresponding to r[0])
  17. const k = 0; // Index of the known value (a corresponds to r[0])
  18. const result = calculateRatios(r, a_k, k);
  19. console.log(result); // Output: [40, 60, 80]