SHARE
TWEET

Untitled

a guest Nov 14th, 2019 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*  Name: Chris Torrella
  2.  *  COSC 311  FA19
  3.  *  hw-11.14
  4.  *  URL:  <your URL>
  5.  */
  6.  
  7. //package hashing;
  8.  
  9. import java.util.Arrays;
  10. import java.util.Random;
  11.  
  12. public class Hashing {
  13.  
  14.     static int h1(int key) {
  15.  
  16.         return key % 11;
  17.  
  18.     }
  19.  
  20.     static int h2(int key) {
  21.  
  22.         return 7 - (key % 7);
  23.  
  24.     }
  25.  
  26.  
  27.     static int store(int d, int[] table) {
  28.  
  29.         int h1 = h1(d);
  30.         int h2 = h2(d);
  31.  
  32.         System.out.printf("Data: %d\nh1(data): %d\nh2(data): %d\n", d, h1, h2);
  33.  
  34.  
  35.  
  36.         if (table[h1] != -1) {
  37.  
  38.             System.out.println("h1 collision; attempting h2");
  39.  
  40.             if (table[h2] != -1) {
  41.  
  42.                 System.out.println("h2 collision; probing...");
  43.  
  44.                 while (table[h2] != -1) {
  45.                     h2 = (h2 + 1) % 11;
  46.                 }
  47.                 System.out.println("found free space; storing at table[" + h2 + "]");
  48.                 table[h2] = d;
  49.  
  50.             } else {
  51.  
  52.                 System.out.println("no collision for h2; data stored at table[" + h2+"]");
  53.  
  54.                 table[h2] = d;
  55.  
  56.             }
  57.  
  58.         } else {
  59.  
  60.             System.out.println("no collision for h1; data stored at table[" + h1 + "]");
  61.  
  62.             table[h1] = d;
  63.  
  64.         }
  65.         return 0;
  66.     }
  67.  
  68.     static int genRandInt(Random r) {
  69.         return r.nextInt(100);
  70.     }
  71.  
  72.     public static void main(String[] args) {
  73.  
  74.         Random r = new Random(97);
  75.         int[] table = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
  76.         int numInts = 8;
  77.  
  78.  
  79.         //System.out.println();
  80.  
  81.         for (int i=1; i<=numInts; i++) {
  82.             System.out.println("\n-----------Storing int #"+i+"-----------");
  83.             store( genRandInt(r), table );
  84.         }
  85.  
  86.         System.out.println("\n--------------Results---------------");
  87.  
  88.         System.out.println("Final table: " + Arrays.toString(table));
  89.  
  90.     }
  91. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top