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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
|
use std::fs;
fn main() {
let f = fs::read_to_string("input2").unwrap();
let mut nums_vec: Vec<u32> = vec![];
// part one
for line in f.lines() {
let mut first = 0;
let mut second = 0;
// part two
// convert words to numbers
let nline = replace(line);
// println!("replaced:{}", nline);
// Read first int
for c in nline.chars() {
first = get_num(&c);
if first != 0 {
break
}
}
// Read the second int
let chars = nline.chars().rev();
for c in chars {
second = get_num(&c);
if second != 0 {
break
}
}
if first == 0 || second == 0 {
println!("{}:{}", first, second);
panic!();
}
let num = (first * 10) + second;
// println!("result:{}\n", num);
nums_vec.push(num);
}
// println!("{:?}", nums_vec);
let mut final_num = 0;
for num in nums_vec {
final_num += num
}
println!("{}", final_num);
}
fn replace(s: &str) -> String {
let wordmap: Vec<(&str, &str)> = vec![
("one", "1"),
("two", "2"),
("three", "3"),
("four", "4"),
("five", "5"),
("six", "6"),
("seven", "7"),
("eight", "8"),
("nine", "9")
];
// println!("{}", s);
let mut s = s.to_string().clone();
//first
let mut nstring = "".to_string();
let mut len = 0;
for _ in s.chars() {
len += 1;
}
'main: for cidx in 0..len {
let temp = s.split_at(cidx);
// skip if a number is first
for c in temp.0.chars() {
if get_num(&c) > 0 {
break 'main
}
}
for word in &wordmap {
let replace = temp.0.replace(word.0, word.1);
if replace != temp.0 {
nstring = replace.to_string() + temp.1;
break 'main;
}
}
nstring = s.clone();
}
s = nstring.clone();
// println!("{}", s);
//second
let mut len = 0;
for _ in s.chars() {
len += 1;
}
'main: for cidx in (0..len).rev() {
let temp = s.split_at(cidx);
for word in &wordmap {
let replace = temp.1.replace(word.0, word.1);
if replace != temp.1 {
nstring = temp.0.to_string() + &replace;
break 'main;
}
}
nstring = s.clone();
}
nstring
}
fn get_num(c: &char) -> u32 {
match c.to_digit(10) {
Some(n) => n,
None => 0,
}
}
|