DEV Community

Discussion on: Daily Challenge #144 - Box Office Clerk

Collapse
 
idanarye profile image
Idan Arye • Edited

Rust:

fn tickets(bills: &[usize]) -> Result<bool, String> {
    let mut change_25 = 0usize;
    let mut change_50 = 0usize;

    for bill in bills {
        match bill {
            25 => {
                change_25 += 1;
            }
            50 => {
                if 1 <= change_25 {
                    change_25 -= 1;
                    change_50 += 1;
                } else {
                    return Ok(false);
                }
            }
            100 => {
                if 1 <= change_25 && 1 <= change_50 {
                    change_25 -= 1;
                    change_50 -= 1;
                } else if 3 <= change_25 {
                    change_25 -= 3;
                } else {
                    return Ok(false);
                }
            }
            _ => {
                return Err(format!("Expected a 25, 50 or 100 bill - got {}", bill));
            }
        }
    }

    Ok(true)
}

fn main() {
    assert!(tickets(&[25, 25, 50]) == Ok(true));
    assert!(tickets(&[25, 100]) == Ok(false));
    assert!(tickets(&[25, 25, 50, 50, 100]) == Ok(false));
    assert!(tickets(&[25, 25, 50, 50]) == Ok(true));
    assert!(tickets(&[25, 50, 25, 100]) == Ok(true));
}