首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从该和到值的列表中获取元素数组

从该和到值的列表中获取元素数组
EN

Stack Overflow用户
提问于 2021-09-27 23:03:05
回答 1查看 684关注 0票数 1

下面是我问题的简化版本,下面的背景摘要提供了一个更好的背景。

问题:

创建一个函数,该函数列出数组中与给定值之和的列表中的所有元素。

Given:

代码语言:javascript
复制
List<int> list = new List<int>() { 1, 2, 3, 4, 5, 9 };

如果提供的值为10,则函数应该返回一个数组,其中包含列表1、2、3、4和1、4、5、2、3、5和1、9。

背景:

我正在尝试数字化一个名为Pastra (或Bastra)的旧纸牌游戏,目的是从董事会收集卡片。您只能收集与牌号值相匹配的卡,也只能收集与牌号相加的任何编号卡。王牌是1分。

我已经有了收集具有同等价值的卡片的代码。

我需要的是从原始列表中创建一个包含与给定值之和的元素的值数组。

我需要知道哪个列表更大,以及知道哪个列表包含哪些卡片,这样同一张卡片就不会被收集超过一次。(注:这超出了这个问题的范围。我想要自己发现,然而,它是为了提供上下文,为什么我需要这种方式的信息)。

示例:

和上面一样,如果董事会有一个Ace,2,3,4,5和9,如果我要玩10,我可以收集Ace,2,3,4,或者Ace,4,5,或者2,3,5,或者Ace,9。

谢谢你的帮助,非常感谢。

EN

回答 1

Stack Overflow用户

发布于 2021-09-28 00:12:35

这里是一个递归的解决方案,它可以找到所有正数的组合。如果数字集包含重复数字,它不会删除重复的组合。

代码语言:javascript
复制
IEnumerable<IReadOnlyList<int>> FindCombosThatAddToValue(IReadOnlyList<int> numbers, int value)
{
    var indices = new BitArray(numbers.Count);
    var combos = new List<IReadOnlyList<int>>();
    FindCombos(0, 0);
    return combos;

    void FindCombos(int index, int total)
    {
        if (index >= numbers.Count)
            return;

        var n = numbers[index];
        var newTotal = total + n;

        if (newTotal == value)
        {
            // this is a matching combo so lets return it
            var combo = new List<int>();

            for (int i = 0; i < index; i++)
            {
                if (indices[i])
                {
                    combo.Add(numbers[i]);
                }
            }
            
            combo.Add(n);
            combos.Add(combo);
        }
        else
        {
            if (newTotal < value)
            {
                // try for more including this number/index
                indices.Set(index, true); // index included in total
                FindCombos(index + 1, newTotal);
            }

            // try for more not including this number/index
            indices.Set(index, false); // index not included in total
            FindCombos(index + 1, total);
        }
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69354071

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档