algorithm for generating grid of points - javascript

I've got array of coordinates in following schema (x,y):
array = [[1,2],[1,5],[1,1],[2,2],[2,5],[2,1]]
I would like to do some process to achieve effect:
array1 = [[[1,2],[1,5],[1,1]],[[2,2],[2,5],[2,1]]]; array2 = [[[2,2],[2,5],[2,1]]]
and
array1a = [[[1,2],[2,2]]]; array2a = [[[1,5],[2,5]]]; array3a=[[[1,1],[2,1]]]
in other words I would like to get coordinates of all parallel and perpendicular lines.
I've came up with two double loops (one by x, and another by y) but maybe there is another faster(better) way
--
pseudo code:
for (var i = 0; i < length; i++) {
for (var j = 0; j < length2; j++) {
var x = points[i][j][0];
var y = points[i][j][1];
};
};
for (var i = 0; i < length2; i++) {
for (var j = 0; j < length; j++) {
var x = points[i][j][0] ;
var y = points[i][j][1] ;
};
};
EDIT
OK, here's the situation:
I've got this kind of rectangle, I've got coordinates of points (red mark) as array:
array = [[1,2],[1,5],[1,1],[2,2],[2,5],[2,1]]
and I want to make antoher array which will be like this:
array1 = [[[1,2],[1,5],[1,1]],[[2,2],[2,5],[2,1]]]
in above array there are coordinates of points thats one of green line containts. Those lines are parallel or perpendicular lines to sides of rectangle.

If you sort the points by X coordinate and then group them together by X coordinate, each group is a set of points on a vertical line.
Similarly, if you sort the points by Y coordinate and then group them together by Y coordinate, each group is a set of points on a horizontal line.
If this sounds simplistic, I apologize. But your initial description and the added diagram with your further explanation leads me to believe that it's what you're asking for.

Related

Highlighting areas in leaflet using markers?

I'm trying to highlight an area surrounded by node markers. Currently, I'm doing this by creating polygons. Each node in the database is assigned a polygon ID and those with the same IDs are pushed into the array to act as the vertices of the same polygon.
However, as the data is retrieved from the database in the order they were entered into the table, polygon self-intersection happens like in the picture below:
Self-intersection in polygon
I've tried to sort the vertices by starting from the first and looking for the nearest node, then from that node I look for the nearest again and so on. It worked for some, but some cases still have self-intersection like this:
Self-intersection after sorting using nearest node
Is there any leaflet plugin that will allow me to highlight an area surrounded by nodes? Below is my code for sorting the vertices. All vertices of the same polygon ID are first pushed into the array "arr" before being sorted.
var i;
var j;
var flag = 0;
var sortedarray = [];
var finalarray = [];
for (j = 0; j < initiallength - 1; j++) {
if (flag == 0) {
finalarray.push(arr[0]);
arr.splice(0, 1);
flag++;
}
sortedarray = [];
for (i = 0; i < arr.length; i++) {
var x = L.GeometryUtil.distance(map, finalarray[j], arr[i]);
sortedarray.push(x);
}
var smallest = Math.min.apply(Math, sortedarray);
var x = sortedarray.indexOf(smallest);
finalarray.push(arr[x]);
arr.splice(x, 1);
}
var polygon = L.polygon(finalarray).setStyle(myStyle).addTo(map);

How can one maintain multiple lists of array indexes whose values are used by a function that outputs an array of results?

