#include <iostream>
#include <string>
using namespace std;

/**
   A simulated traffic light.
*/
class TrafficLight
{
public:
   TrafficLight();
   TrafficLight(string initial_color);
   void next();
   string get_color() const;
   int get_reds() const;

private:
   int steps; // counts how many times next() has been called
};

TrafficLight::TrafficLight()
{
   steps = 0; // green
}

TrafficLight::TrafficLight(string initial_color)
{
   if (initial_color == "green")
      steps = 0;
   else if (initial_color == "yellow")
      steps = 1;
   else // red
      steps = 2;
}

void TrafficLight::next()
{
   steps++;
}

string TrafficLight::get_color() const
{
   int state = steps % 3;
   if (state == 0) return "green";
   if (state == 1) return "yellow";
   return "red";
}

int TrafficLight::get_reds() const
{
   // Red occurs at steps 2, 5, 8, ...
   if (steps < 2) return 0;
   return (steps - 2) / 3 + 1;
}

int main()
{
   TrafficLight tl1;
   cout << tl1.get_color() << endl;
   cout << "Expected: green" << endl;
   cout << tl1.get_reds() << endl;
   cout << "Expected: 0" << endl;

   tl1.next();
   cout << tl1.get_color() << endl;
   cout << "Expected: yellow" << endl;
   cout << tl1.get_reds() << endl;
   cout << "Expected: 0" << endl;

   tl1.next();
   cout << tl1.get_color() << endl;
   cout << "Expected: red" << endl;
   cout << tl1.get_reds() << endl;
   cout << "Expected: 1" << endl;

   tl1.next();
   cout << tl1.get_color() << endl;
   cout << "Expected: green" << endl;
   cout << tl1.get_reds() << endl;
   cout << "Expected: 1" << endl;

   TrafficLight tl2("red");
   cout << tl2.get_color() << endl;
   cout << "Expected: red" << endl;
   cout << tl2.get_reds() << endl;
   cout << "Expected: 1" << endl;

   tl2.next();
   cout << tl2.get_color() << endl;
   cout << "Expected: green" << endl;
   cout << tl2.get_reds() << endl;
   cout << "Expected: 1" << endl;

   tl2.next();
   tl2.next();
   cout << tl2.get_color() << endl;
   cout << "Expected: red" << endl;
   cout << tl2.get_reds() << endl;
   cout << "Expected: 2" << endl;

   return 0;
}

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: