therealbluepandabear
09/22/2021, 11:55 PMfun String.checkIfShuffledVersionOfAns(ans: String): Boolean {
val listOfChars = this.toCharArray()
val shuffledListOfStrings = mutableListOf<String>()
var iterations = 0
while (iterations < 100000) {
listOfChars.shuffle()
if (!shuffledListOfStrings.distinct().contains(listOfChars.concatToString())) {
shuffledListOfStrings.add(listOfChars.concatToString())
}
iterations++
}
for (string in shuffledListOfStrings.distinct()) {
if (string == this) return true
}
return false
}
ephemient
09/23/2021, 12:09 AMsorted() == ans.sorted()
Paul Griffith
09/23/2021, 12:10 AMfun String.checkIfShuffledVersionOfAns2(ans: String): Boolean {
return this == ans || this.groupingBy { it }.eachCount() == ans.groupingBy { it }.eachCount()
}
ephemient
09/23/2021, 12:13 AMtherealbluepandabear
09/23/2021, 12:36 AMPaul Griffith
09/23/2021, 12:37 AMgroupingBy
returns a Group
object, and eachCount
gives you a Map<Char, Int>
ephemient
09/23/2021, 12:38 AMtherealbluepandabear
09/23/2021, 12:42 AMephemient
09/23/2021, 1:59 AMtoCharArray().apply { sort() } contentEquals ans.toCharArray().apply { sort() }
would be more efficient as it doesn't need to construct List<Char>
but honestly that's a super minor compared to the improvement from original bogosort-like implementationMichael Böiers
09/23/2021, 8:06 AMchristophsturm
09/23/2021, 9:39 AMtodd.ginsberg
09/23/2021, 11:47 AMephemient
09/23/2021, 12:03 PMephemient
09/23/2021, 12:05 PMval counts = ByteArray(26)
for (char in this) counts[char - 'a']++
for (char in ans) count[char - 'a']--
return counts.all { it == 0 }
would do the job with less overhead than either the sorting or counting implementations in many casesephemient
09/23/2021, 12:06 PMchristophsturm
09/23/2021, 12:15 PMchristophsturm
09/23/2021, 12:17 PMchristophsturm
09/23/2021, 12:24 PMtodd.ginsberg
09/23/2021, 12:26 PMJonathan Mew
09/24/2021, 8:49 AMchristophsturm
09/24/2021, 9:14 AMephemient
09/24/2021, 9:31 AMchristophsturm
09/24/2021, 11:30 AMchristophsturm
09/24/2021, 11:32 AMephemient
09/26/2021, 2:51 AMephemient
09/26/2021, 2:53 AMmain summary:
Benchmark Mode Cnt Score Error Units
Bench.arrayCount thrpt 5 19.111 ± 0.452 ops/s
Bench.mapCount thrpt 5 1.300 ± 0.006 ops/s
Bench.sorting thrpt 5 9.599 ± 0.056 ops/s
Bench.troveCount thrpt 5 4.074 ± 0.018 ops/s
ephemient
09/26/2021, 2:55 AMchristophsturm
09/26/2021, 11:35 AMobject TroveCountMutableInt {
fun String.isPermutationOf(other: String): Boolean {
val map = MutableMap()
for (c in this) map.add(c, 1)
for (c in other) map.add(c, -1)
val iter = map.valueCollection().iterator()
while (iter.hasNext()) {
if (iter.next() != 0)
return false
}
return true
}
}
class MutableMap : TCharIntHashMap() {
fun add(key: Char, value: Int) {
var idx = insertKey(key)
if (idx < 0) {
idx = -idx - 1
_values[idx] += value
} else {
_values[idx] = value
postInsertHook(consumeFreeSlot)
}
}
}