Next Version Dojo
March 10, 2016
In the Yammer Redmond office, we usually do a little coding Dojo on Wednesday after lunch. We pick a small problem and work on it (individually or in pairs) and then compare our solutions.
Yesterday the problem was called “Next Version”:
Create a function nextVersion, that will take a string in parameter, and will return a string containing the next version number.
nextVersion("1.2.3") === "1.2.4"; nextVersion("0.9.9") === "1.0.0."; nextVersion("1") === "2"; nextVersion("220.127.116.11.18.104.22.168") === "22.214.171.124.126.96.36.199"; nextVersion("9.9") === "10.0";
All numbers, except the first one, must not be greater than 9: if there are, you have to set them to 0 and increment the next number in sequence.
So I used me some Ruby.
The first version was a naive implementation:
- Remove the dots from the string.
- Store the length, to check later if we’ve gone from, say 99 to 100
- Add one to the version
- If our string hasn’t gotten any longer, just split it into individual characteres (numbers) and join with dots (“.”)
- If it has grown, take the first two digits as the major version number, and dot-separate the rest.
Now, this has some gaping holes, but all the examples given above will pass. However, if you have a number that starts with a “0” and should still have a “0” after incrementing, say, “0.8.9” => “0.9.0”, it will fail. When you change the string “089” to an integer, it will become
89, and when you add one you’ll get 90 => “90”. Since the length changed (“089” is 3 characters, “90” is two), the above algorithm will return the next version as “90”. “0.8.9” to “90”. Not the jump we wanted.
We can fix this by checking if we started with zero:
The same algorithm, except we check if our version begins with zero, and at the end, if it should still have a zero at the front we prepend it to the string.
This still has a problem, though. If we want to go from version “10.9” to “11.0”, it will fail; since the lengths of the strings don’t change, it will return “1.1.0”. Ooops.
There are ways you could take the same algorithm I started with and make it work. Instead, I decided to change tactics. The 3rd algorithm:
- Splits the version string into a array of integers and reverses it.
- Adds 1 to the first element in the array.
- For each element except the last, if it is greater than 9, add 1 to the next number in the list.
- Reverse the array and join into a dot-separated string again.
Full file with tests is here