|
1 |
| -use std::time::Instant; |
2 |
| -use std::io::{BufRead, BufReader}; |
3 |
| -use std::fs::*; |
| 1 | +use core::num; |
| 2 | +use std::sync::atomic::AtomicUsize; |
4 | 3 | use rand::Rng;
|
5 |
| -use rayon::prelude::*; |
| 4 | +use rayon::{prelude::*, vec}; |
| 5 | +use rust_coding_challenges::utils::read_text_file_from_args; |
| 6 | +use std::cmp::min; |
| 7 | +use std::{fs::*, os}; |
| 8 | +use std::io::{BufRead, BufReader, Read}; |
| 9 | +use std::sync::{mpsc, Arc}; |
| 10 | +use std::thread; |
| 11 | +use std::time::Instant; |
| 12 | +use std::sync::atomic::Ordering; |
| 13 | + |
| 14 | +pub fn solve(text: String) -> usize { |
| 15 | + let num_threads = std::thread::available_parallelism().unwrap().get(); |
| 16 | + count_words_parallel(text, num_threads) |
| 17 | +} |
| 18 | + |
| 19 | +fn count_words_parallel(text: String, num_threads: usize) -> usize { |
| 20 | + let lines: Vec<String> = text.lines().map(|line| line.to_string()).collect(); |
| 21 | + let lines_per_thread = (lines.len() + num_threads - 1) / num_threads; |
| 22 | + let total_word_count = Arc::new(AtomicUsize::new(0)); |
| 23 | + let mut handles = Vec::new(); |
| 24 | + |
| 25 | + for i in 0..num_threads { |
| 26 | + let start = lines_per_thread * i; |
| 27 | + let end = min(start + lines_per_thread, lines.len()); |
| 28 | + |
| 29 | + let total_word_count_clone = Arc::clone(&total_word_count); |
| 30 | + let chunk = lines[start..end].to_vec(); |
6 | 31 |
|
7 |
| -pub fn solve(file: File) -> usize { |
8 |
| - let reader = BufReader::new(file); |
9 |
| - let str = reader |
10 |
| - .lines() |
11 |
| - .filter_map(Result::ok) |
12 |
| - .collect::<Vec<String>>() |
13 |
| - .join("\n"); |
14 |
| - count_words(&str) |
| 32 | + let handle = thread::spawn(move || { |
| 33 | + let count = count_words_in_chunk(&chunk); |
| 34 | + total_word_count_clone.fetch_add(count, Ordering::Relaxed) |
| 35 | + }); |
| 36 | + handles.push(handle); |
| 37 | + } |
| 38 | + for handle in handles { |
| 39 | + handle.join().unwrap(); |
| 40 | + } |
| 41 | + total_word_count.load(Ordering::Relaxed) |
15 | 42 | }
|
16 | 43 |
|
17 |
| -fn count_words(text: &str) -> usize { |
18 |
| - text.lines() |
19 |
| - .flat_map(|f| f.split_whitespace()) |
20 |
| - .count() |
| 44 | +fn count_words_in_chunk(chunk: &[String]) -> usize { |
| 45 | + chunk |
| 46 | + .iter() |
| 47 | + .flat_map(|line| line.split_whitespace()) |
| 48 | + .count() |
21 | 49 | }
|
0 commit comments