Implementation of A star Algorithm problem - algorithm

I am implementing an indoor map, using A star algorithm as its pathfinding algorithm. I came across a library in github and modified it into my floorplan, it works but now I'm trying to study how the user implemented A star algorithm and compared it to the algorithm's pseudocode. I can't seem to understand a part of his code.
Here is a snippet of the A star algorithm code below:
'
while(!openList.isEmpty()){
Node current=openList.poll();
visitedSet.add(current);
List<Node> neighbors=getAdj(current);
for(Node neighbor : neighbors){
if(!visitedSet.contains(neighbor)){
int g=neighbor.calculateG(startNode);
int h=neighbor.calculateH(endNode);
int tempf=g+h;
if(openList.contains(neighbor)){
int f=neighbor.getF();
if(f>tempf){
openList.remove(neighbor);
neighbor.setF(tempf);
neighbor.setH(h);
neighbor.setG(g);
neighbor.setParent(current);
openList.add(neighbor);
}
}
else {
neighbor.setF(tempf);
neighbor.setH(h);
neighbor.setG(g);
neighbor.setParent(current);
openList.add(neighbor);
}
}
if(neighbor.equals(endNode))
return true;
}
}
return false;
}
'
I understand every part of it except for this part right here
if(openList.contains(neighbor)){
int f=neighbor.getF();
if(f>tempf){
openList.remove(neighbor);
neighbor.setF(tempf);
neighbor.setH(h);
neighbor.setG(g);
neighbor.setParent(current);
openList.add(neighbor);
}
}
else {
neighbor.setF(tempf);
neighbor.setH(h);
neighbor.setG(g);
neighbor.setParent(current);
openList.add(neighbor);
}
}
My own explanation is this. If openList contains neighbor, then get the neighbor's F value (I don't know if the F value is also tempf), after getting the F value of the neighbor, compare if the F value is greater than the tempf value, again, I don't know the difference between F value and tempf. If the F value is greater then remove the neighbor from the openlist since it's already examined, set its F to tempf, which I don't know why, set Parent to current, again, I don't know why I should set the current node to parent. I kind of confused here, will someone explain what i'm missing? P.S. I'm a newbie in programming and in algorithms but i'm really trying, please be kind. Thank you.

Related

Solving "Check for BST" question on GeeksForGeeks but keep getting wrong answers but I can't seem to find the issue. Can someone please explain?

Trying to solve "Check for BST" question on GeeksForGeeks but I keep getting wrong errors but I don't think there is an issue with my code. Can someone please look at my code and explain? Thank you.
public class Solution
{
//Function to check whether a Binary Tree is BST or not.
static boolean answer = true;
boolean isBST(Node root)
{
// code here.
if(root==null) return false;
traverseLeft(root.left,root.data);
traverseRight(root.right,root.data);
return answer;
}
void traverseLeft(Node root, int val){
if(root == null) return;
if(root.data >= val){
answer = false;
return;
}
traverseLeft(root.left,root.data);
traverseRight(root.right,root.data);
}
void traverseRight(Node root, int val){
if(root == null) return;
if(root.data <= val){
answer = false;
return;
}
traverseLeft(root.left,root.data);
traverseRight(root.right,root.data);
}
}
There are several issues with your attempt:
result should not be a static variable. As a static variable, its value will survive across different test cases, never resetting to true after the first test has run, and thus possibly giving false negatives.
Instead you should let the recursive function return whether the BST is valid in that particular subtree. The caller should then capture that boolean result for both its children and perform a logical AND to determine what its own response will be: true if, and only when, it is true for both recursive calls for the children and its own value is within the acceptable range. In all other cases it should return false. That way you have no need for a more global variable.
It is not enough to compare a node's value with the value of its parent. For instance, your logic would consider the following tree a valid BST, but it isn't:
6
/
1
\
10
While the value 10 passes the test your code has (it is at least 1), it should also not be greater than 6. So a correct algorithm will pass two limiting values to the recursive calls: a lower limit and an upper limit.

How do I make this code for detecting palindrome in a Linked List cover all cases?

So, I was solving this problem of detecting a palindrome in a linked list. I came up with the following solution for it:
class Solution {
public boolean isPalindrome(ListNode head) {
ListNode temp=head;
boolean [] arr = new boolean[10];
int count=0;
if(head==null) return false;
while(temp!=null)
{
if(arr[temp.val]==false)
arr[temp.val]=true;
else
arr[temp.val]=false;
temp=temp.next;
}
for(int i=0;i<10;i++)
{
if(arr[i]==true)
count++;
}
if(count<2)return true;
return false;
}
Now, the logic behind this solution is correct as far as I can see but it fails for cases like this: [1,0,0], [4,0,0,0,0] etc. How do I overcome this? (Pls dont reply with a shorter method I want to know the reason behind why this fails for certain cases.)
First of all Welcome to StackOverflow!
Because of how simple this problem's solution can be I feel obligated to tell you that a solution with an auxiliary stack is not only easy to implement but also easy to understand. But since you asked why your code fails for certain cases I'll answer that question first. Your code in particular is counting the number of digits that have an odd count.
Although this seems to be what you are supposed to do to detect a palindrome notice that a linked list that looks like 1 -> 1 -> 0 -> 0 is also considered a palindrome under your code because the count is always going to be less than 0.
Your solution works for telling us if it is possible to create a palindrome given a set of digits. Suppose that the question was like "given a linked list tell me if you can rearrange it to create a palindrome" but it does not work for "is this linked list a palindrome".

How can i do that counting limits take too much time for big integers?

Im Vladimir Grygov and I have very serious problem.
In our work we now work on really hard algorithm, which using limits to cout the specific result.
Alghoritm is veary heavy and after two months of work we found really serious problem. Our team of analytics told me to solve this problem.
For the first I tell you the problem, which must be solve by limits:
We have veary much datas in the database. Ec INT_MAX.
For each this data we must sort them by the alghoritm to two groups and one must have red color interpretation and second must be blue.
The algorithm counts with ID field, which is some AUTO_INCREMENT value. For this value we check, if this value is eequal to 1. If yeas, this is red color data. If it is zero, this is blue data. If it is more. Then one, you must substract number 2 and check again.
We choose after big brainstorming method by for loop, but this was really slow for bigger number. So we wanted to remove cycle, and my colegue told me use recursion.
I did so. But... after implementation I had got unknown error for big integers and for example long long int and after him was wrote that: "Stack Overflow Exception"
From this I decided to write here, because IDE told me name of this page, so I think that here may be Answer.
Thank You so much. All of you.
After your comment I think I can solve it:
public bool isRed(long long val) {
if (val==1)
{return true; }
else if (val==0)
{ return false; }
else { return isRed(val - 2); }
}
Any halfway decent value for val will easily break this. There is just no way this could have worked with recursion. No CPU will support a stacktrace close to half long.MaxInt!
However there are some general issues with your code:
Right now this is the most needlesly complex "is the number even" check ever. Most people use Modulo to figure that out. if(val%2 == 0) return false; else return true;
the type long long seems off. Did you repeat the type? Did you mean to use BigInteger?
If the value you substract by is not static and it is not solveable via modulo, then there is no reason not to use a loop here.
public bool isRed (long long val){
for(;val >= 0; val = val -2){
if(value == 0)
return false;
}
return true;
}

Changing from recursion to iteration

I have my function that needs changing to iteration, because of very slow executing of it.
There are two recursive calls, depends which condition is true.
It's something like this:
(I have static array of classes outside function, let's say data)
void func(int a, int b, int c, int d) {
//something
//non-recursive
//here..
for (i=0; i<data.length; i++) {
if (!data[i].x) {
data[i].x = 1;
if (a == data[i].value1)
func(data[i].value2,b,c,d);
else if (a == data[i].value2)
func(data[i].value1,b,c,d);
data[i].x = 0;
}
}
}
!!
EDIT: Here is my algorithm: http://pastebin.com/F7UfzfHv
Function searches for every paths from one point to another in graph, but returns (to an array) only one path in which are only unique vertices.
!!
And I know that good way to manage that is to use stack... But I don't know how. Could someone give me a hint about it?
There is a good possibility that your function might be computing the same thing again and again, which in technical terms is called as overlapping sub-problems(if you are familiar with the dynamic programming then you might know). First try to identify whether that is the case or not. Since you haven't told anything about what function do and I can't tell the exact problem.
Also the thing you are talking about using a stack is not of great use since recursion uses a stack internally. Using external stack instead of internal is more error prone is not of great use.

Calculating paths in a graph

I have to make a method for making a list with all the paths in a graph.My graph has only one start node and one finish node. Each node has a list whith its children and other list whith its parents. I have to make another list containing all the paths (each of them in another list)
Any suggestion??
It depends on whether it is acyclic or not. Clearly a cycle will result in infinity paths (once round the loop, twice round, 3 times round... etc etc). If the graph is acyclic then you should be able to do a depth-first seach (DFS) (http://en.wikipedia.org/wiki/Depth-first_search) and simply count the number of times you encounter the destination node.
First familiarize yourself with basic graph algorithms (try a textbook, or google). Figure out which one best suits the problem you are solving, and implement it. You may need to adapt the algorithm a little, but in general there are widely known algorithms for all basic graph problems.
If you have a GraphNode class that looks something like this:
public class GraphNode
{
public IEnumerable<GraphNode> Children { get; set; }
// ...
}
Then this sould do the work:
public static class GraphPathFinder
{
public static IEnumerable<IEnumerable<GraphNode>> FindAllPathsTo(this GraphNode startNode, GraphNode endNode)
{
List<IEnumerable<GraphNode>> results = new List<IEnumerable<GraphNode>>();
Stack<GraphNode> currentPath = new Stack<GraphNode>();
currentPath.Push(startNode);
FindAllPathsRecursive(endNode, currentPath, results);
return results;
}
private static void FindAllPathsRecursive(GraphNode endNode, Stack<GraphNode> currentPath, List<IEnumerable<GraphNode>> results)
{
if (currentPath.Peek() == endNode) results.Add(currentPath.ToList());
else
{
foreach (GraphNode node in currentPath.Peek().Children.Where(p => !currentPath.Contains(p)))
{
currentPath.Push(node);
FindAllPathsRecursive(endNode, currentPath, new List<IEnumerable<GraphNode>>());
currentPath.Pop();
}
}
}
}
It's a simple implementation of the DFS algorithm. No error checking, optimizations, thread-safety etc...
Also if you are sure that your graph does not cycles, you may remove the where clause in the foreach statement in the last method.
Hope this helped.
You could generate every possible combination of vertices (using combinatorics) and filter out the paths that don't exist (where the vertices aren't joined by an edge or the edge has the wrong direction on it).
You can improve on this basic idea by having the code that generates the combinations check what remaining vertices are available from the current vertex.
This is all assuming you have acyclic graphs and wish to visit each vertex exactly once.

Resources