/*
Divide a given amount into bills and coins using a greedy algorithm.
This program is written in idiomatic Rust, using clear structure,
functions, slices, sorting, and full explanations.
*/
fn divide_amount(amount: i32, denominations: &[i32]) {
println!("Dividing amount: {}\n", amount);
let mut remaining = amount;
for &d in denominations {
let count = remaining / d; // integer division
if count > 0 {
println!("{}-unit: {}", d, count);
remaining %= d; // reduce remaining amount
}
}
if remaining > 0 {
println!("\nWarning: leftover amount = {}", remaining);
}
}
fn main() {
let bills_coins: [i32; 9] = [500, 100, 200, 50, 20, 10, 5, 2, 1];
// Rust: sort descending using sort_by
let mut denominations = bills_coins.to_vec();
denominations.sort_by(|a, b| b.cmp(a));
let amount: i32 = 9749;
divide_amount(amount, &denominations);
}
/*
run:
Dividing amount: 9749
500-unit: 19
200-unit: 1
20-unit: 2
5-unit: 1
2-unit: 2
*/