|
|
Re: What is the meaning of life?
|
Posted: Apr 9, 2012 9:49 AM
|
|
"No one managed to figure out what the code does without running it."
Challenge accepted (though I'm sure everyone has already done so by now, since it was December).
Nice puzzle! Took me about a minute. I believe it prints out 42.
Here is my analysis: Each of the four nested loops results in "meaning += Math.random() +1" being run 20*30*700*2000 times, or 420000000 times. So, "meaning" gets Math.random() + 1 added to it 420000000 times. Since Math.random() returns a double (or maybe it was a float) greater than or equal to 0, but less than 1, and since "meaning" is an integer, the Math.random() value gets dropped every time. As such, "meaning" has a final value of 420000000. The String.replaceAll() call reduces the string to 42.
This is a reference to Hitchhiker's Guide to the Galaxy; 42 is the answer to the ultimate question of life, the universe, and everything. The real question, though, is "what is the question?"
I almost missed realizing that the result of Math.random() gets dropped, and I must admit that I don't get why "*$" is in the replaceAll method replace string. I assume it to be a regular expression, which I am not familiar enough with.
I haven't run it yet, so if I'm wrong or have missed something, that'd explain why.
This reminds me of another problem I saw posted somewhere a long time ago, which was basically "Given the lowest common multiple of all integers between 1 and 10 (inclusive), write a piece of code that finds the lowest common multiple of all integers between 1 and 20 (inclusive)".
Fun times.
|
|