Sunday, December 13, 2009

Java Puzzler - on Code-o-matic

I don't have a puzzle of my own today - I've covered up most things I know & I really don't want to end up repeating myself! So for now I am going to point you to a puzzle I had come across some time ago - http://code-o-matic.blogspot.com/2009/02/crazy-java-puzzler.html

I really don't know the answer to this puzzle - but then again I've never been good with Generics or hardcore Java - you folks might know an answer. Give it a shot - and do let us know too if you got an answer!

Sunday, November 22, 2009

Puzzle 59 – Comparing the Java way.

A really cool part of the collection framework is the Collections.sort() function. The function sorts out a collection based on the natural ordering of elements. Of course – for you own data types you need to define what the ‘natural’ ordering is. Doing that is really simple though – just implement the compareTo() method of the Comparable interface and we are ready to go.

That brings me to today’s questions. The code below for the Points class implements the compareTo() method. Now my manager kept insisting that there is something not right about it – but the code looks alright to me.

What do you folks think – are there any problems with the code below?

package com.twister;

import java.util.ArrayList;
import java.util.Collections;

public class Points implements Comparable<Points>{
int xCoordinate;
/*
* 1. Returns 0 if both points have same xCoordinate (say 3 & 3) - returns 3-3=0
* 2. Returns +ve if first point is on the
* right hand side of the second point (say 5, -3) - returns 5 - (-3) = 8
* 3. Returns -ve if first point is on the
* left hand side of the second point (say -5, 3) - returns (-5) - (3) = -8
*/
public int compareTo(Points p) {
return xCoordinate - p.xCoordinate;
};

public static void main(String[] args) {
ArrayList
<Points> arrPoints = new ArrayList<Points>();
/* Add lots of points to the array list */
Collections.sort(arrPoints);
/*Print the sorted collection */
}
}

Got a view? Leave one here.

Wednesday, November 18, 2009

So where is the puzzle this week?

I have been a irregular with puzzles on Twister for some time now – for one I have covered most of the puzzles that could be covered in the twister format and secondly I been working on Quiz4j – adding puzzles and quizzes to it.

When I started
Quiz4j my vision was to create site that would cater to Java Programming Puzzles and Quizzes. I found programming puzzles a really good way to learn and keep in touch with some challenging programming. The more I got interested the more stuff I found around – and I released that there were loads of good programming quizzes and puzzle resources out there – and really having one more site which did the same thing was not going to help much!
Considering that there is a limitation to what one person could do – my plan is to gradually evolve Quiz4J into a community of people like us who enjoy programming puzzles. It’s not going to be something that happens overnight but something that I look forward to happening in the next 3-4 months. You’ll see some quick updates in the next few weeks on Quiz4J – getting rid of some stuff and addition of a lot more.

So what about twisters? Are we not going to have any more of these puzzles? Yes – sure I am going to continue posting puzzles on Twisters. I planning to cut a few overheads – score cards, answer post are few of the things you would see going off. The comment system would be used more as a discussion tool than just posting answers. Puzzles might get a bit more difficult – and you might see me pointing a to existing discussion that writing my own puzzles.

Well so what do you folks think? I really really interested in hearing from you!!!

Monday, November 16, 2009

Puzzle 58 – Solution

There are a couple of solutions possible for this puzzle – I’ll leave figuring out how these solutions work to you!

The first one,

package com.twister;

import java.util.ArrayList;
import java.util.List;

public class Gener {
public void read(List<?> x){}

public static void main(String[] args) {
new Gener().read(new ArrayList<Float>());
}
}


and the second,

package com.twister;

import java.util.ArrayList;
import java.util.List;

public class Gener {
public <Integer>void read(List<Integer> x){}

public static void main(String[] args) {
new Gener().read(new ArrayList<Float>());
}
}

Sunday, November 8, 2009

Puzzle 58 – Simple Upgrade.

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

Here is the puzzle straight and simple. A piece of code was written which had a read() method with the signature below. Thing change and instead of using integers – it was now required to use Floats instead of Integers.

To cut a long story short what is the minimum change considering additions/deletions (each char added or deleted count as 1) to get the code below to compile. (I think it can be done in less than 10 characters)

package com.twister;

import java.util.ArrayList;
import java.util.List;

public class Gener {
public void read(List<Integer> x){}

public static void main(String[] args) {
new Gener().read(new ArrayList<Float>());
}
}


Got an answer? Leave one here

Puzzle 57 – Solution

Here is the first solution that works for last weeks puzzle,

class X{
public static void main(String[] a){
System.out.print(a[
0]);
}
}

Run the program as given below
java X
"Hello World"


The second one – (the one that I had in mind) is

class X {
static {
System.out.print(
"Hello World");
System.exit(
0);
}
}

Sunday, November 1, 2009

Puzzle 57 – Hello World - Again

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

It's been two weeks since I wrote a puzzle out here – so I end up typing the simplest program I could think of in Java.

class X{
public static void main(String[] a){
System.out.print(
"Hello World");
}
}

That's the smallest program that I could in java that prints hello world (72 characters excluding all the white spaces). Hope you folks noticed the clever use of variable names and print instead of println.

Well here is the really simple challenge. Write some code that does exactly what the above code does – just use less number of characters. Remember the code has got to compile cleanly and run cleanly and produce the same output as the snippet above. Easy!

Looking for more Java Puzzles? Check out these sites.

Got an answer? Leave one here.

Sunday, October 25, 2009

Puzzles, Puzzles and more Puzzles.

The past couple of months I have been pretty much fascinated with programming puzzles. I have been on a lookout for really good puzzle sites - and participating in competitions whenever I get the chance.

It all started a couple of months back when I first heard of Google Code Jam. The idea really fascinated me and since then I been solving lots of puzzles around the net (with some attempts to write my own). Currently you find me on Al Zimmermann's Programming Contests playing around with the darts.

I have also been busy compiling of all puzzle/programming sites on the web - you can have a look at it here - http://www.quiz4j.com/contest.do. I am still working on the page and it might be a couple of weeks before my list is finally complete (if ever) - but it’s pretty huge already. Do have a look - I'm sure you will find something you like. If like what you see please share the link around!!!

There are no puzzles this week on twister - I'll be back with the regular java questions (and maybe a couple of tricky ones!!!) from next week.

Sunday, October 18, 2009

Puzzle 56 – Cube Traversal

Language – Java | Type – Concept | Last date 25-Oct-2009 12:00 p.m. IST | Points 5

We been dealing with Java concepts lately and its time to give concepts a break and get to some real world puzzles. Here is a small programming puzzle to get things started. Do let me know what you think of this question so I could think about adding more questions like these.





Submitting java code on scarky has few rules that need to be followed.
1. You can just have one class and it must be named Main. It should not be inside any package.
2. You need to read all input before you can start writing any output. (Use System.out.print() & System.out.println() for output)
3. For the exact format of input and output refer to the example test case.

You can find a standard template to read the input data here.

Your solution would be evaluated automatically by scarky.
In case of any issues you could reach me at admin@quiz4j.com

Puzzle 55 – Solution

The solution to last time puzzle was to use an instance initializer. An instance initalizer is a piece of code similar to a static block that gets called whenever an instance is created (the compiler inlines this code at the beginning of each constructor).

package com.twisters;
public class NoConstructor {

boolean isConstructor = false; //No changes permitted to this line
{isConstructor = true;}

/* No Code may be added or changed in main*/
public static void main(String[] args) {
NoConstructor noConstructor
= new NoConstructor();
System.out.println(noConstructor.isConstructor);
//Prints true
}
}

Monday, October 12, 2009

Puzzle 55 – The No constructor dilemma.

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

This week’s puzzle is pretty simple and the question self explanatory (I hope).

package com.twisters;
public class NoConstructor {

boolean isConstructor = false; //No changes permitted to this line

/* No Code may be added or changed in main*/
public static void main(String[] args) {
NoConstructor noConstructor
= new NoConstructor();
System.out.println(noConstructor.isConstructor);
//Prints true
}
}

The NoConstructor class must not have any explicit constructor (that is - don’t use the word NoConstructor any more times in your solution). That's all - everything else about the puzzle should be self explanatory from the comments!

Got an answer? Leave one here

Puzzle 54 – Solution

The principle that I wanted to bring out in this puzzle was that we can break out of any labeled block by using a break statement.

package com.twister;
public class NoIf {

public static void main(String[] args) {
if(true){}
System.out.println(
"Print This");
noPrint:{
if(true){break noPrint;}
System.out.println(
"Print This - Not!");
}
if(true){}
System.out.println(
"Print This");
}
}

The other popular solution was to wrap the code in a try-catch-finally block. As the catch block will not execute without any exception – the second print statement is skipped.

My favorite solution for this puzzle is the one by vector9x,
System.out.println("Print This - Not!".substring(0,10));

Scores to be updated next week!!

Sunday, October 4, 2009

Puzzle 54 – No More If’s

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

Today’s unearthly puzzle finds its roots in code written by a Jalvanian master. The question in today’s puzzle should be self explanatory.

package com.twister;
public class NoIf {

public static void main(String[] args) {
if(true){}
System.out.println(
"Print This");
if(true){}
System.out.println(
"Print This - Not!");
if(true){}
System.out.println(
"Print This");
}
}


It’s kind of pretty obvious what needs to be done – the code says it all.

You must of course follow the Three Jalvanian Laws.

1. You may only add but not delete nor comment out any of the code.

2. A real Jalvanian would never use an else so neither must you.

3. You may not use any more boolean variables (there are three in the code – which must remain unaltered) or conditions that evaluate to a boolean value. (So no true==false – since false is a boolean value etc).

That’s all folks!!

Got an answer? Do leave it here.

Sunday, September 27, 2009

Out on Vacation!

I am on a vacation this week – so no new puzzle this week.

However for those looking for a Java puzzle to think over this post should be interesting - http://www.javaspecialists.eu/archive/Issue173.html

Puzzle 53 – Solution

The problem that occurred was that even though the Constants class was recompiled the MyData class still continues to retain the old value of the constant Author. This happens because static final fields are in-lined into the code.

As c0dep0et points out in his comment,
"From JLS:
Simple names that refer to final variables whose initializers are constant expressions qualify to be compile-time constants."

One way to resolve this problem would be to make sure that all files depended on the Constants file are recompiled when the Constants file is recompiled. (Alternately not declaring the field as final would work!).

Modern IDE are more intelligent and usually recompile depended class when a final static field is changed in a class!

Sunday, September 20, 2009

Twister updates.

There have been a few suggestions and questions that have been asked and since a lot of new folks have joined Twisters its time for a few updates.

1. @Anonymous – Appreciate your comment on 'code not showing up right in feed readers.' I think I have got that fixed and things should look right from now on (at least that’s what I hope)!

2. @tonthatduy – There is a score sheet that I update after every puzzle (it's the last link in the Top Score widget).
If your solution is deemed right – you get points for that puzzle.
If your solution is wrong – well it should be marked up as a 0 (or sometime when I am just feeling lazy – I just leave it blank!)

To answer your question in particular, your solution for puzzle 51 was not quite right. It broke one of the rules – "no deletes, no moving about the code,
no commenting out …" Putting two slashes // ended up commenting out some of the code!

3. I have made a small change to the way the sharing icons works (if you have not noticed they are the cute icons that you can see at the bottom of each post). Clicking on the link would no longer bookmark/submit the individual post but rather submits the Twisters site. Considering that a post on usually Twisters expire in a week – sharing an individual post does not make much sense.

4. For those who like solving puzzles there is
JFactor - Java Treasure Hunt that I had designed a few moths ago, that you could try out. Hope you find the Treasure Hunt fun and challenging!!

Finally, I would like to thank all you folks for your support and encouragement in keeping Twisters going!!!

Puzzle 53 – Statically Speaking.

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

This puzzle is interesting because it's based on a real life incident that happened with a colleague of mine. To give you a gist of what happened, here is the code (well this isn't the real code – just the important part)

package com.twister;
class MyData{
String author
= com.twister.Constants.AUTHOR;
//lot of other stuff comes here…

public static void main(String[] args) {
MyData mydata
= new MyData();
System.out.println(mydata.author);
}
}

package com.twister;
class Constants{
public static final String AUTHOR = "SAM"; //Me of course

}

Here is what happened. This was some code that I had written – see my name in the Constants file. Well my colleague picked up my code and just modified the String Author to his, recompiled the Constants file and went on to show a demo to the manager. Ops something went wrong here, which got him into a lot of trouble. Can you figure out what went wrong? (Assume he codes using Notepad). What are the possible solutions to this problem?

Got an answer? Do leave it here.

Puzzle 52 – Solution

The answer to last weeks puzzle is 0. That’s right the minimum code change needed to get the code to print true is 0!!

Surprised – well let’s have a look at what the Java Docs have to say for the getBoolean() method -

"Returns true if and only if the system property named by the argument exists and is equal to the string true …" (read more).

To get the code to print true, we just need to run the program with the right command line arguments, namely,

java -Dfalse=true com.twister.MyTruth

You would find a good discussion on this topic here.

@Sebastian & Mohamed El-Beltagy – Good catch folks!!!

Sunday, September 13, 2009

Puzzle 52 – "Satyameva Jayate" : Truth shall always prevail.

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

What is the minimum change (additions only – no deleting or commenting out code) that you need to make to the code so that the program prints true?

This should be easy – but it does highlight another peculiarity to look out for.

package com.twister; public class MyTruth { public static void main(String[] args) { boolean b = Boolean.getBoolean("false"); System.out.println(b); //This should print true } }

Got an answer? Do leave it
here.

Puzzle 51 – Solution

This puzzle brought in a variety of solutions and as usual all solutions that meet the conditions of the puzzle would be considered correct.

The solution I had in mind is,

package com.twister; public class Area { //should initialize to 0 - formula mentioned for documentation int area = this.length*this.breath; //Instance variables get initialized to 0 int length = 10; int breath = 20; public static void main(String[] args) { Area a = new Area(); //Do whatever needs to be done in main } }

I find this solution pretty suitable for this problem for a couple of reasons:

1. It does not destroy the essence of the code – the
variable area remains part of the class Area which makes the code look logical. The other solution that does the same is making area a method.

2. It goes with the comment of keeping the code self documenting which getting the code to compile.

Of course some of the other solutions are pretty neat too – It's just that I am a little biased towards this one!!

@Matthieu – I missed giving you points for your solution last time – thats corrected now.

@Simonz – You solution (for puzzle 50) is correct too – It satisfies all the rules of puzzle 50.

@Yauheni – Welcome back - : ) – I wish I get my next vacation soon!

Sunday, September 6, 2009

Puzzle 51 – This and That!

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

Improving upon last week’s code, I came up with this:

package com.twister; public class Area { //should initialize to 0 - formula mentioned for documentation int area = length*width; //Instance variables get initialized to 0 int length; int width; public static void main(String[] args) { Area a = new Area(); //Do whatever needs to be done in main } }


Now while this is much better than the previous code (no hard coded values, self documenting), I seem to be having a problem with the code. As you might have already guessed this code does not compile!!!

Your challenge is pretty simple – get this code to compile by adding minimum number of characters to this code. Also a few additional conditions that you need to meet are -

a. You may only add code to get this to work – no deletes, no moving about the code, no commenting out any code! Additions only!

b. Obviously as before, declaring length and width as static would do the trick – but then that is so obvious that it can’t be the right solution, can it?
(So I am looking for something that solves the problem in less than 12 characters).

Got an answer? Do leave it here.

Puzzle 50 – Solution


Declaring the variable breadth as a
static variable solves the problem of forward reference in the puzzle. Static code is referenced and initialized before any instance code – and so the forward reference problem of the breadth variable gets solved.

package com.twister;

public class Area {

int length = 10;
int area = length*breadth;
static int breadth = 20;

public static void main(String[] args) {
Area a
= new Area();
System.out.println(a.area);
}
}

A neat trick pointed out by TheMalkolm solves the problem using just 5 characters!

Sunday, August 30, 2009

Puzzle 50 – Before & After

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

Do you remember the first time you wrote some java code and were stuck on a really silly thing for hours? Well this puzzle is right up that alley,

package com.twister; public class Area { int length = 10; int area = length*breath; int breath = 20; public static void main(String[] args) { Area a = new Area(); System.out.println(a.area); } }

Apart for being a really silly piece of code with all values ‘hard coded’ – as you might have already guessed this code fails to compile.
The puzzle - what is the minimum code addition (no deletes, no moving the code – plain addition only) that is needed to make this code compile and run to give the expected output – 200?

Got an answer? Do leave it here.

Puzzle 49 – Solution

With 49 (coincidence?) comments posted for the last puzzle – this was the most solved puzzle till date. There were a range of solutions and I have listed out the common solution below,

Solution 1- Use a Finalizer.

The simplest solution that one could use for this problem is to add a finalizer in the code that restores the looper object.

package com.twister; public class StopTheLoop { static StopTheLoop looper; public static void main(String[] args) { looper = new StopTheLoop(); looper = null; do{ System.out.println("Infinite Loop");; }while(looper==null); } @Override protected void finalize() throws Throwable { looper = this; } }

The hint to use this solution came from the fact the line -- first created a new Object and then the reference was set to null – which meant that when the garbage collector runs you had a chance to restore the object.

Solution 2 – Override the System.out with a custom object that exits, after doing a single print.

package com.twister; import java.io.PrintStream; public class StopTheLoop { static StopTheLoop looper; public StopTheLoop() { PrintStream ps = new PrintStream(System.out){ @Override public void println(String x) { super.println(x); System.exit(0); } }; System.setOut(ps); } public static void main(String[] args) { looper = new StopTheLoop(); looper = null; do{ System.out.println("Infinite Loop");; }while(looper==null); } }

Solution 3 – Creating a thread that exits or restores looper after some time or by checking if the looper reference is null and creating a new object.

package com.twister; public class StopTheLoop extends Thread { static StopTheLoop looper; static { new StopTheLoop().start(); } public static void main(String[] args) { looper = new StopTheLoop(); looper = null; do { System.out.println("Infinite Loop"); } while (looper == null); } @Override public void run() { Thread.yield(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.exit(0); } }

I think this about covers all the solutions for this puzzle.

Sunday, August 23, 2009

Puzzle 49 – Stop me if you can ...

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

After a long week here is the next puzzle,

package com.twister;
public class StopTheLoop {
static StopTheLoop looper;

public static void main(String[] args) {
looper
= new StopTheLoop();
looper
= null;
do{
System.out.println(
"Infinite Loop");;
}
while(looper==null);
}
}

This program keeps printing the string "Infinite Loop" an infinite number of times. Without making any changes to the main method (no additions, deletions, modifications, redefining main) - convert this program so that the loop runs a finite number of times.
Note : the loop must run at least one time.

Got an answer? Do leave it here.