C++ Boggle Solver Issues - c++

void scoreBoardHelper(Grid<char>& board, Lexicon& lex, Set<string>& visitedPrefixes, string current, GridLocation location, Set<string>& foundWords, Set<GridLocation> visitedTiles){
if(lex.contains(current) && current.size()>3){
foundWords.add(current);
}
if(current == ""){
current += board[location];
visitedTiles.add(location);
}
//check neighbors
GridLocation neighbor = location;
for(int i = 0; i<8; i++){
switch (i) {
case 0:
neighbor.col++;
break;
case 1:
neighbor.col--;
break;
case 2:
neighbor.row++;
break;
case 3:
neighbor.row--;
break;
case 4:
neighbor.col++;
neighbor.row++;
break;
case 5:
neighbor.col--;
neighbor.row--;
break;
case 6:
neighbor.col--;
neighbor.row++;
break;
case 7:
neighbor.col++;
neighbor.row--;
break;
}
if(board.inBounds(neighbor) && board[neighbor]!=current[current.size()-2] && !visitedTiles.contains(neighbor) && lex.containsPrefix(current + board[neighbor]) && !visitedPrefixes.contains(current + board[neighbor])){
visitedPrefixes.add(current + board[neighbor]);
visitedTiles.add(neighbor);
scoreBoardHelper(board, lex, visitedPrefixes, current + board[neighbor], neighbor, foundWords, visitedTiles);
}
neighbor = location;
}
}
int scoreBoard(Grid<char>& board, Lexicon& lex) {
Set<string> visitedPrefixes;
Set<GridLocation> visitedTiles;
string current = "";
GridLocation location;
Set<string> foundWords;
for(int r=0;r<board.numRows();r++){
location.row=r;
for(int c=0;c<board.numCols();c++){
location.col=c;
scoreBoardHelper(board, lex, visitedPrefixes, current, location, foundWords, visitedTiles);
}
}
int previousPoints = 0;
for(string word : foundWords){
cout<<"found word: "<<word<<endl;
previousPoints += points(word);
}
return previousPoints;
}
I wrote these 2 functions but they don't seem to solve boggle. When I remove the !visitedTiles.contains(neighbor) check, it works as expected but it finds extra words that it should discard. When it has this check it narrows the solution unexpectedly and finds 2 words where it should find many more. Note: The points function works fine.

Related

Reverse Polish notation Calculator

I am currently working on a RPN calculator, it takes an infix expression converts it to postfix and shows the answer. I mostly got it right, but when I pop the answer from the stack if shows only the last digit of the result
ex
Enter infix: (1+1)*13+10/2
Postfix: 11+13*102/+
Result is: 1
Enter infix: 2*13+10/2
Postfix: 213*102/+
Result is:1
It gets it right for this kind of inputs
Enter infix: 3*2+5
Postfix: 32*5+
Result is : 11
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
using namespace std;
class infix2postfix
{
public:
void push(int symbol);
int pop();
void infix_to_postfix();
int priority(char symbol);
int isEmpty();
int white_space(char);
int eval_post();
};
char infix[100], postfix[100];
int stack[100];
int top;
int main()
{
infix2postfix ip;
top=-1;
cout<<"Enter infix : ";
gets(infix);
ip.infix_to_postfix();
cout<<"Postfix : "<<postfix<<endl;
cout<<"Result is : "<<ip.eval_post()<<endl;
return 1;
}
void infix2postfix :: infix_to_postfix()
{
int i,p=0;
char next;
char symbol;
for(i=0; i<strlen(infix); i++)
{
symbol=infix[i];
if(!white_space(symbol))
{
switch(symbol)
{
case '(':
push(symbol);
break;
case ')':
while((next=pop())!='(')
postfix[p++] = next;
break;
case '+':
case '-':
case '*':
case '/':
case '%':
case '^':
while( !isEmpty( ) && priority(stack[top])>= priority(symbol) )
postfix[p++]=pop();
push(symbol);
break;
default: /*if an operand comes*/
postfix[p++]=symbol;
}
}
}
while(!isEmpty( ))
postfix[p++]=pop();
postfix[p]='\0'; /*End postfix with'\0' to make it a string*/
}
/*This function returns the priority of the operator*/
int infix2postfix :: priority(char symbol)
{
switch(symbol)
{
case '(':
return 0;
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
default :
return 0;
}
}
void infix2postfix :: push(int symbol)
{
if(top>100)
{
cout<<"Stack overflow\n";
exit(1);
}
stack[++top]=symbol;
}
int infix2postfix :: pop()
{
if( isEmpty() )
{
cout<<"Stack underflow\n";
exit(1);
}
return (stack[top--]);
}
int infix2postfix :: isEmpty()
{
if(top==-1)
return 1;
else
return 0;
}
int infix2postfix :: white_space(char symbol)
{
if( symbol == ' ' || symbol == '\t' )
return 1;
else
return 0;
}
int infix2postfix :: eval_post()
{
int a,b,i,temp,result;
for(i=0; i<strlen(postfix); i++)
{
if(postfix[i]<='9' && postfix[i]>='0')
push(postfix[i]-'0');
else
{
a=pop();
b=pop();
switch(postfix[i])
{
case '+':
temp=b+a;
break;
case '-':
temp=b-a;
break;
case '*':
temp=b*a;
break;
case '/':
temp=b/a;
break;
case '%':
temp=b%a;
break;
case '^':
temp=pow(b,a);
}
push(temp);
}
}
result=pop();
return result;
}
Consider what happens when eval_post() is given 213*102/+ to work with. Let's start in the middle, with the '1' after the asterisk. The '1' is a digit, so push it [stack ends with: 1]. Similarly, the 0 and 2 get pushed [stack ends with: 1, 0, 2]. Then the division symbol is encountered, so pop 2 and 0, then push 0/2 = 0 [stack ends with: 1, 0]. Finally, the addition symbol is encountered, so pop 0 and 1, then push 1+0=1, which is then popped as your answer.
One symptom of your problem is that, if things work, the stack should be empty when eval_post() returns. However, it is not empty when your infix includes numbers with more than one digit. Note that "10" gets pushed onto the stack as two numbers: "1" followed by "0". You want the value 10 pushed.
There are also some style problems with the code, but this appears to be the main functional problem.

Declared enum and IF on its elements

