Friday, January 11, 2013

Arithmetic Progression

Just solved the hard problem Arithmetic Progression at interviewstreet, and i found it interesting so i decided to share its idea with you.

Problem
 
Let F(a,d) denote an arithmetic progression (AP) with first term 'a' and common difference 'd'. i.e  F(a,d) denotes an infinite AP => a, a+d, a+2d, a+3d,... You are given 'n' APs => F(a1,d1), F(a2,d2), F(a3,d3),... F(an,dn). Let G(a1,a2,... an,d1,d2,... dn) denote the sequence obtained by multiplying the 'n' APs.

Multiplication of 2 sequences is defined as follows: Let the terms of the first sequence be A1, A2, Am, and terms of the second sequence be B1, B2,... Bm. The sequence obtained by multiplying these two sequences is: A1*B1, A2*B2,... Am*Bm. We also give the definition for the kth difference of a sequence. If A1, A2,... Am,... be the terms of a sequence, then the terms of the 1st difference of this sequence are given by A2-A1, A3-A2,... Am-Am-1,... In general, if A1, A2,... Am,... be the terms of the kth difference of a sequence, then the terms of the k+1th difference are given by A2-A1, A3-A2,... Am-Am-1,... We say that the kth difference of a sequence is a constant, if all the terms of the kth difference are equal.

Let F'(a,d,p) be a sequence defined as => ap, (a+d)p, (a+2d)p,... Similarly, G'(a1,a2,... an,d1,d2,... dn,p1,p2,... pn) is defined as => product of F'(a1,d1,p1), F'(a2,d2,p2),... F'(an,dn,pn). Now, your task is to find the smallest 'k' for which the kth difference of the sequence G' is a constant. You are also required to find this constant value.

You will be given many operations. Each operation is of one of the 2 forms:
1.) 0 i j => 0 indicates a query (1<=i<=j<=n).You are required to find the smallest 'k' for which the  kth difference of G'(ai,ai+1,... aj,di,di+1,... dj,pi,pi+1,... pj) is a constant. You should also output this constant value.
2.) 1 i j v => 1 indicates an update (1<=i<=j<=n). For all i<=k<=j, we update pk = pk+v.

Input:

The first line of input contains a single integer 'n', denoting the number of APs. Each of the next 'n' lines consists of 3 integers ai, di, pi (1<=i<=n). The next line consists of a single integer 'q', denoting the number of operations. Each of the next 'q' lines consist of one of the two operations mentioned above.

Output:

For each query, output a single line containing 2 space separated integers 'K' and 'V'. 'K' is the least value for which the Kth difference of the required sequence is a constant. 'V' is the value of this constant. Since 'V' might be large, output the value of 'V' modulo 1000003.

Note: 'K' will always be such that it fits into a signed 64-bit integer. All indices for query and update are 1-based. Do not take modulo 1000003 for 'K'.

Constraints:

1<=n<=100000
1<=ai, di, pi<=10000
1<=q<=100000
For updates of the form "1 i j v", 1 <= v <= 10000

Solution

Unfortunately i tried to find anything related to number theory to find an equation to help solving this problem, but i couldn't find anything useful, actually that's why i managed to share it with you. I did some calculations by my own and i got some interesting equations to solve this problem, and here we go:

To get the K and V for an AP F(A, D, P):

K = P, V = D^P*P!

To get the K and V for F(A1, D1, P1)*F(A2, D2, P2)*F(A3, D3, P3):

I found that K will always equal to: P1+P2+P3.

And with the help of my friend Neal Zane, he helped me to find that V = (D1^P1*D2^P2*D3^P3)*(P1+P2+P3)!.

Now by knowing all the equations needed to solve this problem, we will use segment trees to solve this problem.

Thursday, January 10, 2013

View Angle Problem

Yesterday i was participating in a contest and faced a nice geometry problem named View Angle. After the contest i managed to solve this problem and here are the problem statement and my solution.

Flatland has recently introduced a new type of an eye check for the driver's licence. The check goes like that: there is a plane with mannequins standing on it. You should tell the value of the minimum angle with the vertex at the origin of coordinates and with all mannequins standing inside or on the boarder of this angle. As you spend lots of time "glued to the screen", your vision is impaired. So you have to write a program that will pass the check for you.
Input
The first line contains a single integer n (1 ≤ n ≤ 105) — the number of mannequins. Next n lines contain two space-separated integers each: xi, yi (|xi|, |yi| ≤ 1000) — the coordinates of the i-th mannequin. It is guaranteed that the origin of the coordinates has no mannequin. It is guaranteed that no two mannequins are located in the same point on the plane.
Output
Print a single real number — the value of the sought angle in degrees. The answer will be considered valid if the relative or absolute error doesn't exceed 10 - 6.

Sample test(s)
Input
2
2 0
0 2
Output
90.0000000000
Input
3
2 0
0 2
-2 2
Output
135.0000000000
Input
4
2 0
0 2
-2 0
0 -2
Output
270.0000000000
Input
2
2 1
1 2
Output
36.8698976458


Solution for first test case


Solution for second test case


Solution for third test case


Solution for forth test case


Solution

In order to solve this problem its obvious we need to get the angles between every two adjacent points and getting the max angle say A, and the answer will be 360-A "The angle that will include all other points".

C++ Solution


Monday, December 24, 2012

Segment Trees and lazy propagation

In this topic i will explain a very interesting data structure that can be used to solve a specific set of problems. I will start by explaining its definition and the proceeding with an example problem to solve with it.

Table of contents:
  • What  is segment trees?
  • Order of growth of segment trees operations
  • Show me your code
  • Lazy propagation
  • Sample problems to try 
  • References
What is segment trees?

Segment Trees is a Tree data structure for storing intervals, or segments, It allows querying which of the stored segments contain a given point. It is, in principle, a static structure; that is, its content cannot be modified once the structure is built. It only uses O(N lg(N)) storage.

A segment trees has only three operations: build_tree, update_tree, query_tree.

Building tree: To init the tree segments or intervals values
Update tree: To update value of an interval or segment
Query tree: To retrieve the value of an interval or segment

Example Segment Tree:
  • The first node will hold the information for the interval [i, j]
  • If i<j the left and right son will hold the information for the intervals [i, (i+j)/2] and [(i+j)/2+1, j]
Notice that the height of a segment tree for an interval with N elements is [logN] + 1. Here is how a segment tree for the interval [0, 9] would look like:

 

Order of growth of segment trees operations
  • build_tree: O(N lg(N)) 
  • update_tree: O(lg(N + k)) 
  • query_tree: O(lg(N + k))
K = Number of retrieved intervals or segments

Show me your code

 


Lazy Propagation 

Sometimes a segment tree operation wouldn't survive if the problem constraints is too large, here it come lazy propagation along with the segment tree.

In the current version when we update a range, we branch its childs even if the segment is covered within range. In the lazy version we only mark its child that it needs to be updated and update it when needed.




Note: Read my solution for problem Can you answer these queries I in this article.


Sample Problems to try
References

Wednesday, December 19, 2012

Lucas' Theorem to solve binomial coefficients

I am happy cause only one problem and i will be done solving interviewstreet mathematical problems. After solving the Binomial Coefficients  problem i think i have something useful to share with you.

In this problem you are given two number N and P, where P is a prime number. You are requested to find how many binomial coefficients of n become to 0 after modulo by P.

So the output should be the number of  \tbinom nks (0<=k<=n)  each of which after modulo operation by P is 0.

I hear you saying its an easy problem, but you won't say that after knowing about the input constraints.

Constraints:
n is less than 10500.
P is less than 109.

For such large number i will use Java to solve this problem, thanks to the BigInteger Class in java. After doing some search i found that there is a theorem called Lucas' Theorem which is as follows:

Given n, k, and prime p, binomial (n,k) is divisible by p if and only if at least one of  the base p digits of k is larger than the corresponding digit of m (also base p digit).

So to solve this problem we need to find the base P representation of n, and counting how many numbers (R) that have all digits (in base P) less than the corresponding digit in n.

1. We have k is between 0 and n, so we have (n+1) numbers to check with n.
2. Now need to find R.

Now if n in base P is as follows: abc...

Then we need to get all numbers that have:

1. First digit is 0, 1, 2, .... a-1
2. Second digit is 0, 1, 2, .... b-1
3. Third digit is 0, 1, 2, ...., c-1

Obviously R = (a+1)*(b+1)*(c+1).

So we have (n+1) total numbers, subtracting  R, then the result would be n+1-R.

Friday, December 7, 2012

Hacking linux keyboard

Now again with another interesting kernel hack, in this post i will show you a sample input device that report keyboard events without pressing any keys. In this sample i will report the left arrow key pressed event whenever the user pressing any key.

Actually i was building a new keyboard hardware with its device driver, but as i don't have time to share a video with you now about my new se7so keyboard, i thought about something interesting to share with you :).

As the user will be forced to write from right to left, instead of writing from left to right, I was trying to login my machine and because of the module was loaded i was forced to write my password from right to left :D "what comes around, goes around".

You can download the code from sourceforge.

Enjoy the video ;).

Monday, December 3, 2012

Apache JMeter along with jsf pages

Two days ago i was allocated a task from my team leader to load test our new web application after deploying it on the production environment. We used lots of open source technologies in this application but the main challenge was to configure JMeter to pass the JSF login page that contains a button posts to a JSF action.

If you don't know about JMeter, you may need to read this topic on my blog.

Step 1: Creating a Thread Group with the following configuration:

Name: Schindler Thread Group
Number of threads (Users): 300
Ramp-Up Period (In seconds): 2
Loop count: 2



Step 2: Creating Once Only Controller under the Thread Group with the following configuration:

Name: Schindler Login



Step 3: Creating an HTTP Request under the Once Only Controller with the following configuration

Name: Initial Login request
Server Name: my.server.name
Port Number: 80
Path: /Schindler-web/login.xhtm
Implementation: Java
Protocol: HTTP
Method: GET
Follow Redirects: True



Step 4: Creating an XPath Extractor to extract the view state of the login button

Name: Xpath Extractor
ِApply to: Main sample only
Reference name: myViewState
XPath query: //input[@id='javax.faces.ViewState']/@value



Step 5: Creating an HTTP Request to submit credentials to the jsf login action with the following config

Name: Auth
Server Name: my.server.name
Port Number: 80
Path: /Schindler-web/login.xhtml
Implementation: Java
Protocol: HTTP
Method: POST
Follow Redirects: True
Use KeepAlive: True
Parameters:

j_username : admin : encode = true : include equals = true
j_password : password : encode = true : include equals = true
javax.faces.ViewState : ${myViewState} : include equals = true
login : Login : include equals = true
loginForm : loginForm : include equals = true



Step 6: In the same level of the Once Only Controller create an HTTP URL Re-writing modifier to extract the session id with the following configuration

Name: HTTP URL Re-writing Modifier
Session Argument Name: JSESSIONID
Cache Session ID = true



Step 7: Create an HTTP Cookie Manager to save the session id and sending it along with all the requests

Name: HTTP Cookie Manager



Step 8: Create some listeners to view the results in my case i preferred to use View Results in Table, Graph Results, and View Results Tree.


Table View

Graph View

Tree View

Notes: To be able to survive any problems you face, use Firebug to check the request on your browsers and what are the parameters sent along with the request and make sure that your jmeter requests are configured with the same parameters and values.

Friday, October 19, 2012

Impartial games problems

Again with a new problem, but this time i will explain a very nice approach to solve a specific set of problems located under the category of game theory.

Impartial games

In combinatorial game theory, an impartial game is a game in which the allowable moves depend only on the position and not on which of the two players is currently moving, and where the payoffs are symmetric. In other words, the only difference between player 1 and player 2 is that player 1 goes first.

Impartial games include Nim, Sprouts, Kayles, Quarto, Cram, Chomp, and poset games. I will explain the nim problem and how to solve it, then i will move to the Stone Piles problem that i solved this week.
 
Nim Problem

Nim is a game in which two players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object, and no more than a set maximum number from the heap.

An example normal play game is shown below:

A B C
3 4 5 I take 2 from A
1 4 5 You take 3 from C
1 4 2 I take 1 from B
1 3 2 You take 1 from B
1 2 2 I take entire A heap leaving two 2’s.
0 2 2 You take 1 from B
0 1 2 I take 1 from C leaving two 1’s.
0 1 1 You take 1 from B
0 0 1 I take entire C heap and win.

What is your winning strategy? 

Luckily, we can find one. Nim has been solved for all starting positions and for any number of heaps. First we’ll look at different types of game positions, then we’ll do some work with “nimbers” (yes, that really is a word) and then apply them to finding a solution to Nim.

