Alternating Permutations
This post is extension to my previous post: Permutations of small and large elements I m trying to work on alternating permutations and here is my logic: prints [0, 0, 0, 0] I am
Solution 1:
You did not implement the sum (∑) in the formula of André that your refer to.
I would also avoid calculating factorials as you will soon bump into a limitation of floating point precision. You can instead use the triangle of Pascal.
Here is an implementation of an infinite generator of the A sequence. The demo prints the values of A[0] up to A[20]:
function * andre() { // generatorlet pascal = [1];
let a = [1, 1];
yield a[0];
let n = 1;
while (true) {
yield a[n];
// Build the next row in Pascal's Triangle
pascal[n] = 1;
for (let i = n - 1; i > 0; i--) {
pascal[i] += pascal[i-1];
}
// Apply André's formulalet sum = 0;
for (let k = 0; k <= n; k++) {
sum += pascal[k] * a[k] * a[n-k]
}
a[++n] = sum / 2;
}
}
// demo: display A[0] up to A[20]let i = 0;
for (let a ofandre()) {
console.log(`A[${i++}] = ${a}`);
if (i > 20) break;
}
As this sequence increases fast, you'll need higher precision soon. If you need A[i] for higher values of i, then use JavaScript's BigInt
data type.
Post a Comment for "Alternating Permutations"