Last active
November 17, 2016 15:00
-
-
Save pcj/ed8020dd5af08b5430c5d852e0c5431b to your computer and use it in GitHub Desktop.
Dynamic Programming Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* SumArray. Given an input list of integers 'A' with length N, | |
* calculate a NxN matrix 'B' such that the value of a cell B(i,j) is the | |
* sum of A(i)..A(j) forall i<=j. | |
*/ | |
public class SumArray { | |
public static void main(String[] args) { | |
int[] a = new int[]{ 12, 3, 6, 2, 23, 44 }; | |
int[][] b = makeArray(a); | |
System.out.println("--- INPUT ---"); | |
printRow(a); | |
System.out.println("--- OUTPUT ---"); | |
for(int[] row : b) { | |
printRow(row); | |
} | |
} | |
static int[][] makeArray(int[] a) { | |
int n = a.length; | |
int[][] b = new int[n][n]; | |
for (int i = 0; i < n; i++) { | |
for (int j = i; j < n; j++) { | |
if (i == 0) { | |
// If this is the first row, calculate the sum based on the | |
// current into the input array (a[i]) and the aggregate sum | |
// calculated so far (the previous cell in this column) | |
b[i][j] = a[j] + (j > 0 ? b[i][j - 1] : 0); | |
} else { | |
// If this is not the first row, we can find the sum based | |
// on the difference between the cell above us (previous | |
// column) and the index value of the input array (a[i - | |
// 1]). | |
b[i][j] = b[i - 1][j] - a[i - 1]; | |
} | |
} | |
} | |
return b; | |
} | |
static void printRow(int[] row) { | |
for (int i : row) { | |
System.out.print(i); | |
System.out.print("\t"); | |
} | |
System.out.println(); | |
} | |
} |
Author
pcj
commented
Nov 17, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment