Monday, April 21, 2014

HouseNumbers.cpp

I'm really digging algorithms lately!
*** 1.  Street Numbers ***

A computer programmer lives in a street with houses numbered consecutively
(from 1) down one side of the street. Every evening she walks her dog by


leaving her house and randomly turning left or right and walking to the
end of the street and back. One night she adds up the street numbers of
the houses she passes (excluding her own). The next time she walks the


other way she repeats this and finds, to her astonishment, that the two
sums are the same. Although this is determined in part by her house number
and in part by the number of houses in the street, she nevertheless feels


that this is a desirable property for her house to have and decides that
all her subsequent houses should exhibit it.

Write a program to find pairs of numbers that satisfy this condition.
To start your list the first two pairs are: (house number, last number):



         6         8
        35        49

- Your program must compute 10 of these pairs of numbers.
- Your program must run no longer than a few seconds.
- Please submit your source code and the results.
#include <iostream>

using namespace std;

class HouseNumbers {

public:
  void findHouseNumbers() {
        
    long currentNum = 5;
    long currentHigh = 6;
    long lowSum = 10;
    long highSum = 6;
    long numFound = 1;

    while (numFound < 11) {

      while (highSum < lowSum) {
        currentHigh++;
        highSum += currentHigh;
      }

      if (highSum == lowSum) {
        cout << "pair " << numFound << " found : currentNum=" << currentNum;
        cout << " currentHigh=" << currentHigh << " lowSum=" << lowSum;
        cout << " highSum=" << highSum << endl;
        numFound++;
      } else {
        highSum -= currentHigh;
        currentHigh--;
      }

      lowSum += currentNum;
      currentNum++;
      highSum -= currentNum;

    }
    return;
    
  }
};


int main() {
  HouseNumbers *h = new HouseNumbers();
  h->findHouseNumbers();
}