I am trying to debug a bfs algorithm using a adjacent list. It will print correctly to a certain point then goes into infinite loop. I did some printouts and noticed that it eventually loops over the first two nodes of the graph. I am not sure where in my code thats causing this problem. This is anassignment I was given, and this is my last resort. If anyone can point me in the right direction as to what the problem could be would help alot.
void bfsList(linkedList adjList[], int visit[], int j){
Queue queue(24);
if (visit[j] == 0){
cout << j+1 << endl;
visit[j] = 1;
queue.enqueue(j);
while(!queue.isEmpty()){
int k = queue.dequeue();
//queue.print();
for(int i=0;i<adjList[k].len();i++){
if (visit[adjList[k].elementAt(i)-1]==0){
cout << adjList[k].elementAt(i) << endl;
visit[adjList[k].elementAt(i)-1] = 1;
}
if (!queue.isFull()){
queue.enqueue(adjList[k].elementAt(i)-1);
}
}
}
}
}
Enqueue only if node is not visited.
if (visit[adjList[k].elementAt(i)-1]==0){
cout << adjList[k].elementAt(i) << endl;
visit[adjList[k].elementAt(i)-1] = 1;
if (!queue.isFull()){
queue.enqueue(adjList[k].elementAt(i)-1);
}
}
queue.enqueue(adjList[k].elementAt(i)-1);
needs to be dependent, whether the node has been visited.
untested:
if (!queue.isFull() && !visit[adjList[k].elementAt(i)-1]){
queue.enqueue(adjList[k].elementAt(i)-1);
}
Related
This is my code for queue using pointer array.
#include <iostream>
#include <Queue>
using namespace std;
#define size 2
class Queue{
public:
int f;
int r;
int* arr;
public:
Queue(){
arr = new int [size];
int f, r = -1;
}
int isEmpty(){
if(r == -1 && f == -1){
cout<<"Queue underflow";
}
return 0;
}
int isFull(){
if(r == size - 1){
cout<<"Queue overflow";
}
return 0;
}
void enqueue(int val){
if( isFull()){
cout << "Cannot push element in Queue";
}
else{
arr[r] = val;
r++;
cout << "The value in Queue is" << " " << val << endl;
}
}
int dequeue(){
int a = -1;
if( isEmpty()){
cout << "Cannot pop element from Queue";
return 0;
}
else{
a = arr[f];
f++;
return a;
}
}
};
int main(){
Queue q;
q.f = q.r = 0;
q.enqueue(1);
q.enqueue(2);
q.enqueue(3);
cout << "Dequeuing element is" << q.dequeue() << endl;
cout << "Dequeuing element is" << q.dequeue() << endl;
cout << "Dequeuing element is" << q.dequeue() << endl;
cout << "Dequeuing element is" << q.dequeue() << endl;
if( q.isEmpty()){
cout << "Queue is empty";
}
return 0;
}
Here is the output
The value in Queue is 1
Queue overflow The value in Queue is 2
The value in Queue is 3
Dequeuing element is1
Dequeuing element is2
Dequeuing element is3
Dequeuing element is563
Though I have set size as 2 still after printing one it says 'Queue Overflow' and then print the data also when I dequeue 4th element (though there is no forth element) it prints the line with absurd numbers.
As Nathan Pierson correctly pointed out, your functions isFull and isEmpty always return 0, which gets implicitly converted to false in an if statement, hence your checks in enqueue and dequeue are not working and the functions are always executed. Additionally, I would like to point out a few other things:
Please don't use preprocessor directive to define a size variable, use constexpr instead. (constexpr int size = 2;). The name you have chosen (size) is very dangerous, most of the STL containers have a method also called size. Your preprocessor directive would then substitute function call with 2, breaking compilation.
You have two member variables in your Queue class: r and f. What do they mean? You check them in your methods isFull and isEmpty so I guess they are quite important. Please use descriptive names for variables (for example use front and back)
Your methods isFull and isEmpty return int to indicate true or false values. In C++ there is a special type designed to indicate true or false: bool. Please use it instead of int.
How can use the Boost Graph Library to find all the topological sorts of a given DAG G?
I have found some theoretical references explaining that is possible, there's also this code where there's an implementation. But I don't actually want to start from scratch, and I want to use BGL to compute them.
One strategy would be to get all vertices without predecessors (no directed edges to it). And multiplying vectors based on vertices without predecessors. If you have a C++ to do it please share.
The code to get depth_first topological sort:
Given a DAG graph with vertex type vertex_t:
deque<vertex_t> topologicalSorted;
//perform topological sort
if (topologicalSort(graph, topologicalSorted)) {
cout << "The graph is directed acyclic!" << endl;
cout << "Topological order: ";
for (int i = 0; i < topologicalSorted.size(); i++) {
cout << graph[topologicalSorted.at(i)].label << " ";
}
cout << endl;
}
bool topologicalSort()
{
try
{
boost::topological_sort(graph, front_inserter(topologicalSorted));
}
catch (boost::not_a_dag)
{
cout << "not a dag\n";
return false;
}
cout << "top sort OK\n";
return true;
}
Without custom vertex:
deque<int> topologicalSorted;
if (topologicalSort()) {
// Print the results.
for (int i = 0; i < topologicalSorted.size(); i++) {
cout << topologicalSorted.at(i) << ",";
}
cout << endl;
}
Here is some code that I have made that should copy all the nodes in a linked data type correctly, but it is not working. I have checked my logic and wrote it on paper many times, yet it still isn't working. Am I doing something wrong on this part of the code? Is my use of pointers to copy nodes accurate? The part of my Constructor test that goes haywire is the part that starts to print out what's in the queue.
void LinkedQueue<ItemType>::CopyNodesFrom(const LinkedQueue& a_queue)
{
Node<ItemType>* orig_chain_ptr = a_queue.front_ptr_; // Points to nodes in original chain
if (orig_chain_ptr == nullptr) {
front_ptr_ = nullptr; // Original queue is empty
back_ptr_ = nullptr;
return;
}
// Copy first node
front_ptr_ = new Node<ItemType>();
front_ptr_->SetItem(orig_chain_ptr->GetItem());
// Advance original-chain pointer
orig_chain_ptr = orig_chain_ptr->GetNext();
// Copy remaining nodes
Node<ItemType>* new_chain_ptr = front_ptr_; // Points to last node in new chain
Node<ItemType>* temp_ptr;
while (orig_chain_ptr != nullptr) {
temp_ptr = new Node<ItemType>(orig_chain_ptr->GetItem() );
new_chain_ptr->SetNext(temp_ptr);
orig_chain_ptr = orig_chain_ptr->GetNext(); //Advance Our original pointer
new_chain_ptr = new_chain_ptr->GetNext(); //Advance our new chain pointer
} // end while
new_chain_ptr->SetNext(nullptr);
back_ptr_ = new_chain_ptr;
} // end copy constructor
#include <iostream>
#include <string>
#include "LinkedQueue.h" // ADT Queue operations
using namespace std;
void CopyConstructorAndAssignmentTester() {
LinkedQueue<string> queue;
string items[] = {"zero", "one", "two", "three", "four", "five"};
for (int i = 0; i < 6; i++) {
cout << "Adding " << items[i] << endl;
bool success = queue.Enqueue(items[i]);
if (!success)
cout << "Failed to add " << items[i] << " to the queue." << endl;
}
cout << "Queue contains, from front to back, zero one two three four five." << endl;
cout << "Checking Copy Constructor tester " << endl;
LinkedQueue<string> copy_of_queue(queue);
cout << "Copy of queue contains, from front to back, ";
for (int i = 0; i < 6; i++)
{
cout << " " << copy_of_queue.PeekFront();
copy_of_queue.Dequeue();
}
cout << "." << endl;
/*
cout << "Checking Assignment Operator tester " << endl;
LinkedQueue<string> assigned_queue;
assigned_queue.Enqueue("ha");
assigned_queue.Enqueue("ba");
assigned_queue = queue;
cout << assigned_queue << endl;*/
/* cout << "Assigned queue contains, from front to back, ";
for (int i = 0; i < 6; i++)
{
cout << " " << assigned_queue.PeekFront();
assigned_queue.Dequeue();
}
cout << "." << endl;
cout << "Original queue contains, from front to back,";
for (int i = 0; i < 6; i++) {
cout << " " << queue.PeekFront();
queue.Dequeue();
}
cout << "." << endl << endl; */
} // end copyConstructorTester
int main()
{
CopyConstructorAndAssignmentTester();
char a;
cin >> a;
//ConcatenateTester();
//return 0;
} // end main
EDIT: Oh crap, this stumps more people than I thought. XD. I thought I made a blatantly obvious mistake.
This may not be the answer you are looking for, and I'm finding it difficult to spot mistakes in your code lacking the full information of the states being manipulated.
The linked list logic looks all right: nothing jumps out at me as being faulty there in terms of the logic used to copy. Put in a distilled form:
first_node = last_node = new Node(other.first_node->data);
for (Node* other_node = other.first_node->next; other_node; other_node = other_node->next)
{
Node* new_node = new Node(other_node->data);
last_node->next = new_node;
last_node = new_node;
}
last_node->next = nullptr;
I believe this is what you have and it should be correct in terms of the overall logic. Any problems will probably be found elsewhere. Nevertheless, it should make your life easier to reduce the number of states you're working with. This 'new_chain_ptr' is unnecessary and you can just write out the results to 'back_ptr_' directly.
However, I have a different suggestion. You have the rest of the Queue working correctly, yes, including these methods like 'Enqueue'? If so, your copy constructor can be more trivially implemented just using what works already. Start with the state for an empty queue, and then read the elements from the other queue and 'Enqueue' those elements into your copy. Now you can avoid getting yourself tangled up in the low-level linked list logic by utilizing the parts you already know are functioning like so:
// Create empty queue.
first_node = last_node = nullptr;
// Enqueue elements from other queue.
for (Node* other_node = other.first_node; other_node; other_node = other_node->next)
Enqueue(other_node->data);
It might cost you an additional branch or so per iteration but remember that correctness always precedes efficiency, and you can come back and optimize once you have it working. Remember to handle self-assignment if the logic cannot work properly in those cases.
And yes, a debugger will give you a massive edge in accelerating the understanding of the nature of your code in addition to spotting mistakes more quickly.
I am implementing a tree which is a Binary Expression Tree. The leaf nodes are numbers, non-leaf nodes are math operators. Succesfully implemented printInorder,PostOrder, PreOrder, evaluate. But stucked with the printLevel().
Here is my int main ()
int main()
{
EXTree myTree;
string tests[] = {"2.1*3.1+4.2", "(2.0+1.3)/1.4", "2.*(1.3+1.4)","1.2*(1.3+1.4/0.5)","1.2*(1.3+1.4/0.5)-4.4", "1.2*(1.3+1.4/0.5)- (9/3)"};
for (int i=0; i < 6; i++)
{
myTree.build (tests[i]);
myTree.printInorder();
myTree.printPreorder();
myTree.printPostorder();
myTree.printLevel(); //Starting from level = 0
cout << "Evaulating myTree = " << format(myTree.evaluate(),2) << endl;
myTree.removeAll(); // removes all the nodes
}
}
printLevel(); only prints the level of the tree given above and its initally 0.
and here is my printLevel function.
void EXTree:: printLevel()
{
queue<Node*> levelq;
levelq.push(root);
cout << "Current Level is: ";
while( levelq.size() > 0 )
{
Node *cur = levelq.front();
cout << cur->Root << " ";
levelq.pop();
if (cur->Left) levelq.push(cur->Left);
if (cur->Right) levelq.push(cur->Right);
}
cout << endl;
}
But I really didnt understand how to implement the printLevel. Appreciate for any help to clarify it.
I just implemented the inOrder algorith to my printLevel and tried to change it but still didnt get it.
Since you have no problem with recursion, this would work without queue:
void EXTree:: printLevel()
{
int currentLevel = 0;
if (root)
{
cout << "Current Level is: ";
printLevelHelper(root,currentLevel);
}
else
cout << "This BST is Empty\n";
}
// Declare a private method:
void EXTree:: printLevelHelper(Node* &n, int ¤tLevel)
{
cout << currentLevel << ' ';
if (n->Left)
{
currentLevel++;
printLevelHelper(n->Left,currentLevel);
currentLevel--;
}
if (n->Right)
{
currentLevel++;
printLevelHelper(n->Right,currentLevel);
currentLevel--;
}
}
When using Breadth First Search to print the nodes on one level immediately adjacent to each other, you'd just observe when the leftmost child of the leftmost node on the current level pops out of the queue: this must be the start of the next level. I could easily write the code but I'd guess it would incomprehensible for you and this homework is for you (I think you want to label your post appropriately as homework, BTW). Most of your implementation looks like a straight forward implementation. The only thing missing is detecting that the next level is reached.
I am working on a Polynomial class which uses the STL linked list. One of the functions requires me to add two Polynomial's together. For some reason, the += operator seems to be duplicating the node, as opposed to merely modifying the contents.
Here is the class declaration:
class Polynomial
{
public:
Polynomial(pair<double,int>); //Specified constructor
void add(const Polynomial&);
void print();
private:
Polynomial(); //Default constructor
list<pair<double,int> > terms;
};
This is the add member function:
void Polynomial::add(const Polynomial& rhs)
{
list<pair<double,int> >::const_iterator r;
list<pair<double,int> >::iterator l;
for(r=rhs.terms.begin(); r!=rhs.terms.end(); r++)
{
bool match=0;
//Check to see if we have an existing nth order node
for(l=terms.begin(); l!=terms.end(); l++)
{
//If we do, just add the coefficients together
if(l->second == r->second)
{
l->first += r->first;
match = 1;
}
}
//If there was no matching existing node, we need to find out
//where to insert it into the list.
if(!match)
{
l=terms.begin();
bool inserted=0; //Sentinel for the loop
while(l!=terms.end() && !inserted)
{
//If there's only one term in the list
//Just compare and stick it in front or behind the existing node
if(terms.size()==1)
{
int this_exp = l->second;
int exp_to_ins = r->second;
if(exp_to_ins > this_exp) terms.push_back((*r));
if(exp_to_ins < this_exp) terms.push_front((*r));
inserted = 1;
}
//If there's more than one node, we need to traverse the list
if(terms.size()>1)
{
if(l!=terms.begin())
{
int this_exp = l->second;
l++;
int next_exp = l->second;
int exp_to_ins = r->second;
//If the new node value is between the current and next node
//Insert between them.
if((this_exp < exp_to_ins) && (exp_to_ins < next_exp))
{
terms.insert(l,(*r));
inserted = 1;
}
}
else if(l==terms.begin())
{
int this_exp = l->second;
int exp_to_ins = r->second;
//This will be the smallest order node
//Put it in the top spot
if(this_exp > exp_to_ins)
{
terms.push_front((*r));
inserted = 1;
}
l++;
}
}
}
//If we've traversed the list and can't find the right place
//this must be the greatest order node in the list
//so just tack it on the end.
if(!inserted) terms.push_back((*r));
}
}
}
Works fine with ordering the nodes in the correct order, but we have an existing nth order node, rather than just adding the coefficients together, it keeps the original node but seems to make a second node with the coefficients added together, and I have no idea why.
If I run the print function, for what should be F(x) = -2x^7 + 3x^6 - 11x^5 - 2x^4, instead I get F(x) = -2x^7 + 3x^6 - 11x^5 - 10x^5. If I call the size() function on the list, I get 4. But if I run the following code to print out the info from the nodes in the list:
stringstream test;
for(i=terms.end(); i!=terms.begin(); i--)
{
test << "Coefficient: " << i->first << " ";
test << "Exp: " << i->second << endl;
}
cout << "Size: " << terms.size() << endl;
cout << test.str();
The following is output:
Coefficient: -10 Exp: 5
Coefficient: -2 Exp: 7
Coefficient: 3 Exp: 6
Coefficient: -11 Exp: 5
Any help greatly appreciated.
EDIT: This is the test program.
Polynomial p(pair<double, int>(-10, 5));
p.add(Polynomial(pair<double,int> (-2,4)));
p.add(Polynomial(pair<double,int> (3,6)));
p.add(Polynomial(pair<double,int> (-2,7)));
p.add(Polynomial(pair<double, int> (-1,5)));
Your add() function seems to be correct except the print:
for(i=terms.end(); i!=terms.begin(); i--)
{
test << "Coefficient: " << i->first << " ";
test << "Exp: " << i->second << endl;
}
This is completely wrong, and invokes undefined behavior. i is initially terms.end() and you've dereferencing it? items.end() returns past-the-end iterator. Even if I assume it correct for a while, the condition i!=terms.begin() means the first element is never printed!
So the fix is this:
for(list<pair<double,int> >::iterator i=terms.begin(); i!=terms.end(); i++)
{
test << "Coefficient: " << i->first << " ";
test << "Exp: " << i->second << endl;
}
And it prints expected output:
Size: 4
Coefficient: -2 Exp: 4
Coefficient: -11 Exp: 5
Coefficient: 3 Exp: 6
Coefficient: -2 Exp: 7
Is it not correct?
See the output yourself here also : http://www.ideone.com/p8mwJ
By the way, instead of add, you could make it operator+= instead, as:
const Polynomial& operator+=(const Polynomial& rhs)
{
//same code as before
return *this;
}
If you write so, then you can add polynomials as:
Polynomial p(pair<double, int>(-10, 5));
p += Polynomial(pair<double,int> (-2,4));
p += Polynomial(pair<double,int> (3,6));
p += Polynomial(pair<double,int> (-2,7));
p += Polynomial(pair<double, int> (-1,5));
Demo : http://www.ideone.com/aA1zF
I just read your comment, and came to know that you want to print it in reverse order, in that case, you could use rbegin() and rend() instead of begin() and end() as:
for(list<pair<double,int> >::const_reverse_iterator i=terms.rbegin();
i!=terms.rend();
i++)
{
test << "Coefficient: " << i->first << " ";
test << "Exp: " << i->second << endl;
}
I would also advice you to make print a const function as :
void print() const
//^^^^ this makes the function const!
Better yet overload operator<< .
Anyway reverse order printing demo : http://www.ideone.com/Vk6XB
Your test loop (the one printing in the stringstream) is incorrect: it's undefined behavior to dereference the end () iterator. Probably your "std::list" is implemented in a circular way (i.e. with begin == end+1) so dereferencing "end" gives you *begin in your test loop.
Use reverse iterators to print the list in reverse order:
for (i = list.rbegin (); i != list.rend (); ++i)
{
test << "Coefficient: " << i->first ; // etc.
}
Besides the problem pointed out by #Nawaz, there is also a problem in the Polynomial::add function.
If the if(terms.size()==1) block is executed, a new item is inserted in the list. But that increases the size of the list by one, so the if(terms.size()>1) block will also be executed. And this can insert the same node once more.
A bit further in the while loop, you increment l, and proceed using the next node, without checking whether it's valid (ie. without comparing to terms.end()).
There might be more such mistakes, but these came up after a cursory glance.