1
1
package com .williamfiset .algorithms .datastructures .segmenttree ;
2
2
3
+ import static com .google .common .truth .Truth .assertThat ;
3
4
import static org .junit .Assert .*;
4
5
6
+ import com .williamfiset .algorithms .utils .TestUtils ;
5
7
import org .junit .Before ;
6
8
import org .junit .Test ;
7
9
8
10
public class SegmentTreeWithPointersTest {
9
11
10
- static final int LOOPS = 50 ;
11
- static final int TEST_SZ = 1000 ;
12
- static final int MIN_RAND_NUM = 0 ;
13
- static final int MAX_RAND_NUM = +2000 ;
14
-
15
12
@ Before
16
13
public void setup () {}
17
14
@@ -28,28 +25,37 @@ public void testIllegalSegmentTreeCreation2() {
28
25
29
26
@ Test
30
27
public void testSumQuery () {
31
-
32
28
int [] values = {1 , 2 , 3 , 4 , 5 };
33
29
Node tree = new Node (values );
34
30
35
- assertEquals ( 1 , tree .sum (0 , 1 ));
36
- assertEquals ( 2 , tree .sum (1 , 2 ));
37
- assertEquals ( 3 , tree .sum (2 , 3 ));
38
- assertEquals ( 4 , tree .sum (3 , 4 ));
39
- assertEquals ( 5 , tree .sum (4 , 5 ));
31
+ assertThat ( tree .sum (0 , 1 )). isEqualTo ( 1 );
32
+ assertThat ( tree .sum (1 , 2 )). isEqualTo ( 2 );
33
+ assertThat ( tree .sum (2 , 3 )). isEqualTo ( 3 );
34
+ assertThat ( tree .sum (3 , 4 )). isEqualTo ( 4 );
35
+ assertThat ( tree .sum (4 , 5 )). isEqualTo ( 5 );
40
36
}
41
37
42
- // Select a lower bound index for the Fenwick tree
43
- public static int lowBound (int N ) {
44
- return (int ) (Math .random () * N );
45
- }
46
-
47
- // Select an upper bound index for the Fenwick tree
48
- public static int highBound (int low , int N ) {
49
- return Math .min (N , low + (int ) (Math .random () * N ));
38
+ @ Test
39
+ public void testAllSumQueries () {
40
+ int n = 100 ;
41
+ int [] ar = TestUtils .randomIntegerArray (n , -1000 , +1000 );
42
+ Node tree = new Node (ar );
43
+
44
+ for (int i = 0 ; i < n ; i ++) {
45
+ for (int j = i + 1 ; j < n ; j ++) {
46
+ long bfSum = bruteForceSum (ar , i , j );
47
+ long segTreeSum = tree .sum (i , j );
48
+ assertThat (bfSum ).isEqualTo (segTreeSum );
49
+ }
50
+ }
50
51
}
51
52
52
- public static long randValue () {
53
- return (long ) (Math .random () * MAX_RAND_NUM * 2 ) + MIN_RAND_NUM ;
53
+ // Finds the sum in an array between [l, r) in the `values` array
54
+ private static long bruteForceSum (int [] values , int l , int r ) {
55
+ long s = 0 ;
56
+ for (int i = l ; i < r ; i ++) {
57
+ s += values [i ];
58
+ }
59
+ return s ;
54
60
}
55
61
}
0 commit comments