【发布时间】:2014-10-01 00:47:58
【问题描述】:
我正在尝试编写一个程序,该程序从用户那里接收一个“单词”,并打印出它在所有排列中的字典顺序。我具有获取等级和计算阶乘的功能(出于复杂性原因,迭代地进行),但我需要一个主要方法来测试程序并使其可运行。到目前为止,这是我所拥有的:
编辑:我正在尝试将执行上述操作的 this C program 转换为 Java。我遇到的麻烦主要是增加和更新计数功能得到错误:The type of expression must be an array type but i resolved to int/String.
package ranking;
public class Ranking {
public static void increaseCount (int count, String str) {
int i;
for (i=0; str[i]; i++)
count[str[i]]++;
for (i=1; i < 256; i++)
count[i] += count[i-1];
}
public static void updateCount (int count, String ch){
int i;
for (i=ch; i < 256; i++)
count[i]--;
}
public static int findRank (String str) {
int length = str.length();
int mul = fact(length);
int rank = 1, i;
int count[256] = {0};
increaseCount(count, str);
for (i=0; i < length; i++) {
mul/= length - i;
rank += count [ str[i] - 1] * mul;
updateCount(count, str[i];)
}
return rank;
}
public static int factorial (int n){
int fact = 1;
if (n ==0 || n==1) {
return 1;
}
else {
for (int i=1; i<=n; i++){
fact *= i;
}
}
return fact;
}
public static void main (String[] args){
String str = "string";
System.out.print(findRank(str));
}
}
【问题讨论】:
-
另外,你确定这段代码正确地生成了输入字符串的所有排列吗?我可能会尝试使用此处实现的 Steinhaus-Johnson-Trotter 算法之类的东西:stackoverflow.com/a/11916946/2514228
标签: java permutation ranking lexicographic