Optimizations anyone?
[1/4] from: kpeters::otaksoft::com at: 6-Feb-2008 12:34
Hi all ~
I just wrote the function below to validate Canadian Social Insurance numbers (SIN)
and it strikes me as, well, rather awkward.
SINs are 9 digits wide and the rightmost digit is the check digit.
Any Rebolish ideas anyone?
TIA
Kai
valid-sin: function [ sin [string!] ] [ digits8 ] [
if any [
9 <> length? trim sin
none = to-integer sin
] [ return false ]
; from left to right all even positions
evens: copy ""
sin: skip sin 1
forskip sin 2 [ evens: append evens form ( 2 * to-integer to-string first sin )]
;
evens-sum: 0
foreach digit evens [ evens-sum: evens-sum + ( to-integer to-string digit )]
;
; from left to right all odd positions
odds-sum: 0
digits8: copy/part head sin 8
forskip digits8 2 [ odds-sum: odds-sum + ( to-integer to-string first digits8 )]
;
total-sum: evens-sum + odds-sum
next-ten: 10 * (1 + to-integer to-string first to-string total-sum )
check-digit: next-ten - total-sum
;
sin: head sin
check-digit = ( to-integer to-string sin/9 )
]
; 2 valid SINs
valid-sin "130692544"
valid-sin "193456787"
[2/4] from: gregg:pointillistic at: 6-Feb-2008 14:25
Hi Kai,
KP> I just wrote the function below to validate Canadian Social InsuranceKP> numbers
(SIN) and it strikes me as, well, rather awkward.
Looks like SINs use the Luhn algorithm to calc the check digit.
luhn?: func [
card-num [string!]
/local cksum flag val
] [
cksum: 0
card-num: trim/all copy card-num
flag: even? length? card-num
foreach digit card-num [
val: to integer! form digit
if flag [
val: val * 2
if val > 9 [val: val - 9]
; - alt -
;val: pick [0 2 4 6 8 1 3 5 7 9] val + 1
]
cksum: cksum + val
flag: not flag
]
;print cksum
0 = remainder cksum 10
]
-- Gregg
[3/4] from: brock:kalef:innovapost at: 6-Feb-2008 16:38
You should add your implementation of Luhn validation script to
Wikipedia... http://en.wikipedia.org/wiki/Luhn_algorithm
[4/4] from: kpeters::otaksoft::com at: 6-Feb-2008 17:41
Thanks, Gregg ~
exactly what I was hoping for!
Kai
On Wed, 6 Feb 2008 14:25:36 -0700, Gregg Irwin wrote: