Finding the angle which is located in most intervals of angles - c++

I've got angle intervals (in radians) [0,2π)
for example intervals [(2π)/3,(3π)/4],[π/2,π] etc.
but there may also be interval [(3π)/2,π/3]
I have to find the angle which is located in most intervals.
What's the best way to find it in C++?
How can I represent the angle intervals?

You could implement a simple sweep-line algorithm to solve this problem.
For each interval, add the start and end of the interval to a vector; sort this vector, then iterate through it. If you have any intervals that cross the 2π-boundary, simply split it into two intervals, which are both inside of (0, 2π).
As you iterate through the list, keep track of how many overlapping itervals there are at the current point, and what the best angle you've seen so far has been (and how many intervals were overlapping at that angle). Once you reach the end, you know what the optimum angle is.
If you need more than one angle, you can rather easily adapt this approach to remember intervals with maximal overlap, rather than single angles.

I'd do it by maintaining a partition of [0, 2π] into ranges corresponding to interval coverage, with a count for each range. First, here's how the algorithm would work under the condition that none of the intervals crosses 0 (or 2π). The intervals are also assumed to be normalized as follows: if an interval ends at 0, it is changed to end at 2π; if it starts at 2π, it is changed to start at 0.
create a list of (range, count) pairs, initialized with a single range [0, 2π] and a count of 0. (The list will be ordered by the start of the range. The ranges in the list will only overlap at their endpoints and will always cover [0, 2π]).
process each interval as described below
scan the list for a (range, count) pair with the highest count. Resolve ties arbitrarily. Return an arbitrary angle within the range.
To process an interval i:
Find the first (range, count) pair (call it s) for which i.start >= s.range.start (i.e., the range contains i.start). (Note that if i.start is the end of one range, then it will be the start of another; this pick the pair for which it is the start.)
Find the last (range, count) pair e for which i.end <= e.range.end. (Note that if i.end is the start of one range, then it will be the end of another; this picks the pair for which it is the end.)
If i.start > s.range.start (i.range starts in the interior of s), split s into two (range, count) pairs s1 = ([s.range.start, i.start], s.count) and s2 = ([i.start, s.range.end], s.count). Replace s in the list with s1 and s2 (in that order).
If i.end < e.range.end, replace e in a manner parallel to the previous step, using i.end to do the split.
For each pair from s (or s2 if s was split in step 3) up to and including e (or e1 if e was split in step 4), add 1 to the count.
If you don't care to keep track of the actual number of intervals that contain a particular angle, just that it's the maximum, the bookkeeping for intervals that cross 0 (or 2π) is easier: just take the complement of the interval (reverse the start and end) and subtract one from the counts in step 5 instead of adding. If you do need the absolute counts, then do the complement trick and then add 1 to every count on the list.
The above will not deal correctly with intervals that abut (e.g.: [0, π/3] and [π/3, π]; or [2π/3, 2π] and [0, 1]). In those cases, as I understand it, the angle at which they abut (π/3 or 0) should be counted as being in two intervals. The above algorithm could be tweaked so that when an interval start coincides with a range end point, a new (range, count) pair is inserted after the pair in question; the new pair would have a single-angle range (that is, range.start == range.end). A similar procedure would apply for the range that starts at the end of an interval. I think that with those tweaks the above algorithm correctly handles all cases.

