20-CS-122-001 Computer Science II Spring 2012
Hamming: Recursive Solution With Heap (fast)

Virtual functions, classes, inheritance, lists, queues, stacks, applications

Prev      Next      Lectures      heap_a.h      heap_a.cc

#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include "heap_a.h"
using namespace std;

reallong first (reallong *p) { return *p; }
reallong *rest (reallong *p) { return p+1; }

class HamSeq {
friend void ham(reallong *);
friend reallong valfunc(void *);
   reallong *primes, mult;

public:
   HamSeq (reallong *p, reallong m) { primes = p; mult = m; }
   reallong value () { return mult*first(primes); }
};

reallong valfunc (void *obj) { 
   return ((HamSeq *)obj)->mult*first(((HamSeq *)obj)->primes); 
}

// ham(p) = 
//   if (p is null) return null;
//   return first(p) +| merge(times(ham(p), first(p)), ham(rest(p)));
//
void ham(reallong *p) {
   int i=1;
   HamSeq *n = new HamSeq(p, 1);
   Heap q(1000, valfunc);
   q.insert(n);
   while (true) {  
      n = (HamSeq *)q.dequeue();
      reallong *primes = n->primes;
      reallong multiplier = n->mult;

      cout << i++ << ":\t" << first(primes)*multiplier;
      q.insert(new HamSeq(primes, multiplier*first(primes)));
      if (first(rest(primes)) > 0)
         q.insert(new HamSeq(rest(primes), multiplier));
      getchar();

      delete n;
   }
}

int main(int argc, char **argv) {
   reallong *p = new reallong[argc];
   cout << "\nprime list:";
   p[argc-1]=0;
   for (int i=0; i < argc-1; i++) cout << " " << (p[i] = atoi(argv[i+1]));
   cout << "\n\n";
   ham(p); 
}