在bash中从数组生成尽可能少的数字

时间:2017-05-04 15:10:47

标签: arrays bash shuffle

让我们说我有一个带有一些数字的数组,从最低到最高的数字排序:

root@blubb:~# min=1
root@blubb:~# echo $array 
1 2 3 6 16 26 27

我希望bash脚本始终尝试首先定义的最小数量(在这种情况下min = 1),如果不可能,请添加1并再次尝试,直到它最终有效(在这种情况下需要4)

我尝试使用shuf和while- / for循环,但无法使其正常运行。

2 个答案:

答案 0 :(得分:1)

min=1
array="1 2 3 6 16 26 27"

found=0
res=$min
for elem in $array; do
    if [[ $elem = $res ]]; then 
        found=1
        continue
    fi
    if [[ $found = 1 ]]; then
       ((res+=1))
       if ((elem>res)); then
           break
       fi
    fi
done

echo $res

或使用功能

function min_array {
    local min array res found
    min=$1
    shift
    array=$*

    found=0
    res=$min
    for elem in $array; do
        if [[ $elem = $res ]]; then
            found=1
            continue
        fi
        if [[ $found = 1 ]]; then
            ((res+=1))
            if ((elem>res)); then
                break
            fi
        fi
    done
    echo $res
}

$ min_array 1 1 2 3 6 16 26
4

$ min_array 6 1 2 3 6 16 26
7

$ min_array 8 1 2 3 6 16 26
8

编辑一个案例丢失,另一个案例

function min_array {
    local min array res found
    min=$1
    shift
    array=$*

    found=0
    res=$min
    for elem in $array; do
        if [[ $elem = $res ]]; then
            found=1
            ((res+=1))
            continue
        fi
        if [[ $found = 1 ]]; then
            if ((elem>res)); then
                break
            else
                ((res+=1))
            fi
        fi
    done
    echo $res
}

答案 1 :(得分:0)

试试这个。

@media screen and ( max-height: 600px ){
    background: blue;
}