https://kotlinlang.org logo
Title
c

Chachako

09/07/2021, 1:17 AM
Hello everyone, do someone know how to merge the repeated content in the path string? E.g.
new.foo.bar.foo.bar.baz
merged to
new.foo.bar.baz
foo.bar.foo.bar.qux
merged to
foo.bar.qux
but
foo.bar.break.foo.bar
does not merge 🤯
I have found a way to solve it! This is my code: https://bit.ly/3jLHHPk 😁
t

The Monster

09/07/2021, 4:19 AM
Great job solving your problem. I am happy for you. I'm a somewhat beginner, so I'm curious about a couple of things in your code: 1. Is there any reason why your
main()
function is marked
suspend
? According to this linter rule https://rules.sonarsource.com/kotlin/tag/coroutines/RSPEC-6318 it is not compliant because the
main()
function does not have any suspension point. Based on the docs,
runBlocking
function should be used on the
main
function if we want coroutine in main https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/run-blocking.html 2. There is a lot of coroutine imports in the code, but code in
main
does not seem to need any?
c

Chachako

09/07/2021, 4:56 AM
@The Monster yep, they have no meaning, they are the rest redundant code I played in the last playground. 😆
👍 1
🙌 1
m

Matteo Mirk

09/07/2021, 8:18 AM
Alternatively you could use regular expressions to find and replace:
"""(.*)\1""".toRegex().replace(input, "$1")
but bear in mind that this solution is still O(n^2) in time complexity like your solution
:mind-blown: 1
c

Chachako

09/07/2021, 8:58 AM
This is incredibly short! 😱
But there seems to be a little problem, such as
A.B.C.A.B.C.A.B.C
. It is expected to print
A.B.C
, but printed
A.B.C.A.B.C
. In addition, I don’t understand the regular expression.
😁 1
s

Syed Ovais Akhtar

09/08/2021, 5:31 AM
You can slice the string then use sets for removing duplication
m

Matteo Mirk

09/08/2021, 11:57 AM
let me explain the regex: 1. .* match any char 0 or more times, as many as you can (greedy mode) 2. (.*) save it in a capturing group 3. \1 match a substring identical to capturing group 1 4. (.*)\1 match a substring which is followed by a duplicate the substrings are found by greedy consumption of the chars and backtracking whenever a match is not found. This code doesn’t do exactly what you want because the duplicate it finds in your example is
.A.B.C
, so after it’s done it cannot reduce it any further because “A.B.C” isn’t equal to “.A.B.C”
:today-i-learned: 1