ocaml: phase 5.1 balance.ml baseline (paren/bracket/brace balance via Stack)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 51s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 51s
is_balanced walks a string; on each char:
'(', '[', '{' -> Stack.push c
')', ']', '}' -> require stack non-empty AND top = expected opener,
else mark ok = false
others -> skip
At end: !ok && Stack.is_empty stack.
Five test cases:
'({[abc]d}e)' -> true
'(a]' -> false (no matching opener)
'{[}]' -> false (mismatched closer)
'(())' -> true
'' -> true
Sum of (if balanced then 1 else 0) -> 3.
Exercises:
Stack.create / push / pop / is_empty
s.[!i] string indexing
while loop + bool ref short-circuit
multi-arm if/else if/else if dispatch
31 baseline programs total.
This commit is contained in:
25
lib/ocaml/baseline/balance.ml
Normal file
25
lib/ocaml/baseline/balance.ml
Normal file
@@ -0,0 +1,25 @@
|
||||
let is_balanced s =
|
||||
let stack = Stack.create () in
|
||||
let n = String.length s in
|
||||
let ok = ref true in
|
||||
let i = ref 0 in
|
||||
while !i < n && !ok do
|
||||
let c = s.[!i] in
|
||||
(if c = '(' || c = '[' || c = '{' then Stack.push c stack
|
||||
else if c = ')' then
|
||||
(if Stack.is_empty stack || Stack.pop stack <> '(' then ok := false)
|
||||
else if c = ']' then
|
||||
(if Stack.is_empty stack || Stack.pop stack <> '[' then ok := false)
|
||||
else if c = '}' then
|
||||
(if Stack.is_empty stack || Stack.pop stack <> '{' then ok := false));
|
||||
i := !i + 1
|
||||
done;
|
||||
!ok && Stack.is_empty stack
|
||||
|
||||
;;
|
||||
|
||||
(if is_balanced "({[abc]d}e)" then 1 else 0) +
|
||||
(if is_balanced "(a]" then 1 else 0) +
|
||||
(if is_balanced "{[}]" then 1 else 0) +
|
||||
(if is_balanced "(())" then 1 else 0) +
|
||||
(if is_balanced "" then 1 else 0)
|
||||
@@ -1,6 +1,7 @@
|
||||
{
|
||||
"anagrams.ml": 3,
|
||||
"bag.ml": 3,
|
||||
"balance.ml": 3,
|
||||
"bfs.ml": 6,
|
||||
"btree.ml": 39,
|
||||
"brainfuck.ml": 75,
|
||||
|
||||
Reference in New Issue
Block a user