In this challenge, you will be given a string that may have mixed uppercase and lowercase letters and your task is to convert that string to either lowercase only or uppercase only based on:
- making as few changes as possible
- if the string contains equal number of uppercase and lowercase letters, convert the string to lowercase.
For example:
solve("coDe") = "code". Lowercase characters > uppercase. Change only the "D" to lowercase.
solve("CODe") = "CODE". Uppercase characters > lowecase. Change only the "e" to uppercase.
solve("coDE") = "code". Upper == lowercase. Change all to lowercase.
Tests:
solve("code")
solve("CODe")
solve("COde")
solve("Code")
Good luck!
This challenge comes from KenKamau on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!
Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!
Top comments (11)
JavaScript
Something like this should do it:
“A simple step for RegEx. A huge leap for a bunch of loops and
if
s.”Python solution. Uses helper function that counts the matching elements in a list. I use that to compare the string to itself converted to upper- and lowercase.
TIO link
in nim:
probably too verbose but that way I am only looping once through the string :-)
Tests:
solve("code") = "code"
solve("CODe") = "CODE"
solve("COde") = "code"
solve("Code") = "code"
Please let me know if there are any changes to be made.
Haskell solution:
Here's a C implementation that does a pretty good job at being as lazy as possible (which is what I always aspire to, even if it ends up being a lot of work to get to be lazy)
It updates the string in-place, passing through only once if nothing is to be done, or if its original guess of the final case was right. Otherwise, it passes through again only up to the last char it guessed wrong on.
Worst case, it iterates the string twice (minus one last character on the second pass), but the typical case is more like a single pass.
In C for old-times sake, and because if you're bothering to do this sort of thing at all it'd better be in a performant language just to make any of it worth the effort.
Output:
(a "total string passes including cleanup" of 1 is where the string was just passed over once)
Here is the simple solution without any advanced approach (e.g. ASCII code converting, regular expression and so on.):
Is it really a challenge?
Kotlin
True story..
Your solution is nice and short. 👍
Honestly i don't know what's more "efficient".