Damm algorithm: Difference between revisions
Content added Content deleted
(add BQN) |
(→{{header|Ruby}}: modernized, shortened; end-less def, digits) |
||
Line 2,401: | Line 2,401: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
<lang ruby> |
<lang ruby>TABLE = [ |
||
idx = 0 |
|||
for i in 0 .. nbr.length - 1 |
|||
a = nbr[i].to_i |
|||
return false if a == nil |
|||
idx = @table[idx][a] |
|||
end |
|||
idx == 0 |
|||
end |
|||
@table = Array.new [ |
|||
[0,3,1,7,5,9,8,6,4,2], [7,0,9,2,1,5,4,8,6,3], |
[0,3,1,7,5,9,8,6,4,2], [7,0,9,2,1,5,4,8,6,3], |
||
[4,2,0,6,8,7,1,3,5,9], [1,7,5,0,9,8,3,4,2,6], |
[4,2,0,6,8,7,1,3,5,9], [1,7,5,0,9,8,3,4,2,6], |
||
Line 2,419: | Line 2,409: | ||
] |
] |
||
def damm_valid?(n) = n.digits.reverse.inject(0){|idx, a| TABLE[idx][a] } == 0 |
|||
while true |
|||
print "Number to check: " |
|||
[5724, 5727, 112946].each{|n| puts "#{n}: #{damm_valid?(n) ? "" : "in"}valid"} |
|||
</lang> |
|||
puts "this number is valid!" |
|||
⚫ | |||
else |
|||
5727: invalid |
|||
112946: valid |
|||
end |
|||
</pre> |
|||
⚫ | |||
this number is valid! |
|||
Number to check: 5727 |
|||
this number is invalid! |
|||
Number to check: 112940 |
|||
this number is invalid! |
|||
Number to check: 112946 |
|||
this number is valid! |
|||
Number to check: 1321 |
|||
this number is valid!</pre> |
|||
=={{header|Rust}}== |
=={{header|Rust}}== |