简体   繁体   中英

Program for permutation and combination yields an unexpected output

After thinking for quite a long time on how to make a Java program that outputs all the possible combinations from a given input array, I finally thought of doing so by combining recursion and iteration.

My code takes input a char array {a,b,c} and should give an output of all possible array of length 3.

My code is-

public class Brute {

    char[] val = new char[] { 'a', 'b', 'c' };

    void work(char arr[], int i) {
        for (int j = 0; j <= 2; j++) {
            if (i <= 2) {
                arr[i] = val[j];
            }
            while (i <= 2) {
                i = i + 1;
                if (i <= 2) {
                    work(arr, i);
                    System.out.println(new String(arr));
                }
            }
        }
    }

    public static void main(String args[]) {
        Brute b = new Brute();
        char arr[] = new char[] { 'p', 'q', 'r' };
        b.work(arr, 0);

    }

}

The output is:

aaa
aaa
aaa

I can't understand why it gives me this output instead of all combinations.

问题在于,不是将i的值重新初始化为0,而是始终将i的值保留为3,并且将i的递增值(即3)传递给其他递归调用。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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