Last active
August 24, 2019 04:03
-
-
Save OmarKRostom/79f2503957432ac536a09cf227f5993f to your computer and use it in GitHub Desktop.
Solution to prison after n days problem. Time Complexity O(M^N)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun prisonAfterNDays(cells: IntArray, N: Int): IntArray { | |
var currentIndex = 0 | |
val prisonMap = HashMap<List<Int>, Int>() | |
while (currentIndex < N) { | |
var tempArr = cells.clone() | |
if (prisonMap[tempArr.toList()]?.hashCode() != null) { | |
val cycleLength = currentIndex - prisonMap[tempArr.toList()]!! | |
val remainingDays = N - currentIndex | |
val numOfRepeats = remainingDays / cycleLength | |
val newIndex = currentIndex + (cycleLength * numOfRepeats) | |
tempArr = prisonMap.filterValues { it == (N - newIndex).plus(prisonMap[tempArr.toList()]!!) }.keys.first().toIntArray() | |
cells.forEachIndexed { index, _ -> cells[index] = tempArr[index] } | |
break | |
} else { | |
prisonMap[tempArr.toList()] = currentIndex | |
} | |
for (prisonIndex in 0 until cells.size) { | |
if (prisonIndex == 0 || prisonIndex == cells.size - 1) cells[prisonIndex] = 0 | |
else if (tempArr[prisonIndex - 1] == tempArr[prisonIndex + 1]) cells[prisonIndex] = 1 | |
else cells[prisonIndex] = 0 | |
} | |
currentIndex++ | |
} | |
return cells | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment