Bigint Display

Краен срок
16.12.2020 17:00
Точки
4

Срокът за предаване на решения е отминал

Едно нещо, което не имплементирахме за домашно 2 беше Display trait, защото би трябвало да е сравнително прост и си имаше достатъчно други неща за имплементация. Но сега ще искаме да имплементирате даже 2 различни начина за display-ване на един Bigint.

Първо, дефиниция и парсене:

use std::str::FromStr;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
    pub digits: Vec<u8>,
}

impl FromStr for Bigint {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut digits = Vec::with_capacity(s.len());

        for c in s.chars() {
            if let Some(digit) = c.to_digit(10) {
                digits.push(digit as u8);
            } else {
                return Err("Invalid input!");
            }
        }

        Ok(Bigint { digits })
    }
}

Даваме ви някаква проста готова имплементация, защото вече ги писахте, така че няма какво да ви караме да я мислите. Все пак, чувствайте се свободни да си я напишете както на вас ви харесва, стига да не чупи външния интерфейс, т.е. типовете, които връща. За нашите тестове, тази имплементация ще е достатъчна.

Забележете, че този Bigint няма знак -- не е особено предизвикателство да го напечатате, така че нека просто го изпуснем за опростяване.

Това, което очакваме да имплементирате е, първо, един Display:

use std::fmt;
use std::fmt::Write; // опционално, може да ви трябва, може би не, зависи какво правите.

impl fmt::Display for Bigint {
    /// Форматира число като за хора, по най-простия начин -- просто показва цифрите една след
    /// друга:
    ///
    ///   let bigint = Bigint::from_str("100000").unwrap();
    ///   println!("{}", bigint);
    ///   // => 100000
    ///
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        todo!()
    }
}

Един проблем на този вид печатане е че може да е малко тегаво да разберете колко голямо е това число. Би било по-удобно да го напечатате с групички по 3 цифри, хиляди, милиони, и т.н. Но има само една имплементация за Display на един тип, нали?

Е, можем да решим този проблем сравнително лесно -- като си имплементираме нов тип, който държи reference към стария, но се форматира по различен начин:

pub struct Delimited<'a> {
    bigint: &'a Bigint,
}

impl Bigint {
    pub fn delimited(&self) -> Delimited {
        Delimited { bigint: self }
    }
}

impl<'a> fmt::Display for Delimited<'a> {
    /// Форматира Bigint по малко по-човешки начин -- със запетайки на всеки 3 цифри (за да отделим хиляди, милиони и т.н.):
    ///
    ///   let bigint = Bigint::from_str("100000").unwrap();
    ///   println!("{}", bigint.delimited());
    ///   // => 100,000
    ///
    ///   let bigint = Bigint::from_str("100000000").unwrap();
    ///   println!("{}", bigint.delimited());
    ///   // => 100,000,000
    ///
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        todo!()
    }
}

Както и друг път, полетата, които не са pub може да ги променяте и преименувате както решите. Единственото, което ще правим в нашите тестове, е да конструираме Bigint-ове с Bigint::from_str и да ги конвертираме до низове, използвайки format! макроса. Вие напишете конкретните имплементации на Display за двата типа, както са описани. Мислете за edge cases.

Решения

Андрей
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Андрей

use std::str::FromStr;
use std::fmt::{self, Write};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for d in &self.digits {
write!(f, "{}", d)?;
}
Ok(())
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let first_group_len = self.bigint.digits.len() % 3;
let mut group_len = first_group_len;
for (i, d) in self.bigint.digits.iter().enumerate() {
if group_len == 0 {
if i > 0 { f.write_char(',')?; }
group_len = 3;
}
write!(f, "{}", d)?;
group_len -= 1;
}
Ok(())
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-1jl2y54/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.26s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Борислав Димитров
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Борислав Димитров

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut vec_to_string = String::new();
for dig in &self.digits {
vec_to_string.push_str(&dig.to_string());
}
write!(f, "{}", vec_to_string)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut vec_to_string = String::new();
let vec_len = self.bigint.digits.len();
for i in 0..vec_len{
vec_to_string.push_str(&self.bigint.digits[i].to_string());
if (vec_len-i) % 3 == 1 && i != vec_len-1 {
vec_to_string.push(',');
}
}
write!(f, "{}", vec_to_string)
}
}
/*
fn main() {
let bigint = Bigint::from_str("100000").unwrap();
println!("{}", bigint);
let bigint = Bigint::from_str("0").unwrap();
println!("{}", bigint);
let bigint = Bigint::from_str("1").unwrap();
println!("{}", bigint);
let bigint = Bigint::from_str("12").unwrap();
println!("{}", bigint);
let bigint = Bigint::from_str("123").unwrap();
println!("{}", bigint);
let bigint = Bigint::from_str("1234").unwrap();
println!("{}", bigint);
let bigint = Bigint::from_str("12345").unwrap();
println!("{}", bigint);
let bigint = Bigint::from_str("100000").unwrap(); // => 100,000
println!("{}", bigint.delimited());
let bigint = Bigint::from_str("100000000").unwrap(); // => 100,000,000
println!("{}", bigint.delimited());
let bigint = Bigint::from_str("0").unwrap();
println!("{}", bigint.delimited());
let bigint = Bigint::from_str("1").unwrap();
println!("{}", bigint.delimited());
let bigint = Bigint::from_str("12").unwrap();
println!("{}", bigint.delimited());
let bigint = Bigint::from_str("123").unwrap();
println!("{}", bigint.delimited());
let bigint = Bigint::from_str("1234").unwrap();
println!("{}", bigint.delimited());
let bigint = Bigint::from_str("12345").unwrap();
println!("{}", bigint.delimited());
}
*/
Compiling solution v0.1.0 (/tmp/d20201216-2274206-11xwoht/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.33s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Иван Лучев
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Иван Лучев

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt::{self};
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.digits.iter().map(|x| (*x + '0' as u8) as char).collect::<String>())
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut output = String::new();
for (index, digit) in self.bigint.digits.iter().enumerate() {
output.push((*digit + '0' as u8) as char);
if (self.bigint.digits.len() - index - 1) % 3 == 0 {
output.push(',');
}
}
output.pop();
write!(f, "{}", output)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-eaxxx/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.41s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Тодор Димов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Тодор Димов

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!( f, "{}", &self.digits.iter().map( |d| d.to_string() ).collect::<String>() )
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!( f, "{}", self.bigint.digits.rchunks( 3 ).rev().map( |c| c.iter().map( |d| d.to_string() ).collect::<String>() ).collect::<Vec<String>>().join( "," ) )
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-3a0qbp/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.50s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Теодор Тошков
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Теодор Тошков

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt::{self};
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
self.digits
.iter()
.map(|i| (i + 48) as char)
.collect::<String>()
)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
// TODO: fix
// no standard interleave :(
// 1 write = doesn't work with yuge numbers
// allocations for days
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}",
self.bigint
.digits
.rchunks(3)
.map(|chunk| chunk.iter().map(|i| (i + 48) as char).collect::<String>())
.rev()
.collect::<Vec<String>>()
.join(",")
)
}
}
fn main() {
let bigint = Bigint::from_str("10000000000").unwrap();
println!("{}", bigint.delimited());
println!("{}", bigint);
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-3gq91x/solution)
warning: function is never used: `main`
  --> src/lib.rs:71:4
   |
71 | fn main() {
   |    ^^^^
   |
   = note: `#[warn(dead_code)]` on by default

warning: 1 warning emitted

    Finished test [unoptimized + debuginfo] target(s) in 1.61s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Тервел Вълков
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Тервел Вълков

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let string = self.digits.
iter().
map(|&digit| std::char::from_digit(digit as u32, 10).unwrap()).
collect::<String>();
write!(f, "{}", string)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut string = String::new();
let mut digits = self.bigint.digits.clone();
digits.reverse();
let mut counter = 0;
for digit in digits {
if counter == 3 {
string.push_str(",");
counter = 0;
}
string.push_str(&digit.to_string());
counter += 1;
}
write!(f, "{}", string.chars().rev().collect::<String>())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bigint(s: &str) -> Bigint {
Bigint::from_str(s).unwrap()
}
#[test]
fn test_display() {
assert_eq!("0", format!("{}", bigint("0")));
assert_eq!("1", format!("{}", bigint("1")));
assert_eq!("10", format!("{}", bigint("10")));
assert_eq!("100", format!("{}", bigint("100")));
assert_eq!("1000", format!("{}", bigint("1000")));
assert_eq!("10000", format!("{}", bigint("10000")));
assert_eq!("100000", format!("{}", bigint("100000")));
assert_eq!("1000000", format!("{}", bigint("1000000")));
assert_eq!("10000000", format!("{}", bigint("10000000")));
assert_eq!("100000000", format!("{}", bigint("100000000")));
assert_eq!("1000000000", format!("{}", bigint("1000000000")));
}
#[test]
fn test_display_delimited() {
assert_eq!("1", format!("{}", bigint("1").delimited()));
assert_eq!("10", format!("{}", bigint("10").delimited()));
assert_eq!("100", format!("{}", bigint("100").delimited()));
assert_eq!("1,000", format!("{}", bigint("1000").delimited()));
assert_eq!("10,000", format!("{}", bigint("10000").delimited()));
assert_eq!("100,000", format!("{}", bigint("100000").delimited()));
assert_eq!("1,000,000", format!("{}", bigint("1000000").delimited()));
assert_eq!("10,000,000", format!("{}", bigint("10000000").delimited()));
assert_eq!("100,000,000", format!("{}", bigint("100000000").delimited()));
assert_eq!("1,000,000,000", format!("{}", bigint("1000000000").delimited()));
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-1x340vv/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.46s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Илиян Йорданов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Илиян Йорданов

#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
use super::*;
fn get_bigint(s: &str) -> Bigint {
Bigint::from_str(s).unwrap()
}
#[test]
fn first_display() {
assert_eq!(format!("{}", get_bigint("100000")), "100000");
assert_eq!(format!("{}", get_bigint("")), "");
assert_eq!(format!("{}", get_bigint("7")), "7");
assert_eq!(format!("{}", get_bigint("98989898081")), "98989898081");
}
#[test]
fn second_display() {
assert_eq!(format!("{}", get_bigint("100000").delimited()), "100,000");
assert_eq!(
format!("{}", get_bigint("100000000").delimited()),
"100,000,000"
);
assert_eq!(format!("{}", get_bigint("").delimited()), "");
assert_eq!(format!("{}", get_bigint("1").delimited()), "1");
assert_eq!(format!("{}", get_bigint("11").delimited()), "11");
assert_eq!(format!("{}", get_bigint("111").delimited()), "111");
assert_eq!(format!("{}", get_bigint("1111").delimited()), "1,111");
assert_eq!(format!("{}", get_bigint("11111").delimited()), "11,111");
assert_eq!(
format!("{}", get_bigint("111111111111111111111111").delimited()),
"111,111,111,111,111,111,111,111"
);
}
}
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::char;
use std::fmt;
fn to_char(dig: &u8) -> char {
char::from_digit(*dig as u32, 10).unwrap()
}
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = String::new();
for d in self.digits.iter() {
s.push(to_char(d));
}
write!(f, "{}", s)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = String::new();
let digits = &self.bigint.digits;
if digits.len() >= 1 {
let mut iterator = digits.iter();
s.push(to_char(iterator.next().unwrap()));
let mut pos = (digits.len() as i8) - 2;
for d in iterator {
if pos % 3 == 2 {
s.push(',');
}
s.push(to_char(d));
pos = pos - 1;
}
}
write!(f, "{}", s)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-13bucdd/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.25s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Християна Панайотова
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Християна Панайотова

use std::str::FromStr;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
impl fmt::Display for Bigint {
/// Форматира число като за хора, по най-простия начин -- просто показва цифрите една след
/// друга:
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint);
/// // => 100000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut num_str = String::new();
for num in self.digits.iter() {
num_str.push_str(&num.to_string());
}
write!(f, "{}", num_str)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
/// Форматира Bigint по малко по-човешки начин -- със запетайки на всеки 3 цифри:
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000
///
/// let bigint = Bigint::from_str("100000000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000,000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut num_str = String::new();
let mut counter = self.bigint.digits.len();
for num in self.bigint.digits.iter() {
counter = counter - 1;
num_str.push_str(&num.to_string());
if counter % 3 == 0 && counter != 0 {
num_str.push_str(",");
}
}
write!(f, "{}", num_str)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-muc1b1/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.93s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Георги Анастасов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Анастасов

use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut number_for_print = String::new();
for number in &self.digits {
number_for_print.push_str(&number.to_string());
}
write!(f, "{}", number_for_print)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut number_for_print = String::new();
let digit_len = self.bigint.digits.len();
for number in 0..digit_len {
if number % 3 == digit_len % 3 && number != digit_len && number != 0 {
number_for_print.push_str(",");
}
number_for_print.push_str(&self.bigint.digits[number].to_string());
}
write!(f, "{}", number_for_print)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-v7wati/solution)
    Finished test [unoptimized + debuginfo] target(s) in 2.00s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Георги Гергинов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Гергинов

use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", stringify_vec_u8(&self.digits))
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.bigint.digits.len() <= 3 {
write!(f, "{}", stringify_vec_u8(&self.bigint.digits))
} else {
let mut dig_count: usize = 0;
let mut stringified_reversed = String::new();
for d in self.bigint.digits.iter().rev() {
stringified_reversed.push((*d + '0' as u8) as char);
dig_count += 1;
if dig_count % 3 == 0 && dig_count != self.bigint.digits.len() {
stringified_reversed.push(',');
}
}
let mut stringified = String::new();
for c in stringified_reversed.chars().rev() {
stringified.push(c);
}
write!(f, "{}", stringified)
}
}
}
pub fn stringify_vec_u8(vec: &Vec<u8>) -> String {
let mut stringified = String::new();
for d in vec {
stringified.push((*d + '0' as u8) as char);
}
stringified
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-d8kgfu/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.29s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Йоана Зелова
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Йоана Зелова

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut number_string = String::from("");
for digit in &self.digits {
number_string.push((('0' as u8) + digit) as char);
}
write!(f, "{}", number_string)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let len = self.bigint.digits.len();
let remain = len % 3;
let mut string: String = String::from("");
for i in 0..remain {
string.push((('0' as u8) + self.bigint.digits[i]) as char);
}
if string.len() != 0 && remain != len {
string.push(',');
}
let mut cnt = 0;
for i in remain..len {
string.push((('0' as u8) + self.bigint.digits[i]) as char);
cnt = cnt + 1;
if cnt == 3 && i != (len - 1) {
cnt = 0;
string.push(',');
}
}
write!(f, "{}", string)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-tcav4l/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.33s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Биляна Йорданова
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Биляна Йорданова

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.digits.is_empty() {
write!(f, "{}", 0)?;
} else {
for n in &self.digits {
write!(f, "{}", n)?;
}
}
Ok(())
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.bigint.digits.is_empty() {
write!(f, "{}", 0)?;
} else {
let len = self.bigint.digits.len();
for n in 0..len {
write!(f, "{}", self.bigint.digits[n])?;
if (len - 1 - n) % 3 == 0 && n != len - 1 {
write!(f, "{}", ',')?;
}
}
}
Ok(())
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-3ngglv/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.32s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Мартин Дацев
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Мартин Дацев

use std::str::FromStr;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
if digits.len() == 0 {
digits.push(0);
}
Ok(Bigint { digits })
}
}
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut s = "".to_owned();
for d in &self.digits {
s.push_str(&d.to_string());
}
write!(f, "{}", s)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = "".to_owned();
for (i, d) in self.bigint.digits.iter().enumerate() {
if (self.bigint.digits.len() - i) % 3 == 0 && i != 0 {
s.push_str(",");
}
s.push_str(&d.to_string());
}
write!(f, "{}", s)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-1ctopl0/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.34s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Гергана Тончева
  • Некоректно
  • 2 успешни тест(а)
  • 1 неуспешни тест(а)
Гергана Тончева

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
use std::fmt::Write; // опционално, може да ви трябва, може би не, зависи какво правите.
impl fmt::Display for Bigint {
/// Форматира число като за хора, по най-простия начин -- просто показва цифрите една след
/// друга:
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint);
/// // => 100000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.digits.iter().fold(Ok(()), |result, digits| {
result.and_then(|_| write!(f, "{}", digits))
})
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
/// Форматира Bigint по малко по-човешки начин -- със запетайки на всеки 3 цифри:
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000
///
/// let bigint = Bigint::from_str("100000000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000,000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut i = 3 - self.bigint.digits.len() % 3;
let mut flag = 0;
self.bigint.digits.iter().fold(Ok(()), |result, digits| {
if i == 3 {
if flag == 1{
print!(",");
}
i = 0;
}
flag = 1;
i = i + 1;
result.and_then(|_| write!(f, "{}", digits))
})
}
}
fn main() {
println!("Hello, world!");
let k = Bigint{
digits: vec![2, 0, 0, 0, 0, 0, 0],
};
println!("{}", k);
let l = Delimited{
bigint: &k,
};
println!("{}", l);
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-dc1y43/solution)
warning: unused import: `std::fmt::Write`
  --> src/lib.rs:27:5
   |
27 | use std::fmt::Write; // опционално, може да ви трябва, може би не, зависи какво правите.
   |     ^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_imports)]` on by default

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

warning: 2 warnings emitted

    Finished test [unoptimized + debuginfo] target(s) in 1.26s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... FAILED
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

failures:

---- solution_test::test_bigint_delimited_display stdout ----
,thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `"1234"`,
 right: `"1,234"`', tests/solution_test.rs:32:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    solution_test::test_bigint_delimited_display

test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out

error: test failed, to rerun pass '--test solution_test'
Владислав Георгиев
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Владислав Георгиев

use std::str::FromStr;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
impl fmt::Display for Bigint {
/// Форматира число като за хора, по най-простия начин -- просто показва цифрите една след
/// друга:
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint);
/// // => 100000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut str_rep: String = "".to_owned();
for digit in self.digits.iter() {
let single_digit: String = digit.to_string();
str_rep.push_str(&single_digit);
}
write!(f, "{}", str_rep)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl<'a> fmt::Display for Delimited<'a> {
/// Форматира Bigint по малко по-човешки начин -- със запетайки на всеки 3 цифри (за да отделим хиляди, милиони и т.н.):
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000
///
/// let bigint = Bigint::from_str("100000000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000,000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut str_rep: String = "".to_owned();
let len = self.bigint.digits.len();
// let groups = len / 3;
let mut group = 0;
for i in (1..len).rev() {
let single_digit: String = self.bigint.digits[i].to_string();
print!("{}\n",i);
group+=1;
str_rep = single_digit + &str_rep;
if (group) % 3 == 0 {
group = 0;
print!("{}", str_rep);
str_rep = ",".to_owned() + &str_rep;
}
}
str_rep = self.bigint.digits[0].to_string() + &str_rep;
write!(f, "{}", str_rep)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-asa0sr/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.39s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Петър Милев
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Петър Милев

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
if(digits.len() == 0) {
digits.push(0);
}
Ok(Bigint { digits })
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
// for printing Bigint
impl std::fmt::Display for Bigint {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "{}", self.digits.iter().map(|el| el.to_string()).collect::<String>())
}
}
// for printing delimited Bigint
impl<'a> std::fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut count = 0;
write!(f, "{}",
self.bigint.digits
.iter()
.rev()
.map(|el| { count += 1; (if count == 4 { count = 1; "," } else { "" }).to_string() + &el.to_string() })
.collect::<String>().chars().rev().collect::<String>())
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-1liaf62/solution)
warning: unnecessary parentheses around `if` condition
  --> src/lib.rs:22:11
   |
22 |         if(digits.len() == 0) {
   |           ^^^^^^^^^^^^^^^^^^^ help: remove these parentheses
   |
   = note: `#[warn(unused_parens)]` on by default

warning: 1 warning emitted

    Finished test [unoptimized + debuginfo] target(s) in 1.58s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Лъчезар Младенов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Лъчезар Младенов

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
impl fmt::Display for Bigint {
/// Форматира число като за хора, по най-простия начин -- просто показва цифрите една след
/// друга:
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint);
/// // => 100000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let vec_str: String = self.digits.iter().map(ToString::to_string).collect();
write!(f, "{}", vec_str)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
/// Форматира Bigint по малко по-човешки начин -- със запетайки на всеки 3 цифри (за да отделим хиляди, милиони и т.н.):
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000
///
/// let bigint = Bigint::from_str("100000000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000,000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut vec_str: String = (*self.bigint).digits.iter().map(ToString::to_string).collect();
let mut index = vec_str.len() as i64 - 3;
while index > 0 {
vec_str.insert(index as usize, ',');
index -= 3;
}
write!(f, "{}", vec_str)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-1knd7j2/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.32s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Тихомир Каменов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Тихомир Каменов

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.digits.is_empty() {
return write!(f, "{}", "0");
}
let mut s = String::new();
for i in self.digits.iter() {
s += &i.to_string();
}
write!(f, "{}", s)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.bigint.digits.is_empty() {
return write!(f, "{}", "0");
}
let mut s = String::new();
// used to specify the location of the first comma in the output
let comma_offset = self.bigint.digits.len() % 3;
for i in 0..self.bigint.digits.len() {
if i > 0 && i >= comma_offset && (i - comma_offset) % 3 == 0 {
s += ",";
}
s += &self.bigint.digits[i].to_string();
}
write!(f, "{}", s)
}
}
#[cfg(test)]
mod tests {
use super::Bigint;
use std::str::FromStr;
#[test]
fn test_fmt(){
assert_eq!(format!("{}", Bigint::from_str("").unwrap()), "0");
assert_eq!(format!("{}", Bigint::from_str("1000").unwrap()), "1000");
assert_eq!(format!("{}", Bigint::from_str("123").unwrap()), "123");
}
#[test]
fn test_fmt_delimited() {
assert_eq!(format!("{}", Bigint::from_str("").unwrap().delimited()), "0");
assert_eq!(format!("{}", Bigint::from_str("10000000000").unwrap().delimited()), "10,000,000,000");
assert_eq!(format!("{}", Bigint::from_str("500000").unwrap().delimited()), "500,000");
assert_eq!(format!("{}", Bigint::from_str("43562").unwrap().delimited()), "43,562");
assert_eq!(format!("{}", Bigint::from_str("1000").unwrap().delimited()), "1,000");
assert_eq!(format!("{}", Bigint::from_str("123").unwrap().delimited()), "123");
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-293uxf/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.37s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Георги Катевски
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Георги Катевски

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
use std::fmt::Write; // опционално, може да ви трябва, може би не, зависи какво правите.
impl fmt::Display for Bigint {
/// Форматира число като за хора, по най-простия начин -- просто показва цифрите една след
/// друга:
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint);
/// // => 100000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut number = String::new();
for num in &self.digits[0..self.digits.len() - 1] {
number.push_str(&num.to_string());
}
number.push_str(&self.digits[self.digits.len() - 1].to_string());
write!(f, "{}", number)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
/// Форматира Bigint по малко по-човешки начин -- със запетайки на всеки 3 цифри:
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000
///
/// let bigint = Bigint::from_str("100000000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000,000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut number = String::new();
let mut count=0;
for num in &self.bigint.digits[0..self.bigint.digits.len() - 1] {
number.push_str(&num.to_string());
count+=1;
if(self.bigint.digits.len()%3==0 && count%3==0 && count!=0)
{
number.push_str(",");
}
if(self.bigint.digits.len()%3==2 && count%3==2 && count!=0)
{
number.push_str(",");
}
if(self.bigint.digits.len()%3==1 && count%3==1 && count!=0)
{
number.push_str(",");
}
}
number.push_str(&self.bigint.digits[self.bigint.digits.len() - 1].to_string());
write!(f, "{}", number)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-zjsik4/solution)
warning: unnecessary parentheses around `if` condition
  --> src/lib.rs:80:14
   |
80 |            if(self.bigint.digits.len()%3==0 && count%3==0 && count!=0)
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove these parentheses
   |
   = note: `#[warn(unused_parens)]` on by default

warning: unnecessary parentheses around `if` condition
  --> src/lib.rs:84:14
   |
84 |            if(self.bigint.digits.len()%3==2 && count%3==2 && count!=0)
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove these parentheses

warning: unnecessary parentheses around `if` condition
  --> src/lib.rs:88:14
   |
88 |            if(self.bigint.digits.len()%3==1 && count%3==1 && count!=0)
   |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove these parentheses

warning: unused import: `std::fmt::Write`
  --> src/lib.rs:29:5
   |
29 | use std::fmt::Write; // опционално, може да ви трябва, може би не, зависи какво правите.
   |     ^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_imports)]` on by default

warning: 4 warnings emitted

    Finished test [unoptimized + debuginfo] target(s) in 1.34s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Ася Русанова
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Ася Русанова

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for element in self.digits.iter() {
write!(f, "{}", element)?;
}
Ok(())
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut delimeted_number: String = String::new();
let length: usize = self.bigint.digits.len();
for i in 0..length {
delimeted_number.push_str(&self.bigint.digits[i].to_string());
if length % 3 == 0 && i % 3 == 2 && i != length - 1 {
delimeted_number.push_str(",");
}
else if length % 3 == 1 && i % 3 == 0 && i != length - 1 {
delimeted_number.push_str(",");
}
else if length % 3 == 2 && i % 3 == 1 && i != length - 1 {
delimeted_number.push_str(",");
}
}
write!(f, "{}", delimeted_number)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
#[test]
fn test_basic_display() {
assert_eq!(format!("{}", Bigint::from_str("100000").unwrap()), "100000");
assert_eq!(format!("{}", Bigint::from_str("943820032").unwrap()), "943820032");
}
#[test]
fn test_delimeted_display_with_length_le_three() {
assert_eq!(format!("{}", Bigint::from_str("1").unwrap().delimited()), "1");
assert_eq!(format!("{}", Bigint::from_str("23").unwrap().delimited()), "23");
assert_eq!(format!("{}", Bigint::from_str("666").unwrap().delimited()), "666");
}
#[test]
fn test_delimeted_display_with_length_divisible_by_three() {
//length mod 3 == 0
assert_eq!(format!("{}", Bigint::from_str("100000").unwrap().delimited()), "100,000");
assert_eq!(format!("{}", Bigint::from_str("100000000").unwrap().delimited()), "100,000,000");
assert_eq!(format!("{}", Bigint::from_str("999432156231").unwrap().delimited()), "999,432,156,231");
}
#[test]
fn test_delimeted_display_with_length_with_remainder_one() {
//length mod 3 == 1
assert_eq!(format!("{}", Bigint::from_str("3000").unwrap().delimited()), "3,000");
assert_eq!(format!("{}", Bigint::from_str("3900760").unwrap().delimited()), "3,900,760");
}
#[test]
fn test_delimeted_display_with_length_with_remainder_two() {
//length mod 3 == 2
assert_eq!(format!("{}", Bigint::from_str("10000").unwrap().delimited()), "10,000");
assert_eq!(format!("{}", Bigint::from_str("19328765").unwrap().delimited()), "19,328,765");
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-1oujiat/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.41s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Костадин Пеков
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Костадин Пеков

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
//use std::fmt::Write; // опционално, може да ви трябва, може би не, зависи какво правите.
impl fmt::Display for Bigint {
/// Форматира число като за хора, по най-простия начин -- просто показва цифрите една след
/// друга:
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint);
/// // => 100000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = String::new();
for i in &self.digits
{
s.push_str(&i.to_string());
}
write!(f, "{}", s)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
/// Форматира Bigint по малко по-човешки начин -- със запетайки на всеки 3 цифри (за да отделим хиляди, милиони и т.н.):
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000
///
/// let bigint = Bigint::from_str("100000000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000,000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = String::new();
let mut count = self.bigint.digits.len();
for i in &self.bigint.digits
{
s.push_str(&i.to_string());
count-=1;
if(count%3 == 0 && count != 0)
{
s.push(',');
}
}
write!(f, "{}", s)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-f8r2ex/solution)
warning: unnecessary parentheses around `if` condition
  --> src/lib.rs:76:12
   |
76 |             if(count%3 == 0 && count != 0)
   |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: remove these parentheses
   |
   = note: `#[warn(unused_parens)]` on by default

