次のコードを実行してテストする準備ができています。
public class RecursionSum {
/* Sum a row until <code>index</code>. */
private static int rowSum(int[] a, int index) {
if (index == 0) { return a[0]; }
// add the current element to the recursive sum
return a[index] + rowSum(a, index - 1);
}
/* Sum a whole row. */
private static int rowSum(int[] a) {
return (a.length == 0) ? 0 : rowSum(a, a.length - 1);
}
/* Find the index of the array having the max sum until <code>index</code>. */
private static int maxRow(int[][] a, int index){
if (index == 0) { return 0; }
// compare the current row's sum with the recursive max row's sum,
// update index when it's a new winner
int maxIndex = maxRow(a, index - 1);
return (rowSum(a[maxIndex]) < rowSum(a[index])) ? index : maxIndex;
}
/* Find the index of the array having the max sum. */
public static int maxRow(int[][] a){
return a.length == 0 ? 0 : maxRow(a, a.length - 1);
}
/* very simple test */
public static void main(String[] args) {
int a1[][] = {};
int a2[][] = {{1, 2, 3, 4}};
int a3[][] = {{ 1, 2, 3, 4}, {8, 90}, {5, 6, 7}, {300, 4, 9}, {4, 6, 12}};
System.out.println(maxRow(a1));
System.out.println(maxRow(a2));
System.out.println(maxRow(a3));
}
}