day-04.rs (3242B)
1 fn main() {
2 let input = std::fs::read_to_string("input.txt")
3 .unwrap()
4 .trim()
5 .split("-")
6 .map(|op| op.parse::<usize>().unwrap())
7 .collect::<Vec<usize>>();
8
9 println!("Rust:");
10 println!("Part 1: {}", part_1(&input));
11 println!("Part 2: {}", part_2(&input));
12 }
13
14 fn part_1(input: &Vec<usize>) -> usize {
15 let start = input[0];
16 let end = input[1];
17 let mut pw_count = 0;
18 for first in (start / 100000)..=(end / 100000) {
19 for second in first..=9 {
20 if first * 100000 + second * 10000 > end {
21 break;
22 }
23 for third in second..=9 {
24 for forth in third..=9 {
25 for fifth in forth..=9 {
26 for sixth in fifth..=9 {
27 let pw = first * 100000
28 + second * 10000
29 + third * 1000
30 + forth * 100
31 + fifth * 10
32 + sixth;
33 // Ensure in range.
34 if pw >= start && pw <= end {
35 if first == second
36 || second == third
37 || third == forth
38 || forth == fifth
39 || fifth == sixth
40 {
41 pw_count += 1;
42 }
43 }
44 }
45 }
46 }
47 }
48 }
49 }
50
51 pw_count
52 }
53
54 fn part_2(input: &Vec<usize>) -> usize {
55 let start = input[0];
56 let end = input[1];
57 let mut pw_count = 0;
58 for first in (start / 100000)..=(end / 100000) {
59 for second in first..=9 {
60 if first * 100000 + second * 10000 > end {
61 break;
62 }
63 for third in second..=9 {
64 for forth in third..=9 {
65 for fifth in forth..=9 {
66 for sixth in fifth..=9 {
67 let pw = first * 100000
68 + second * 10000
69 + third * 1000
70 + forth * 100
71 + fifth * 10
72 + sixth;
73 // Ensure in range.
74 if pw >= start && pw <= end {
75 if (first == second && second != third)
76 || (first != second && second == third && third != forth)
77 || (second != third && third == forth && forth != fifth)
78 || (third != forth && forth == fifth && fifth != sixth)
79 || (forth != fifth && fifth == sixth)
80 {
81 pw_count += 1;
82 }
83 }
84 }
85 }
86 }
87 }
88 }
89 }
90
91 pw_count
92 }