交替排列 [英] Alternating permutations

查看:454
本文介绍了交替排列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这篇文章是我上一篇文章的扩展:大小元素的排列

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:

function Factorial(n) { 
    
    var res=1; 
          
    for (var i = 2; i <= n; i++) 
        res = res * i; 
    return res; 
} 
    
    
let n = 4;
let A = [];
let C = [];
let a = Factorial(n);
for(let i=0; i<=n;i++) {
    A[i] = 0;
}
A[1] = 1;
for(let k=0; k<n; k++) {
    let b = Factorial(k)*Factorial(n-k);
        
    A[k] = a/b * A[k]*A[n-k]/2;
}
console.log(A);

prints [0, 0, 0, 0]

根据我的前一篇文章,我期望输入n = 4的A [n + 1] = 5.但是我得到的都是零.如何解决此问题.

I am expecting A[n+1] = 5 for input n = 4 as per my previous post. But I am getting all zeros. How to fix this issue.

推荐答案

您没有在我还将避免计算阶乘,因为您很快就会遇到浮点精度的限制.您可以改为使用帕斯卡三角形.

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.

这里是A序列的无限生成器的实现.该演示会打印A [0]到A [20]的值:

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() { // generator
    let 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 formula
        let 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 of andre()) {
    console.log(`A[${i++}] = ${a}`);
    if (i > 20) break;
}

随着此序列快速增加,您很快将需要更高的精度.如果您需要 A [i] 以获得更高的 i 值,请使用JavaScript的 BigInt 数据类型.

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.

这篇关于交替排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