Advertisement
Guest User

Untitled

a guest
Apr 22nd, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.67 KB | None | 0 0
  1. use rand::Rng;
  2. use std::collections::HashMap;
  3. use std::io;
  4. extern crate rand;
  5. pub const A: f32 = 0.666;
  6. fn main() {
  7.  
  8. let mut size: usize = 100;
  9. println!("###Hash function search with size {};", size);
  10. let mut res = hash_search(&hash_fn(&random_key(&size), &size), &generate(&size));
  11. size = 1000;
  12. println!("###Hash function search with size {};", size);
  13. res = hash_search(&hash_fn(&random_key(&size), &size), &generate(&size));
  14. size = 5000;
  15. println!("###Hash function search with size {};", size);
  16. res = hash_search(&hash_fn(&random_key(&size), &size), &generate(&size));
  17. size = 10000;
  18. println!("###Hash function search with size {};", size);
  19. res = hash_search(&hash_fn(&random_key(&size), &size), &generate(&size));
  20. size = 20000;
  21. println!("###Hash function search with size {};", size);
  22. res = hash_search(&hash_fn(&random_key(&size), &size), &generate(&size));
  23.  
  24. }
  25. fn hash_search(key: &usize, map: &HashMap<usize, i32>) -> Option<i32>{
  26. match map.get(key){
  27. Some(x) => {
  28. println!("\tValue for key {} is {} !\n", *key, *x);
  29. return Some(*x)
  30. },
  31. None => {
  32. println!("\tValue for key {} not founded in this scope!\n", *key);
  33. return None
  34. }
  35. };
  36.  
  37. }
  38. fn random_key(size : &usize) -> usize{
  39. let key = rand::thread_rng().gen_range(0, size + 1);
  40. return key;
  41. }
  42. fn generate(size: &usize) -> HashMap<usize, i32> {
  43. let mut map: HashMap<usize, i32> = HashMap::new();
  44. for i in 1..*size + 1 {
  45. let mut temp: usize;
  46. loop {
  47. if map.is_empty() {
  48. map.insert(hash_fn(&i, &size), i as i32);
  49. } else {
  50. if let Some(&getter) = map.get(&i) {
  51. temp = hash_fn(&i, size);
  52. } else {
  53. map.insert(hash_fn(&i, &size), i as i32);
  54. break;
  55. }
  56. if let Some(&getter) = map.get(&temp) {
  57. println!("In key {} we have collision;", i);
  58. temp = hash_fn(&temp, size);
  59. } else {
  60. map.insert(hash_fn(&temp, size), i as i32);
  61. break;
  62. }
  63. }
  64. }
  65. }
  66. println!("\tmap: \n\t\tkeys: ");
  67. print!("\t\t\t");
  68. for val in map.keys(){
  69. print!("{} ",val)
  70. }
  71. println!("\n\t\tvalues: ");
  72. print!("\t\t\t");
  73. for val in map.values(){
  74. print!("{} ",val)
  75. }
  76. println!();
  77.  
  78. return map;
  79. }
  80. fn hash_fn(key: &usize, size : &usize) -> usize{
  81. let result = (*size as f32)*A*(*key as f32);
  82. return result.floor() as usize;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement