Look and say sequence (C Plus Plus)

From LiteratePrograms
Jump to: navigation, search
Other implementations: C++ | dc | Eiffel | Haskell | J | Java | Lua | OCaml | Perl | PHP | Python | Ruby | Scala | sed | sh

This program is a code dump.
Code dumps are articles with little or no documentation or rearrangement of code. Please help to turn it into a literate program. Also make sure that the source of this code does consent to release it under the CC0 license.

This is a simple C++ program to generate look-and-say sequences such as the Conway sequence.

<<look_and_say_sequence.cpp>>=
#include<string>
#include<vector>
#include<iostream>
#include<sstream>

std::vector<std::string> look_and_say(const std::string &seed, size_t len)
{
	std::vector<std::string> seq;
	seq.push_back(seed);

	for(size_t i=1; i<len; ++i) {
		const std::string &val(seq.back());

		std::ostringstream nextval;
		for(size_t ix=0; ix<val.size(); ) {
			char ch(val[ix]);
			size_t n(1);
			while(++ix<val.size() && val[ix]==ch) ++n;
			nextval<<n<<ch;
		}
		seq.push_back(nextval.str());
	}

	return seq;
}

int main()
{
	std::vector<std::string> seq(look_and_say("3", 10));

	for(size_t i=0; i<seq.size(); ++i) {
		if(i) std::cout<<", ";
		std::cout<<seq[i];
	}
	std::cout<<'\n';

	return 0;
}
Download code
hijacker
hijacker
hijacker
hijacker