Last active
January 31, 2018 09:41
-
-
Save AnthonyMikh/bf7b5eedb707a27608853196f3593916 to your computer and use it in GitHub Desktop.
Решение задачи №66 от Unilecs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate num; //В Rust нет нативной длинной арифметики | |
#[derive(Debug, PartialEq)] | |
enum POTError<'a> { | |
NoCoincide(&'a str), | |
EmptyString, | |
PowerIsTooLarge, | |
} | |
type BoundType = u32; //Если впоследствие верхняя граница поменяется, | |
const BOUND: BoundType = 1000; //изменения надо будет внести только сюда | |
fn find_power(line: &str) -> Result<BoundType, POTError> { | |
if line.is_empty() { | |
return Err(POTError::EmptyString); | |
} | |
use num::{FromPrimitive, BigUint}; | |
let mut rest = line; | |
let big2: BigUint = FromPrimitive::from_usize(2).unwrap(); | |
let mut acc: BigUint = FromPrimitive::from_usize(1).unwrap(); | |
let mut power: BoundType = 0; | |
while !rest.is_empty() { | |
power += 1; | |
if power > BOUND { | |
return Err(POTError::PowerIsTooLarge) | |
} | |
acc *= &big2; | |
let str_power = acc.to_string(); | |
if !rest.starts_with(&str_power) { | |
return Err(POTError::NoCoincide(rest)); | |
} | |
let (_, unprocessed) = rest.split_at(str_power.len()); | |
rest = unprocessed; | |
} | |
Ok(power) | |
} | |
#[test] | |
fn do_tests() { | |
use POTError::*; | |
assert_eq!(find_power("24816"), Ok(4)); | |
assert_eq!(find_power("248163264128"), Ok(7)); | |
assert_eq!( | |
find_power("24816lol not number"), | |
Err(NoCoincide("lol not number")) | |
); | |
assert_eq!(find_power(""), Err(EmptyString)); | |
assert_eq!(find_power(&really_big_test_case()), Err(PowerIsTooLarge)); | |
} | |
fn really_big_test_case() -> String { | |
use num::{FromPrimitive, BigUint}; | |
let mut buffer = String::new(); | |
let big2: BigUint = FromPrimitive::from_usize(2).unwrap(); | |
let mut acc: BigUint = FromPrimitive::from_usize(1).unwrap(); | |
for _ in 1..(BOUND+2) { | |
acc *= &big2; | |
buffer += &acc.to_string(); | |
} | |
buffer | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
playground: https://play.rust-lang.org/?gist=2bb3f5ceaf91ff9cb4c1a83884210f1e&version=stable