snippetcppMinor
Create ranges from an array of integers
Viewed 0 times
createarrayrangesintegersfrom
Problem
Given an array of
numbers.
Example:
Is there any improvement possible in this implementation?
ints, return a string identifying the range ofnumbers.
Example:
- Input arr - [0 1 2 7 21 22 1098 1099]
- Output - "0-2,7,21-22,1098-1099"
Is there any improvement possible in this implementation?
#include
#include
#include
#include
std::string range_creator(std::vector & vec)
{
std::sort(std::begin(vec),std::end(vec));
int first=vec.at(0);
int prev=first-1;
std::stringbuf buffer;
std::ostream os (&buffer);
for(auto &x : vec)
{
if(++prev == x)
continue;
else
{
if(first != --prev)
{
os vec={0,1,2,7,8,9,10,21,22,23,24,25,27,1098,1099,1100,2000};
std::cout<<range_creator(vec);
return 0;
}Solution
You can make good use of
I think my code is still subject to further improvements, but I'm no expert, so I'll leave it to the community.
std::adjacent_find. Like this:std::string range_creator(std::vector & vec)
{
auto first = std::begin(vec), last = std::end(vec);
if(first == last)
return "";
std::sort(first, last);
std::stringbuf buffer;
std::ostream os (&buffer);
while(true)
{
auto mid = std::adjacent_find(first, last,
[](int x, int y){ return x + 1 != y; });
if(mid == last)
break;
if(first == mid)
os << *first << ",";
else
os << *first << "-" << *mid << ",";
first = ++mid;
}
if(first == --last)
os << *first;
else
os << *first << "-" << *last;
return buffer.str();
}I think my code is still subject to further improvements, but I'm no expert, so I'll leave it to the community.
Code Snippets
std::string range_creator(std::vector<int> & vec)
{
auto first = std::begin(vec), last = std::end(vec);
if(first == last)
return "";
std::sort(first, last);
std::stringbuf buffer;
std::ostream os (&buffer);
while(true)
{
auto mid = std::adjacent_find(first, last,
[](int x, int y){ return x + 1 != y; });
if(mid == last)
break;
if(first == mid)
os << *first << ",";
else
os << *first << "-" << *mid << ",";
first = ++mid;
}
if(first == --last)
os << *first;
else
os << *first << "-" << *last;
return buffer.str();
}Context
StackExchange Code Review Q#85552, answer score: 4
Revisions (0)
No revisions yet.