Skip to content

Instantly share code, notes, and snippets.

@skytreader
Last active August 29, 2015 13:55
Show Gist options
  • Save skytreader/8706127 to your computer and use it in GitHub Desktop.
Save skytreader/8706127 to your computer and use it in GitHub Desktop.
The Worm Turns
#include <stdio.h>
#include <string.h>
#include <list>
#include <iostream>
#include <sstream>
using namespace std;
typedef struct point{
int row, col;
} point;
bool ranToSelf(std::list<point> snakeRep){
point head = snakeRep.front();
int eqCount = 0;
for(std::list<point>::iterator it = snakeRep.begin(); it != snakeRep.end(); it++){
if((*it).row == head.row && (*it).col == head.col){
eqCount++;
}
}
return eqCount == 2;
}
bool ranOffBoard(std::list<point> snakeRep){
point head = snakeRep.front();
return 0 >= head.row || head.row > 50 || 0 >= head.col || head.col > 50;
}
std::string move_snake(std::string movestring){
std::list<point> snakeRep;
for(int i = 30; i >= 11; i--){
point p;
p.row = 25;
p.col = i;
snakeRep.insert(snakeRep.end(), p);
}
int moveCounter = 1;
for(std::string::iterator it = movestring.begin(); it != movestring.end(); it++){
// Move the tail
snakeRep.pop_back();
// Get the head
point head = snakeRep.front();
point newHead;
newHead.row = -1;
newHead.col = -1;
switch(*it){
case 'N':
newHead.row = head.row - 1;
newHead.col = head.col;
break;
case 'E':
newHead.col = head.col + 1;
newHead.row = head.row;
break;
case 'W':
newHead.col = head.col - 1;
newHead.row = head.row;
break;
case 'S':
newHead.row = head.row + 1;
newHead.col = head.col;
break;
}
snakeRep.push_front(newHead);
if(ranToSelf(snakeRep)){
std::stringstream ss;
ss << moveCounter;
return "The worm ran into itself on move " + ss.str() + ".\n";
} else if(ranOffBoard(snakeRep)){
std::stringstream ss;
ss << moveCounter;
return "The worm ran off the board on move " + ss.str() + ".\n";
}
moveCounter++;
}
std:: stringstream ss;
ss << moveCounter;
return "The worm successfully made all " + ss.str() + " moves.\n";
}
int main(){
int moveLength;
cin >> moveLength;
while(moveLength != 0){
std::string moveString;
cin >> moveString;
cout << move_snake(moveString);
cin >> moveLength;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment