102 lines
3.3 KiB
Rust
102 lines
3.3 KiB
Rust
use std::collections::HashMap;
|
|
use std::fs;
|
|
|
|
fn puzzle1() {
|
|
let contents = fs::read_to_string("./day1.txt").expect("Don't find the file");
|
|
let lines = contents.lines();
|
|
let mut values: Vec<i32> = vec![];
|
|
|
|
for line in lines {
|
|
let mut first = String::new();
|
|
let mut last = String::new();
|
|
for c in line.chars() {
|
|
if c.is_ascii_digit() {
|
|
if first.is_empty() {
|
|
first = c.to_string();
|
|
last = first.clone();
|
|
} else {
|
|
last = c.to_string();
|
|
}
|
|
}
|
|
}
|
|
let result: i32 = format!("{}{}", first, last).parse().unwrap();
|
|
// println!("First : {} - Last : {} ({})", first, last, result);
|
|
values.push(result)
|
|
}
|
|
let sum: i32 = values.iter().sum();
|
|
println!("Puzzle 1 : {:?}", sum)
|
|
}
|
|
|
|
fn puzzle2() {
|
|
let digits_letter = [
|
|
"one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
|
|
];
|
|
let start = "otfsen";
|
|
let mut dict_digit = HashMap::new();
|
|
|
|
dict_digit.insert("one", "1");
|
|
dict_digit.insert("two", "2");
|
|
dict_digit.insert("three", "3");
|
|
dict_digit.insert("four", "4");
|
|
dict_digit.insert("five", "5");
|
|
dict_digit.insert("six", "6");
|
|
dict_digit.insert("seven", "7");
|
|
dict_digit.insert("eight", "8");
|
|
dict_digit.insert("nine", "9");
|
|
|
|
let contents = fs::read_to_string("./day1.txt").expect("Don't find the file");
|
|
let lines = contents.lines();
|
|
let mut values: Vec<i32> = vec![];
|
|
|
|
for line in lines {
|
|
let mut first = String::new();
|
|
let mut last = String::new();
|
|
for (i, c) in line.chars().enumerate() {
|
|
if c.is_ascii_digit() {
|
|
if first.is_empty() {
|
|
first = c.to_string();
|
|
last = first.clone();
|
|
} else {
|
|
last = c.to_string();
|
|
}
|
|
} else if start.contains(c) {
|
|
for j in 1..6 {
|
|
if i + j > line.len() {
|
|
break;
|
|
}
|
|
let word = &line[i..i + j];
|
|
if digits_letter.contains(&word) {
|
|
if first.is_empty() {
|
|
first = dict_digit
|
|
.get(&word)
|
|
.expect("No found digit in hash")
|
|
.parse()
|
|
.unwrap();
|
|
last = first.clone();
|
|
} else {
|
|
last = dict_digit
|
|
.get(&word)
|
|
.expect("No found digit in hash")
|
|
.parse()
|
|
.unwrap();
|
|
}
|
|
}
|
|
// println!("j : {} - word : {}", j, word)
|
|
}
|
|
}
|
|
}
|
|
// print!("First : {} - Last : {}", first, last);
|
|
let result: i32 = format!("{}{}", first, last).parse().unwrap();
|
|
// println!(" ({})", result);
|
|
values.push(result)
|
|
}
|
|
let sum: i32 = values.iter().sum();
|
|
println!("Puzzle 2 : {:?}", sum)
|
|
}
|
|
|
|
fn main() {
|
|
println!("> Day 1");
|
|
puzzle1();
|
|
puzzle2();
|
|
}
|