[2018][rust][3.1]

sorbet
Alpha Chen 6 years ago
parent cf72591813
commit 71fb3478c3

@ -21,17 +21,24 @@ fn solve(input: &str) -> Result<String, Box<Error>> {
.map(str::trim) .map(str::trim)
.map(Claim::from_str) .map(Claim::from_str)
.collect::<Result<_, _>>()?; .collect::<Result<_, _>>()?;
let fabric = claims.iter().fold(HashMap::new(), |mut fabric, claim| { let fabric = claims.iter().fold(HashMap::new(), |mut fabric: HashMap<(usize, usize), Vec<usize>>, claim| {
for square_inch in claim.square_inches() { for square_inch in claim.square_inches() {
fabric fabric
.entry(square_inch) .entry(square_inch)
.and_modify(|count| *count += 1) .and_modify(|ids| ids.push(claim.id))
.or_insert(1); .or_insert(vec![claim.id]);
} }
fabric fabric
}); });
let output = fabric.values().filter(|&&count| count > 1).count(); let values: Vec<_> = fabric.values().collect();
Ok(output.to_string()) let output = values
.iter()
.map(|ids| ids[0])
.filter(|id| !values.iter().any(|ids| ids.len() > 1 && ids.contains(id)))
.next()
.unwrap()
.to_string();
Ok(output)
} }
#[test] #[test]
@ -43,7 +50,7 @@ fn test_solve() {
" "
.trim(); .trim();
assert_eq!(&solve(input).unwrap(), "4"); assert_eq!(&solve(input).unwrap(), "3");
} }
#[derive(Debug, PartialEq, Eq)] #[derive(Debug, PartialEq, Eq)]

Loading…
Cancel
Save