You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash脚本开发:寻找乘积最均衡的数组元素组合

Bash脚本优化:寻找乘积最均衡的因子组合

我正在开发一个Bash脚本,遇到了无法解决的问题,感谢@markp-fuso和@pjh的帮助!

我定义了两个整数数组dividers_1、dividers_2,以及存储目标乘积的变量product:

#!/bin/bash
dividers_1=("1" "2" "4" "6" "8" "9" "12" "16" "18" "24" "32" "36" "48" "64")
dividers_2=("1" "2" "3" "4" "7" "9" "12" "16" "18" "24" "27" "32" "36" "48" "54")
product=16

核心需求

从两个数组中各取一个数(顺序不限),使二者乘积等于product,且找到最均衡组合——即两数的差值尽可能小:

  • 理想状态是两数相等,比如product=16时,最优组合是4x4而非1x16;
  • 若无法实现完美均衡,则找次优解,比如product=64时,8x8不存在,最优组合为4x16(或16x4);
  • 若不存在任何符合条件的组合,返回错误信息。

补充说明:“均匀分布”的优先级是优先两数相等,其次差值最小。例如目标乘积为900时,最优是30x30(差值0),次优是25x36或36x25(差值11),最不均衡的是1x900或900x1(差值899)。

当前代码瓶颈

我多次重写后陷入瓶颈,现有代码未优化,执行./find_combo.sh 64应返回Found it: 4 x 16,但当前实现无法满足需求,寻求优化建议,要求尽量减少依赖,当前使用Bash 5.2版本。

当前代码如下:

#!/bin/bash
## find_combo.sh

# Both arrays are hard written for convenience. Usually it's generated by another function that find all the dividers from a given number.
dividers_1=(1 2 4 6 8 9 12 16 18 24 32 36 48 64)
dividers_2=(1 2 3 4 7 9 12 16 18 24 27 32 36 48 54)
product=$1

# check if combination is valid
is_valid_combination() {
    local result=$1
    for elem in "${dividers_1[@]}" "${dividers_2[@]}"; do
        if [ "$elem" == "$result" ]; then
            return 0  # valid
        fi
    done
    return 1  #not valid
}

# Find the most balanced combination
balanced_combination=""
min_difference=999999999  #initial value

for num1 in "${dividers_1[@]}"; do
    for num2 in "${dividers_2[@]}"; do
        result=$((num1 * num2))
        difference=$((num1 > num2 ? num1 - num2 : num2 - num1))

        if [ "$result" -eq "$product" ] && [ "$difference" -lt "$min_difference" ] && is_valid_combination "$num1" && is_valid_combination "$num2"; then
            balanced_combination="$num1 x $num2"
            min_difference="$difference"
        fi
    done
done

# check if a balanced combination is found
if [ -n "$balanced_combination" ]; then
    echo "Found it: $balanced_combination"
else
    echo "Sorry, no combination found for $product"
fi

内容的提问来源于stack exchange,提问作者sh_k_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 03:43:35