简体   繁体   English

字符串Java的词法等级

[英]Lexicographic rank of a string Java

I am trying to write a program that takes in a 'word' from the user and prints out its lexicographic rank among all of its permutations. 我正在尝试编写一个程序,该程序从用户那里获取一个“单词”,并在所有排列中打印出其字典顺序。 I have the functions for getting the rank and the calculating factorials (iteratively for complexity reasons) but I need a main method to test the program and make it runnable. 我具有获取排名和计算阶乘的功能(出于复杂性原因,需要迭代进行),但是我需要一种主要方法来测试程序并使之可运行。 Here's what I have so far: 这是我到目前为止的内容:

EDIT: I am trying to convert this C program that does the above correctly into Java. 编辑:我正在尝试将正确执行上述操作的C程序转换为Java。 I have run into troubles mostly with the increase and update Count functions getting the error: 我遇到了麻烦,主要是因为增加和更新Count函数收到错误:
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));
}

} }

Just try some loop: 只需尝试一些循环:

public static void main(final String[] args) {
    final Scanner scan = new Scanner(System.in);
    System.out.println("Enter a string: ");
    String inputChars;
    while (!(inputChars = scan.next()).equals("exit")) {
        System.out.println(inputChars);
    }
    scan.close();
}

Tested. 经过测试。 Works. 作品。

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

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