所有的可能性,小于只使用ÿ数X? [英] All possibilities that are less than X using only Y numbers?

查看:139
本文介绍了所有的可能性,小于只使用ÿ数X?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这些数字:2,25,37,54,54,76,88,91,99](这是随机的)

Say I have these numbers: [2, 25, 37, 54, 54, 76, 88, 91, 99] (these are random)

和我需要找到那些小于100并非所有的数字都在这些组合中使用的号码的所有组合。例如:2,2 + 25 + 37,+ 54 25

And I need to find all combinations of those numbers that are less than 100. Not all numbers have to be used in these combinations. Examples: 2, 2+25+37, 54+25

我怎么能在JavaScript中实现这一目标?

How can I achieve this in JavaScript?

感谢

推荐答案

所以,如果你有一个数字数组:

So if you have an array of numbers:

var arr = [2, 25, 37, 54, 54, 76, 88, 91, 99]

第一滤波器阵列到只是小于100

First filter the array to just that which is less than 100

var filtered = arr.filter(function(val){ return val < 100; });

现在,你需要找到的幂集这些数字。

Now you need to find the power set of those numbers.

它看起来像有中code 这里的样本,将实现这一目标。

It looks like there's a sample of code here that will accomplish that.

摘录

function powerset(arr) {
    var ps = [[]];
    for (var i=0; i < arr.length; i++) {
        for (var j = 0, len = ps.length; j < len; j++) {
            ps.push(ps[j].concat(arr[i]));
        }
    }
    return ps;
}

所以,你会采取

var powerSet = powerset(filtered);

和一些糖,可以用加入很好地格式化结果

And as some sugar, you could format the result nicely with join

console.log('{' + powerSet.join('}{') + '}');

如果你真的想为一组所有集合的输出,这在技术上是更正确的:)

or if you really want it output as a set of all sets, this would technically be more correct :)

console.log('{ {' + powerSet.join('}{') + '} }');

下面是一个 工作演示

Here's a WORKING DEMO

修改

很抱歉,您要设置其所有套小于100肯纳贝克是正确的。沟过滤第一步,然后修改幂方法从而减少使用快速查看,如果一个数组的总和小于100:

Sorry, you want the set of all sets whose sum is less than 100. kennebec is right. Ditch the filtering first step, and then modify the powerset method thus, using reduce to quickly see if an array's sum is less than 100:

function powerset(arr) {
    var ps = [[]];
    for (var i=0; i < arr.length; i++) {
        for (var j = 0, len = ps.length; j < len; j++) {
            var arrCandidate = ps[j].concat(arr[i]);
            if (arrCandidate.reduce(function(p, c){ return p + c; }) < 100)
                ps.push(arrCandidate);
        }
    }
    return ps;
}

下面是一个已更新DEMO

Here's an UPDATED DEMO

这篇关于所有的可能性,小于只使用ÿ数X?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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