Wednesday, January 28, 2015

Will Code for Food.


For my normal friends, this disclaimer is a must -:
 Most of the words and sentences in this blog are full of geek and the dreaded mathematics. But you can magically make this nerdy blog go away. The trick is to press the keys Ctrl and W together and even before you finish reading this sentence, the blog will be gone, gone far away in some parallel universe in which it will be pressing Ctrl + W and you will be the one disappearing away!.
It was a drowsy Saturday night when before starting some boring TV serial to fall asleep, I decided to check what’s new on Facebook. I see my friend Janko describing some nice mathematical problem on project-euler with absurd words along with gigantic adjectives ;) Moreover, there is steak on offer. Yes, you read it correct, there is steak on offer for the problem solver. The first thing to flash after reading has to be this cartoon.


The problem had to be solved. It will be an injustice to the steak, if it goes unserved. The only thing on mind now: Mission 498.
I start thinking about the problem. Thought of an solution which would work in . But algebra is a bitch and does not go hand in hand with number theory; else my solution would had worked like a charm. The problem is in is the algebraic remainder and does correlate with the numeric remainder. Only if this was true, the problem would had been a cakewalk. But then one does not get steak for crappy code. The wheels in the brain have to be turned. The pages of the scratchpad have to be made dirty. Some Greek symbols have to be used to add dignity to the solution.
Another look at the problem and you know what has to be done. Why should you be dividing by when you can divide by . Yes, one can always substitute . This makes trivial i.e. last terms of binomial expansion of . To spell it out -:
Now that it has become a piece of cake, it’s time to code.. While traditionally I would had chosen C++ to code, but with recent ventures with Gospodice Princess I decided to show off python. Oh! You don’t know Gospodice Princess.
  • He is atomic.
  • Don’t know atomic, He is Aleksandar Tomic.
  • Don’t know Aleksandar Tomic, He is Aleksandar Tomic (SQL).
  • Don’t know Aleksandar Tomic (SQL), then go to savski most, close your eyes and jump into the river :D.
Cool, now that we know who Gospodice Princess is, we can proceed to the code. I wouldn’t want to leave an opportunity to show-off awesomeness of python, especially to my dear friend, Gospodice Princess. Just because I want the code to remain readable, the code is lengthy i.e. 18 lines; Yes, a python code with 18 lines is considered lengthy.
def ncr (n,r,p):
    num, dem = 1, 1;
    for i in range(r):
        num, dem = (num * (n-i) ) % p , (dem * (i+1)) % p ;
    return (num * pow(dem, p-2, p)) % p ;

def lucas(n, m, p):
    if n == 0 and m == 0 : return 1; np, mp  = n % p, m % p; return 0 if
    mp > np else lucas(n//p, m//p, p) * ncr ( np, mp, p);

def solve(n,m,d,p):
    return (lucas(n,d,p) * lucas(n-d-1, m-d-1,p)) % p;

if __name__ == '__main__' :
    if solve(6,3,1,999999937) != 24 : print ("Test1 Failed") ;
    if solve(100,10,4,1000000000000037) != 227197811615775: print ("Test2 Failed") ;
    print (solve(10**13, 10**12, 10**4,999999937));
    

So, now that the minor problem has been solved with a beautiful python code, the complex problem still remains. The problem of getting the steak lunch when the two parties are 6000 miles apart. I will leave this part for Janko to solve.
For honesty, I did take a little help from a friend (Fernando) to simplify the summation of combinatorial coefficients, but rest is my own work.
Cheers and Pozdrav.

Tuesday, September 18, 2012

Coorg: Yet another trip to remember. Part II

Peter, Jack, Colin and George; Only the ingenious souls can enjoy the beauty of randomness of these names. These smart-asses have made their day and may please fly off from here. Whereas, the feather-brains have aptly recognized that these are characters from The Secret Seven. The sharp goofballs must still be thinking where the hell are Pam and Barbara. Well, in an institute full of nerds, objects with two girls are rare extinct species. (Please pause for 2 minutes to show sympathy for us. Thank you.)  This is precisely why the thirsty (you know what i mean) Jack always wishes to roam on Brigade road. And his pet dog pig Dewey is always with him.

Million gags take flight during trips, especially the nifty ones. Most of them die due to scant grey matter. I will pen down few of them here, so that later, we can refresh ourselves with these ludicrous memories. Wait. What. Oh My God! Are those tears rolling down your face ? Ahh, Okay, lets cease this heart touching (hmm, so you didn't feel it heart touching. Die you cold-blooded stone-hearted b*st*rd. Die) note here only and start with one of the many George's incidents which never fail to put a smile across that face :) 

Generally, people aim to get things done with minimal resources or cost. But our friend, George, is somewhat different. He is audacious and always takes the road less traveled. If the world can accomplish a task in 40 rupees, he will spiritedly do it in 60 rupees. Hats Off Man!. Salute. Respect. 

But things are different today. Colin has stepped-up. He has left no stone unturned in his quest for persuading the chauffeur to offer his Bolero at INR 1200 since the Indica had been offered at INR 1500. His god-like confidence, in defending his stance, would had surely blown your mind. (George  has thanked Colin for the favor and now carries an assassin's smile on his face.)

Jack, while roaming around in illicit areas, found a beautiful Nigam (Nigam comes from nagar-nigam, which in hindi means co-orporation. The nick is completely random, bears no coincidence with anyone. and is used to avoid law suites and district courts) named Dewey. The Nigam was so vivacious, that Jack instantly bought him for INR 200 400. Jack's happiness knew no bounds when he got acquainted with Huey, Dewey's Nigam B-). The news that Huey came free with Dewey, made Jack so ecstatic that he started dancing. (A glimpse of jack dancing).  

River-rafting is fun; encountering raffles during river-rafting is more fun. Everything was going smooth and sexy until our Black-Pearl was hit by a ice-berg rock. The black-pearl shivered, wobbled and sent off a shudder toppling Colin and George. Alas! Both of them didn't knew swimming :(. A friend in need is a friend indeed. Wait. No, I didn't dive to get those jackasses out. Jack rose up to the occasion. He extended his row for Colin to grab and get back. Colin, battling against odds, combating the river-waves, somehow wrangled to grab the row. As soon as Colin got his hands on the row, Jack, the buffoon, let it go. Faaakkk! What! What did you do Jack!  How can you let it go! Oh My God! Then went Colin along with the river. Perfect KLPD, but Sad. Finally, Superman came into action and got Colin and George back onto the boat. Shhhuuwww. What a relief.

There are still many more hoaxes, but I have breakfast at yuktahaar tomorrow :p. Enjoy the post and do wake me up tomorrow morning for my morning meal.

Cheers.

Monday, September 17, 2012

Coorg: Yet another trip to remember

Before the story starts, there is `yet' in the title because there have been many awesome trips which I haven't blogged about. Glimpses from two different excursions follow.

Munnar, Kerala
Savitri Valley, Mahabaleshwar

After a lot of hiccups and alibis; Peter, Jack, Colin and George (names changed to ease leg-pulling)  rolled out towards Bangalore for a fun and frolic trip. 

What initially seemed as a will-be boring train journey turned to be quite an amusing one. The way George turns pale things into engaging ones is indeed commendable. This one started with Jack's interesting 'Two Samosa Theory' and our laziness to pack supper. Now there were we, waiting for the train to halt so that we can hunt the platform for any cafe/stall. We probed the vicinity until the train's siren; got back onto the boogie; to find that George is yet to board the train back. Poor thing was busy buying the idlis, unaware of short duration of the halt. "Run you Idiot", we all screamed in unison. George scrambled his way and somehow managed to get hold of the rod to get in. Sssshhhuuww. (Kudos if the DDLJ scene flashed your mind. Yes, something similar to the photo below :p). Alas! even though we had George back in train, the idlis weren't :(. But the saying `` दाणे दाणे पे लिखा है खाने  वाले का नाम '' has seriously got some x-factor in it. Seeing our George's dismal efforts at getting the idlis in, an angelic woman offered us fried rice and boy! weren't those awesome :).  Planning the Bangalore trip, thrashing Colin over and over again in the game of court, chit-chats about Malaika, were highlights of rest of the journey.



Life isn't easy. All the plannings got a low blow, when the pleasant Bangalore morning awestruck-ed us with 
  • Diesel prices have been hiked by INR 5.00
  • KSTRC is on strike today.
What! Fuck! KSTRC strike! today!!! Oh dear God, why, why only today. The whole Majestic wore a dull look. It was like a 40 inch Full HD Television in Grayscale! All we could see were a few hot beautiful reporters gathering crowd to make some Friday morning breakfast news! 

We then went to Huey's Palace, roamed about the near-by places until Jack met with a tragic blow! (Ohho, not what you are thinking ;), its was just that his slippers broke.) Yes, you guessed it right :p, his slippers broke. Unfortunately (yes, you read it right, UNFORTUNATELY), there was a Bata showroom near-by.

Who on this green earth would had guessed that Jack was on his path to set a guinness world record. I take this opportunity to congratulate, my friend, Jack for selecting the his favorite pair from half-a-dozen-choices in less than 115mins 54secs. Colin had a vital role in helping Jack cross a century of minutes for making the selection. The night was full of fun beauties, as we visited the live wire of Bangalore, i.e. Brigade Road :) 

Dewey had booked tickets for Coorg, which indeed is an alluring place. It was pleasing to see George and Huey's eyes full of tears of joy when we climbed up an hillock told assuming it to be a sun-rise point. Though it wasn't a sun-rise point, we were astonished to find an elephant, dog, pig and even a bear on the hillock ;). This was followed by a magnificent waterfall. Yes, tall splendid, statuesque waterfall indeed. Look at the picture below to assert these adjectives. 
Abbi Falls, Coorg.

The clock struck and it was time for the most awesome sport in Coorg i.e. river-rafting. River-rafting is so much fun, especially during winter times when the rivers have abundant water. The thunderous gurgling of the river increases the thrill exponentially!

The deal had been finalized; 7.5 km of river-rafting; They say revenge is better served cold and it was time to awestruck people hotties of Bangalore. No, we didn't fail. The jaws of all beauties on the river-bank dropped when they saw 6 semi-nude super-sexy hulks boys walking down the bank. It was a marvelous experience. rowing; swimming; racing; shouting-like-hooligans; crashing-into-other-boat-pirate-style; Mind blowing!

Experience must have been more mesmerizing for George and Dewey as they got to mingle with girls from the other boat, when the boats crashed into each other ;).

The post is getting too long now. I must stop. Congratulations if you have read it till here :). Excuse me for mistakes (of any sort), i made while writing this post. There are many more incidents to share, will write the other volumes later :). Till then keep the following two points in mind.
  1. Make sure your workplace has a good foosball table. If you don't play foosball, then please do. 
  2. Never play foosball if both teams are equally matched! Your game may not end or will have a very long deuce. 
Enjoy :)

P.S. Even if you guess the people behind these dummy names, do not comment it. I know you are an intelligent beast. 

Friday, March 30, 2012

[Solved] Plugged in, Not Charging

Many times, we face this problem and our head starts spinning. Its like seriously wtf has gone wrong. The computer says that your charger/adapter is plugged in but the battery is not charging even tough the battery is strikingly low in power. 


You may try switching on-off the power-switch, rebooting your system, but the problem still exists (obviously, thats why you are here :p ). Then you search the web and end up landing in blogs which say to play with your bios which is highly risky for a non-geeky guy (the sad part for this trick is that it may not work always or even if it does work, it works temporarily). Many even try getting a new battery. Not needed!, its not a problem with your battery. Here's a simple solution. 

Try a getting another (new) adapter. This does work. You may/should try using your friends'/neighbors' adapter before placing an order for the same. 

Hope this helps, cheers :)

And, we are back again...

Time flew by, and bits & pieces pilled up over this electronic diary . But, finally, the heap has been cleared and here we are, back into action!. Feels great to be back. Few posts coming up, hope you enjoy them :)

~Learn, Teach & Blog

Saturday, February 5, 2011

Android Intents

    We are back, This time with more on android. In this article i will share my experience of using intents and try to simplify things.

    Whenever one calls a function, he/she can pass arguments to the function. Similarly when one calls another activity from an activity, how are the arguments passed to the called application ? Or even if two activities want to talk ( exchange messages ), how do they achieve it ?. How does an activity start another activity ? The answer to these questions is intents !

    Intent is basically a carrier for your message. You can send messages to the other activity via intents. The way i most prefer is to put it into extras and then get the bundle
eg.


Intent intent = new Intent() ;
intent.putExtra("Name", "Saket" ) ; //These are key-value pairs with string key.
intent.putExtra("Age", 20 ) ; //Value can of any type


To get the sent information on other side, one can follow the following way.

Bundle bundle = getIntent().getExtras();
String name = bundle.getString("Name");
int age = bundle.getInt("Age");

and so on....

So, We now know how to pass messages. One thing here, to ponder over, is that an activity can call an activity/service as a sequel or may be it is expecting a reply from the called activity. A rough example of a sequel calling can be an ImageDisplayActivity or a SlideShowActivity. Example of calling an activity, when expecting a reply, is calling SelectImageActivity which displays images of a given folder and then replies the imageFile which was selected by the user. Another can be of calling MakeTransactionActivity which tells if the transaction was successfully completed or not, etc. The above two methods of initiating another activity can be done by

  • startActivity()
  • startActivityForResult().

Also one can broadcast some info or object using intents, to other Broadcast Receivers, by the means of sendBroadcast() and other similar methods. The broadcast listeners have to override their onReceive() method.
For more information on broadcasting intents refer here

For initiating other standard activites, just call startActivity with the activity Action. eg the most common is to initiate a phone call. This is a way how it can be done.


Intent intent = new Intent ( Intent.ACTION_CALL ) ;
intent.setData( Uri.parse("tel:999666333") ) ;
startActivity( intent ) ;

Hope this helps :)

Friday, January 7, 2011

Rendering Made Easy

This one concerns friends who have to do away with Graphics. We had our Graphics, some of us liked it while the others "Really" liked it ! :p . The main reason for such "real" liking were the painstaking assignments. Yes!, The assignments, which can be great fun for some, are tremendously boring for others.
    Writing long C++ codes to get triangles form rectangle and circles, is like calculating the sum of first n Fibonacci numbers with pen and paper!. Many a times people are not comfortable with stack manipulation of Instruction Pointer, and they are asked to manipulate stack of matrices.
    The main problem arises when triangles have to aligned to look like robots and dogs. Also the texture of the triangles have to be so adjusted that the triangle skeleton indeed looks like a Dog!. Write a file, compile it, run it, change values, compile it, run it, change values, compile it, run it,...and so on.
   But all this can be avoided :D. To your rescue is Python, a language which requires minimum amount of code. I would like to draw your attention to PyFLTK ( Python Fast Light Tool Kit ). It will certainly make your life easy.
   No need to write codes !. Just design your window on an interactive shell :). Type a statement and see the results. No need to compile, no need to re-execute the previous steps, no need to bang your head against the wall. Here's an example.
        > python
        >>> from fltk import *
        >>> window = Fl_Window(300,300)
        >>> window.end()
        >>> window.show()
        # Window pops up here
        >>> window.label("My new title")
        # Window label changes immediately
        >>> window.color(FL_RED)
        >>> window.redraw()
        # Window color changes to red immediately. TADA !

Short, rather much shorter codes.
from fltk import * ;
window = Fl_Window(300,300) ;
window.end();
Fl.run();
Thats it, just 4 lines to create a window. Probably you will still be including libraries and header files in your C++ code.

Show/Hide Functions


Still bothered about your submission in C++ ?
You can put your OpenGl code inside the python file by wrapping it with gl_start() and gl_finish()
     gl_start()
     ... put your OpenGL code here ...
     gl_finish()
Voila ! Party TIme :P

To install PyFLTK, and enjoy Graphics ;) go here.
You can find more about PyFLTK here