回答編集履歴
2
追記
answer
CHANGED
@@ -65,4 +65,44 @@
|
|
65
65
|
映画 -> 映画館はどこも満席。
|
66
66
|
映画 -> ジュニーは戦場へ行くという映画は面白い。
|
67
67
|
映画 -> 休日はおうちで映画鑑賞。
|
68
|
+
```
|
69
|
+
|
70
|
+
[追記] もっと簡単になるな...
|
71
|
+
```C++
|
72
|
+
#include <iostream>
|
73
|
+
#include <fstream>
|
74
|
+
#include <random>
|
75
|
+
#include <string>
|
76
|
+
|
77
|
+
/* fileで指定されたテキストファイル内の文字列の中から
|
78
|
+
wordを含む文字列を返す。
|
79
|
+
複数ある場合、そのうちいずれかを乱数を用いて返す。
|
80
|
+
存在しない場合/ファイルオープン失敗の場合、空文字列を返す。
|
81
|
+
*/
|
82
|
+
std::string find_word(const std::string& file, const std::string& word) {
|
83
|
+
std::string result;
|
84
|
+
std::ifstream stream(file);
|
85
|
+
if (stream.is_open()) {
|
86
|
+
std::string line;
|
87
|
+
int count = 0;
|
88
|
+
std::random_device gen;
|
89
|
+
while (std::getline(stream, line)) {
|
90
|
+
if (line.find(word) != std::string::npos) {
|
91
|
+
++count;
|
92
|
+
if ( std::bernoulli_distribution(1.0/count)(gen) ) result = line;
|
93
|
+
}
|
94
|
+
}
|
95
|
+
}
|
96
|
+
return result;
|
97
|
+
}
|
98
|
+
|
99
|
+
int main() {
|
100
|
+
std::string word = "映画";
|
101
|
+
for (int i = 0; i < 10; ++i) {
|
102
|
+
std::string result = find_word("d.txt", word);
|
103
|
+
if (!result.empty()) {
|
104
|
+
std::cout << word << " -> " << result << std::endl;
|
105
|
+
}
|
106
|
+
}
|
107
|
+
}
|
68
108
|
```
|
1
追記
answer
CHANGED
@@ -1,4 +1,6 @@
|
|
1
1
|
※ 回答ではありませんし、C実装でもありません。
|
2
|
+
暇つぶしに書いてみたんで、なにかのタシになれば。
|
3
|
+
|
2
4
|
```C++
|
3
5
|
#include <iostream>
|
4
6
|
#include <fstream>
|