Wednesday, December 7, 2011

Javachats - My Personal Blog

Its been over a year since I wrote a blog post. I ran out of puzzles - after all how many quirks could a single language have ;)!

I started writing out a bit again - this time its a more personal blog. More about stuff I do, things day in and day out and the occasional general post. Of course since I work in and around Java most if it would be about Java!

Hoping to see some old friends again @ my new blog - http://javachats.blogspot.com/

Signing off - Sam!


Monday, August 2, 2010

Puzzle 64 - The Future is Secure

Java 1.5 adds a lot when it comes to threading. However thread programing is always a little tricky and Threading casually can lead to problems - With Great Power Come Great Responsibility. There is a Major bug (and a minor performance bug). Can you spot them both?

package com.test; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.ScheduledThreadPoolExecutor; public class MyObject { public static Executor ex = new ScheduledThreadPoolExecutor(100); public static void main(String[] args) throws InterruptedException, ExecutionException { Tracker t = new Tracker(); Future<Tracker> f[] = new Future[1000]; for(int i=0;i<1000;i++){ /*The code in MyFutureTask.call() would be executed sometime in the future*/ f[i] = new FutureTask<Tracker>(new MyFutureTask(t)); ex.execute((Runnable) f[i]); } /*Wait for all the future task to complete!*/ for(int i=0;i<1000;i++){ f[i].get(); } /*Print out the number of future task that we have completed*/ System.out.println(t.getValue()); /*This prints the number of task executed - 1000*/ } } class MyFutureTask implements Callable<Tracker>{ Tracker myTracker; MyFutureTask(Tracker t) { myTracker = t; } @Override public synchronized Tracker call() throws Exception { /*Some complex business logic inserted at this point*/ int rand = new Random().nextInt(1000); Thread.sleep(rand); myTracker.increment(); return myTracker; } } class Tracker{ Integer value = 0; public void increment() { value++; } public int getValue(){ return value; } }

Wednesday, July 28, 2010

Puzzle 63 - Out of the Box

Java 1.5 introduced Autoboxing and since then a lot of code has been indiscriminately been using Autoboxing. I've picked up a simple case this time around (in fact its based on Joshua Bloch's - Effective Java). We'll look at a more real world problem next week.

package com.test; import java.util.Comparator; public class Order { public static void main(String[] args) { Comparator<Integer> naturalOrder = new Comparator<Integer>(){ public int compare(Integer first, Integer second) { return first < second ? -1 :(first == second ? 0:1); } }; /*This one is obviously broken - outputs 1 instead of 0 - Why?*/ System.out.println(naturalOrder.compare(new Integer(42), new Integer(42))); /*This one works but is still broken - outputs 0 as expected! - Why is this broken?*/ System.out.println(naturalOrder.compare(42,42)); } }

Sunday, July 18, 2010

Puzzle 62 - WARNING - Is this the End?

The world is about to end, but maybe, just maybe there is some Hope. So it give it a spin and try it. After all the fate of Earth rests in your hands!
(The code is well commented, I think you'll find everything you need out there.)

package com.test; import java.util.ArrayList; import java.util.List; /*This class had been set to trigger on December 21, 2012. *Due to a programming this class will trigger off in the next 15 mins *of you reading it. *Yes its a know issue and we've sorry about it, but right now there are other major *issues to solve and this can wait for later! **/ public class DoomsDayEarth { /*No point in returning anything once the world has been destroyed!*/ public static void destroyWorld(List<EvilObject> evilObjects) { /*You do get a chance to save the world. Try it!*/ Hope.save(evilObjects); /*This code destroys the world and prints world destroyed. *Prevent that from happening and if possible get it to print world saved * */ for(Destroy d : evilObjects) { d.destroy(); } } public static void main(String[] args) { List<EvilObject> evil = new ArrayList<EvilObject>(); evil.add(new EvilObject()); DoomsDayEarth.destroyWorld(evil); } } /*This is the only class that you can modify. Whatever happens there is always Hope!*/ class Hope { /*Write some code here that will save the world. Remember you just have 15 mins *to save the world, before main starts up, so be quick. **/ public static void save(List<EvilObject> evilObjects) { } } interface Destroy{ void destroy(); } class EvilObject implements Destroy { public void destroy() { //This method has the power to destroy the world! //To prevent any possible misuse, the code has been censored //and is not published on twisters! System.out.println("The world is destroyed!"); } } class GoodObject implements Destroy { public void destroy() { //This method does nothing. Its sole purpose is to replicate the EvilObject //without doing any evil!! System.out.println("The world is saved!"); } }

Sunday, July 11, 2010

Puzzle 61 - Set for Optimization?

I'm back with an optimization question. Lately I've been dealing with some huge volume of data and I've realized how performance can start to be a serious problem as the data increases. Here is a small illustration with relatively less data (50,000 values). Hopefully the question should be self explanatory from the code.

package com.test; import java.util.List; import java.util.ArrayList; class MyCollection{ public static void populateList(List<Long> l, int multiple){ for(int i=0; i<50000; i++){ Long value = Long.valueOf(i*multiple); l.add(value); } } public static void main(String[] args) { List<Long> listOf2 = new ArrayList<Long>(); populateList(listOf2, 2); List<Long> listOf3 = new ArrayList<Long>(); populateList(listOf3, 3); long startTimestamp, endTimestamp; List<Long> commonA = null, commonB = null, commonC = null; //First Attempt - Runs in 60 seconds startTimestamp = System.currentTimeMillis(); commonA = new ArrayList<Long>(listOf2); commonA.retainAll(listOf3); endTimestamp = System.currentTimeMillis(); System.out.println("Execution Time : " + (endTimestamp-startTimestamp)/1000); //Second Attempt - Runs in 73 seconds - //There are fewer elements in commonB shouldn't this run faster? startTimestamp = System.currentTimeMillis(); commonB = new ArrayList<Long>(listOf3); commonB.retainAll(listOf2); endTimestamp = System.currentTimeMillis(); System.out.println("Execution Time : " + (endTimestamp-startTimestamp)/1000); System.out.println("Are Equal : " + (commonA.equals(commonB))); //Third Attempt - Runs in 2 seconds startTimestamp = System.currentTimeMillis(); /* This part has been intentionally left blank. * That is because I need to have a question for the puzzle, * and I felt like leaving out the Third part would be the right * thing do to. * I've done most of the hard work so this should be easy to fill. * Yes this must run 10 times faster than the solution I have provided * and should be done just as many lines (3 to 5 lines of code should be fine!). * Well I never said anything about life being fair, did I? * */ endTimestamp = System.currentTimeMillis(); System.out.println("Execution Time : " + (endTimestamp-startTimestamp)/1000); System.out.println("Are Equal : " + (commonA.equals(commonC))); } }


Just keep in mind that both the "Are Equal" print statements print true and that you don't use the reference commonA or commonB when writing the code for the third part. You are free to make any other changes (in the place where the comments are there).

Update - The commonA, commonB were incorrectly pointing to the objects listOf2/listof3. That has been corrected to create new Objects -- it now reads commonA = new ArrayList(listOf2); instead of commonA = listOf2;.
Thanks to Colin Hebert for pointing it out.

Puzzle 60 (Go Soft) - Solution

Last week we looked at soft-reference and the answer that naturally comes is what the Java Doc has to say about soft references "As long as the referent of a soft reference is strongly reachable, that is, is actually in use, the soft reference will not be cleared".
Looking at the code - we have strongly reachable reference to the MemoryIntensiveObject(), O and one would expect the soft reference to exists. However as Jeremy Manson points out in his blog, this might not necessarily be the case.

As mentioned before this question was based on the Jeremy Manson blog post.

Monday, July 5, 2010

Go Soft?

An interesting post that I read sometime ago rakes up this discussion. I'll add the reference to the original post next week.

To give a bit of background we first see what a SoftReference object is. SoftReference is an object which is cleared at the discretion of the garbage collector in response to memory demand. Soft references are most often used to implement memory-sensitive caches. An object that is reachable (only) from a SoftReference is eligible for Garbage collection. The java doc is pretty clear - I recommend reading it!

The problem is the pretty little three line code below,
Object someMethod() { Object o = new MemoryIntensiveObject(); SoftReference<MemoryIntensiveObject> ref = new SoftReference<MemoryIntensiveObject>(o); //Assume garbage collector at this point and needed to free up memory. return ref.get(); }


Is the soft reference bound to return the object that was originally pointed by o ?

Monday, June 28, 2010

More puzzles coming this way.

Its been over 6 months since I have posted here - mostly cause I ran out of stuff to post!! Well time to announce a come back. That's right folks next week (Sunday) onwards we'll start of with some POJP - thats Plain Old Java Puzzles!!

If anyone is wondering why today, do have a look at this one for a clue -- http://twisters.quiz4j.com/2009/06/puzzle-37-fun-with-strings-birthday.html

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!!