warning: 1 warning emitted

    Finished test [unoptimized + debuginfo] target(s) in 1.27s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Деян Горанов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Деян Горанов

use std::str::FromStr;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
impl fmt::Display for Bigint {
/// Форматира число като за хора, по най-простия начин --
/// просто показва цифрите една след друга:
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint);
/// // => 100000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let output =
self.digits.iter()
.map(|d| d.to_string())
.collect::<String>();
write!(f, "{}", output)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl<'a> fmt::Display for Delimited<'a> {
/// Форматира Bigint по малко по-човешки начин --
/// със запетайки на всеки 3 цифри (за да отделим хиляди, милиони и т.н.):
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000
///
/// let bigint = Bigint::from_str("100000000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000,000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let output =
self.bigint.digits
.rchunks(3)
.rev()
.map(|ds|
ds.iter()
.map(|d| d.to_string())
.collect::<String>()
)
.collect::<Vec<String>>()
.join(",");
write!(f, "{}", output)
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! make_tests {
(
$func:expr,
[$( $name:ident($($args:tt),* $(,)?) ),* $(,)?]
) => {
$(
#[test]
fn $name() {
$func($($args),*);
}
)*
}
}
make_tests!(
|n_str| {
let n = Bigint::from_str(n_str).unwrap();
assert_eq!(n_str, format!("{}", n))
},
[ displays_0("0")
, displays_10("10")
, displays_123("123")
, displays_5432("5432")
, displays_156234("156234")
, displays_32156234("32156234")
, displays_100000000("100000000")
, displays_1000000000000000000("1000000000000000000")
]
);
make_tests!(
|input, expected| {
let n = Bigint::from_str(input).unwrap();
assert_eq!(expected, format!("{}", n.delimited()))
},
[ displays_delimited_0(
"0",
"0",
)
, displays_delimited_10(
"10",
"10",
)
, displays_delimited_123(
"123",
"123",
)
, displays_delimited_5432(
"5432",
"5,432",
)
, displays_delimited_156234(
"156234",
"156,234",
)
, displays_delimited_32156234(
"32156234",
"32,156,234",
)
, displays_delimited_100000000(
"100000000",
"100,000,000",
)
, displays_delimited_1000000000000000000(
"1000000000000000000",
"1,000,000,000,000,000,000",
)
]
);
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-blueo4/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.52s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Пламен Николов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Пламен Николов

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl Bigint {
fn validate_digits(digits: &Vec<u8>) {
if digits.is_empty() {
panic!("'digits' must have at least 1 element");
}
for &digit in digits {
if digit > 9_u8 {
panic!("digits must be numbers between 0 and 9 inclusive");
}
}
}
fn normalize_digits(digits: &mut Vec<u8>) {
while let Some(0) = digits.last() {
digits.pop();
}
if digits.is_empty() {
digits.push(0);
}
}
fn from_vector(digits: Vec<u8>) -> Self {
let mut digits = digits;
Bigint::validate_digits(&digits);
Bigint::normalize_digits(&mut digits);
Bigint { digits }
}
pub fn is_zero(&self) -> bool {
return self.digits.len() == 1 && self.digits[0] == 0
}
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits: Vec<u8> = vec![];
for ch in s.chars() {
if ch >= '0' && ch <= '9' {
digits.push(ch.to_digit(10).unwrap() as u8);
} else {
return Err("Invalid input!");
}
}
if digits.is_empty() {
digits.push(0);
}
digits.reverse();
return Ok(Self::from_vector(digits));
}
}
use std::fmt;
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut result = self.digits.clone();
result.reverse();
let result: String = result.into_iter().map(|digit| digit.to_string()).collect();
write!(f, "{}", result)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut result: Vec<String> = Vec::new();
let mut counter = 0;
for &digit in &self.bigint.digits {
if counter == 3 {
result.push(String::from(","));
counter = 0;
}
result.push(digit.to_string());
counter += 1;
}
result.reverse();
let result: String = result.into_iter().collect();
write!(f, "{}", result)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-fiyn26/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.47s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Александър Димитров
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Александър Димитров

