Monday, October 19, 2015


Q:Given a string find the first non repeating character in it
A:
void getFirstNonRepeatingCharacter(String input)
{
    var freq = new Dict<char, int>();
    for(int i = 0; i < input.Length; i++)
    { 
        freq[input[i]] += 1;
     }
    foreach (KeyValuePair<char, int> kvp in freq)
    {
        if (kvp.value == 1)
             Console.WriteLine("{0}", freq[kvp.key]);
     }
 }


Let n and k be fixed positive integers of the same parity, k n. We are given 2n lamps
numbered 1 through 2n; each of them can be on or off. At the beginning all lamps are off. We
consider sequences of k steps. At each step one of the lamps is switched (from off to on or from
on to off).
Let N be the number of k-step sequences ending in the state: lamps 1, . . . , n on, lamps
n+1, . . . , 2n off.
Let M be the number of k-step sequences leading to the same state and not touching lamps
n+1, . . . , 2n at all.
Find the ratio N/M.

Let us call the first set of operations that results in N as admissible
Let us call the second set of operations that result in M as restricted.

For a lamp to remain on, it must be switched an odd number of times.
For a lamp to remain off, it must be switched an even number of times.

Take any lamp l  1<=l <= n and supposed it was switched kl times which should be odd number for the lamp to remain on. Select arbitrarily an even number of Kl switches and replace each of them by the switch of the lamp n+l. This can be done in 2^(kl-one) ways because a kl element set must have 2^(kl-1) subsets of even cardinality. and we started out by saying k1 + .. kn = k.
Since each lamp can be affected independent of others, there are 2^(k1-1) . 2^(k2-1) . 2^(k3-1) . ...2^(kn-1)  = 2 ^(k-n) ways of combining these actions. In any one of these combinations, the end state is the desired state as per the question.
Therefore N/M = 2 ^(k-n).

Sunday, October 18, 2015

Cloud Foundry versus Octopus: 
In the realm of software deployment for Cloud computing, there are different software stacks for Windows and Linux families. Usually they have their own solutions for deployment because by their nature they are different ecosystems and have different platforms. Take Ubuntu for example, and you will find the following list of software: Apache, MySQLZooKeeper, Storm, Kafka, Spark, Cassandra, Nginx, Marathon and Docker usually. And take windows and you will have the following list of software: .NET, Visual Studio, Team Foundation Server, Octopus etc.  While Docker has made applications portable, we want to view the solution for continuous deployment as well as configuration management.  
Let us first identify the two primary candidates for the deployment software. On Ubuntu we have Cloud Foundry and an Windows we have Octopus. 
CloudFoundry is a tool for automated software deployment and hosting with the following benefits: 
You decrease time to production 
You can iterate faster –develop->build->test->deploy 
You increase productivity of developers 
You improve the quality of the products 
You improve the efficiency of IT operations 
You increase the utilization of hardware 
Octopus is a tool that does massive deployments over several different virtual machines with the same configuration and software that you decide It can maintain simultaneous dev, test and production environments and tear them down at will. You can configure different VMs in different pools and they can be used as appropriate.   Octopus can prepare a  VM with any kind of installer.

Both CloudFoundry and Octopus have web interfaces that give you the overall picture of all your deployments. Both come with their security features as well as what’s in progress and what’s completed views. 
However Octopus manages at VM level as well where as CloudFoundry manages based on application stacks.  This is a tremendous advantage because you can choose different VMs specifically or could with a pool of VMs if you are not particular. 
Both tools are scalable and have high performance but the level of control and features are different where Octopus comes out ahead. 
The purpose of these comparisions is to see if there are some ideas that can be ported between the two ecosystems. At the same time, this study should also improve the understanding of these tools. 
However,  we should remind ourselves that these tools are built for different eco-systems with different requirements. 

#coding question

Generate the following pattern when x is given upto Nth terms
For ex:
Input: x=2 ,N=5
OUTPUT:
2
12
1112
3112
132112
https://en.wikipedia.org/wiki/Look-and-say_sequence

Find the next higher no. Of x Whose binary represent does not contain consecutive 1s-
For ex:
Input:
12
Output:
16

int next_non_consecutive_one(int x)
{
bool previous = false;
bool current = false;
bool found = false;
while (!found){
x = x + 1;
int y = x;
 while (y)
{
   if ((y & 0x1) == 0x1)
        current = true;
   else
        current = false;
   if (previous == current && previous == true) {// consecutive 1
         found = false;
          break;
    }
    previous = current;
    y = y >> 1;
}
 if (y == 0) found = true;
}
return x;
}

Today I setup FishEye Crucible for code reviews in my team.

Saturday, October 17, 2015

Let us look at another way to solve previous problem:
Q: A unit square is dissected into n > 1 rectangles such that their sides are parallel to the sides of the square. Any line, parallel to a side of the square and intersecting its interior, also intersects the interior of some rectangle. Prove that in this dissection, there exists a rectangle having no point on the boundary of the square.

A: We suppose the contrary that such dissection does result in  a rectangle with no points on the boundary of the square. We will consider an arbitrary counterexample. We know that each rectangle is attached to at least one side of the square. No rectangle can be attached to opposite sides otherwise one of its sides lies on a splitting line.

We call two rectangles as opposite if they are attached to the opposite sides of ABCD. We claim that there exists two opposite rectangles having a common point.

Consider the union L of all rectangles attached to the left. and assume that they have no common points with the rectangles attached to the right. Now if we take a polygonal line P that connects the top and bottom of the square  and passing close to the right boundary of L then it is easy to visualize that the rectangles of L do not have opposites per our assumption. This means there are rectangles to the right of P and before the rectangles attached to the right. We call them buffer rectangles. Some of these buffer rectangles are attached to the top and some are attached to the bottom. Consequently there is a point on P within the square where the top and the bottom rectangles meet. So there always exists a pair of opposite rectangles
and more importantly no buffer rectangles exist.

Having established that there are opposite rectangles within a square, let us take two arbitrary rectangles within the square that are opposites and say one is connected to the left  which we call a and another is connected to the right which we call b. Let X be a common point that lies on the edge shared between a and b.

If X belongs to their horizontal sides, say when a and b are passing over each other horizontally, then X lies on a horizontal splitting line along the common edge.

If X belongs to their vertical sides, say when a and b are meeting each other horizontally, then the lie on which X lies is not a splitting line. Consequently it intersects the interior of some rectangle. we call this line l.
we can assume an aribitrary rectangle c higher than both a and b that this line intersects. Let the lowermost point of c that lies on the line l be called Y. Then between Y and rectangles a and b, they may be buffer rectangles unless Y lies on a or b. If Y lies on a or b, then the top sides of two rectangles pass through Y and this provides a splitting line again.
If Y lies on two buffer rectangles a' and b' then they a' has to be to the left of b or b' has to be the right of a. Either way the buffer rectangles a' and b' are attached to the opposite sides and are opposites having a common point on l.
Since the top sides of the two rectangles pass through Y, we again have a splitting line.
The presence of a splitting line means the rectangles can be combined and there is at least one rectangle with edges on opposite sides.
Since we have proved that splitting lines exists in all cases, our arbitrary counterexample cannot hold. In such a case we have proved by contradiction that such dissection results in a rectangle having no points on the boundary of the square simply by eliminating splitting lines.

Friday, October 16, 2015

Q: A unit square is dissected into n > 1 rectangles such that their sides are parallel to the sides of the square. Any line, parallel to a side of the square and intersecting its interior, also intersects the interior of some rectangle. Prove that in this dissection, there exists a rectangle having no point on the boundary of the square.

