sweet1cris

Untitled

Feb 4th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.53 KB | None | 0 0
  1. class HashFunction {
  2.     public int cap, seed;
  3.  
  4.     public HashFunction(int cap, int seed) {
  5.         this.cap = cap;
  6.         this.seed = seed;
  7.     }
  8.  
  9.     public int hash(String value) {
  10.         int ret = 0;
  11.         int n = value.length();
  12.         for (int i = 0; i < n; ++i) {
  13.             ret += seed * ret + value.charAt(i);
  14.             ret %= cap;
  15.         }
  16.         return ret;
  17.     }
  18. }
  19.  
  20. public class CountingBloomFilter {
  21.  
  22.     public int[] bits;
  23.     public int k;
  24.     public List<HashFunction> hashFunc;
  25.  
  26.     public CountingBloomFilter(int k) {
  27.         // initialize your data structure here
  28.         this.k = k;
  29.         hashFunc = new ArrayList<HashFunction>();
  30.         for (int i = 0; i < k; ++i)
  31.             hashFunc.add(new HashFunction(100000 + i, 2 * i + 3));
  32.         bits = new int[100000 + k];
  33.     }
  34.  
  35.     public void add(String word) {
  36.         // Write your code here
  37.         for (int i = 0; i < k; ++i) {
  38.             int position = hashFunc.get(i).hash(word);
  39.             bits[position] += 1;
  40.         }
  41.     }
  42.  
  43.     public void remove(String word) {
  44.         // Write your code here
  45.         for (int i = 0; i < k; ++i) {
  46.             int position = hashFunc.get(i).hash(word);
  47.             bits[position] -= 1;
  48.         }
  49.     }
  50.  
  51.     public boolean contains(String word) {
  52.         // Write your code here
  53.         for (int i = 0; i < k; ++i) {
  54.             int position = hashFunc.get(i).hash(word);
  55.             if (bits[position] <= 0)
  56.                 return false;
  57.         }
  58.         return true;
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment