-1
import java.util.Arrays;
import java.util.Scanner;

public class SuffixArray {
public static class Tuple implements Comparable<Tuple>{
    public Integer originalIndex;
    public Integer firstHalf;
    public Integer secondHalf;
@Override
    public int compareTo(Tuple o) {
        if(this.firstHalf.compareTo(o.firstHalf)==0){
            return this.secondHalf.compareTo(o.secondHalf);
        }else {
            return this.firstHalf.compareTo(o.firstHalf);
        }
    }
}
public static void main(String args[]){
    Scanner scanner = new Scanner(System.in);
    String input = scanner.next();
    int n = input.length();
    Tuple[] tuples = new Tuple[n];
    int[][] suffixRank = new int[100][100];
    for (int i = 0; i < n; i++){
        tuples[i] = new Tuple();
        suffixRank[0][i] = input.charAt(i) - 'a';
    }
    for(int step=1, count=1;count < n;count*=2, step++){
        for (int i = 0; i<n;i++){
            tuples[i].firstHalf = suffixRank[step-1][i];
            tuples[i].secondHalf = i + count < n ? suffixRank[step-1][i+count] : -1;
            tuples[i].originalIndex = i;
        }
        Arrays.sort(tuples);
        for (int i=0;i<n;i++){
            suffixRank[step][tuples[i].originalIndex] = i > 0 && tuples[i].firstHalf == tuples[i-1].firstHalf && tuples[i].secondHalf==tuples[i-1].secondHalf ? suffixRank[step][tuples[i].originalIndex] : i;
        }
    }
    for (int i=0;i<n;i++){
        System.out.print(tuples[i].originalIndex + " ");
    }
  }
}

The above program is a suffix array using an nlogn algorithm. I have applied the same algorithm from the resource which is the link that is posted below. If I apply the same algorithm in C++, it works fine but when I apply the same code in Java, it gives me the wrong output. It gives me the wrong index of tuples. I cannot figure out what is wrong with this code, so please help me.

Suffix Array

test case 1:

Input: abaab Output: 3 2 0 4 1 Expected Output: 2 3 0 4 1

test case 2:

Input: banana Output: 4 5 3 1 0 2 Expected Output: 5 3 1 0 4 2

  • It's hard to tell why you think this isn't working right. Can you give an example of some input you are providing, the output you are expecting, and the output you're actually getting? – Dawood ibn Kareem Jun 09 '18 at 04:27

1 Answers1

0

Don't know if this is the only problem with the code, but a small inaccuracy appears at the for loop after the sorting. Specifically, after the if clause in the loop you should swap

? suffixRank[step][tuples[i].originalIndex] : i;

with this:

? suffixRank[step][tuples[i-1].originalIndex] : i;
DGounaris
  • 182
  • 9