@@ -49,14 +49,14 @@ class CorporatePolicy : AdventOfCode<String>(2015, 11) {
4949 }
5050
5151 private fun String.rotate (): String {
52- require(rule0AppliesTo(this )) { " a password has to be exactly 8 lowercase letters: '${ this } " }
52+ require(rule0AppliesTo(this )) { " a password has to be exactly 8 lowercase letters: '$this ' " }
5353
5454 var newPassword = this
5555 do {
5656 newPassword = newPassword.inc(lettersToSkip)
5757 } while (newPassword.notAllRulesApply())
5858
59- check(rule0AppliesTo(newPassword)) { " a password has to be exactly 8 lowercase letters: '$newPassword " }
59+ check(rule0AppliesTo(newPassword)) { " a password has to be exactly 8 lowercase letters: '$newPassword ' " }
6060 return newPassword
6161 }
6262
@@ -67,19 +67,22 @@ fun String.inc(toSkip: List<Char> = emptyList()): String {
6767 val highestChar = ' z'
6868 require(highestChar !in toSkip) { " incrementation only works correct if the highest char is not to skip" }
6969
70- var suffix = " "
71- var incIndex = lastIndex
72- while (incIndex >= 0 ) {
73- val prefix = substring(0 .. <incIndex)
74- if (get(incIndex) == highestChar) {
75- suffix = "a$suffix"
76- incIndex--
77- } else {
78- var incChar = get(incIndex).inc()
70+ if (toSkip.isNotEmpty()) {
71+ for (i in 0 .. lastIndex) {
72+ if (get(i) in toSkip) {
73+ // when a to-skip-char occurs early, skip counting up the suffix
74+ return substring(0 .. < i) + get(i).inc() + " a" .repeat(lastIndex - i)
75+ }
76+ }
77+ }
78+
79+ for (i in lastIndex downTo 0 ) {
80+ if (get(i) != highestChar) {
81+ var incChar = get(i).inc()
7982 while (incChar in toSkip) {
8083 incChar = incChar.inc()
8184 }
82- return prefix + incChar + suffix
85+ return substring( 0 .. < i) + incChar + " a " .repeat(lastIndex - i)
8386 }
8487 }
8588 throw StringOverflowException (" String '$this ' cannot be incremented without making it longer." )
0 commit comments