Thursday, June 28, 2012

C++ - Convert list of numbers to list of ranges

I recently needed to convert a list of zip codes to a list of ranges of zip codes. Example below (the numbers are only for illustration, real zip-code are 6 or 7 digit)-
Input: {1, 2, 3, 4, 6, 8, 9}

Output: {(1,4), (6,6), (8, 9)}

What is the use?
I needed to enter it in a database table like:
+----+-------+-----+
| id | start | end |
+----+-------+-----+
|  1 |     1 |   4 |
|  2 |     6 |   6 |
|  3 |     8 |   9 |
+----+-------+-----+
for looking up if a input zip-code falls in any range (zip code where our carrier accepts shipments).

This is my small program in C++ to do this (Download)-
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

template <typename T>
inline T convert(string &s)
{
T out;
istringstream ss(s);
ss >> out;
return out;
}

int main()
{
ifstream infile("input.txt");
ofstream outfile("output.txt");

string cur_line, last_line;
int cur, last;

if (infile.good()) {
getline(infile, cur_line);
cur = convert<int>(cur_line);
outfile << cur_line << ',';
last = cur;
}

while(getline(infile, cur_line))
{
cur = convert<int>(cur_line);

if (cur != last + 1) {
outfile << last_line << '\n';
outfile << cur_line << ',';
}

last = cur;
last_line = cur_line;
}

outfile << last_line;

infile.close();
outfile.close();

return 0;
}

I hope you find good use for this program.