Weird Behaviour in C++ Snake School Assignment - c++

So over the last few weeks we've been coding snake in c++ step by step. Right now we have to implement the snake actually growing. (All of this happens in the console)
We realize the growth by saving the head and the tail of the snake, as well as the Direction the Head went on a given field and then moving the tail into that saved direction from the field the tail is on.
Theoretically skipping this tail movement once when we eat a fruit should let our snake grow.
However, my Snake either doesnt grow at all, or grows infinitely until I pass the Field on which the fruit was again, or ,in this current iteration, grows mostly correct but only in the direction which I was facing when eating the fruit. Also in this Iteration the size of the snake changes, if I comment out the GenerateFruit() Command (Even when that command is completely empty).
I'm clueless as to what im doing wrong. I've had different behaviour just by having a literally empty if statement.
Heres the main part of the code:
bool MoveSnake(SnakeDataT snakeData){
//Collision detection: If the new x/y Coordinate hits the walls we have a collision.
if (snakeData.Head.x + snakeData.dx == WIDTH - 1 || snakeData.Head.x + snakeData.dx == 0 || snakeData.Head.y + snakeData.dy == HEIGHT + 1 || snakeData.Head.y + snakeData.dy == 0)
{
SetCursor(WIDTH, HEIGHT);
cout << "\n";
cout << "\n";
cout << "\n";
cout << "Game Over" << endl;
return false;
}
//Save current Movement Direction in current coordinate
snakeData.Field[snakeData.Head.x][snakeData.Head.y].dx = snakeData.dx;
snakeData.Field[snakeData.Head.x][snakeData.Head.y].dy = snakeData.dy;
//Fruit Collision:
if (snakeData.Head.x == snakeData.Fruit.x && snakeData.Head.y == snakeData.Fruit.y)
{
//GenerateFruit(snakeData); <- If I leave this out it literally changes behaviour?!
}
else if (!(snakeData.Head.x == snakeData.Fruit.x && snakeData.Head.y == snakeData.Fruit.y))
{
//Delete at Tail Position
SetCursor(snakeData.Tail.x, snakeData.Tail.y);
cout << ' ';
//Move Tail by saved Direction. I did try this with the Tail coordinates first, but after many different iterations this showed the weirdest results.
snakeData.Tail.x += snakeData.Field[snakeData.Head.x][snakeData.Head.y].dx;
snakeData.Tail.y += snakeData.Field[snakeData.Head.x][snakeData.Head.y].dy;
}
//Move Head
snakeData.Head.x += snakeData.dx;
snakeData.Head.y += snakeData.dy;
//Draw Head
SetCursor(snakeData.Head.x, snakeData.Head.y);
cout << "\xCE";
return true;
Here are my structs:
#define WIDTH 30
#define HEIGHT 30
enum FieldTypeT
{
empty,
Snake
};
struct FieldT
{
FieldTypeT fieldType;
int dx;
int dy;
};
struct PointT
{
int &x;
int &y;
};
struct SnakeDataT
{
PointT Head;
PointT Fruit;
int &dx;
int &dy;
PointT Tail;
FieldT Field[WIDTH][HEIGHT];
};
If you need more Insight I'll add what you need.
Bear with me though, the Teacher is asking for questionable practices.

Related

How to go about making a "Sorted Array to Balanced BST" recursion algorithm to an iterative one?

I've searched around but can't really understand or find help, since this iterative algorithm will require two stacks (to contain a left_Index and right_Index).
The main recursive way involves having it one side until the left_Index >= right_Index, and recursively doing so for both sides and per subsection (if that makes sense), which I don't understand how to do so exactly since I'm maintaining two stacks and need to see how exactly they relate to one another.
This problem is mostly due to me not understanding the way the normal recursive method words, although when looking at them side by side to see how to approach it, I always get stuck on what to do.
The backstory as to why I'm doing this:
Trying to solve the word ladder problem to go from A to B and decided to make a BST where the connections are connected by singular character differences and lengths. I'm getting the words from a text file containing a lot of the dictionary, and since I'm using a BST as the master list with all vertices the fact that this is a dictionary means every insert will be in order so the tree is right-leaning (so the speeds are slow for inserting O(n^2) which is a big hinderance). I was planning on storing data in an array then making a balanced BST from that since I believe speeds should go faster since insertion will be O(n*logn) which seems great. The problem with that is that I can't use a recursive approach since there's a lot of data leading to stack overflows, so I need to make it iteratively with stacks and loops, but am finding it too difficult.
My bad attempt at a start:
while (lindx.the_front() < rindx.the_back())
{
mid =(lindx.the_front() + rindx.the_back()) / 2;
dictionary.addVertex(vector[mid]);
std::cout << "Pushed " << vector[mid] << '\n';
rindx.push(mid - 1);
}
That basically gets the 1/2's from the left half of the program from a linked stack I made. "the_front()" is the first insertion, "the_back()" is the final/latest insert into the list. The main problem I have is understanding how to make it repeat per half to get all the values.
I need to find my past homework where I've done this but the code is something along the lines of...
void array2balanced(int array[], int lIndex, int rIndex)
{
//base case
if(lIndex > rIndex)
{
return;
}
//recursive cals
else
{
mid = (lIndex+rIndex)/2;
tree.insert(array[mid]);
array2balanced(array, lIndex, mid-1);
array2balanced(array, mid+1, rIndex);
}
}
UPDATE:
Progress so far
void balancedTree(std::vector<std::string> vector, dictionaryGraph &dictionary) // divide and conquer into tree?
{
linkedStack<int> lindx, rindx, midX;
unsigned int l_Index{ 0 }, r_Index{ vector.size() - 1 }, mid{ (l_Index + r_Index) / 2 };;
lindx.push(l_Index);
rindx.push(r_Index);
midX.push(mid);
int testCount{ 0 };
std::cout << "There are " << vector.size() << " words.\n";
while (!midX.empty())
{
mid = midX.pop();
l_Index = lindx.pop();
r_Index = rindx.pop();
std::cout << "inputted " << vector[mid] << '\n';
dictionary.addVertex(vector[mid]);
testCount++;
if (r_Index > l_Index)
{
midX.push((l_Index + mid) / 2);
lindx.push(l_Index);
rindx.push(mid - 1);
}
if (l_Index < r_Index)
{
midX.push((mid + r_Index) / 2);
lindx.push(mid + 1);
rindx.push(r_Index);
}
}
std::cout << testCount << " words were inputted...\n"; // To see how many were inserted
system("pause");
}
Problem I have is some inputs get repeated and some missed.
I don't think you need two stacks. You just need either a one stack or one queue.
Below codes can be tested on Leetcode
Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
One Stack Method
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
if not nums:
return None
l = len(nums)
node = TreeNode(0)
head = node
s = collections.deque([(node, 0, l)])
while s:
node, left, right = s.pop()
mid = (right + left) // 2
node.val = nums[mid]
if mid < right-1:
node.right = TreeNode(0)
s.append((node.right, mid+1, right))
if left < mid:
node.left = TreeNode(0)
s.append((node.left, left, mid))
return head
One Queue Method
def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
if not nums:
return None
l = len(nums)
node = TreeNode(0)
head = node
q = collections.deque([(node, 0, l)])
while q:
node, left, right = q.popleft()
mid = (right + left) // 2
node.val = nums[mid]
if left < mid:
node.left = TreeNode(0)
q.append((node.left, left, mid))
if mid < right-1:
node.right = TreeNode(0)
q.append((node.right, mid+1, right))
return head
They are implemented using deque. Notice popleft() returns the first element(like stack) and pop() returns the last element(like queue).
This problem is mostly due to me not understanding the way the normal
recursive method words, although when looking at them side by side to
see how to approach it, I always get stuck on what to do.
It takes practice ... and maybe reviewing other peoples work.
require two stacks (to contain a left_Index and right_Index).
My apologies, I do not understand why the OP thinks this. My demo below has only 1 stack called 'todo', perhaps you will find the idea useful.
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
#include <cassert>
#include "./BTree.hh" // code not provided, used in this MCVE to
// conveniently provide "showTallTreeView()"
typedef std::vector<int> IVec_t;
class T607_t
{
IVec_t m_sortedIVec; // sorted - created with for loop
IVec_t m_recursiveIVec; // extract from sorted by recursion
IVec_t m_iterativeIVec; // extract from sorted by iteration
public:
T607_t() = default;
~T607_t() = default;
int exec(int , char** )
{
fillShowSortedIVec();
fillShowRecursiveIVec();
fillShowIterativeIVec();
showResults();
return 0;
}
private: // methods
The vectors are in class T607_t, so that each is available to any member function.
For this MCVE, I simply create "IVec_t m_sortedIVec;" and fill with a simple for loop:
void fillShowSortedIVec()
{
for (int i=0; i<15; ++i)
m_sortedIVec.push_back (i*100); // create in sorted order
showIVec(m_sortedIVec, "\n m_sortedIVec :");
}
Next (in this MCVE) is the recursive fill and show, and my adaptation of the OP's recursive method to produce the recursive insert sequence:
// ///////////////////////////////////////////////////////////////
void fillShowRecursiveIVec()
{
assert(m_sortedIVec.size() > 0);
int max = static_cast<int>(m_sortedIVec.size()) - 1;
// use OP's recursive insert
array2balancedR (m_sortedIVec, 0, max);
// NOTE - 'sequence' is inserted to 'm_recursiveIVec'
// instead of into tree the op did not share
showIVec(m_recursiveIVec, "\n m_recursiveIVec:");
}
// recursive extract from: m_sortedIVec to: m_recursiveIVec
// my adaptation of OP's recursive method
void array2balancedR(IVec_t& array, int lIndex, int rIndex)
{
//base case
if(lIndex > rIndex)
{
return;
}
else //recursive calls
{
int mid = (lIndex+rIndex)/2;
m_recursiveIVec.push_back(array[mid]); // does this
// tree.insert(array[mid]); // instead of this
array2balancedR(array, lIndex, mid-1); // recurse left
array2balancedR(array, mid+1, rIndex); // recurse right
}
}
Note: I left the "IVec_t& array" as a parameter to this function, because the OP's code has it. Within this 'class' wrapper, the function need not pass the array 'through the recursion', because each method has access to the instance data.
Next (in this MCVE) is a fill and show action using one possible iterative approach. I styled this iterative approach carefully to match the OP's recursive effort.
First, I added a 'tool' (IndxRng_t) to simplify the 'stack' capture of iterations for later processing. (i.e. "todo").
// //////////////////////////////////////////////////////////////
// iterative extract from m_sortedIVec to: m_iterativeIVec
class IndxRng_t // tool to simplify iteration
{
public:
IndxRng_t() = delete; // no default
IndxRng_t(int li, int ri)
: lIndx (li)
, rIndx (ri)
{}
~IndxRng_t() = default;
// get'er and set'er free. also glutton free. gmo free.
bool done() { return (lIndx > rIndx); } // range used up
int mid() { return ((lIndx + rIndx) / 2); } // compute
IndxRng_t left(int m) { return {lIndx, m-1}; } // ctor
IndxRng_t right(int m) { return {m+1, rIndx}; } // ctor
private:
int lIndx;
int rIndx;
};
void fillShowIterativeIVec()
{
assert(m_sortedIVec.size() > 0);
int max = static_cast<int>(m_sortedIVec.size()) - 1;
array2balancedI(m_sortedIVec, 0, max);
// 'sequence' inserted to 'm_iterativeIVec'
showIVec(m_iterativeIVec, "\n m_iterativeIVec:");
}
void array2balancedI(IVec_t& array, int lIndex, int rIndex)
{
std::vector<IndxRng_t> todo;
todo.push_back({lIndex, rIndex}); // load the first range
// iterative loop (No recursion)
do
{
if (0 == todo.size()) break; // exit constraint
// no more ranges to extract mid from
// fetch something to do
IndxRng_t todoRng = todo.back();
todo.pop_back(); // and remove from the todo list
if(todoRng.done()) continue; // lIndex > rIndex
int mid = todoRng.mid();
m_iterativeIVec.push_back(array[mid]); // do this
// tree.insert(array[mid]); // instead of this
todo.push_back(todoRng.right(mid) ); // iterate on right
todo.push_back(todoRng.left(mid) ); // iterate on left
}while(1);
}
And this mcve generates a result display:
void showResults()
{
assert(m_recursiveIVec.size() == m_sortedIVec.size());
assert(m_iterativeIVec.size() == m_sortedIVec.size());
std::cout << std::endl;
std::stringstream ss; // for btree use only
std::cout << "\n demo:\n create a BTree, "
<< std::flush;
std::cout << "\n Insert IVec_t " << std::endl;
BBT::BTree_t btree(ss);
std::cout << std::flush;
for (size_t i=0; i<m_iterativeIVec.size(); ++i)
btree.insertPL(m_iterativeIVec[i]);
std::cout << "\n iterative result:\n\n"
<< btree.showTallTreeView();
}
void showIVec(IVec_t& ivec, std::string lbl)
{
std::cout << lbl << std::endl;
for (auto it : ivec)
std::cout << std::setw(5) << it << std::flush;
std::cout << std::endl;
}
}; // class T607_t
int main(int argc, char* argv[])
{
T607_t t607;
return t607.exec(argc, argv);
}
My output (on Ubuntu 17.10, g++ 7.2.0),
m_sortedIVec :
0 100 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400
m_recursiveIVec:
700 300 100 0 200 500 400 600 1100 900 800 1000 1300 1200 1400
m_iterativeIVec:
700 300 100 0 200 500 400 600 1100 900 800 1000 1300 1200 1400
demo:
create a BTree,
Insert IVec_t
iterative result:
BTree_t::showTallTreeView(): (balance: 0 sz: 15)
0
100
200
300
400
500
600
700
800
900
1000
1100
1200
1300
1400
-----------------
Iterative JavaScript implementation of converting sorted array to Binary Search Tree (BST):
function sortedArrayToBstIteratively(nums) {
// use stack to iteratively split nums into node tuples and reuse values
const stack = []
// add root node to tree
const tree = { first: 0, last: nums.length - 1 }
stack.push(tree)
// split array in the middle and continue with the two halfs
while (stack.length > 0) {
const node = stack.pop()
if (node.last >= node.first) {
if (node.last === node.first) {
// node reaches a single leaf value (last == first)
node.value = nums[node.first]
} else {
// node has still valid indices to further split the array (last > first)
const middle = Math.ceil((node.first + node.last) / 2)
node.value = nums[middle]
node.left = { first: node.first, last: middle - 1 }
node.right = { first: middle + 1, last: node.last }
stack.push(node.left)
stack.push(node.right)
}
} else {
// node has no more valid indices (last < first), create empty leaf
node.value = null
}
delete node.first
delete node.last
}
// console.log(JSON.stringify(tree))
return tree
}

Stuck/general help in developing A* on a 2D grid

I think I am close to finishing this implementation of A* but my mind is becoming fried and am looking for pointers on what I should be doing to complete it.
My current problem is that my function that runs through A* remains stuck on the same node, as in the current node never moves into any other of the open nodes.
Here is my main function, note that the heuristic(Node &n1, Node &n2) function is currently set to always to return 0, so it should currently be working more like a Dijkstra algorithm rather than A*. Also, movement is restricted to the NESW plane, no diagonal movement, so distance_between(Node &n1, Node &n2) always returns 1.
void astar(Node start_, Node end_) {
Node start = start_;
Node end = end_;
// compute f,g,h for the start node
start.g = 0;
start.h = heuristic(start, end);
start.f = start.g + start.h;
// insert start node into the open set
openNodes.insert(&start);
// while the set of open nodes is not empty
while (openNodes.size() > 0) {
// pick the most promising node to look at next
Node currentNode;
cout << "currentNode before: ";
currentNode.displaylocation();
// go through all the open nodes and find the one with the smallest 'f' value
Node* minf = (*openNodes.begin()); // set initial value for minimum f to be the first node in the set of open nodes
for (auto n : openNodes) {
if (n->f <= minf->f) {
minf = n;
}
}
currentNode = *minf; // set the current node to the node that holds the smallest 'f' value
cout << "currentNode after: ";
currentNode.displaylocation();
// if the current node is the end node, then we have found a path
if (currentNode.type == -3) {
break;
}
// remove the current node from the set of open nodes, and add it to the set of closed nodes
openNodes.erase(&currentNode);
closedNodes.insert(&currentNode);
// go through the currents node's neighbours
for (auto n : neighbours(currentNode)) {
cout << "neighbour local: " << n.location.x << "," << n.location.y << "\n";
if (closedNodes.count(&n) == 0 && n.type != -2) { // if this node is neither closed or a blocker
int new_g = currentNode.g + distance_between(currentNode, n);
if (openNodes.count(&n) != 0) { // if we have not seen this node before, add to the open set
openNodes.insert(&n);
}
else if (new_g >= n.g) { // else if we have seen this node before, and already found a shorter path to it from the starting node
}
n.g = new_g;
n.f = n.g + heuristic(n, end);
n.parent_ = &currentNode;
}
}
cout << "\n A* run success! \n";
//break;
}
}
Here is the deceleration of things like the Node struct and the global variables:
// The size of the grid
#define WIDTH 6
#define HEIGHT 6
// Holds values for x and y locations on the grid
struct Coord {
int x, y;
};
// holds data for each node required for A*
struct Node {
int type; // used for defining if this node is a blocker, empty, start or end
Coord location;
int g = 0;
int h = 0;
int f = g + h;
Node *parent_; // pointer to this node's parent
std::string debugmessage;
void displaylocation() {
std::cout << "I am the node at: " << location.x << "," << location.y << "\n";
}
};
// The 2D grid array for A*, requiring a Node struct to store the data of each cell
Node astarArray[WIDTH][HEIGHT];
// Sets for A*
std::set<Node *> openNodes; // contains the nodes that are yet to be considered (if this is empty, then there are no more paths to consider or there is no path)
std::set<Node *> closedNodes; // contains the nodes that have already been considered (if the end node is placed in here, a path has been found)
// stores the start and end values for A*
Node start_A, end_A;
void astar(Node start_, Node end_);
int distance_between(Node& n1, Node& n2);
int heuristic(Node& n1, Node& n2);
std::list<Node> neighbours(Node& n_);
// returns the distance between two nodes for A*
int distance_between(Node& n1, Node& n2) {
return 1; // always return 1 as we are working in a grid restricted to NSEW movement
}
int heuristic(Node& n1, Node& n2) {
return 0; // return 0 to work as a Dijkstra algorithm rather than A*
}
// finds a node's neighbours for A*
std::list<Node> neighbours(Node& n_) {
std::list<Node> neighbours_;
int x = n_.location.x;
int y = n_.location.y;
// start at the location belonging to 'n_'
//for (int y = n_.location.y; y < HEIGHT; y++) {
//for (int x = n_.location.x; x < WIDTH; x++) {
// east
if (x < WIDTH - 1) {
neighbours_.push_back(astarArray[x + 1][y]);
}
// west
if (x > 0) {
neighbours_.push_back(astarArray[x - 1][y]);
}
// south
if (y < HEIGHT - 1) {
neighbours_.push_back(astarArray[x][y + 1]);
}
// north
if (y > 0) {
neighbours_.push_back(astarArray[x][y -1]);
}
//}
//}
return neighbours_;
}
Thank you very much for reading and for any help you can give. I will provide more code if required.
The main problem you have is that you are using the pointers (mem address) to find out if a node is in your set or not.
currentNode = *minf; // set the current node to the node that holds the smallest 'f' value
Then you copy to currentNode the contents of minf.
currentNode will have a different address from the pointer to minf
openNodes.erase(&currentNode); will not remove minf because currentNode does not have the same address.
I would suggest you investigate more on how to implement A* as you are missing some steps. Look for priority queues.
Instead of the mem address of the node, use the position index for that node in the grid (pos.x * numCols) + pos.y

Array of struct value is being changed when it shouldn't

I have been working for some time on a programming project and am stuck on something that someone else may find trivial.
I have an array of struct, that stores values for an event node graph.
Everything works fine until the 85th loop where a enum value of "ACTIVE" is being assigned to a part of the array ( Q[0].state ) that is not even being called.
At this point Q[notifydep].state = QUEUED; should be happening (and does). notifydep = 2 at this loop.
The problem shows up in below code at first instance where it says Watch Point. (in the nested for loop)
Here is a part of the code where it is happening. I hope I am giving enough code and not too much...
for (int w = qstarted; w < qendrunning; w++) {
PrintState(queue[w]);
if (Q[queue[w]].completetime == 0 && Q[queue[w]].state == ACTIVE) {
PrintState(queue[w]);
jobscopy[queue[w]].finishTime = currentday + 1;
Q[queue[w]].state = COMPLETED;
PrintState(queue[w]);
/*Put workers back into our available workers array*/
for (int i = 0; i < jobscopy[queue[w]].numPeopleUsed; i++) {
not_working_end++;
not_working[not_working_end] = jobscopy[queue[w]].peopleIDs[i];
}
/*Notify dependent jobs that this job has completed*/
for (int notify = 0; notify < Q[queue[w]].tocount; notify++) {
notifydep = Q[queue[w]].to[notify]; // ancestor job#
Q[notifydep].edges--; // decrement ancestor edge
/*check if notified job has 0 edges, if 0 then enqueue job*/
if (Q[notifydep].edges == 0 && Q[notifydep].state == WAITING) {
queue[qend++] = Q[notifydep].jobnum; // add job to qend then increment qend
Q[notifydep].state = QUEUED;
PrintState(notifydep);
cout << "\n" << __LINE__ << "============== Watch Point ===============";
PrintState(0);
}
}
cout << "\n============== Watch Point ===============";
PrintState(queue[w]);
cout << "\n" << __LINE__ << "============== Watch Point ===============";
PrintState(0);
dequeue(queue, w); // remove completed job from job running queue
curjobs--;
} else if (Q[queue[w]].completetime > 0 && Q[queue[w]].state == ACTIVE) {
Q[queue[w]].completetime--;
}
} // end check for completed jobs
This is the definition for the struct from my .h
struct AdjacencyList {
NodeType state; // what is present state of job?
NodePath path; // is job part of critical path?
int jobnum;
int edges;
int tocount;
int fromcount;
int completetime;
int to[50];
int from[50];
};
Any help would be greatly appreciated. I am fairly new to c++ and have been learning a lot. I first spend a great deal of effort researching and debugging before bugging everyone on SO. Thanks
SUB

Connect 4 PVP Function

I can't seem to find something that specifically answers my question. I am looking for a solution to my problem. The connect 4 player versus player seems to just ask the first player to drop then the second player to drop, but the first if statement is no longer true so it continues to ask the second player to drop. I am using eclipse for mac osx although the game is programmed for ASCII character set.
display();
int hold;
int hold2 = 0;
int charsPlaced = 0;
bool gamewon = false;
char player = 15;
string r;
while (!gamewon)
{
if (hold2 != -1)
{
if (player == 15)
{
cout << ax << " what column would you like to drop in?";
player = 178;
}
else
{
cout << bx << " what column would you like to drop in?";
player = 176;
}
}
You need to switch the players' turn after each action. If P1 took an action, you need to update the "turn" so that the next time the code loops it will ask for P2. Then, after you've done the stuff you need to do for P2, you need to update the "turn" so that the next time it loops it will ask for P1 action.
Here's a different approach on your code by using an enum. You can use a bool type variable which is false for P1 and true for P2, or an int that's 1 or 2, but that's a bit harder to understand from the outisde.
// omitted code
enum PlayerTurn { ePlayer1 = 0, ePlayer2 };
// omitted code
PlayerTurn plTurn = ePlayer1;
while (!gamewon)
{
if (pTurn == ePlayer1)
{
cout << ax << " what column would you like to drop in?";
// TODO: stuff to do for Player #1
}
else
{
cout << bx << " what column would you like to drop in?";
// TODO: stuff to do for Player #2
}
// TODO: decide if game has been won, mechanics etc.
// move to the next player without overflowing the 2 possible values (0 and 1)
plTurn = (plTurn + 1) % 2;
}
Then, on your display() function, you can show any ASCII character you wish.

c++ trying to find the distance between 2 nodes

I am currently working on a function that has 1 helper function, the main function takes in 2 strings and searches for the first one (which becomes a reference as if it was m_root) and a second one to be searched in the tree. once they are searched, my helper function is supposed to search for the 2nd city and count the distance it had to travel as if a truck was going towards that city.
int Stree::distance(string origin_city, string destination_city)
{
int total_distance = 0;
Node *new_root = m_root;
new_root = find_node(m_root, origin_city);
total_distance = get_distance(new_root, total_distance, destination_city);
return total_distance;
}
int Stree::get_distance(Node* cur, int distance, string destination)
{
Node *tmp = cur;
if(cur == NULL)
return 0;
if(cur->m_city == destination || tmp->m_city == destination)
{
//cout << distance + cur->m_parent_distance << endl;
return distance += cur->m_parent_distance;
}
if(tmp->m_left != NULL)
{
//cout << "checking left" << endl;
tmp = cur->m_left;
return get_distance(cur->m_left, distance, destination) ;
}
else
{
//cout << "checking right" << endl;
return get_distance(cur->m_right, distance, destination);
}
}
In a cursory glance, I don't see anywhere that you modify or increment distance, whether it be the distance variable or something like:
return 1 + get_distance(cur->m_right, distance, destination);
So I would make sure that in an algorithmic sense, each step walked is counted, otherwise it will certainly return 0 every time.