Compare two software version numbers

Get help with using AutoHotkey and its commands and hotkeys
User avatar
jNizM
Posts: 2614
Joined: 30 Sep 2013, 01:33
GitHub: jNizM
Contact:

Compare two software version numbers

29 May 2020, 06:48

What do you think about an efficient and clean way to compare 2 different version numbers
Or does someone have another suggestion?

What we got:

Code: Select all

version1 := "13.15.16654.0"
version2 := "14.1.16654"		; 2nd one is newer

version3 := "13.9.16654"		; first one is newer
version4 := "13.08.16644.99"

version5 := "13.15.16654.0"		; both are the same
version6 := "13.15.16654.0"		; both are the same
Possible solution:

Code: Select all

; split first version in an array of subversions
array1  := StrSplit(version1, ".")
; split second version in an array of subversions
array2  := StrSplit(version2, ".")
; get the version with the most subversions
length  := array1.Length() > array2.Length() ? array1.Length() : array2.Length()

; loop throw all subversions
loop % length
{
	; if the subversion of the first version is bigger than the second one (from left to right); -> break the loop
	if (array1[A_Index] > array2[A_Index])
	{
		compare := "version 1 is newer (" array1[A_Index] ")"
		break
	}
	; if the subversion of the second version is bigger than the first one  (from left to right); -> break the loop
	if (array2[A_Index] > array1[A_Index])
	{
		compare := "version 2 is newer (" array2[A_Index] ")"
		break
	}
	; if all subversions are the same
	compare := "version is the same"
}

As function:

Code: Select all

;	returns		1	= 	First  Version  is newer
;	returns 	2	= 	Second Version  is newer
;	returns		0	=	Both   Versions are the same
VersionCompare(version1, version2)
{
	ver1 := StrSplit(version1, ".")
	ver2 := StrSplit(version2, ".")
	len  := ver1.Length() > ver2.Length() ? ver1.Length() : ver2.Length()

	loop % len
	{
		if (ver1[A_Index] > ver2[A_Index]) {
			compare := 1
			break
		}
		if (ver2[A_Index] > ver1[A_Index]) {
			compare := 2
			break
		}
		compare := 0
	}
	return compare
}
[AHK] 1.1.32.00 x64 Unicode | [WIN] 10 Pro (Version 2004) x64 | [GitHub] Profile
Donations are appreciated if I could help you
Rohwedder
Posts: 3133
Joined: 04 Jun 2014, 08:33
Location: Germany

Re: Compare two software version numbers

29 May 2020, 07:35

Hallo.
try:

Code: Select all

VersionCompare(V1,V2)
{
;	returns >0	= 	First  Version  is newer
;	returns <0	= 	Second Version  is newer
;	returns ""	=	Both   Versions are the same
	V1  := StrSplit(V1, "."), V2  := StrSplit(V2, ".")
	While, !(q := V1[A_Index] - V2[A_Index]) And (q > "")
		Continue
	Return q
}

Return to “Ask For Help”

Who is online

Users browsing this forum: AHKStudent, Bing [Bot], c7aesa7r, Google [Bot], NOLLIE, TAC109 and 48 guests