Skip to content

Commit 945e7b5

Browse files
Fix:/Number of count of major element in Boyer Moore algorithm (TheAlgorithms#4728)
* Number of count of major element in Boyer Moore algorithm * test: add `BoyerMooreTest` * style: basic linting * tests: add test case from the issue --------- Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com> Co-authored-by: vil02 <vil02@o2.pl>
1 parent 9dde8a7 commit 945e7b5

File tree

2 files changed

+32
-20
lines changed

2 files changed

+32
-20
lines changed

src/main/java/com/thealgorithms/others/BoyerMoore.java

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,28 @@
66
*/
77
package com.thealgorithms.others;
88

9-
import java.util.*;
10-
11-
public class BoyerMoore {
9+
public final class BoyerMoore {
10+
private BoyerMoore() {
11+
}
1212

13-
public static int findmajor(int[] a) {
13+
public static int findmajor(final int[] a) {
1414
int count = 0;
1515
int cand = -1;
16-
for (int i = 0; i < a.length; i++) {
16+
for (final var k : a) {
1717
if (count == 0) {
18-
cand = a[i];
18+
cand = k;
1919
count = 1;
2020
} else {
21-
if (a[i] == cand) {
21+
if (k == cand) {
2222
count++;
2323
} else {
2424
count--;
2525
}
2626
}
2727
}
28-
for (int i = 0; i < a.length; i++) {
29-
if (a[i] == cand) {
28+
count = 0;
29+
for (final var j : a) {
30+
if (j == cand) {
3031
count++;
3132
}
3233
}
@@ -35,15 +36,4 @@ public static int findmajor(int[] a) {
3536
}
3637
return -1;
3738
}
38-
39-
public static void main(String[] args) {
40-
Scanner input = new Scanner(System.in);
41-
int n = input.nextInt();
42-
int[] a = new int[n];
43-
for (int i = 0; i < n; i++) {
44-
a[i] = input.nextInt();
45-
}
46-
System.out.println("the majority element is " + findmajor(a));
47-
input.close();
48-
}
4939
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.thealgorithms.others;
2+
import static org.junit.jupiter.api.Assertions.assertThrows;
3+
4+
import java.util.stream.Stream;
5+
import org.junit.jupiter.api.Assertions;
6+
import org.junit.jupiter.api.Test;
7+
import org.junit.jupiter.params.ParameterizedTest;
8+
import org.junit.jupiter.params.provider.Arguments;
9+
import org.junit.jupiter.params.provider.MethodSource;
10+
11+
public class BoyerMooreTest {
12+
13+
@ParameterizedTest
14+
@MethodSource("inputStream")
15+
void numberTests(int expected, int[] input) {
16+
Assertions.assertEquals(expected, BoyerMoore.findmajor(input));
17+
}
18+
19+
private static Stream<Arguments> inputStream() {
20+
return Stream.of(Arguments.of(5, new int[] {5, 5, 5, 2}), Arguments.of(10, new int[] {10, 10, 20}), Arguments.of(10, new int[] {10, 20, 10}), Arguments.of(10, new int[] {20, 10, 10}), Arguments.of(-1, new int[] {10, 10, 20, 20, 30, 30}), Arguments.of(4, new int[] {1, 4, 2, 4, 4, 5, 4}));
21+
}
22+
}

0 commit comments

Comments
 (0)