Showing posts with label Solution. Show all posts
Showing posts with label Solution. Show all posts

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 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, October 18, 2009

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 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, September 27, 2009

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

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 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 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 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 48 - Solution

The code snippet defines an Enum, a feature introduced in Java 1.5.

This code creates a type-safe enumeration with apples, oranges, and grapes as members and for each member a String value is stored (the color of the fruit).

You can read more about enums on http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html

Sunday, August 16, 2009

Puzzle 47 - Solution

There are different categories of solutions to this puzzle, with the most simplest placed first to the most difficult!

1. DataType1 - Datatype4 all have different values and we rely on autoboxing and numeric promotions to get the job done.

package com.twister;
public class Mystery {

public static boolean isEqual(Integer f1,Long f2){
return f1.equals(f2);
}

public static void main(String[] args) {
int f1 = 1;
long f2 = 1;

System.out.println(
"f1 is equals to f2 : "+ (f1==f2));//prints true
System.out.println("f1 is equals to

f2 :
"+ isEqual(f1,f2));//prints false
}

}


2. DataType1 - Datatype2 are same and Datatype3 - Datatype4 are the same. Relies on autoboxing and the fact that the equals method of Float treats +0 as not equal to -0.

package com.twister;
public class Mystery {

public static boolean isEqual(Float f1, Float f2){
return f1.equals(f2);
}

public static void main(String[] args) {
float f1 = +0.0f;
float f2 = -0.0f;

System.out.println(
"f1 is equals to f2 : "+ (f1==f2));//prints true
System.out.println("f1 is equals to

f2 :
"+ isEqual(f1,f2));//prints false
}

}


3. DataType1 - Datatype4 are all the same.

package com.twister;
public class Mystery {

public static boolean isEqual(Object f1, Object f2){
return f1.equals(f2);
}

public static void main(String[] args) {
Object f1
= new Object()
{
@Override
public boolean equals(Object obj) {
return false;
}
};
Object f2
= f1;

System.out.println(
"f1 is equals to f2 : "+ (f1==f2));//prints true
System.out.println("f1 is equals to

f2 :
"+ isEqual(f1,f2));//prints false
}
}

Sunday, August 2, 2009

Puzzle 46 - Solution

The puzzle that I had posted (print just the max) is actually a toned down version of the much harder - print out the 10 numbers in ascending order (hence the title Just a sort). You might want to give that a try at your own leisure (and remember writing more than 25 lines of code is still a strict no-no!!)

Here is a solution that I picked up from TheMalkolm which covers the essence of how this could be done!

private static int max(int x, int y){
return x > y ? x : y;
}

private static printMax(num0, num1..., num9){
return max(num0,max(num1,max(num2,max(num3,max(num4,max(num5,max(num6,max(num7,max(num8,num9)))))))));

@Nash - You took me way too literally. When I said no other classes - I really meant no other classes to be used to sort out the numbers. Sorry for the confusion - I need to be more specific with the words I use. Using native code was a really novel idea!

Wednesday, July 29, 2009

Puzzle 45 - Solution

There are many solutions to the puzzle and I've have tried to broadly classify the solution into variuos groups.
These don't necessary cover all the solution...

1. Run the program by passing two arguments to it.
First time both the arguments are same, the next time both the arguments are different
someType1 & someType2 = int
someValue1 = Integer.parseInt(args[0]);
someValue2 = Integer.parseInt(args[1]);
First Run: java com.twisters Equal_Unequal 1 1

Second Run: java com.twisters Equal_Unequal 1 2

2. Run the program by passing just one parameter.
Depending on a java principal get the program to print true and false.


a. Use the caching property of the wrapper classes for values below 127.
someType1 & someType2 = Float
someValue1 = Float.parseFloat(args[0]);
someValue2 = Float.parseFloat(args[0]);

First Run: java com.twisters Equal_Unequal 1
Second Run: java com.twisters Equal_Unequal 1024

b. Use the NAN property of floats
someType1 & someType2 = float
someValue1 = Float.parseFloat(args[0])/Float.parseFloat(args[0]);
someValue2 = someValue1;

First Run: java com.twisters Equal_Unequal 1.0
Second Run: java com.twisters Equal_Unequal 0.0

3. Change an External condition.
a. Create or delete a file on the file system
someType1 & someType2 = boolean
someValue1 = isFileExists(c:\test1.txt)
someValue2 = isFileExists(c:\test2.txt)

First Run: java com.twisters Equal_Unequal /*Create both the files so someValue1 & someValue2 are both true*/
Second Run: java com.twisters Equal_Unequal /*Create just one files so only one of someValue1 or someValue2 is true*/

b. Change an environment variable

c. change the time of the machine.

4. Use a Random generator in the code.
There are many ways to generate random results. Though technically not absolutely accurate - one of the runs in bound to generate a true first and a false the second time.

5. Byte code manipulation.
You can't recompile the code but you can always go ahead and change the byte code ;)

This should cover up most of the solutions - though I would suggest having a look at the comments for a real wide varity of solutions.
I would post the scores for this question as a separate post this weekend - watch out for it!!

Sunday, July 26, 2009

Puzzle 44 – Solution

The point to note here was that the argument type was same for all the constructor calls – namely String. Java 1.5 adds the variable arguments language feature makes it possible to call a method with a variable number of arguments. More information can be got at http://today.java.net/pub/a/today/2004/04/19/varargs.html

Declaring the constructor as ExtraLoad(String... s){} takes care that all the constructor have a definition!!

Wednesday, July 22, 2009

Puzzle 43 – Solution

The way to stop the code from printing STOP ME IF YOU CAN is to rename the run() method. Since MultiThreader implements Runnable the run method is required. A default implementation of the run method can be obtained by extending the Thread class.

package com.twisters;
class MultiThreader extends thread implements Runnable{ /*15 additional char */

public void _run(){ /*1 additional character */
System.out.println(
"STOP ME IF YOU CAN");
}

public static void main(String[] args) {
MultiThreader m
= new MultiThreader();
Thread t
= new Thread(m);
t.start();
}
}


The other way to prevent the code from running the main method itself is to throw an exception in a initializer which would do the trick too!!

My solution pick of the week - Vishwanath's Solution - I just love out of the Box Solutions!

Scores for this puzzle will be updated next week!!!

Sunday, July 19, 2009

Puzzle 42 – Solution.

Nan is a special number having a unique property that one Nan is not equal to another Nan. In java a floating point variable can be assigned Nan as a value.

So, someType = float & someValue = Float.Nan or 0.0f/0.0f, gives you the desired result!

class Equals {
public static void main(String args[]){
float x = Float.NaN;
System.out.println(x
== x) //This prints false!!
}
}

Wednesday, July 15, 2009

Puzzle 41 - Solution

TheMalkolm hits the nail on the head with his comment--> "Main idea to place output statement to if (or while) clause."

Also since System.out.println does not return any value (return type is void) it cannot be placed in the if clause, we need to use an alternate method of the System.out like printf().

package com.twister;
class GroovyStyle{/*class name inspired by Yauheni*/
public static void main(java.lang.String[] args){

if(null==System.out.printf("Hello world",(Object[])null)){}
}
}

@Sebastian- Seems that there is a problem with word verification on Firefox 3.5. Hopefully someone at Google fixes it soon. I have currently disabled the word verification process - that should makes things easier for you folks. Now I just need to keep my fingers crossed that I don't end up with spam comments :)!

Sunday, July 12, 2009

Puzzle 40 – Solution.

I like these optimization puzzles since it brings a variety of solutions and just shows how small changes to the algorithm could make a huge impact.

Here is the optimization that I had in mind. It makes the code run in less than 5 seconds on my machine. Throw in a couple of more optimizations like incrementing by 20 instead of 1 (see comments here) brings down the execution time to less than half a second!!

package com.sam.twisters.euler;
/* Problem 5 : Euler
* 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
* What is the smallest number that is evenly divisible (divisible without reminder) by all of the numbers from 1 to 20?
*/

public class prog5 {
/*Simple function to check if the divisor completely divides the divident*/
public static boolean isDivisble(int divident, int divisor) {
if(divident%divisor == 0){
return true;
}
else{
return false;
}
}

public static void main(String[] args)
{
long startTime = System.nanoTime();
boolean va = true;

/* Start looping though all the numbers and see if we can find one divisible by all numbers
* from 1 to 20.
*/
int i = 1;
do{
va
= true; //Assume that i is a valid answer to the puzzle
//Optimization -->for(int d=1;d<=20;d++){
/*
(1 char, start from 11 and not 1).
This works since atleast one of the numbers from 11 to 20 has each of the numbers 1-10 as a factor,
so for example when we test if a number is divisble by 12 - we also indirectly test that the
number is divisible by 2,3,4 and 6
*/
for(int d=11;d<=20;d++){
if (!isDivisble(i, d)){ //Yikes my assumption was wrong!
va = false;
//Optimization -->break; (6 char)
break;
}
}
i
++;
}
while(!va);
System.out.println(i);
long estimatedTime = System.nanoTime() - startTime;
System.out.println((
float)estimatedTime/1000000000);
}
}

http://www.blogtrog.com/code.aspx?id=7617cc6e-c724-4122-b5c5-bf6eb703a700

Best solutions for the week?

@TheMalkolm - I'll pick TheMalkolm solution - its a pretty good optimization to the existing code.

@Sebastian - Yep your second solution is pretty neat (took some time figuring out how it works!!) though as you pointed out it uses a completely different algorithm. Neat nonetheless!!

Wednesday, July 8, 2009

Puzzle 39 - Solution.

There are really many ways in which one could solve this puzzle. I'll just point out a couple. The trick was generating an inverse of the number.

a. float result = Math.exp(Math.log(a) - Math.log(b))
b. float result = a * Math.pow(b, -1)

There were two bonus points on offer for getting a solution without using any class additional class except java.lang.Object. Lots of folks came up with the solution which was basically using an alternate notation for the '/' sign.

return a \u002F b;

Sunday, July 5, 2009

Puzzle 38 – Solution.

The keystroke that does the trick for me is '0'. Yep adding a 0 to 52 changes it to 42.

int theAnswer = 052;

If you still wondering what has changed, it's that adding a leading 0 to a literal number means that the number is considered as an octal number. Doing a quick math would reveal that octal(52) = decimal (42).

This is also a pitfall – one should be careful of not adding any leading 0 in Java!

@SlimMo - Pretty neat thinking! That was indeed a unique solution - my favorite one for this puzzle!