Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use rand::Rng;
- use std::collections::HashMap;
- use std::io;
- extern crate rand;
- pub const A: f32 = 0.666;
- fn main() {
- let mut size: usize = 100;
- println!("###Hash function search with size {};", size);
- let mut res = hash_search(&hash_fn(&random_key(&size), &size), &generate(&size));
- size = 1000;
- println!("###Hash function search with size {};", size);
- res = hash_search(&hash_fn(&random_key(&size), &size), &generate(&size));
- size = 5000;
- println!("###Hash function search with size {};", size);
- res = hash_search(&hash_fn(&random_key(&size), &size), &generate(&size));
- size = 10000;
- println!("###Hash function search with size {};", size);
- res = hash_search(&hash_fn(&random_key(&size), &size), &generate(&size));
- size = 20000;
- println!("###Hash function search with size {};", size);
- res = hash_search(&hash_fn(&random_key(&size), &size), &generate(&size));
- }
- fn hash_search(key: &usize, map: &HashMap<usize, i32>) -> Option<i32>{
- match map.get(key){
- Some(x) => {
- println!("\tValue for key {} is {} !\n", *key, *x);
- return Some(*x)
- },
- None => {
- println!("\tValue for key {} not founded in this scope!\n", *key);
- return None
- }
- };
- }
- fn random_key(size : &usize) -> usize{
- let key = rand::thread_rng().gen_range(0, size + 1);
- return key;
- }
- fn generate(size: &usize) -> HashMap<usize, i32> {
- let mut map: HashMap<usize, i32> = HashMap::new();
- for i in 1..*size + 1 {
- let mut temp: usize;
- loop {
- if map.is_empty() {
- map.insert(hash_fn(&i, &size), i as i32);
- } else {
- if let Some(&getter) = map.get(&i) {
- temp = hash_fn(&i, size);
- } else {
- map.insert(hash_fn(&i, &size), i as i32);
- break;
- }
- if let Some(&getter) = map.get(&temp) {
- println!("In key {} we have collision;", i);
- temp = hash_fn(&temp, size);
- } else {
- map.insert(hash_fn(&temp, size), i as i32);
- break;
- }
- }
- }
- }
- println!("\tmap: \n\t\tkeys: ");
- print!("\t\t\t");
- for val in map.keys(){
- print!("{} ",val)
- }
- println!("\n\t\tvalues: ");
- print!("\t\t\t");
- for val in map.values(){
- print!("{} ",val)
- }
- println!();
- return map;
- }
- fn hash_fn(key: &usize, size : &usize) -> usize{
- let result = (*size as f32)*A*(*key as f32);
- return result.floor() as usize;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement