Skip to content

Instantly share code, notes, and snippets.

@athalean
Last active May 11, 2016 17:30
Show Gist options
  • Save athalean/c8b18831c4c7de1c6d329695fa160ed9 to your computer and use it in GitHub Desktop.
Save athalean/c8b18831c4c7de1c6d329695fa160ed9 to your computer and use it in GitHub Desktop.
extern crate core;
use std::collections::HashSet;
use std::sync::{Mutex, Arc};
use core::cmp::Ordering;
use std::thread;
struct Emitter {
count: Mutex<i32>,
maximum: i32
}
impl Emitter {
fn emit(&self) -> Result<Option<i32>, &'static str>{
let mut count = match self.count.lock() {
Ok(c) => c,
Err(_) => return Err("Error during locking.")
};
*count += 1;
match (*count).cmp(&self.maximum) {
Ordering::Greater => Ok(None),
_ => Ok(Option::Some(count.clone()))
}
}
fn new(maxmium: i32) -> Emitter {
Emitter { count: Mutex::new(1), maximum: maxmium }
}
}
fn factor_sum(i: i32) -> i32 {
let mut sum = 0;
let mut factor = 1;
while factor < i {
match i % factor == 0 {
true => {
sum += factor;
factor += 1;
},
false => {
factor += 1
}
}
}
sum
}
fn consume(emitter: &Emitter, amicables: &Mutex<HashSet<i32>>) {
loop {
match emitter.emit().unwrap() {
Some(number) => {
let sum = factor_sum(number);
if sum < number && factor_sum(sum) == number {
println!("amicable pair found: {} {}", sum, number);
let mut amics = amicables.lock().unwrap();
amics.insert(sum);
amics.insert(number);
}
},
None => break
}
}
}
fn main() {
let maximum = 10000;
let emitter = Arc::new(Emitter::new(maximum));
let mut threads = vec![];
let a_refs = Arc::new(Mutex::new(HashSet::new()));
for _ in 0..4 {
let emitter_ref = emitter.clone();
let amicables_ref = a_refs.clone();
threads.push(thread::spawn(move || {
consume(&emitter_ref, &amicables_ref);
}));
}
for thread in threads {
thread.join().unwrap();
}
let mut amicables = a_refs.lock().unwrap().iter().map(|&x| x.clone()).collect::<Vec<i32>>();
amicables.sort();
let list = amicables.iter().map(|x| x.to_string()).collect::<Vec<String>>().join(", ");
println!("\nThese are all amicable numbers found: \n{}\n", list);
println!("Sum: {}", amicables.iter().fold(0, |x, y| {x + y}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment