View Single Post
  #6 (permalink)  
Old 05-25-2008, 05:30 AM
gofer gofer is offline
Newbie
 
Join Date: May 2008
Posts: 3
Rep Power: 0
gofer is on a distinguished road
Default Re: Generating all sequences of 1s and 0s of length 30

Thanks for the help This is what I came up with:
Code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <fstream>

using namespace std;

struct SortStrings
{
	bool operator()( const string& lhs, const string& rhs ) const
	{
		return lhs.length() < rhs.length();
	}
};

std::string StringFromInt( int n )
{
	if( n == 0 )
		return "0";

	int i = 31;
	while( !( (1 << i) & n ) ) // Finds the most significant bit equal to 1
		--i;

	std::string result;

	for( int j = i; j>=0; --j )
	{
		std::string res = (1<<j) & n ? "1" : "0";
		result.append( res );
	}

	return result;
}

void GenereateInvalidDict( std::vector<std::string>& out )
{
	std::vector<std::string> temp;
	for(int i = 0; i < 1024; ++i)
	{
		std::string s = StringFromInt(i);
		temp.push_back( s );

		if( s.length() < 10 )
			temp.push_back( std::string("0") += s );
		if( s.length() < 9 )
			temp.push_back( std::string("00") += s );
	}

	std::sort( temp.begin(), temp.end(), SortStrings() );

	std::vector<std::string> temp2;
	for( size_t i = 0; i<temp.size(); ++i )
	{
		bool bNeeded = true;

		for( size_t j = 0; j<i; ++j )
		{
			std::string toSearch = temp[j];
			toSearch += temp[j];
			toSearch += temp[j];
			if( temp[i].find( toSearch ) != temp[i].npos )
			{
				bNeeded = false;
				//break;
			}
		}
		if( bNeeded )
			temp2.push_back( temp[i] );
	}

	for( size_t i = 0; i<temp2.size(); ++i )
	{
		std::string s = temp2[i];
		s.append( temp2[i] );
		s.append( temp2[i] );

		out.push_back( s );
	}
}

bool IsValid( const std::vector<std::string>& invalid, const string& s )
{
	for( size_t i = 0; i<invalid.size(); ++i )
		if( s.find( invalid[i] ) != s.npos )
			return false;
	return true;
}
void Generate1sAnd0s( const std::vector<std::string>& invalid, const std::string& s, ostream& out )
{
	if( s.length() == 30 )
	{
		out << s.c_str() << endl;
		return;
	}

	string s0 = s; s0.append( "0" );
	string s1 = s; s1.append( "1" );
	if( IsValid( invalid, s0 ) )
		Generate1sAnd0s( invalid, s0, out );
	if( IsValid( invalid, s1 ) )
		Generate1sAnd0s( invalid, s1, out );
}

int main()
{
	std::vector<std::string> invalid;
	GenereateInvalidDict( invalid );
	Generate1sAnd0s( invalid, "", cout );
	cout << "Done" << endl;
	return 0;
}
GenereateInvalidDict generates the dictionary of invalid strings and Generate1sAnd0s recursively appends a 1 and/or a 0 to the string if it's a valid one, until it reaches the required length of 30
Reply With Quote