Split number into 4 random numbers

前端 未结 7 815
-上瘾入骨i
-上瘾入骨i 2020-12-30 08:11

I want to split 10 into an array of 4 random numbers, but neither can be 0 or higher than 4. For example [1,2,3,4],

7条回答
  •  被撕碎了的回忆
    2020-12-30 08:42

    Basically you need the partitions (See https://en.wikipedia.org/wiki/Partition_(number_theory)) of 10 and apply your conditions on the resulting set.

    // Partition generator taken from 
    // https://gist.github.com/k-hamada/8aa85ac9b334fb89ac4f
    
    function* partitions(n) {
    
        if (n <= 0) throw new Error('positive integer only');
        yield [n];
    
        var x = new Array(n);
        x[0] = n;
        for (var i = 1; i < n; i++) x[i] = 1;
    
        var m = 0, h = 0, r, t;
        while (x[0] != 1) {
            if (x[h] == 2) {
                m += 1;
                x[h] = 1;
                h -= 1;
            } else {
                r = x[h] - 1;
                x[h] = r;
    
                t = m - h + 1;
                while (t >= r) {
                    h += 1;
                    x[h] = r;
                    t -= r;
                }
                m = h + (t !== 0 ? 1 : 0);
                if (t > 1) {
                    h += 1;
                    x[h] = t;
                }
            }
            yield x.slice(0, m + 1);
        }
    }
    
    results = [];
    // Get all possible partitions for your number
    for (var partition of partitions(10)) {
        // Apply your conditions (must be 4 numbers, none of them greater than 4)
        if(partition.length != 4 || partition.some((x) => x > 4)) continue;
        results.push(partition);
    }
    console.log(results);

提交回复
热议问题