My solution would involve a list of pairs of start of the interval and how many intervals overlap it:
1 2 3 2 1
|---------|--------|-----|---------------|------|
|------------------|
|--------------|
|---------------------|
|----------------------------|
So, sort all the start and end points and traverse the list assigning each new interval the count of intervals it overlaps with (increasing it if it's a start point, decreasing otherwise). Then take the maximum from the overlap counts.

I think you'll run into weird edge cases if you don't do this symbolically.
Your angular ranges are not only not exactly representable as binary fractions (introducing rounding errors) they're irrational. (Pi is greater than 3.14159265359 but less than 3.14159265360; how do you say that an angle equals Pi/2 besides symbolically?)
The most robust way I see to do it is to take all combinations of intervals in turn, determine their intersection, and see which of these combined intervals are the result of the intersection of the most individual intervals.
This also has a bonus of giving you not just one, but all of the angles that satisfy your condition.

Related

Efficient algorithm to find weights of all cycles in an undirected weighted graph

My aim is to find all the cycles and their respective weights in an weighted undirected graph. The weight of a cycle is defined as sum of the weights of the paths that constitute the cycle. My preset algorithm does the following:
dfs(int start, int now,int val)
{
if(visited[now])
return;
if(now==start)
{
v.push_back(val);// v is the vector of all weights
return;
}
dfs through all nodes neighbouring to now;
}
I call dfs() from each start point:
for(int i=0;i<V;++i)
{
initialise visited[];
for(int j=0;j<adj[i].size();++j)// adj is the adjacency matrix
dfs(i,adj[i][j].first,adj[i][j].second);
// adj is a vector of vector of pairs
// The first element of the pair is the neighbour index and the second element is the weight
}
So the overall complexity of this algorithm is O(V*E)(I think so). Can anyone suggest a better approach?
Since not everyone defines it the same way, I assume...
the weigths are on the edges, not vertices
the only vertex in a cycle that is visited more than one time is the start/end vertex
a single vertex, or two connected vertices, are no cycle, ie. it needs at least three vertices
between two vertices in your graph, there can't be more than one edge (no "multigraph")
Following steps can determine if (at least) one odd-weighted cycle exists:
Remove all vertices that have only 0 or 1 connected edges (not really necessary, but it might be faster with it).
Split every even-weighted edge (only them, not the odd-weighted ones!) by inserting a new vertex. Eg. if the egde between vertex A and B has weight 4, it should become A-Z 2 and Z-B 2, or A-Z 3 and Z-B 1, or something like that.
The actual weight distribution is not important, you don't even need to save it. Because, starting after this step, all weights are not necessary anymore.
What did this actually do? Think like every odd weight is 1, and every even one is 2. (This doesn't change if there is a odd-weighted cycle: If 3+4+8 is odd then 1+2+2 is too). Now you're splitting all 2 into two 1. Since now the only existing weight is 1, determining if the sum is odd is the same as determining if the edge "count" is odd.
Now, for checking bipartiteness / 2coloring:
You can use a modified DFS here
A vertex can be unknown, 0, or 1. When starting, assign 0 to a single vertex, all others are unknown. The unknown neighbors of a 0-vertex always get 1, and the ones of a 1-vertex always get 0.
While checking neighbors of a vertex if they were already visited, check too if the number is different from the vertex you're processing now. If not, you just found out that your graph has odd-weigthed cycles and you can stop everything.
If you reach then end of DFS without finding that, there are no odd-weighted cycles.
For the implementation, note that you could reach the "end" of DFS while there are still unvisited vertices, namely if you have a disconnected graph. If so, you'll need to set one of the remaining vertices to a known number (0) and continue DFS from there on.
Complexity O(V + E) (this time really, instead of a exponential thing or not-working solutions).

Extracting operations from Damerau-Levenshtein

The Damerau-Levenshtein distance tells you the number of additions, deletions, substitutions and transpositions between two words (the latter is what differentiates DL from Levenshtein distance).
The algo is on wikipedia and relatively straightforward. However I want more than just the distance; I want the actual operations.
Eg a function that takes AABBCC, compares it to ABZ, and returns:
Remove A at index 0 -> ABBCC
Remove B at index 2 -> ABCC
Remove C at index 4 -> ABC
Substitute C at index 5 for Z -> ABZ
(ignore how the indices are affected by removals for now)
It seems you can do something with the matrix produced by the DL calculation. This site produces the output above. The text below says you should walk from the bottom right of the matrix, following each lowest cost operation in each cell (follow the bold cells):
If Delete is lowest cost, go up one cell
For Insert, go left one cell
Otherwise for Substitute, Transpose or Equality go up and left
It seems to prioritise equality or substitution over anything else if there's a tie, so in the example I provided, when the bottom-right cell is 4 for both substitution and removal, it picks substitution.
However once it reaches the top left cell, equality is the lowest scoring operation, with 0. But it has picked deletion, with score 2.
This seems to be the right answer, because if you strictly pick the lowest score, you end up with too many As at the start of the string.
But what's the real steps for picking an operation, if not lowest score? Are there other ways to pick operations out of a DL matrix, and if so do you have a reference?
I missed a vital part of fuzzy-string's explanation of how to reconstruct the operations:
But when you want to see the simplest path, it is determined by working backwards from bottom-right to top-left, following the direction of the minimum Change in each cell. (If the top or left edge is reached before the top-left cell, then the type of Change in the remaining cells is overwritten, with Inserts or Deletes respectively.)
...which explains why the equality operation in cell [1,1] is ignored and the delete is used instead!

Maze least turns

I have a problem that i can't solve.I have a maze and I have to find a path from a point S to a point E,which has the least turns.It is known that the point E is reacheable.I can move only in 4 directions,left,right,up and down.It doesn't have to be the shortest path,just to have least turns.
I tried to store the number of turns in a priority queue.For example when I reach a certain place in the maze I will add the numbers of turns till there.From there I would add his neighbours to the priority queue,if they weren't visited already or they weren't walls,with the value of the current block i was sitting,for example t + x which can have the following values ( 0-if the neighbour is facing in the same direction I was facing when i got near him,or 1 if it is in a different direction).It seems that this approach doesn't work for every case.
I will appreciate if somebody could offer me some hints, without any code.
You are on the right track. What you need to implement for this problem is Dijkstra's algorithm. You just need to consider not just points as graph vertices, but pair of (point,direction). From every vertex (p,d) you have 5 edges (although last one can be blocked by wall): (p,0), (p,1), (p,2), (p,3), (neighbour of p in direction d, d). First four edges are of weight 1 (as you turn here), and the last one is of weight 0 (no turn, just move forward). Algorithm is good enough to ignore loops and works fine for edges of weight 0. You should end when any vertex (end point, _) is extracted from priority queue.
This method has one issue, as too many verticies are inspected in the process. If your maze is small, that's not the problem. Otherwise, consider a slight modification known as A*. You need a good heuristic function, describing lower bound on number of turns to the goal.

Comparing two graphs

I need to compare many graphs(up to a few millions graph comparisons) and I wonder what is the fastest way to do that.
Graphs' vertices can have up to 8 neighbours/edges and vertex can have value 0 or 1. Rotated graph is still the same graph and every graph has identical number of vertices.
Graph can look like this:
Right now I'm comparing graphs by taking one vertex from first graph and comparing it with every vertex from second graph. If I find identical vertex then I check if both vertices' neighbours are identical and I repeat this until I know if graphs are identical or not.
This approach is too slow. Without discarding graphs that are for sure different, it takes more than 40 seconds to compare several thousands graphs with about one hundred vertices.
I was thinking about calculating unique value for every graph and then only compare values. I tried to do this, but I only managed to come up with values that if are equal then graphs may be equal and if values are different then graphs are different too.
If my program compares these values, then it calculates everything in about 2.5 second(which is still too slow).
And what is the best/fastest way to add vertex to this graph and update edges? Right now I'm storing this graph in std::map< COORD, Vertex > because I think searching for vertex is easier/faster that way.
COORD is vertex position on game board(vertices' positions are irrelevant in comparing graphs) and Vertex is:
struct Vertex
{
Player player; // Player is enum, FIRST = 0, SECOND = 1
Vertex* neighbours[8];
};
And this graph is representing current board state of Gomoku with wrapping at board edges and board size n*n where n can be up to 2^16.
I hope I didn't made too many errors while writing this. I hope someone can help me.
First you need to get each graph into a consistent representation, the natural way to do this is to create an ordered representation of the graph.
The first level of ordering is achieved by grouping according to the number of neighbours.
Each group of nodes with the same number of neighbours is then sorted by mapping their neighbours values (which are 0 and 1) on a binary number which is then used to enforce an order amongst the group nodes.
Then you can use a hashing function which iterates over each node of each group in the ordered form. The hashed value can then be used to provide an accelerated lookup
The problem you're trying to solve is called graph isomorphism.
The problem is in NP (although it is not known whether it's NP-Complete) and no polynomial time algorithm for it has been found.
The algorithm you describe seems to take exponential time.
This is a possible suggestion for optimization.
I would recommend to try memoization (store all the vertex pairs that are found to be different), so that the next time those two vertices are compared you just do a simple lookup and reply. This may improve the performance (or worsen it), depending on the type of graphs you have.
You have found out yourself that checking isomorphism can be done by checking one bord with all the n*n shifts times 8 rotations of the other, thus having O(n^3) complexity.
This can be reduced to O(n^2). Let's shift only in one direction, say by moving the x axis. Then we only have to find the proper y-offset. For this, we concatenate the elements as follows for both graphs:
. . 1 . 0 . . 3
0 1 . . => 0 1 2 . => 0 3 0 1 2 0 2
. 0 . . 0 . 2 .
_______
1 2 3 4 ^---- a 0 indicates start of a row
We get two arrays of size n and we have to check whether one is a cyclic permutation of the other. For this, we concatenate array a with itself and search for the other.
For example if the two arrays would be a=0301202 and b=0203012 we search for 0203012 in 03012020301202 using KMP or similar, which runs in O(n + 2n)=O(n) time (we can get rid of the whole preprocessing since the first array always is the same).
Combining this O(n) x-check with the n y-shifts and the 8 rotations gives O(n^2) overall complexity by using O(n) additional space.

How to find the nonidentical elements from multiple vectors?

Given several vectors/sets, each of which contains multiple integer numbers which are different within one vector. Now I want to check, whether there exists a set which is composed by extracting only one element from each given vectors/sets, in the same time the extracted numbers are nonidentical from each other.
For example, given sets a, b, c, d as:
a <- (1,3,5);
b <- (3,6,8);
c <- (2,3,4);
d <- (2,4,6)
I can find out sets like (1, 8, 4, 6) or (3, 6, 2, 4) ..... actually, I only need to find out one such set to prove the existence.
applying brutal force search, there can be maximal m^k combinations to check, where m is the size of given sets, k is the number of given sets.
Are there any cleverer ways?
Thank you!
You can reformulate your problem as a matching in a bipartite graph:
the node of the left side are your sets,
the node of the right side are the integer appearing in the sets.
There is an edge between a "set" node and an "integer" node if the set contains the given integer. Then, you are trying to find a matching in this bipartite graph: each set will be associated to one integer and no integer will be used twice. The running time of a simple algorithm to find such a matching is O(|V||E|), here |V| is smaller than (m+1)k and |E| is equal to mk. So you have a solution in O(m^2 k^2). See: Matching in bipartite graphs.
Algorithm for bipartite matching:
The algorithm works on oriented graphs. At the beginning, all edges are oriented from left to right. Two nodes will be matched if the edge between them is oriented from right to left, so at the beginning, the matching is empty. The goal of the algorithm is to find "augmenting paths" (or alternating paths), i.e. paths that increase the size the matching.
An augmenting path is a path in the directed graph starting from an unmatched left node and ending at an unmatched right node. Once you have an augmenting path, you just have to flip all the edges along the path to one increment the size of the matching. (The size of the matching will be increased because you have one more edge not belonging to the matching. This is called an alternating path because the path alternate between edges not belonging to the matching, left to right, and edges belonging to the matching, right to left.)
Here is how you find an augmenting path:
all the nodes are marked as unvisited,
you pick an unvisited and unmatched left node,
you do a depth first search until you find an unmatched right node (then you have an augmenting path). If you cannot find an unmatched right node, you go to 2.
If you cannot find an augmenting path, then the matching is optimal.
Finding an augmenting path is of complexity O(|E|), and you do this at most min(k, m) times, since the size of best matching is bounded by k and m. So for your problem, the complexity will be O(mk min(m, k)).
You can also see this reference, section 1., for a more complete explanation with proofs.