Skip to content

Commit d1a02f5

Browse files
committed
BAEL-8771 Count the Number of Sign Changes in an Array
1 parent a64ac4d commit d1a02f5

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.baeldung.signchanges;
2+
3+
import org.assertj.core.api.Assertions;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.util.Arrays;
7+
import java.util.stream.IntStream;
8+
9+
public class SignChangesInAnArrayUnitTest {
10+
11+
int[] sampleArray = {1, -2, -3, 4, 0, -1, 5};
12+
13+
int countSignChanges(int[] arr) {
14+
if (arr == null || arr.length < 2) {
15+
return 0;
16+
}
17+
int count = 0;
18+
19+
int prevSign = Integer.signum(arr[0]);
20+
21+
for (int i = 1; i < arr.length; i++) {
22+
int currentSign = Integer.signum(arr[i]);
23+
24+
if (currentSign != 0 && prevSign != 0 && currentSign != prevSign) {
25+
count++;
26+
}
27+
28+
if (currentSign != 0) {
29+
prevSign = currentSign;
30+
}
31+
}
32+
33+
return count;
34+
}
35+
36+
@Test
37+
void givenArray_whenExistsSignChanges_thenReturnSignChangesQuantity() {
38+
int result = countSignChanges(sampleArray);
39+
Assertions.assertThat(result).isEqualTo(4);
40+
}
41+
42+
int countSignChangesStream(int[] arr) {
43+
if (arr == null || arr.length < 2) {
44+
return 0;
45+
}
46+
47+
int[] signs = Arrays.stream(arr)
48+
.map(Integer::signum)
49+
.filter(s -> s != 0)
50+
.toArray();
51+
52+
return (int) IntStream.range(1, signs.length)
53+
.filter(i -> signs[i] != signs[i - 1])
54+
.count();
55+
}
56+
57+
@Test
58+
void givenArray_whenUsingStreams_thenReturnSignChangesQuantity() {
59+
int result = countSignChangesStream(sampleArray);
60+
Assertions.assertThat(result).isEqualTo(4);
61+
}
62+
63+
}

0 commit comments

Comments
 (0)