Skip to content

Commit 40d5243

Browse files
author
Gonzalo Diaz
committed
[BUGFIX] sonarcloud: Fix this access on a collection that may trigger an 'ArrayIndexOutOfBoundsException'.
Accessing an array element should not trigger an ArrayIndexOutOfBoundsException javabugs:S6466
1 parent 6559d02 commit 40d5243

File tree

2 files changed

+36
-6
lines changed

2 files changed

+36
-6
lines changed

algorithm-exercises-java/src/main/java/ae/projecteuler/Problem0015.java

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,27 +15,39 @@ private Problem0015() {}
1515
* Problem 0015.
1616
*/
1717
public static Long problem0015(Integer gridSide) {
18+
int limit;
1819

19-
Long[][] grid = new Long[gridSide + 1][gridSide + 1];
20+
if (gridSide <= 0) {
21+
limit = 0;
22+
} else {
23+
limit = gridSide + 1;
24+
}
25+
26+
Long[][] grid = new Long[limit][limit];
2027

2128
// initialization
22-
for (int i = 0; i <= gridSide; i++) {
23-
for (int j = 0; j <= gridSide; j++) {
29+
for (int i = 0; i < limit; i++) {
30+
for (int j = 0; j < limit; j++) {
2431
grid[i][j] = 1L;
2532
}
2633
}
2734

2835
// vertex computing
29-
for (int i = 1; i <= gridSide; i++) {
30-
for (int j = 1; j <= gridSide; j++) {
36+
for (int i = 1; i < limit; i++) {
37+
for (int j = 1; j < limit; j++) {
3138
long upperParent = grid[i - 1][j];
3239
long leftParent = grid[i][j - 1];
3340

3441
grid[i][j] = upperParent + leftParent;
3542
}
3643
}
3744

38-
Long result = grid[gridSide][gridSide];
45+
Long result;
46+
if (grid.length > 0) {
47+
result = grid[grid.length - 1][grid.length - 1];
48+
} else {
49+
result = 0L;
50+
}
3951

4052
String log;
4153
log = String.format("Problem 00015 solved: %d", result);

algorithm-exercises-java/src/test/java/ae/projecteuler/Problem0015Test.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,22 @@ class Problem0015Test {
1616
String.format("Problem 0015 answer must be: %d", answer)
1717
);
1818
}
19+
20+
@Test void problem0015edgeCase() {
21+
22+
Integer input = 0;
23+
Long answer = 0L;
24+
Long solutionFound = Problem0015.problem0015(input);
25+
26+
assertEquals(answer, solutionFound,
27+
String.format("Problem 0015 answer must be: %d", answer)
28+
);
29+
30+
input = -1;
31+
answer = 0L;
32+
solutionFound = Problem0015.problem0015(input);
33+
assertEquals(answer, solutionFound,
34+
String.format("Problem 0015 answer must be: %d", answer)
35+
);
36+
}
1937
}

0 commit comments

Comments
 (0)