use std::str::FromStr;
use std::fmt;
// Declaration of BigInt given for the task
#[derive( Debug, Clone, PartialEq, Eq )]
pub struct Bigint {
pub digits: Vec<u8>,
}
// Implementation of BigInt given for the task
impl FromStr for Bigint {
type Err = &'static str;
fn from_str( s: &str ) -> Result< Self, Self::Err > {
let mut digits = Vec::with_capacity( s.len() );
for c in s.chars() {
if let Some( digit ) = c.to_digit( 10 ) {
digits.push( digit as u8 );
} else {
return Err( "Invalid input!" );
}
}
Ok( Bigint { digits } )
}
}
impl fmt::Display for Bigint {
fn fmt( &self, f: &mut fmt::Formatter ) -> fmt::Result {
for num in self.digits.iter() {
let res = write!( f, "{}", num );
if res.is_err() {
return res;
}
}
Ok(())
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited( &self ) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt( &self, f: &mut fmt::Formatter ) -> fmt::Result {
for ( i, num ) in self.bigint.digits.iter().enumerate() {
let len = self.bigint.digits.len();
let ind = len - 1 - i;
let del = ind % 3 == 0 && i != len - 1;
let res;
if del {
res = write!( f, "{},", num );
} else {
res = write!( f, "{}", num );
}
if res.is_err() {
return res;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn bi( s: &str ) -> Bigint {
Bigint::from_str( s ).unwrap()
}
fn assert_normal( s: &str ) {
assert_eq!( format!( "{}", bi( s ) ), s );
}
fn assert_delimited( s: &str, exp: &str ) {
assert_eq!( format!( "{}", bi( s ).delimited() ), exp );
}
#[test]
fn test_normal() {
assert_normal( "0" );
assert_normal( "1" );
assert_normal( "10" );
assert_normal( "100" );
assert_normal( "1000" );
assert_normal( "10000" );
assert_normal( "100000" );
assert_normal( "1000000" );
assert_normal( "10000000" );
assert_normal( "100000000" );
assert_normal( "1000000000" );
assert_normal( "10000000000" );
assert_normal( "100000000000" );
assert_normal( "1000000000000" );
assert_normal( "10000000000000" );
assert_normal( "100000000000000" );
assert_normal( "1000000000000000" );
assert_normal( "10000000000000000" );
assert_normal( "100000000000000000" );
assert_normal( "1000000000000000000" );
assert_normal( "10000000000000000000" );
assert_normal( "100000000000000000000" );
assert_normal( "1000000000000000000000" );
}
#[test]
fn test_delimited() {
assert_delimited( "0", "0" );
assert_delimited( "1", "1" );
assert_delimited( "10", "10" );
assert_delimited( "100", "100" );
assert_delimited( "1000", "1,000" );
assert_delimited( "10000", "10,000" );
assert_delimited( "100000", "100,000" );
assert_delimited( "1000000", "1,000,000" );
assert_delimited( "10000000", "10,000,000" );
assert_delimited( "100000000", "100,000,000" );
assert_delimited( "1000000000", "1,000,000,000" );
assert_delimited( "10000000000", "10,000,000,000" );
assert_delimited( "100000000000", "100,000,000,000" );
assert_delimited( "1000000000000", "1,000,000,000,000" );
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-1rtzf/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.22s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Мартин Великов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Мартин Великов

fn main() {
}
use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut buffer = String::new();
for digit in &self.digits {
buffer.push_str(&digit.to_string());
}
write!(f,"{}",buffer)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut temp_vec : Vec<u8> = self.bigint.digits.clone();
temp_vec.reverse();
let mut buffer = String::new();
let mut counter=0;
let temp_vec_length = temp_vec.len();
for digit in &temp_vec {
counter = counter + 1;
buffer.push_str(&digit.to_string());
if counter % 3 == 0 && temp_vec_length > 0 && counter < temp_vec_length {
buffer.push_str(",");
}
}
write!(f,"{}",buffer.chars().rev().collect::<String>())
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-cvzbmg/solution)
warning: function is never used: `main`
 --> src/lib.rs:1:4
  |
1 | fn main() {
  |    ^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: 1 warning emitted

    Finished test [unoptimized + debuginfo] target(s) in 1.33s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Бетина Христова
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Бетина Христова

use std::str::FromStr;
use std::fmt;
use std::fmt::Write;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Ok(for c in &self.digits {
write!(f, "{}", c);
})
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let digits_count = &self.bigint.digits.len();
let mut ctr = 0_usize;
Ok(for c in &self.bigint.digits {
write!(f, "{}", c);
if (digits_count - ctr + 2) % 3 == 0 && (ctr + 1) < *digits_count {
write!(f, ",");
}
ctr = ctr + 1;
})
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-tc8b8i/solution)
warning: unused import: `std::fmt::Write`
 --> src/lib.rs:3:5
  |
3 | use std::fmt::Write;
  |     ^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: unused `std::result::Result` that must be used
  --> src/lib.rs:31:13
   |
31 |             write!(f, "{}", c);
   |             ^^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_must_use)]` on by default
   = note: this `Result` may be an `Err` variant, which should be handled
   = note: this warning originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

warning: unused `std::result::Result` that must be used
  --> src/lib.rs:52:13
   |
52 |             write!(f, "{}", c);
   |             ^^^^^^^^^^^^^^^^^^^
   |
   = note: this `Result` may be an `Err` variant, which should be handled
   = note: this warning originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

warning: unused `std::result::Result` that must be used
  --> src/lib.rs:54:17
   |
54 |                 write!(f, ",");
   |                 ^^^^^^^^^^^^^^^
   |
   = note: this `Result` may be an `Err` variant, which should be handled
   = note: this warning originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

warning: 4 warnings emitted

    Finished test [unoptimized + debuginfo] target(s) in 1.28s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Васил Папукчиев
  • Некоректно
  • 2 успешни тест(а)
  • 1 неуспешни тест(а)
Васил Папукчиев

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
use std::fmt::Write; // опционално, може да ви трябва, може би не, зависи какво правите.
impl fmt::Display for Bigint {
/// Форматира число като за хора, по най-простия начин -- просто показва цифрите една след
/// друга:
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint);
/// // => 100000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut vector_str = String::new();
for digit in &self.digits {
vector_str.push_str(&digit.to_string());
}
write!(f, "{}", vector_str)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
/// Форматира Bigint по малко по-човешки начин -- със запетайки на всеки 3 цифри (за да отделим хиляди, милиони и т.н.):
///
/// let bigint = Bigint::from_str("100000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000
///
/// let bigint = Bigint::from_str("100000000").unwrap();
/// println!("{}", bigint.delimited());
/// // => 100,000,000
///
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut comma_separated = String::new();
let count = self.bigint.digits.len();
let first_comma_position = count % 3;
let mut is_first_comma_added;
is_first_comma_added = false;
let mut current_position: i32 = 0;
for i in 0..count {
let digit = &self.bigint.digits[i];
comma_separated.push_str(&digit.to_string());
if !is_first_comma_added && current_position + 1 == (first_comma_position as i32) {
comma_separated.push_str(",");
is_first_comma_added = true;
current_position = -1;
}
else if current_position + 1 == 3 && i + 1 != count {
comma_separated.push_str(",");
}
current_position = current_position + 1;
}
write!(f, "{}", comma_separated)
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-19suymk/solution)
warning: unused import: `std::fmt::Write`
  --> src/lib.rs:27:5
   |
27 | use std::fmt::Write; // опционално, може да ви трябва, може би не, зависи какво правите.
   |     ^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_imports)]` on by default

warning: 1 warning emitted

    Finished test [unoptimized + debuginfo] target(s) in 1.37s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... FAILED
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

failures:

---- solution_test::test_bigint_delimited_display stdout ----
thread 'main' panicked at 'assertion failed: `(left == right)`
  left: `"12,"`,
 right: `"12"`', tests/solution_test.rs:30:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace


failures:
    solution_test::test_bigint_delimited_display

test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out

error: test failed, to rerun pass '--test solution_test'
Даниел Стоянов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Даниел Стоянов

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
use std::fmt::Write; // опционално, може да ви трябва, може би не, зависи какво правите.
fn filter_digits(digits: &Vec<u8>) -> Vec<u8> {
let mut numb = Vec::new();
let mut it = digits.iter();
let mut temp = it.next();
while temp== Some(&0) {
temp=it.next();
}
if temp == None {
numb.push(0);
}
else {
numb.push(*temp.unwrap());
}
for val in it {
numb.push(*val);
}
if numb.len() == 0 {
numb.push(0);
numb
}
else {
numb
}
}
fn is_zero(digits: &Vec<u8>) -> bool {
let vec = digits;
let vec = filter_digits(vec);
(vec.len() == 1) && (vec[0] == 0)
}
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match is_zero(&self.digits) {
true => write!(f, "{}", 0),
_ => {
let temp = filter_digits(&self.digits);
let it = temp.iter();
for val in it {
write!(f, "{}", *val);
}
write!(f, "{}", "")
}
}
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match is_zero(&self.bigint.digits) {
true => write!(f, "{}", 0),
_ => {
let temp = filter_digits(&self.bigint.digits);
let mut counter: i8 = (temp.len() as i8) % 3;
let mut flag = counter== 0;
let it = temp.iter();
for val in it {
if flag == true {
write!(f, "{}", *val);
flag = false;
}
else if counter % 3 == 0 {
write!(f, ",{}", *val);
}
else {
write!(f, "{}", *val);
}
counter = counter - 1;
}
write!(f, "{}", "")
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_display() {
let bigint1 = Bigint::from_str("1").unwrap();
let bigint2 = Bigint::from_str("12").unwrap();
let bigint3 = Bigint::from_str("123").unwrap();
let bigint4 = Bigint::from_str("1234").unwrap();
let bigint5 = Bigint::from_str("12345").unwrap();
let bigint6 = Bigint::from_str("123456").unwrap();
let bigint7 = Bigint::from_str("1234567").unwrap();
let bigint8 = Bigint::from_str("12345678").unwrap();
let bigint9 = Bigint::from_str("123456789").unwrap();
let bigint10 = Bigint::from_str("12345678910").unwrap();
let bigint0 = Bigint::from_str("01000").unwrap();
assert_eq!(format!("{}", bigint1), "1");
assert_eq!(format!("{}", bigint2), "12");
assert_eq!(format!("{}", bigint3), "123");
assert_eq!(format!("{}", bigint4), "1234");
assert_eq!(format!("{}", bigint5), "12345");
assert_eq!(format!("{}", bigint6), "123456");
assert_eq!(format!("{}", bigint7), "1234567");
assert_eq!(format!("{}", bigint8), "12345678");
assert_eq!(format!("{}", bigint9), "123456789");
assert_eq!(format!("{}", bigint10), "12345678910");
assert_eq!(format!("{}", bigint0), "1000");
}
#[test]
fn test_delimited() {
let bigint1 = Bigint::from_str("1").unwrap();
let bigint2 = Bigint::from_str("12").unwrap();
let bigint3 = Bigint::from_str("123").unwrap();
let bigint4 = Bigint::from_str("1234").unwrap();
let bigint5 = Bigint::from_str("12345").unwrap();
let bigint6 = Bigint::from_str("123456").unwrap();
let bigint7 = Bigint::from_str("1234567").unwrap();
let bigint8 = Bigint::from_str("12345678").unwrap();
let bigint9 = Bigint::from_str("123456789").unwrap();
let bigint10 = Bigint::from_str("12345678910").unwrap();
let bigint0 = Bigint::from_str("01000").unwrap();
assert_eq!(format!("{}", bigint1.delimited()), "1");
assert_eq!(format!("{}", bigint2.delimited()), "12");
assert_eq!(format!("{}", bigint3.delimited()), "123");
assert_eq!(format!("{}", bigint4.delimited()), "1,234");
assert_eq!(format!("{}", bigint5.delimited()), "12,345");
assert_eq!(format!("{}", bigint6.delimited()), "123,456");
assert_eq!(format!("{}", bigint7.delimited()), "1,234,567");
assert_eq!(format!("{}", bigint8.delimited()), "12,345,678");
assert_eq!(format!("{}", bigint9.delimited()), "123,456,789");
assert_eq!(format!("{}", bigint10.delimited()), "12,345,678,910");
assert_eq!(format!("{}", bigint0.delimited()), "1,000");
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-1vhelek/solution)
warning: unused import: `std::fmt::Write`
  --> src/lib.rs:26:5
   |
26 | use std::fmt::Write; // опционално, може да ви трябва, може би не, зависи какво правите.
   |     ^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_imports)]` on by default

warning: unused `std::result::Result` that must be used
  --> src/lib.rs:67:21
   |
67 |                     write!(f, "{}", *val);
   |                     ^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: `#[warn(unused_must_use)]` on by default
   = note: this `Result` may be an `Err` variant, which should be handled
   = note: this warning originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

warning: unused `std::result::Result` that must be used
  --> src/lib.rs:95:25
   |
95 |                         write!(f, "{}", *val);
   |                         ^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: this `Result` may be an `Err` variant, which should be handled
   = note: this warning originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

warning: unused `std::result::Result` that must be used
  --> src/lib.rs:99:25
   |
99 |                         write!(f, ",{}", *val);
   |                         ^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: this `Result` may be an `Err` variant, which should be handled
   = note: this warning originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

warning: unused `std::result::Result` that must be used
   --> src/lib.rs:102:25
    |
102 |                         write!(f, "{}", *val);
    |                         ^^^^^^^^^^^^^^^^^^^^^^
    |
    = note: this `Result` may be an `Err` variant, which should be handled
    = note: this warning originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

warning: 5 warnings emitted

    Finished test [unoptimized + debuginfo] target(s) in 1.32s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Антонина Ускова
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Антонина Ускова

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for digit in self.digits.iter() {
write!(f, "{}", digit)?;
}
Ok(())
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let len = self.bigint.digits.len();
for i in 0..len {
write!(f, "{}", self.bigint.digits[i])?;
if (len - (i + 1)) % 3 == 0 && i != (len - 1) {
write!(f, ",")?;
}
}
Ok(())
}
}
#[cfg(test)]
mod test {
use super::{Bigint, FromStr};
#[test]
fn test_zero() {
let bigint = Bigint::from_str("0").unwrap();
assert_eq!(format!("{}", bigint), String::from("0"));
assert_eq!(format!("{}", bigint.delimited()), String::from("0"));
}
#[test]
fn test_digits_div_by_and_more_than_3() {
let mut num_str = "100000";
let mut bigint = Bigint::from_str(num_str).unwrap();
assert_eq!(format!("{}", bigint), String::from(num_str));
assert_eq!(format!("{}", bigint.delimited()), String::from("100,000"));
num_str = "100000000";
bigint = Bigint::from_str(num_str).unwrap();
assert_eq!(format!("{}", bigint), String::from(num_str));
assert_eq!(format!("{}", bigint.delimited()), String::from("100,000,000"));
}
#[test]
fn test_1_digit_diff_than_zero() {
let bigint = Bigint::from_str("1").unwrap();
assert_eq!(format!("{}", bigint), String::from("1"));
assert_eq!(format!("{}", bigint.delimited()), String::from("1"));
}
#[test]
fn test_2_digits() {
let bigint = Bigint::from_str("10").unwrap();
assert_eq!(format!("{}", bigint), String::from("10"));
assert_eq!(format!("{}", bigint.delimited()), String::from("10"));
}
#[test]
fn test_3_digits() {
let bigint = Bigint::from_str("100").unwrap();
assert_eq!(format!("{}", bigint), String::from("100"));
assert_eq!(format!("{}", bigint.delimited()), String::from("100"));
}
#[test]
fn test_4_digits() {
let bigint = Bigint::from_str("1000").unwrap();
assert_eq!(format!("{}", bigint), String::from("1000"));
assert_eq!(format!("{}", bigint.delimited()), String::from("1,000"));
}
#[test]
fn test_5_digits() {
let bigint = Bigint::from_str("10000").unwrap();
assert_eq!(format!("{}", bigint), String::from("10000"));
assert_eq!(format!("{}", bigint.delimited()), String::from("10,000"));
}
}
Compiling solution v0.1.0 (/tmp/d20201216-2274206-s9wu2v/solution)
    Finished test [unoptimized + debuginfo] target(s) in 1.26s
     Running target/debug/deps/solution_test-589a43f0f4b10ca3

running 3 tests
test solution_test::test_bigint_delimited_display ... ok
test solution_test::test_bigint_display ... ok
test solution_test::test_bigint_parsing ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Ивайло Иванов
  • Коректно
  • 3 успешни тест(а)
  • 0 неуспешни тест(а)
Ивайло Иванов

use std::str::FromStr;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bigint {
pub digits: Vec<u8>,
}
impl FromStr for Bigint {
type Err = &'static str;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let mut digits = Vec::with_capacity(s.len());
for c in s.chars() {
if let Some(digit) = c.to_digit(10) {
digits.push(digit as u8);
} else {
return Err("Invalid input!");
}
}
Ok(Bigint { digits })
}
}
use std::fmt;
use std::str;
impl fmt::Display for Bigint {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let result = self.digits.iter().map(|i|i.to_string()).collect::<String>();
write!(f, "{}", result)
}
}
pub struct Delimited<'a> {
bigint: &'a Bigint,
}
impl Bigint {
pub fn delimited(&self) -> Delimited {
Delimited { bigint: self }
}
}
impl<'a> fmt::Display for Delimited<'a> {