This article was originally posted on JRoller on December 23, 2011.
We have an application that monitors other applications, something like the Windows Task Manager. The developers in charge of this application were given the task to add an uptime column to the table. We advised them to use a tool from the Linux machine on which the application was running which gives back the uptime in seconds. All they had to do was format this information nicely and print it in the cell.
Before you utter the WTF words, let me explain how this works. In fact it is pretty simple.
First, we notice that there are altogether four possibilities, as you can see in the comments. So we make a nice hierarchy of the possibilities: if one uptime has only minutes while the other has not, then we know that the one that has only minutes is the smallest. Clever!
Repeat this thinking process with hours. Great!
Same number of days? We can check that if we have one uptime containing only minutes and the other one only hours, then we have a winner. Woohoo!
Still no decisions? It is time to use the hammer, the "compareStringWithNumber" method.
This method uses another helper method called "split". What it does is that it creates a list of all the numbers and other characters in the uptime String. So we use a regular expression to find all the numbers, and try to look for it again in the String (because those damn Scanners can not give us this information). This whole method is of course buggy, I let you find the cases when it does not work (hint: 11:11 hour will not for instance).
Now let's go back to the hammer. We have our two lists of numbers and things, with probably the same numbers of element (or not?). We check again that we are really dealing with numbers, because we should have the same format, but we are not sure. So just in case, we insert a String comparison. We might have days before minutes, but we should not. Or should we? No, I'm pretty confident all this works.
No comments:
Post a Comment