diff --git a/Cargo.lock b/Cargo.lock index eb564c0..9543680 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -37,6 +37,10 @@ version = "0.2.139" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79" +[[package]] +name = "luhn" +version = "0.1.0" + [[package]] name = "once_cell" version = "1.17.1" diff --git a/Cargo.toml b/Cargo.toml index 032f738..a45516b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ members = [ "balance", "empty-zeros", "fraction-math", + "luhn", "parens", "repeated-groups", "scrabble", diff --git a/luhn/Cargo.toml b/luhn/Cargo.toml new file mode 100644 index 0000000..9b8ce56 --- /dev/null +++ b/luhn/Cargo.toml @@ -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] diff --git a/luhn/src/main.rs b/luhn/src/main.rs new file mode 100644 index 0000000..f1dafee --- /dev/null +++ b/luhn/src/main.rs @@ -0,0 +1,24 @@ +fn main() { + println!("{}", validate(vec![1, 2, 3, 4, 5, 6, 7, 8, 9])); +} + +fn validate(card: Vec) -> 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 +}