Skip to content

Commit

Permalink
Update AlphanumericComparator.kt Modified Compare function to reduce …
Browse files Browse the repository at this point in the history
…the no of return statements
  • Loading branch information
KesharwaniArpita authored Oct 19, 2024
1 parent e0d368a commit 3bd1bb1
Showing 1 changed file with 30 additions and 37 deletions.
67 changes: 30 additions & 37 deletions app/src/main/java/be/scri/helpers/AlphanumericComparator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -4,53 +4,46 @@ package be.scri.helpers
// make IMG_5.jpg come before IMG_10.jpg
class AlphanumericComparator {
fun compare(
string1: String,
string2: String,
): Int {
var thisMarker = 0
var thatMarker = 0
val s1Length = string1.length
val s2Length = string2.length
var result = 0 // Initialize result variable
string1: String,
string2: String,
): Int {
var thisMarker = 0
var thatMarker = 0
val s1Length = string1.length
val s2Length = string2.length

while (thisMarker < s1Length && thatMarker < s2Length) {
val thisChunk = getChunk(string1, s1Length, thisMarker)
thisMarker += thisChunk.length
while (thisMarker < s1Length && thatMarker < s2Length) {
val thisChunk = getChunk(string1, s1Length, thisMarker)
thisMarker += thisChunk.length

val thatChunk = getChunk(string2, s2Length, thatMarker)
thatMarker += thatChunk.length
val thatChunk = getChunk(string2, s2Length, thatMarker)
thatMarker += thatChunk.length

// If both chunks contain numeric characters, sort them numerically.
if (isDigit(thisChunk[0]) && isDigit(thatChunk[0])) {
// Simple chunk comparison by length.
val thisChunkLength = thisChunk.length
result = thisChunkLength - thatChunk.length
// If equal, the first different number counts.
if (result == 0) {
for (i in 0 until thisChunkLength) {
result = thisChunk[i] - thatChunk[i]
if (result != 0) {
break // Exit loop if a difference is found
}
}
// If both chunks contain numeric characters, sort them numerically.
var result: Int
if (isDigit(thisChunk[0]) && isDigit(thatChunk[0])) {
// Simple chunk comparison by length.
val thisChunkLength = thisChunk.length
result = thisChunkLength - thatChunk.length
// If equal, the first different number counts.
if (result == 0) {
for (i in 0 until thisChunkLength) {
result = thisChunk[i] - thatChunk[i]
if (result != 0) break
}
} else {
result = thisChunk.compareTo(thatChunk)
}

if (result != 0) {
break // Exit the loop if the result is not zero
}
} else {
result = thisChunk.compareTo(thatChunk)
}

// Return the final comparison result
return if (result != 0) {
result
} else {
s1Length - s2Length
if (result != 0) {
return result
}
}

return s1Length - s2Length
}

private fun getChunk(
string: String,
length: Int,
Expand Down

0 comments on commit 3bd1bb1

Please sign in to comment.