[英]Java - Finding permutations of a word using recursion?
I have a program, that will find all the possible permutations of a word given as a command line argument, but am unable to get any output from the program, the program compiles fine, and when I have run through the program, i can't see what's wrong. 我有一个程序,可以找到作为命令行参数给出的单词的所有可能排列,但无法从程序中获取任何输出,程序可以正常编译,当我运行该程序时,我可以看错了。 Any ideas?
有任何想法吗?
import java.io.*;
02
03 public class Anagrams
04 {
05 private static char [] word;
06 private static char [] permutation;
07 private static boolean [] characterUsed;
08
09
10
11 public static void main(String [] args)throws Exception
12 {
13
14 word = args[0].toCharArray();
15 permutation = new char[word.length];
16 characterUsed = new boolean[word.length];
17 printPermutations(0);
18 }//main
19
20 private static void printPermutations(int currentIndex)throws Exception
02 {
03
04 if(currentIndex == permutation.length)
05 System.out.println(permutation);
06 else
07 {
08 for(int index=0;index<word.length-1;index++)
09 {
10 //if the character at that index hasn't been used
11 if(!characterUsed[index]);
12 {
13 //mark character at this position as in use
14 characterUsed[index] = true;
15 //put the character in the permutation
16 permutation[index]= word[currentIndex];
17 printPermutations(currentIndex +1);
18 characterUsed[index] = false;
19 }//if
20 }//for
21 }//else
22 }//printPermutation
41 }//Anagrams
change 更改
permutations[index] = permutations[currentIndex];
to 至
permutations[index] = argument[currentIndex];
premutation
has not been pre-populated so you are always assigning it to the null character. premutation
尚未预先填充,因此您始终将其分配给空字符。
In the future doing something like System.out.println("<"+myString+">");
将来做类似
System.out.println("<"+myString+">");
事情System.out.println("<"+myString+">");
is helpful for these kinds of issues. 对于此类问题很有帮助。
And change 并改变
for (int index = 0; index < argument.length-1; index++)
to 至
for (int index = 0; index < argument.length; index++)
Not sure if this is the only problem, but this line also looks iffy: 不知道这是否是唯一的问题,但此行看起来也很困难:
for (int index = 0; index < argument.length - 1; index++)
Are you meaning not to use the last char
in the array? 您是不是要使用数组中的最后一个
char
? You probably mean: 您可能是说:
for (int index = 0; index <= argument.length - 1; index++)
or 要么
for (int index = 0; index < argument.length; index++)
The reason it is not printing anything is because of an error in the for-loop. 它不打印任何内容的原因是因为for循环中的错误。 Try
尝试
for (int index = 0; index < argument.length; index++) for(int索引= 0;索引<参数。长度;索引++)
I believe problem is on line 11 & 12. Did you really intend to have the ; 我认为问题出在11和12行上。您是否真的打算拥有; at the end of if condition?
如果条件结束?
10 //if the character at that index hasn't been used
11 if(!characterUsed[index]);
Hope that helps.. 希望有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.