tables-cpp

#include <iostream>
#include <string>

using namespace std;

string represent(int i) {
  const char* symbs = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  if (i<36)
    return string(1,symbs[i]);
  else
    return "[" + to_string(i) + "]";
}

string showIntAtBase(int base, int val) {
  string result;
  do {
    int n = val / base,
        r = val % base;
    result = represent(r) + result;
    val = n;
  } while(val!=0);
  return result;
}

string showBase(int base, int val) {
  string r = showIntAtBase(base,val);
  int pad = 2;
  if (r.length()<pad)
    return string(pad-r.length(), ' ')+r;
  else
    return r;
}

template<class F>
string row(F op, int base, int i) {
  string result="|";
  for(int start=0; start<base; ++start) {
    result += " " + showBase(base, op(start,i)) + " |";
  }
  return result;
}

template<class F>
string table(F op, int base) {
  string result;
  for(int start=0; start<base; ++start) {
    result += "| " + showBase(base,start) + string(" ") + row(op, base, start) + "\n";
  }
  return result+"\n";
}

int mult(int a, int b) {
  return a*b;
}

int sum(int a, int b) {
  return a+b;
}

template<class F>
string mdTable(F op, int base) {
  string result;
  result = "|    " + row(mult, base, 1) + "\n|";

  for(int i=0; i<base+1; ++i)
    result += ":--:|";
  result += "\n";

  result += table(op,base);
  return result;
}

int main(int argc, char* argv[]) {
  int base = atoi(argv[1]);

  cout << mdTable(sum,base);
  cout << mdTable(mult,base);
  return 0;
}