Convert seconds to compound duration: Difference between revisions

Content added Content deleted
(Added AutoHotkey)
(→‎{{header|Rust}}: Made Rust solution more general.)
Line 929: Line 929:


=={{header|Rust}}==
=={{header|Rust}}==
This solution sacrifices some efficiency and conciseness for generality. The benefit of doing it this way is that any values can be filled in for days, hours, minutes and seconds and the `balance` method will account for it.
<lang rust>fn seconds_to_compound(secs: u32) -> String {
<lang rust>use std::fmt;
let part = |comps: &mut String, c: &str, one: u32, secs: &mut u32| {
if *secs >= one {
let div = *secs / one;
comps.push_str(&(div.to_string() + c));
*secs -= one * div;
if *secs > 0 {
comps.push_str(", ");
}
}
};



let mut secs = secs;
struct CompoundTime {
let mut comps = String::new();
w: usize,
part(&mut comps, "w", 60 * 60 * 24 * 7, &mut secs);
d: usize,
part(&mut comps, "d", 60 * 60 * 24, &mut secs);
h: usize,
part(&mut comps, "h", 60 * 60, &mut secs);
m: usize,
part(&mut comps, "m", 60, &mut secs);
s: usize,
part(&mut comps, "s", 1, &mut secs);
}
comps

macro_rules! reduce {
($s: ident, $(($from: ident, $to: ident, $factor: expr)),+) => {{
$(
$s.$to += $s.$from / $factor;
$s.$from %= $factor;
)+
}}
}

impl CompoundTime {
#[inline]
fn new(w: usize, d: usize, h: usize, m: usize, s: usize) -> Self{
CompoundTime { w: w, d: d, h: h, m: m, s: s, }
}

#[inline]
fn balance(&mut self) {
reduce!(self, (s, m, 60),
(m, h, 60),
(h, d, 24),
(d, w, 7));
}
}

impl fmt::Display for CompoundTime {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}w {}d {}h {}m {}s",
self.w, self.d, self.h, self.m, self.s)
}
}

fn main() {
let mut ct = CompoundTime::new(0,3,182,345,2412);
println!("Before: {}", ct);
ct.balance();
println!("After: {}", ct);
}</lang>
}</lang>