add luhn's algorithm (issue #312)
parent
e4660ab365
commit
93f04e0d98
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "luhn"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
@ -0,0 +1,24 @@
|
||||
fn main() {
|
||||
println!("{}", validate(vec![1, 2, 3, 4, 5, 6, 7, 8, 9]));
|
||||
}
|
||||
|
||||
fn validate(card: Vec<u8>) -> bool {
|
||||
let mut card = card;
|
||||
let given_check = card.pop().unwrap();
|
||||
|
||||
let mut check = 0;
|
||||
for (i, n) in card.iter().rev().enumerate() {
|
||||
check += match i & 1 == 0 {
|
||||
true => {
|
||||
if *n > 4 {
|
||||
(*n * 2) - 9
|
||||
} else {
|
||||
*n * 2
|
||||
}
|
||||
}
|
||||
false => *n,
|
||||
};
|
||||
}
|
||||
|
||||
10 - (check % 10) == given_check
|
||||
}
|
Loading…
Reference in new issue