How to make permutation in bash with N! input?

后端 未结 3 1113
你的背包
你的背包 2021-01-15 14:44

I have to make a permutation in bash with \"eval\" and \"seq\" commands. So I have to make first a permutation that could contain the same numbers, then I have to filter it

3条回答
  •  孤城傲影
    2021-01-15 15:46

    It is a permutation problem, so I have found some others have did it. You can see the answer Generating permutations using bash

    So through the answer, you can write the code like this:

    perm() {
        local items="$1"
        local out="$2"
        local i
        [[ "$items" == "" ]] && echo "$out" && return
        for (( i=0; i<${#items}; i++ )) ; do
            perm "${items:0:i}${items:i+1}" "$out${items:i:1}"
        done
    }
    
    test() {
        local number="$1"
        local iniitem="$(seq -s' ' 1 ${number} | sed -n 's/ //g;p')"
        perm "$iniitem"
    }
    

    Then you can use the function like this:
    test 3:
    the output:

    123
    132
    213
    231
    312
    321
    

提交回复
热议问题