Files
freeCodeCamp/curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69f8c998d78ad3171a0713bf.md
T

2.0 KiB

id, title, challengeType, dashedName
id title challengeType dashedName
69f8c998d78ad3171a0713bf Challenge 292: Wider Aspect Ratio 28 challenge-292

--description--

Given two strings for different image dimensions, return the aspect ratio of the image with a greater width-to-height ratio.

  • The given strings will be in the format "WxH", for example, "1920x1080".
  • The aspect ratio is the ratio of width to height, reduced to the lowest whole numbers. For example, "1920x1080" reduces to "16:9".
  • Return a string in format "W:H", for example, "16:9".

--hints--

getWiderAspectRatio("1920x1080", "800x600") should return "16:9".

assert.equal(getWiderAspectRatio("1920x1080", "800x600"), "16:9");

getWiderAspectRatio("1080x1350", "2048x1536") should return "4:3".

assert.equal(getWiderAspectRatio("1080x1350", "2048x1536"), "4:3");

getWiderAspectRatio("640x480", "2440x1220") should return "2:1".

assert.equal(getWiderAspectRatio("640x480", "2440x1220"), "2:1");

getWiderAspectRatio("360x640", "1080x1920") should return "9:16".

assert.equal(getWiderAspectRatio("360x640", "1080x1920"), "9:16");

getWiderAspectRatio("3440x1440", "2048x858") should return "43:18".

assert.equal(getWiderAspectRatio("3440x1440", "2048x858"), "43:18");

getWiderAspectRatio("12345x61234", "12534x51234") should return "2089:8539".

assert.equal(getWiderAspectRatio("12345x61234", "12534x51234"), "2089:8539");

--seed--

--seed-contents--

function getWiderAspectRatio(a, b) {

  return a;
}

--solutions--

function getWiderAspectRatio(a, b) {
  function gcd(x, y) {
    return y === 0 ? x : gcd(y, x % y);
  }

  function parse(str) {
    const [w, h] = str.split("x").map(Number);
    const g = gcd(w, h);
    return { ratio: w / h, simplified: `${w / g}:${h / g}` };
  }

  const imageA = parse(a);
  const imageB = parse(b);

  return imageA.ratio >= imageB.ratio ? imageA.simplified : imageB.simplified;
}