Sunday, May 31, 2009

Puzzle 29 – Enter the Matrix!

Language – Java | Type – Concept | Last date 3-June-2009 9:00 p.m. IST | Points 5

Lately I have been playing around with the look of the blog quite a bit. I decided its time to get in something new. This question reflects that mood!

Conceptual questions are getting a little boring aren’t they? Let’s get our hands dirty with programming shall we? Here’s your question -

Write a program to scan and print the elements of a matrix. (3 X 3)

Twist: Use a single for loop only. Any other Looping Structure, recursion can not be used. No additional classes except those required to scan the elements – Scanner or Console! (No Collection framework classes)

Note: Scan elements of the matrix first. Print elements later in a normal matrix form (i.e. rows and cols).

You don't have to actually write the program - just mention the principal involved - probably with a little pseudo code!

Link of the day – http://www.getdropbox.com – site gives you 3 GB free storage (who’s doesn’t) but has too many excellent features to ignore. (Use My Referral for free extra space)

Puzzle 28 -Solution.

I got a lot of unexpected solutions for this puzzle. I say unexpected because it's really not possible to know all possible solutions to the questions I post. Really – there so much room for improvisation.

Most of the questions are based on a Java principle. There are a few hints as to what I am looking for – so let's see what this puzzle was all about.

The solution that I had in mind for this puzzle was to add the static modifier to both the base and derived class fooBar() method.
In case of static functions – static over ride would apply the base class function would get called irrespective of the object pointed by the reference.
Adding a static modifier to a function does not change its signature – a signature of a function consists of its name, return type and parameters. Everything else is a modifier for the function.

The other common solutions were
a. Making Base reference point to Base class object. (Now I do remember why I had originally kept the Base class abstract!)
b. Calling super.fooBar() from the Derived Classes foobar().

Truthfully the challenge was --> 'Java dictates that polymorphism come into play when the Base class reference points to the derived class Object. Lets change that shall we?'
This means you had to stop the polymorphic behavior of Java from coming into play.

Nonetheless I'll consider any solution that gets 'Base Ahoy!' printed instead of 'Derived Ahoy' as correct!!

Wednesday, May 27, 2009

Puzzle 28 - Change the Rules (Polymorphism)

Language – Java | Type – Concept | Last date 31-May-2009 12:00 p.m. IST | Points 3

Yesterday I was reading some of the old post here and some of them are pretty interesting. Sure a lot of them are simple run of the mill questions – but some are pure gems. This one is a favorite of mine. The answer is already there but it still would be good to hear your solutions for it.

So much for old nostalgia. Time to move on.

public class Base{
public void fooBar()

{System.out.println(
"Base Ahoy!");}
}

public class Derived

extends Base{
public void fooBar()

{System.out.println(
"Derived Ahoy!");}

public static

void main(String args[]){
Base b
= new Derived

();
b.fooBar();
//Get this should pint Base Ahoy!
}
}

Java dictates that polymorphism come into play when the Base class reference points to the derived class Object. Lets change that shall we?

Get this code to compile and run. Only instead of printing Derived Ahoy get the code to print Base Ahoy. Oh no If’s please!
Usual rules - Add any amount of code you like but no deletes.Make it tough?

Site of the day - http://www.javaonthebrain.com - Lots of cool applets out there -- Nostagia again!!!

Got an answer? Why don’t you leave it here.

Puzzle 27 Solution.

I must admit this puzzle was a bit of a cliche - atleast for those who have spend some years on Java. The question does show up in one form or the other from time to time.
Nonetheless the format of Twisters make multiple solution possible - and its fun to see the different solutions that you folks come up with.

1. The general principle on which this puzzle was based is that a static method can be accessed using a reference variable.
So the solution was to change the SomeMethod() to static, that way it could be accessed by the reference without an object.
Solution --> public static void SomeMethod(){}

2. A common solution that I got was adding a if statement before ex=null; preventing ex from becoming null in the first place.
Solution -->
if(true == false)
ex = null;
Prevention is indeed better than cure.

3. A third solution is assign ex a new Object immediately after it is set to null.
Solution -->
ex = null;
ex = new Exceptional();

That covers up all the right solutions for this puzzle. Can anyone think of more?

Leaders board and score to be updates with the next post!

Sunday, May 24, 2009

Puzzle 27 – To Null or Not to Null (Pointer Exception)

Language – Java | Type – Concept | Last date 27-May-2009 9:00 p.m. IST | Points 3

The format of the puzzle – make it very easy at times to answer a puzzle without really giving it a lot of though. It put me in a dilemma – should I allow the puzzle to be simple or make them tough right from the beginning. I would love to make that decision – but I found someone better to make this decision – You.

Oh don't worry it's not an opinion asking post. It's just a small change in how things work. Let me explain – The puzzles would be in the same format as they were before. You will also have an extra choice – answer it the way it is or hit what I call the 'make it tough.' link. Voila the same puzzle but a little tougher now!!!

My suggestion – Try and answer the puzzle without hitting the 'make it tough' link – just to see what solution you come up with at the top of your mind. Post it – Really I love to hear from you folks. Hit the 'make it tough' link and see if your solution still works. You can always re-post a new solution anytime!!

Enough of my chatter – puzzle time!

package com.twisters;
public class Exceptional{

public void SomeMethod(){}

public static void main(){
Exceptional ex
= new Exceptional();
ex
= null;
ex.SomeMethod();
//This must not throw an exception!!
}
}


Your code must not throw a null pointer exception.
You may add (but not delete) any additional amount of code – and no you are not allowed to handle the exception using try-catch. Make it tough?

Site for the day - http://www.theproblemsite.com/treasure_hunt/ - Try your luck out there treasure hunters!

Got an answer? Do leave it here.

Puzzle 26 – Solution

Every puzzle on twisters has a concept. The concept is really simple – something we day in and day out as programmers.

The last puzzle was no different. It was based on the concepts –
1. Method overriding is different from method overloading.
2. The signature of the equals method in the object class is equals (Object). It can be over ridden by the more specific equals (Loaded).

The solution I had in mind for the last puzzle was - writing an overloaded equals() method. There were clues all over – if you looked carefully enough. The title was specific 'No overriding'. The word overriding was highlight to draw attention to it. And most importantly there were these words 'Read carefully.' Behive kind of read my mind – read his comments here.

The most common solution that I got was to change the true to false in the System.out.println() in one way or the other. There are many ways to do that – I’ll list up some,

a. System.out.println(!new Loaded().equals(new Loaded())
b. System.out.println(new Loaded().equals(new Loaded() == false)
c. System.out.println(true || new Loaded().equals(new Loaded())
d. System.out.println(new Loaded().getClass().equals(new Loaded().getClass())

One solution that was really unique was by Makkhdyn - extends ArrayList [or any other class with an overridden equals and a default constructor].

So who got it right? Everyone who left a comment – that’s a long list. Listing out all the names is no longer feasible – so I’ll just update the leader boards & publish all scores soon.

Till then watch out for the next puzzle – I got a surprise out there.

Wednesday, May 20, 2009

Puzzle 26 - No Overriding Please!!!

Language – Java | Type – Problem (Code) | Last date 24-May-2009 12:00 p.m. IST | Points 3

This puzzle gave me a lot of trouble. I had a real hard time deciding which one to put here. Finally I decided to give this one a go. This one is tough – real tough, at least it was the first time I saw it. I never did get a solution – one of my friends pointed it out to me. So much for the story – I'll leave you with the hint 'Read carefully.'

package com.twisters;
public class Loaded {
public Loaded (){}
public static void main(String[] args) {
System.out.println(
new Loaded().equals(new Loaded())) //Line 1
}
}

Get the System.out.prinltn() to print true at line 1.
You may add (but not delete) any additional amount of code - by the way did I mention that you are not allowed to Override the equals method :)!

Site for the day – http://www.topcoder.com/ - Programming contest site that gives cash awards.

Got an answer? Do leave it here.

Puzzle 25 - Solution

The '~' operator though rarely used gets you the two's complement of that number.
Basically what it boils down too is 2 is converted to -3, 1 to -2 and 0 to -1.

So, here the line that does the trick -
int x = ~0; //Here x is initalized to -1.
The one character used '~'

I did get couple of other interesting - though not correct solutions for this puzzle.

Kannan gives us - System.out.println("X is : " + 0) - The first time I saw it I was wondering how I had missed thinking of something so obviuos. This solution though relies on deleteing the character 'x' -so it can't be considered right.

Shyam - gives us a solution without any additional characters. Read up his commenets here.

Who's got it right this time?
1. Alex
2. Behive
3. bernardomen - Thanks for your comments too!!
4. Tim Yates
5. Anonymous

Sunday, May 17, 2009

Puzzle 25 - Deja-Vu (Code completion -3)

Language – Java | Type – Problem (Code) | Last date 20-May-2009 9:00 p.m. IST | Points 2

I spend some time making a few changes with the blog look and feel – customizing thing around – I especially like the social sharing icons I put down there – gives the blog a lot more color! I wonder if there is a hint hidden here :). Folks time to get on with the next question.

If you haven't had a look at the previous puzzle – do have a look at it before you begin this one!

For the rest – getting a feeling of Deja-Vu? Think you have seen this puzzle before? – you have it's the same question as the previous one. Ditto – Same.

package com.twisters;
public class UnIncrement{
public static void main(String[] args) {
int x = 0;
x
++;
System.out.println(
"X is : " + x);//This must print 'X is 0'
}
}


Get the System.out.prinltn() to print 'X is 0' at line 6.
You may add (but not delete) any additional amount of code.

(Same lines – thats because I copy pasted them!!!)

Here the change – the puzzle a lot simpler now. My clause "You can just add one character to the above code to get it to work - any one character but that all"

Site of the day - http://interviewpattern.com/post/Puzzles-and-Riddles-on-the-interview-(Part-e28093-I).aspx. If you like analytical puzzles you might enjoy the post!

Got an answer? Do leave it here.

Puzzle 24 – Solution.

The last puzzle brought out so many solutions that I am having a hard time figuring out which one I like best. Here the list of solutions – I am not posting the entire snippet just the relevant line – check the previous (or next) puzzle if you want to have a look at the question!

1. Solution by Joe Smith and Mine:
x = x++; - Yep Joe got me there. I do spend a lot of my time on Java Ranch so many of the puzzle question do in fact stem out from there. Real Java questions turning to Java puzzles.

2. Solution by Bernardomen, Kannan, Stefan - System.out.println("X is : " + --x); - this one is neat and self explanatory.


3. Solution anonymously left - int x = 0-1; Cute isn’t it?


4. Solution by me – int x = -01; - never said anything about the two characters being continuous did I?

That about covers all the solutions – I got. Here is one more answer that I got but it’s not correct. Usually I don’t point out wrong answer – but this one is a bit special – I thought about a similar question a few months back – and tried to figure out the reason why this particular construct (x++--) doesn’t work? Anyone want to attempt a guess on this?

Congrats to
1. Joe Smith
2. Bernardomen

3. Kannan

4. Stefan

5. Anonymous
for getting the right solution

Thursday, May 14, 2009

Puzzle 24 - Recessional Increment (Code Complete - 2)

Language – Java | Type – Problem (Code) | Last date 17-May-2009 12:00 p.m. IST | Points 2

Without much ado - here is the next puzzle!

package com.twisters;
public class UnIncrement{
public static void main(String[] args) {
int x = 0;
x
++;
System.out.println(
"X is : " + x);//This must print 'X is 0'
}
}

Get the System.out.prinltn() to print 'X is 0' at line 6.
You may add (but not delete) any additional amount of code.

Sounds too simple doesn't it? Time to throw in a few additional clauses - generously I’ll just add one.
"You can just add two characters to the above code to get it to work - any two characters buts that all"

If you’re wondering why this puzzle is so easy - its because I have a few plans up my sleeves to make this more interesting in my next post-:)

Link of the day - http://javatutorialsworld.blogspot.com/2009/05/simple-java-twisters.html - have fun with the increment operator and see if you can get all six correct!

Got an answer? Do leave it here.

Puzzle 23 - Solution

There are two set of solutions to the last puzzle. One of them wasn't exactly what I had in mind.

Here the first one,
package com.twisters;
interface TwistedInterface{void getA();}

class TwistedBase implements TwistedInterface {
public void getA() {}
}

public class TwistedClass extends TwistedBase implements TwistedInterface {
public static void main(String[] args) {
System.out.println(
"In Main");
}
}

Pretty simple explanation – the TwistedClass extends the TwistedBase that implements the getA() method. Since the getA() method is implemented in the base class it need not be implemented in the child class.

The second one,
package com.twisters;
interface TwistedInterface{void getA();}

public abstract class TwistedClass implements TwistedInterface {
public static void main(String[] args) {
System.out.println(
"In Main");
}
}

This solution is even more simpler – Just make the TwistedClass abstract. You no longer need to implement the getA() method in TwistedClass!

The class Twisted had a main method - a probable hint that the class should run.
However as the question was worded - get the class to 'Compile' and said nothing about 'Running' both solution are correct! Maybe I should be more careful with my wordings - but this just brings out the essence of what twisters was supposed to be - many ways to solve a puzzles.

All I can add is this is going to get more fun going forward so keep watching this space for more...

Congrats to
1. Stefan
2. Behive
3. George PĆ³lya
4. Shyam
5. Joe Smith
For getting the right solution.

Leaders board will be updated with next post.

Wednesday, May 13, 2009

Twister & Treasure Hunt Updates

I out on a party tonight - so the new puzzle is going to be delayed by a day.

The other thing I am excited about is the Java Treasure Hunt. I think I got the base ready and if things work out as plan there be some really intereting updates soon. I am still thinking of a good name for the event - any suggestions?

Other than tha a few other small changes planned for the blog!!:)

