aboutsummaryrefslogtreecommitdiff
path: root/src/day7pt2.rs
blob: b536cac0deda7302f3d9d957f07df4189cce1c76 (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
61
62
63
64
65
66
67
68
use std::cmp::Ordering;

pub fn cmp_hands(a: &str, b: &str) -> Ordering {
    let s1 = String::from("AKQT98765432");
    // first rule
    let mut cnt_a = vec![];
    let mut cnt_b = vec![];
    for c in s1.chars() {
        cnt_a.push(a.match_indices(c).count());
        cnt_b.push(b.match_indices(c).count());
    }

    let a_jok = a.match_indices("J").count();
    let b_jok = b.match_indices("J").count();

    cnt_a.sort();
    cnt_a.reverse();
    cnt_b.sort();
    cnt_b.reverse();
    cnt_a[0] += a_jok;
    cnt_b[0] += b_jok;

    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;
            }
        }
    }

    let s2 = String::from("AKQT98765432J");
    // 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 = s2.chars().position(|x| x == ac).unwrap();
            let b_i = s2.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);
}