Решение на Дигитален корен от Георги Бонев

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

Към профила на Георги Бонев

Резултати

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

Код

//from the official documentation, where parameter self is changed to parameter c:char
pub fn to_digit(c: char, radix: u32) -> Option<u32> {
assert!(radix <= 36, "to_digit: radix is too high (maximum 36)");
// the code is split up here to improve execution speed for cases where
// the `radix` is constant and 10 or smaller
let val = if radix <= 10 {
match c {
'0' ..= '9' => c as u32 - '0' as u32,
_ => return None,
}
} else {
match c {
'0'..='9' => c as u32 - '0' as u32,
'a'..='z' => c as u32 - 'a' as u32 + 10,
'A'..='Z' => c as u32 - 'A' as u32 + 10,
_ => return None,
}
};

Хмм, не съм сигурен, че кода ще бъде по-бърз, actually :). Пак изпълняваш същия код и случая 0-9 е първи случай. Match statement-а се превежда до същото нещо. Евентуално ако radix-а е под 11, правиш по-малко проверки в случай на грешен вход, но тук сравняваш едно-единствено число. Единствено спестяваш 2 if-а в случай на грешка, на цената на 1 допълнителен if във всеки случай.

Няма как да съм сигурен без да го benchmark-на, но си признавам, че 1) ме мързи, и 2) това е дооооста малка оптимизация :).

if val < radix { Some(val) }
else { None }
}
/// Десетична бройна система: 0-9
pub fn decimal(input: &str) -> Option<u32> {
let mut sum = 0;
let string = input.clone();
let mut chars = string.chars();
while let Some(c) = chars.next() {
// let cc = c.unwrap();
let val = match c {
'0' ..= '9' => c,
_ => return None,
};
let mut digit = to_digit(c,10);
sum = sum + digit.unwrap();
}
while sum / 10 != 0 {
let mut newSum = 0;
while sum / 10 != 0 {
newSum = newSum + sum % 10;
sum = sum / 10;
}
newSum = newSum + sum;
sum = newSum;
}
if sum < 10 { Some(sum) }
else { None }
}
/// Шестнадесетична бройна система: 0-9, последвано от a-f
pub fn hex(input: &str) -> Option<u32> {
let mut sum = 0;
let string = input.clone();
let mut chars = string.chars();
let mut vecHex = Vec::new();
while let Some(c) = chars.next() {
let val = match c {
'0' ..= 'f' => c,
_ => return None,
};
vecHex.push(c);
}
while vecHex.len() > 0 {
let mut i = 0;
while i < vecHex.len() {
let c = vecHex.pop();
let cc = c.unwrap();
let mut digit = to_digit(cc,16);
sum = sum + digit.unwrap();
i = i + 1;
}
let mut quotient;
let mut remainder;
while sum / 16 != 0 {
quotient = sum / 16;
remainder = sum % 16;
sum = sum / 16;
if remainder == 0 { vecHex.push('0') }
if remainder == 1 { vecHex.push('1') }
if remainder == 2 { vecHex.push('2') }
if remainder == 3 { vecHex.push('3') }
if remainder == 4 { vecHex.push('4') }
if remainder == 5 { vecHex.push('5') }
if remainder == 6 { vecHex.push('6') }
if remainder == 7 { vecHex.push('7') }
if remainder == 8 { vecHex.push('8') }
if remainder == 9 { vecHex.push('9') }
if remainder == 10 { vecHex.push('a') }
if remainder == 11 { vecHex.push('b') }
if remainder == 12 { vecHex.push('c') }
if remainder == 13 { vecHex.push('d') }
if remainder == 14 { vecHex.push('e') }
if remainder == 15 { vecHex.push('f') }
}
}
if sum < 16 { Some(sum) }
else { None }
}
/// Осмична бройна система: 0-7
pub fn octal(input: &str) -> Option<u32> {
let mut sum = 0;
let string = input.clone();
let mut chars = string.chars();
let mut vecHex = Vec::new();
while let Some(c) = chars.next() {
let val = match c {
'0' ..= '7' => c,
_ => return None,
};
vecHex.push(c);
}
while vecHex.len() > 0 {
let mut i = 0;
while i < vecHex.len() {
let c = vecHex.pop();
let cc = c.unwrap();
let mut digit = to_digit(cc,8);
sum = sum + digit.unwrap();
i = i + 1;
}
let mut quotient;
let mut remainder;
while sum / 8 != 0 {
quotient = sum / 8;
remainder = sum % 8;
sum = sum / 8;
if remainder == 0 { vecHex.push('0') }
if remainder == 1 { vecHex.push('1') }
if remainder == 2 { vecHex.push('2') }
if remainder == 3 { vecHex.push('3') }
if remainder == 4 { vecHex.push('4') }
if remainder == 5 { vecHex.push('5') }
if remainder == 6 { vecHex.push('6') }
if remainder == 7 { vecHex.push('7') }
}
}
if sum < 8 { Some(sum) }
else { None }
}
/// Двоична бройна система: 0-1
pub fn binary(input: &str) -> Option<u32> {
let mut sum = 0;
let string = input.clone();
let mut chars = string.chars();
let mut vecHex = Vec::new();
while let Some(c) = chars.next() {
let val = match c {
'0' ..= '1' => c,
_ => return None,
};
vecHex.push(c);
}
while vecHex.len() > 0 {
let mut i = 0;
while i < vecHex.len() {
let c = vecHex.pop();
let cc = c.unwrap();
let mut digit = to_digit(cc,2);
sum = sum + digit.unwrap();
i = i + 1;
}
let mut quotient;
let mut remainder;
while sum / 2 != 0 {
quotient = sum / 2;
remainder = sum % 2;
sum = sum / 2;
if remainder == 0 { vecHex.push('0') }
if remainder == 1 { vecHex.push('1') }
}
}
if sum < 2 { Some(sum) }
else { None }
}
fn main() {
/* assert_eq!(decimal("345"), Some(3));
assert_eq!(hex("345"), Some(0xc));
assert_eq!(octal("1"), Some(1));
assert_eq!(binary("1"), Some(1));
let num = String::from("1");
assert_eq!(binary(&num[..]), Some(1));
println!("{:?}",hex("fe2"));
println!("{:?}",decimal("52585879"));
println!("{:?}",octal("17767"));*/
}

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

Compiling solution v0.1.0 (/tmp/d20200111-2173579-5c5qcn/solution)
warning: unused variable: `val`
  --> src/lib.rs:35:21
   |
35 |                 let val = match c {
   |                     ^^^ help: consider prefixing with an underscore: `_val`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: unused variable: `val`
  --> src/lib.rs:66:13
   |
66 |         let val = match c {
   |             ^^^ help: consider prefixing with an underscore: `_val`

warning: variable `quotient` is assigned to, but never used
  --> src/lib.rs:86:17
   |
86 |         let mut quotient;
   |                 ^^^^^^^^
   |
   = note: consider using `_quotient` instead

warning: value assigned to `quotient` is never read
  --> src/lib.rs:89:13
   |
89 |             quotient = sum / 16;
   |             ^^^^^^^^
   |
   = note: `#[warn(unused_assignments)]` on by default
   = help: maybe it is overwritten before being read?

warning: unused variable: `val`
   --> src/lib.rs:126:13
    |
126 |         let val = match c {
    |             ^^^ help: consider prefixing with an underscore: `_val`

warning: variable `quotient` is assigned to, but never used
   --> src/lib.rs:143:17
    |
143 |         let mut quotient;
    |                 ^^^^^^^^
    |
    = note: consider using `_quotient` instead

warning: value assigned to `quotient` is never read
   --> src/lib.rs:146:13
    |
146 |             quotient = sum / 8;
    |             ^^^^^^^^
    |
    = help: maybe it is overwritten before being read?

warning: unused variable: `val`
   --> src/lib.rs:172:13
    |
172 |         let val = match c {
    |             ^^^ help: consider prefixing with an underscore: `_val`

warning: variable `quotient` is assigned to, but never used
   --> src/lib.rs:189:17
    |
189 |         let mut quotient;
    |                 ^^^^^^^^
    |
    = note: consider using `_quotient` instead

warning: value assigned to `quotient` is never read
   --> src/lib.rs:192:13
    |
192 |             quotient = sum / 2;
    |             ^^^^^^^^
    |
    = help: maybe it is overwritten before being read?

warning: variable does not need to be mutable
  --> src/lib.rs:40:13
   |
40 |         let mut digit = to_digit(c,10);
   |             ----^^^^^
   |             |
   |             help: remove this `mut`
   |
   = note: `#[warn(unused_mut)]` on by default

warning: variable does not need to be mutable
  --> src/lib.rs:80:17
   |
80 |             let mut digit = to_digit(cc,16);
   |                 ----^^^^^
   |                 |
   |                 help: remove this `mut`

warning: variable does not need to be mutable
   --> src/lib.rs:138:17
    |
138 |             let mut digit = to_digit(cc,8);
    |                 ----^^^^^
    |                 |
    |                 help: remove this `mut`

warning: variable does not need to be mutable
   --> src/lib.rs:184:17
    |
184 |             let mut digit = to_digit(cc,2);
    |                 ----^^^^^
    |                 |
    |                 help: remove this `mut`

warning: function is never used: `main`
   --> src/lib.rs:207:1
    |
207 | fn main() {
    | ^^^^^^^^^
    |
    = note: `#[warn(dead_code)]` on by default

warning: variable `newSum` should have a snake case name
  --> src/lib.rs:44:17
   |
44 |         let mut newSum = 0;
   |                 ^^^^^^ help: convert the identifier to snake case: `new_sum`
   |
   = note: `#[warn(non_snake_case)]` on by default

warning: variable `vecHex` should have a snake case name
  --> src/lib.rs:63:13
   |
63 |     let mut vecHex = Vec::new();
   |             ^^^^^^ help: convert the identifier to snake case: `vec_hex`

warning: variable `vecHex` should have a snake case name
   --> src/lib.rs:123:13
    |
123 |     let mut vecHex = Vec::new();
    |             ^^^^^^ help: convert the identifier to snake case: `vec_hex`

warning: variable `vecHex` should have a snake case name
   --> src/lib.rs:169:13
    |
169 |     let mut vecHex = Vec::new();
    |             ^^^^^^ help: convert the identifier to snake case: `vec_hex`

warning: unused variable: `val`
  --> src/lib.rs:35:21
   |
35 |                 let val = match c {
   |                     ^^^ help: consider prefixing with an underscore: `_val`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: unused variable: `val`
  --> src/lib.rs:66:13
   |
66 |         let val = match c {
   |             ^^^ help: consider prefixing with an underscore: `_val`

warning: variable `quotient` is assigned to, but never used
  --> src/lib.rs:86:17
   |
86 |         let mut quotient;
   |                 ^^^^^^^^
   |
   = note: consider using `_quotient` instead

warning: value assigned to `quotient` is never read
  --> src/lib.rs:89:13
   |
89 |             quotient = sum / 16;
   |             ^^^^^^^^
   |
   = note: `#[warn(unused_assignments)]` on by default
   = help: maybe it is overwritten before being read?

warning: unused variable: `val`
   --> src/lib.rs:126:13
    |
126 |         let val = match c {
    |             ^^^ help: consider prefixing with an underscore: `_val`

warning: variable `quotient` is assigned to, but never used
   --> src/lib.rs:143:17
    |
143 |         let mut quotient;
    |                 ^^^^^^^^
    |
    = note: consider using `_quotient` instead

warning: value assigned to `quotient` is never read
   --> src/lib.rs:146:13
    |
146 |             quotient = sum / 8;
    |             ^^^^^^^^
    |
    = help: maybe it is overwritten before being read?

warning: unused variable: `val`
   --> src/lib.rs:172:13
    |
172 |         let val = match c {
    |             ^^^ help: consider prefixing with an underscore: `_val`

warning: variable `quotient` is assigned to, but never used
   --> src/lib.rs:189:17
    |
189 |         let mut quotient;
    |                 ^^^^^^^^
    |
    = note: consider using `_quotient` instead

warning: value assigned to `quotient` is never read
   --> src/lib.rs:192:13
    |
192 |             quotient = sum / 2;
    |             ^^^^^^^^
    |
    = help: maybe it is overwritten before being read?

warning: variable does not need to be mutable
  --> src/lib.rs:40:13
   |
40 |         let mut digit = to_digit(c,10);
   |             ----^^^^^
   |             |
   |             help: remove this `mut`
   |
   = note: `#[warn(unused_mut)]` on by default

warning: variable does not need to be mutable
  --> src/lib.rs:80:17
   |
80 |             let mut digit = to_digit(cc,16);
   |                 ----^^^^^
   |                 |
   |                 help: remove this `mut`

warning: variable does not need to be mutable
   --> src/lib.rs:138:17
    |
138 |             let mut digit = to_digit(cc,8);
    |                 ----^^^^^
    |                 |
    |                 help: remove this `mut`

warning: variable does not need to be mutable
   --> src/lib.rs:184:17
    |
184 |             let mut digit = to_digit(cc,2);
    |                 ----^^^^^
    |                 |
    |                 help: remove this `mut`

warning: variable `newSum` should have a snake case name
  --> src/lib.rs:44:17
   |
44 |         let mut newSum = 0;
   |                 ^^^^^^ help: convert the identifier to snake case: `new_sum`
   |
   = note: `#[warn(non_snake_case)]` on by default

warning: variable `vecHex` should have a snake case name
  --> src/lib.rs:63:13
   |
63 |     let mut vecHex = Vec::new();
   |             ^^^^^^ help: convert the identifier to snake case: `vec_hex`

warning: variable `vecHex` should have a snake case name
   --> src/lib.rs:123:13
    |
123 |     let mut vecHex = Vec::new();
    |             ^^^^^^ help: convert the identifier to snake case: `vec_hex`

warning: variable `vecHex` should have a snake case name
   --> src/lib.rs:169:13
    |
169 |     let mut vecHex = Vec::new();
    |             ^^^^^^ help: convert the identifier to snake case: `vec_hex`

    Finished test [unoptimized + debuginfo] target(s) in 1.94s
     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 версия и 5 коментара)

Георги качи първо решение на 05.11.2019 16:15 (преди почти 6 години)

Кода минава тестовете, но можеше да бъде по-чист. Подозирам, че си бързал да го довършиш преди крайния срок... Затова е добре да си дадеш повече време преди срока :).