Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.88 KB | None | 0 0
  1. mod upc_code {
  2.     use std::io;
  3.  
  4.     #[allow(dead_code)]
  5.     pub struct UPCCode {
  6.         pub code: Vec<i8>,
  7.         pub check_digit: i8,
  8.     }
  9.  
  10.     impl UPCCode {
  11.         #[allow(dead_code)]
  12.         fn validate_nums(&self) -> bool {
  13.             for code in &self.code {
  14.                 if !is_1_digit(*code) {
  15.                     return false;
  16.                 }
  17.             }
  18.  
  19.             is_1_digit(self.check_digit)
  20.         }
  21.  
  22.         fn add_odd_total(&self) -> (i8, i8) {
  23.             let mut result: (i8, i8) = (0, 0);
  24.  
  25.             for code in &self.code {
  26.                 if code % 2 == 0 {
  27.                     result.0 += code;
  28.                 } else {
  29.                     result.1 += code;
  30.                 }
  31.             }
  32.  
  33.             result
  34.         }
  35.  
  36.         #[allow(dead_code)]
  37.         pub fn check_code(&self) -> Result<bool, io::Error> {
  38.             if !&self.validate_nums() {
  39.                 return Err(io::Error::new(
  40.                     io::ErrorKind::Other,
  41.                     "A number used isn\'t 1 digit!",
  42.                 ));
  43.             }
  44.  
  45.             let mut total: i8 = 0;
  46.             let (even_nums, odd_nums): &(i8, i8) = &self.add_odd_total();
  47.  
  48.             total += ((odd_nums * 3) + even_nums) % 10;
  49.  
  50.             if (total == 0 && self.check_digit == 0) || (10 - total == self.check_digit) {
  51.                 return Ok(true);
  52.             }
  53.  
  54.             Ok(false)
  55.         }
  56.     }
  57.  
  58.     #[allow(dead_code)]
  59.     fn is_1_digit(num: i8) -> bool {
  60.         if num < 0 || num > 9 {
  61.             return false;
  62.         }
  63.  
  64.         true
  65.     }
  66. }
  67.  
  68. fn main() {
  69.     println!("Hello");
  70.  
  71.     let code: Vec<i8> = vec![2, 3, 4, 5, 5, 6, 6, 3, 2, 1];
  72.     let check_digit: i8 = 3;
  73.  
  74.     let my_upc = upc_code::UPCCode {
  75.         code: code,
  76.         check_digit: check_digit,
  77.     };
  78.  
  79.     println!("Result: {}", my_upc.check_code().unwrap());
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement