Exercism track submissions
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

clock - iteration 2

+6 -65
+6 -65
rust/clock/src/lib.rs
··· 1 1 use std::fmt::Display; 2 2 3 - #[derive(Copy, Clone, PartialEq, Debug)] 4 - pub struct Clock(i32, i32); 3 + #[derive(PartialEq, Eq, Debug)] 4 + pub struct Clock(i32); 5 5 6 6 impl Display for Clock { 7 7 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> { 8 - write!(f, "{:02}:{:02}", self.0, self.1) 9 - } 10 - } 11 - 12 - fn adjust_hour(hrs: i32) -> i32 { 13 - match hrs.abs() { 14 - 24 => 0, 15 - 0..=23 => hrs, 16 - _ => hrs % 24, 17 - } 18 - } 19 - 20 - fn adjust_min(mins: i32) -> (i32, i32) { 21 - match mins.abs() { 22 - 60 => (mins / 60, 0), 23 - 0..=59 => (0, mins), 24 - _ => (adjust_hour(mins / 60), mins % 60), 25 - } 26 - } 27 - 28 - fn check_hr_neg(hr: i32) -> i32 { 29 - if hr.is_negative() { 30 - 24 - hr.abs() 31 - } else { 32 - hr 8 + write!(f, "{:02}:{:02}", self.0 / 60, self.0 % 60) 33 9 } 34 10 } 35 11 36 - fn check_min_neg(min: i32, hr: i32) -> (i32, i32) { 37 - if min.is_negative() { 38 - let h = check_hr_neg(adjust_hour(hr - 1)); 39 - let m = 60 - min.abs(); 40 - (h, m) 41 - } else { 42 - (hr, min) 43 - } 44 - } 45 - 46 - fn proc(hr: i32, min: i32) -> (i32, i32) { 47 - let (mut h, m) = adjust_min(min); 48 - h = check_hr_neg(adjust_hour(hr + h)); 49 - 50 - check_min_neg(m, h) 51 - } 52 - 12 + const DAY: i32 = 24 * 60; 53 13 impl Clock { 54 14 pub fn new(hours: i32, minutes: i32) -> Self { 55 - let mut x = Clock(0, 0); 56 - 57 - x.0 = check_hr_neg(adjust_hour(hours)); 58 - 59 - let (a, b) = proc(x.0, minutes); 60 - 61 - x.0 = a; 62 - x.1 = b; 63 - x 15 + Clock((hours * 60 + minutes).rem_euclid(DAY)) 64 16 } 65 17 66 18 pub fn add_minutes(&self, minutes: i32) -> Self { 67 - let mut x = *self; 68 - 69 - let (h, m) = adjust_min(minutes); 70 - 71 - x.0 += h; 72 - x.1 += m; 73 - 74 - let (a, b) = proc(x.0, x.1); 75 - 76 - x.0 = a; 77 - x.1 = b; 78 - x 19 + Clock((self.0 + minutes).rem_euclid(DAY)) 79 20 } 80 21 }