fork(1) download
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text.RegularExpressions;
  4.  
  5. public class Version : IComparable<Version>
  6. {
  7. public int[] Parts { get; }
  8.  
  9. public Version(string value)
  10. {
  11. if (value == null)
  12. throw new ArgumentNullException();
  13. if (!Regex.IsMatch(value, @"^[0-9]+(\.[0-9]+)*$"))
  14. throw new ArgumentException("Invalid format");
  15. var parts = value.Split('.');
  16. Parts = new int[parts.Length];
  17. for (var i = 0; i < parts.Length; i++)
  18. Parts[i] = int.Parse(parts[i]);
  19. }
  20.  
  21. public override string ToString()
  22. {
  23. return string.Join(".", Parts);
  24. }
  25.  
  26. public int CompareTo(Version that)
  27. {
  28. if (that == null) return 1;
  29. var thisLength = this.Parts.Length;
  30. var thatLength = that.Parts.Length;
  31. var maxLength = Math.Max(thisLength, thatLength);
  32. for (var i = 0; i < maxLength; i++)
  33. {
  34. var thisPart = i < thisLength ? this.Parts[i] : 0;
  35. var thatPart = i < thatLength ? that.Parts[i] : 0;
  36. if (thisPart < thatPart) return -1;
  37. if (thisPart > thatPart) return 1;
  38. }
  39. return 0;
  40. }
  41. }
  42.  
  43. public class Test
  44. {
  45. public static void Main()
  46. {
  47. Version a, b;
  48.  
  49. a = new Version("4.2.1");
  50. b = new Version("4.2.6");
  51. a.CompareTo(b); // a < b : -1
  52.  
  53. a = new Version("2.8.4");
  54. b = new Version("2.8.0");
  55. a.CompareTo(b); // a > b : 1
  56.  
  57. a = new Version("5.2");
  58. b = null;
  59. a.CompareTo(b); // a > null : 1
  60.  
  61. a = new Version("3");
  62. b = new Version("3.6");
  63. a.CompareTo(b); // a < b : -1
  64.  
  65. var versions = new List<Version>
  66. {
  67. new Version("2.0"),
  68. new Version("1.1.5"),
  69. new Version("3.0.10"),
  70. new Version("1"),
  71. null,
  72. new Version("1.0.1")
  73. };
  74.  
  75. versions.Sort();
  76.  
  77. foreach (var version in versions)
  78. Console.WriteLine(version?.ToString() ?? "NULL");
  79. }
  80. }
Success #stdin #stdout 0.12s 24368KB
stdin
Standard input is empty
stdout
NULL
1
1.0.1
1.1.5
2.0
3.0.10