-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwordpair.cpp
More file actions
107 lines (93 loc) · 2.53 KB
/
Copy pathwordpair.cpp
File metadata and controls
107 lines (93 loc) · 2.53 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
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
#include <fstream>
#include <string>
#include <unordered_set>
#include <vector>
void process_file( std::unordered_multiset<std::string> &set, std::fstream &file )
{
std::vector<std::string> words;
std::string word = "";
char c;
while( file.get( c ) )
{
switch( c )
{
case ' ':
case '\t':
case '\n':
if( word != "" )
{
words.push_back( word );
word = "";
}
break;
default:
if( c >= 'A' && c <= 'z' )
{
word = word + c;
}
}
}
for( auto it = words.begin(); it != words.end(); ++it )
{
if( it + 1 != words.end() )
{
set.insert( *it + " " + *(it + 1) );
}
}
}
std::pair<std::string, std::string> find_most_frequent_pair(
std::unordered_multiset<std::string> &set )
{
std::string frequent_pair = "";
std::string last_pair = "";
int max_count = 0;
int count = 0;
for( auto it = set.begin(); it != set.end(); ++it )
{
if( *it == last_pair ) continue;
count = set.count( *it );
if( count > max_count )
{
max_count = count;
frequent_pair = *it;
}
last_pair = *it;
}
if( frequent_pair != "" )
{
std::string first = "", second = "";
bool second_word = false;
for( auto c = frequent_pair.begin(); c != frequent_pair.end(); ++c )
{
switch( *c )
{
case ' ':
second_word = true;
break;
default:
if( second_word )
{
second += *c;
}
else first += *c;
}
}
return std::make_pair( first, second );
}
else return std::make_pair( "", "" );
}
int main()
{
std::fstream text_file( "./doves.txt" );
if( !text_file.is_open() )
{
std::cerr << "couldn't open doves.txt for reading" << std::endl;
}
std::unordered_multiset<std::string> pairs;
std::string line = "";
process_file( pairs, text_file );
auto pair = find_most_frequent_pair( pairs );
std::cout << "most frequent pair is " << pair.first << ", " << pair.second << std::endl;
std::cout << "occurances: " << pairs.count( pair.first + " " + pair.second ) << std::endl;
}