0

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. I have run into troubles mostly with the increase and update Count functions getting the error:
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));
}

}

  • Also, are you sure this code correctly generates all permutations of the input string? I might try to use something like the Steinhaus-Johnson-Trotter algorithm implemented here: http://stackoverflow.com/a/11916946/2514228 – Micah Smith Aug 07 '14 at 17:08

1 Answers1

0

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.

atmin
  • 370
  • 1
  • 7