Showing posts with label funny. Show all posts
Showing posts with label funny. Show all posts

Friday, September 20, 2013

Java: Get Instance of Inner Class


Today my good unpredictable friend Mishuk gave me a piece of Java code which is full of nested classes. I was not surprised at all as I already know his love for inner classes. Then he asked me whether it is possible to call a method from the innermost class, i.e. is it possible to get an instance of the nested classes. At first I thought how hard could it be, but it eventually turned out to be thought provoking. It was not as straight forward for me as I thought (I won't deny, I know a very little Java, which is why this little bit of trick had surprised me). So I just wanted to put it up here for future references.

The class he gave me follows:

class A {
    String name="A";
   
    public class B {
        String name="B";
       
        public class C {
            String name= "C";
           
            public void print(String name){
                System.out.println(name);
                System.out.println(C.this.name);
                System.out.println(B.this.name);
                System.out.println(A.this.name);                               
            }
        }
    }
}

As there was a restriction that the above code can't be modified, the only way to do this is to somehow get instances in a hierarchical manner. Because you cannot get instances of B without creating an instance of A and so on. But Java has a cool thing called reflection, and using reflection, it is possible to get instances from the inner class as well. So here is how the print() method from class C can be called. The idea is to create instances following the hierarchical order and then use the last one. Now it seems easy!

import java.lang.reflect.*;

class Main {
    public static void main(String[] args) throws Exception {
        Class classAB = A.B.class;
        Class classABC = A.B.C.class;
        Constructor constructorAB = classAB.getConstructor(A.class);
        Constructor constructorABC = classABC.getConstructor(A.B.class);
        A instanceA = new A();
        A.B instanceAB = constructorAB.newInstance(instanceA);
        A.B.C instanceABC = constructorABC.newInstance(instanceAB);
        instanceABC.print("JAVA SUCKS WITHOUT REFLECTION");
    }
}

Oh, one more thing, for those who don't know this yet and too lazy to run some Java codes, here is the output:

JAVA SUCKS WITHOUT REFLECTION
C
B
A

Yah I know this may be done in hundreds of different ways and exceptions should be handled and and and and .... who cares?


Sunday, January 23, 2011

A C++ Mistake


Consider this piece of code:
int f = 10;

int ff() {
    return f = 5;
}

int main() {
    printf("%d %d\n", ff(), f);
    return 0;
}
As I have expected it to print "5 5" (I was using Dev C++) so did I get, but I didn't know it was wrong until the judge showed me the famous and fabulous "WA". The correct output is "5 10", because, function parameters are though of to be similar as assignment operation and should be performed from right to left. Now it makes sense. But got some penalty for stupid yet adorable Dev C++. However, I've learnt this... that's the good side of it! So, you too be careful if you don't know that already.

Monday, January 3, 2011

Story of Centipede



The centipede was very good at walking with its hundred legs. It never spent a thought on just how it could walk. Until one day, when a big black bug asked the centipede “How can you manage to walk with all those feet? Don’t you find it hard to coordinate their rhythm?” The black bug already left, when the centipede was still sitting down, pondering how it could walk, wondering, and (for the first time in his life) even worrying a little bit. From that day on, the centipede couldn’t walk anymore.

So you better not think too much if you want to achieve something.


Wednesday, August 4, 2010

Simple Take Away Game


Combinatorial games are two-player games with an outcome (i.e. it cannot end in a draw) and the players move alternatively from one position to other position depending on their move and finally reach a terminal position. When a player reaches the terminal position, the winner is decided based on the type of game play.

There are two types of game plays – normal play and the misère play .In a normal play , the one who moves the game to the terminal position is the winner and in a misère play , the one who moves the game to the terminal position is a loser.And if the rules of the game are same for both the players , then its a impartial game and when the rules are different for the two players , then its a partisan game.An common example of partisan game is a game of chess.

Take Away Game :


A take away game is a impartial combinatorial game where there is a single pile with n chips and players remove a certain number of chips from the pile depending on the rules of the game.Let us for the ease of analysis consider a normal play where the one who takes the game to the terminal position wins the game.

Consider a pile of n chips and say the rules of the game are given

  • N={0,1,2,3,..,n} be the positions that the game can be and a 0 signifies a terminal position and a n signifies a starting position

  • S={1,3,4} be the possible set of moves

  • A player can take away ‘x’ chips from the current pile where x € {S}.


Say we need to analyze the game given n and S .By analysis what we mean is given n and S and assuming optimal play, who wins the game.To analyze the game we define two positions namely N position where the Next player to play wins and P position where the Previous player to have played wins.So a game ideally starts with either a P or a N position but always ends in a P position.

So we arrive at the following rules which can be recursively used to define the P and N positions.

  1. All terminal positions are P positions in a normal play.

  2. From an P position, any move takes us to a position.

  3. From a N position, we can reach a P position in at least one possible way so that we emerge the final winner.


If the game starts with P position , the second player to play wins because, from P position the game can move to only to N position and the Second player wins by taking the game again to a P position according to the Rule 3 stated above(this is called playing optimally).
If the game starts with a N position , the current player wins the game by taking the game always to a P position.

So Let S be {1,3,4} for our analysis.
We use the following Algorithm to classify the P and N positions of {0,1,2,… n}.

  • Step 1: Label every terminal position as a P-position.

  • Step 2: Label every position that can reach a labeled P-position in one move as an N-position.

  • Step 3: Find those positions whose only moves are to labeled N-positions; label such positions as P-positions.

  • Step 4: If no new P-positions were found in step 3, stop; otherwise return to step 2


So we begin by adding ‘0′ to P position and let set P={0} denote the currently recognized P positions .By using Step 1, { 1,3,4} are decided to be N positions and analyzing the next number in the close proximity , we take ‘2′.

‘2′ has only one transition and its to a N position so 2 gets added to P and 1,3,4 gets added to N in this iteration. Now moving to the next iteration, 5(2+3) and 6(2+4) are N positions and analyzing for 7, we have the possible transitions as 6,4,3 which are all N positions and hence 7 gets added to P
hence at the end of second iteration, P={0,2,7} and N={1,3,4,5,6} . On continuing further, we get the following

P={0,2,7,9,14,16,21,23….} and N={1,3,4,5,6,8,10,11,12,13,15,17,18,19,20….}

So generalizing all positions which leave a remainder of 0 or 2 on dividing by 7 are P positions and others are N positions.

So say we have 21 chips then we are asked to comment on the winner assuming the optimal game play, we can conclude from the above derivations that 21 is a P position so the second player can win if he plays optimally . Say i start with 21 , the possible moves are 20,18,17 which are all N positions . Say we move to one of these

17 can move to 16,14,13 (14,16 are both P position)
18 can move to 17,15,14 (14 is a P position)
20 can move to 19,17,16 ( 16 is a P position)

For all the above cases , we observe that there is a possible transition that the second player can make such that the game proceeds to a P position and the cycle continues and finally the second player comes to a N position which could be either 1,3,4 so that the second player makes a suitable move and moves to 0 winning the game. If the Second player at any stage makes a non-optimal move , the game goes temporarily out of his control and he may or may-not win the game.

Another Example from SPOJ :


Let us analyze this Problem from SPOJ NGM which can actually be found here.

The problem states that a number n is taken and the player take turns and subtract the number by any one of its non zero digits.And the one who makes this number ‘0′ wins the game .The two players are Nikofir and Trofim. This problem helps us understand the above discussed concepts.

Analysis :


We start by adding 0 to P and 1,2,3,4,5,6,7,8,9 all lead to 0 directly hence are added to N . Now we analyze 10 which goes to 9 alone which is a N position and gets added to P . So at end of one iteration,

P={0,10) N=(1,2,3,4,5,6,7,8,9} .

Next the following numbers {11,12,13,14,15,16,17,18,19 }all have one possible move to {0,10} so they belong to N and the next P number is 20 proceeding we fins tht P is a set of multiples of 10

P={ x| x is a multiple of 10}

N={x | x is not a multiple of 10}

So given number which is not a multiple of 10 it is in N position and the player who plays first always wins i.e. Nikofir wins always .

If the given number is a multiple of 10 , then its in P position and Trofim wins.

Stress on Optimal Play :


Why do we need to analyze an optimal play? The need for all this analysis is to make the computer make the best move at the current position so that it poses a challenge to the player who plays and if the player gets lucky, he can take advantage of these analysis to make a winning move.

Friday, June 11, 2010

BrainF**k & C++


Here is my bf to C translator, so I can write some bf sh*ts and test easily on my VC++08. To run the program with command line, _NO_ARGS must be cleared with 0.

#define _CRT_SECURE_NO_WARNINGS 1
#define _NO_ARGS 0
#include <stdio.h>

FILE *fin, *fout;

void print(char *str, int tab);
int unknown(char ch);

int main(int argc, char **argv) {
char ch, pr, temp[1024];
int tab = 0, cnt, carr;
if(_NO_ARGS) {
scanf("%s", temp);
fin = fopen(temp, "rb");
scanf("%s", temp);
fout = fopen(temp, "wb");
}
else if(argc < 2) {
printf("insufficient arguments...\n");
return 1;
}
else if(argc < 3) {
fin = fopen(argv[1], "rb");
fout = fopen("noname.c", "wb");
}
else {
fin = fopen(argv[1], "rb");
fout = fopen(argv[2], "wb");
}
if(!fin || !fout) {
printf("file error...\n");
return 2;
}
print("#include <stdio.h>", tab);
print("", tab);
print("char buff[1024];", tab);
print("", tab);
print("int main() {", tab++);
print("char *p = buff;", tab);
pr = 0;
cnt = 0;
carr = 0;
while((ch=fgetc(fin))!=EOF) {
if(unknown(ch)) continue;
if(ch=='.' || ch==',' || ch=='[' || ch==']') {
if(carr) {
if(pr=='+') sprintf(temp, "(*p) += %d;", cnt);
else if(pr=='-') sprintf(temp, "(*p) -= %d;", cnt);
else if(pr=='>') sprintf(temp, "p += %d;", cnt);
else if(pr=='<') sprintf(temp, "p -= %d;", cnt);
carr = cnt = 0;
print(temp, tab);
}
if(ch=='.') print("putchar(*p);", tab);
else if(ch==',') print("*p = getchar();", tab);
else if(ch=='[') print("while(*p) {", tab++);
else if(ch==']') print("}", --tab);
}
else if(ch==pr || !carr) {
carr = 1;
cnt++;
}
else {
if(pr=='+') sprintf(temp, "(*p) += %d;", cnt);
else if(pr=='-') sprintf(temp, "(*p) -= %d;", cnt);
else if(pr=='>') sprintf(temp, "p += %d;", cnt);
else if(pr=='<') sprintf(temp, "p -= %d;", cnt);
carr = cnt = 1;
print(temp, tab);
}
pr = ch;
}
if(carr) {
if(pr=='+') sprintf(temp, "(*p) += %d;", cnt);
else if(pr=='-') sprintf(temp, "(*p) -= %d;", cnt);
else if(pr=='>') sprintf(temp, "p += %d;", cnt);
else if(pr=='<') sprintf(temp, "p -= %d;", cnt);
print(temp, tab);
}
print("return 0;", tab);
print("}", --tab);
fclose(fin);
fclose(fout);
return 0;
}

void print(char *str, int tab) {
int i;
if(str[0]) {
for(i=0; i<tab; i++) fputc('\t', fout);
for(i=0; str[i]; i++) fputc(str[i], fout);
}
fputc('\n', fout);
}

int unknown(char ch) {
switch(ch) {
case '+':
case '-':
case '<':
case '>':
case '.':
case ',':
case '[':
case ']': return 0;
default : return 1;
}
return 1;
}

Here is a sample bf code I have written just now, and here is the translated C code.
But no matter the size, bf is really fun!!!

Friday, May 28, 2010

C++ :: Get Variable's Name



How to print a variables name instead of its value? (not just by giving the name yourself)

This can be easily done with a #define pre-processor directive. As #define treats the preceding expression as cstring, it is possible to get the variables name as a string. Look below:

#include <stdio.h>

#define getVarName(varName,holder) sprintf(holder, "%s", #varName)

int main() {
int var = 100; // just any type of identifier
char name[100]; // it will get the variables name
getVarName(var, name);
puts(name);
return 0;
}

It will print "var" instead of "100" or something other. I saw it years ago somewhere I can't remember now. Today, it suddenly struck me and I think it might be useful who knows when...

Wednesday, March 17, 2010

FIFA World Cup 2010


FIFA World Cup South Africa 2010 Official Theme Song





Lyrics


ooooooh wooooooh

give me freedom, give me fire,
give me reason, take me higher
see the champions, take the field now,
you define us, make us feel proud...
in the streets are, exaliftin',
as we lose our inhabition,
celebration its around us,
every nation, all around us

singin' forever young,
singin' songs underneath that sun
lets rejoice in the beautiful game
and together at the end of the day.

[chorus]:
we all say...

when I get older I will be stronger
they'll call me freedom
just like a wavin' flag
and then it goes back |||

when I get older I will be stronger
they'll call me freedom
just like a wavin' flag
and then it goes back |||

Oooooooooooooh woooooooooohh hohoho

give you freedom, give you fire,
give you reason, take you higher
see the champions, take the field now,
you define us, make us feel proud
in the streets are, exaliftin,
every loser in ambition,
celebration, its around us,
every nations, all around us

singin' forever young,
singin' songs underneath that sun
lets rejoice in the beautiful game.
and together at the end of the day.

[chorus]

Oooooooooooooh woooooooooohh hohoho

[chorus]
___________________________________



Song: Wavin' Flag
Artist: K'naan



Tuesday, March 16, 2010

Blogger Code Formatter


Blogger is a wonderful place to write blogs and there are many code bloggers out there, who want to share their coding skills with the world! But, certainly there are some problems with blogger posting methods, for example, in a <pre> tag, it will ignore tabs, and it causes great problems with some operators like '<', '>' etcetera... So, we can easily write a simple program and use it easily as a code formatter for blogger. Here's an example:

#include <cstdio>

int main(int argc, char **argv) {
    FILE *in = fopen(argv[1], "r");
    FILE *out = fopen(argv[2], "w");
    char ch;
    if(argc < 3) {
        printf("Usage: $ %s <infile> <outfile>\n", argv[0]);
        return 1;
    }
    if(in==NULL) {
        printf("file %s can't be opened.\n", argv[1]);
        return 2;
    }
    if(out==NULL) {
        printf("file %s can't be opened.\n", argv[2]);
        return 3;
    }
    while(fscanf(in, "%c", &ch)==1) {
        if(ch=='>') fprintf(out, "&gt;");
        else if(ch=='<') fprintf(out, "&lt;");
        else if(ch=='&') fprintf(out, "&amp;");
        else if(ch=='\t') fprintf(out, "    ");
        else fprintf(out, "%c", ch);
    }
    fclose(in);
    fclose(out);
    printf("file %s was written succesfully.\n", argv[2]);
    return 0;
}

Windows:

In windows, execute this with any compiler and grab the .exe file, paste it in your C:\WINDOWS\system32 folder. So, for example, if the file name is "blog.cpp", you will get "blog.exe", just paste it to your system32 folder. So now you can use it as a command in command prompt. If you like to format a file, say, "test.cpp", cd to the directory where "test.cpp" is, and to transform, the command is "blog test.cpp blog_test.cpp". Now just open the "blog_test.cpp" file and paste it in the <pre> tags.

Linux

Run it with g++, command: "g++ -o blog blog.cpp", and give enough permissions to the executable "blog", command: "chmod 777 blog". Now, we need to paste it in the "/bin" directory, but as it is write protected, we'll need to log in as root. To do this, write on prompt: "sudo nautilus", it will ask your password, and then an explorer will be opened, and now, just go to the "/bin" directory using it and paste the file. The usage is similar as stated in the Windows part.

Makes life a bit easier...


Monday, February 15, 2010

C/C++ Array of Functions




Oh, never thought of it? well, this is actually not array of functions, this is array of function pointer. You know, in C/C++, pointers are very powerful tools for accessing and allocating memory, and anything that has a logical entity in any type of memory, a pointer can access it pretty easily and this feature made all other languages jealous that they say allowing pointers are threat-full, lolzzz....

Well, here is a simple code presented that shows the use of such an array. Actually, we all know, like a character array s[100], s is the pointer to it, similarly, a function defined as f(int a), f is the pointer to it. Well, enough talk, lets examine the code...



#include <stdio.h>

inline int add(int a, int b) {
return a + b;
}

inline int sub(int a, int b) {
return a - b;
}

inline int mul(int a, int b) {
return a * b;
}

inline int div(int a, int b) {
return a / b;
}

inline int mod(int a, int b) {
return a % b;
}

int main() {
int (*func_array[])(int, int) = {&add, &sub, &mul, &div, &mod};
for(int i=0; i<5; i++) printf("%d\n", func_array[i](10, 5));
return 0;
}


Easy as usual...


Friday, February 5, 2010

Confidence, Trust and Hope


A bit unusual words...


Confidence:

Once all the villagers decided to pray for the rain. On the day of prayer all the people gathered around and only one boy came with an umbrella. That's confidence.

Trust:

Trust should be like the feeling of a one year old baby. When you throw him in the air, he laughs because he knows you will never let him fall.

Hope:

Every night you go to bed with no assurance to wake up alive in the next morning. But still you make plans for the next day. How could you live if you did not have hope for tomorrow?

So be confident, trust in your abilities, never loose hope and do your best whatever you do to make the world more colorful...


Thursday, January 14, 2010

SyntaxHighlighter for Blogger


Installing SyntaxHighlighter in Blogspot blogs



Hello code bloggers, here is a short description and quick guide on how to install SyntaxHighlighter in your blogs and sites as well to beautify your codes. Actually nothing is more painful than reading out rusty codes no matter how cool they really are, so presentation does matter.

To go straight forward, go to Dashboard &rArr Layout &rArr Edit Html. Here you will see your current template. First save the current code to your hard drive before changing anything, so in-case you destroy the whole thing mistakenly, you have nothing to worry, just paste that again here, and every change is reverted. Actually it is good to store every working version of the template in your hard drive.

Now find the part in the html code:

</body>

</html>

First, we need to add some javascript links here, i.e. between these two tags. The files are located on the author's own host, http://alexgorbatchev.com/pub/sh/current/. The version I used for this blog is also uploaded here.We'll use it from there. But if you have your own host, you can download the files and make changes (as this project is open source) and upload it there, then use your links.

First add (I mean copy and paste) SyntaxHighlighter Core scripts:

<!-- SyntaxHighlighter core js files -->
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shLegacy.js' type='text/javascript'></script>
<!-- -->

Now add highlighting brushes for your favorite languages:

<!-- SyntaxHighlighter brushes -->
<!-- some are added here, explore the hosted files for more language supports -->
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPython.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushPlain.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushVb.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'></script>
<!-- -->

When you paste the above lines, it will include highlighting functionality for C++, Bash, Java, Python, Plain Text, Visual Basic, XML. To add more, you can add more links to the files in this directory http://alexgorbatchev.com/pub/sh/current/scripts/. You should only add the files which has a name in the following format: "shBrush<language_name>.js". Clearly, it will add the functionality for "language_name" language.

Now the core style and theme:

<!-- SyntaxHighlighter core style -->
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<!-- -->

<!-- SyntaxHighlighter theme -->
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<!-- -->

You can only use one theme at a time, Default theme is added here, its best in my opinion. However, you can check other themes from this directory: http://alexgorbatchev.com/pub/sh/current/styles/. You can change the link of SyntaxHighlighter theme to any of the files having name pattern "shTheme<theme_name>.js" from this directory.

Now add the main script that will invoke SyntaxHighlighter, also, here you can put some initial parameters (see below) as well:

<!-- SyntaxHighlighter main js -->
<script type='text/javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf';
SyntaxHighlighter.config.tagName = 'pre';
SyntaxHighlighter.defaults['wrap-lines'] = false;
SyntaxHighlighter.defaults['ruler'] = true;
SyntaxHighlighter.all()
</script>
<!-- -->

Here you see, some defaults like line wrapping disabled, ruler visible, and also, SyntaxHighlighter is associated with the <pre>...</pre> tag. The clipboardSwf is the background style. And one special parameter for blogger blogs: bloggerMode = true. For the complete configuration list, visit http://alexgorbatchev.com/wiki/SyntaxHighlighter:Configuration.
All done, just save it...

How to write codes in pre-tag? Well, all you need to do is just invoke the classes in pre tag... for example, you might want to add a c++ code, you should do this:

<pre class="brush: cpp">
/*
** write your codes here.
** make sure you convert all < to &lt; and > to &gt;, important!
** do not use tabs, use 4/8 spaces instead, no break tags needed.
*/
</pre>

Clearly, the brush names are those "language_names" that you included above, for example, "shBrushCpp.js" will be invoked with "cpp", "shBrushXml.js" will be invoked with "xml", etc etc... Actually, in general, the class inclusion might look like class="param_list"
For complete usage, demonstration, and information, visit: http://alexgorbatchev.com/wiki/SyntaxHighlighter in the For Users section.

Hope this helps... not a big deal. Happy blogging.

Sunday, January 3, 2010

Online Compiler / Interpreter



Visit http://www.ideone.com/
This is a free online compiler introduced and being developed by SPOJ team, a lots of thanks goes to them! and supports almost all available languages on SPOJ system.

So, if you are a C++ programmer, or like to learn some new esoteric or functional programming, or want to use gcc/g++ but don't have linux, or server side programming languages but don't want to setup a new IDE or virtual server, you can use this site... free for all!!!

Have fun...

Thursday, December 31, 2009

Happy New Year....






Happy new year, wishing you all a very very happy 2010...


Let 2009 go away with all your sorrows and mistakes...


Thursday, July 9, 2009

Craziest Language Ever !!!


Just have a look at these programming languages... They are really crazy as their names.
  1. Brainf**k
  2. Intercal
  3. Whitespace
These are called esoteric programming languages.

Monday, July 6, 2009

0.99999999................... = 1


Wanna see the proof? Check it out.... Let's assume,
Let, x = 0.99999999999999.......................
=> 10x = 9.99999999999999.......................
=> 10x = 9 + 0.99999999999999...................
=> 10x = 9 + x
=>  9x = 9
=>   x = 1
So, 0.99999999999999............................ = 1
Is anything going wrong here?