Skip to content

Instantly share code, notes, and snippets.

@wperron
Created August 8, 2023 13:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wperron/e619714b083b69608c5b51ba94646cc4 to your computer and use it in GitHub Desktop.
Save wperron/e619714b083b69608c5b51ba94646cc4 to your computer and use it in GitHub Desktop.
Rust implementation of Luhn's algorithm
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment