【问题标题】:Create a loop for 3 different variables to output all possible combinations为 3 个不同的变量创建一个循环以输出所有可能的组合
【发布时间】:2018-12-15 16:37:03
【问题描述】:

假设我有 3 行代码

ABC
123
!@#

我如何创建一个 for 循环来输出将它们拼凑在一起的方法的数量?

E.GABC123!@#, ABC!@#123, 123ABC!@#$

这是我当前的代码行

 #!/bin/bash



    alphabet='ABC' numbers='123' special='!@#'

 for name in $alphabet$numbers$special 
  do   
  echo $name 
  done  
  echo  done

【问题讨论】:

  • 您可以尝试使用两个嵌套的for 循环和内部for 循环来减小大小
  • 请将您迄今为止尝试过的内容添加到您的问题中。
  • 嗨,我已经添加了我尝试过的内容,但我仍然无法绕过为所有可能的组合循环变量背后的逻辑

标签: bash for-loop


【解决方案1】:

您也可以使用 大括号扩展 完全不使用循环(但您无法排除,例如ABCABCABC)。例如:

#!/bin/bash

alpha='ABC'
num='123'
spec='!@#'

printf "%s\n" {$alpha,$num,$spec}{$alpha,$num,$spec}{$alpha,$num,$spec}

使用/输出示例

$ bash permute_brace_exp.sh
ABCABCABC
ABCABC123
ABCABC!@#
ABC123ABC
ABC123123
ABC123!@#
ABC!@#ABC
ABC!@#123
ABC!@#!@#
123ABCABC
123ABC123
123ABC!@#
123123ABC
123123123
123123!@#
123!@#ABC
123!@#123
123!@#!@#
!@#ABCABC
!@#ABC123
!@#ABC!@#
!@#123ABC
!@#123123
!@#123!@#
!@#!@#ABC
!@#!@#123
!@#!@#!@#

【讨论】:

    【解决方案2】:
    alphabet='ABC' numbers='123' special='!@#'
    
    for name1 in $alphabet $numbers $special 
    #on 1st iteration, name1's value will be ABC, 2nd 123 ...
    do
        for name2 in $alphabet $numbers $special
        do
            for name3 in $alphabet $numbers $special
            do
                #here we ensure that we want strings only as combination of that three strings 
                if [ $name1 != $name2 -a $name2 != $name3 ]
                then
                echo $name1$name2$name3
                fi
            done
        done
    done 
    

    如果您还想打印字符串,例如 123123123ABCABCABC,请删除 if 条件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-02
      • 1970-01-01
      • 2022-11-04
      • 2011-10-22
      相关资源
      最近更新 更多