Programmer's Blog

Programmer's reference

Monthly Archives: July 2017

[C++] HashMap Implementation

template <typename K, typename V, size_t tableSize, typename F = KeyHash<K, tableSize> >
class HashMap
{
 public:
    HashMap() :
       table(),
       hashFunc()
 {
 }

~HashMap()
{
 // destroy all buckets one by one
 for (size_t i = 0; i < tableSize; ++i) {
     HashNode<K, V> *entry = table[i];

     while (entry != NULL) {
        HashNode<K, V> *prev = entry;
        entry = entry->getNext();
         delete prev;
}

 table[i] = NULL;
 }
}

bool get(const K &key, V &value)
{
     unsigned long hashValue = hashFunc(key);
     HashNode<K, V> *entry = table[hashValue];

     while (entry != NULL) {
         if (entry->getKey() == key) {
             value = entry->getValue();
             return true;
         }

     entry = entry->getNext();
     }

     return false;
}

void put(const K &key, const V &value)
{
   unsigned long hashValue = hashFunc(key);
   HashNode<K, V> *prev = NULL;
   HashNode<K, V> *entry = table[hashValue];

   while (entry != NULL && entry->getKey() != key) {
       prev = entry;
       entry = entry->getNext();
   }

   if (entry == NULL) {
       entry = new HashNode<K, V>(key, value);

       if (prev == NULL) {
            // insert as first bucket
            table[hashValue] = entry;

       } else {
            prev->setNext(entry);
       }
  } else {
       // just update the value
       entry->setValue(value);
  }
}

void remove(const K &key)
{
   unsigned long hashValue = hashFunc(key);
   HashNode<K, V> *prev = NULL;
   HashNode<K, V> *entry = table[hashValue];

   while (entry != NULL && entry->getKey() != key) {
       prev = entry;
       entry = entry->getNext();
   }

   if (entry == NULL) {
      // key not found
      return;

   } else {
       if (prev == NULL) {
       // remove first bucket of the list
       table[hashValue] = entry->getNext();

   } else {
       prev->setNext(entry->getNext());
   }

   delete entry;
 }
}

private:
   HashMap(const HashMap & other);
   const HashMap & operator=(const HashMap & other);
   // hash table
   HashNode<K, V> *table[tableSize];
   F hashFunc;
};
Advertisements

[C++] Basic Binary Search Tree

struct node
{
   int data;
   node * left;
   node * right;
};

//insert elements
node * insert(node * root, int value) {
 
   node *newnode = new node();
   newnode->data = value;
 
   if (!root)
   {
     newnode->left = newnode->right = NULL;
     return newnode;
   } 
   else
   {
     node *tmp = root;
     while (tmp->left != NULL || tmp->right != NULL)
     {
         if (value <= tmp->data)
         tmp = tmp->left;
         else if (value > tmp->data)
         tmp = tmp->right; 
     }
     if (tmp->left) tmp->right = newnode;
     else tmp->left = newnode;
 }

 return root;
}

//inorder search
void inOrder(node *root) {

  if (!root) return;
  if(root->left) inOrder(root->left);
      cout << root->data << " ";
  if(root->right) inOrder(root->right);
}

int max(int i , int j)
{
   return i > j ? i : j;
}

//retrieve height of BST
int height(Node* root)
{
 
  if (!root) return 0;
  else if (!root->left && !root->right) return 0;
  int i = height(root->left) +1;
  int j = height(root->right) +1;
  return max(i,j);
 
}

//Level Order Search
void printLevel(node* root, int h)
{
  if (!root) return;
  if (h == 1)
    cout << root->data << " ";
  else if (h > 1)
  {
     printLevel(root->left, h - 1);
     printLevel(root->right, h - 1);
  }
}

void printLevelOrder(node * root)
{
  if (!root) return;
  int h = height(root);
  for (int i = 0 ; i <= h ; i++)
     printLevel(root, i);
}

//lowest common ancestor
node * lca(node * root, int v1, int v2)
{
   if (!root) return NULL;
 
   if (root->data == v1 || root->data == v2)
       return root;
 
   node* lcaLeft = lca(root->left, v1, v2);
   node* lcaRight = lca(root->right, v1, v2);
 
   if (lcaLeft && lcaRight) return root;
       return (!lcaLeft) ? lcaRight : lcaLeft;
 
}


