ocaml: phase 5.1 majority_vote.ml baseline (Boyer-Moore majority, [3;3;4;2;4;4;2;4;4] = 4)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 25s
O(n) time / O(1) space majority vote algorithm:
let majority xs =
let cand = ref 0 in
let count = ref 0 in
List.iter (fun x ->
if !count = 0 then begin
cand := x;
count := 1
end else if x = !cand then count := !count + 1
else count := !count - 1
) xs;
!cand
The candidate is updated to the current element whenever count
reaches zero. When a strict majority exists, this guarantees the
result.
majority [3;3;4;2;4;4;2;4;4] = 4 (5 of 9, > n/2)
97 baseline programs total.
This commit is contained in:
@@ -51,6 +51,7 @@
|
|||||||
"json_pretty.ml": 24,
|
"json_pretty.ml": 24,
|
||||||
"kadane.ml": 6,
|
"kadane.ml": 6,
|
||||||
"lambda_calc.ml": 7,
|
"lambda_calc.ml": 7,
|
||||||
|
"majority_vote.ml": 4,
|
||||||
"levenshtein.ml": 11,
|
"levenshtein.ml": 11,
|
||||||
"memo_fib.ml": 75025,
|
"memo_fib.ml": 75025,
|
||||||
"mortgage.ml": 1073,
|
"mortgage.ml": 1073,
|
||||||
|
|||||||
15
lib/ocaml/baseline/majority_vote.ml
Normal file
15
lib/ocaml/baseline/majority_vote.ml
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
let majority xs =
|
||||||
|
let cand = ref 0 in
|
||||||
|
let count = ref 0 in
|
||||||
|
List.iter (fun x ->
|
||||||
|
if !count = 0 then begin
|
||||||
|
cand := x;
|
||||||
|
count := 1
|
||||||
|
end else if x = !cand then count := !count + 1
|
||||||
|
else count := !count - 1
|
||||||
|
) xs;
|
||||||
|
!cand
|
||||||
|
|
||||||
|
;;
|
||||||
|
|
||||||
|
majority [3; 3; 4; 2; 4; 4; 2; 4; 4]
|
||||||
@@ -407,6 +407,12 @@ _Newest first._
|
|||||||
binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree *
|
binary search tree (`type 'a tree = Leaf | Node of 'a * 'a tree *
|
||||||
'a tree`) with insert + in-order traversal. Tests parametric ADT,
|
'a tree`) with insert + in-order traversal. Tests parametric ADT,
|
||||||
recursive match, List.append, List.fold_left.
|
recursive match, List.append, List.fold_left.
|
||||||
|
- 2026-05-09 Phase 5.1 — majority_vote.ml baseline (Boyer-Moore
|
||||||
|
majority, [3;3;4;2;4;4;2;4;4] → 4). O(n) time / O(1) space:
|
||||||
|
candidate-and-count refs; on match increment, on mismatch
|
||||||
|
decrement and replace candidate when count reaches zero.
|
||||||
|
Demonstrates the classical streaming algorithm. 97 baseline
|
||||||
|
programs total.
|
||||||
- 2026-05-09 Phase 5.1 — adler32.ml baseline (Adler-32 checksum of
|
- 2026-05-09 Phase 5.1 — adler32.ml baseline (Adler-32 checksum of
|
||||||
"Wikipedia" = 300286872 = 0x11E60398). Two running sums modulo
|
"Wikipedia" = 300286872 = 0x11E60398). Two running sums modulo
|
||||||
65521; final checksum is `b * 65536 + a`. Used by zlib for stream
|
65521; final checksum is `b * 65536 + a`. Used by zlib for stream
|
||||||
|
|||||||
Reference in New Issue
Block a user