Решение на Дигитален корен от Любослав Карев

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

Към профила на Любослав Карев

Резултати

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

Код

fn formula_calculate(n: u32, base: u32) -> u32{
let k:f64 = (n as f64).log(base as f64) + 1_f64;
let mut sum: u32 = 0;
for i in 0..(k as u32){
sum += (n % (base.pow(i+1)) - n % (base.pow(i))) / (base.pow(i));
}
sum
}

Интересно решение -- очаквах да го разбиете на символи, но и това работи :). Бих се опитал да използвам по-ясни имена. formula_calculate примерно е доста общо име на функция, която може да прави каквото и да е. Може би sum_digits щеше да е по-ясно. Вместо k, може би digit_count или max_digits.

В математическите формули се използват често еднобуквени променливи, отчасти понеже може да са доста абстрактни, отчасти защото имаш дефиниции с думи. Примерно избираме епсилон, такова че <обяснения>. В код обикновено се работи с конкретни неща, които могат да имат конкретни имена, а ако нямат, и просто се смята някаква обща формула, може да сложиш по един коментар някъде за самата формула и какво значат компонентите ѝ.

fn get_digital_root(input: &str, radix: u32) -> Option<u32>{
let mut current_input_number: u32;
match u32::from_str_radix(input, radix){
Ok(value) => current_input_number = value,
Err(E) => return None,
};
current_input_number = formula_calculate(current_input_number, radix);
while current_input_number > radix-1{
current_input_number = formula_calculate(current_input_number, radix);
}
Some(formula_calculate(current_input_number, radix))
}
/// Десетична бройна система: 0-9
pub fn decimal(input: &str) -> Option<u32> {
get_digital_root(input, 10)
}
/// Шестнадесетична бройна система: 0-9, последвано от a-f
pub fn hex(input: &str) -> Option<u32> {
get_digital_root(input, 16)
}
/// Осмична бройна система: 0-7
pub fn octal(input: &str) -> Option<u32> {
get_digital_root(input, 8)
}
/// Двоична бройна система: 0-1
pub fn binary(input: &str) -> Option<u32> {
get_digital_root(input, 2)
}
#[cfg(test)]
mod tests {
use crate::{decimal, hex, octal, binary};
#[test]
fn decimal_tests() {
assert_eq!(decimal("123"), Some(6));
assert_eq!(decimal("765"), Some(9));
assert_eq!(decimal("99999999"), Some(9));
assert_eq!(decimal("5"), Some(5));
assert_eq!(decimal("asdasdas"), None);
}
#[test]
fn hex_tests(){
assert_eq!(hex("7b"), Some(3));
assert_eq!(hex("345"), Some(0xc));
assert_eq!(hex("a12f"), Some(0xd));
assert_eq!(hex("5"), Some(5));
assert_eq!(hex("asdasdas"), None);
}
#[test]
fn octal_tests(){
assert_eq!(octal("74521"), Some(0o5));
assert_eq!(octal("345"), Some(0o5));
assert_eq!(octal("7777777"), Some(0o7));
assert_eq!(octal("5"), Some(0o5));
assert_eq!(octal("asdasdas"), None);
}
#[test]
fn binary_tests(){
assert_eq!(binary("11010010101"), Some(0b1));
assert_eq!(binary("101010101"), Some(0b1));
assert_eq!(binary("1"), Some(0b1));
assert_eq!(binary("0"), Some(0b0));
assert_eq!(binary("asdasdas"), None);
}
#[test]
fn test_basic() {
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));
}
}

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

Compiling solution v0.1.0 (/tmp/d20200111-2173579-26mo5/solution)
warning: unused variable: `E`
  --> src/lib.rs:17:13
   |
17 |         Err(E) => return None,
   |             ^ help: consider prefixing with an underscore: `_E`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: variable `E` should have a snake case name
  --> src/lib.rs:17:13
   |
17 |         Err(E) => return None,
   |             ^ help: convert the identifier to snake case: `e`
   |
   = note: `#[warn(non_snake_case)]` on by default

warning: unused variable: `E`
  --> src/lib.rs:17:13
   |
17 |         Err(E) => return None,
   |             ^ help: consider prefixing with an underscore: `_E`
   |
   = note: `#[warn(unused_variables)]` on by default

warning: variable `E` should have a snake case name
  --> src/lib.rs:17:13
   |
17 |         Err(E) => return None,
   |             ^ help: convert the identifier to snake case: `e`
   |
   = note: `#[warn(non_snake_case)]` on by default

    Finished test [unoptimized + debuginfo] target(s) in 4.33s
     Running target/debug/deps/solution-a73e64ec87929bd0

running 5 tests
test tests::binary_tests ... ok
test tests::decimal_tests ... ok
test tests::hex_tests ... ok
test tests::octal_tests ... ok
test tests::test_basic ... ok

