简体   繁体   English

如何使以下代码动态化/我可以注入循环吗?

[英]How to make the following code dynamic/ can I inject for loops?

I have a program which prints the all the possibilities of permutations for a given string. 我有一个程序可以打印给定字符串的所有排列可能性。 But it is static, I hard coded 3 for loops, assuming that the string will be of length 3. But if I have to make it dynamic, the user may enter input a string of length 5. So what I'm asking is if I can inject for loops as per the input of the user? 但这是静态的,我假设该字符串的长度为3,所以我将3硬编码为循环。但是,如果我必须使它成为动态字符串,那么用户可能会输入一个长度为5的字符串。所以我要问的是我可以根据用户的输入注入循环吗?

import java.util.*;
import java.lang.*;

    class Ideone
    {
        public static void main (String[] args) throws java.lang.Exception
        {
            // your code goes here
            String input = "abc";
            int i=0,j=0,k=0;
            for(i=0;i<3;i++){
                for(j=0;j<3;j++){
                    for(k=0;k<3;k++){
                       System.out.println(input.charAt(i)+""+input.charAt(j)+""+input.charAt(k)); 
                    }
                }
            }       
        }
    }

Nope, injecting for loops isn't something that's feasible (fortunately, it would make the language a mess!) 不,注入循环是不可行的(不幸的是,这会使语言一团糟!)

Tasks like this would usually be achieved using recursion, which can easily be used to generate permutations (of strings, arrays or anything else.) 通常使用递归来实现这样的任务,该递归可以轻松地用于生成(字符串,数组或其他任何东西)排列。

If you really don't want to use recursion there are other ways around it, you can calculate permutations via rotation in loops for instance - but these approaches will generally be harder to follow (and write.) 如果您真的不想使用递归,则可以使用其他方法,例如,可以通过循环旋转来计算置换-但是这些方法通常很难遵循(和编写)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM