This question was given in my college assignment to be done in C. After doing that, I rewrote the program again in rust. I come from a C/Python background and this is my first rust program. Please critique it. The Program is given inputs in the following format
{num_items} {max_weight}
{item_weight_1} ... {item_weight_num_items}
The output is the number of items and the indices of the chosen items to be put in the bag
use std::io::{self, BufRead};
fn main() {
let reader = io::stdin();
let top_line: Vec<i32> = reader
.lock()
.lines()
.next()
.unwrap()
.unwrap()
.trim()
.split(' ')
.map(|s| s.parse().unwrap())
.collect();
let num_items: i32 = top_line[0];
let max_weight: i32 = top_line[1];
let items: Vec<i32> = reader
.lock()
.lines()
.next()
.unwrap()
.unwrap()
.trim()
.split(' ')
.map(|s| s.parse().unwrap())
.collect();
let s: (i32, i32) = (1..1 << num_items)
.map(|i| {
(
items
.iter()
.enumerate()
.filter(|&(t, _)| (i >> t & 1 == 1))
.map(|(_, elem)| elem.clone())
.sum::<i32>(),
i,
)
})
.map(|(elem, i)| (max_weight - elem, i))
.filter(|&(elem, _)| (elem >= 0))
.min_by(|(a, _), (b, _)| a.cmp(&b))
.unwrap();
let ans: Vec<i32> = (0..num_items)
.filter(|&t| (s.1 >> t & 1 == 1))
.map(|t| t + 1)
.collect();
println!("{}", ans.len());
println!(
"{}",
ans.iter()
.fold(String::new(), |acc, &arg| acc + &arg.to_string() + " ")
);
}
Example input
6 44
14 13 21 8 56 3
Example output
3
1 4 3