Advertisement
Guest User

Untitled

a guest
Apr 20th, 2019
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. class AlphanumComparator : Comparator<String> {
  2. override fun compare(s1: String, s2: String): Int {
  3. var thisMarker = 0
  4. var thatMarker = 0
  5. val s1Length = s1.length
  6. val s2Length = s2.length
  7.  
  8. while (thisMarker < s1Length && thatMarker < s2Length) {
  9. val thisChunk = getChunk(s1, s1Length, thisMarker)
  10. thisMarker += thisChunk.length
  11.  
  12. val thatChunk = getChunk(s2, s2Length, thatMarker)
  13. thatMarker += thatChunk.length
  14.  
  15. // If both chunks contain numeric characters, sort them numerically.
  16. var result: Int
  17. if (isDigit(thisChunk[0]) && isDigit(thatChunk[0])) {
  18. // Simple chunk comparison by length.
  19. val thisChunkLength = thisChunk.length
  20. result = thisChunkLength - thatChunk.length
  21. // If equal, the first different number counts.
  22. if (result == 0) {
  23. for (i in 0..thisChunkLength - 1) {
  24. result = thisChunk[i] - thatChunk[i]
  25. if (result != 0) {
  26. return result
  27. }
  28. }
  29. }
  30. } else {
  31. result = thisChunk.compareTo(thatChunk)
  32. }
  33.  
  34. if (result != 0) {
  35. return result
  36. }
  37. }
  38.  
  39. return s1Length - s2Length
  40. }
  41.  
  42. private fun getChunk(string: String, length: Int, marker: Int): String {
  43. var current = marker
  44. val chunk = StringBuilder()
  45. var c = string[current]
  46. chunk.append(c)
  47. current++
  48. if (isDigit(c)) {
  49. while (current < length) {
  50. c = string[current]
  51. if (!isDigit(c)) {
  52. break
  53. }
  54. chunk.append(c)
  55. current++
  56. }
  57. } else {
  58. while (current < length) {
  59. c = string[current]
  60. if (isDigit(c)) {
  61. break
  62. }
  63. chunk.append(c)
  64. current++
  65. }
  66. }
  67. return chunk.toString()
  68. }
  69.  
  70. private fun isDigit(ch: Char): Boolean {
  71. return '0' <= ch && ch <= '9'
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement