Re: string letter distribution algorithm
"Ulterior" <leonardas.survila@gmail.com> wrote in message
news:1182345021.663722.300630@w5g2000hsg.googlegroups.com...
Hi, everyone,
I have a simple problem, which bothers me for some while. I will try
to explain it -
There is some string, whith different letters in it. Is it possible to
analyse this string and the
reffer to it knowing that it has some certain letters in it using only
some integer value?
I.e if a string is 'catpow', there is 5 unique letters 'c', 'a', 't',
'p', 'o' and 'w'. word evaluates to some integer value, lets say
1234.
I would like to filter out all words except those having letter 't' in
it using single integer value and simple arithmetical expression.
Thank you in advance.
Here is something I threw together. Not sure if it's what you want, and
it's not optimized and is pretty much just C code.
#include <iostream>
#include <map>
#include <cmath>
int WordLetters( const char* Word )
{
int Result = 0;
for ( int i = 0; Word[i] != 0; ++i )
{
unsigned char LetterValue = static_cast<unsigned char>( toupper(
Word[i] ) );
// Ignore special characters, only treat characters
if ( LetterValue >= 'A' && LetterValue <= 'Z' )
Result |= static_cast<int>( std::pow( 2, LetterValue - 'A' ) );
}
return Result;
}
bool LetterInWord( char Letter, int WordValue )
{
unsigned char LetterValue = static_cast<unsigned char>( toupper(
Letter ) );
// Ignore special characters, only treat characters
if ( LetterValue >= 'A' && LetterValue <= 'Z' )
return (WordValue & static_cast<int>( std::pow(2, LetterValue -
'A' ))) != 0;
else
return false;
}
int main()
{
if ( sizeof(int) < 4 )
{
std::cout << "int is not big enough. try long int or something" <<
"\n";
return 1;
}
int Catpow = WordLetters( "Catpow" );
std::cout << "X in Catpow: " << LetterInWord( 'X', Catpow ) << "\n";
std::cout << "T in Catpow: " << LetterInWord( 'T', Catpow ) << "\n";
std::cout << "C in Catpow: " << LetterInWord( 'C', Catpow ) << "\n";
std::cout << "W in Catpow: " << LetterInWord( 'w', Catpow ) << "\n";
return 0;
}
Basically all I'm doing is converting each letter 'A' through 'Z' to a
number 1 thorugh 26. Then I take it as a binary place. Which means that I
need an ordinal value with at least 26 bits, for my system int fits that
since it has 32 bits. Then I simply set the bit on for that place.