Moved int hash functions into own file, and use in quick_select().

This commit is contained in:
Nathan Vegdahl 2016-08-14 16:03:17 -07:00
parent fbeadfce29
commit cf49cdbb02
4 changed files with 37 additions and 14 deletions

View File

@ -4,6 +4,7 @@ use std;
use std::cmp;
use std::cmp::Ordering;
use lerp::{Lerp, lerp_slice};
use hash::hash_u64;
/// Partitions a slice in-place with the given unary predicate, returning
/// the index of the first element for which the predicate evaluates
@ -120,9 +121,10 @@ pub fn quick_select<T, F>(slc: &mut [T], n: usize, mut order: F)
{
let mut left = 0;
let mut right = slc.len();
let mut seed = n as u64;
loop {
let i = (left + right) / 2;
let i = left + (hash_u64(right as u64, seed) as usize % (right - left));
slc.swap(i, right - 1);
let ii = left +
@ -139,6 +141,8 @@ pub fn quick_select<T, F>(slc: &mut [T], n: usize, mut order: F)
} else {
left = ii + 1;
}
seed += 1;
}
}
@ -241,4 +245,11 @@ mod tests {
quick_select_ints(&mut list, 0);
assert_eq!(list[0], 0);
}
#[test]
fn quick_select_4() {
let mut list = [8, 9, 7, 4, 6, 1, 0, 5, 3, 2];
quick_select_ints(&mut list, 9);
assert_eq!(list[9], 9);
}
}

23
src/hash.rs Normal file
View File

@ -0,0 +1,23 @@
pub fn hash_u32(n: u32, seed: u32) -> u32 {
let mut hash = n;
for _ in 0..3 {
hash = hash.wrapping_mul(1936502639);
hash ^= hash.wrapping_shr(16);
hash = hash.wrapping_add(seed);
}
return hash;
}
pub fn hash_u64(n: u64, seed: u64) -> u64 {
let mut hash = n;
for _ in 0..4 {
hash = hash.wrapping_mul(32416190071 * 314604959);
hash ^= hash.wrapping_shr(32);
hash = hash.wrapping_add(seed);
}
return hash;
}

View File

@ -36,6 +36,7 @@ mod scene;
mod assembly;
mod halton;
mod sampling;
mod hash;
mod color;
mod shading;

View File

@ -12,6 +12,7 @@ use ray::Ray;
use tracer::Tracer;
use halton;
use hilbert;
use hash::hash_u32;
use math::{fast_logit, upper_power_of_two};
use image::Image;
use surface;
@ -373,16 +374,3 @@ struct BucketJob {
w: u32,
h: u32,
}
fn hash_u32(n: u32, seed: u32) -> u32 {
let mut hash = n;
for _ in 0..3 {
hash = hash.wrapping_mul(1936502639);
hash ^= hash.wrapping_shr(16);
hash = hash.wrapping_add(seed);
}
return hash;
}