Nov 20, 2012

Can you write a program in Java? for beginner to intermediate level coding

Q. Can you write code to generate a 4 digit number, where the same number cannot be repeted? For example, 1234 is valid, but 1124 or 1214 are invalid because the value 1 is repeated.A. Firstly, write some pseudo code

1. Have an array or list of numbers - 0,1,2,3,4,5,6,7,8,9
2. Shuffle these numbers randomly in a list or array.
3. Pick the first 4 number from the list or array
4. concatenate these 4 randomly selected numbers and return them as a 4 digit result.

Q. What if you didn't have the shuffle method in the Collections class?A. Here is the pseudo code

1. Have an array - 0,1,2,3,4,5,6,7,8,9
2. Loop through these numbers 4 times and randomly pick an index.
3. Once a number from an index is used, set the number on that index to say -1 so that the same number cannot be picked again.
4. If the same index was randomly picked, try again.
5. concatenate these 4 randomly selected numbers and return them as a 4 digit result.

Q. Can you see any flaw(s) in the above code?A. Mathematically you can only generate 5040 numbers. This was calculated as described below:

1. There are 10 numbers from 0 to 9.2. You can't repeat the same number, so first digit can be chosen from 10 possible numbers, the second digit from 9 possible numbers, the third digit from 8 possible numbers, and the final and fourth digit from 7 possible numbers.3. Hence, the number of 4 digit number combinations you can have is -- 10 * 9 * 8 * 7 = 540.

Flaw 1:

So, if the GENERATION_COUNT is set to 5041, the while loop in the getUniquelyGeneratedNumbers(int size) method will never return false, and you will end up with an endless loop.

Flaw 2:

The above code generate a new thread for each execution. This can potentially create 5040 new threads, which can be expensive new real production code and also can adversely impact performance as the CPU spends more time in context switching. It is best to use the Java 5 executor framework that lets create a pool of thread and reuse them.