20-CS-122-001 Computer Science II Spring 2012
Hamming: Recursive Solution With Priority Queue

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

Prev      Next      Lectures      pqueue.h      pqueue.cc

#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include "pqueue.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 valfunc (void *ham) { 
   return ((HamSeq *)ham)->mult*first(((HamSeq *)ham)->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) {
   HamSeq *n = new HamSeq(p, 1);
   PQueue q(valfunc);
   q.insert(n);
   for (int i=1 ; i <= 3000 ; i++) {  
      n = (HamSeq *)q.dequeue();
      reallong *primes = n->primes;
      reallong multiplier = n->mult;

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

      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); 
}