blob: 9a68b3a516dcf4e1f5b604b5600ffc445590b445 (
plain)
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
|
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);
}
}
}
}
|