diff options
Diffstat (limited to 'day2/src')
| -rw-r--r-- | day2/src/main.rs | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/day2/src/main.rs b/day2/src/main.rs new file mode 100644 index 0000000..9a68b3a --- /dev/null +++ b/day2/src/main.rs @@ -0,0 +1,88 @@ +use std::env; +use std::io::BufReader; +use std::io::BufRead; +use std::fs::File; +use std::process; +use std::collections::HashSet; + +fn main() { + let args: Vec<String> = env::args().collect(); + if args.len() != 2 { + println!("Wrong number of arguments. Provide just a file name."); + process::exit(1); + } + let filename = &args[1]; + println!("Using file {} as input.", filename); + let f = match File::open(filename) { + Ok(file) => file, + Err(e) => { + println!("Failed to open file {}. {:?}", filename, e); + process::exit(1); + } + }; + let file = BufReader::new(&f); + + let mut strings: Vec<String> = Vec::new(); + // exercise 1 + for line in file.lines() { + let l = line.unwrap(); + strings.push(l); + } + + // exercise 1 + let mut doubles = 0; + let mut triples = 0; + + for string in &strings { + let chars: Vec<char> = string.chars().collect(); + let mut is_double = false; + let mut is_triple = false; + for ch in &chars { + let exacts: Vec<&char> = chars.iter().filter(|&c| c == ch).collect(); + let count = exacts.len(); + match count { + 2 => { is_double = true; } + 3 => { is_triple = true; } + _ => {} + } + } + + if is_double { + doubles += 1; + } + + if is_triple { + triples += 1; + } + } + + println!("Doubles: {}", doubles); + println!("Triples: {}", triples); + let checksum = doubles * triples; + println!("Checksum: {}", checksum); + + // exercise 2 + let n = strings.len(); + for i in 0..n { + let string = &strings[i]; + let s_chars: Vec<char> = string.chars().collect(); + + let char_count = s_chars.len(); + for j in (i + 1)..n { + let other = &strings[j]; + let o_chars: Vec<char> = other.chars().collect(); + + let mut commons: Vec<&char> = Vec::new(); + for k in 0..char_count { + if s_chars[k] == o_chars[k] { + commons.push(&s_chars[k]); + } + } + + if commons.len() == char_count - 1 { + let sol: String = commons.into_iter().collect(); + println!("Solution: {}", sol); + } + } + } +} |
