patterncppMinor
Defusing a bomb using a state machine
Viewed 0 times
defusingusingstatemachinebomb
Problem
This code is a solution for /r/daily_programmer #293.
The idea of this challenge is, you are given input in the form of colored wires:
and you are then to determine if cutting the input wires in the order they are listed will cause the "bomb" to detonate or defuse.
What causes the detonation is determined by the previous wire cut. The challenge lists a pre-determined set of colored wires for which the previous wire is not allowed to be followed by a cut of that color or the bomb will detonate.
The idea of this challenge is, you are given input in the form of colored wires:
red wire
green wire
blue wire
...and you are then to determine if cutting the input wires in the order they are listed will cause the "bomb" to detonate or defuse.
What causes the detonation is determined by the previous wire cut. The challenge lists a pre-determined set of colored wires for which the previous wire is not allowed to be followed by a cut of that color or the bomb will detonate.
#include
#include
#include
using namespace std;
#define ERROR(msg) \
do { \
cout previous_cuts;
public:
Bomb(string initial_wire);
int cut_wire(string wire);
vector get_previous_cuts();
};
Bomb::Bomb(string initial_wire)
{
string wire(initial_wire);
Wire current_wire(wire);
previous_cuts.push_back(current_wire);
}
int Bomb::cut_wire(string wire)
{
Wire new_wire(wire);
previous_cuts.push_back(new_wire);
if (current_wire.is_conflicted(new_wire))
return explode();
current_wire = new_wire;
return 0;
}
int Bomb::explode(void)
{
cout \n");
string bomb_fname(argv[1]);
ifstream bomb_fh(bomb_fname);
if (!bomb_fh.is_open())
ERROR("Error reading bomb input\n");
string input_wire_color;
getline(bomb_fh, input_wire_color);
Bomb bomb(input_wire_color);
while (getline(bomb_fh, input_wire_color)) {
if (bomb.cut_wire(input_wire_color) < 0)
return 0;
}
cout << "Bomb defused\n";
return 0;
}Solution
Two things stand out:
-
In your
This is creating a locally scoped variable
-
You are keeping track of more information than you need to. You only need know the previous wire to know if the current wire is going to cause an explosion. You are however keeping track of every wire in
-
In your
Bomb constructor, you do this:Wire current_wire(wire);This is creating a locally scoped variable
current_wire and setting its value to wire, it's not updating the member variable of the class.-
You are keeping track of more information than you need to. You only need know the previous wire to know if the current wire is going to cause an explosion. You are however keeping track of every wire in
previous_cuts, although you're not using the value anyway. Generally, you're better off not having redundant code, so if you're not going to use it, get rid of it.Code Snippets
Wire current_wire(wire);Context
StackExchange Code Review Q#147921, answer score: 3
Revisions (0)
No revisions yet.