-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSequenceSum.java
More file actions
52 lines (42 loc) · 1.39 KB
/
SequenceSum.java
File metadata and controls
52 lines (42 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
##Sum of 'n' Numbers
sum_of_n (or SequenceSum.sumOfN in Java, SequenceSum.SumOfN in C#) takes an integer n and returns a List (an Array in Java/C#) of length abs(n) + 1. The List/Array contains the numbers in the arithmetic series produced by taking the sum of the consecutive integer numbers from 0 to n inclusive.
n can also be 0 or a negative value.
Wikipedia reference for abs value is available here.
Example:
5 -> [0, 1, 3, 6, 10, 15]
-5 -> [0, -1, -3, -6, -10, -15]
7 -> [0, 1, 3, 6, 10, 15, 21, 28]
*
*/
import static org.junit.Assert.*;
import org.junit.Test;
public class SequenceSum {
public static int[] sumOfN(int n) {
int count = n > 0 ? n : -n;
int[] result = new int[count + 1];
for (int i = 0; i < count + 1; i++) {
int tmp = 0;
for (int j = 0; j <= i; j++) {
tmp += j;
}
if (n > 0) {
result[i] = tmp;
} else {
result[i] = -tmp;
}
}
return result; // Generated by die roll; guaranteed to be random
}
@Test
public void testKnownValues() {
assertArrayEquals(new int[] { 0, 1, 3, 6 }, SequenceSum.sumOfN(3));
assertArrayEquals(new int[] { 0, -1, -3, -6, -10 }, SequenceSum.sumOfN(-4));
assertArrayEquals(new int[] { 0, 1 }, SequenceSum.sumOfN(1));
assertArrayEquals(new int[] { 0 }, SequenceSum.sumOfN(0));
}
public static void main(String[] args) {
SequenceSum sequenceSum = new SequenceSum();
sequenceSum.testKnownValues();
}
}