I'm working on Snake game. Although I have a little problem. I created enum with possible directions:
enum Direction{
n = 0, // north
e = 1, // east
s = 2, // south
w = 3 // west
};
And then I created a ChangeDirection() function, which basing on previous direction will change it. (For example, if you go to the right/east, you can't switch to left/west):
void ChangeDirection(char key){
switch (key){
case 'w':
if (Direction != 2)
Direction = 0;
break;
case 'd':
if (Direction != 3)
Direction = 1;
break;
case 's':
if (Direction != 0)
Direction = 2;
break;
case 'a':
if (Direction != 1)
Direction = 3;
break;
}
But my ifs clearly don't work; following error occurs:
Expected primary-expression before '!=' token
Anyone could help? How can I rearrange it to work? Why doesn't it work? Thanks!
Direction CurrentDir = e; // somewhere in the code
// ....
//another place in the code, so on..
CurrentDir = s;
//....
void ChangeDirection(char key){
switch (key){
case 'w':
if (CurrentDir != s)
CurrentDir = n;
break;
case 'd':
if (CurrentDir != w)
CurrentDir = e;
break;
// so on ..
}

Sorting array of pointers

I am trying to sort an array of pointers, which are pointing to a character array of names. I can get the program to sort the first two names but not the rest. Also the names are part of a structure.
void sort( Class* ptrs[], int num_classes){
bool swap=false;
do
{
swap=false;
for (int i=0; i<=num_classes-1; i++) {
if (ptrs[i]->title[i]>ptrs[i+1]->title[i]) {
Swap(&ptrs[i], &ptrs[i+1]);
swap=true;
}
}
}while(swap);
}
void Swap(Class** num1,Class** num2){
Class* temp=*num1;
*num1=*num2;
*num2=temp;
}
struct Class{
char title[MAX];
int units;
char grade;
};
int main(){
int choice,num_classes=0;
char class_selection[MAX];
Class* ptrs[MAX];
char* class_ptr[MAX];
bool Continue=false;
Class classes[MAX];
for (int i = 0; i < MAX; i++){
ptrs[i]=&classes[i];
}
cout<<" 1. Add new class"<<endl<<" 2. Edit an existing class"<<endl<<" 3. Display a class"<<endl<<" 4. List all classes"<<endl<<" 5. Display GPA"<<endl<<" 6. Delete all classes"<<endl<<" 7. Quit"<<endl<<"Enter selection number: ";
cin>>choice;
if (choice!=7) {
Continue=true;
}
switch (choice) {
case 1:
add(ptrs,num_classes);
num_classes++;
break;
case 2:
edit(ptrs,num_classes);
cin.ignore();
break;
case 3:
sort(ptrs,num_classes);
cin.ignore();
cout<<"Enter the name of the class to display: ";
cin.getline(class_selection, MAX);
for (int j =0; j<MAX; j++) {
class_ptr[j]=&class_selection[j];
}
Bin_search(ptrs,num_classes,class_ptr);
break;
case 4:
sort(ptrs,num_classes);
display(ptrs,num_classes);
break;
case 5:
// display_GPA();
break;
case 6:
// delete_end();
break;
}
if (choice == 7) {
// delete_end();
//system('pause");
return 0;
}
}
This code is comparing i-th character of corresponding titles, not the whole titles:
if (ptrs[i]->title[i]>ptrs[i+1]->title[i]) {
// ^^^ ^^^
Possible ways to solve:
Change this
char title[MAX];
to
std::string title;
And after that you'll be able to write
if (ptrs[i]->title > ptrs[i+1]->title) {
Only if you can't use std::string for some reason, use strcmp:
if (strcmp(ptrs[i]->title, ptrs[i+1]->title) > 0) {

c++ Recursive Tree building with pointers and a state machine

I have a simple state machine (entered below). My major problem is that I am trying to make a recursive call to the function that is my state machine. What I do upon entry of the function is create a new node for my tree and then push that through. When I do a recursive call, I create a new node over and over. This can work, but when adding children to a parent I'm a little confused. Can someone help look over this and help me take my tree node (parent I'm assuming) and attach a child to it?
TreeNodeClass* ProcessTree(TokenT token, vector <list <stateAssoc> >& vecTree, int depth)
{
int state = 1; //Assume this is a new record.
bool noState = false;
bool update = true;
int dex = 0;
string root, value, data, tag;
TreeNodeClass* treeNode;
treeNode = new TreeNodeClass; //Assume a new node per state machine visit.
//Need 11 to break out of loop as well.
while(state != 10)
{
switch(state)
{
case 1: dex = 1;
break;
case 2: dex = 6;
root = yylval;
break;
case 3: dex = 7;
break;
case 4: dex = 3;
value = yylval;
treeNode->CreateAttrib(root, value);
break;
case 5: dex = 2;
break;
case 6: dex = 4;
data = yylval;
break;
case 7: //Really Don't do anything. Set the tag creation at 8...
dex = 8;
tag = yylval;
if(data != "" and data != "authors")
treeNode->CreateTag(data, tag);
break;
case 8: {
//New TreeNode already grabbed.
//TreeNodeClass* childNode = new TreeNodeClass;
childNode = ProcessTree(token, vecTree, depth+1);
childNode->SetHeight(depth);
treeNode->AddChildren(childNode);
}
token = TokenT(yylex()); //Get a new token to process.
dex = 5;
break;
case 9: dex = 9;
update = false;
if(yylval != treeNode->ReturnTag())
{
state = 11;
}
break;
case 10: update = false;
treeNode->SetHeight(1);
break;
default: cout << "Error " << endl;
cout << state << endl;
cin.get();
break;
}
if(!noState)
state = FindMatch(vecTree[dex], token);
if(update)
token = TokenT(yylex());
else
update = true;
}
return treeNode;
}
You may assume that the dex is simply an index to an array of lists that will return a correct state or 11 (error). Also you may assume that this funciton has atleast been called once on an input file and has started parsing. Thank you for your help.
Looking at your code, you have
int state = 1;
//Code
while(state != 10) {
switch(state) {
case:1 dex = 1; break; //Only case you run
//more cases
case 8: { //never enter here
//New TreeNode already grabbed.
//TreeNodeClass* childNode = new TreeNodeClass;
childNode = ProcessTree(token, vecTree, depth+1);
childNode->SetHeight(depth);
treeNode->AddChildren(childNode); //should work if assuming function is correct
}
//stuff
break;
default: break;//blah
}
}
//blah
return treeNode;
I see no other reason than the fact state is always equal to 1 that your code at case 8 would fail. This is assuming treeNodeClass::AddChildren(TreeNodeClass*) has been properly implemented. WIthout that code, I can assume it's not your problem. Is there some method in which state wouldn't be 1 in the switch?

C++ Stack Implementation (not working right)

Here's the previous thread where I got help with this same lab. My stack is misbehaving, to say the least, when I add an item to stack, to print out later, it doesn't seem to add right. I always print out plus'(+), not matter if I enter another operand(*,/,+).
I am using a stack to convert a, user inputed, infix express to postfix. It seems to work fine except printing out the operands in the stack at the end.
#include <iostream>;
#include <vector>
using namespace std;
class DishWell{
public:
char ReturnFront(){
return Well.front();
}
void Push(char x){
Well.push_back(x);
}
void Pop(){
Well.pop_back();
}
bool IsEmpty(){
return Well.empty();
}
private:
vector<char> Well;
};
bool Precidence(char Input, char Stack){
int InputPrecidence,StackPrecidence;
switch (Input){
case '*':
InputPrecidence = 4;
break;
case '/':
InputPrecidence = 4;
break;
case '+':
InputPrecidence = 3;
break;
case '-':
InputPrecidence = 3;
break;
case '(':
InputPrecidence = 2;
break;
default:
InputPrecidence = 0;
}
switch (Stack){
case '*':
StackPrecidence = 4;
break;
case '/':
StackPrecidence = 4;
break;
case '+':
StackPrecidence = 3;
break;
case '-':
StackPrecidence = 3;
break;
case '(':
StackPrecidence = 2;
break;
default:
StackPrecidence = 0;
}
if(InputPrecidence>StackPrecidence) return true;
else return false;
}
int main(int argc, char** argv) {
DishWell DishTray;
char Input;
bool InputFlag;
InputFlag = true;
cout<<"Enter Input, invalid input will terminate"<<endl;
while(InputFlag){
cout<<"Input: ";
cin>>Input;
cout<<endl;
if((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||Input>='0'&&Input<='9')))//If Digit or Number
cout<<Input;
if((Input=='*'||Input=='/'||Input=='+'||Input=='-')){//if operand
if(DishTray.IsEmpty())
DishTray.Push(Input);
else if(Precidence(Input,DishTray.ReturnFront()))
DishTray.Push(Input);
else if(!Precidence(Input,DishTray.ReturnFront()))
cout<<"Output: "<<Input<<endl;
}
else if(!((((Input>='a'&&Input<='z')||(Input>='A'&&Input<='Z'))||(Input>='0'&&Input<='9')))||((Input=='*'||Input=='/'||Input=='+'||Input=='-')))//if not digit/numer or operand
InputFlag = false;
}
int counter = 0;
while(!DishTray.IsEmpty()){
counter++;
cout<<counter<<" Element "<<DishTray.ReturnFront()<<endl;
DishTray.Pop();
}
return 0;
Thank you, Macaire Bell
Your loop calls front(), but then calls pop_back(). This will always return the first element in the vector, until all elements are popped, since you are never erasing the front element. Your ReturnFront() method should probably be:
char ReturnBack(){
return Well.back();
}
And then your loop at the end:
while(!DishTray.IsEmpty()){
counter++;
cout<<counter<<" Element "<<DishTray.ReturnBack()<<endl; // will return last element
DishTray.Pop(); // actually pop the element printed
}
When you're working with a stack, you usually want to be able to see the value on the top of the stack. Your class only allows the very first item pushed (i.e. the bottom of the stack) to be visible. Your ReturnFront() should probably return Well.back() and perhaps it should be called something like ReturnTop().
Wouldn't you want to see the value returned from pop_back() instead if discarding it as you're currently doing?