How to run a query on Array of object? - arrays

I often find my self trying to calculate closest point in an Array of points, or lowest Sprite in array of sprites .. etc
For example: to calculate the lowest point in an Array:
var lowestPoint:Point;
var lowestY:Float= Math.POSITIVE_INFINITY;
for (point in points)
if (point.y < lowestY)
{
lowestPoint= point;
lowestY.y= point.y;
}
So, isn't there better way to calculate this? may be a library?

The question is: Why are you writing this often?
If the real problem is that you don't want to rewrite the same code over and over, use a function.
If you're just looking for a more simple way to write this, try using Lambda.fold, you can read how it works Here
This will find the lowest point in points.
Note that it does make the assumption that at least one point is in the array.
var lowest = Lambda.fold(points, function(a, b) { return if (a.y < b.y) a else b; }, points[0])
The combination of using Lambda.map, Lambda.filter, and Lambda.reduce will provide you with a powerful query interface, but remember that implementing your function with a for loop will provide better performance than by using Lambda.fold.
You could clean up for loop code by doing:
var lowestPoint:Point = points[0];
for (point in points)
if (point.y < lowestPoint.y)
{
lowestPoint = point;
}
(again, this assumes that there is at least one point in points)

Related

Matlab: Difference bettween two different sized arrays

