Advertisement
Filkolev

Array Sums With Recursion

Apr 16th, 2015
322
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function fun_11() {
  2.     var array = [
  3.             [1, 2, 3, 4],
  4.             [5, 6, 7, 8],
  5.             [9, 10, 11, 12],
  6.             [13, 14, 15, 16]
  7.         ];
  8.  
  9.     function recursiveLineSum(arr, row, maxRowSum) {
  10.         var sum = 0;
  11.  
  12.         if (row >= arr.length) {
  13.             return maxRowSum;
  14.         }
  15.  
  16.         arr[row].forEach(function (element) {
  17.             sum += element;
  18.         });
  19.  
  20.         if (sum > maxRowSum) {
  21.             maxRowSum = sum;
  22.         }
  23.  
  24.         return recursiveLineSum(arr, row + 1, maxRowSum);
  25.     }
  26.  
  27.     function recursiveColSum(arr, column, maxColSum) {
  28.         var i = 0,
  29.             tempSum = 0;
  30.  
  31.         if (column >= arr.length) {
  32.             return maxColSum;
  33.         }
  34.  
  35.         for (; i < arr.length; i += 1) {
  36.             tempSum += arr[i][column];
  37.         }
  38.  
  39.         if (tempSum >= maxColSum) {
  40.             maxColSum = tempSum;
  41.         }
  42.  
  43.         return recursiveColSum(arr, column + 1, maxColSum);
  44.     }
  45.  
  46.     console.log(recursiveLineSum(array, 0, 0));
  47.     console.log(recursiveColSum(array, 0, 0));
  48. }
  49.  
  50. fun_11();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement