Saturday, December 15, 2012

Tic Tac Toe - Unbeatable Algorithm

This post is part of the "First Few Old Blog Posts" archive.
You could expect a certain lack of coherency/maturity from these posts.

For my Computer Project at school , I had to make a simple Java Program. The rules although simple, were very restricting since my class hadn't learnt as much in programming, The program had to be console based (i.e. no Graphics), I could not use any Library Classes apart from the ones that came along with java.lang and Console Input classes. Also, my class hadn't learnt about inheritance and other OOP stuff so I had to stay clear from those too.

The trouble now was to make a good enough project that fit the criteria.
My classmates had settled on making games such as hangman, crossword, calculators etc, but I had already made most of them before while I was getting into programming, and they didn't have much appeal to me.

In the end , I concluded that the project would have to be small anyway, so I decided to make Tic Tac Toe Singleplayer. I'd already made Tic Tac Toe mutliplayer last year as part of a larger package , so I thought that it would be a nice addition to have this as well.

The 3x3 grid was constructed using a 2 dimensional array.
You had to play against the computer in 3 modes - Easy , Medium and Hard respectively.

Easy mode was simple. I used Math.random() to decide the X and Y co-ordinates of the resulting move.

Medium randomly chose between playing easy or hard for that move.

And hard used an algorithm that was impossible to beat. Of course , tic tac toe isn't such a full blown game , and any person smart enough could play any number of matches and always make a tie. But anyway, here is the code for all 3 modes.

Note: This is a function that simply calculates the position that the computer plays in, in a given circumstance. It takes an integer value (int c) that contains the difficulty value (1,2 or 3 for easy,medium or hard). It also takes a 2 dimensional character array of length 3 and 3 (char[][] u) which contains 'X' (player value) , 'O' (computer value) or '-' (empty value). The function returns an integer array of size 2 which contains the x and y co-ordinates of the computed value.

To see the whole program , click here.

     
    public static int[] compute(int c,char[][] u){
        int ar[]=new int[2];
        if (c==1){
            int x=(int)(Math.random()*3);
            int y=(int)(Math.random()*3);
            if (u[x][y]=='-'){
                ar[0]=x;
                ar[1]=y;
                return ar;
            }
            else{
                return compute(1,u);
            }
        }
        if (c==2){
            return compute(((int)(Math.random()*3)+1),u);
        }
        if (c==3){
            boolean mark=false;
            int x=0,y=0;
            int count=0;
            for (int i=0;i<3;i++){
                for (int j=0;j<3;j++){
                    if (u[i][j]=='-'){
                        count++;
                        u[i][j]='X';
                        if (check(u)==2){
                            mark=true;
                            x=i;
                            y=j;
                        }
                        u[i][j]='-';
                    }
                }
            }
            for (int i=0;i<3;i++){
                for (int j=0;j<3;j++){
                    if (u[i][j]=='-'){
                        u[i][j]='O';
                        if (check(u)==1){
                            mark=true;
                            x=i;
                            y=j;
                        }
                        u[i][j]='-';
                    }
                }
            }
            if ((!mark)&&(predict(u,0,0)>1||predict(u,0,2)>1||predict(u,1,1)>1||predict(u,2,0)>1||predict(u,2,2)>1)){
                for (int i=0;i<3;i++){
                    for (int j=0;j<3;j++){
                        if (u[i][j]=='-'&&((i==0&&j==1)||(i==1&&j==0)||(i==1&&j==2)||(i==2&&j==1))){
                            u[i][j]='O';
                            for (int k=0;k<3;k++){
                                for (int l=0;l<3;l++){
                                    if (u[k][l]=='-'){
                                        u[k][l]='O';
                                        if (check(u)==1){
                                            mark=true;
                                            x=k;
                                            y=l;
                                        }
                                        u[k][l]='-';
                                    }
                                }
                            }
                            u[i][j]='-';
                        }
                    }
                }
            }
            if (!mark){
                if (count==9){
                    int ran=(int)(Math.random()*5);
                    switch(ran){
                        case 0 : x=0;
                                 y=0;
                                 break;
                        case 1 : x=1;
                                 y=1;
                                 break;
                        case 2 : x=2;
                                 y=2;
                                 break;
                        case 3 : x=0;
                                 y=2;
                                 break;
                        case 4 : x=2;
                                 y=0;
                                 break;
                    }
                }
                else if (count==8){
                    if (u[1][1]=='-'){
                        x=1;
                        y=1;
                    }
                    else{
                        int ran=(int)(Math.random()*4);
                        switch(ran){
                            case 0 : x=0;
                                     y=0;
                                     break;
                            case 1 : x=2;
                                     y=0;
                                     break;
                            case 2 : x=2;
                                     y=2;
                                     break;
                            case 3 : x=0;
                                     y=2;
                                     break;
                        }
                    }
                }
                else{
                    if (u[0][0]=='-'&&u[2][2]=='O'){
                        x=0;
                        y=0;
                    }
                    else if (u[2][2]=='-'&&u[0][0]=='O'){
                        x=2;
                        y=2;
                    }
                    else if (u[0][2]=='-'&&u[2][0]=='O'){
                        x=0;
                        y=2;
                    }
                    else if (u[2][0]=='-'&&u[0][2]=='O'){
                        x=2;
                        y=0;
                    }
                    else{
                        if (u[0][0]=='-'){
                            x=0;
                            y=0;
                        }
                        else if (u[2][2]=='-'){
                            x=2;
                            y=2;
                        }
                        else if (u[0][2]=='-'){
                            x=0;
                            y=2;
                        }
                        else if (u[2][0]=='-'){
                            x=2;
                            y=0;
                        }
                        else{
                            for (int i=0;i<3;i++){
                                for (int j=0;j<3;j++){
                                    if (u[i][j]=='-'){
                                        x=i;
                                        y=j;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (u[x][y]=='-'){
                ar[0]=x;
                ar[1]=y;
                return ar;
            }
            else{
                return compute(3,u);
            }
        }
        return ar;
    }


Well, I admit that this algorithm isn't the most efficient one out there, but I had functionality in mind, instead of efficiency, so I rolled with a makeshift solution.
But what's more fun is to tell everyone that you couldn't beat my program the next day at the computer lab. They enthusiastically take up the challenge at once, and their faces were worth being looked at when most of them lost to the computer at the second game.

It was great fun.

Thursday, December 13, 2012

My website is back with a bang

This post is part of the "First Few Old Blog Posts" archive.
You could expect a certain lack of coherency/maturity from these posts.

Alright , let's narrate the whole event from my point of view.

Last week , during the evening , I desired to check on the Abstergo Project hosted on my website. To my surprise , I was redirected instead to some other advertisement page. Confused , I then tried the direct URL for my website. The same thing happened again. Furious , I logged in to my host's CPanel , and found out that my account was suspended.

I rewarded myself with a big giant Facepalm. I realized what an utter idiot I had been.
My host was called 0fees. It was a free host and one of the best in it's business out there. I had previously hosted several websites on it's services and I had no problem trusting it to be reliable with my website too. I trusted it so much to the point that I had kept no backups at all of my site. In fact , anything that was to be backed up , was put up on my website. And now , I realized how stupid I had acted. That day , I remembered a big lesson I had learnt in my childhood.

Never trust anything that's free. (Except Google)

So now I was stuck without a website. All my files were lost. All my database entries were gone. Why was my account suspended? Well it's obviously a marketing gimmick to get me to upgrade to paid hosting. I actually considered paying for the hosting just to recover my files back. But then I realized that the paid hosting would be on a different server , thus removing all hopes for a recovery.

The worse part is that my website meant a lot to me. Every line that I code , every line that I write on the internet , every account that I make somewhere , can be traced from my website. I use my website to organize myself. So that I can keep track of every contribution I make to the internet. This is especially required due to the fact that I have OCD. I have to sort every of my actions else I feel that all my work is useless. I have to remind myself that I have a blog , I have a twitter , I've made my own quotes etc to realize that I have done something atleast. The worse problem an organized person can face is losing his organizer. And I had lost my website.

At once , I began to rewrite my website. It was of course , a hard job. I was aided by Google's webcache and I could recover the text content in my website. But all the resources were lost and I had to make them from scratch. Luckily , I had a backup of a few of my bigger projects thus they could also be restored. Once I was done , came the question of where I would host the website now. I first considered turning my home desktop into a server since it was switched on for 20 hours a day anyway. Then I remembered of my good friend , JamezQ. He owned a server with above 99% uptime. I had hosted small Java projects on it many times and it worked great. But I was hesitant in asking to host my entire website on it. As it turned out , he was glad to have my website on his server. And so , I uploaded all my files , configured the MySQL databases , and restored the subdomains. But even then , a few projects could not be restored as I had kept the backups on my laptop which I do not have right now.

So , yeah. There you go , my website is back with a new look. There's new content and a better interface.
Check it out at http://enkrypt.in

Also , while making the website , I took to myself for making some entertaining error pages.
400 - Bad Request http://enkrypt.in/400.htm
401 - Authorization Required http://enkrypt.in/401.htm
403 - Forbidden http://enkrypt.in/403.htm
404 - Not found http://enkrypt.in/404.htm
500 - Internal Server Error http://enkrypt.in/500.htm

Thursday, December 6, 2012

A record every day

This post is part of the "First Few Old Blog Posts" archive.
You could expect a certain lack of coherency/maturity from these posts.

One particularly interesting fact about my weird life is that I have an obsession with getting stuff done. Even if any work at that point happens to be non existent.
If any day passes by without any significant reduction from my workload/to-do list or any addition to my personal records , then that day is to be considered as a complete waste of time and energy.

Now , if you've read my older blogs , then you'll know that I am an OCD patient. What that means is that I need to consistently keep a track of any work done , any work that shouldn't be done , any work that should be done in the future , and so on.
Out of all these , obviously the most important is to keep track of any work that needs to be done in the future. This is why last year , I furnished a complete To-Do list of every work that needs to be done by me at some point later. As of now , the list stands in 57 points of work that needs finishing. All the points mentioned on the list do not consist of everyday work such as shopping or cleaning the lawn as some might expect , but it is rather a collection of long term projects such as learning Android Development or writing a previously thought out novel.

I hold this list to high regard. Every point noted within demands a lot of time , patience and energy which would in some way or the other benefit me later either by self gratification . or by any other method.
When I look back to my past , I see the transition or marking progress. When I was 10 , I used to see how much I had progressed every year. By the time I was 13 , I measured progress monthly. And now at 15 , I do so in a more or so , daily/weekly manner.

The next point and the most important point is the one presented by the title of this blog.
And that is my commitment to setting records.
You see , every now and then , I attempt activities that are not listed in my to-do list either because they are not important enough or they produce inconsiderable results. Among these , I put forward great emphasis on personal achievements.

What sort of personal achievements you ask?
Well let's say that just today , I got chased by a beggar for the first time , I walked over a sewer bridge for the first time , I tripped over a road divider for the first time and I was ambushed by a group of crows for the first time.

It's just that the possibility of doing "firsts" fascinates me. The fact that I'm doing (or being done) something for the first time in my life gives me a great deal of satisfaction and that is why I deliberately put myself in such situations where such "firsts" are possible.
Like for example , all those "firsts" that I accomplished today , they were the result of deliberately choosing to walk all the way to my friend's house , rather than taking a cab (or an auto in linguistic precision).

This is why sometimes , instead of sitting at home and trying to contemplate on sad and stupid stuff , I sometimes set foot outside my house to get some achievement accomplished.
Just this month , during the Diwali dinner held at school , I accomplished a lot of "firsts".
I took pictures with every girl in my class (except 2 because they did not turn up to the party)
I wore a suit for a good whole of an hour
I confessed to a watchman how hideous his uniform was
I walked 10 meters on my toes and most importantly ,
I ran through every corridor that the school had (a pretty great task considering that the party was held at the grounds implying that every corridor was fucking dark and deserted)

And the most daring firsts were also recorded this very month
I stayed 24 hours without food
I stayed 24 hours without water (on separate days) (dehydration is worse than hunger. I had to sleep more than half of the day to keep myself distracted)
I slept for 20 hours straight
I ate a burger for every hour in a day
And most importantly - I got drunk for the first time (this was just last week and it was just a few simple glasses of beer , nothing to worry about)

So , yup. With all these stuff to do , I take pride in saying that almost every day , I am setting and breaking records. It seems eminent that with so much , soon I will be needing a list to maintain all these achievements , and every achievement that was close to completion and every achievement that should be avoided  , and so on.

So , yup. That is it. In summary , I give high regard to working and achieving. Something that I take pride in.
I know that many of the records as such do not present much moral value and you will dissent in opinion about the necessity of performing such acts , but I assure you that they were all executed in safe environments. The last think I want you to assume is me being a reckless teen. Pssh , me? I barely even get out of my house.

I just think that this is my blog , and it needs to contain any personal habit that needs to be mentioned. Also , I haven't posted a self centered blog in a very long time.