I'm trying to backtrack through a linkedlist I have created to solve a knight's tour problem, but once I hit a condition requiring me to backtrack, it totally empties the list. I have figured out it is because when I return false from the function findpath() to keep my while loop going, it continually loops back through the goback() function. What I'm having trouble figuring out is why. When i go through the goback function and call the calcmove function, it pushes the correct move to the structure I have declared, so passing false should keep the loop going and restart with the boolean cando and figuring out if that is false or not. But, it should be true because I just tested it and pushed it to the stack. Instead, it's emptying the list after I backtrack for the first time. So calcmove() would just be returning false every time after the first pop. But I don't see why that's happening. I need to return false to keep the loop going. What I need it to do is go back only once, find a new move, and continue on. Why would it be looping back to the function where the value on the list gets popped? If the value worked, and a new move is created (which I did verify it is doing correctly), it should be ready to call with a new (true) boolean. Is this just an inherently bad way of implementing the backtracking?
#include "stdafx.h"
#include "Header.h"
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <iomanip>
llist list;
Move m;
int board[8][8];
int cx[] = { -2, -1, 1, 2, 2, 1, -2, -1 };
int cy[] = { 1, 2, 2, 1, -1, -2, -1, -2 };
int movenum = 1;
Move first;
/*Check to see if move is within the constraints of the board*/
bool constraints(int k, int b) {
if ((k < 0) || (b < 0) || (k > 7) || (b > 7) || (board[k][b] != -1)) {
return true;
}
else {
return false;
}
}
/* Initialization of 8x8 board, fill the array with -1 */
void initboard() {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
board[x][y] = -1;
}
}
}
/* Output the current board array */
void printboard(int arr[8][8]) {
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
cout << std::setw(2) << arr[x][y] << " ";
}
cout << endl;
}
}
void updateboard(int k, int b) {
board[k][b] = movenum;
movenum++;
}
bool calcmove(int x, int y, int i) {
for (i; i < 9; i++) {
int a0 = x + cx[i];
int a1 = y + cy[i];
/*if(board[a0][a1] == board[first.x][first.y]){
}*/
if (constraints(a0, a1) == false) {
updateboard(a0, a1);
m.x = a0;
m.y = a1;
m.index = i;
list.push(m);
//list.display();
return true;
}
}
return false;
}
void goback(int k, int b) {
board[k][b] = -1;
list.display();
Move m = list.pop();
bool cando = calcmove(m.x, m.y, m.index);
cout << "prev is " << m.x << " , " << m.y << endl;
if (cando) {
return;
}
else {
goback(m.x,m.y);
}
}
bool findpath(){
bool cando = calcmove(m.x, m.y, 0);
if (cando) {
return false;
}
else {
movenum--;
goback(m.x, m.y);
return false; /*------> inserting this here drains the list*/
}
return true;
}
int main()
{
int m1 = 1;
int m2 = 2; //random
first.x = m1;
first.y = m2;
first.index = 0;
list.push(first); //push first node on to stack
initboard();
updateboard(m1, m2); //update board
while (!findpath()) {
;
}
printboard(board);
}
the .h file:
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include <ostream>
using std::cout;
using std::endl;
using std::setw;
struct Move {
int x;
int y;
uint32_t index;
};
struct node
{
public:
Move info;
struct node *next;
};
class llist {
struct node *start;
public:
void push(Move coords) {
struct node *p = new node;
p = newnode(coords);
if (start == NULL) {
start = p;
}
else {
p->next = start;
start = p;
//cout << "pushed" << endl;
}
}
Move pop() {
if (start == NULL) {
throw std::runtime_error("The list is empty");
}
else {
struct node *temp = new node;
temp = start;
Move data = start->info;
start = start->next;
delete temp;
//cout << "pop successful" << endl;
return data;
}
}
node *newnode(Move value) {
struct node *temp = new(struct node);
if (temp == NULL) {
return 0;
}
else {
temp->info = value;
temp->next = NULL;
return temp;
}
}
void display()
{
struct node *temp;
if (start == NULL)
{
cout << "The List is Empty" << endl;
return;
}
temp = start;
cout << "Elements of list are: " << endl;
while (temp != NULL)
{
cout << temp->info.x << "->";
temp = temp->next;
}
cout << "empty" << endl;
}
};
The goal of this is to create a linked list, solve the problem using the list for backtracking (push the current move unless no moves are available, then pop the previous values), and return the completed board.
Related
#include <iostream>
#include <list>
using namespace std;
const int TABLESIZE = 3;
class HashTable
{
public:
string k;
int v;
HashTable* next;
HashTable(string k, int v)
{
this->k = k;
this->v = v;
next = NULL;
}
};
class HashMapTable
{
private:
HashTable **t;
public:
HashMapTable()
{
t = new HashTable * [TABLESIZE];
for (int i = 0; i < TABLESIZE; i++)
{
t[i] = NULL;
}
}
int HashFunction(int v)
{
return v % TABLESIZE;
}
void Insert(string k, int v)
{
int hV = HashFunction(v);
HashTable* p = NULL;
HashTable* en = t[hV];
while (en!= NULL)
{
p = en;
en = en->next;
}
if (en == NULL)
{
en = new HashTable(k, v);
if (p == NULL)
{
t[hV] = en;
} else
{
p->next = en;
}
} else
{
en->v = v;
}
}
void PrintTable()
{
for (int i = 0; i < TABLESIZE; i++)
{
if(t[i] != NULL)
{
cout << t[i]->k << " " << t[i]->v << endl;
}
}
}
~HashMapTable()
{
for (int i = 0; i < TABLESIZE; i++)
{
if (t[i] != NULL)
delete t[i];
delete[] t;
}
}
};
int main()
{
HashMapTable HT;
cout << "entering the pairs now" << endl;
HT.Insert("Boramir", 25);
HT.Insert("Legolas", 101);
HT.Insert("Gandalf", 49);
cout << "printing the pairs now" << endl;
HT.PrintTable();
}
My issue is that not all the key value pairs in the table are being printed depending on the table size. If it's 3 (the desired amount) only 2 print, but if it's at least 7, they all print? I'm not sure what piece of my code is causing this to happen. Also, if there are multiple pairs in one bucket, the second/third/etc pair doesn't print and I'm not sure why. Thanks for any help.
This assignment (I've linked the full description here) asks us to create a multi server queue simulation (i.e. grocery store type scenario). My code seems to be working for the most part however I currently have 2 questions pertaining to my output that I am having a hard time answering.
Why does queue_total not match the actual number of elements displayed in each queue at the end of the program?
Why won't new items be enqueued to the shortest queue even though the shortest_queue function seems to be working?
The main code:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iomanip>
#include "queue_2.h"
using namespace std;
// Utility function to return shortest queue.
int shortest_queue(Queue line[], int queuecount)
{
int shortest = 0;
// Condition 1: If a queue is empty
// with no active transactions, return it.
for (int i = 0; i < queuecount; i++) {
if (line[i].empty() && line[i].get_trans_time() == 0)
return i;
}
// Condition 2: If a queue is simply empty,
// return it next.
for (int i = 0; i < queuecount; i++) {
if(line[i].empty()) {
return i;
}
}
// Condition 3: (otherwise) If all queues are
// occupied check for shortest queue.
for (int i = 1; i < queuecount; i++) {
if(line[i].size() < line[shortest].size())
shortest = i;
}
return shortest;
}
// Utility function to return total number
// of customers waiting in queues.
int queue_total(Queue q[], int queuecount)
{
int custcount = 0;
for (int i = 0; i < queuecount; ++i)
custcount += q[i].size();
return custcount;
}
int main()
{
// Variable decelrations
int trans_time = 0;
int count = 0;
int entry_time;
int wait_sum = 0;
int wait_time = 0;
int seed = 3;
int ariv_prob = 80;
int MAX_TRANS_TIME = 12;
int DURATION = 120;
int queuecount = 4;
int shortline;
int temp;
// Create a list of queues
// and random number generator
Queue line[queuecount];
srand(seed);
for (int time = 1; time < DURATION + 1; time++)
{
// Display the time
cout << "Time: " << time << endl;
// Check probablity only once per iteration
if ( rand() % 100 < ariv_prob ) {
shortline = shortest_queue(line, queuecount);
line[shortline].enqueue(time);
}
// Update the transaction times for
// the corresponding queues and compute
// summary statistics.
for (int i = 0; i < queuecount; i++) {
if ( line[i].get_trans_time() == 0 ) {
if ( !line[i].empty() ) {
entry_time = line[i].print_front();
line[i].dequeue();
temp = (time - entry_time);
if(temp > wait_time)
wait_time = temp;
wait_sum += (time - entry_time);
++count;
line[i].set_trans_time((rand() % MAX_TRANS_TIME) + 1);
}
}
// Decrement and update transaction time.
else {
trans_time = line[i].get_trans_time() - 1;
line[i].set_trans_time(trans_time);
}
}
// Display status of the queues for the
// the given iteration.
for (int i = 0; i < queuecount; i++) {
cout << setw(4) << line[i].get_trans_time() << " ";
line[i].display();
}
cout << endl;
}
cout << count << " customers waited an average of ";
cout << wait_sum / count << " ticks." << endl;
cout << "The longest time a customer waited was " << wait_time << " ticks." << endl;
cout << queue_total(line, queuecount) << " customers remain in the lines." << endl;
return 0;
}
The queue implementation
#ifndef QUEUE_H
#define QUEUE_H
#include <iostream>
using namespace std;
class Queue {
private:
struct Node {
int data;
Node* next;
Node(int d) {
data = d;
next = NULL;
}
};
Node* front;
Node* rear;
int count;
int trans_time;
public:
Queue() {
front = rear = NULL;
count = trans_time = 0;
}
void enqueue(int x) {
// Create a new linked Node.
Node* temp = new Node(x);
// If the queue is already empty
// then new node is front and rear
if (empty()) {
front = rear = temp;
return;
}
// Add the new node at the end
// of the queue and change the rear
rear->next = temp;
rear = temp;
++count;
}
void dequeue() {
// If the queue is empty
// then we can return NULL
if (empty())
return;
// Store the previous front and
// move the front one node ahead
Node* temp = front;
front = front->next;
// If front becomes NULL, then
// Change the rear to be NULL as well
if (front == NULL)
rear = NULL;
delete(temp);
--count;
}
// Utility function to check
// if the queue is empty
bool empty() {
return (front == NULL && rear == NULL);
}
int size() {
return count;
}
// Utility function to print front
// element of the queue
int print_front() {
return front->data;
}
void display() {
Node* temp = front;
while (!(temp == NULL)) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
void set_trans_time(int i) {
trans_time = i;
}
int get_trans_time() {
return trans_time;
}
};
#endif
Your enqueue function doesn't increment (or set) the count when inserting into an empty queue. This causes the count to be 0 for a queue with 1 element.
The comparisons for count > 0 or count >= 0 before decrementing/incrementing it should be unnecessary. If those conditions are ever false then you have a problem elsewhere that caused the inconsistency.
Everything works fine apart from the array that's supposed to remember the connected nodes for each node, although it counts only some of them and I'm not sure why. I believe the problem is here:
if (G->v[j] != NULL || G->v[i] != NULL)
However, I'm not sure how to change it.
#include <iostream>
#include <time.h>
#include <list>
#include <iterator>
#include <stack>
#include <queue>
#include "Profiler.h"
using namespace std;
# define MAX_SIZE 20
class Node
{
public:
int key;
int colour; // -1 not visited(white), 0 under visit(gray), 1 visited(black)
Node* p;
int d, f;
list<Node*> adj;
};
Node* newNode(int key) //constructor
{
Node* node = new Node();
node->key = key;
node->colour = -1; // white, not visited
node->d = 0;
node->f = 0;
node->p = NULL;
return node;
}
class Edge
{
public:
Node *v1,*v2;
};
Edge* newEdge(Node* u, Node* v)
{
Edge* edge = new Edge();
edge->v1 = u;
edge->v2 = v;
return edge;
}
class Graph
{
public:
Node* v[MAX_SIZE];
list<Edge*> e;
};
Graph* newGraph(int nb_of_vertices, int nb_of_edges)
{
Graph* G = new Graph();
int i, j;
for (i = 0; i < nb_of_vertices; i++)
{
G->v[i] = NULL;
}
for (i = 0; i < nb_of_vertices; i++)
{
Node* v1 = newNode(i);
G->v[i] = v1;
do
j = rand() % (nb_of_vertices-1);
while (j == i);
if (G->v[j] != NULL || G->v[i] != NULL)
{
Node* v2 = newNode(j);
G->v[j] = v2;
G->v[i]->adj.push_back(v2);
Edge* edge = newEdge(v1, v2);
G->e.push_back(edge);
}
}
return G;
}
void printGraph(Graph* G, int n)
{
list <Node*> ::iterator it;
for (int i = 0; i < n; i++)
{
cout << G->v[i]->key << '\t' << G->v[i]->colour << '\t' << G->v[i]->d << '\t' << G->v[i]->f << '\t';// << G->v[i]->p << '\t';
for (it = G->v[i]->adj.begin(); it != G->v[i]->adj.end(); ++it)
{
cout << (*it)->key << ' ';
}
cout << '\n';
}
list <Edge*> ::iterator it2;
for (it2 = G->e.begin(); it2 != G->e.end(); ++it2)
{
cout << (*it2)->v1->key << "-" << (*it2)->v2->key << ' ';
}
cout << '\n';
}
queue <Node*> solution;
stack <Node*> topsort;
int no_cycle = 1;
void DFSvisit(Graph* G, Node* v, int& time)
{
Node* node = newNode(0);
time++;
v->d = time;
v->colour = 0;
while (!v->adj.empty())
{
node = v->adj.front();
v->adj.pop_front();
if (v->colour == 0)
no_cycle = 0;
if (node->colour == -1)
{
node->p = v;
DFSvisit(G, node, time);
}
}
v->colour = 1;
time++;
v->f = time;
solution.push(v);
topsort.push(v);
}
void DFS(Graph* G, int n)
{
int time = 0, i;
for (i = 0; i < n; i++)
{
if (G->v[i]->colour == -1)
DFSvisit(G, G->v[i], time);
}
}
int main()
{
srand(time(NULL));
int nb_of_vertices = 10, nb_of_edges = 3;
Graph* G = newGraph(nb_of_vertices, nb_of_edges);
printGraph(G, nb_of_vertices);
DFS(G, nb_of_vertices);
printGraph(G, nb_of_vertices);
// DFS traversal
cout << "\nDFS TRAVERSAL\n";
while (!solution.empty())
{
cout << solution.front()->key << " ";
solution.pop();
}
cout << '\n';
// Tarjan's algorithm
// Topological sort
if (no_cycle)
{
cout << "\nTOPOLOGICAL SORTING\n";
while (!topsort.empty())
{
cout << topsort.top()->key << " ";
topsort.pop();
}
}
else
cout << "\nImpossible to perform topological sort, the generated graph contains cycles.\n";
return 0;
}
I made a program that involves a binary search tree. Basically, my segregates a set of input integers into "bins" in such a way that each bin are equal in value when their contents are summed.
#include <iostream>
#include <vector>
#ifndef DEBUG
#define DEBUG 0
#endif
using namespace std;
class Node {
private:
int weight = 0;
Node* leftNode;
Node* rightNode;
int bin = 0;
public:
Node() {}
Node(int weight) {
this->weight = weight;
}
void printContents() {
cout << weight << " ";
if(leftNode) leftNode->printContents();
if(rightNode) rightNode->printContents();
}
void addNode(Node* node) {
if(node->getWeight() <= this->weight) {
if(leftNode) leftNode->addNode(node);
else leftNode = node;
} else {
if(rightNode) rightNode->addNode(node);
else rightNode = node;
}
}
Node* getNode(int weight) {
if(!hasChildren()) {
if(this->weight == weight && bin == 0) return this;
else return nullptr;
} else {
Node* n = nullptr;
if(this->weight == weight && bin == 0) {
n = this;
}
Node* child;
if(leftNode && weight <= this->weight) {
child = leftNode->getNode(weight);
} else if(rightNode && weight > this->weight) {
child = rightNode->getNode(weight);
} else {
child = nullptr;
}
if(child) {
return child;
}
else return n;
}
}
bool hasChildren() {
if(leftNode || rightNode) return true;
else return false;
}
int getWeight() {
return weight;
}
void setBin(int bin) {
this->bin = bin;
}
int getBin() {
return bin;
}
void unbin() {
bin = 0;
}
void operator=(Node* node) {
this->weight = node->weight;
this->leftNode = node->leftNode;
this->rightNode = node->rightNode;
this->bin = node->bin;
}
};
class Bin {
private:
int binNum = 0;
int weight = 0;
int targetWeight = 0;
vector<Node*> nodes;
public:
Bin(int binNum, int targetWeight) {
this->binNum = binNum;
this->targetWeight = targetWeight;
}
void addNode(Node* node) {
weight += node->getWeight();
node->setBin(binNum);
nodes.push_back(node);
}
Node* removeLatestNode() {
Node* n = nodes.back();
weight -= n->getWeight();
nodes.pop_back();
n->unbin();
return n;
}
int getWeight() {
return weight;
}
bool isFull() {
if(weight == targetWeight) return true;
else return false;
}
bool willBeOverloaded(int x) {
if(weight + x > targetWeight) return true;
else return false;
}
};
void organize(Node* rootNode, int bins, int weightPerBin) {
#if DEBUG
cout << "Weight per bin: " << weightPerBin << endl;
#endif
for(int i = 1; i <= bins; i++) {
Bin bin(i, weightPerBin);
int x = weightPerBin;
while(!bin.isFull()) {
while(x > 0) {
Node* n = rootNode->getNode(x);
if (n) {
#if DEBUG
cout << "bin " << i << " : ";
cout << n->getWeight() << endl;
#endif
if (!bin.willBeOverloaded(n->getWeight())) {
#if DEBUG
cout << "adding to bin " << i << " : " << n->getWeight() << endl;
#endif
bin.addNode(n);
x = weightPerBin - bin.getWeight();
if(bin.isFull()) break;
} else {
x--;
}
} else {
x--;
}
}
if(!bin.isFull()) {
Node* n = bin.removeLatestNode();
#if DEBUG
cout << "removing from bin " << i << " : " << n->getWeight() << endl;
#endif
x = n->getWeight() - 1;
}
}
}
}
int getWeightPerBin(int* weights, int n, int bins) {
int weight = 0;
for(int i = 0; i < n; i++) {
weight += weights[i];
}
return weight/bins;
}
int main() {
int n;
int *weights;
int bins;
cin >> n;
weights = new int[n];
for(int i = 0; i < n; i++)
cin >> weights[i];
cin >> bins;
Node nodes[n];
nodes[0] = new Node(weights[0]); //the root node
for(int i = 1; i < n; i++) {
nodes[i] = new Node(weights[i]);
nodes[0].addNode(&nodes[i]);
}
organize(&nodes[0], bins, getWeightPerBin(weights, n, bins));
for(int i = 0; i < n; i++) {
cout << nodes[i].getBin() << " ";
}
return 0;
}
I developed this program in CLion IDE and it works perfectly. Recently I discovered that Xcode can also be used to develop C++ programs so I tried using it with the exact same code. But when I run the program, it always returns:
xcode error screenshot
It returns an error called EXC_BAD_ACCESS which is the first time I've encountered it. I'm a student who has a good background in Java and is currently learning C++ for a class. My knowledge in C++ is limited and I'd like to know whether this problem is due to Xcode or is inherent in my code.
You don't initialize leftNode and rightNode - they are not magically initialized to nullptr, so calling a function like
void printContents() {
cout << weight << " ";
if(leftNode) leftNode->printContents();
if(rightNode) rightNode->printContents();
}
will have Undefined Behaviour.
I suggest you initialize your variables before using them.
I tried to implement BFS for graphs using link list but i have some issues with it, using a queue it only displays the nodes of that origin and not after it. The answer should be 2031 but i only get 203.
The code is below:
#include <iostream>
#include <cmath>
#include <vector>
#include <stdlib.h>
#include <queue>
using namespace std;
class linkListNode
{
public:
linkListNode *next;
int destination;
bool visited;
linkListNode()
{
next = NULL;
destination =0;
visited=false;
}
};
class linkList
{
public:
linkListNode *head;
linkList()
{
head = NULL;
}
// append type insert
void insert(int value)
{
linkListNode *temp2 = new linkListNode;
temp2->destination = value;
temp2->next = NULL;
linkListNode *nodePtr = new linkListNode;
if (head == NULL)
{
head = temp2;
temp2->next = NULL;
}
else
{
nodePtr = head;
while (nodePtr->next)
{
nodePtr = nodePtr->next;
}
nodePtr->next = temp2;
}
}
void display()
{
linkListNode *temp = new linkListNode;
temp = head;
while (temp)
{
cout << temp->destination << " --> ";
temp = temp->next;
}
cout << endl;
}
int size()
{
linkListNode *temp = head;
int sizer = 0;
while (temp)
{
sizer++;
temp = temp->next;
}
return sizer;
}
};
class edge
{
public:
int origin;
linkList final;
bool visited;
edge()
{
//origin = NULL;
//cost=0;
visited=false;
}
};
class graph
{
private:
vector <edge> vectorOfEdges;
int vertices;
public:
graph(int v)
{
vertices = v;
vectorOfEdges.clear();
}
void addRoute(int ori, int dest)
{
int counter = 0;
for (int i = 0; i<vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin== ori)
{
counter = 1; // means element was present in the list
e.final.insert(dest);
}
vectorOfEdges[i] = e;
}
if (counter == 0) // when counter is set to zero, this means that the element was not found in the vector and needs to be pushed
{
edge e;
e.origin = ori;
e.final.insert(dest);
vectorOfEdges.push_back(e);
}
}
void printGraph()
{
edge e;
for (int i = 0; i<vectorOfEdges.size(); i++)
{
e = vectorOfEdges[i];
cout << e.origin << ":- ";
e.final.display();
cout << endl;
}
}
int sizeOfEdge(edge e)
{
int x = e.final.size() + 1;
return x;
}
int max(int one, int two)
{
if (one > two)
{
return one;
}
else
{
return two;
}
}
void BFS(int start)
{
edge e;
queue <int> q;
int save_index=0;
for (int i=0;i<vectorOfEdges.size();i++)
{
e=vectorOfEdges[i];
if (e.origin == start)
{
save_index=i;
q.push(e.origin);
e.visited=true;
break;
}
}
while (!q.empty())
{
int x=q.front();
cout << x << " " ;
q.pop();
linkListNode *l = e.final.head;
while (l)
{
if (l->visited == false)
{
q.push(l->destination);
l->visited=true;
l=l->next;
}
else
{
l=l->next;
}
}
}
}
};
int main()
{
graph g(4);
g.addRoute(0, 1);
g.addRoute(0, 2);
g.addRoute(1, 2);
g.addRoute(2, 0);
g.addRoute(2, 3);
// g.printGraph();
//cout << "Following is Breadth First Traversal (starting from vertex 2) \n";
g.BFS(1);
}
Your code is only running for the node that you have provided as the starting value for your BFS traversal.
void BFS(int start)
{
queue<int> q;
bool startFound = false;
for (int i = 0; i < vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin == start)
{
q.push(e.origin);
check.push_back(e.origin);
e.visited = true;
startFound = true;
break;
}
}
if (!startFound)
{
cout << "Start vertex not found in the graph" << endl;
return;
}
while (!q.empty())
{
int x = q.front();
cout << x << " ";
q.pop();
for (int i = 0; i < vectorOfEdges.size(); i++)
{
edge e = vectorOfEdges[i];
if (e.origin == x)
{
linkListNode *l = e.final.head;
while (l != NULL)
{
bool found = false;
if (l->visited == false)
{
l->visited = true;
for (int i = 0; i < check.size(); i++)
{
if (check[i] == l->destination)
{
found = true;
break;
}
}
if (found == false)
{
check.push_back(l->destination);
q.push(l->destination);
}
}
l = l->next;
}
}
}
}
}
Instead, do this to run it for every node.