bool processBST(Node* root, int& min, int& max)
 {
   if (!root) return true;
 
   if(root->data > min && root->data < max &&
     processBST(root->left, min, root->data) && processBST(root->right, root->data, max))
   return true;
     else
   return false;
 
 }

//check if a tree is BST
bool checkBST(Node* root) {
 
 if (!root) return true;
 
 int min = -2147483648;
 int max = 2147483647;
 
 bool a = processBST(root, min, max);
 return a;
}

[C++] find maximum in each of subsequence

problem: Find max in each of the 3 numbers in the sequence

2 3 1 5 6 3 6

ans: 3 5 6 6 6

void printKMax(int arr[], int n, int k){
 deque<int> d;
 int max = 0;
 int maxpos = 0;
 for (int i = 0 ; i < n ; i++)
 {
     d.push_back(arr[i]);
     if (d.size() > k) d.pop_front(); //if size > subseq, drop

     if (max < d.back())  //compare first number in deque
     {
         max = d.back();
         maxpos = k - 1;
     }
     else
         maxpos--;        //the pos in maximum in subseq shifts
 
     if (maxpos <= 0)  //if max num is out of deque
     {                 //check all numbers in the subseq
         max = 0;
         for (int j = 0 ; j < d.size() ; j++)
         {
             if (max < d.back())
             {
                 max = d.back();
                 maxpos = j;
             }
             d.push_back(d.front());
             d.pop_front();
     } 
 }
 
 if (d.size() < k)
 continue;

 cout << max << " ";
}
 
 
 cout << "\n";
}

[C++] (LCS) Longest common sequence problem

 string k = String1;
 string g = String2;
 k.insert(0,1,' ');
 g.insert(0,1,' ');
 
 int m = k.length();
 int n = g.length();
 int arr[m][n];
 
 for (int i = 0 ; i < m ; i++) arr[i][0] = 0;
 for (int j = 0 ; j < n ; j++) arr[0][j] = 0;
 
 for (int i = 1 ; i < m ; i++ )
 {
     for (int j = 1 ; j < n ; j++)
     {
         if (k[i] == g[j])
         {
             arr[i][j] = arr[i-1][j-1] + 1;
         }
         else
         {
             arr[i][j] = arr[i][j-1] > arr[i-1][j] ? arr[i][j-1] : arr[i-1][j];
         }
     }
 } 
 
 cout << arr[m-1][n-1] << endl;

[java] thread pool example

public class ThreadPool implements Runnable{
   private final LinkedBlockingQueue\<Runnable\> queue;
   private final List\<Thread\> threads;
   private boolean shutdown;

public ThreadPool(int numberOfThreads) {
   queue = new LinkedBlockingQueue\<\>();
   threads = new ArrayList<>();

for (int i=0; i\<numberOfThreads; i++) {
   Thread thread = new Thread(this);
   thread.start();
   threads.add(thread);
   }
}

public void execute(Runnable task) throws InterruptedException {
   queue.put(task);
}

private Runnable consume() throws InterruptedException {
   return queue.take();
}

public void run() {
   try {
       while (!shutdown) {
         Runnable task = this.consume();
         task.run();
       }
   } catch(InterruptedException e) {
 }
   System.out.println(Thread.currentThread().getName() + " shutdown");
 }

public void shutdown() {
   shutdown = true;

   threads.forEach((thread) -\> {
   thread.interrupt();
   });
}

public static void main(String[] args) throws InterruptedException {
    ThreadPool threadPool = new ThreadPool(5);
    Random random = new Random();

    for (int i=0; i\<10; i++) {
        int fi = i;
        threadPool.execute(() -\> {
          try {
             Thread.sleep(random.nextInt(1000));
             System.out.printf("task %d complete\n", fi);
          } catch (InterruptedException e) {
             e.printStackTrace();
          }
        });
    }

    Thread.sleep(3000);
    threadPool.shutdown();
}
}