public class e9sp01sol { // Solve the problem two different ways: public static void main(String[] args) { version1(); // no raggedness version2(); // raggedness (more elegant) } // Assume fixed size for key matrix ("wastes" space, though): private static void version1() { int[][][] key = new int[4][3][3]; String A[][] = { {"abcbb", "ba"}, {"abba", "accb"}, {"aaba"}, {"cca", "cbcbb", "aaaa"} }; System.out.println("abc"); System.out.println("---"); for(int i=0; i<=A.length-1; i++) { for(int j=0; j<=A[i].length-1; j++) { key[i][j] = char_counts(A[i][j]); for(int k=0;k<=key[i][j].length-1;k++) System.out.print(key[i][j][k]); System.out.println(); } System.out.println(); } } // method version1 // Use ragged arrays: private static void version2() { String A[][] = { {"abcbb", "ba"}, {"abba", "accb"}, {"aaba"}, {"cca", "cbcbb", "aaaa"} }; int[][][] key = new int[A.length][][]; // made a bit more general System.out.println("abc"); System.out.println("---"); for(int i=0; i<=A.length-1; i++) { key[i] = new int[A[i].length][]; for(int j=0; j<=A[i].length-1; j++) { key[i][j] = char_counts(A[i][j]); for(int k=0;k<=key[i][j].length-1;k++) System.out.print(key[i][j][k]); System.out.println(); } System.out.println(); } } // method version2 // Return an array of counts of characters in input s: private static int[] char_counts(String s) { // Initialize counts of 'a', 'b', and 'c' for String s: int ac = 0; int bc = 0; int cc = 0; // Count each character in s: for(int i=0; i<=s.length()-1; i++) { switch(s.charAt(i)) { case 'a': ++ac; break; case 'b': ++bc; break; case 'c': ++cc; break; default: System.err.println("Unrecognized character!"); System.exit(0); } } // Return counts: return new int[] {ac,bc,cc}; } // method char_counts } // class e9sp01sol /* output for both versions: abc --- 131 110 220 112 310 102 032 400 */