【问题标题】:Calculate all possible sum combinations in a given array of space delimited numbers using BASH [closed]使用 BASH [关闭] 计算给定空格分隔数字数组中所有可能的总和组合
【发布时间】:2020-02-14 17:52:44
【问题描述】:

有没有办法使用纯 BASH 计算给定数组中所有可能的总和组合?

示例: 2 3 4....n

输出: 5 7 6 9 等等

【问题讨论】:

  • 为什么排除 2、3 和 4?
  • 输出需要给定列表或数组中的数字总和,而不是元素本身

标签: bash combinations


【解决方案1】:

使用指标来判断要对哪些元素求和。您可以将其实现为 1 和 0 的数组,其中 1 表示 包含在总和中。要遍历所有组合,只需从与数字数组长度相同的数组开始,实现二进制递减很容易。如果指标只有一个 1,则跳过计算,因为您不希望仅包含数字。要只报告每个总和一次,请使用关联数组来保存总和。

#!/bin/bash
sum () {
    sum=0
    for n in "$@" ; do
        ((sum += n ))
    done
    printf %d "$sum"
}

numbers=(2 3 4)
indicator=()
for _i in "${numbers[@]}" ; do
    indicator+=(1)
done

declare -A sums

while si=$(sum "${indicator[@]}") ; (( si > 0 )) ; do
    if (( si != 1 )) ; then
        sum=0
        for ((i=0; i<${#numbers[@]}; ++i)) ; do
            (( indicator[i] && (sum+=numbers[i]) ))
        done
        sums[$sum]=1
    fi

    # Binary decrement.
    i=0
    until (( indicator[i] || i > ${#indicator[@]} )) ; do
        indicator[i++]=1
    done
    indicator[i]=0
done
echo "${!sums[@]}"

【讨论】:

    【解决方案2】:

    这是您可以做到的一种方式,但它需要 Python3:

    import itertools
    numbers = [2, 3, 4]
    print(list(itertools.chain(*list(map(lambda x: x, 
         [list(map(sum, list(itertools.combinations(numbers,x)))) for x in range(2, len(numbers) +1)]
         )))))
    

    将打印:

    [5, 6, 7, 9]
    

    如果您希望 Bash 动态且快速,我认为 Bash 不是解决此问题的合适工具。

    【讨论】:

    • 感谢您的宝贵回答,但我特别要求它在 BASH 本身中。有任何想法吗?谢谢
    猜你喜欢
    • 2013-10-06
    • 1970-01-01
    • 2021-08-21
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多