Skip to content

Commit a89783b

Browse files
authored
Merge pull request #389 from spiralgo/631.-Design-Excel-Sum-Formula
631. Design Excel Sum Formula
2 parents 5bdea85 + 93865bd commit a89783b

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package algorithms.curated170.hard;
2+
3+
import java.util.Arrays;
4+
5+
public class DesignExcelSumFormula {
6+
7+
class Excel {
8+
9+
private static final int NO_POS = -1;
10+
Object[][] matrix;
11+
private final int M, N;
12+
13+
public Excel(int height, char width) {
14+
M = height;
15+
N = colIdx(width);
16+
17+
matrix = new Object[M][N + 1];
18+
19+
for (int i = 0; i < M; i++) {
20+
Arrays.fill(matrix[i], 0);
21+
}
22+
}
23+
24+
public void set(int row, char col, int val) {
25+
matrix[row - 1][colIdx(col)] = val;
26+
}
27+
28+
public int get(int row, char col) {
29+
if (matrix[row - 1][colIdx(col)] instanceof Integer) {
30+
return (int) matrix[row - 1][colIdx(col)];
31+
} else {
32+
return calculate(row, col);
33+
}
34+
}
35+
36+
public int sum(int row, char col, String[] numbers) {
37+
matrix[row - 1][colIdx(col)] = numbers;
38+
return calculate(row, col);
39+
}
40+
41+
public int calculate(int row, char col) {
42+
String[] numbers = (String[]) matrix[row - 1][colIdx(col)];
43+
44+
int sum = 0;
45+
for (String num : numbers) {
46+
int separatorIdx = num.indexOf(":");
47+
48+
if (separatorIdx == NO_POS) {
49+
char c = num.charAt(0);
50+
int r = Integer.parseInt(num.substring(1));
51+
52+
sum += get(r, c);
53+
} else {
54+
sum += sumSubMatrix(num, separatorIdx);
55+
}
56+
}
57+
58+
return sum;
59+
}
60+
61+
private int sumSubMatrix(String num, int separatorIdx) {
62+
int sum = 0;
63+
64+
String cell1 = num.substring(0, separatorIdx);
65+
String cell2 = num.substring(separatorIdx + 1);
66+
67+
char c1 = cell1.charAt(0);
68+
int r1 = Integer.parseInt(cell1.substring(1));
69+
70+
char c2 = cell2.charAt(0);
71+
int r2 = Integer.parseInt(cell2.substring(1));
72+
73+
for (int i = r1; i <= r2; i++) {
74+
for (char j = c1; j <= c2; j++) {
75+
sum += get(i, j);
76+
}
77+
}
78+
return sum;
79+
}
80+
81+
private int colIdx(char col) {
82+
return col - 'A';
83+
}
84+
85+
}
86+
87+
}

0 commit comments

Comments
 (0)