RosettaCodeData/Task/Look-and-say-sequence/C++/look-and-say-sequence.cpp

31 lines
568 B
C++
Raw Permalink Normal View History

2018-06-22 20:57:24 +00:00
#include <iostream>
2013-04-10 21:29:02 -07:00
#include <sstream>
2018-06-22 20:57:24 +00:00
#include <string>
2013-04-10 21:29:02 -07:00
2018-06-22 20:57:24 +00:00
std::string lookandsay(const std::string& s)
2013-04-10 21:29:02 -07:00
{
2018-06-22 20:57:24 +00:00
std::ostringstream r;
2013-04-10 21:29:02 -07:00
2018-06-22 20:57:24 +00:00
for (std::size_t i = 0; i != s.length();) {
auto new_i = s.find_first_not_of(s[i], i + 1);
2013-04-10 21:29:02 -07:00
2018-06-22 20:57:24 +00:00
if (new_i == std::string::npos)
new_i = s.length();
2013-04-10 21:29:02 -07:00
2018-06-22 20:57:24 +00:00
r << new_i - i << s[i];
i = new_i;
}
return r.str();
}
2013-04-10 21:29:02 -07:00
int main()
{
2018-06-22 20:57:24 +00:00
std::string laf = "1";
2013-04-10 21:29:02 -07:00
2018-08-17 15:15:24 +01:00
std::cout << laf << '\n';
2018-06-22 20:57:24 +00:00
for (int i = 0; i < 10; ++i) {
laf = lookandsay(laf);
2018-08-17 15:15:24 +01:00
std::cout << laf << '\n';
2018-06-22 20:57:24 +00:00
}
2013-04-10 21:29:02 -07:00
}