Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,15 @@
"match"
]
},
{
"slug": "luhn",
"difficulty": 1,
"topics": [
"str to digits",
"iterators",
"higher-order functions"
]
},
{
"slug": "largest-series-product",
"difficulty": 1,
Expand Down
7 changes: 7 additions & 0 deletions exercises/luhn/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
# Generated by Cargo
# will have compiled files and executables
/target/

# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
# More information here http://doc.crates.io/guide.html#cargotoml-vs-cargolock
Cargo.lock
3 changes: 3 additions & 0 deletions exercises/luhn/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
[package]
name = "luhn"
version = "0.0.0"
13 changes: 13 additions & 0 deletions exercises/luhn/example.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
pub fn is_valid(candidate: &str) -> bool {
if candidate.chars().any(|c| c.is_alphabetic()) || candidate.chars().count() == 1 {
return false;
}

candidate.chars()
.filter_map(|c| c.to_digit(10))
.rev()
.enumerate()
.map(|(index, digit)| if index % 2 == 0 { digit } else { digit * 2 })
.map(|digit| if digit > 9 { digit - 9 } else { digit })
.sum::<u32>() % 10 == 0
}
38 changes: 38 additions & 0 deletions exercises/luhn/tests/luhn.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
extern crate luhn;

use luhn::*;

#[test]
fn single_digit_string_is_invalid() {
assert!(!is_valid("1"));
}

#[test]
#[ignore]
fn single_zero_string_is_invalid() {
assert!(!is_valid("0"));
}

#[test]
#[ignore]
fn valid_canadian_sin_is_valid() {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

long cat is long.

(No change necessary)

assert!(is_valid("046 454 286"));
}

#[test]
#[ignore]
fn invalid_canadian_sin_is_invalid() {
assert!(!is_valid("046 454 287"));
}

#[test]
#[ignore]
fn invalid_credit_card_is_invalid() {
assert!(!is_valid("8273 1232 7352 0569"));
}

#[test]
#[ignore]
fn strings_that_contain_non_digits_are_invalid() {
assert!(!is_valid("046a 454 286"));
}