Let us orient the square along horizontal and vertical. A horizontal or vertical line which intersects the interior of a square but does not intersect the interior of any rectangle is called a splitting line. A rectangle having no points on the interior of a square is called an interior rectangle.
Let us assume the contrary that there exists a dissection into more than one rectangles such that there are no interior rectangles and no splitting lines. Under such assumption n > 2 otherwise they will have a common side which will form a splitting line.
Let us define an operation that combines rectangles if they have a common side.With this operation the simple dissection mentioned above reduces the number of rectangles leaving no splitting lines and no rectangles which is a contradiction. So a splitting line and interior rectangle has to exist.
Now let us denote the initial square by points ABCD so that A and B lie along the horizontal. We consider a and b as two rectangles containing the vertices A and B respectively. Rectangle a is not equal to rectangle b otherwise one of their sides provides a splitting line. So let us further assume that the height of a is less than the height of b. We can use the same argument as we will use now for the other case as well when a's height is more than that of b. We are merely picking one case to proceed with the arguments. Now if consider a rectangle c next to the lower right corner of a, then a and c can have the following two cases:
height of a is greater than that of c: Then there exists a rectangle d adjacent to both a and c such that it does not have anything common with sides AB, BC and even AD but it has a common point with CD and its left side provides a splitting line. This results in the same contradiction as earlier.
height of a is less than that of c: In this case the rectangle d will lie over a but it should not border with AD otherwise it would combine with a and the same argument as above holds.
Thus we have proved by contradiction by considering all the cases.



Thursday, October 15, 2015

Q:In the coordinate plane consider the set S of all points with integer coordinates. For a
positive integer k, two distinct points A,B belonging to  S will be called k-friends if there is a point C belonging to S such that the area of the triangle ABC is equal to k. A set T is a subset of S will be called a k-clique
if every two points in T are k-friends. Find the least positive integer k for which there exists
a k-clique with more than 200 elements.
A: Let us picture this problem. We can peg one vertex of the triangle on the origin and choose the remaining points  B(u,v) and C(x,y) such that they form a triangle with an area k. These points are said to be k-friends. If we translate this triangle by a vector, it will not change the area and we will get new k-friends. There are many such translations possible before we determine their number let us look at the properties of the triangle. One such translation would be to choose a new origin such that the old-origin and new-origin are k-friends.
We know the well known formula for a triangle with one vertex at origin is half of mod(uy-vx) which is equal to k for k-friends. This is equivalent to saying  the gcd of u,v is also a divisor of 2k. In other words, two points (u,v) and (0,0) are k -friends if and only if the gcd(u,v) is a divisor of 2k. When we translate, the new point (s,t) and (u,v) are k friends if and only if the point (u-s,v-t) is a k friend of (0,0) which implies gcd(u-s, v-t) divides 2k.
Let us choose a number n that does not divide 2k The claim here is that a k-clique cannot have more than n^2 elements. This is because all points (x,y) can be divided into n^2 classes determined by the remainders that x and y leave in the division by n. If a set T has more than this many points, some two points will have to fall into the same class. This means n divides u-s and n divides v-t  and hence n divides gcd(u-s,v-t) Since n does not divide 2k therefore d does not divide 2k. Points (s,t) and (u,v) are now k-friends and the set T is not a k-clique. Our claim holds.
We can now investigate different values of n to come up with 200 elements.


#custom authentication in django
We take a short break to list the custom authentication in django:
we can do this the following ways
1) we can change the  default authentication backend
2) we can change the user model
3) we can change the permissions
4) we can change the default user

How does a JWTHelper parse ?

token_parts = token.split('.')

if len(token_parts) >= 2:

        import base64

        header = base64.b64decode(token_parts[0])

        claims = base64.b64decode(token_parts[1])

        if len(token_parts) == 3:

           crypto = base64.b64decode(token_parts[2])
        if header and header.get("alg") and header.get("enc") and header.get("iv") and header.get("typ"):

                alg = header["alg"]

                enc = header["enc"]  

                iv = header["iv"]

                typ = header["typ"]

Wednesday, October 14, 2015

Q: For every positive integer n, determine the number of permutations (a1, a2, . . . , an) of the

set {1, 2, . . . , n} with the following property:
2(a1 + a2 + · · · + ak) is divisible by k for k = 1, 2, . . . , n.

A: For each n, let Fn be the number of permutations with the said property and call them 'nice'. For n = 1,2,3 every permutation is nice, so F1 = 1, F2 = 2, F3 = 6.

Now if we take an n > 3 and consider any nice permutation (a1, a2, ... an) of {1, 2, ... n}, then n-1 must be a divisor of the number.

We now rewrite the property for k = n-1 not in terms of a1, a2, an-1 but as the sum of 1, 2 ..n  and subtracting an. This gives us
 n(n+1) - 2an = (n+2)(n-1) + (2-an)
