#include class Switch { public: Switch(bool c, Switch* n = nullptr, Switch* p = nullptr) : conducting(c), next(n), prev(p) {} bool getConducting() const { return conducting; } void toggleConducting() { conducting = !conducting; } Switch*& getNext() { return next; } Switch*& getPrev() { return prev; } private: Switch(Switch const&) = delete; Switch& operator=(Switch const&) = delete; bool conducting; Switch* next; Switch* prev; }; class Circuit { public: Circuit() : start(nullptr), current(nullptr) {} void add(bool state) { start = new Switch(state, start); if (start->getNext()) start->getNext()->getPrev() = start; } void print(std::ostream& os) const { Switch* cur = start; while (cur != nullptr) { bool on = cur->getConducting(); if (cur == current) os << (on ? 'i' : 'o'); else os << on; cur = cur->getNext(); } } bool goForward() { if (current && current->getNext()) current = current->getNext(); else if (current && !current->getNext()) return false; else if (start) current = start; if (current) current->toggleConducting(); return true; } void goBack() { if (current) current = current->getPrev(); else current = nullptr; if (current) current->toggleConducting(); } /* Solves the puzzle as it is now, from the position we are at now. * This solves the problem with minimal state information. * (more difficult than requirements on exam) */ void solveCurrentState(std::ostream& os) { os << "Not implemented!" << std::endl; } /* Check if a move forward will "win". */ bool winConditionMet() { std::cerr << "Not implemented!" << std::endl; return false; } private: Circuit(Circuit const&) = delete; Circuit& operator=(Circuit const&) = delete; Switch* start; Switch* current; }; #include int main() { std::random_device rnd; Circuit c; for (int i = 0; i < 10; ++i) c.add(rnd()%2); std::cout << "Switches in \"off\" state show as '0'." << std::endl; std::cout << "Switches in \"on\" state show as '1'." << std::endl; std::cout << "You show as 'i' if you are on an \"on\" switch." << std::endl; std::cout << "You show as 'o' if you are on an \"off\" switch." << std::endl; std::cout << "You can enter many commands at once." << std::endl; std::cout << "Command 'f' attempt to move forward." << std::endl; std::cout << "Command 'b' attempt to move backward." << std::endl; std::cout << "Command 's' print solution command string." << std::endl; std::cout << "Command 'q' quit the game." << std::endl; std::cout << "Press 'Enter' after your command(s)." << std::endl; char cmd; do { c.print(std::cout); std::cout << ": forward or back (f/b)? "; std::cin >> cmd; if ( cmd == 'f' || cmd == 'F' ) { if ( ! c.goForward()) { if ( c.winConditionMet() ) { std::cout << "You win!" << std::endl; break; } else { std::cout << "Some switch is still off!" << std::endl; } } } else if ( cmd == 'b' || cmd == 'B' ) { c.goBack(); } else if ( cmd == 's' ) { c.solveCurrentState(std::cout); } } while (cmd != 'q'); std::cout << std::endl; return 0; }