Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package day04
- import java.io.File
- /**
- * author: vishnu
- * date: 5/20/17
- * purpose:
- */
- fun main(args: Array<String>) {
- val rooms = getRooms()
- println("Part 1: total = ${rooms.map { it.id }.sum()}")
- println("Part 2: room = ${findNorthPoleRoom(rooms)}")
- }
- private fun getRooms() =
- File("src/day04/rooms.txt").readLines()
- .map {
- val name = it.substring(0, it.length - 10)
- val id = it.substring(it.length - 10, it.length - 7).toInt()
- val checksum = it.substring(it.length - 6, it.length - 1)
- Room(name, id, checksum)
- }
- .filter { it.isReal() }
- private fun findNorthPoleRoom(rooms: List<Room>) =
- rooms[rooms.indexOfFirst { decryptRoomName(it.name, it.id).contains("northpole") }].id
- private fun decryptRoomName(name: String, id: Int): String {
- val increase = id % 26
- return name.toCharArray()
- .map {
- when {
- it == '-' -> ' '
- it.toInt() + increase > 122 -> it.plus(increase - 26)
- else -> it.plus(increase)
- }
- }
- .joinToString("")
- }
- internal class Room(val name: String, val id: Int, val checksum: String) {
- fun isReal(): Boolean {
- val chars: MutableMap<Char, Int> = HashMap(Math.min(name.length, 26))
- name.toCharArray()
- .filterNot { it == '-' }
- .forEach {
- when {
- chars.containsKey(it) -> chars.put(it, chars.getValue(it) + 1)
- else -> chars.put(it, 1)
- }
- }
- val sortedMap = chars.toSortedMap(ValueComparator(chars))
- val generated = sortedMap.keys.take(5).joinToString("")
- return generated == checksum
- }
- }
- internal class ValueComparator(val base: Map<Char, Int>) : Comparator<Char> {
- override fun compare(a: Char, b: Char) = if (base.getValue(a) > base.getValue(b)) -1 else 1
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement