Advertisement
Guest User

Untitled

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