在 JavaScript 中构建一个特定大小的数组,其中连续元素和是完美的平方
我们需要编写一个接受数字n的JavaScript函数。我们的函数应该返回一个以某种方式排列的整数数组1..n,使得每2个连续数字的和是一个正方形。
示例
此代码将是-
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));输出结果
控制台中的输出将是-
[ 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8 ]