Skip to content

Instantly share code, notes, and snippets.

@luiscoms
Last active December 14, 2016 20:40
Show Gist options
  • Save luiscoms/fedc26466503e6b563e73ae425a51461 to your computer and use it in GitHub Desktop.
Save luiscoms/fedc26466503e6b563e73ae425a51461 to your computer and use it in GitHub Desktop.
Compare versions
class SemVer {
public int compareVersion(String v1, String v2) {
String[] v1Parts = v1.split("\\.");
String[] v2Parts = v2.split("\\.");
int length = Math.max(v1Parts.length, v2Parts.length);
for (int i=0; i<length ;i++) {
int numV1 = (i < v1Parts.length)? Integer.parseInt(v1Parts[i]) : 0;
int numV2 = (i < v2Parts.length)? Integer.parseInt(v2Parts[i]) : 0;
if (numV1 != numV2)
return (int) Math.signum(numV1 - numV2);
}
return 0;
}
}
public class Application {
public static void main(String []args) {
System.out.println(new SemVer().compareVersion("1.2.1", "1.2.1"));
System.out.println(new SemVer().compareVersion("1.2.2", "1.2.1"));
System.out.println(new SemVer().compareVersion("1.2.0", "1.2.1"));
}
}
import UIKit
class SemVer {
func compareVersion(v1:String, v2:String) -> Int {
// if v1 is equal v2 then return 0
// if v1 is greater than v2 then return 1
// if v1 is lower than v2 then return -1
return v1.compare(v2, options: NSString.CompareOptions.numeric).rawValue
}
}
print(SemVer().compareVersion(v1: "1.2.1",v2: "1.2.1"))
print(SemVer().compareVersion(v1: "1.2.2",v2: "1.2.1"))
print(SemVer().compareVersion(v1: "1.2.0",v2: "1.2.1"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment