使用嵌套循环生成单词

使用嵌套循环生成单词

我制作了这个脚本,它生成小写字母和数字的所有组合并回显它们。它有效,但我想知道是否有一种方法可以简化添加新字符的过程,而不是我目前必须为我想添加的每个新字符创建一个新函数的方法。这是我的脚本:

declare -r LIST=$(echo {a..z} {0..9})

function word_generation_2 {
    for char1 in  ${LIST}; do
        for char2 in  ${LIST}; do
            echo ${char1}${char2}
        done
    done
}

function word_generation_3 {
    for char1 in  ${LIST}; do
        for char2 in  ${LIST}; do
            for char3 in  ${LIST}; do
                echo ${char1}${char2}${char3}
            done
        done
    done
}


function word_generation_4 {
    for char1 in  ${LIST}; do
        for char2 in  ${LIST}; do
            for char3 in  ${LIST}; do
                for char4 in  ${LIST}; do
                    echo ${char1}${char2}${char3}${char4}
                done
            done
        done
    done
}


function word_generation_5 {
    for char1 in  ${LIST}; do
        for char2 in  ${LIST}; do
            for char3 in  ${LIST}; do
                for char4 in  ${LIST}; do
                    for char5 in  ${LIST}; do
                         echo ${char1}${char2}${char3}${char4}${char5}
                    done
                done
            done
        done
    done
}


for ((i = 2; i < 6; i++)); do
    word_generation_${i}
done

输出是:

aa

...


99999

我想保持这样。首先是 2 个字符的所有组合,然后是 3 个字符的所有组合,依此类推。

答案1

在 Bash 或其他支持的东西中数组,您可以将字符集放入数组中,然后再次循环数组,再次在前面添加字符:

chars=( {a,b,c} )
doubles=()
triplets=()
for c in "${chars[@]}" ; do 
    doubles+=( ${chars[@]/#/$c} )
done
for c in "${chars[@]}" ; do 
    triplets+=( ${doubles[@]/#/$c} )
done
echo "${triplets[@]}"

打印aaa aab aac ... ccc,您可以根据需要重复较长的内容,或者将其转换为递归函数。 (这${var//}是一个模式替换where#标记字符串的开头。当它应用于数组时,它应用于全部数组的值,一次一个。)

相关内容