Magic squares of doubly even order: Difference between revisions
Content deleted Content added
→JS ES6: Updated primitives, tidied. |
|||
Line 1,278:
'use strict';
//
const
const
sqr = n * n,
power = Math.log2(sqr),
scale = replicate(n / 4);
return chunksOf(n)(
map((x, i) => x ? 1 + i : sqr - i)(
isInt(power) ? truthSeries(power) : (
compose(
flatten,
scale,
map(scale),
chunksOf(4)
)(truthSeries(4))
)
)
);
})() : undefined;
0 >= n
[true]
) : (() => {
const xs = truthSeries(n - 1);
return xs.concat(xs.map(x => !x));
})();
// TEST -----------------------------------------------
const
// Magic squares of
map(n => {
lines =
sums =
.concat(diagonals(lines))
)
.map(xs => xs.reduce((a, b) => a + b, 0)),
sum = sums[0];
return [
"Order: " + n.toString(),
"Summing to: " + sum.toString(),
"Row, column and diagonal sums checked: " +
all(eq(sum))(sums)
.toString() + '\n',
lines.map(
xs => xs.map(
compose(justifyRight(3)(' '), str)
)
.join(' '))
.join('\n')
].join('\n')
})([4, 8, 12])
.join('\n\n');
// GENERIC FUNCTIONS ----------------------------------
// all :: (a -> Bool) -> [a] -> Bool
const all = p =>
// True if p(x) holds for every x in xs.
xs => xs.every(p);
//
const
enumFromThenTo(0)(n)(
xs.length - 1
).reduce(
(a, i) => a.concat([xs.slice(i, (n + i))]),
[]
);
//
const
x => fs.reduceRight((a, f) => f(a), x);
//
const
const
nCols = 0 < nRows ? (
xs[0].length
) : 0;
return nRows !== nCols ? [
[],
[]
] : (() => {
const
ns = enumFromTo(0)(nCols - 1),
f = zipWith(x => y => xs[y][x])(ns);
return [f(ns), f(reverse(ns))];
})();
};
//
const
const d = x2 - x1;
length: Math.floor(y - x2) / d + 2
};
//
const
Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// eq (==) :: Eq a => a -> a -> Bool
const eq = a => b => a === b;
// flatten :: NestedList a -> [a]
const flatten = nest => nest.flat(Infinity);
//
const
//
const
// map
(Array.isArray(xs) ? (
) :
//
const
},
// reverse :: [a] -> [a]
const reverse =
xs.slice(0).reverse()
) : xs.split('').reverse().join('');
// show :: a -> String
const show = x => JSON.stringify(x);
//
const
// transpose :: [[a]] -> [[a]]
const transpose = xs =>
xs[0].map((_, iCol) => xs.map((row) => row[iCol]));
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f => xs => ys =>
xs.slice(
0, Math.min(xs.length, ys.length)
).map((x, i) => f(x)(ys[i]));
// MAIN -----------------------------------------------
return
})();</lang>
{{Out}}
<pre>Order: 4
|