Another code for exercism, It is to convert Vec of u32 from one base to another base. Please help to make it more idiomatic, Also if this type of question is welcomed here or not.
#[derive(Debug, PartialEq)]
pub enum Error {
InvalidInputBase,
InvalidOutputBase,
InvalidDigit(u32),
}
pub fn convert(number: &[u32], from_base: u32, to_base: u32) -> Result<Vec<u32>, Error> {
if from_base < 2 {
return Err(Error::InvalidInputBase);
}
if to_base <2 {
return Err(Error::InvalidOutputBase);
}
if number.iter().any(|&x| x > 0 && x >= from_base ){
return Err(Error::InvalidDigit(from_base));
}
let res: u32 = number.iter().rev().enumerate().map(|(index, x)| x*from_base.pow(index as u32)).sum();
Ok(convert_back(res, to_base))
}
fn convert_back(number: u32, base: u32) -> Vec<u32>{
let mut res: Vec<u32> = Vec::new();
let mut inter = number as f64;
loop {
inter = inter as f64/base as f64;
res.push((inter.fract()*base as f64).round() as u32);
if inter as u32 ==0{
break
}
inter = inter.trunc();
}
res.reverse();
res
}
Some tests
fn decimal_to_binary() {
let input_base = 10;
let input_digits = &[4, 2];
let output_base = 2;
let output_digits = vec![1, 0, 1, 0, 1, 0];
assert_eq!(
ayb::convert(input_digits, input_base, output_base),
Ok(output_digits)
);
}
fn trinary_to_hexadecimal() {
let input_base = 3;
let input_digits = &[1, 1, 2, 0];
let output_base = 16;
let output_digits = vec![2, 10];
assert_eq!(
convert(input_digits, input_base, output_base),
Ok(output_digits)
);
}
fn hexadecimal_to_trinary() {
let input_base = 16;
let input_digits = &[2, 10];
let output_base = 3;
let output_digits = vec![1, 1, 2, 0];
assert_eq!(
convert(input_digits, input_base, output_base),
Ok(output_digits)
);
}
fn invalid_positive_digit() {
let input_base = 2;
let input_digits = &[1, 2, 1, 0, 1, 0];
let output_base = 10;
assert_eq!(
convert(input_digits, input_base, output_base),
Err(Error::InvalidDigit(2))
);
}
fn output_base_is_zero() {
let input_base = 10;
let input_digits = &[7];
let output_base = 0;
assert_eq!(
convert(input_digits, input_base, output_base),
Err(Error::InvalidOutputBase)
);
}
```