test result: ok. 5 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

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

Любослав качи първо решение на 03.11.2019 18:07 (преди почти 6 години)

Любослав качи решение на 03.11.2019 18:32 (преди почти 6 години)

fn formula_calculate(n: u32, base: u32) -> u32{
let k:f64 = (n as f64).log(base as f64) + 1_f64;
let mut sum: u32 = 0;
for i in 0..(k as u32){
sum += (n % (base.pow(i+1)) - n % (base.pow(i))) / (base.pow(i));
}
sum
}
/// Десетична бройна система: 0-9
pub fn decimal(input: &str) -> Option<u32> {
let mut current_input_number: u32;
- match input.parse::<u32>(){
+ match u32::from_str_radix(input, 10){
Ok(value) => current_input_number = value,
Err(E) => return None,
};
current_input_number = formula_calculate(current_input_number, 10);
while current_input_number > 9{
current_input_number = formula_calculate(current_input_number, 10);
}
Some(formula_calculate(current_input_number, 10))
}
/// Шестнадесетична бройна система: 0-9, последвано от a-f
pub fn hex(input: &str) -> Option<u32> {
let mut current_input_number: u32;
- match input.parse::<u32>(){
+ match u32::from_str_radix(input, 16){
Ok(value) => current_input_number = value,
Err(E) => return None,
};
+ println!("{}", current_input_number);
current_input_number = formula_calculate(current_input_number, 16);
while current_input_number > 0xf{
current_input_number = formula_calculate(current_input_number, 16);
}
Some(formula_calculate(current_input_number, 16))
}
/// Осмична бройна система: 0-7
pub fn octal(input: &str) -> Option<u32> {
- unimplemented!()
+ let mut current_input_number: u32;
+
+ match u32::from_str_radix(input, 8){
+ Ok(value) => current_input_number = value,
+ Err(E) => return None,
+ };
+
+ current_input_number = formula_calculate(current_input_number, 8);
+ while current_input_number > 7{
+ current_input_number = formula_calculate(current_input_number, 8);
+ }
+ Some(formula_calculate(current_input_number, 8))
}
/// Двоична бройна система: 0-1
pub fn binary(input: &str) -> Option<u32> {
- unimplemented!()
+ let mut current_input_number: u32;
+
+ match u32::from_str_radix(input, 2){
+ Ok(value) => current_input_number = value,
+ Err(E) => return None,
+ };
+
+ current_input_number = formula_calculate(current_input_number, 2);
+ while current_input_number > 1{
+ current_input_number = formula_calculate(current_input_number, 2);
+ }
+ Some(formula_calculate(current_input_number, 2))
}
#[cfg(test)]
mod tests {
- use crate::{decimal, hex};
+ use crate::{decimal, hex, octal, binary};
#[test]
fn decimal_tests() {
assert_eq!(decimal("123"), Some(6));
assert_eq!(decimal("765"), Some(9));
assert_eq!(decimal("99999999"), Some(9));
assert_eq!(decimal("5"), Some(5));
assert_eq!(decimal("asdasdas"), None);
}
#[test]
fn hex_tests(){
- assert_eq!(hex("345"), Some(0xc));
assert_eq!(hex("7b"), Some(3));
+ assert_eq!(hex("345"), Some(0xc));
assert_eq!(hex("a12f"), Some(0xd));
assert_eq!(hex("5"), Some(5));
assert_eq!(hex("asdasdas"), None);
+ }
+
+ #[test]
+ fn octal_tests(){
+ assert_eq!(octal("74521"), Some(0o5));
+ assert_eq!(octal("345"), Some(0o5));
+ assert_eq!(octal("7777777"), Some(0o7));
+ assert_eq!(octal("5"), Some(0o5));
+ assert_eq!(octal("asdasdas"), None);
+ }
+
+ #[test]
+ fn binary_tests(){
+ assert_eq!(binary("11010010101"), Some(0b1));
+ assert_eq!(binary("101010101"), Some(0b1));
+ assert_eq!(binary("1"), Some(0b1));
+ assert_eq!(binary("0"), Some(0b0));
+ assert_eq!(binary("asdasdas"), None);
}
}

Любослав качи решение на 03.11.2019 21:35 (преди почти 6 години)

fn formula_calculate(n: u32, base: u32) -> u32{
let k:f64 = (n as f64).log(base as f64) + 1_f64;
let mut sum: u32 = 0;
for i in 0..(k as u32){
sum += (n % (base.pow(i+1)) - n % (base.pow(i))) / (base.pow(i));
}
sum
}

Интересно решение -- очаквах да го разбиете на символи, но и това работи :). Бих се опитал да използвам по-ясни имена. formula_calculate примерно е доста общо име на функция, която може да прави каквото и да е. Може би sum_digits щеше да е по-ясно. Вместо k, може би digit_count или max_digits.

В математическите формули се използват често еднобуквени променливи, отчасти понеже може да са доста абстрактни, отчасти защото имаш дефиниции с думи. Примерно избираме епсилон, такова че <обяснения>. В код обикновено се работи с конкретни неща, които могат да имат конкретни имена, а ако нямат, и просто се смята някаква обща формула, може да сложиш по един коментар някъде за самата формула и какво значат компонентите ѝ.

-/// Десетична бройна система: 0-9
-pub fn decimal(input: &str) -> Option<u32> {
+
+fn get_digital_root(input: &str, radix: u32) -> Option<u32>{
let mut current_input_number: u32;
- match u32::from_str_radix(input, 10){
+ match u32::from_str_radix(input, radix){
Ok(value) => current_input_number = value,
Err(E) => return None,
};
- current_input_number = formula_calculate(current_input_number, 10);
- while current_input_number > 9{
- current_input_number = formula_calculate(current_input_number, 10);
+ current_input_number = formula_calculate(current_input_number, radix);
+ while current_input_number > radix-1{
+ current_input_number = formula_calculate(current_input_number, radix);
}
- Some(formula_calculate(current_input_number, 10))
+ Some(formula_calculate(current_input_number, radix))
}
+/// Десетична бройна система: 0-9
+pub fn decimal(input: &str) -> Option<u32> {
+ get_digital_root(input, 10)
+}
+
/// Шестнадесетична бройна система: 0-9, последвано от a-f
pub fn hex(input: &str) -> Option<u32> {
- let mut current_input_number: u32;
-
- match u32::from_str_radix(input, 16){
- Ok(value) => current_input_number = value,
- Err(E) => return None,
- };
-
- println!("{}", current_input_number);
- current_input_number = formula_calculate(current_input_number, 16);
- while current_input_number > 0xf{
- current_input_number = formula_calculate(current_input_number, 16);
- }
- Some(formula_calculate(current_input_number, 16))
+ get_digital_root(input, 16)
}
/// Осмична бройна система: 0-7
pub fn octal(input: &str) -> Option<u32> {
- let mut current_input_number: u32;
-
- match u32::from_str_radix(input, 8){
- Ok(value) => current_input_number = value,
- Err(E) => return None,
- };
-
- current_input_number = formula_calculate(current_input_number, 8);
- while current_input_number > 7{
- current_input_number = formula_calculate(current_input_number, 8);
- }
- Some(formula_calculate(current_input_number, 8))
+ get_digital_root(input, 8)
}
/// Двоична бройна система: 0-1
pub fn binary(input: &str) -> Option<u32> {
- let mut current_input_number: u32;
-
- match u32::from_str_radix(input, 2){
- Ok(value) => current_input_number = value,
- Err(E) => return None,
- };
-
- current_input_number = formula_calculate(current_input_number, 2);
- while current_input_number > 1{
- current_input_number = formula_calculate(current_input_number, 2);
- }
- Some(formula_calculate(current_input_number, 2))
+ get_digital_root(input, 2)
}
#[cfg(test)]
mod tests {
use crate::{decimal, hex, octal, binary};
#[test]
fn decimal_tests() {
assert_eq!(decimal("123"), Some(6));
assert_eq!(decimal("765"), Some(9));
assert_eq!(decimal("99999999"), Some(9));
assert_eq!(decimal("5"), Some(5));
assert_eq!(decimal("asdasdas"), None);
}
#[test]
fn hex_tests(){
assert_eq!(hex("7b"), Some(3));
assert_eq!(hex("345"), Some(0xc));
assert_eq!(hex("a12f"), Some(0xd));
assert_eq!(hex("5"), Some(5));
assert_eq!(hex("asdasdas"), None);
}
#[test]
fn octal_tests(){
assert_eq!(octal("74521"), Some(0o5));
assert_eq!(octal("345"), Some(0o5));
assert_eq!(octal("7777777"), Some(0o7));
assert_eq!(octal("5"), Some(0o5));
assert_eq!(octal("asdasdas"), None);
}
#[test]
fn binary_tests(){
assert_eq!(binary("11010010101"), Some(0b1));
assert_eq!(binary("101010101"), Some(0b1));
assert_eq!(binary("1"), Some(0b1));
assert_eq!(binary("0"), Some(0b0));
assert_eq!(binary("asdasdas"), None);
+ }
+
+
+ #[test]
+ fn test_basic() {
+ 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));
}
}

Добро решение. Получаваш и бонус точка за тестовете, макар че съм малко разочарован, че не си тествал с 0, освен двоичния случай -- може да е потенциално интересен edge case. За бъдещи домашни вероятно ще съм по-придирчив към тестове що се отнася до бонус точки :).