Is it possible to find the difference beetwen two arrays of different size?
My problem is that I have two arrays, that scaled are pretty similar and I need the error in each point.
The data look like this:-
Yaw data is much bigger than Yaw Ref.
You could take a very naive approach and simply pad each element of the reference array. That is fairly simple to do:
n = length(yaw)/length(yaw_ref);
yaw_ref_pad = zeros(length(yaw), 1);
for j = 1:length(yaw_ref)-1
yaw_ref_pad((n*j):(n*(j+1)) = yaw_ref(j);
end
You could also do something more adaptive, which may or may not be what you want. This approach uses the derivatives to determine where the padded reference should switch. This might be considered a bit circular, since your system looks like an overdamped PID system and this uses the output to seed the input.
yaw_ref_pad = zeros(length(yaw), 1);
[x, peaks] = findpeaks(diff(yaw));
for j = 1:length(peaks)-1
yaw_ref_pad(peaks(j):peaks(j+1)) = yaw_ref(j);
end
Either way, after filling yaw_ref_pad, your result is simply
error = yaw_ref_pad - yaw;

Find all building lat/long coords within a polygon

I have a polygon of lat/long pairs. I want to somehow build a list of addresses and after research I know this is going to be extremely difficult. I know there is not a way to automatically do this from any service.
From what I understand I could try to build a database with addresses and lat/long coordinates and match them against all possible points within the polygon. That would be great if I could easily find free data like this. The closest thing I can find is http://openaddresses.io which is still very incomplete and I need the whole US.
Is there a service (software, online, API) that can at least find all buildings in a polygon? I could at least then reverse geocode the point and get the address out if it's valid.
Can anyone suggest anything to help achieve my end goal of finding all addresses in a polygon? The only requirement really is it needs to be free.
If you have the resorces, you can program it yourself. Just use a formula that calculates if a given point is inside of a polygon and adapt it to work with your coordinates.
I had a similar problem. My app needed to check the neighborhood in wich a latLgn was included. The Wikimapia API returned me all neighborhoods within a radius, but not wich one had the coordinate within it´s boundaries.
I had to adapt the function myself, because the API didn´t do it (although it provided me with all the data necessary to extract the information).
Here´s the function I made. (in C#)
public bool NoPoligono(PointCollection poligono)
{
bool result = false;
Point local = new Point(double.Parse(this.Lng, CultureInfo.InvariantCulture), double.Parse(this.Lat, CultureInfo.InvariantCulture));
int j = poligono.Count - 1;
for (int i = 0; i < poligono.Count(); i++)
{
if (Math.Abs(poligono[i].Y) < Math.Abs(local.Y) && Math.Abs(poligono[j].Y) >= Math.Abs(local.Y) || Math.Abs(poligono[j].Y) < Math.Abs(local.Y) && Math.Abs(poligono[i].Y) >= Math.Abs(local.Y))
{
if (Math.Abs(poligono[i].X) + (Math.Abs(local.Y) - Math.Abs(poligono[i].Y)) / (Math.Abs(poligono[j].Y) - Math.Abs(poligono[i].Y)) * (Math.Abs(poligono[j].X) - Math.Abs(poligono[i].X)) < Math.Abs(local.X))
result = !result;
}
j = i;
}
return result;
}
It belong to a class named Ponto, that represented a coordinate in my application´s logic. It served to validate if it was inside of the polygon (PointCollection) passed as a parameter.

As3 Best solution about arrays

Let me cut to the main issue, I have a grid which is 50 by 50. And I need a way of having a true or false variable for each cell in the grid and the default value would be false, every time the method is called.
I need the array so I can see which cells I have visited so I don't need to revisited them for my path finding system that I'm working on .
But currently I have a double array[] [] which I need to loop every time I use this method. (up to 3 times a second but mostly never) which means looping 2500 value. Which doesn't sound very good. What would be the best solution, is this the best solution or am I missing something stupid.
Hope you can help and point me into the right direction.
Another possible improvement is using a single-dimensional vector, maybe wrapped into a class, that will contain 2500 elements and its indexes would mean (width*50+height). Like this:
private var _visited:Vector.<Boolean>;
function checkVisited(x:int,y:int):Boolean {
return _visited(x*50+y); // x and y are in 0-49 range
}
Vectors can be two-dimensional should you need them, you declare vector of vectors like this:
var _visited:Vector.<Vector.<Boolean>>;
Initialize with pushing the filled Vector.<Boolean> once, then just change the elements as you do with a normal array.
The main advantage of vectors is that they are solid, that is, if there are 50 elements in a vector, you are sure that there exists a value at any index from 0 to 49 (even if null, or NaN in case of Numbers), this also makes internal processing of vectors easier, as the Flash engine can calculate proper memory location by just using the index and the link to the vector, which is faster than first referencing the array about whether there is a value at that index, if yes, get its memory location, then reference.
From my experience of making tile based games with different grids I usually have a Tile class, that will contain all your necessary values, most typical would be:
posX:int
posY:int
isChecked:Boolean
You can add as many as you need for your app.
Then I have a Grid class that will create you grid and have some useful methods like giving neighbor tiles.
In the Grid class I make the grid this way:
public var tileLineArray:Vector.<Tile>;
public var tile2dArray:Vector.<Vector.<Tile>>;
public function makeGrid(w:int, h:int):void
{
tileLineArray = new Vector.<Tile>();
tile2dArray = new Vector.<Vector.<Tile>>();
for (var i:int = 0; i < gridWidth; i++)
{
var rowArray:Vector.<Tile> = new Vector.<Tile>();
for (var j:int = 0; j < gridHeight; j++)
{
var t:Tile = new Tile();
t.posX = i;
t.posY = j;
tileLineArray.push(t);
rowArray.push(t);
}
tile2dArray.push(rowArray);
}
}
What it will give you is that you can access tiles in a single line to by coordinates x,y;
var myTile:Tile = tileLineArray[lineID];
var myTile:Tile = tile2dArray[targetX][targetY];
I use Vectors in this example as they outperform Arrays and you keep the type of the stored object intact.
It is not a problem for Flash to loop through the array; if you want improve performance, break the loop if you've done all what you wanted with it, continue the loop if the tile does not meet the requirements and you don't need to process it.
Also, having a 2d array can improve performance, since you can process only the area of the array that you need.
One more advice is not to be afraid to make X more smaller arrays to store some data from the bigger array and loop trough the small ones. As the data of the arrays is not a primitive (int, uint etc.) but a Class, it will hold a pointer/reference to the object, so you're not actually making copies of the objects every time.

Algorithm for 3D dice generation

I am making a simple test application in C that is supposed to generate three dimensional dice. I am going to use OpenGL to do the actual drawing, but I cannot figure out how to actually generate the vertices. Of course, the whole point of this test was to see if my algorithm worked, but I found a major logic error that I cannot fix. Can somebody please point me to an article, website, or something that explains the concept? If not, although I would prefer to do the actual implementation myself, the C code is acceptable.
Basically, this is what I did before I forgot what I was doing for the algorithm:
void calculateVertices(int sides) {
BOOL isDone = FALSE;
int vectorsPerSide = 3;
VDVector3f *vertices = malloc((sizeof(VDVector3f) * (sides + 1)));
VDVector3f *normals = malloc((sizeof(VDVector3f) * (sides + 1)));
while (!isDone) {
// Start by positioning the first vertex.
vertices[0] = VDVector3fMake(0.0, 0.0, 1.0);
for (int index = 1; index <= sides; index ++) {
}
// Not a match, increase the number of vectors
vectorsPerSide ++;
}
}
Basically, it loops until a match is found. This sounds inefficient to me, but I had no other idea as to how to do this. The first vertex will actually be removed from the array at the end; I was going to use it to create the first side, which would have been used to properly position the others.
My main goal here is to be able to pass number (like 30) to it, and have it set the vertices automatically. I will not have protections against making one sided and two sided dice, because I have something special in mind. I will have those vertices entered elsewhere.
Thanks in advance for the help!
By the way, I have an algorithm that can normalize the completed vertex array. You don't have to bother helping with that.
I don't think this is possible to generalize this. How, for example would you make a fair 5 or 9 sided die? I don't think I have ever seen such a thing. A quick search on wikipedia suggests platonic solids may be what you are after. http://en.wikipedia.org/wiki/Platonic_solid

Storage of 2d data at irregular rates

This is for a Terrain Generation and rendering program.
I have a loop that looks like this:
x = -MAX_SIGHT_DISTANCE;
y = -MAX_SIGHT_WIDTH;
while (x < MAX_SIGHT_DISTANCE)
{
while (y < MAX_SIGHT_WIDTH)
{
value = noise2d(x+camera.x, y+camera.y);
if (pointInFrustum(x-camera.x, y-camera.y, value, direction, FOV, MAX_SIGHT_DISTANCE) == 1)
{
// TODO: STORE VALUE TO AN ARRAY....SOMEHOW...
}
dz = value-camera.z;
distance = sqrt(x*x + y*y + (dz)*(dz));
x += DISTANCE_FUNCTION(distance);
y += DISTANCE_FUNCTION(distance);
}
}
It's supposed to find a semi-random height value at different resolutions: Much higher resolution up close, and lower resolution farther away.
Later,
for x
{
glBegin(GL_TRIANGLE_STRIP);
for y
{
glVertex(x, y);
glVertex(x+1, y);
}
glEnd();
}
This is supposed to be the rendering code (in pseudo-code, of course).
I have to specify the coordinates of each point. I'd really like to use triangle strips here, so I need to have all points in one strip following each other.
Comes my question: How do I store these points? In python I'd create a list, and then just render everything in the list.
Problem is this is in C, arrays aren't dynamic. So I need a size. How can I know that size? How can I loop through it in an intelligent way (since it has variable widths)? And how can I prevent stuff like the end of one row joining with the beginning of another row?
Or am I doing the whole thing wrong?
How about you use a dynamic data structure like a stack of linked-lists?
Each linked list would hold the points for each triangle strip.
The stack would contain the a linked list for each triange strip.
Linked list would suit your problem because you dont really need to index your elements.

Resources