-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathad2_2_copy.rs
More file actions
executable file
·61 lines (52 loc) · 2.19 KB
/
ad2_2_copy.rs
File metadata and controls
executable file
·61 lines (52 loc) · 2.19 KB
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
use std::fs;
use std::collections::HashSet;
/// Check if a number has repeating pattern, return the number if true, 0 otherwise
fn check_id(num: i64) -> i64 {
let s = num.to_string();
let len = s.len();
if len <= 1 {
return 0;
}
// Check chunk sizes from 1 to half the length
(1..=len / 2)
.filter(|&chunk_size| len % chunk_size == 0)
.any(|chunk_size| {
let chunks: HashSet<&str> = s.as_bytes()
.chunks(chunk_size)
.map(|c| std::str::from_utf8(c).unwrap())
.collect();
chunks.len() == 1
})
.then_some(num)
.unwrap_or(0)
}
/// Sum all valid IDs from ranges in the input lines
fn check_id_lists(lines: &[&str]) -> i64 {
lines.iter()
.filter(|line| !line.is_empty())
.flat_map(|line| {
let mut parts = line.split('-');
let start: i64 = parts.next().unwrap().trim().parse().unwrap();
let end: i64 = parts.next().unwrap().trim().parse().unwrap();
start..=end
})
.map(check_id)
.sum()
}
fn main() {
let file_path_test = "C:\\Users\\iuliia.bubis\\Documents\\MobaXterm\\home\\advent_of_code\\task2_test.txt";
let file_path_task = "C:\\Users\\iuliia.bubis\\Documents\\MobaXterm\\home\\advent_of_code\\task2.txt";
let task_test_str = fs::read_to_string(file_path_test)
.expect("Failed to read test file");
let task_test: Vec<&str> = task_test_str.split(',').map(str::trim).collect();
println!("Read the file {:?}", task_test);
let task_task_str = fs::read_to_string(file_path_task)
.expect("Failed to read task file");
let task_task: Vec<&str> = task_task_str.split(',').map(str::trim).collect();
let test1: Vec<&str> = "11-22,33-35".split(',').collect();
let test2: Vec<&str> = "12121212-12121223".split(',').collect();
println!("Test 1 {:?} : {}", test1, check_id_lists(&test1));
println!("Test 2 {:?} : {}", test2, check_id_lists(&test2));
println!("Test result: {}", check_id_lists(&task_test));
println!("Task result: {}", check_id_lists(&task_task));
}