DEV Community

Discussion on: Daily Challenge #14 - Square into Squares

Collapse
 
alvaromontoro profile image
Alvaro Montoro

JavaScript

const decompose = number => {
  let components = [];
  let modifier = 1;
  do {
    // initialize the values before the loop
    components = [];
    let remaining = number ** 2;

    // from number - 1 until 1 check if the square of the number is less than the remaining
    for (let number = Math.floor(Math.sqrt(remaining)) - modifier; remaining > 0 && number > 0; number--) {
      if (number**2 <= remaining) {
        components.push(number);
        remaining -= number**2;
        // if a squared component is found, continue from the square root of the remaining
        number = Math.floor(Math.sqrt(remaining)) + 1;
      }
    }
    // the modifier is used to check for the next set of
    modifier++;
  // do this while there are duplicates (duplicates mean that one number -in particular 1- was repeated)
  // this code is a variation of https://stackoverflow.com/a/34192063/3695983
  } while (components.length !== new Set(components).size);
  return components.reverse();
}

And a live demo on CodePen.

Collapse
 
alvaromontoro profile image
Alvaro Montoro

Not really inspired lately, my code is getting bigger and messier... and I'm running behind on these challenges :-/

Collapse
 
coreyja profile image
Corey Alexander

I feel ya! Me tooooo

I got this one started but ran into a tougher example that I haven't worked through yet! Definitely want to get it wrapped up but I'm definitely not doing 1 a day anymore