The last part (2 - an) must be divisible by n-1, hence it must be equal to 0, n-1 or 2n-2.
Each of these implies an is either 1 or (n+1)/2 or n

Similarly if we assume an = (n+1)/2, the permutation is nice taking k = n - 2, we get  that n-2 has  to be a divisor of
 2(a1+a2 ...+an-2) = 2((1+2+...+n)-an-an-1) = n(n+1) - (n+1)-2an-1
= (n+2)(n-2) + (3 - 2(an-1))
Since the last component has to be divisible by n-2, it is equal to 0 or n-2 or 2n-4. 0 and 2n-4 are excluded because 2 an-1 -3 is odd. The remaining possibility 2(an-1 -3 = n -2) leads to an-1 = (n+1)/2 = an which cannot be true. This eliminates (n+1)/2 as a possible value of an.

From the above two we are left with either an = 1 or an = n

If an  = n, then (a1, a2, ..., an-1) is a nice permutation of {1, 2 ... n-1}. There are Fn-1 such permutations. Attaching n to any one of them in the end, creates a nice permutation of {1, 2, .. n}

If an = 1, then a1 - 1, a2 -1, ... an-1 - 1 is a permutation of 1,2 ... n-1  It is also nice because the number resulting from the property = 2(a1 + ...+ak) - 2k which is divisible by k for k <= n -1

Here too any one of the nice permutations of Fn-1 nice permutations (b1, b2 ... bn-1) of {1,2 ...n-1} gives rise to a nice permutation of {1,2 ...n} whose last term is 1.

These observations show that there are Fn-1 nice permutations of {1,2 . ... n} exist both with the last term as 1 and the last term as n. Therefore there is a recurrence of Fn = 2 Fn-1 With the base value F3 = 6, we get the formula Fn = 3.2 ^ (n-2) for n>=3.

#puzzle
A king has ten slaves. He receives 60000 bottles of wine from a neighboring king. His advisors inform him that one of the bottles is poisoned but the rest are clean.How can the king find the poisoned bottle ? Assume the poison is highly potent and no matter the dilution will be fatal.
Answer He labels each bottle with their binary representation. Each of the ten slaves is assigned a position from 0 to 9. Each of them drinks from a bottle only when the bit corresponding to their position in set The order in which the slaves die yields the label of the poisoned bottle.

Tuesday, October 13, 2015

Find all positive integers n, for which the numbers in the set S = {1, 2, . . . , n} can be colored red and blue, with the following condition being satisfied: the set S × S × S contains exactly 2007 ordered triples (x, y, z) such that (i) x, y, z are of the same color and (ii) x + y + z is divisible by n.
The answer is n = 64  and n = 84.

Let the numbers 1,2, ...n be colored red and blue. They are partitioned into sets of Red and Blue and denoted by R and B respectively. The size of R = r and the size of B = n - r. The triple (x, y, z) belonging to triple S x S x S is monochromatic if x, y, and z have the same color and bichromatic otherwise.(x,y,z) is divisible if  x+y+z is divisible by n.
Here the claim is there are exactly r^2-rb+b^2 divisible monochromatic triples
For any pair (x,y) that belongs to  S x S , there exists  a unique z for the chosen x,y that belongs to S such that the triple is divisible. There are exactly n ^2 divisible triples. Moreover if the triple is bichromatic, then x, y, z are either blue or two red or vice versa. In both those cases, there is exactly one pair that belongs to the set R x B.. We assign such pair to triple (x, y, z).
Consider any pair (x,y) belonging to RxB, and denote z = z for  a given x,y. Since x != y, the triples x,y,z in any order is distinct and x,y is assigned to each of them. Each pair in RxB is assigned exactly three times.
Therefore, the number of bichromatic divisible triples is three times the number of elements in RxB and the number of monochromatic ones is n^2 - 3rb where n = r + b and can be written as r^2-rb+b^2
To find all values of n where the desired coloring is possible, we have to find all n, for which there exists a composition n = r + b and r^2 -rb + b^2 = 2007.
Solving for these two equations we get (r,b)=(51,18) or (r,b)=(51,33) and the possible values of n = 51+18=69 and n = 51+33=84.