Advertisement
Guest User

Untitled

a guest
Dec 16th, 2017
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.25 KB | None | 0 0
  1. package day16
  2.  
  3. class Dancer(val input: String, val iterations: Long) {
  4.     private val danceMoves: List<DanceMove>
  5.  
  6.     init {
  7.         danceMoves = input.split(",").map { fullDanceMoveString ->
  8.             val danceMoveType = fullDanceMoveString[0]
  9.             val danceMoveArgs = fullDanceMoveString.substring(1).split("/")
  10.             when (danceMoveType) {
  11.                 's' -> MoveS(danceMoveArgs[0].toInt())
  12.                 'x' -> MoveX(danceMoveArgs[0].toInt(), danceMoveArgs[1].toInt())
  13.                 else -> MoveP(danceMoveArgs[0].first(), danceMoveArgs[1].first())
  14.             }
  15.         }
  16.     }
  17.  
  18.     fun dance(): String {
  19.         tailrec fun getStatesInCycle(seen: Set<String>, seenList: List<String>, previous: String): List<String> {
  20.             if (seen.contains(previous)) {
  21.                 return seenList
  22.             }
  23.             val newStep = danceMoves.fold(previous, { danceState, move -> move.execute(danceState) })
  24.             return getStatesInCycle(seen + previous, seenList + previous, newStep)
  25.         }
  26.  
  27.         val initialDanceState = CharRange('a', 'p').joinToString(separator = "")
  28.         val cycleStates = getStatesInCycle(setOf(), listOf(), initialDanceState)
  29.  
  30.         return cycleStates[(iterations % cycleStates.size).toInt()]
  31.     }
  32.  
  33.     private interface DanceMove {
  34.         fun execute(danceState: String): String
  35.     }
  36.  
  37.     private class MoveS(val noOfLastElements: Int) : DanceMove {
  38.         override fun execute(danceState: String): String {
  39.             return danceState.spin(noOfLastElements)
  40.         }
  41.     }
  42.  
  43.     private class MoveX(val i: Int, val j: Int) : DanceMove {
  44.         override fun execute(danceState: String): String {
  45.             return danceState.swap(danceState[i], danceState[j])
  46.         }
  47.     }
  48.  
  49.     private class MoveP(val x: Char, val y: Char) : DanceMove {
  50.         override fun execute(danceState: String): String {
  51.             return danceState.swap(danceState[danceState.indexOf(x)], danceState[danceState.indexOf(y)])
  52.         }
  53.     }
  54. }
  55.  
  56. private fun String.swap(c1: Char, c2: Char): String {
  57.     return this.replace(c1, '-').replace(c2, c1).replace('-', c2)
  58. }
  59.  
  60. private fun String.spin(amount: Int): String {
  61.     return this.takeLast(amount) + this.take(this.length - amount)
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement