Building an array of specific size with consecutive element sum being perfect square in JavaScript


We are required to write a JavaScript function that takes in a number n. Our function should return an array of integers 1..n arranged in a way, such that the sum of each 2 consecutive numbers is a square.

Example

The code for this will be −

 Live Demo

const n = 15;
const buildSquaresArray = (n = 1, res = []) => {
   const helper = (res, set, n) => {
      if(set.size === n){
         return true;
      };
      for(let i = 1; i <= n; i++){
         if (set.has(i)){
            continue;
         };
         if(res.length && Math.sqrt(res[0] + i) % 1 !== 0){
            continue;
         };
         set.add(i);
         res.unshift(i);
         if(helper(res,set,n)){
            return true;
         }
         res.shift();
         set.delete(i);
      };
      return false;
   };
   return helper(res,new Set(),n) ? res : false;
};
console.log(buildSquaresArray(n));

Output

And the output in the console will be −

[
   9,  
   7,  
   2,
   14,
   11,  
   5,
   4,
   12,
   13,  
   3,  
   6,
   10,
   15,  
   1,  
   8
]

Updated on: 17-Apr-2021

65 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements