need a simple integer pattern algorithm
Hello all,
In code, I need to transform these values:
256 becomes 0
128 becomes 1
64 becomes 2
32 becomes 3
16 becomes 4
8 becomes 5
4 becomes6
Is there some way to express this mathematically so that I do nto have to use a table lookup? I know this sounds like I am an idiot, but I can not figure out an obvious algorithm.
Regards,
Ellay K.
Re: need a simple integer pattern algorithm
Well, clearly the numbers on the left are powers of 2. Specifically, they are the powers
8
7
6
5
4
3
2
These can then be converted easily as 8-z.
This suggests a complete expression of y = 8 - log2(x). You will need to account for conversions between double and int in this case. Alternatively, powers of 2 can be handled purely with integers but that gets you into bit operations. Not always worth it.
Re: need a simple integer pattern algorithm
Re: need a simple integer pattern algorithm
Quote:
Originally Posted by
ekhule
Is there some way to express this mathematically so that I do nto have to use a table lookup?
What if you could use a very small lookup table with just eleven entries? Check this out,
Code:
int N = 11; // table size
std::cout << (512 % N) << std::endl;
std::cout << (256 % N) << std::endl;
std::cout << (128 % N) << std::endl;
std::cout << (64 % N) << std::endl;
std::cout << (32 % N) << std::endl;
std::cout << (16 % N) << std::endl;
std::cout << (8 % N) << std::endl;
std::cout << (4 % N) << std::endl;
std::cout << (2 % N) << std::endl;
std::cout << (1 % N) << std::endl;
std::cout << (0 % N) << std::endl;
Amazingly all first ten powers of 2 and 0 taken modulo 11 give a unique number between 0 and 10 (which can be used as entries in the lookup table).
Re: need a simple integer pattern algorithm
Quote:
Originally Posted by
ekhule
In code, I need to transform these values:
256 becomes 0
128 becomes 1
64 becomes 2
32 becomes 3
16 becomes 4
8 becomes 5
4 becomes6
Is there some way to express this mathematically so that I do nto have to use a table lookup? I know this sounds like I am an idiot, but I can not figure out an obvious algorithm.
Nobody asked the obvious question: WHY???
What’s wrong with table lookup? And how mathematical expression is better?
Also, is your input limited to these few values? Or could you get, for example, 42? Then what?
Did you consider a set of if() statements? Or a switch?
Are you after performance? Or compactness?
In other words: WHY???
Re: need a simple integer pattern algorithm
Quote:
Originally Posted by
VladimirF
Nobody asked the obvious question: WHY???
Probably because this is how the instructor told him/her to do it.