blob: 064b622609e3a5bc4c017d5381c120f70e43ada6 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
use std::cmp::Ordering;
pub fn cmp_hands(a: &str, b: &str) -> Ordering {
let s = String::from("AKQJT98765432");
// first rule
let mut cnt_a = vec![];
let mut cnt_b = vec![];
for c in s.chars() {
cnt_a.push(a.match_indices(c).count());
cnt_b.push(b.match_indices(c).count());
}
cnt_a.sort();
cnt_a.reverse();
cnt_b.sort();
cnt_b.reverse();
for i in 0..cnt_a.len() {
if cnt_a[i] != cnt_b[i] {
if (cnt_a[i] as i64 - cnt_b[i] as i64) < 0 {
return Ordering::Less;
} else {
return Ordering::Greater;
}
}
}
// second rule
for i in 0..a.len() {
let ac = a.chars().nth(i).unwrap();
let bc = b.chars().nth(i).unwrap();
if ac != bc {
let a_i = s.chars().position(|x| x == ac).unwrap();
let b_i = s.chars().position(|x| x == bc).unwrap();
if (b_i as i64 - a_i as i64) < 0 {
return Ordering::Less;
} else {
return Ordering::Greater;
}
}
}
return Ordering::Equal;
}
pub fn main() {
let txt = std::fs::read_to_string("./input/day7.txt").unwrap();
let mut hands = vec![];
for line in txt.lines() {
let x = line.split(" ").collect::<Vec<_>>();
hands.push((x[0], x[1].parse::<u64>().unwrap()));
}
hands.sort_by(|a, b| cmp_hands(a.0, b.0));
let mut sum = 0;
for i in 0..hands.len() {
sum += hands[i].1 * (i + 1) as u64;
}
println!("{}", sum);
}
|