Friday, May 17, 2019

PowerMockito: Mocking Private and Public Static Methods

Assume following class with private and public static methods and we want to write junit test which access those methods. We are mocking these static methods.

Mock Private Static Method

For mocking private static method we need to use

Mock Public Static Method

When mocking public static method we could use either of following:
OR
Here is the implementation

BE CAREFUL NOT USE FOLLOWING WITH PUBLIC STATIC METHOD

This will give ERROR
  org.mockito.exceptions.misusing.UnfinishedStubbingException: 
  Unfinished stubbing detected here:
  -> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)

  E.g. thenReturn() may be missing.
  Examples of correct stubbing:
      when(mock.isOk()).thenReturn(true);
      when(mock.isOk()).thenThrow(exception);
      doThrow(exception).when(mock).someVoidMethod();
  Hints:
   1. missing thenReturn()
   2. you are trying to stub a final method, you naughty developer!
   3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed      
      







DeRegistration of a service removed health checks on other services?

$\mathtt{REFERENCE}$ @ GitHub Issue

Problem

I had been tyring to integrate Consul and Fabio.

I was able to run both these servers. Also I was able to register services to consul. That was reflected in Fabio as well. I was able to access the registered services through Fabio.

The problem I stuck into was when I tried to Deregister a service from consul, it did deregister but all the Checks from all other services were also gone. Because of the Fabio stopped accessing other services as well.

Solution

Well I really didn't find what was going on with Consul or Fabio.

All I did to fix this issue was Update the Consul version.

I had been using Consul Linux version 1.4.3.

I updated the consul to 1.5.0 and BOOM!! it fixed the issue.






Wednesday, May 8, 2019

Daily Coding Problem #294: Smallest Weight Strictly Ascending Then Descending Path

Problem Definition

This problem was asked by Square.

A competitive runner would like to create a route that starts and ends at his house, with the condition that the route goes entirely uphill at first, and then entirely downhill.

Given a dictionary of places of the form {location: elevation}, and a dictionary mapping paths between some of these locations to their corresponding distances, find the length of the shortest route satisfying the condition above. Assume the runner's home is location 0.

For example, suppose you are given the following input:

  elevations = {0: 5, 1: 25, 2: 15, 3: 20, 4: 10}
  paths = {
      (0, 1): 10,
      (0, 2): 8,
      (0, 3): 15,
      (1, 3): 12,
      (2, 4): 10,
      (3, 4): 5,
      (3, 0): 17,
      (4, 0): 10
  }
  


In this case, the shortest valid path would be 0 -> 2 -> 4 -> 0, with a distance of 28.

Solution using BackTracking

To solve this problem we need to go through all possible valid paths and determine the minimum weight path.

It can be solved easily with Back Tracking using recursive method.

Solution Overview

  • Start from the starting node which is 0.
  • For each of the path that can be explored from current node, travel along that path if it is valid i.e. Elevation must be valid since we must travel strictly uphill and then downhill only. Anytime we encounter invalid node, we back track and follow different path. Also if node which has already been visited in given path is encountered we should back track since it will give cycle.
  • If we can safely reach final destination node which is 0 again, we store the path summation in a list (OR update miniumum weight)
  • After we have found a path, we need to back track again since there may be many possible paths and we need to find the optimal path.

Java Implementation

Following is implementation in Java. This prints lightest weight and the path. (GoLang version solution, below prints all valid paths with their weights.)

GoLang Implementation

Following is implementation in GoLang. This solution actually prints all valid paths with their path weight. It can be easily modified to return the minimum weight path.

Complexity

This solves the problem by traversing every possible paths. So the theoretical time complexity is $O(2^n)$.

However since the question has restriction that the path has to strictly ascend and then descend, we are returning path as invalid as soon as we encounter invalid path. Because of this restriction, in practice the time complexity will be $O(n).$

Alternative Solution with Memoization

In the previous solution, we start from first node 0 and keep on exploring all possible paths all the way to destination. During the exploration we keep updating track of path sum for all paths and update the best path.

In this solution, we compute the best path and best path weight that can be attained from given node. We cache this result and use it later when we encounter the same node in other path.

This solution does not require to pass currentPath, currentPathSum, bestPath and bestWeight to findPathHelper()

Computation is done from the end. Idea is lightest tail path will be part of the solution path.
Following in implementation.

Complexity

The time complexity will be $O(n).$






Friday, May 3, 2019

Daily Coding Problem #291: Minimum Number of Boats to save population

Problem Definition

An imminent hurricane threatens the coastal town of Codeville. If at most two people can fit in a rescue boat, and the maximum weight limit for a given boat is k, determine how many boats will be needed to save everyone.

For example, given a population with weights [100, 200, 150, 80] and a boat limit of 200, the smallest number of boats required will be 3.

Solution

To be able to determine the smallest number of boats, we need to maximize the number of pairing. To maximize the number of pairing, for given weight we must pair with the maximum value possible. If we pair we smaller weight we may not get the minimum number.

For example, given a population with weights [30, 150, 170, 50] and a boat limit of 200. Here if we pair 30 with 50, then 150 and 170 are left alone hence resulting into the result 3. However, it is possible to pair 30 with 170 and 50 with 150 satisfying the constraint. This pairing will give the result 2.

Therefore, for each weight, we must pair it with the maximum weight possible. We might be tempted to use following solution:
  1. For each weight, iterate through rest of the weights to find the maximum weight with which it can be paired. Make sure to avoid already used weight.
This solution will work, but it will have time complexity $O(n^2)$

Solution Using Sorting

Following is implementation is using sorting. This method is still $O(n^2)$. It takes $O(n)$ time find pair. I am trying to figure out if the pair could be found in $O(logn)$ time instead so that the overall time complexity will be $O(nlogn)$

Implementation

Complexity

Sorting can be done in $O(n logn)$ time.
Finding a pair will take $O(n)$ time.

$\therefore$ The Time Complexity of this method will be $\cal{O(n^2)}$.






Thursday, May 2, 2019

Kruskal's MST Algorithm Using Union-Find Data Structure

$\mathtt{REFERENCE}$ @ Source Class Notes

Kruskal's Algorithm

  1. Like Prim's Algorithm, it is also a greedy algorithm.
  2. While Prim's Algorithm starts from single node and keep growing to reach a final tree, this algorithm starts with $|V|$ trees and keep on combining to finally reach the MST.

Main Features

  1. It starts with a forest of size $n = |V|$ trees.
  2. At each step, it combines two trees to obtain a bigger tree and reduces the number of tress in the forest by 1.
  3. When the forest has a single tree, it is a Minimum Spanning Tree (MST).
Use Union-Find data structure to make it faster.

Formal Sketch of Kruskal's MST Algorithm

  1. $A = \phi$ // A is an empty forest
  2. Sort the edges in the graph in increasing order of the weight.
  3. for each edge $(u,v) \in G.E$ in increasing order of weight {
    1. if $u$ and $v$ are not already connected (find by using Union-Find) {
      1. $A = A \cup \{(u,v)\}$
      2. UNION(u,v) // Union-Find operation
      }
    }
  4. return A

Implementation

Following is the implementation of above explanation.

Complexity

  • Sorting takes $O(|E|log|E|)$ times
  • Union-Find operations can be done in $O(log|V|)$ time if properly implemented
$\therefore$ The Time Complexity of this method will be $O(|E|log|E|)$ time.

for dense graph, $|E| \approx |V|^2 \Rightarrow$ SLOW
for sparse graph, $|E| \approx |V| \Rightarrow$ FAST