Building a sparsely-connected neural network from scratch in Javascript.
I have a 2d array. Each object in the second dimension (array[x][y]) holds 2 arrays, starts:[] and ends:[]. Each object in these arrays holds value and weight. Ends are incoming connections. Starts are outgoing connections. So, when a "synapse" is created, it is stored in the starts array of the pre-synaptic neuron and the ends array of the post-synaptic neuron. (Neurons aren't actual objects, just cells in the array).
My current predict function:
predict(array, values){
var result = [];
if(values.length <= array[0].length){
for(var a = 0; a < values.length; a++){
for(var b = 0; b < array[0][a].starts.length; b++){
array[0][a].starts[b].value = values[a];
}
}
for(var c = 0; c < array.length; c++){
for(var d = 0; d < array[c].length; d++){
var sum = 0;
for(var e = 0; e < array[c][d].ends.length; e++){
sum += array[c][d].ends[e].weight * array[c][d].ends[e].value;
}
}
for(var f = 0; f < array[c][d].starts[f].length; f++){
array[c][d].starts[f].value = util.sigmoid(sum);
}
}
for(var g = 0; g < array[array.length-1].length; g++){
var sum = 0;
for(var h = 0; h < array[array.length-1][g].ends.length; h++){
sum += util.sigmoid(array[array.length-1][g].ends[h].weight * array[array.length-1][g].ends[h].value;
}
result.push(util.sigmoid(sum);
}
}
else{
log.add("### PREDICT ### Not enough input neurons. Afferent growth signal.");
}
return result;
}
This works fine if I'm looking for a boolean output (0 or 1). I, however, have multiple outputs and I only want to back-propagate through the chain of weights that is relevant to each output. I'm aware that the same weight will appear in multiple chains - this is something that I want to test. I've read somewhere that actual back-propagation is inefficient, but I think that it's required here.
I would like to avoid looping through the entire network again to find the chain if possible. Also, if you see anything wrong with my predict function, please let me know!
For some context, I've made a little game. The game has a player box and a target box. I would like to input playerX, playerY, targetX, and targetY. Outputs are Down, Left, Up, and Right (directions the player can move). So, if input is 1, 1, 5, 5 ... and the "Up" output node is "heaviest", I want to correct the weights in the chain that led to the Up output and reinforce the weights in the chain that led to the Down output.

How can sort an array by comparing to n-1

I am facing this problem in javascript : I have lot of random map coordinates(latitude,longitude) stored in an array like
var coordinates = [
[64,22],[55,33],[28,35],[...,...]
]
I also have a method that calculates distance between two of those points
like
var getDistance =function(point1,point2)
{
return L.dist(point1,point2);//leaflet method
}
then here is my problem :
how to sort my array to have the distance sorted by closest from first coordinate then closest to second, then closest to third, then closest to fourth... ? anyone have a solution for this... im lost :(
edit 1 :
I tried to resolve the problem with a nested for loop ... but the results seems to be wrong.
var cloestIndex = 1;
var closestDistance = 99999999;
for (var i = 0; i < coords.length; i++) {
for (var j = i + 1; j < coords.length; j++) {
if ((Map().distance(coords[i], coords[j]) < closestDistance) &&
(Map().distance(coords[i], coords[j]) != 0){
closestDistance = (Map().distance(coords[i], coords[j]));
closestIndex = j;
}
}
console.log("CD", closestDistance + "(" + closestIndex + ")");
finalArray.push(coords[closestIndex]);
coords.splice(closestIndex, 0);
cloestDistance = 9999999;
}
how to sort my array to have the distance sorted by cloest from first coordinate then cloest to second, then cloest to third, then cloest to fourth... ?
That's not called a "sort" because "closest distance to previous" is not an ordering. Sorting them by distance to a single point would be.
So to do what you want, you really should literally follow your description and first put the first coordinate in the result array, then find the closest-to-that in the rest and add it, then find the closest-to-that and so on until no more coordinates are left.

TypeError: matrix[y].push is not a function when trying to create 2d array with javascript

I'm trying to create an array that represents a matrix (256×256), full of zeroes that I will later change with functions. I tried by using for loops and the .push function, but something is wrong and I can't figure out what's happening. Here's my code
var matrix = [];
for (x = 0; x < 255; x++) {
matrix.push([]);
for (y = 0; y < 255; y++) {
matrix[y].push([0]);
}
}
What I want this to do, is push an empty array into matrix, fill it with 256 zeroes, and then repeat that 255 more times.
The problem is that you're only pushing in one array then trying to fill in 255 of them. Your code should look more like this (assuming you want 256 zeroes instead of 255)
var matrix = [];
for (var x = 0; x < 256; x++) {
matrix.push([]);
for (var y = 0; y < 256; y++) {
matrix[x].push(0);
}
}

How can I group and animate individual rows on this raphael canvas?

The following code creates a 10 x 15 grid of 40 pixel squares. I would like to be able to group the squares into rows for animating later. Specifically, I want to animate the rows dropping to the bottom and then apply animated matrix transforms to them. Eventually they will just replicate the same grid at a new location.
<script type="text/javascript">
var squares = [];
var paperHeight = 600;
var paperWidth = 400;
var squareSize = 40;
var cols = paperWidth / squareSize;
var rows = paperHeight / squareSize;
var paper = Raphael($("#grid-test")[0],paperWidth,paperHeight);
for (var i = 0; i < cols; i++) {
// Begin loop for rows
for (var j = 0; j < rows; j++) {
// Scaling up to draw a rectangle at (x,y)
var x = i * squareSize;
var y = j * squareSize;
// For every column and row, a square is drawn at an (x,y) location
paper.rect(x,y,squareSize,squareSize);
}
}
</script>
You can keep track of the elements with a 2 dimensional array [row][column]. Then iterate over each column in a row to get the appropriate elements; then just animate them. Note that you need to swap i/j when bullding; currently you're building [column][row].
http://jsfiddle.net/7ncHM/
var rowsArr = [];
for (var i = 0; i < cols; i++) {
// Begin loop for rows
rowsArr[i] = [];
for (var j = 0; j < rows; j++) {
// Scaling up to draw a rectangle at (x,y)
var x = j * squareSize; // swap i/j
var y = i * squareSize;
// For every column and row, a square is drawn at an (x,y) location
rowsArr[i][j] = paper.rect(x,y,squareSize,squareSize);
// draw and store directly, isn't that elegant? :)
}
}
function animateRow(i) {
var row = rowsArr[i];
for(var j = 0; j < row.length; j++) { // iterate elements in row
row[j].animate({y: 400}, 2000);
}
}
animateRow(2);
You'll have difficulty animating individual rows if you don't store a reference to the squares which make up a row (presumably this is what the unused squares[] array is for...)
Each time you call paper.rect assign the result to an element in squares[]
You could then have an function which takes a given row of your array and applies Raphael's .animate to each square - giving the impression of the whole row being animated.
http://raphaeljs.com/reference.html#Element.animate
In response to your comment - you can add elements to a Raphael set and then animate the set -eg...
var squares = [];
var paperHeight = 600;
var paperWidth = 400;
var squareSize = 40;
var cols = paperWidth / squareSize;
var rows = paperHeight / squareSize;
var paper = Raphael($("#grid-test")[0],paperWidth,paperHeight);
var rowSets = [];
// *** GRID CONSTRUCTION CODE STARTS ***///
// I have swapped the usage of i and j within the loop so that cells
// in a row are drawn consecutively.
// Previously, it was column cells which were drawn
// consecutively
for (var i = 0; i < rows; i++) {
//create a new set which will hold this row
rowSets[i] = paper.set();
squares[i] = [];
// Begin loop for cells in row
for (var j = 0; j < cols; j++) {
// Scaling up to draw a rectangle at (x,y)
var x = j * squareSize;
var y = i * squareSize;
// For every column and row, a square is drawn at an (x,y) location
var newRect = paper.rect(x,y,squareSize,squareSize);
// add the new cell to the row
rowSets[i].push(newRect);
squares[i][j] = newRect;
}
}
// *** GRID CONSTRUCTION CODE ENDS ***
squares[5][5].attr({fill : '#f00'}); // colour an individual cell
rowSets[6].attr({fill : '#00f'}); // colour an entire row
rowSets[6].animate({y : 10 * squareSize},400); // animate an enitre row
This means you could build a set of rows (and of columns) and animate them as individual units.
UPDATE
As a Raphael set is just a way of associating elements together to provide an easy way to apply operations en masse. It does not work in the same way as "Group" in Visio for example - ie They are still individual elements and will be animated independently.
Raphael will not find the centre of the set to do a rotation around. Each element of the set will be rotated around its own centre.
This problem can be solved by using a path to define an entire row at once as an SVG path. However this means that rows are now "one entity" and you will have difficulty addressing one cell, or one column. However you could switch the indiviual cells for a "row path" before performing the transform. The user/player hopefully wouldn't notice.
You can replace the // *** GRID CONSTRUCTION *** code with the following code to build rows as paths... (JSFiddle Demo)
//Build a row path - this path will be used as the basis of all the rows
var sPath = "lpw 0 l0 sq l-pw 0 l0 -sq " //outline of the whole row
for (var cell = 1; cell < cols; cell++){
sPath += "msq 0 l0 sq Z "; //insert an "upright" cell separator
};
sPath = sPath.replace(/sq/g,squareSize).replace(/pw/g,paperWidth);
//we have no 'for' loop for columns now as we are creating entire row .paths
for (var j = 0; j < rows; j++) {
//we apply the 'M' (Move) offset here to the beginning of the path
//This is simply to adjust the Y-offset of the start of the path
//ie to put the the path in a new row position
rowSets[j] = paper.path("M0 " + j * squareSize + sPath);
}

Categories

Resources