Skip to content

Instantly share code, notes, and snippets.

@sanxiyn
Last active December 13, 2015 21:18
Show Gist options
  • Select an option

  • Save sanxiyn/4975995 to your computer and use it in GitHub Desktop.

Select an option

Save sanxiyn/4975995 to your computer and use it in GitHub Desktop.
Count
extern mod core;
use core::comm;
use core::task;
fn find_max_and_count(list: ~[int]) -> (int, uint) {
let min = list.min();
let max = list.max();
let range = (max - min) as uint;
let mut count = vec::from_elem(range + 1, 0);
let mut max = 0;
let mut max_count = 0;
for list.each |&k| {
let i = (k - min) as uint;
let v = count[i];
let new = k;
let new_count = v + 1;
count[i] = new_count;
if new_count > max_count || new_count == max_count && new < max {
max = new;
max_count = new_count;
}
}
(max, max_count)
}
fn split_to(v: ~[int], n: uint) -> ~[~[int]] {
let mut result = vec::from_fn(n, |_| ~[]);
let min = v.min();
let max = v.max();
let range = (max - min) as uint;
let count = range / n;
do vec::consume(v) |_, e| {
let i = ((e - min) as uint) / count;
let i = if i < n {i} else {n-1};
result[i].push(e);
}
result
}
fn find_max_occurrence(list: ~[int]) -> int {
let n = 4;
let lists = split_to(list, n);
let mut chans = ~[];
let mut ports = ~[];
for n.times {
let (input_port, input_chan) = comm::stream();
let (output_port, output_chan) = comm::stream();
do task::spawn {
let list = input_port.recv();
let result = find_max_and_count(list);
output_chan.send(result);
}
chans.push(input_chan);
ports.push(output_port);
}
do vec::consume(lists) |i, list| {
chans[i].send(list);
}
let mut max = 0;
let mut max_count = 0;
for ports.each |&port| {
let (new, new_count) = port.recv();
if new_count > max_count || new_count == max_count && new < max {
max = new;
max_count = new_count;
}
}
max
}
fn main() {
let list = vec::from_fn(100, |i| i as int);
io::println(fmt!("%d", find_max_occurrence(list)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment