Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Name: Chris Torrella
- * COSC 311 FA19
- * hw-11.14
- * URL: <your URL>
- */
- //package hashing;
- import java.util.Arrays;
- import java.util.Random;
- public class Hashing {
- static int h1(int key) {
- return key % 11;
- }
- static int h2(int key) {
- return 7 - (key % 7);
- }
- static int store(int d, int[] table) {
- int h1 = h1(d);
- int h2 = h2(d);
- System.out.printf("Data: %d\nh1(data): %d\nh2(data): %d\n", d, h1, h2);
- if (table[h1] != -1) {
- System.out.println("h1 collision; attempting h2");
- if (table[h2] != -1) {
- System.out.println("h2 collision; probing...");
- while (table[h2] != -1) {
- h2 = (h2 + 1) % 11;
- }
- System.out.println("found free space; storing at table[" + h2 + "]");
- table[h2] = d;
- } else {
- System.out.println("no collision for h2; data stored at table[" + h2+"]");
- table[h2] = d;
- }
- } else {
- System.out.println("no collision for h1; data stored at table[" + h1 + "]");
- table[h1] = d;
- }
- return 0;
- }
- static int genRandInt(Random r) {
- return r.nextInt(100);
- }
- public static void main(String[] args) {
- Random r = new Random(97);
- int[] table = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
- int numInts = 8;
- //System.out.println();
- for (int i=1; i<=numInts; i++) {
- System.out.println("\n-----------Storing int #"+i+"-----------");
- store( genRandInt(r), table );
- }
- System.out.println("\n--------------Results---------------");
- System.out.println("Final table: " + Arrays.toString(table));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement