Wednesday, April 9, 2008

Make your code Smaller with Function Pointers and Templates

While programing we find ourselves with things we would need to write over and over again. Even tho copy paste is very friendly to use, it tends to make the code larger, and since we are bound to make bugs every now and then. Its not easy fixing hundreds of times in the same error, so most of us use functions. Functions are an essential part of programing when it comes to extremely complex algorithms, but sometimes functions aren't enough and we still end up writing the same processes over and over again. For example we might have a common process, lets say we have a simple loop (of course a simple loop is simple but for the sake of explaining lets use a loop) so lets say we have something like this
void primary_process(int beginning, int times)
{
int x;
for (x=0;x<times;x++)
cout << beginning + x << " ";
}
yet as we keep on programing we notice that we use that loop a lot of times, the only thing that changes is the formula that we use on the number. So we could write yet another function with the same loop.
void primary_process_multiply(int beginning, int times)
{
int x;
for (x=0;x<times;x++)
cout << beginning * x << " ";
}
But that would be writing the same loop function once again. What we can do is use a function
int sum(int a, int b)
{
return a+b;
}
int multiply(int a, int b)
{
return a*b;
}

once again this functions are extremely simple but in a real programing environment functions could take hundreds of lines. Now that we have this two functions lets use function pointers.
a function pointer can be declared like this
class (*function_name)(classes)
so if we whant to rewrite our loop function but using a function pointer we do this
void primary_process(int beginning, int times,int (*function)(int,int))
{
int x;
for (x=0;x<times;x++)
cout << function(beginning,x) << " ";
}
Now you must notice how I added a function pointer in the parameters the function will take, and then I used the function pointer like if it were a normal function. How we use this?
well here is an example
primary_process(1,15,sum);
cout << endl;
primary_process(3,14,multiply);
by writing the name of the function in the third parameter, I pass the function I want to use to the primary_process function
now its important to note that the function pointer must contain the same amount of parameters as the function it will point at otherwise it will fail to work.
Now we have made our code smaller and without duplicates. But what if another problem arises. Lets say we want to play those same processes but to other types, in our example we want to use characters too and also output characters. Well we could copy all 3 functions and make functions that get characters in them OR. Use templates.
look at this code.

template <class T>
T sum(T a, T b)
{
return a+b;
}
template <class T>
T multiply(T a, T b)
{
return a*b;
}
template <class T>
void primary_process(T beginning, int times, T (*process)(T,T))
{
int x;
for (x=0;x<times;x++)
cout << process(begining,(T)x) << " ";
}
by using templates in functions we allow it to take any type of class, it could be an integer, a character, even a custom class. of course there could be exceptions but I won't discuss them today. Yet this way allows us to use different types in similar processes now for using this functions I ran this example code.
primary_process('a',5,sum);
cout << endl;
primary_process('b',10,multiply);
cout << endl;
primary_process(1,15,sum);
cout << endl;
primary_process(3,14,multiply);
this returned.
a b c d e
b ─ & ê Ω L « ► r
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
0 3 6 9 12 15 18 21 24 27 30 33 36 39

In a larger programing environment we might use classes that need to go trough the same processes, and this processes might take hundreds even thousands of lines, and sometimes having duplicates of those processes will cause enormous headaches when debugging.
By using this methods we can have cleaner codes, and be able to change them fast in the future instead of going trough a all the copies of itself.

back to the code.

A step further in encryption

In an early post, Simple Encryption Methods, I mentioned 4 kinds of bitwise level operations that could be used to encrypt data. Between them was, mask, inverse, reverse and rotate. If you want speed its good to remember that the more complex the more processing time it has to be done yet it normally also means that it is more secure. Mixing several kinds of operations can be a good idea. if only you know the order it would be like the formula itself is a giant password. But also, if you want security its a good thing not to use the same process with each word, that would just generate an alternate alphabet that can be easily decrypted by using word associations. So you need to vary your methods in a way a pattern its difficult to recognize. So we start by mixing the methods. We need a formula that tells what methods to use, so the lowest form would be, if the method will be used or not used. Also we can alter the order of the methods this can create a large amount of possibilities. But first we have to know, that when using this 4 kinds of methods the inverse one can be anywhere. And therefore should be used once.
Its easy to identify why rotate and reverse don't matter when you did the inverse (if before or after.
1100 rotated once 1001 and then inversed 0110
1100 inversed 0011 rotated once 0110
1100 reversed 0011 inversed 1100
1100 inversed 0011 reversed 1100

note that in combinations inverse and reverse will return the same, but this is not true for all values.
mask also have this property lets see at a simple test
1100 masked with 1010 is 0110 inversed is 1001
1100 inversed is 0011 masked with 1010 is 1001

this has been tested with all possible combinations and is true for all.
therefore we don't need to care about the position of the inverse only if it exist or not
inverse rotate reverse masked is the same as rotate inverse reverse masked and therefore is the same as rotate reverse inverse masked and therefore is the same as rotate reverse masked inverse.

Yet on further testing the position between rotate reverse and masked, does matter, So its a good thing to play with their order when building an encryption method. Also since the position of inverse doesn't mater don't go around making more than one inverse because two inverse is the same as no inverse.

Remember you can get creative with the formula of encryption a nice idea is to force an order of encryption, by using a formula that generates values for each letter that affect the way they are encrypted and by using the letter before as a value to alter the encryption. This way ensures that not only you need to know the method and the formula, but you need to encrypt in an order, and the encryption depends on the message itself making it hard to identify a pattern between two messages.

Tuesday, April 8, 2008

Lunatic Night Walk. The sea of darkness

So two weeks or so have passed since my last long walk, to keep my sanity I decided to take this next trip, this time, I knew where I was going. To my surprise things might be a bit misleading in the night, specially when you can't hear your destination or see it in the night. Once again I was talking in the cellphone with my good friend Gerson, who once again asked me to please don't go walking in the night. But since I don't want to reach the old age I didn't listen and went out of my house at 12:00 am

To my happiness the bar "El Colegial" was open at that hour so I used the only two dollars and 25 cents I had in my pocket to buy myself a nice Smirnof Green apple, before the long journey I was about to go. Not knowing how lost I was gonna get.

Because I am shush a good person and like to keep my island clean I decided to turn back and walk around the houses for a while so once I finished the drink I had a trashcan nearby to dispose it.

That done I decided to go out of the known area and take the unknown path. Near the end was when I began getting confused, what in Google map appeared as a street was actually a large metal bridge for people only. The metal planks made loud noises and bent down as I walked in them. But the river under it looked nice and calm. After that I made my first mistake, I tough I had to keep walking forward but I saw a guy standing in the middle of the empty street so I took a turn. In the way near the funerary I saw a strange light orb come out and hover into some bushes. Also found another strange guy standing in the middle of a street who I think asked me for money but I had none.

I found myself in the viaduct what just told me, I have made a huge mistake and I was walking away from my destination. So I took a turn and went into the next street. As I walked I notice a place full of people so I took a turn to a more solitary street were I saw a rather peculiar building that had the name Stealth in it and the drawing of a black angel in one side. finally I found a dead end and no sign of the sea. Even tho in the map it looks like I was so close to the sea I took a turn passed behind the bat and kept on walking some rather unused streets that belonged to some factories. later I found a bridge that was only for cars so I decided to walk back away from what I tougth was the good way. ending up in a rather strange neighborhood with old houses.

Creepy enough I got in the heart of those old and small looking houses where I saw a guy entering a house with a bicycle and his face was masked. Y took a turn away from him and ended up in a dead end, so I walked back and took another dead end so I just traced my steps back and went walking in front of another bar. back to were I came from but trough another street.

and when I finished walking I found myself in the street were I saw the first guy standing. So I began rethinking where I was and decided to take a turn toward the correct path. I ended up in a large bridge and I tough I was in the bridge I wanted to take in the first place so I walked back and ended back in the street with the black angel so trying to walk other streets just in case someone saw me didn't noticed I was lost I took a few unnecessary turns back to the bridge. The buildings there looked extremely old and the gates looked almost castle like. but I kept on walking.

Then I started looking in the direction the river went and I noticed that all that was over there was some rather heavy dark looking wilderness and the most nearer streets that went in the direction I tough was the sea was in another side of a highway, and there was no sidewalk there. But considering it was already 1 am in the morning in a rather solitary place I ran in the middle of the highway and not even one car passed. I was getting scared, I was passing near construction sights and no sign of the sea. No sound no wind just the distant bark of dogs. I was about to call Gerson who I told I was gonna call him so he could hear the sea, and tell him I had failed miserably and was now lost. But then I heard it, the sound of the sea, the beautiful sound of crashing of waves. I followed the street and saw some dogs barking at me, yet no sign of path to go there, I was thinking again to turn back. but then I notice an open green area that wasn't full of tall grass, and immediately called my friend. Happy with joy I finally saw the waves, the almost infinite plain of darkness, I was so overjoyed.

Under a nice tree I found a fallen tree that served perfectly as a seat and there I sat, for about an hour. Looking at the sea and meditating. While in there I saw some nocturnal birds running in the shoreline. Probably eating. Until I decided to leave.

I took the same path back, now looking at the map I notice I took a rather long path when I could have took a short cut, but the reason of this walks is not to get to places fast, is just to enjoy the beauty of the night. To go to places at hours no one goes, and experience the world without the pain of the sun. In the way I saw this guy coming from the University, for a reason I found him familiar, he looked almost like my friend, so after we passed each other I decided to look back, just to find out he was also looking back. But I kept on walking.

Passed in front of "El Colegial" wish was already closed, only the bartender was cleaning around.

and I got back home with a smile in my face and a large feeling of accomplishment, the waves still fresh in my mind, the beautiful sight of the moonless night, the blurry of the horizon like a lived dream.

4 sleeping pills
2 pain relievers
no casualties.

Sunday, April 6, 2008

Drawing with Light

SO yeah it has been a weekend or so I haven't written stuff. I feel I have failed you people. But no fear I come with lunacy. Not programing because I am a bit null after the exams. So a few days ago I was talking to my good friend Gerson over the internet and he asked a bunch of things about my digital camera, and I, sounding like a total newbie didn't knew anything about my camera, so I decided to look at the manual. After noticing I could change the time the shutter is open and the wideness of the shutter and the amount of sensors, I said. HEY I know how to test this, lets draw with light. And here is the result.
side note: its just a star get over it.

who can resist not making a star with this new power.

after a star who can resist not making an inverted one.

my symbol or an attempt to do my symbol

Fire chaos weee. Because a flash ligth is not the only source of light.

Look at the pretty fire spirits... and hands?

I'm not human....

basically by letting the shutter be open for a long time it detects a lot of what happens and swallows a lot of light. so by letting it be on for 8 seconds I can draw with light. The hard part is to stay still so you don't look so blurry.

Thursday, April 3, 2008

Simple Encryption methods

We all like to be sneaky every now and then, there is information we don't want anyone to read, or just someone who we trust. But as we all know, just talking around is insecure, using a public medium to transfer information will be viewable to anyone that has the knowledge to get it. So we employ encryption. For encryption we need to have something in mind all the time. The data we encrypt we need to decrypt later, so we need to use methods that won't end up in data being lost and we need to use methods we can remember later. Thanks to computers we can use more complex methods to encrypt our data, and let them remember how to decrypt it.
Most of the time all we have to do is reverse the process, so let me explain some computer level encryptions. And since everything is binary in computers most encryption can be done in the bitwise level.
I believe one of the most common processes used on basic encryptions is masking. Masking consists of using the bitwise operator XOR or ^ in order to "mask" a sequence of bits. XOR is the same as the logic exclusive or in logic, its truth table is
A|B|A^B
1|1|0
1|0|1
0|1|1
0|0|0
this sounds weird to be used as encryption but lets see what happens with larger numbers. Lets say we have this 10110101 and we want to encrypt it with the "mask" 10101010 (notice that both the code and the mask have the same amount of bits"
10110101
10101010 ^
00011111
the result is 00011111 now thats nothing like the mask or the original thing. The good thing about masking is that if we take the new object and mask it with the same mask...
00011111
10101010^
10110101 we get the original number. This way you can mask with different numbers each letters and only if someone knows the mask then they can decrypt it.
Another good operation is inverse, its not a very strong encryption since it only does one thing, but in combination with other encryptions it can become slightly powerful. Lets say we use what we got in the last encryption 00011111 and we decide to inverse it
~00011111 = 11100000
now if someone whanted to decrypt it, they had to inverse it first and mask it later.
since when you ~11100000 you get 11100000.

now getting deeper in the code lets use another kind of encryption. Rotation.

#define ROR(x, n) ((x>>n)|(x<<8*sizeof(x)-n))
#define ROL(x, n) ((x<<n)|(x>>8*sizeof(x)-n))
this two functions might be useful in encryption and are used in several encryptions. they rotate the bits to one side or the other.
lets go in depth with it lets say we have 11100000 and we rotate it twice to the left (the ROL function)
so first er have 11100000 << 2 and we get 10000000 then the other side of the function gets that the sizeof this is 1 byte (8 bits) so
11100000 >> 6 so we get 00000011
then we or this two values and we get 10000011
if we use ROR and rotate it to the right twice we get 11100000

so now we have 10000011 a number very different from 10110101 but if we trace back all our steps we will get that number. only you know what steps you took and what masks you used.

I guess I have time to explain one last function. Reverse. The reverse function is used to reverse the numbers for example 10000011 would turn 11000001 this function isn't very strong since it can only return one value of each letter but just like inverse it can be mixed. A good way to use this is to use a character table for speed.
static char REVtable[256] ={ 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff };
using this table that is written in hex numbers you can quickly return the reverce of any character.

NOW well enough of binary lets look at some code. and mask one letter
unsigned char I = 'A';

printf("Original: %c\n",I);
I = REV(I);
printf("Reversed: %c\n",I);
I = ~I;
printf("Inverted: %c\n",I);
I = I ^ 'B';
printf("Masked: %c\n",I);
I = ROR(I,2);
printf("Rotated: %c\n Start Decoding:\n",I);
I = ROL(I,2);
printf("Rotated back: %c\n",I);
I = I ^ 'B';
printf("Masked: %c\n",I);
I = ~I;
printf("Inversed: %c\n",I);
I = REV(I);
printf("Reversed: %c\n",I);
this returns the following.
Original: A
Reversed: é
Inverted: }
Masked: ?
Rotated: ╧
Start Decoding:
Rotated back: ?
Masked: }
Inversed: é
Reversed: A

you could run this kind of processes in each letter of a sentence, make sure to remember the masks and the amount of rotation used in each letter. With a good ammount of combinations your encryption will be really hard to decode.

Wednesday, April 2, 2008

A quick formula for extracting numbers.

We know how to extract booleans out of larger integers, but what if our base is larger than one. What if we want to store numbers like example a 3. We know that if we whant to store a number of any base we can just go and take for example, if we have 3,2,1 in base 4(numbers from 0 to 3) and we want to store them in a single decimal integer we can do (3)(4^0)+(2)(4^1)+(1)(4^2),(in other place number*(base^position)) but what if after we get a number 27 we want to extract them individually. well the formula is rather easy it is floor(number/pow(base,position))%base so if we take 27 and we want the numper in position 1 (that we know its 2) we do this:
floor(27/pow(4,1)%4
floor(27/4)%4
floor(6.75)%4
6%4
2.
This way we can store things that hold more than just yes or no questions. Using the other formulas to store items we can create highly portable data by compressing all possibilities in numbers, Converting to larger bases for example hexadecimal or one that uses all the letters of the alphabet makes it more portable.

Tuesday, April 1, 2008

Lets Play Rock Paper Scissors

Rock paper scissors one of the most balanced games that exists, every option has equal possibilities to win, loose or draw. The rps system is implemented in many games and hidden with many fancy names like elements, weak points and strong point and others. The good thing about this is that it can be used in strategies once you know your enemies, while giving you the option to grow in one without being the weakest nor the strongest. But now I would like to propose a more complex system. Lets include the rps in a circle, the angle between each point is 120. So lets take any position in a circle and say its stronger point its that position + 120 and its weakest point its that position + 128. Now lets make a bonus system out of that and the closer you are to the stronger point you get a 100% bonus while the closer you are to the weakest point you get -100%. This leave us with two arks. one arc has a length of 120 and goes from 120 to 240 from 100% in 120 to 0 in 180 to -100% in 240. And we also have an arc of 240, this arc goes from -180 in 240, to 0 in 0 as it starts the circle again and finally 100% in 120. Now to put it in code let me explain my float modulus formula.
float fmodulus(float a,int b)
{
return ((a/b)-floor(a/b))*b;
}
this formula behaves like modulus. In other words it returns the residual of a division but with the difference that the first number can be a float and not an integer.
now for the formula to calculate the bonus we have this. It can be made better but lets use this for explanation.
float huebonus(float a,float p)
{
a = fmodulus(a,360); //first we clean the atacking point so its between 0 and 360;
float b = fmodulus(a+120,360); //then we get the strong point and we also put it between 0 and 360
float c = b + 120; // then we need the weak point
float d = fmodulus(c,360); //then we get the weak point and make sure its in the circle
float e = d + 240; //then we get the strong point again this time from the weakpoint
p = fmodulus(p,360); //we put the defending point in the circle
if((b<=p)&&(p<c)) //first we check if its between a+120 and a+240
return (60 - p + b)/60;
else if ((c>360)&&(0<=p)&&(p<d)) then if a+240 is larger than 0 then we check from 0 to the correct point
return (b - p - 300)/60;
else if((d<=p)&&(p<e))//then we check from a+240 and from that point +240 (the weak point)
return (p - 120 - d)/120;
else //once again if its larger than 360 we check from 0 to that point
return (240 + p - d)/120;
}

great now how can we make this pretty. just use color hues!.
thats for today back to the code.