Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- pub fn maximum_count_threaded_2 (nums: Vec<i32>, thread_count: usize) -> i32 {
- let mut nums = &*nums;
- let len = nums.len();
- let thread_work_amount = (len + (thread_count - (len - 1) % thread_count + 1)) / thread_count; // trust me this works
- let mut handles = vec!();
- for current_thread_id in 0..thread_count {
- let (current_nums, rest): (&[i32], &[i32]) = if current_thread_id == thread_count - 1 {
- (nums, &[])
- } else {
- nums.split_at(thread_work_amount)
- };
- nums = rest;
- let current_nums: Vec<i32> = current_nums.into();
- let current_handle = thread::spawn(move || {
- let mut positive_count = 0;
- let mut negative_count = 0;
- for v in current_nums {
- if v > 0 {
- positive_count += 1;
- } else if v < 0 {
- negative_count += 1;
- }
- }
- (positive_count, negative_count)
- });
- handles.push(current_handle);
- }
- let results = handles.into_iter()
- .map(|handle| handle.join().unwrap_or((0, 0)))
- .fold((0, 0), |(positive_count, negative_count), v| (positive_count + v.0, negative_count + v.1));
- max(results.0, results.1)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement