Comparing Software Version Numbers
by Peter.
Software version numbers tend to be in the format ‘Major.minor.point’, which makes sorting versions require a little bit of work. If we only had a single dot we could just convert them to numbers and use < and >. However, we often don’t and sometimes people put letters in their versions also, like ‘1.2.A’.
Here’s my solution, in Scala:
def compAsc(a: String, b: String): Boolean = { val separator = '.' val aSplit = List.fromString(a, separator) val bSplit = List.fromString(b, separator) def comp(a: List[String], b: List[String]): Boolean = { !a.isEmpty match { case true if !b.isEmpty => { if (a.head == b.head) { // if both equal, keep comparing comp(a.tail, b.tail) } else { a.head < b.head } } // if a has a value but b doesn't then a is larger case true if b.isEmpty => false // if a doesn't have a value but b does then b is larger case false if !b.isEmpty => true // in all other cases assume a is larger case _ => true } } comp(aSplit, bSplit) } def compDesc(a: String, b: String): Boolean = { val separator = '.' val aSplit = List.fromString(a, separator) val bSplit = List.fromString(b, separator) def comp(a: List[String], b: List[String]): Boolean = { !a.isEmpty match { case true if !b.isEmpty => { if (a.head == b.head) { // if both equal, keep comparing comp(a.tail, b.tail) } else { a.head > b.head } } // if a has a value but b doesn't then a is larger case true if b.isEmpty => true // if a doesn't have a value but b does then b is larger case false if !b.isEmpty => false // in all other cases assume a is larger case _ => false } } comp(aSplit, bSplit) } |
Some examples:
scala> val l = List("1.24", "3.2", "3.0", "3.0.1 beta") l: List[java.lang.String] = List(1.24, 3.2, 3.0, 3.0.1 beta) scala> l.sort(compAsc) res0: List[java.lang.String] = List(1.24, 3.0, 3.0.1 beta, 3.2) scala> l.sort(compDesc) res1: List[java.lang.String] = List(3.2, 3.0.1 beta, 3.0, 1.24) |
And why, do you ask, am I working with software version numbers? Let’s just say it has something to do with www.mobtest.com. More soon!