Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- mod upc_code {
- use std::io;
- #[allow(dead_code)]
- pub struct UPCCode {
- pub code: Vec<i8>,
- pub check_digit: i8,
- }
- impl UPCCode {
- #[allow(dead_code)]
- fn validate_nums(&self) -> bool {
- for code in &self.code {
- if !is_1_digit(*code) {
- return false;
- }
- }
- is_1_digit(self.check_digit)
- }
- fn add_odd_total(&self) -> (i8, i8) {
- let mut result: (i8, i8) = (0, 0);
- for code in &self.code {
- if code % 2 == 0 {
- result.0 += code;
- } else {
- result.1 += code;
- }
- }
- result
- }
- #[allow(dead_code)]
- pub fn check_code(&self) -> Result<bool, io::Error> {
- if !&self.validate_nums() {
- return Err(io::Error::new(
- io::ErrorKind::Other,
- "A number used isn\'t 1 digit!",
- ));
- }
- let mut total: i8 = 0;
- let (even_nums, odd_nums): &(i8, i8) = &self.add_odd_total();
- total += ((odd_nums * 3) + even_nums) % 10;
- if (total == 0 && self.check_digit == 0) || (10 - total == self.check_digit) {
- return Ok(true);
- }
- Ok(false)
- }
- }
- #[allow(dead_code)]
- fn is_1_digit(num: i8) -> bool {
- if num < 0 || num > 9 {
- return false;
- }
- true
- }
- }
- fn main() {
- println!("Hello");
- let code: Vec<i8> = vec![2, 3, 4, 5, 5, 6, 6, 3, 2, 1];
- let check_digit: i8 = 3;
- let my_upc = upc_code::UPCCode {
- code: code,
- check_digit: check_digit,
- };
- println!("Result: {}", my_upc.check_code().unwrap());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement