Wednesday, July 29, 2009

Puzzle 46 - Just a Sort.

Language – Java Type – Concept Last date 2-Aug-2009 9:00 p.m. IST Points 5

Its been a long time since we had a programming question out here. So here is one where you get to punch in some real code.

Print the maximum number of a list of ten inputted numbers.

Easy? Well here are some clauses that should make this harder.
1. No classes may be used except java.lang.Object. So no collection frameworks, none of the inbuilt stuff to sort the numbers :).
2. No arrays may be used in the entire code.
3. Should compile and run with Java 1.4

Here is what the pseudo code for the program should look like;

int num1 = [scan the number at runntime]
.
.
.
int num9 = [scan the number at runntime]
int num10 = [scan the number at runntime]

printMax(num1,num2,num3,....num10)

If you find yourself more than 20 to 25 lines of code ... think again!!

Got a solution. Do leave it here.

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 45 – Equally Unequal - II

Language – Java | Type – Concept | Last date 29-Jul-2009 9:00 p.m. IST | Points 2 + Bonus

The last puzzle seems to have got a lot of flake for being simple – It also got the maximum participation – so it looks like you folks like simplicity but don’t like simplicity :)

So I decided to try something different this week! There are lots of new folks who have joined in and I would like, you to climb the point ladder quickly – here is the perfect opportunity!

package com.twisters;
public class Equal_Unequal {
public static void main(java.lang.String[] args) {
<someType1> x = <someValue1>;
<someType2> y = <someValue2>;
System.out.println(
"Values are equal : "+(x==y));
}
}

Steps that you need to follow:

1. Fill in a value for both the someType and someValue. They could be same or different.
2. You may not add any other code or delete any of the existing code.
3. Run the program. It should print Values are equal : true
4. Run the program. It should print Values are equal : false

P.S – As you can see you cannot compile again between the two runs – in case it wasn’t obvious enough.

Pretty simple up too now so here is the catch – For every different logical solution that you offer you get two bonus points. Now for a solution to be logically different it must satisfy two criteria.
a. sometype must be different from the other solutions.
b. It must exhibit a different Java principle (or different logical reason) from the other solutions that you have posted.
In case you are not sure if its logically different I would suggest to post the solution!

While it is not necessary to explain what you consider your solution as the guiding principle of your solution - it would be great if you do give a short explanation.

I can think of three – probably four different logical solutions to this puzzle (& frankly more than 20 if you remove the logical clause).

Looking for hints and more bonuses? You might want to watch out for an additional clause on twitter.

As usual looking forward to your solutions!!

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 44 – The One!

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

From where I come from everything is driven by statistic. Its no wonder that I am so much attached to number & tracking. I track the number of visitors on the blog - Google Analytics, Feed Subscribers, Twitter followers even my donate widget is one which shows how much progress I have made - at 0 right now :(!!
I sure would love any help to improve on any of these numbers ;)

The number that's pretty interesting though is the question rating. Its a pointer to the type of questions that you folks find interesting. I try to align questions to what you folks are looking for - in terms of type and difficulty though not always immediately.

Breaking out from my rant and getting to the puzzle at hand -

Have you ever had to code to silly standards. Well here is a typical construct!

package com.twisters;
public class ExtraLoad{
public static void main(String[] args) {
ExtraLoad ex
= new ExtraLoad();
ExtraLoad ex1
= new ExtraLoad("Hello");
ExtraLoad ex2
= new ExtraLoad("Hello", "World");
ExtraLoad ex3
= new ExtraLoad("Hello", "World", "Wide Web");
}
}


Get this code to compile – don't comment or delete any code.

Standard says -
You may not have more than one constructor in the code - Silly isn't it!

Sure you could rename the method to Extraload1(String), ExtraLoad2(String,String) but that would not be an interesting solution, would it? So here another clause - No changes to any part of main() method.

As usual looking forward to your solutions!!

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 43 – Run a Thread.

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

Contrary to what the title says – this puzzle is about stopping a rouge thread form running.
The challenge is pretty simple – all you need to do is stop the code from printing “STOP ME IF YOU CAN”

package com.twisters;
class MultiThreader implements Runnable{
public void run(){
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();
}
}

Rules:
No code may be deleted or commented – but you folks already know this!
No changes to or in the main method at all.
No code may be added to the body of the run() method!

One way to solve this is to rename the run() method to _run() and write an empty run() method. This needs a minimum 20 characters including the necessary white space. You may use a maximum of 18 characters including any white spaces. (Growing pretty obsessive with this 18 character limit – ain’t I)

Pretty simple puzzle to be honest!!

Got an answer? Leave your answer here.


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 42 - Equally Unequal.

Language - Java | Type - Concept | Last date 19-Jul-2009 12:00 p.m. IST | Points 3

This might be old puzzle, someone asked this question on Java Ranch. I think it's a pretty neat & tough puzzle why don't you folks give it a try!

class Equals {

public static void main(String args[]){

<sometype> x = <somevalue>;

System.out.println(x
== x) //This should print false

}

}


Replace the placeholders <sometype> and <somevalue> with any construct or value so that the System.out.println() prints out a false. No other changes/additions/deletions are permitted.

Looking for a hint? I think one might just show up on twitter soon.

Got an answer? Leave your answer here.

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 41 – Hello World

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

Lately I have been reading up on groovy and the hello world program in groovy is just so groovy!

println ‘Hello World’

This brings me to the next questions!

Write a program that prints Hello World in Java. No Semicolons anywhere in the code. No, not even one!! Not even using a alternate notation like unicode!!

P.S – I know Groovy can be run as a Java program – but here I mean Java code, that compiles using the javac compiler!!

Got an answer? Do leave it here.

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 40 - Divide and optimize (Optimization Series puzzle - 3)

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

If you have not looked at code optimization puzzle before - I would suggest having a look at the first one!

It's surprising how badly a program can start performing if you carelessly use nested loops. Well the code takes around 100 seconds to run and that's just too much. I think about 10 seconds is the maximum the code for this question should run. Any takers?

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

for(int d=1;d<=20;d++){

if (!isDivisble(i, d)){ //Yikes my assumption was wrong!

va = false;

}

}

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=fdc2fad6-f541-4c8d-934d-3b838323a66b

Rules? Same as before -

1. This code takes about 100 seconds to run. Get it to run in under 10 seconds.

2. You see while it's really great that you have decided to help me - I really don't want you to mess up my entire code. So here is the deal - you can change a maximum of 18 characters (yes that's all).

3. What constitutes a character change?

a. Inserting a character - each character (including space) that you add to the existing code.

b. Deleting a character - each character (including space) that you delete from the existing code.

c. Over writing a character - well you cannot do that. You could delete and insert but you cannot over write.

d. Cut Paste - Special Rule for cut paste is you can cut code from the existing code and paste it somewhere (except inside a comment) else in the code without using up a single char.

Just remember its cut-paste and not copy-paste.

Got an answer? Do leave it here.
(Do use BlogTrog and post the link to your code here, in case you have a problem posting the code in the comments!!)

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 39 – Divide and Rule.

Language – Java | Type – Program | Last date 8-Jul-2009 9:00 p.m. IST | Points 5

Write a program to divide two floating point numbers - No using the '/' sign in the entire program – That's all folks.

I think I had a similar Puzzle before - maybe it might help - Puzzle 10 & its solution here - Puzzle 10 Solution

Got an answer? Leave it here.

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!

Wednesday, July 1, 2009

Puzzle 38 – The Answer to Life, the Universe and Everything

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

Everyone seems to have their own opinion on life. The correct answer as we all know (Check Puzzle 34 for Details) is 42 – so it looks like some one has made a typo in the code snippet below. Let’s correct this code shall we?

/* Code Snippet */
int theAnswer = 52;
System.out.println(
"The answer to life is " + theAnswer);

I was about to delete the 5 and replace it with a 4 when one of my friends (she’s imaginary, but that's beside the point) pointed out that it's pretty impolite to delete someone else's code. She also tells me that I should make minimum changes to get this code to work. So I am stuck trying to figure out what is the minimum number of characters I can add (no deletes allowed) to get this code to work.

Think you could help me with this? Leave an answer here.

Puzzle 37 – Solution

Thanks everyone for the Birthday wishes - it was great getting so many greetings!

The String class has an intern() method. The intern() method makes sure that if Strings are equal then it returns the same string. Read up on the intern() for more information.

package com.twisters;
class Stingify{
public static void main(String args[]){
String firstOne
= new String("Happy Birthday").intern();
String secondOne
= new String("Happy Birthday").intern();
/* No change to the line below! */
System.out.println(
"First String is equal to second : " + (firstOne == secondOne));
}
}

I did offer a bonus point for anyone who came up with more than one solution so for those of you did get in more than one solution the bonus point is on!

Sebastian came up with what I suspect is almost all possible solutions to this puzzles. I would check out his solutions - specially the one he marked out as favorite. Its my favorite too -:).