I have to find an algorithm that can find the total amount of intersections between two sets of arrays, whereas one of the array is sorted.
An example, we have these two arrays and we draw straight lines towards corresponding number.
These two arrays gives us a total of 7 intersections.
What kind of algorithms does it exist to help me with this problem?
I have used the search button but did not find anything that would solve this problem for me.
Thanks
Given two number M and N, the lines won't intersect if
the top M is to the right of the top N, and the bottom M is to the right of the bottom N
the top M is to the left of the top N, and the bottom M is to the left of the bottom N
In the other two cases:
left top, right bottom
right top, left bottom
the lines do intersect.
In the example, 8 is to the left of all 4 numbers on the top row, and to the right of 3 numbers on the bottom, so 8 intersects with three numbers.
5 is to the right of 8 on top, left of 8 on the bottom, giving one intersection. 5 is left of 4 and 1 on top, and right of 4 and 1 on the bottom, giving two more. So 5 intersects with three numbers.
Note that we counted the intersection of 5 and 8 twice. In fact every intersection will be counted twice. If you finish the example, you'll count 14 intersections. Divide by 2 at the end to get the answer.
you can represent each line as y=a+bx and then compare each line to the others by comparing their y values.
each line will have maximum one intersection with each other line.
Related
I have being given with a question to scan 2 dimensional array, the array represent a garden, u can step on the garden grass only if the grass is cut down and not too high. a cut down grass represented by number 1. high grass represented with a number bigger then 1, the bigger the number - the higher the grass, heights are unique. in this garden you can have ant colonies which is represented by 0. you can't step on ant colony, no matter what.
Your goal is to cut down all the grass and make it level 1, but u must cat the smallest grass first before you cut any bigger grass. u start from any corner of the garden u choose, as long as u don't stand on an ant colony.
once u cut a grass, it will become number 1, which means, u can now step on it, remember, u can't step on grass bigger then number 1.
Edit:
- heights are unique
The algorithm should return the number of steps made (else -1) , obviously the less steps the better, and you can't go out of the board.
Example:
this matrix
[1,1,1,0]
[1,0,2,1]
[1,0,3,1]
output: 3, because u start from the bottom right cornet, then, u go up, and then left, (chop the grass) and then down (chop grass again).
suggested solution:
is using some kind of a flood fill algorithm (recursion in all directions), and in any case use calculated data structure - like min heap, to hold the current smallest grass height so far, without a pre-clculated min heap we can't never know if we can cut the grass. we take the minimum number from the heap, and start searching for it in the matrix. every cell we encounter, we will go in all directions to search for the number we want.
This solution is obviously the worst, but it solve the problem. I was just wandering if someone can have a better one, I can imagine some dynamic programming solution maybe, not sure. Hell =D
An algorithm that finds the shortest path (with the minimum number of steps):
Collect all cells with height > 1 and sort them by height in increasing order. (They are all unique).
Add the starting cell to the beginning of the sorted collection of cells.
Iterate through the collection and find the shortest path between the current cell and the next cell in the collection, assuming that all cells with higher heights are the ant colonies (cannot be visited). This can be done with BFS. Example:
1 2 4
1 3 0
1 1 1
On the first iteration, we need to find the shortest path between bottom-right corner and cell with height = 2. We should run BFS in the 'virtual garden' where all cells with height > 2 are impossible to go through:
1 2 0
1 0 0
1 1 1
Note, that you need not change higher cells to zero value, just to change the condition in BFS.
Join all found shortest paths.
I am trying to perform the closest pairs algorithm - there is one area however where I am totally stuck.
The problem can be solved in O(n log n) time using the recursive divide and conquer approach, e.g., as follows:
1) Sort points according to their x-coordinates.
2) Split the set of points into two equal-sized subsets by a vertical line x=xmid.
3) Solve the problem recursively in the left and right subsets. This yields the left-side and right-side minimum distances dLmin and dRmin, respectively.
4) Find the minimal distance dLRmin among the set of pairs of points in which one point lies on the left of the dividing vertical and the second point lies to the right.
5) The final answer is the minimum among dLmin, dRmin, and dLRmin.
My problem is with Step 3: Let's say that you've split your 8 element array into two halves, and on the left half you have 4 points - 1,2,3 and 4. Let's also say that points 2 and 3 are the closest pair among those 4 points. Well, if you keep recursively dividing this subset into halves, you will eventually end up calculating the min between 1-2 (on the left), you will calculate the min between 3-4 (on the right), and you will return the minimum-distance pair from those two pairs..
HOWEVER - you've totally missed the distance between 2-3, as you've never calculated it since they were on opposite sides... so how is this issue solved? Notice how Step 4 comes AFTER this recursive process, it seems to be an independent step and only applies to the end result after Step 3, and not to every subsequent division of the subarrays that occurs within Step 3.. is it? Or is there another way of doing this that I'm missing?
The steps are a bit misleading, in that steps 2-5 are all part of the recursion. At every level of recursion, you need to calculate dLmin, dRmin, and dLRmin. The minimum of these is returned as the answer for that level of recursion.
To use your example, you would calculated dLmin as the distance between points 1 and 2, dRmin as the distance between points 3 and 4, and then dLRmin as the distance between points 2 and 3. Since dLRmin is the smallest in your hypothetical case, it would be returned.
This question already has an answer here:
Algorithm for toggling values in a matrix [closed]
(1 answer)
Closed 9 years ago.
Flip the world is a game. In this game a matrix of size N*M is given, which consists of numbers. Each number can be 1 or 0 only. The rows are numbered from 1 to N, and the columns are numbered from 1 to M.
Following steps can be called as a single move.
Select two integers x,y (1<=x<=N and 1<=y<=M) i.e. one square on the matrix.
All the integers in the rectangle denoted by (1,1) and (x,y) i.e. rectangle having top-left and bottom-right points as (1,1) and (x,y) are toggled(1 is made 0 and 0 is made 1).
For example, in this matrix (N=4 and M=3)
101
110
101
000
if we choose x=3 and y=2, the new state of matrix would be
011
000
011
000
For a given state of matrix, aim of the game is to reduce the matrix to a state where all numbers are 1. What is minimum number of moves required.
How to solve this problem?
This is not a homework problem.I'm pretty confused with it.I'm fighting with this problem for past two days.And maintaining a 2-D array for number of ones and zeros.
I tried like balancing the number of one's and number of zeroes.But didn't work out.Any hints or solutions. ?
Source: Hackerearth
Hint #1: Use a greedy approach from bottom to top. That is: if the cell (n, m) is 0 then you must apply XOR to the rectangle (0,0)-(n,m). So try traversing all cells from bottom to top and from right to left and if the current cell is zero then perform a move on it.
This yields a O(n^4) solution.
To get a n^2 solution use, for example, accumulated sums in every rectangle.
I am trying to grasp the explanation of the closest pair point problem in various literatures. While the basic approach is the same in all of them, divide-solve-combine (divide and conquer), and get linear time merge (combine/conquer), the actual implementation is subtly different among the articles and books.
The linear-time-merge is key here which tries to limit the number of points to be compared.
The way the points are being considered in the Kleinberg book is a bit different the way points are considered in this Wikipedia article or Cormen book.
Anyway, for the later two, we find nice explanations for the number of points to be considered here, and here, including many others.
For the problem in hand, please take a look at these slides (slide 32) for the Kleinberg book. The claim of 11 point gap is in the same slide. A more detailed explanation can be found here in page 6, section 6.2.5.6.
However, in the same page of the above mentioned slides (slide 32), we find a claim something like, "Still true if we replace 12 with 7."
I have failed to find an explanation of the above claim.
Please see the figure below,
If we consider the red point to be compared with those in the right half, the points
in the right half should be in the shaded half circle. I have tried to put the extreme ones
in blue. Still they are |5-(-2)|+1 = 8 and |5-15|+1 = 11 apart.
What is it I might be missing here?
Actually you do not need to compute the distance for the lower half of the points, since in your range if you consider points sorted according to y-axis then you start from bottom and go up considering only the points in the region above it.
You can put 9 points on the grid actually. If (0,0) is center and assuming delta=1, you can have 9 points at (-1,-1), (-1,0),..., (1,1).
Proof that it is only at most 9:
Even at optimal packing, you can only have 3 layers of circles each with radius (1/2)with all the centers inside a 2X2 square.
So, the difference drops down to 8 after this. To get to seven you have to assume that it is not a special case (I forgot the technical term for it, but it is a popular assumption in computational geometry. It also states that 3 points cannot be on a same line. It is called "generality assumption" or something like that.
According to CLRS 33.4:
There're 2 points to the left of line l (see the most left 2 points), 2 points to the right of line l (see the most right 2 points), and 4 points on line l (both PL and PR are on the same points).
2 + 2 + 4 = 8
not including the self, so it's 8 - 1 = 7
e.g. we're counting the distance between PL (the upper point on l) and other points, let's do it counterclockwise:
the 1st point (PL) is the most left one,
2nd (PL) is bottom left,
3rd (PL) is the bottom point on l,
4th (PR) is also the bottom point on l,
5th (PR) is the bottom right one,
6th (PR) is the upper right one,
7th (PR) is the upper point on l.
I'm learning for the test and I can't manage with this problem:
We are given a set of n < 1000 points and an integer d. The task is to create two disjoint sets of points A_1 and A_2 (which union is given set of n points) in such way that the distance (euclidean) between each pair of points from A_i (for i = 1 or 2) is less or equal to d. If it is not possible, print -1.
For example, input:
d = 3, and points:
(5,3), (1,1), (4,2), (1,3), (5,2), (2,3), (5,1)
we can create:
A_1 = { (2,3), (1,3), (1,1) }
A_2 = { (5,3), (4,2), (5,2), (5,1) }
since each pair of points from A_i (for i = 1 or 2) are close enough.
I really want to know how to solve it, but no idea. Since n is small, algorithm can be even O(n^2 log n), but I don't know how to start. I was thinking that maybe start with counting the distance between each pair of points, then take two points with maximum distance and place them in to different sets (if their distance is greater than d). Then repeat this step for the rest of pairs, but the problem is how to decide where I can legally put next points. Can anyone help with this algorithm?
Let's consider a simple graph with n nodes (corresponding to the n points). Two nodes are connected if the distance between the two corresponding points is greater that d.
If is is possible to create the two disjoints sets, we must have a bi-partite graphe (if some nodes are not connected to the others, they can be put in any set).
Thus, we only need to test the bipartiteness of the graph which is simple :
http://en.wikipedia.org/wiki/Bipartite_graph#Testing_bipartiteness
Think of an array with all the points across the top and all the points down the side.
Fill in the array with a zero in any cell if the two points (left and top) that define the cell are more than d apart and one if the two points are less than d apart.
(5,3), (1,1), (4,2), (1,3), (5,2), (2,3), (5,1)
(5,3), 0 1 0 1 1 1
(1,1), 0 0 1 0 1 0
(4,2), 1 0 0 1 1 1
(1,3), 0 1 0 0 1 0
(5,2), 1 0 1 0 0 1
(2,3), 1 1 1 1 0 0
(5,1) 1 0 1 0 1 0
(Note: You have to fill in the each triangle with the same 0s and 1s flipped.)
Ignore the diagonal. Pay attention to the top-right triangular section.
Skip the 0th column.
Start with the 1st column and, if it doesn't have a 1 in the top row, swap it with another column to its right that has a 1 in the top row. Then swap the same rows too to keep the diagonal blank. (If there isn't one, there is no solution.) [Example: Swap column 2 and 3 and row 2 and 3] Note that the choice of this row may become an optimizing factor.
Move to the next column and if it doesn't have a 1 in the top row, swap with a column to the right that does and swap the corresponding rows. If there is not one, try swapping it with a row below it that has a 1 in that column and do the corresponding column. The rows below it should be ignored if below the diagonal.
We are collecting points in the top left corner of the triangle that have 1's in them. These points can all go in one of the collections.
This is where I get lost in doing this in my head but you have to do a similar process starting in the bottom right corner of the triangle and collecting points that will be in the other collection. Swap rows and corresponding columns to collect 1s in the bottom right corner of the triangle.
Once you have swapped enough rows that you can form a rectangle in the top right corner--a true rectangle without the bottom left corner cut off--and that rectangle contains all the 0's, you have a solution. If you can't do that, there is no solution.
There is a comparison of the lowest row with a 1 in the triangle and the rightmost column with a 1 in the triangle and the cell where they meet. That cell has to be in the triangle for a solution to exist.
(I left you a big "to-do" to find how to interleave the swaps of rows and columns to clean the 0's out of the top-left and bottom-right corners of the triangle. Maybe a discussion here can resolve how to make it work. Or find out it won't work.)
Starting with a distance matrix seems to be a good idea. Then in this distance matrix pick every entry that is greater than d. This entry means that the according points have to be in different sets.
Start with two empty sets and iterate all relevant entries ( > d).
If sets are empty, put the two points into them. Otherwise there are three options:
If it is clear which set the points belong to, put them into them (that means, inserting the point preserves the max-distance criterion, which can be obtained from the distance matrix).
If the points cannot be inserted into one of the sets, the problem is not solvable.
If both sets are possible for both points, we have a problem. I would suggest starting a new pair of point sets and putting the points into them. Then if a subsequent point pair is unclear again, check for the second set pair. If it is yet unclear, check for a third set pair and so on. If a point pair is inserted into a previous set, check the following sets, if points are now clear. At the end you have a list of pairs of sets of points, which can be united as you wish.
I just had an idea for a second approach, which is similar, but should be a bit faster.
We also start with the distance matrix.
Additional to the two sets, we maintain a stack, queue or whatever of newly added entries.
So if we pick the first relevant entry from the distance matrix, the points are added to both queues. As long as there is an entry in one of the queues, do the following:
Remove the point from the queue and insert it into the set. If the insertion breaks the max-distance criterion, the problem is not solvable. Examine the row or column in the distance matrix for this very point and extract every relevant entry in this row/column. Add the partner point to the queue of the other set (because this has to be in a different set).
If both queues are empty, add the next relevant entry that has not yet been visited to the queues and start over.
This algorithm has the advantage that the points are processed in the order they can impact each other. Therefore, there is no need for more than one pair of sets.