Решение на Дигитален корен от Ричи Хаджиев

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

Към профила на Ричи Хаджиев

Резултати

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

Код

fn sum(input: String, radix: u32) -> u32 {
input.chars().map(|c| c.to_digit(radix).unwrap()).sum::<u32>()
}
fn validate(input: &str, radix: u32) -> Option<&str>{
if input.is_empty() {
return None
}
else {
for c in input.chars() {
if !c.is_digit(radix) {
return None
}
}
return Some(input)
}
}
fn hex_helper(input: String) -> String{
if input.len() == 1 {
input
}
else {
let new = format!("{:x}", sum(input, 16));
hex_helper(new)
}
}

Подозирам, че тук можеше да минеш без String, а функцията ти да приема &str. Рекурсивното извикване би било hex_helper(&new[..]) или директно hex_helper(&new). Би ти спестило едно извикване на .to_string() в дългите верижки method call-ове по-долу.

pub fn hex(input: &str) -> Option<u32> {
let radix = 16;
let validated_input = validate(input, radix);
match validated_input {
None => return None,
Some(val) => Some(hex_helper(val.to_string()).chars().next().unwrap().to_digit(radix).unwrap())

Всеки път като имаш unwrap() тук, можеше да го заместиш с една match клауза и да върнеш None ако не получиш очаквания резултат. И щеше да премахнеш напълно нуждата от validate. Нещо повече, тъй като Option работи с ?, вероятно можеше да замениш този код със Some(hex_helper(val.to_string()).chars().next()?.to_digit(radix)?).

}
}
fn dec_helper(input: String) -> String{
if input.len() == 1 {
input
}
else {
let new = format!("{}", sum(input, 10));
dec_helper(new)
}
}
pub fn decimal(input: &str) -> Option<u32> {
let radix = 10;
let validated_input = validate(input, radix);
match validated_input {
None => return None,
Some(val) => Some(dec_helper(val.to_string()).chars().next().unwrap().to_digit(radix).unwrap())
}
}
fn oct_helper(input: String) -> String{
if input.len() == 1 {
input
}
else {
let new = format!("{:o}", sum(input, 8));
oct_helper(new)
}
}
pub fn octal(input: &str) -> Option<u32> {
let radix = 8;
let validated_input = validate(input, radix);
match validated_input {
None => return None,
Some(val) => Some(oct_helper(val.to_string()).chars().next().unwrap().to_digit(radix).unwrap())
}
}
fn bin_helper(input: String) -> String{
if input.len() == 1 {
input
}
else {
let new = format!("{:b}", sum(input, 2));
bin_helper(new)
}
}
pub fn binary(input: &str) -> Option<u32> {
let radix = 2;
let validated_input = validate(input, radix);
match validated_input {
None => return None,
Some(val) => Some(bin_helper(val.to_string()).chars().next().unwrap().to_digit(radix).unwrap())
}
}

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

Compiling solution v0.1.0 (/tmp/d20200111-2173579-kns9mg/solution)
    Finished test [unoptimized + debuginfo] target(s) in 4.13s
     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 коментара)