I've made an a-star implementation with euclidean heuristics, and it works, but makes unnecessary movements in some situations.
Here is the screenshot:
http://clip2net.com/s/6v2iU4
Path starts on the blue circle and, in theory, cell to the right of it has less F (movement cost + heuristic cost), so a-star takes it first, but it ends up in building not the shortest path.
How can i fix this?
Or a-star is supposed to work this way and i dont need to do anything?
My code: http://pastebin.com/02u33jY6 (h + cpp)
The problem with your algorithm is, your implementation returns the path, when it finds the destination in your openList.
The A* should terminate when destination node is in the closedList, not in the open list.
// check if there is dst node on the closed list
for ( unsigned int i = 0; i < closedList.size(); i++ )
{
if ( closedList.at( i ).getIndex() == dstTileIndex )
{
GSPathFinderNode* backtrackNode = &closedList.at( i );
resultPathNodes->insert( resultPathNodes->begin(), GSCommonMapNode( backtrackNode->getIndex(),
backtrackNode->getPosX(),
backtrackNode->getPosY() ) );
while ( 1 )
{
for ( unsigned int j = 0; j < closedList.size(); j++ )
{
if ( closedList.at( j ).getIndex() == backtrackNode->getParentNodeIndex() )
{
backtrackNode = &closedList.at( j );
resultPathNodes->insert( resultPathNodes->begin(), GSCommonMapNode( backtrackNode->getIndex(),
backtrackNode->getPosX(),
backtrackNode->getPosY() ) );
if ( backtrackNode->getIndex() == srcTileIndex )
return true; // success
}
}
}
}
}
Related
I´m trying to write a method to determine if a singly linked list of type string is a palindrome.
The idea is to copy the second half to a stack, then use an iterator to pop the elements of the stack and check that they are the same as the elements from 0 to around half of the singly linked list.
But my iterator method is throwing an infinite loop:
public static boolean isPalindrome(LinkedList<String> list, Stack<String> stack ) {
int halfList = (int) Math.ceil(list.size()/2); // we get half the list size, then round up in case it´s odd
// testing: System.out.println("half of size is " + halfList);`
// copy elements of SLL into the stack (push them in) after reaching the midpoint
int count = 0;
boolean isIt = true;
Iterator<String> itr = list.iterator();
Iterator<String> itr2 = list.iterator();
System.out.println("\n i print too! ");
// CHECK!! Node head = list.element();
// LOOP: traverse through SLL and add the second half to the stack (push)
// if even # of elements
if ( list.size() % 1 == 0 ) {
System.out.println("\n me too! ");
while ( itr.hasNext() ) {
String currentString = itr.next(); // this throws an exception in thread empty stack exception
count ++;
if ( count == halfList ) stack.push(list.element());
// THIS IS THE INFINITE LOOP
System.out.println("\n me three! ");
}
}
// else, if odd # of elements
else {
while ( itr.hasNext() ) {
count ++;
if ( count == halfList -1 ) stack.push(list.element());
}
}
// Now we compare the first half of the SLL to the stack (pop off elements)
// even
if ( list.size() % 1 == 0 ) {
while ( itr2.hasNext() ) {
count ++;
if ( count == halfList +1 ) break;
int compared = stack.pop().compareTo(list.element());
if ( compared != 0) isIt = false; // if when comparing the two elements, they aren´t similar, palindrome is false
}
}
// odd
else {
while ( itr2.hasNext() ) {
count ++;
if ( count == halfList ) break;
int compared = stack.pop().compareTo(list.element());
if ( compared != 0) isIt = false;
}
}
return isIt;
}
What am I doing wrong?
There are many issues:
list.size() % 1 == 0 is not checking whether the size is even. The correct check is % 2.
The stack exception cannot occur on the line where you put that comment. It occurs further down the code where you have stack.pop(). The reason for this exception is that you try to pop an element from a stack that has no more elements.
The infinite loop does not occur where you put that comment. It would occur in any of the other loops that you have further in the code: there you never call itr.next() or itr2.next(), and so you'll loop infinitely if you ever get there.
The stack never gets more than 1 value pushed unto it. This is because you have a strict equality condition that is only true once during the iteration. This is not what you want: you want half of the list to end up on the stack. This is also the reason why you get a stack error: the second half of your code expects there to be enough items on the stack.
push(list.element()) is always going to push the first list value to the stack, not the currently iterated one. This should be push(currentString).
count ++; is placed at an unintuitive place in your loops. It makes more sense if that line is moved to become the last statement in the loop.
The if ( count statements are all wrong. If you move count ++ to be the last statement, then this if should read if ( count >= halfList ) for the even case, and if ( count > halfList ) for the odd case. Of course, it would have been easier if halfList would have been adapted, so that you can deal equally with the odd and even case.
The second part of your code has not reset the counter, but continues with count ++. This will make that if ( count == halfList ) is never true, and so this is another reason why the stack.pop() will eventually raise an exception. Either you should reset the counter before you start that second half (with count = 0;) or, better, you should just check whether the stack is empty and then exit the loop.
The second half of your code does not need to make the distinction between odd or even.
Instead of setting isIt to false, it is better to just immediately exit the function with return false, as there is no further benefit to keep on iterating.
The function should not take the stack as an argument: you always want to start with an empty stack, so this should be a local variable, not a parameter.
There is no use in doing Math.ceil on a result that is already an int. Division results in an int when both arguments are int. So to round upwards, add 1 to it before dividing: (list.size()+1) / 2
Avoid code repetition
Most of these problems are evident when you debug your code. It is not so helpful to put print-lines with "I am here". Beter is to print values of your variables, or to step through your code with a good debugger, while inspecting your variables. If you had done that, you would have spotted yourself many of the issues listed above.
Here is a version of your code where the above issues have been resolved:
public static boolean isPalindrome(LinkedList<String> list) {
Stack<String> stack = new Stack<String>();
int halfList = (list.size()+1) / 2; // round upwards
Iterator<String> itr = list.iterator();
while (halfList-- > 0) itr.next(); // skip first half of list
while ( itr.hasNext() ) stack.push(itr.next()); // flush rest unto stack
Iterator<String> itr2 = list.iterator();
while ( itr2.hasNext() && !stack.empty()) { // check that stack is not empty
if (stack.pop().compareTo(itr2.next()) != 0) return false; // no need to continue
}
return true;
}
Lets say that on a 2d grid of 20x20, you have your character at position (5,5).
He is able to walk up to 4 tiles in his move. However, there may be obstacles blocking your path such as a wall.
Is there any efficient / easy way for calculating exactly which tiles he would be able to walk to without checking every single possible move ( e.g. move up 0 and right 0 then move up 0 and right 1 e.t.c )?
At the moment I'm calculating the places that you can walk through with this horrific thing:
int playerx = GridPane.getRowIndex(button);
int playery = GridPane.getColumnIndex(button);
int position = playery*8+playerx;
for (int i = 0; i < 5; i++)
{
for (int j = i-4; j < 5-i; j++)
{
try
{
int expectedCollumn = playerx+j;
int actualCollumn = ((position+i+j*8)-((position+i+j*8)%8))/8;
if(expectedCollumn==actualCollumn)
{
Button temp = (Button)gridPane.getChildren()
.get(position+i+j*8);
if (!temp.getText().equals("W") &&
!temp.getText().equals("P"))
{
temp.setText("T");
}
}
actualCollumn = ((position-i+j*8)-((position-i+j*8)%8))/8;
if(expectedCollumn==actualCollumn)
{
Button temp2 = (Button)
gridPane.getChildren().get(position-i+j*8);
if (!temp2.getText().equals("W") &&
!temp2.getText().equals("P"))
{
temp2.setText("T");
}
}
}
}
}
However, its showing as if you are able to walk to the otherside of the wall and I'm not sure how I would go about fixing this.
Many thanks in advance.
For path finding, you should figure out how this works:
https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
and then move on to A* or something more efficient.
Thanks to everyone that answered but the solution was simple
incase somehow someone finds this post and is interested it was a simple recursive call
void getReachableTiles(Tile current, Int stamina, List<Tile> visited, List<Tile> reachable) {
if (stamina <= 0) return;
List<Tile> neighbours = new List<>(current + up, current + left, ..)
for (Tile t in neighbours) {
if (!visited.contains(t)) {
visited.append(t);
if (!t.isWall()) {
reachable.append(t);
getReachableTiles(t, stamina - 1, visited, reachable);
}
}
}
}
Basically, I have the following clunky set of if statements in my code put in place to set any erroneous sensor readings to zero.
if (soil_moisture > 150 || soil_moisture <-100){
soil_moisture = 0;
}
if (soil_temperature > 150 || soil_temperature < -100 ){
soil_temperature = 0;
}
if (ambient_temperature > 150 || ambient_temperature < -100 ){
ambient_temperature = 0;
}
if (ambient_humidity > 150 || ambient_humidity <-100){
ambient_humidity = 0;
}
The way it's written seems redundant and inefficient, and I'm wondering, if there's a better way of doing this. Is it possible to create an array of the variables soil_temperature, soil_moisture, etc... and then loop through these variables in a for loop, which has the if statement embedded in it?
It is perfectly fine to do this although a loop would work too. Depending on your idea of "efficient". Is smaller code more efficient? Less writing or less instructions. For the first criteria, a loop would be far more efficient. For the second, this holds true also. Instruction per instruction though, this is a very efficient method.
You could use a helper routine to trim down the code:
boolean outOfBounds(int value, int low, int high)
{
if ( value < low || value > high )
return true;
else
return false;
}
Then in your code ...
if ( outOfBounds(soil_moisture, -100, 150) ) {
soil_moisture = 0;
}
if ( outOfBounds(soil_temperature, -100, 150) ) {
soil_temperature = 0;
}
// etc.
If your limits are always -100 and 150, then you could pass a pointer to the variable, and set it to zero within the routine:
void resetBounds(int *pvar)
{
if ( *pvar < -100 || *pvar > 150 ) {
*pvar = 0;
}
}
In your code:
resetBounds(&soil_moisture);
resetBounds(&soil_temperature);
// etc.
Pretty clean to my eyes.
As for your loop, yes, that would work, but it implies the overhead of copying the values into an array, and then looping over them, which distracts from what you're doing to them. It's almost like the mechaism gets in way of seeing what's happening. Just my opinion.
Have fun!
In my program I need to generate array with powers' (from 0 to 5) sum of numbers from 1 to 100,000.
So I tried to compile this code:
const enum size_t MAX_ARRAY_SIZE = 100_000 + 1;
const enum size_t MAX_POWER_SIZE = 5 + 1;
const enum power_sum = calc_power_sum();
// some unimportant code here
pure ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE] calc_power_sum() {
ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE] power_sum;
power_sum[0][] = 1;
foreach (x, ref element; power_sum[1]) {
element = x;
}
foreach (n; 2 .. MAX_POWER_SIZE) {
foreach (x, ref element; power_sum[n]) {
element = power_sum[n - 1][x] * power_sum[1][x];
}
}
foreach (ref power; power_sum) {
foreach (x; 1 .. MAX_ARRAY_SIZE) {
power[x] += power[x - 1]; // error appears here
}
}
return power_sum;
}
But compiler says:
$ dmd problem.d
problem.d(130): Error: array index 6 is out of bounds [1LU, 2LU, 3LU, 4LU, 5LU, 6LU][0 .. 6]
problem.d(15): called from here: calc_power_sum()
What am I doing wrong?
At first glance looks like you have simply misunderstood array dimension order. You have
ulong[MAX_POWER_SIZE][MAX_ARRAY_SIZE]
and your code assumes directly opposite
ulong[MAX_ARRAY_SIZE][MAX_POWER_SIZE]
Also I am afraid 100 000 may be a bit too much, after above mentioned fix I get an internal compiler error. Works for smaller MAX_ARRAY_SIZE values though.
As Mihail said, you should reverse the order of dimensions.
However, you most likely won't be able to do what you plan for all sizes because the maximum size of static array is limited in D ( http://dlang.org/arrays.html ) :
The total size of a static array cannot exceed 16Mb.
I have been implementing various forms of simple collision detection with varying results. I have a fairly good working version of collision detection, but there are some odd behaviors that I can't work out.
Just for a reference, i'm making a simple pong game, and trying to refine the collision. The problems I get are when the ball collides with the paddle on either the top or bottom side. In those cases, the ball hovers above (or below) the paddle and does not move. I'm guessing this is because of how i'm checking for collision and how i'm altering the movespeed of the ball.
I would like to implement a way I differentiate between top/bottom and left/right collision but this is the only method that works decently:
static void CheckCollision(PActor object1, PActor object2, PInput pinput)
{
if ( CheckObjectCollision( object1, object2 ) )
{
AdjustMoveSpeed( object1, object2, pinput );
}
}
static bool CheckObjectCollision(PActor object1, PActor object2)
{
int object1LeftBound = object1.position.x;
int object1RightBound = object1.position.x + object1.actorTextureXSize;
int object1TopBound = object1.position.y;
int object1BottomBound = object1.position.y + object1.actorTextureYSize;
int object2LeftBound = object2.position.x;
int object2RightBound = object2.position.x + object1.actorTextureXSize;
int object2TopBound = object2.position.y;
int object2BottomBound = object2.position.y + object2.actorTextureYSize;
if ( object1RightBound < object2LeftBound )
return false;
if ( object1LeftBound > object2RightBound )
return false;
if ( object1BottomBound < object2TopBound )
return false;
if ( object1TopBound > object2BottomBound )
return false;
return true;
}
I am guessing that the root of some of the problems i'm having is the function AdjustMoveSpeed, here it is:
static void AdjustMoveSpeed(PActor object1, PActor object2, PInput pinput)
{
PVector prevMouseLocation = pinput.GetPrevMouseLocation();
PVector currMouseLocation = pinput.GetCurrMouseLocation();
int currentMoveSpeed;
int nextMoveSpeed;
if (typeid(object1) == typeid(PBall))
{
object1.moveSpeed.x *= -1;
if ( typeid(object2) == typeid(PPlayer) )
{
currentMoveSpeed = object1.moveSpeed.y;
nextMoveSpeed = prevMouseLocation.y - currMouseLocation.y;
object1.moveSpeed.y = (prevMouseLocation.y - currMouseLocation.y) * -1;
}
else
{
if (object1.moveSpeed.y > 0)
object1.moveSpeed.y *= -1;
}
}
else if (typeid(object2) == typeid(PBall))
{
object2.moveSpeed.x *= -1;
if ( typeid(object1) == typeid(PPlayer) )
{
currentMoveSpeed = object1.moveSpeed.y;
nextMoveSpeed = prevMouseLocation.y - currMouseLocation.y;
object2.moveSpeed.y = (prevMouseLocation.y - currMouseLocation.y) * -1;
}
else
{
if (object2.moveSpeed.y > 0)
object2.moveSpeed.y *= -1;
}
}
}
What I was attempting to do with AdjustMoveSpeed, is first check to see which object is the ball, after this, multiply the x move speed by -1 to reverse its direction. After this, I check to see if the other object is a player, if so I set the y move speed to the difference between the previous mouse location and current mouse location. This is here to give the player option to change the balls y speed, or add spin.
I've tried checking for intersection between objects so that I can get a specific side, and the result is the ball just flying in the middle of the screen without actually hitting either paddle.
How do I properly check for collision detection on two objects that are squares?
How can I fix AdjustMoveSpeed so that it works properly with collision detection?
Lastly, how do I keep the momentum of the ball of its current speed is greater than the difference of the mouse location before and after the hit?
I've tried taking comparing the absolute value of currentMoveSpeed and nextMoveSpeed but then the ball doesn't change y speed. Something like this:
if ( abs(currentMoveSpeed) < abs(nextMoveSpeed )
object1.moveSpeed.y = (prevMouseLocation.y - currMouseLocation.y) * -1;
else
object1.moveSpeed.y *= -1
Pong is simple enough that, rather than moving the ball each frame and checking for a collision with a paddle, you can actually solve the equation for when the paddle and ball will collide - if that time is less than one frame, there is a collision.
This completely eliminates the issue of the ball moving so fast it moves through the paddle, an issue that plagues many pong-clones that use the naive method of collision-detection.
This solution is called continuous collision detection - see this answer for more information.
If the ball gets stuck on the paddle instead of bouncing it is probably because it keeps changing direction back and forth. The ball should only bounce if it is heading towards the paddle.
if (sgn(object1.moveSpeed.x) == sgn(object1.x - object2.x)) {
// Ball is already moving away from the paddle, don't bounce!
}
else {
// Ok to bounce!
object1.moveSpeed.x *= -1;
}