-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4.rs
92 lines (82 loc) · 2.43 KB
/
4.rs
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
use std::cmp::Ord;
use std::fs::File;
use std::io::prelude::*;
trait Alphabetize {
fn alphabetize(&mut self);
}
impl Alphabetize for String {
fn alphabetize(&mut self) {
let mut chars: Vec<char> = self.chars().collect();
chars.sort();
*self = chars.into_iter().collect();
}
}
trait ToStringVec {
fn to_string_vec(self) -> Vec<String>;
}
impl<'a> ToStringVec for Vec<&'a str> {
fn to_string_vec(self) -> Vec<String> {
self.iter().map(|s| String::from(*s)).collect()
}
}
trait HasDuplicates {
fn has_duplicates(self) -> bool;
}
impl<'a, T: Clone + Ord> HasDuplicates for &'a [T] {
fn has_duplicates(self) -> bool {
let mut v = self.to_vec();
&mut v.sort();
let mut duplicates = false;
for i in 1..v.len() {
if v[i] != v[i - 1] {
continue;
} else {
duplicates = true;
break;
}
}
duplicates
}
}
trait HasDuplicatesOrAnagrams {
fn has_duplicates_or_anagrams(&self) -> bool;
}
impl HasDuplicatesOrAnagrams for Vec<String> {
fn has_duplicates_or_anagrams(&self) -> bool {
let mut v = self.to_vec();
// rearrange the letters in words into alphabetical order so
// that anagrams will be identical
for word in v.iter_mut() {
word.alphabetize();
}
v.has_duplicates()
}
}
fn parse_line(line: &str) -> Vec<&str> {
line.split_whitespace().collect()
}
fn main() {
let mut f = File::open("4.txt").expect("file not found");
let mut contents = String::new();
f.read_to_string(&mut contents).expect("error reading file");
let passphrases: Vec<Vec<String>> = contents
.trim()
.split('\n')
.map(|x| parse_line(x))
.map(|x| x.to_string_vec())
.collect();
let valid_passphrases =
passphrases.len()
- (passphrases.iter()
.filter(|x| x.has_duplicates())
.collect::<Vec<_>>()
.len());
println!("{}", valid_passphrases);
let valid_passphrases_a =
passphrases.len()
- (passphrases.iter()
.filter(|x| x.has_duplicates_or_anagrams())
.collect::<Vec<_>>()
.len());
println!("{}", valid_passphrases_a);
}