Решение на Дигитален корен от Антонио Миндов

Обратно към всички решения

Към профила на Антонио Миндов

Резултати

  • 20 точки от тестове
  • 0 бонус точки
  • 20 точки общо
  • 6 успешни тест(а)
  • 0 неуспешни тест(а)

Код

pub fn decimal(input: &str) -> Option<u32> {
digital_root(input, 10)
}
pub fn hex(input: &str) -> Option<u32> {
digital_root(input, 16)
}
pub fn octal(input: &str) -> Option<u32> {
digital_root(input, 8)
}
pub fn binary(input: &str) -> Option<u32> {
digital_root(input, 2)
}
fn to_base(numb: u32, base: u32) -> String {
match base {
2 => format!("{:b}", numb),
8 => format!("{:o}", numb),
10 => numb.to_string(),
16 => format!("{:x}", numb),
_ => panic!("What do you mean you want it in that base???")
}
}
fn add_optionals(a: Option<u32>, b: Option<u32>) -> Option<u32> {
a.and_then(|a| b.map(|b| a + b))
}
fn digital_root(input: &str, base: u32) -> Option<u32> {
let result = input.chars().map(|c| c.to_digit(base))
.fold(Some(0), add_optionals);
result.map( |res| to_base(res, base))
.filter( |input| input.len() > 1)
.and_then(|input| digital_root(&input[..], base))
.or(result)
}

Лог от изпълнението

Compiling solution v0.1.0 (/tmp/d20200111-2173579-qi19ru/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.77s
     Running target/debug/deps/solution-a73e64ec87929bd0

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running target/debug/deps/solution_test-38971695424b36d5

running 6 tests
test solution_test::test_binary ... ok
test solution_test::test_decimal_basic ... ok
test solution_test::test_hex_basic ... ok
test solution_test::test_invalid ... ok
test solution_test::test_octal_basic ... ok
test solution_test::test_zeroes ... ok

test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

   Doc-tests solution

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

История (1 версия и 3 коментара)

Антонио качи първо решение на 01.11.2019 16:06 (преди почти 6 години)