ocaml: phase 5.1 luhn.ml baseline (Luhn check-digit, 2/4 inputs valid)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 27s
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 27s
Walks digits right-to-left, doubles every other starting from the
second-from-right; if a doubled value > 9, subtract 9. Sum must be
divisible by 10:
let luhn s =
let n = String.length s in
let total = ref 0 in
for i = 0 to n - 1 do
let d = Char.code s.[n - 1 - i] - Char.code '0' in
let v = if i mod 2 = 1 then
let dd = d * 2 in
if dd > 9 then dd - 9 else dd
else d
in
total := !total + v
done;
!total mod 10 = 0
Test cases:
'79927398713' valid
'79927398710' invalid
'4532015112830366' valid (real Visa test)
'1234567890123456' invalid
sum = 2
Tests right-to-left index walk via 'n - 1 - i', Char.code '0'
arithmetic for digit conversion, and nested if-then-else.
75 baseline programs total.
This commit is contained in:
@@ -35,6 +35,7 @@
|
||||
"fizzbuzz.ml": 57,
|
||||
"flatten_tree.ml": 28,
|
||||
"list_ops.ml": 30,
|
||||
"luhn.ml": 2,
|
||||
"mat_mul.ml": 621,
|
||||
"max_path_tree.ml": 11,
|
||||
"mod_inverse.ml": 27,
|
||||
|
||||
Reference in New Issue
Block a user