Created
December 19, 2018 05:50
-
-
Save Taywee/d5c39192b51f487b17a0843dd2d98568 to your computer and use it in GitHub Desktop.
Daily Programmer 370 Easy first shot solution.
This file contains 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
// Given a slice of upc digits, return the checksum | |
fn upc_raw(input: &[u8]) -> u8 { | |
let mut code = Vec::from(input); | |
while code.len() < 11 { | |
code.insert(0, 0); | |
} | |
if code.len() > 11 { | |
code.resize(11, 0); | |
} | |
let even: u8 = code.iter().step_by(2).sum(); | |
let odd: u8 = code.iter().skip(1).step_by(2).sum(); | |
(10 - ((even * 3 + odd) % 10)) % 10 | |
} | |
// Given a upc string, return the checksum | |
fn upc_str(input: &str) -> u8 { | |
let raw: Vec<u8> = input.chars().map(|i| i.to_digit(10).unwrap() as u8).collect(); | |
upc_raw(&raw) | |
} | |
// Given a upc string as a single number, return the checksum | |
fn upc(input: u64) -> u8 { | |
upc_str(&input.to_string()) | |
} | |
fn main() { | |
for &input in &[4210000526, 3600029145, 12345678910, 1234567] { | |
println!("upc({}) => {}", input, upc(input)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment