mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-01-18 20:39:35 +02:00
Simplify solution to Luhn exercise (#1296)
Maybe we can use bool double and make the code easier to read and comprehend
This commit is contained in:
parent
0e32756795
commit
c01b5ca6ed
@ -16,24 +16,30 @@
|
|||||||
// ANCHOR: luhn
|
// ANCHOR: luhn
|
||||||
pub fn luhn(cc_number: &str) -> bool {
|
pub fn luhn(cc_number: &str) -> bool {
|
||||||
// ANCHOR_END: luhn
|
// ANCHOR_END: luhn
|
||||||
let mut digits_seen = 0;
|
|
||||||
let mut sum = 0;
|
let mut sum = 0;
|
||||||
for (i, ch) in cc_number.chars().rev().filter(|&ch| ch != ' ').enumerate() {
|
let mut double = false;
|
||||||
match ch.to_digit(10) {
|
let mut digit_seen = 0;
|
||||||
Some(d) => {
|
|
||||||
sum += if i % 2 == 1 {
|
for c in cc_number.chars().filter(|&f| f != ' ').rev() {
|
||||||
let dd = d * 2;
|
if let Some(digit) = c.to_digit(10) {
|
||||||
dd / 10 + dd % 10
|
if double {
|
||||||
|
let double_digit = digit * 2;
|
||||||
|
sum += if double_digit > 9 {
|
||||||
|
double_digit - 9
|
||||||
} else {
|
} else {
|
||||||
d
|
double_digit
|
||||||
};
|
};
|
||||||
digits_seen += 1;
|
} else {
|
||||||
}
|
sum += digit
|
||||||
None => return false,
|
};
|
||||||
|
double = !double;
|
||||||
|
digit_seen += 1;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if digits_seen < 2 {
|
if digit_seen < 2 {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user