Coordinates to Grid Box Number - math

Let's say I have some grid that looks like this
_ _ _ _ _ _ _ _ _
| | | |
| 0 | 1 | 2 |
|_ _ _|_ _ _|_ _ _|
| | | |
| 3 | 4 | 5 |
|_ _ _|_ _ _|_ _ _|
| | | |
| 6 | 7 | 8 |
|_ _ _|_ _ _|_ _ _|
How do I find which cell I am in if I only know the coordinates? For example, how do I get 0 from (0,0), or how do I get 7 from (1,2)?
Also, I found this question, which does what I want to do in reverse, but I can't reverse it for my needs because as far as I know there is not a mathematical inverse to modulus.

In this case, given cell index A in the range [0, 9), the row is given by R = floor(A/3) and the column is given by C = A mod 3.
In the general case, where MN cells are arranged into a grid with M rows and N columns (an M x N grid), given a whole number B in [0, MN), the row is found by R = floor(B/N) and the column is found by C = B mod N.
Going the other way, if you are given a grid element (R, C) where R is in [0, M) and C is in [0, N), finding the element in the scheme you show is given by A = RN + C.

cell = x + y*width
Programmers use this often to treat a 1D-array like a 2D-array.

For future programmers
May this be useful:
let wide = 4;
let tall = 3;
let reso = ( wide * tall);
for (let indx=0; indx<reso; indx++)
{
let y = Math.floor(indx/wide);
let x = (indx % wide);
console.log(indx, `x:${x}`, `y:${y}`);
};

Related

Parse data in Kusto

I am trying to parse the below data in Kusto. Need help.
[[ObjectCount][LinkCount][DurationInUs]]
[ChangeEnumeration][[88][9][346194]]
[ModifyTargetInLive][[3][6][595903]]
Need generic implementation without any hardcoding.
ideally - you'd be able to change the component that produces source data in that format to use a standard format (e.g. CSV, Json, etc.) instead.
The following could work, but you should consider it very inefficient
let T = datatable(s:string)
[
'[[ObjectCount][LinkCount][DurationInUs]]',
'[ChangeEnumeration][[88][9][346194]]',
'[ModifyTargetInLive][[3][6][595903]]',
];
let keys = toscalar(
T
| where s startswith "[["
| take 1
| project extract_all(#'\[([^\[\]]+)\]', s)
);
T
| where s !startswith "[["
| project values = extract_all(#'\[([^\[\]]+)\]', s)
| mv-apply with_itemindex = i keys on (
extend Category = tostring(values[0]), p = pack(tostring(keys[i]), values[i + 1])
| summarize b = make_bag(p) by Category
)
| project-away values
| evaluate bag_unpack(b)
--->
| Category | ObjectCount | LinkCount | DurationInUs |
|--------------------|-------------|-----------|--------------|
| ChangeEnumeration | 88 | 9 | 346194 |
| ModifyTargetInLive | 3 | 6 | 595903 |

divide rectangle into n equal parts

i want to code a video platform and have a problem and can't think of a solution right now.
I want to divide a rectangle into equal parts
Came up with a solution for a square but i am unable to come up with a solution for different ratios.
Maybe u guys can help me.
example:
BAD GOOD
n=4
________ ________
| | | | | | | |
| | | | | |---|---|
|_|_|_|_| |___|___|
n=2
________ ________
| | | | |
| | | | |
| | | |–––––––|
| | | | |
|___|___| |_______|
Let X be the width of the rectangle and let Y be the height. Let the goal be to divide this rectangle into N rectangles of equal area whose sides are as close to equal as possible.
The solution is not difficult. First, find all factors of the N. Then, write N as a product of two numbers A and B such that A and B are as close as possible (that is, there is no other choice A' and B' such that |A' - B'| < |A - B|). Assume we chose A > B. All we have to do is put A - 1 lines along the long side of the rectangle, and B - 1 lines along the short side.
For example: n = 4, A = 2 and B = 2 is optimal, so you put A - 1 = 1 and B - 1 = 1 lines along each side of the rectangle (as in your GOOD column for n = 4).
For example: n = 21, A = 7 and B = 3 is optional, so you'd put 6 lines along the long edge of the rectangle and 2 lines along the short edge, equally spaced:
_ _ _ _ _ _ _
|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|
|_|_|_|_|_|_|_|
Of course, for prime values of N, you are not going to get a very nice solution, but then there is no nice solution in that case. In such cases - where A and B are very very different and the rectangle's dimensions are not similarly different - you might want to choose another solution that doesn't require all rectangles have the same side lengths. You could do better by allowing 2 or 3 kinds of rectangles, or more, into the solution, for instance.

What would the conversion of this from EBNF to BNF be? Also, what is the leftmost derivation?

I need to convert this from EBNF to BNF.
<statement> ::= <ident> = <expr>
<statement> ::= IF <expr> THEN <statement> [ ELSE <statement> ] END
<statement> ::= WHILE <expr> DO <statement> END
<statement> ::= BEGIN <statement> {; <statement>} END
Also, I'm stuck on this one:
E -> E+T | E-T | T
T -> T*F | T/F | F
F -> (E) | VAR | INT
VAR -> a | b | c
INT -> 0 | 1 | 2| 3 | 4| 5 | 6 | 7 | 8 | 9
After modifying the grammer to add a ^ operator, What is the leftmost derivation that your grammar assigns to the expression a^2^b*(c+1)? You may find it convenient to sketch the parse tree for this expression first, and then figure out the leftmost derivation from that.
I added G -> F^G | G and then got G 2 G b E as my answer but am not sure if that is correct.

Neo4j shortest path with rels in both directions

I have a graph set up with the function...
create (a:station {name:"a"}),
(b:station {name:"b"}),
(c:station {name:"c"}),
(d:station {name:"d"}),
(e:station {name:"e"}),
(f:station {name:"f"}),
(a)-[:CONNECTS_TO {time:8}]->(b),
(a)-[:CONNECTS_TO {time:4}]->(c),
(a)-[:CONNECTS_TO {time:10}]->(d),
(b)-[:CONNECTS_TO {time:3}]->(c),
(b)-[:CONNECTS_TO {time:9}]->(e),
(c)-[:CONNECTS_TO {time:40}]->(f),
(d)-[:CONNECTS_TO {time:5}]->(e),
(e)-[:CONNECTS_TO {time:3}]->(f)
and using the function
START startStation=node:node_auto_index(name = "a"), endStation=node:node_auto_index(name = "f")
MATCH p =(startStation)-[r*]->(endStation)
WITH extract(x IN rels(p)| x.time) AS Times, length(p) AS `Number of Stops`, reduce(totalTime = 0, x IN rels(p)| totalTime + x.time) AS `Total Time`, extract(x IN nodes(p)| x.name) AS Route
RETURN Route, Times, `Total Time`, `Number of Stops`
ORDER BY `Total Time`
and it returns the results...
+-------------------------------------------------------------+
| Route | Times | Total Time | Number of Stops |
+-------------------------------------------------------------+
| ["a","d","e","f"] | [10,5,3] | 18 | 3 |
| ["a","b","e","f"] | [8,9,3] | 20 | 3 |
| ["a","c","f"] | [4,40] | 44 | 2 |
| ["a","b","c","f"] | [8,3,40] | 51 | 3 |
+-------------------------------------------------------------+
Which is fine except because it is a directed graph and there is no path from c -> b it doesn't return (for instance) [a, c, b, e, f] which is a valid path of length 4.
So, if I add the inverse paths...
MATCH (START)-[r:CONNECTS_TO]->(END )
CREATE UNIQUE (START)<-[:CONNECTS_TO { time:r.time }]-(END )
And run the query again I get... (for paths length 1..4)...
+---------------------------------------------------------------------+
| Route | Times | Total Time | Number of Stops |
+---------------------------------------------------------------------+
| ["a","d","e","f"] | [10,5,3] | 18 | 3 |
| ["a","c","b","e","f"] | [4,3,9,3] | 19 | 4 |
| ["a","b","e","f"] | [8,9,3] | 20 | 3 |
| ["a","c","f"] | [4,40] | 44 | 2 |
| ["a","c","b","c","f"] | [4,3,3,40] | 50 | 4 |
| ["a","c","f","e","f"] | [4,40,3,3] | 50 | 4 |
| ["a","b","c","f"] | [8,3,40] | 51 | 3 |
| ["a","b","a","c","f"] | [8,8,4,40] | 60 | 4 |
| ["a","d","a","c","f"] | [10,10,4,40] | 64 | 4 |
+---------------------------------------------------------------------+
This does include the path [a, c, b, e, f] but it also include [a, c, b, c, f] which uses c twice and [a, c, f, e, f] which uses f (the destination?!) twice.
Is there a way of filtering the paths so each path only includes the same node once?
You could do a filtering after the fact, but it might not be the fastest thing.
Something like this:
START startStation=node:node_auto_index(name = "a"), endStation=node:node_auto_index(name = "f")
MATCH p = (startStation)-[r*..4]->(endStation)
WHERE length(reduce (a=[startStation], n IN nodes(p) | CASE WHEN n IN a THEN a ELSE a + n END)) = length(nodes(p))
WITH extract(x IN rels(p)| x.time) AS Times, length(p) AS `Number of Stops`, reduce(totalTime = 0, x IN rels(p)| totalTime + x.time) AS `Total Time`, extract(x IN nodes(p)| x.name) AS Route
RETURN Route, Times, `Total Time`, `Number of Stops`
ORDER BY `Total Time`
I created a GraphGist with your question and answers in as an executable, live document.
See here: Neo4j shortest path with rels in both directions

Breadth first search, and A* search in a graph?

I understand how to use a breadth first search and A* in a tree structure, but given the following graph, how would it be implemented? In other words, how would the search traverse the graph? S is the start state
Graph Here
It's exactly the same as doing it in a tree. You just need to somehow keep track of which nodes you've already visited so that you don't end up going in circles.
Basically, you treat a graph the same way that you'd treat a tree, except you need to keep track of nodes you've already visited. That's fine for BFS. On top of that, in the case of A*, consider what you'd do when you revisit a node but have found a cheaper route to it.
Paint the graph - Recursively search each node and mark the nodes you visited as dirty. Only recurse when the graph is not dirty.
If memory is not an issue, copy the graph and instead of marking the nodes, remove them from the copy graph.
It's weighted graph. Do you want to find shortest paths or just traverse it?
If you want just traversing, here it is:
1) there is only S in the queue
2) we are adding C and A in the queue, only they are reachable from S directly (with one edge)
3) D, G2 - from C
4) B, E - from A
5) G1 - from D (G2 is already in the queue)
6) there no outgoing edge from G2
7) there's no adjacent nodes of B which aren't already in the queue
So here's the order how nodes where added in the queue: S, C, A, D, G2, B, E, G1
I don't know how helpful you will find this, but here's a complete solution coded in the functional language J (available for free from jsoftware.com).
First, it's probably simplest to work directly from a representation of the graph you show in your picture. I represent this as a (# nodes) x (# nodes) table with a number at (i,j) for the value of the link between node-i and node-j. Also, along the diagonal I've put the number associated with each node itself.
So, I enter this as follows - don't worry too much about the unfamiliar notation, you'll soon see what the result looks like:
grph=: <;.1&>TAB,&.><;._2 ] 0 : 0
A B C D E G1 G2 S
A 2 1 8 2
B 1 1 1 4 2
C 3 1 5
D 1 5 2
E 6 9 7
G1 0
G2 0
S 2 3 5
)
So, I've assigned the variable "grph" as a 9x9 table where the first row and first column are the labels "A"-"E", "G1", "G2", and "S"; I've used tabs to delimit items so this could be cut-and-pasted to or from a spreadsheet as needed.
Now, I'll check the size of my table and display it:
$grph
9 9
grph
+---+--+--+--+--+--+---+---+--+
| | A| B| C| D| E| G1| G2| S|
+---+--+--+--+--+--+---+---+--+
| A | 2| 1| | | 8| | | 2|
+---+--+--+--+--+--+---+---+--+
| B | | 1| 1| 1| | 4 | | 2|
+---+--+--+--+--+--+---+---+--+
| C | | 3| 1| | | | 5 | |
+---+--+--+--+--+--+---+---+--+
| D | | | | 1| | 5 | 2 | |
+---+--+--+--+--+--+---+---+--+
| E | | | | | 6| 9 | 7 | |
+---+--+--+--+--+--+---+---+--+
| G1| | | | | | 0 | | |
+---+--+--+--+--+--+---+---+--+
| G2| | | | | | | 0 | |
+---+--+--+--+--+--+---+---+--+
| S | 2| | 3| | | | | 5|
+---+--+--+--+--+--+---+---+--+
It looks OK and it's easy to compare this to the picture of the graph to check it.
Now I'll drop the first row and column so we're left only with numbers (as boxed literals),
and remove any extraneous tab characters.
grn=. TAB-.~&.>}.}."1 grph
You can see I assign this result to the variable "grn".
Next, I'll replace any empty cells with "_" - which represents infinity - then convert the literals to numeric representation (re-assigning the result to the same name "grn"):
grn=. ".&>(0=#&>grn)}grn,:<'_'
Finally, I'll move the last column and row to the beginning since this is the one for "S" and it's supposed to be first. I'll also display the result to confirm that it looks correct.
]grn=. _1|."1]_1|.grn NB. "S" goes first.
5 2 _ 3 _ _ _ _
2 2 1 _ _ 8 _ _
2 _ 1 1 1 _ 4 _
_ _ 3 1 _ _ _ 5
_ _ _ _ 1 _ 5 2
_ _ _ _ _ 6 9 7
_ _ _ _ _ _ 0 _
_ _ _ _ _ _ _ 0
So, now that I have a simple 8x8 table of numbers representing the graph, it's a simple matter to traverse it.
Here's a simple J function, called "traverseGraph", to read this table, traverse the graph it represents, and return two results: the indexes (0-based origin) of the nodes visited, and the values of the points and edges in the order visited.
traverseGraph=: 3 : 0
pts=. ,_-.~,ix{y [ nxt=. ix=. ,0
while. 0~:#nxt=. ~.ix-.~;([:I._~:])&.><"1 nxt{y do.
ix=. ix,nxt [ pts=. pts,_-.~,nxt{y
end.
ix;pts
)
We start by initializing three variables: the list of indexes "ix" (to zero, since we want to begin in the zeroth row of the table), a variable "nxt" to point to the next group of nodes (initially the same as the starting node), and the list of point values "pts" (starting as the 0th row of our input table, known internally as "y", with all the infinite values removed.)
In the "while." loop, we continue as long as there's more than zero "nxt" values resulting from pulling the current row out of the table and removing any nodes (in "ix") we've already visited. Inside the loop, we accumulate the next set of indexes onto the end of "nxt" and the point values onto "pts". At the end, we return the indexes and point values as our (two-element) result.
We run it like this - it displays the result by default:
traverseGraph grn
+---------------+---------------------------------------------+
|0 1 3 2 5 7 4 6|5 2 3 2 2 1 8 3 1 5 2 1 1 1 4 6 9 7 0 1 5 2 0|
+---------------+---------------------------------------------+
So, the first box contains the indexes starting with "0" and ending with "6". The second boxed item is the vector of point values in the order we accumulated them. I don't know what you do with these, so I just show them.
We can use the indexes to display the node names like this:
0 1 3 2 5 7 4 6{(<"0'SABCDE'),'G1';'G2'
+-+-+-+-+-+--+-+--+
|S|A|C|B|E|G2|D|G1|
+-+-+-+-+-+--+-+--+
I don't know how useful you'll find this but it does outline a simple solution to your problem.

Resources