回答編集履歴

2

追記

2020/06/30 06:48

投稿

episteme
episteme

スコア16614

test CHANGED
@@ -133,3 +133,83 @@
133
133
  映画 -> 休日はおうちで映画鑑賞。
134
134
 
135
135
  ```
136
+
137
+
138
+
139
+ [追記] もっと簡単になるな...
140
+
141
+ ```C++
142
+
143
+ #include <iostream>
144
+
145
+ #include <fstream>
146
+
147
+ #include <random>
148
+
149
+ #include <string>
150
+
151
+
152
+
153
+ /* fileで指定されたテキストファイル内の文字列の中から
154
+
155
+ wordを含む文字列を返す。
156
+
157
+ 複数ある場合、そのうちいずれかを乱数を用いて返す。
158
+
159
+ 存在しない場合/ファイルオープン失敗の場合、空文字列を返す。
160
+
161
+ */
162
+
163
+ std::string find_word(const std::string& file, const std::string& word) {
164
+
165
+ std::string result;
166
+
167
+ std::ifstream stream(file);
168
+
169
+ if (stream.is_open()) {
170
+
171
+ std::string line;
172
+
173
+ int count = 0;
174
+
175
+ std::random_device gen;
176
+
177
+ while (std::getline(stream, line)) {
178
+
179
+ if (line.find(word) != std::string::npos) {
180
+
181
+ ++count;
182
+
183
+ if ( std::bernoulli_distribution(1.0/count)(gen) ) result = line;
184
+
185
+ }
186
+
187
+ }
188
+
189
+ }
190
+
191
+ return result;
192
+
193
+ }
194
+
195
+
196
+
197
+ int main() {
198
+
199
+ std::string word = "映画";
200
+
201
+ for (int i = 0; i < 10; ++i) {
202
+
203
+ std::string result = find_word("d.txt", word);
204
+
205
+ if (!result.empty()) {
206
+
207
+ std::cout << word << " -> " << result << std::endl;
208
+
209
+ }
210
+
211
+ }
212
+
213
+ }
214
+
215
+ ```

1

追記

2020/06/30 06:48

投稿

episteme
episteme

スコア16614

test CHANGED
@@ -1,4 +1,8 @@
1
1
  ※ 回答ではありませんし、C実装でもありません。
2
+
3
+ 暇つぶしに書いてみたんで、なにかのタシになれば。
4
+
5
+
2
6
 
3
7
  ```C++
4
8