All pastes #737940 Raw Edit

Something

public text v1 · immutable
·published 2007-10-15 21:25 UTC
rendered paste body
/*
 * assignment number: 3
 * author: han
 * course: Computer Science II
 * description:
 * due: 2007-10-15
 * file: /home/hanumizzle/c++/recursion.cpp
 * time: 5:30-7:20
 */

#include <iostream>
#include <vector>

using namespace std;

void manipulate_lightbulbs(vector <bool>, int);
void show_lightbulbs(vector <bool>);

int main() {
  vector <bool> bulbs(10, false);

  manipulate_lightbulbs(bulbs, 0);
}

// Recursive function that iterates over the lightbulb and vector and toggles
// them according to the the current interval
void manipulate_lightbulbs(vector <bool> bulbs, int interval) {
  // Interval zero is special-cased; no switching occurs. Otherwise run through
  // and toggle the lightbulbs
  if (interval > 0) {
    // Starting at n, every nth bulb
    for (int i = interval - 1; i < bulbs.size(); i += interval) {
      bulbs[i] = !bulbs[i]; // On if off; off if on
    }
  }

  // Only recurse if current interval is less than length of vector. e.g., ten 
  // light bulbs means ten iterations:w
  if (interval < bulbs.size())
    manipulate_lightbulbs(bulbs, interval + 1);

  // Print out configuration *after* recursion; instances printed out in
  // reverse order, n, n - 1, n - 2, ... 0
  cout << "At position " << interval << ":\t";
  show_lightbulbs(bulbs);
}

void show_lightbulbs(vector <bool> bulbs) {
  // Outputs a cutesy string that looks like [X..X..XX.X]. Light bulbs that
  // are on are 'X's; '.' for off.
  cout << '[';

  for (int i = 0; i < bulbs.size(); i++) {
    cout << (bulbs[i] ? 'X' : '.');
  }

  cout << ']' << endl;
}