|
1 | 1 | package com.baeldung.arrays;
|
2 | 2 |
|
| 3 | +import static org.hamcrest.MatcherAssert.assertThat; |
| 4 | +import static org.hamcrest.Matchers.is; |
3 | 5 | import static org.junit.Assert.*;
|
4 | 6 |
|
5 | 7 | import org.junit.Before;
|
|
9 | 11 |
|
10 | 12 | import java.util.Arrays;
|
11 | 13 | import java.util.List;
|
| 14 | +import java.util.Random; |
12 | 15 | import java.util.stream.Stream;
|
13 | 16 |
|
14 | 17 | public class ArraysUnitTest {
|
@@ -150,4 +153,52 @@ public void whenAsList_thenImmutableArray() {
|
150 | 153 | exception.expect(UnsupportedOperationException.class);
|
151 | 154 | rets.add("the");
|
152 | 155 | }
|
| 156 | + |
| 157 | + @Test |
| 158 | + public void givenIntArray_whenPrefixAdd_thenAllAccumulated() { |
| 159 | + int[] arri = new int[] { 1, 2, 3, 4}; |
| 160 | + Arrays.parallelPrefix(arri, (left, right) -> left + right); |
| 161 | + assertThat(arri, is(new int[] { 1, 3, 6, 10})); |
| 162 | + } |
| 163 | + |
| 164 | + @Test |
| 165 | + public void givenStringArray_whenPrefixConcat_thenAllMerged() { |
| 166 | + String[] arrs = new String[] { "1", "2", "3" }; |
| 167 | + Arrays.parallelPrefix(arrs, (left, right) -> left + right); |
| 168 | + assertThat(arrs, is(new String[] { "1", "12", "123" })); |
| 169 | + } |
| 170 | + |
| 171 | + @Test |
| 172 | + public void whenPrefixAddWithRange_thenRangeAdded() { |
| 173 | + int[] arri = new int[] { 1, 2, 3, 4, 5 }; |
| 174 | + Arrays.parallelPrefix(arri, 1, 4, (left, right) -> left + right); |
| 175 | + assertThat(arri, is(new int[] { 1, 2, 5, 9, 5 })); |
| 176 | + } |
| 177 | + |
| 178 | + @Test |
| 179 | + public void whenPrefixNonAssociative_thenError() { |
| 180 | + boolean consistent = true; |
| 181 | + Random r = new Random(); |
| 182 | + for (int k = 0; k < 100_000; k++) { |
| 183 | + int[] arrA = r.ints(100, 1, 5).toArray(); |
| 184 | + int[] arrB = Arrays.copyOf(arrA, arrA.length); |
| 185 | + |
| 186 | + Arrays.parallelPrefix(arrA, this::nonassociativeFunc); |
| 187 | + |
| 188 | + for (int i = 1; i < arrB.length; i++) { |
| 189 | + arrB[i] = nonassociativeFunc(arrB[i - 1], arrB[i]); |
| 190 | + } |
| 191 | + consistent = Arrays.equals(arrA, arrB); |
| 192 | + if(!consistent) break; |
| 193 | + } |
| 194 | + assertFalse(consistent); |
| 195 | + } |
| 196 | + |
| 197 | + /** |
| 198 | + * non-associative int binary operator |
| 199 | + */ |
| 200 | + private int nonassociativeFunc(int left, int right) { |
| 201 | + return left + right*left; |
| 202 | + } |
| 203 | + |
153 | 204 | }
|
0 commit comments