简体   繁体   English

嵌套For循环动态深度Java

[英]Nested For Loops Dynamic Depth Java

Hello I'm new to programming and registered to this forum :) 您好,我是编程的新手,并已注册此论坛:)

So I created a little program with nested for loops that prints out all combinations of five numbers which can have a value from 0 to 5. With nested for-loops this works fine. 因此,我创建了一个带有嵌套的for循环的小程序,该程序打印出五个数字的所有组合,这些组合的值可以从0到5。使用嵌套的for循环,可以很好地工作。 But isn't there a cleaner solution? 但是没有更清洁的解决方案吗? I tried it with calling the for loop itself, but my brain doesn't get the solution.. :( 我尝试通过调用for循环本身来尝试,但是我的大脑无法解决问题.. :(

//my ugly solution
int store1, store2, store3, store4, store5;
        for (int count = 0; count <= 5; count++) {
            store1 = count;
            for (int count2 = 0; count2 <= 5; count2++) {
                store2 = count2;
                for (int count3 = 0; count3 <= 5; count3++) {
                    store3 = count3;
                    for (int count4 = 0; count4 <= 5; count4++) {
                        store4 = count4;
                        System.out
                                .println(store1 + " " + store2 + " " + store4);
                }
 //I'm trying around with something like this 
    void method1() {
        for (int count = 0; count <= 5; count++) {
                    list.get(0).value = count;
            count++;
            method2();
        }
    }
    void method2() {
        for (int count = 0; count <= 5; count++) {
                    list.get(1).value = count;
            count++;
            method1();
        }
    }

Usually when people try to use recursion or functional, using a loop is simpler or faster. 通常,当人们尝试使用递归或函数时,使用循环会更简单或更快速。 However, in this case recursion is the simpler option in combination with a loop. 但是,在这种情况下,与循环结合使用递归是更简单的选择。

public static void method(List<Integer> list, int n, int m) {
   if (n < 0) {
       process(list);
   } else {
      for(int i = 0; i < m; i++) {
         list.set(n, i);
         method(list, n-1, m);
      }
   }
}

I know that you are trying combinations but this might help. 我知道您正在尝试组合,但这可能会有所帮助。

Permutation with repetitions 重复排列

When you have n things to choose from ... you have n choices each time! 当您有n种选择...时,每次都有n种选择!

When choosing r of them, the permutations are: 选择其中的r个时,排列是:

n × n × ... (r times) = n^r n×n×...(r次)= n ^ r

//when n and r are known statically

class Permutation
{
    public static void main(String[] args)
    {
        char[] values = {'a', 'b', 'c', 'd'};
        int n = values.length;
        int r = 2; 

        int i = 0, j = 0;
        for(i=0; i<n; i++)
        {
            for(j=0; j<n; j++)
            {
                System.out.println(values[j] + " " + values[i]);
            }
        }
    }
}


//when n and r are known only dynamically

class Permutation
{
    public static void main(String[] args)
    {
        char[] values = {'a', 'b', 'c', 'd'};
        int n = values.length;
        int r = 2; 
        int i[] = new int[r];
        int rc = 0;
        for(int j=0; j<Math.pow(n,r); j++)
        {

            rc=0;
            while(rc<r)
            {
                System.out.print(values[i[rc]] + " ");
                rc++;
            }
            System.out.println();
            rc = 0;
            while(rc<r)
            {
                if(i[rc]<n-1)
                {
                    i[rc]++;
                    break;
                }
                else
                {
                    i[rc]=0;
                }
                rc++;
            }
        }
    }
}

Something like this? 像这样吗

// Print all sequences of len(list)+n numbers that start w/ the sequence in list
void method( list, n ) {
    if ( list.length == n )
        // print list
    else for ( int c=0; c<=5; c++ ) {
        // add c to end of list
        method( list, n );
        // remove c from end of list
    }
}

Initial call would be method( list, 5 ) where list is initially empty. 初始调用为method( list, 5 ) ,其中list最初为空。

here another interative but less elegant version 这是另一个有趣但不太优雅的版本

while (store1 < 6) {
        store5++;
        if (store5 == 6) {
            store5 = 0;
            store4++;
        }
        if (store4 == 6) {
            store4 = 0;
            store3++;
        }
        if (store3 == 6) {
            store3 = 0;
            store2++;
        }
        if (store2 == 6) {
            store2 = 0;
            store1++;
        }
        System.out.println(store1 + " " + store2 + " " + store3 + " " + store4 + " " + store5 + " ");
    }

The simplest code I can think of would tackle the problem with an entirely different approach: 我能想到的最简单的代码将使用完全不同的方法来解决该问题:

public class TestA {
    public static void main(String[] argv) {
        for (int i=0; i<(6 * 6 * 6 * 6 * 6); ++i) {
            String permutation = Integer.toString(i, 6);
            System.out.println("00000".substring(permutation.length()) + permutation);
        }
    }
}

From your text (not your code) I gather you have 5 places and 6 symbols, which suggests there are 6 to the 5th power combinations. 从您的文本(而不是您的代码)中,我收集到您有5个位置和6个符号,这表示有6至5个幂组合。 So the code just counts through those numbers and translates the number to the output combination. 因此,代码只是对这些数字进行计数,然后将数字转换为输出组合。

Since this can also be viewed as a number system with base 6, it makes use of Integer.toString which already has formatting code (except the leading zeros) for this. 由于也可以将其视为以6为底的数字系统,因此它使用了Integer.toString,它已经具有格式代码(前导零除外)。 Leading zeros are added where missing. 前导零在缺少的地方添加。

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

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