Cleanup BoyerMoore (#4951)

* modify code to make use of java Optional class

* revert changes

* add java.util.Optional<Integer>

* add java.util.Optional

* refactors: make `findmajor` return `optional`

* refactors: make method name findMajor and split it

* refactors: change method name in tests

* Apply suggestions from code review

Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>

* change back to int

* fix: swap arguments

* tests: add some test cases

* refactor: add `isMajority` and avoid rounding

* style: use `var`

* style: swap arguments of `countOccurrences`

---------

Co-authored-by: vil02 <vil02@o2.pl>
Co-authored-by: Piotr Idzik <65706193+vil02@users.noreply.github.com>
This commit is contained in:
Prathamesh Powar
2023-10-31 13:37:59 +05:30
committed by GitHub
parent d086afce09
commit 574138c7a3
2 changed files with 40 additions and 15 deletions

View File

@ -5,35 +5,50 @@ For more information on the algorithm refer
https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm
*/
package com.thealgorithms.others;
import java.util.Optional;
public final class BoyerMoore {
private BoyerMoore() {
}
public static int findmajor(final int[] a) {
public static Optional<Integer> findMajor(final int[] a) {
final var candidate = findCandidate(a);
final var count = countOccurrences(candidate, a);
if (isMajority(count, a.length)) {
return Optional.of(candidate);
}
return Optional.empty();
}
private static int findCandidate(final int[] a) {
int count = 0;
int cand = -1;
int candidate = -1;
for (final var k : a) {
if (count == 0) {
cand = k;
candidate = k;
count = 1;
} else {
if (k == cand) {
if (k == candidate) {
count++;
} else {
count--;
}
}
}
count = 0;
return candidate;
}
private static int countOccurrences(final int candidate, final int[] a) {
int count = 0;
for (final var j : a) {
if (j == cand) {
if (j == candidate) {
count++;
}
}
if (count > (a.length / 2)) {
return cand;
}
return -1;
return count;
}
private static boolean isMajority(final int count, final int totalCount) {
return 2 * count > totalCount;
}
}