룬 알고리즘 – 종합 녹
Luhn 알고리즘은 신용 카드 번호를 확인하는 데 사용되는 알고리즘입니다. 이 알고리즘은 신용 카드 번호를 문자열로 받아들이고 다음 순서로 신용 카드 번호를 확인합니다. 모든 공백.
google.github.io
// TODO: remove this when you're done with your implementation.
#!(allow(unused_variables, dead_code))
pub fn luhn(cc_number: &str) -> bool {
let cc = cc_number.trim();
let mut have_to_double : bool = false;
let mut sum: u32 = 0;
if cc.split(" ").collect::<Vec<&str>>().len() < 2 {
return false
}
let reversed_cc: String = cc.chars().rev().collect::<String>();
for (i, c) in reversed_cc.chars().enumerate() {
if c == ' ' {
continue;
}
let num:u32 = c.to_digit(10).unwrap();
if have_to_double {
sum += (num*2) / 10 + (num*2) % 10;
have_to_double = false;
} else {
sum += num;
have_to_double = true;
}
}
if sum % 10 == 0 {
return true;
}
return false;
}
#(test)
fn test_non_digit_cc_number() {
assert!(!luhn("foo"));
}
#(test)
fn test_empty_cc_number() {
assert!(!luhn(""));
assert!(!luhn(" "));
assert!(!luhn(" "));
assert!(!luhn(" "));
}
#(test)
fn test_single_digit_cc_number() {
assert!(!luhn("0"));
}
#(test)
fn test_two_digit_cc_number() {
assert!(luhn(" 0 0 "));
}
#(test)
fn test_valid_cc_number() {
assert!(luhn("4263 9826 4026 9299"));
assert!(luhn("4539 3195 0343 6467"));
assert!(luhn("7992 7398 713"));
}
#(test)
fn test_invalid_cc_number() {
assert!(!luhn("4223 9826 4026 9299"));
assert!(!luhn("4539 3195 0343 6476"));
assert!(!luhn("8273 1232 7352 0569"));
}
#(allow(dead_code))
fn main() {}
문자열과 반복자 – 포괄적인 Rust
이 연습에서는 웹 서버의 라우팅 구성 요소를 구현합니다. 서버는 요청 경로를 처리할 수 있는 여러 경로 접두사로 구성됩니다. 경로 접두사에는 와일드카드 문자가 포함될 수 있습니다.
google.github.io
// TODO: remove this when you're done with your implementation.
#!(allow(unused_variables, dead_code))
pub fn prefix_matches(prefix: &str, request_path: &str) -> bool {
let v_prefix = prefix.split("/").collect::<Vec<&str>>();
let v_request_path = request_path.split("/").collect::<Vec<&str>>();
let wildcard = "*";
for (pos, item) in v_prefix.iter().enumerate() {
if pos > v_request_path.len()-1 {
return false
}
if item != &v_request_path(pos) && item.to_string() != wildcard {
return false
}
}
true
}
#(test)
fn test_matches_without_wildcard() {
assert!(prefix_matches("/v1/publishers", "/v1/publishers"));
assert!(prefix_matches("/v1/publishers", "/v1/publishers/abc-123"));
assert!(prefix_matches("/v1/publishers", "/v1/publishers/abc/books"));
assert!(!prefix_matches("/v1/publishers", "/v1"));
assert!(!prefix_matches("/v1/publishers", "/v1/publishersBooks"));
assert!(!prefix_matches("/v1/publishers", "/v1/parent/publishers"));
}
#(test)
fn test_matches_with_wildcard() {
assert!(prefix_matches(
"/v1/publishers/*/books",
"/v1/publishers/foo/books"
));
assert!(prefix_matches(
"/v1/publishers/*/books",
"/v1/publishers/bar/books"
));
assert!(prefix_matches(
"/v1/publishers/*/books",
"/v1/publishers/foo/books/book1"
));
assert!(!prefix_matches("/v1/publishers/*/books", "/v1/publishers"));
assert!(!prefix_matches(
"/v1/publishers/*/books",
"/v1/publishers/foo/booksByAuthor"
));
}