0

extracting continuous ranges from a integer vector

I have sorted vector(with non-repeated values) like this [1,2,3,6,7,8,12,15]

I need to extract every range from such vector like 1-3,6-8,12-15 in to a string like:

"0-3,6-8,12,15"

AJ.
  • 2,561
  • 9
  • 46
  • 81
  • `std::adjacent_find` with a lambda or something can help you here. If you're into that kinda thing. – Keith Layne Jul 26 '12 at 04:34
  • This is a near-exact duplicate, but I haven't found it yet. – chris Jul 26 '12 at 04:34
  • Well, the other one had [this](http://stackoverflow.com/questions/11652686/what-is-the-fastest-way-to-find-longest-consecutive-numbers-streak-in-vector) mentioned as a question that was very similar. I guess the exact dupe got deleted, though. – chris Jul 26 '12 at 04:37
  • 1
    Your approach is correct. I don't see a problem, if you haven't run into any issues, why are you posting? – Mahmoud Al-Qudsi Jul 26 '12 at 04:38
  • I am not sure if its a good solution. I need an efficient solution. – AJ. Jul 26 '12 at 04:44
  • @AJ.: It is already efficient. It is single pass, `O(n)` What more do you want? – Vinayak Garg Jul 26 '12 at 04:47
  • Just so you know, there exists `std::mismatch`. – chris Jul 26 '12 at 04:53
  • 1
    [Python version of this question](http://stackoverflow.com/questions/2154249/identify-groups-of-continuous-numbers-in-a-list) – jogojapan Jul 26 '12 at 05:42
  • 1
    AJ, it's not clear why you deleted the original and replaced it with an identical question. @chris [Here's the original](http://stackoverflow.com/q/11657075/). – Raymond Chen Jul 26 '12 at 16:14
  • @RaymondChen, Thanks, that would be why I couldn't see it. I figured the OP of it removed it. – chris Jul 26 '12 at 16:15

1 Answers1

0

I recently cooked this code. It reads from a file, and instead of string it outputs to a file. I am sure you can modify it to suit your needs.

#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;
}
Vinayak Garg
  • 6,518
  • 10
  • 53
  • 80