Types of impartial game positions

• A game is in a P-position if it secures a win for the Previous player (the one who just moved).
• A game is in a N-position if it secures a win for the Next player.

So in normal play Nim with three heaps, (0,0,1) is an N-position and (1,1,0) is a P-position. We call the position from which no possible moves are left a terminal position. To find whether a Nim position is N or P, we work backwards from the end of the game to the beginning in a process called backwards induction:

1. Label every terminal position as P.
2. Label every position that can reach a P position as N.
3. For positions that only move to N positions, label P.
4. At this point either all positions are labeled or return to step 2 and repeat the process until all positions are labeled.

Applying these rules to Nim, we first set the only terminal position (in other games there could be many) 0,0,0, to P. It is obvious that any position (0,0,n) is an N position, since the next player can just take the last heap in one turn.

Nimber arithmatic

The key operation in the solution to Nim is binary addition without carrying. To add two numbers in this manner, first write out their binary expansions, and then take the exclusive or (XOR) of the two numbers bit by bit.

Theorem 1. A position, (x1, x2, x3), in Nim is a P-position if and only if the nim-sum of its components is zero, x1 ⊕ x2 ⊕ x3 = 0. As an example, take the position (x1, x2, x3) = (13, 12, 8). Is this a P-position? If not, what is a winning move? We compute the nim-sum of 13, 12 and 8:
 
13 = 11012
12 = 11002
8 = 10002
nim-sum = 10012 = 9
 
Since the nim-sum is not zero, this is an N-position according to Theorem 1. Can you find a winning move? You must find a move to a P-position, that is, to a position with an even number of 1’s in each column. One such move is to take away 9 chips from the pile of 13, leaving 4 there. The resulting position has nim-sum zero:

4 = 1002
12 = 11002
8 = 10002
nim-sum = 00002 = 0

Another winning move is to subtract 7 chips from the pile of 12, leaving 5. Check it out.

Now we can solve the Nim game with any number of piles.

Stone Piles problem

This is a much harder problem in which we are going to move to another theorem called Sprague Grundy theorem, in which will help us solving this problem.

You can view this problem at interviewstreet.com using this link. However in this problem the game described as below:

There are N piles of stones where the ith pile has xi stones in it. Alice and Bob play the following game:
  • a. Alice starts, and they alternate turns.
  • b. In a turn, a player can choose any one of the piles of stones and divide the stones in it into any number of unequal piles such that no two of the piles you create should have the same number of stones. For example, if there 8 stones in a pile, it can be divided into one of these set of piles: (1,2,5), (1,3,4), (1,7), (2,6) or (3,5). 
  • c. The player who cannot make a move (because all the remaining piles are indivisible) loses the game.
Given the starting set of piles, who wins the game assuming both players play optimally?

Sprague Grundy Theorem

Definition: A directed graph G(X,F) Where A directed graph, G, is a pair (X,F) where X is a nonempty set of vertices (positions) and F is a function that gives for each x ∈ X  a subset of X, where each of them is a position reachable from x.

The Sprague-Grundy function of a graph, (X,F), is a function, g, defined on X and taking non-negative integer values, such that g(x) =min{n ≥ 0 : n = g(y) for y ∈ F(x)}.

In words, g(x) the smallest non-negative integer not found among the Sprague-Grundy values of the followers of x. If we define the minimal excludant, or mex, of a set of non-negative integers as the smallest non-negative integer not in the set, then we may write simply g(x) =mex{g(y) : y ∈ F(x)}.

Mex means Minimum Excluded Value. Below are some practice examples:

mex({2,4,5,6}) = 0
mex({0,1,2,6}) = 3

Now how to solve the stone piles game?

1. Mark all terminal nodes sg = 0 (In this case its 1 and 2 as the player will not be able to divide them)
2. For each pile compute the sg value of it
3. Get the nim-sum of all the sg values of the piles, if 0 then BOB wins, else ALICE wins.

How to get the sg value of a number?

1. DFS all the possible divisions of this pile
2. Recursively compue the sg values of all the possible divisions
3. Return the mex out of them

Now i am done explaining the whole topic, i think its really interesting and i suggest you solving more problems as i will do isA.