I have extended the deadline for the last puzzle by a day -You might want to have a peek if you have not done so yet :)

Sunday, May 10, 2009

Puzzle 23 – Implement the Unimplemented! (Code Complete – 1)

Language – Java | Type – Problem (Code) | Last date 14-May-2009 9:00 p.m. IST | Points 3

Twisters were started with the objective of having cute Java puzzles – puzzles that are based on really simple principles yet stubble enough to make you pause and think.

However somewhere down the line I though some of the puzzle were too simple – you could just pick the code compile it and punch in the output as the answer. I decided to raise the bar a bit and see how things go.

So here the first puzzle of the new series Code Complete (well its called code complete – because that's what you have to do - complete the code!)

package com.twisters;

interface TwistedInterface{void getA();}

public class TwistedClass implements TwistedInterface {
public static void main(String[] args) {
System.out.println(
"In Main");
}
}

Get this code to compile - You may add (but not delete) any additional amount of code you like with one exception -
you may not implement the getA() method inside the TwistedClass. Feel free to make any other additions!

Commenting out any existing code - is considered as deleting. Cute statements like public class Twisted /*implements TwistedInterface*/ don't count as correct answer thought I really do appreciate ingenuity! -:)

I think this is a tough puzzle – in case you disagree you might want to leave your solution here.

I'd like feedback for this particular puzzle – is it hard or still too easy? Feedback is as always highly appreciated!

Puzzle 22 – Solution

This is a pretty classic puzzle with a pretty classic solution. The program below swaps two numbers without using a temporary variable.

package com.twister;
import java.util.Scanner;

public class Swap{

public static void swap(int a,int b){
System.out.println(
"Numbers before change are "
+ a + " and " + b);
a
= a + b;
b
= a - b;
a
= a - b;
System.out.println(
"Numbers after change are "
+ a + " and " + b);
}

public static void main(String args[]){
swap(
new Scanner(System.in).nextInt(),
new Scanner(System.in).nextInt());
}
}

This program works for all values of integer even if we overflow them. Don’t believe me – go ahead and give it a try!!

Congrats to
1. Behive
for getting the right solution.

Wednesday, May 6, 2009

Puzzle 22 - Swap again!

Language – Java/C++ | Type – Problem (Code) | Last date 10-May-2009 12:00 p.m. IST | Points 5

This is one of those classic puzzles …

Write a program that swaps two numbers.
Twist: Do not use a temporary variable while doing the swap.

Think this one is pretty easy? You might want to try out its tougher variation here.

Got an answer? Why don’t you leave it here.

Puzzle 21 – Solution

The key to the puzzle is 'static method can be called using an object reference.' The solution to this simple puzzle is:

Output – Static Method Print Statement called.
Reason - Static method can be called using object reference.

Sorry no correct answers this week.

Sunday, May 3, 2009

Puzzle 21 – Static This!

Language – Java | Type – Concept | Last date 06-May-2009 9:00 p.m. IST | Points 2

Does anyone really code like this? Anyone out here figure out what does this code do?
package com.twisters;
public class StaticThis {

public static void main(String[] args) {
new StaticThis().print();
}

public static void printStatement(){
System.out.println("Static Method Print Statement called.");
}

public void print() {
this.printStatement();
}
}
Got an answer? Why don’t you leave it here.

Puzzle 20 – Solution.

The key to the last puzzles solution is ‘getting hold of the super class variable in the child class constructor.’ The simplest way to do so is using the super keyword.

The code snippet that achieves this is super.a = 10.

Congrats to
1. Sathi
2. Anonymous
for getting the answer right.

Friday, May 1, 2009

Treasure Hunt - Post 1

Twister is a basic level quiz and I have been for some time thinking of something more advance. That’s what gets me to this post - a Java based Treasure Hunt.

Treasure hunts are always fun - especially if you don't have to run about in dense forest and ride tormenting seas :)

I still have not got everything in place - might be a few more weeks before everything is ready to roll - but I'll try and give you a fair idea about what this is going to be.
It's a treasure hunt - one clue will lead to another - until (or if) you finally find the treasure. The clues are not typical Java features and like most treasure hunts there would be more then one way to break the clues.

The story so far? "Legend has it that HeadHunter of the java.pirate.hunter band has kept this treasure hidden for over 10 years. But nothing can be hidden forever and rumor of The LINK have started to surface. As you well wishing friend and guide I offer you this adventure - something you have never seen before ..."

Keep watching this space for more...