path
stringlengths
5
169
owner
stringlengths
2
34
repo_id
int64
1.49M
755M
is_fork
bool
2 classes
languages_distribution
stringlengths
16
1.68k
content
stringlengths
446
72k
issues
float64
0
1.84k
main_language
stringclasses
37 values
forks
int64
0
5.77k
stars
int64
0
46.8k
commit_sha
stringlengths
40
40
size
int64
446
72.6k
name
stringlengths
2
64
license
stringclasses
15 values
src/main/kotlin/_2018/Day4.kt
thebrightspark
227,161,060
false
{"Kotlin": 548420}
package _2018 import aocRun import format import java.time.Duration import java.time.LocalDateTime import java.time.format.DateTimeFormatter import java.util.regex.Pattern private val pattern = Pattern.compile("\\[(?<timestamp>[\\d-: ]+)]( Guard #(?<guardId>\\d+))?[ ]?(?<message>.*)") private val dateFormat = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm") fun main() { aocRun(puzzleInput) { input -> val records = parseRecords(input) // Find guard with most minutes of sleep val totalSleep = mutableMapOf<Int, Long>() var lastSleepStart: LocalDateTime? = null records.forEach { record -> when (record.type) { RecordType.SLEEP -> lastSleepStart = record.timestamp RecordType.AWAKE -> { val period = Duration.between(lastSleepStart!!, record.timestamp) totalSleep.compute(record.guardId!!) { _, mins -> (mins ?: 0) + period.toMinutes() } lastSleepStart = null } else -> Unit } } val mostSleep = totalSleep.entries.maxByOrNull { it.value }!! val guardId = mostSleep.key println("ID: $guardId, Sleep: ${mostSleep.value.format()}mins") // Find minute during which the guard sleeps the most val sleepFrequencyByMin = mutableMapOf<Int, Int>() var lastSleepStartMin = 0 records.filter { it.guardId == guardId && it.type != RecordType.SHIFT }.forEach { record -> when (record.type) { RecordType.SLEEP -> lastSleepStartMin = record.timestamp.minute RecordType.AWAKE -> { (lastSleepStartMin until record.timestamp.minute).forEach { sleepFrequencyByMin.compute(it) { _, count -> (count ?: 0) + 1 } } } else -> Unit } } val mostFrequentMinute = sleepFrequencyByMin.entries.maxByOrNull { it.value }!!.key println("Min: $mostFrequentMinute") return@aocRun guardId * mostFrequentMinute } aocRun(puzzleInput) { input -> val records = parseRecords(input) // Map of Minute to GuardId and Frequency val sleepFrequency = mutableMapOf<Int, MutableMap<Int, Int>>() var lastSleepStartMin = 0 records.filter { it.type != RecordType.SHIFT }.forEach { record -> when (record.type) { RecordType.SLEEP -> lastSleepStartMin = record.timestamp.minute RecordType.AWAKE -> { (lastSleepStartMin until record.timestamp.minute).forEach { sleepFrequency.compute(it) { _, map -> map?.compute(record.guardId!!) { _, count -> (count ?: 0) + 1 } return@compute map ?: mutableMapOf(record.guardId!! to 1) } } } else -> Unit } } // Get guard which is most frequently asleep on same minute var minute = 0 var guardId = 0 var count = 0 sleepFrequency.forEach { min, map -> val maxEntry = map.maxByOrNull { it.value }!! if (maxEntry.value > count) { minute = min guardId = maxEntry.key count = maxEntry.value } } println("Min: $minute, Guard: $guardId, Count: $count") return@aocRun guardId * minute } } private fun parseRecords(input: String): List<Record> { val records = input.split("\n") .map { val matcher = pattern.matcher(it) if (!matcher.find()) throw RuntimeException("Not a valid input! -> '$it'") return@map Record( matcher.group("guardId")?.toInt(), LocalDateTime.from(dateFormat.parse(matcher.group("timestamp"))), RecordType.fromString(matcher.group("message")) ) } .sortedBy { it.timestamp } // Ensure all records have their guardId set var lastGuardId = -1 records.forEach { record -> record.guardId?.let { lastGuardId = it return@forEach } record.guardId = lastGuardId } return records } private enum class RecordType(val key: String) { SHIFT("begins shift"), SLEEP("falls asleep"), AWAKE("wakes up"); companion object { fun fromString(input: String): RecordType = values().find { input == it.key }!! } } private data class Record(var guardId: Int?, val timestamp: LocalDateTime, val type: RecordType) private val puzzleInput = """ [1518-05-31 00:27] falls asleep [1518-04-15 00:54] wakes up [1518-04-06 00:42] falls asleep [1518-02-08 00:41] wakes up [1518-11-11 00:59] wakes up [1518-11-09 00:46] wakes up [1518-06-15 00:29] falls asleep [1518-05-25 00:44] wakes up [1518-11-21 00:00] Guard #3203 begins shift [1518-08-28 00:04] Guard #1163 begins shift [1518-11-07 00:36] wakes up [1518-04-22 00:16] falls asleep [1518-07-19 00:31] falls asleep [1518-05-04 23:48] Guard #1663 begins shift [1518-10-31 00:24] falls asleep [1518-11-07 00:54] wakes up [1518-06-18 00:04] Guard #859 begins shift [1518-06-26 00:38] falls asleep [1518-07-12 00:46] wakes up [1518-09-14 00:15] wakes up [1518-09-03 00:47] wakes up [1518-05-26 00:41] wakes up [1518-03-17 00:56] wakes up [1518-10-25 00:47] falls asleep [1518-04-08 00:34] falls asleep [1518-05-10 00:44] falls asleep [1518-04-17 00:50] wakes up [1518-06-29 00:39] falls asleep [1518-04-19 00:59] wakes up [1518-11-07 00:35] falls asleep [1518-06-18 00:07] falls asleep [1518-09-26 00:30] falls asleep [1518-10-12 00:31] falls asleep [1518-09-10 00:59] wakes up [1518-07-27 00:53] wakes up [1518-08-05 00:00] falls asleep [1518-10-28 00:53] wakes up [1518-05-19 00:00] Guard #997 begins shift [1518-06-27 00:50] wakes up [1518-10-17 00:28] falls asleep [1518-05-11 00:45] wakes up [1518-03-18 00:07] falls asleep [1518-04-03 00:50] wakes up [1518-04-21 00:04] Guard #113 begins shift [1518-07-24 00:50] wakes up [1518-09-13 00:41] falls asleep [1518-06-19 00:30] wakes up [1518-09-14 00:43] falls asleep [1518-06-24 00:56] wakes up [1518-07-12 00:28] falls asleep [1518-04-21 00:33] wakes up [1518-08-31 00:00] Guard #739 begins shift [1518-05-15 00:55] wakes up [1518-06-09 00:39] falls asleep [1518-03-12 00:03] Guard #997 begins shift [1518-04-15 00:16] falls asleep [1518-09-07 00:26] falls asleep [1518-03-26 00:21] wakes up [1518-06-26 00:40] wakes up [1518-02-05 00:02] Guard #1663 begins shift [1518-04-13 00:06] falls asleep [1518-04-24 23:59] Guard #733 begins shift [1518-02-09 23:59] Guard #419 begins shift [1518-08-28 00:58] wakes up [1518-03-16 00:58] wakes up [1518-11-13 00:19] falls asleep [1518-03-13 00:54] wakes up [1518-04-12 00:46] falls asleep [1518-03-04 00:17] falls asleep [1518-04-10 00:40] falls asleep [1518-05-11 00:01] Guard #1367 begins shift [1518-04-09 00:42] wakes up [1518-03-29 00:53] wakes up [1518-02-27 00:01] Guard #859 begins shift [1518-08-13 00:52] falls asleep [1518-09-22 00:43] falls asleep [1518-05-13 00:19] falls asleep [1518-05-14 00:06] falls asleep [1518-08-05 00:18] wakes up [1518-11-10 00:41] falls asleep [1518-09-10 00:43] falls asleep [1518-03-02 00:44] falls asleep [1518-04-16 23:57] Guard #1163 begins shift [1518-09-09 00:43] falls asleep [1518-02-09 00:01] Guard #997 begins shift [1518-09-13 00:35] falls asleep [1518-09-08 00:04] Guard #3407 begins shift [1518-08-02 00:14] falls asleep [1518-11-07 00:02] Guard #2113 begins shift [1518-06-13 23:57] Guard #661 begins shift [1518-04-29 00:57] wakes up [1518-11-04 00:56] falls asleep [1518-08-03 00:54] wakes up [1518-06-29 00:17] falls asleep [1518-07-15 00:37] wakes up [1518-06-14 23:58] Guard #2221 begins shift [1518-02-11 00:41] falls asleep [1518-10-24 23:56] Guard #739 begins shift [1518-06-12 23:56] Guard #1663 begins shift [1518-02-23 23:51] Guard #2113 begins shift [1518-05-09 00:24] falls asleep [1518-09-21 00:22] wakes up [1518-02-11 00:38] wakes up [1518-07-23 00:54] falls asleep [1518-03-10 23:59] Guard #661 begins shift [1518-03-03 00:03] falls asleep [1518-06-08 00:41] wakes up [1518-02-05 00:12] falls asleep [1518-09-23 00:51] wakes up [1518-05-02 00:39] wakes up [1518-07-06 00:06] falls asleep [1518-03-27 23:57] Guard #2221 begins shift [1518-04-29 00:00] Guard #661 begins shift [1518-05-05 00:22] wakes up [1518-09-12 00:38] wakes up [1518-04-28 00:48] falls asleep [1518-10-08 00:58] wakes up [1518-08-22 00:55] falls asleep [1518-10-22 00:52] falls asleep [1518-07-15 00:56] wakes up [1518-08-15 23:57] Guard #859 begins shift [1518-05-19 23:53] Guard #3407 begins shift [1518-11-03 00:03] Guard #2713 begins shift [1518-10-02 00:01] Guard #859 begins shift [1518-03-08 00:13] falls asleep [1518-03-15 00:02] Guard #859 begins shift [1518-05-01 00:55] wakes up [1518-07-25 00:41] falls asleep [1518-05-24 00:24] falls asleep [1518-05-03 00:58] wakes up [1518-04-11 00:32] falls asleep [1518-09-24 23:54] Guard #2383 begins shift [1518-10-24 00:23] falls asleep [1518-06-24 00:28] falls asleep [1518-08-04 00:59] wakes up [1518-10-21 00:19] wakes up [1518-03-21 00:04] Guard #661 begins shift [1518-06-18 00:15] wakes up [1518-09-29 00:09] falls asleep [1518-05-26 00:20] falls asleep [1518-10-20 00:04] falls asleep [1518-09-29 00:19] wakes up [1518-08-10 00:03] falls asleep [1518-08-03 00:03] falls asleep [1518-07-14 00:41] falls asleep [1518-09-26 00:13] wakes up [1518-02-21 00:05] falls asleep [1518-08-21 00:14] falls asleep [1518-04-27 00:46] wakes up [1518-06-11 23:57] Guard #3203 begins shift [1518-04-26 00:18] wakes up [1518-02-24 00:02] falls asleep [1518-09-13 00:21] falls asleep [1518-07-06 00:18] wakes up [1518-08-08 00:38] falls asleep [1518-03-23 00:37] falls asleep [1518-08-05 00:32] falls asleep [1518-05-12 00:51] falls asleep [1518-05-28 00:58] wakes up [1518-02-15 00:24] wakes up [1518-02-17 00:30] falls asleep [1518-08-11 00:58] wakes up [1518-04-26 00:09] falls asleep [1518-06-20 00:58] wakes up [1518-08-09 00:36] falls asleep [1518-04-25 00:19] wakes up [1518-02-28 00:58] wakes up [1518-04-18 00:06] falls asleep [1518-03-08 00:53] wakes up [1518-09-13 00:36] wakes up [1518-04-10 00:01] Guard #3391 begins shift [1518-11-15 00:48] wakes up [1518-09-24 00:43] wakes up [1518-05-15 00:14] wakes up [1518-07-14 00:59] wakes up [1518-06-28 23:57] Guard #733 begins shift [1518-09-13 00:25] wakes up [1518-07-26 23:56] Guard #3203 begins shift [1518-05-28 00:47] wakes up [1518-11-09 00:03] Guard #3391 begins shift [1518-07-01 00:52] wakes up [1518-10-07 00:04] Guard #661 begins shift [1518-11-05 00:59] wakes up [1518-06-15 00:45] wakes up [1518-09-02 00:40] wakes up [1518-06-05 00:00] Guard #419 begins shift [1518-02-04 00:57] wakes up [1518-07-10 00:30] falls asleep [1518-05-14 00:04] Guard #61 begins shift [1518-06-06 00:00] Guard #3203 begins shift [1518-11-22 00:04] Guard #2713 begins shift [1518-02-11 00:55] wakes up [1518-08-15 00:47] wakes up [1518-10-03 00:02] Guard #2383 begins shift [1518-06-02 00:57] wakes up [1518-04-01 00:37] wakes up [1518-06-29 23:58] Guard #859 begins shift [1518-11-22 00:38] falls asleep [1518-04-13 00:00] Guard #2609 begins shift [1518-07-07 00:48] wakes up [1518-10-29 00:54] wakes up [1518-02-26 00:59] wakes up [1518-10-18 00:04] Guard #1367 begins shift [1518-04-11 00:58] wakes up [1518-10-27 23:59] Guard #1663 begins shift [1518-09-12 00:11] falls asleep [1518-06-21 00:55] wakes up [1518-06-16 00:00] Guard #2113 begins shift [1518-05-19 00:48] wakes up [1518-08-31 00:23] wakes up [1518-10-14 00:59] wakes up [1518-02-17 00:04] Guard #2221 begins shift [1518-11-16 00:58] wakes up [1518-07-08 00:31] wakes up [1518-05-04 00:46] falls asleep [1518-08-02 00:57] wakes up [1518-03-25 00:00] Guard #3407 begins shift [1518-07-29 00:37] falls asleep [1518-07-10 00:04] Guard #3203 begins shift [1518-07-26 00:32] wakes up [1518-10-19 00:57] falls asleep [1518-10-22 23:50] Guard #113 begins shift [1518-11-05 00:02] Guard #661 begins shift [1518-03-20 00:38] falls asleep [1518-05-24 00:51] wakes up [1518-03-07 00:32] wakes up [1518-10-03 00:45] falls asleep [1518-08-15 00:01] Guard #859 begins shift [1518-10-29 00:03] Guard #2221 begins shift [1518-11-12 00:00] falls asleep [1518-11-22 23:58] Guard #733 begins shift [1518-06-18 00:42] falls asleep [1518-10-18 00:58] wakes up [1518-02-19 00:00] Guard #419 begins shift [1518-03-26 00:19] falls asleep [1518-03-14 00:49] falls asleep [1518-09-05 23:47] Guard #419 begins shift [1518-09-03 00:57] falls asleep [1518-08-06 00:00] Guard #661 begins shift [1518-09-24 00:41] falls asleep [1518-09-15 00:55] wakes up [1518-10-15 00:50] wakes up [1518-05-28 00:35] falls asleep [1518-02-11 00:32] falls asleep [1518-06-19 00:36] falls asleep [1518-02-25 00:06] falls asleep [1518-04-20 00:50] wakes up [1518-02-17 00:54] wakes up [1518-05-29 00:00] Guard #2609 begins shift [1518-07-26 00:00] Guard #2383 begins shift [1518-08-14 00:11] falls asleep [1518-08-01 00:00] Guard #2297 begins shift [1518-04-04 00:41] wakes up [1518-06-10 00:55] wakes up [1518-03-19 00:05] falls asleep [1518-06-11 00:30] falls asleep [1518-03-31 00:20] falls asleep [1518-07-13 00:52] wakes up [1518-08-29 00:11] falls asleep [1518-05-16 00:42] wakes up [1518-11-05 00:36] wakes up [1518-10-22 00:40] wakes up [1518-09-06 00:01] falls asleep [1518-09-20 00:42] falls asleep [1518-11-07 00:48] falls asleep [1518-07-31 00:59] wakes up [1518-04-19 00:30] wakes up [1518-05-12 23:56] Guard #997 begins shift [1518-03-04 00:53] wakes up [1518-10-07 00:06] falls asleep [1518-08-28 00:27] falls asleep [1518-05-16 00:17] falls asleep [1518-10-23 00:04] falls asleep [1518-07-08 00:57] wakes up [1518-06-14 00:50] wakes up [1518-04-13 00:46] wakes up [1518-04-05 23:50] Guard #419 begins shift [1518-10-25 00:43] wakes up [1518-04-08 00:18] wakes up [1518-05-12 00:29] wakes up [1518-03-28 23:56] Guard #2609 begins shift [1518-09-13 00:56] wakes up [1518-03-08 00:48] falls asleep [1518-02-12 00:32] falls asleep [1518-10-15 00:02] Guard #2297 begins shift [1518-07-26 00:38] falls asleep [1518-04-06 23:47] Guard #2383 begins shift [1518-10-03 00:40] wakes up [1518-07-23 00:58] wakes up [1518-03-17 00:02] Guard #1367 begins shift [1518-06-30 00:47] falls asleep [1518-09-06 00:24] falls asleep [1518-05-04 00:54] wakes up [1518-04-19 00:39] wakes up [1518-07-15 00:10] falls asleep [1518-07-26 00:28] falls asleep [1518-07-21 00:24] falls asleep [1518-08-09 23:54] Guard #739 begins shift [1518-02-21 00:45] falls asleep [1518-03-10 00:53] wakes up [1518-06-13 00:09] falls asleep [1518-08-06 00:47] falls asleep [1518-10-31 00:53] wakes up [1518-08-23 23:51] Guard #739 begins shift [1518-03-13 00:03] Guard #3203 begins shift [1518-06-02 00:14] falls asleep [1518-10-20 00:38] falls asleep [1518-08-25 00:43] falls asleep [1518-08-31 23:53] Guard #733 begins shift [1518-04-30 00:17] falls asleep [1518-08-06 00:12] falls asleep [1518-11-06 00:02] Guard #739 begins shift [1518-07-02 00:56] wakes up [1518-05-29 00:18] falls asleep [1518-02-14 00:57] wakes up [1518-03-13 00:52] falls asleep [1518-09-26 23:49] Guard #2713 begins shift [1518-05-19 00:37] falls asleep [1518-08-30 00:26] falls asleep [1518-05-30 00:08] falls asleep [1518-09-01 00:54] wakes up [1518-11-04 00:47] wakes up [1518-06-04 00:26] wakes up [1518-08-10 00:48] falls asleep [1518-04-11 00:02] Guard #2221 begins shift [1518-07-11 23:57] Guard #61 begins shift [1518-07-20 00:45] wakes up [1518-04-03 23:59] Guard #3391 begins shift [1518-11-08 00:56] wakes up [1518-08-04 00:56] falls asleep [1518-09-19 00:43] wakes up [1518-02-12 00:00] Guard #61 begins shift [1518-07-06 23:50] Guard #661 begins shift [1518-06-07 00:20] falls asleep [1518-08-08 00:02] Guard #997 begins shift [1518-07-21 00:47] wakes up [1518-11-15 00:02] Guard #1163 begins shift [1518-04-30 00:58] wakes up [1518-08-06 00:19] wakes up [1518-03-08 23:50] Guard #61 begins shift [1518-07-08 23:59] Guard #2609 begins shift [1518-08-22 00:01] Guard #2383 begins shift [1518-06-30 00:55] wakes up [1518-06-19 00:25] falls asleep [1518-05-05 00:03] falls asleep [1518-09-12 23:56] Guard #2609 begins shift [1518-07-03 00:43] wakes up [1518-07-18 00:25] wakes up [1518-07-16 23:57] Guard #941 begins shift [1518-11-21 00:20] falls asleep [1518-11-04 00:59] wakes up [1518-07-27 00:31] falls asleep [1518-10-12 00:43] falls asleep [1518-03-22 00:04] Guard #997 begins shift [1518-03-05 00:03] Guard #1663 begins shift [1518-06-27 00:53] falls asleep [1518-08-22 00:45] falls asleep [1518-07-08 00:00] Guard #1367 begins shift [1518-06-01 00:14] falls asleep [1518-02-25 00:01] Guard #1163 begins shift [1518-09-22 00:15] falls asleep [1518-05-03 00:03] falls asleep [1518-09-22 00:02] falls asleep [1518-09-21 00:54] wakes up [1518-06-21 00:00] Guard #859 begins shift [1518-06-28 00:59] wakes up [1518-03-19 00:21] wakes up [1518-08-31 00:38] wakes up [1518-09-26 00:49] wakes up [1518-11-19 00:36] wakes up [1518-02-28 00:02] Guard #3391 begins shift [1518-02-12 00:58] wakes up [1518-11-08 00:31] falls asleep [1518-04-17 00:41] falls asleep [1518-10-11 00:02] Guard #2113 begins shift [1518-08-03 00:41] falls asleep [1518-06-13 00:43] falls asleep [1518-03-28 00:50] falls asleep [1518-10-21 00:53] wakes up [1518-04-21 00:48] falls asleep [1518-02-16 00:56] wakes up [1518-03-09 00:27] falls asleep [1518-08-04 00:13] falls asleep [1518-02-17 00:47] falls asleep [1518-06-10 23:57] Guard #1163 begins shift [1518-10-11 00:49] falls asleep [1518-08-01 00:17] wakes up [1518-02-20 23:52] Guard #3407 begins shift [1518-03-09 00:00] falls asleep [1518-10-21 23:46] Guard #661 begins shift [1518-02-19 00:29] falls asleep [1518-08-23 00:36] falls asleep [1518-06-16 00:11] falls asleep [1518-08-26 00:52] wakes up [1518-08-07 00:43] falls asleep [1518-11-07 23:59] Guard #997 begins shift [1518-11-18 00:10] falls asleep [1518-07-23 00:34] falls asleep [1518-03-30 00:59] wakes up [1518-03-29 00:48] falls asleep [1518-09-20 23:50] Guard #419 begins shift [1518-06-06 23:57] Guard #1663 begins shift [1518-08-13 00:00] Guard #2113 begins shift [1518-04-28 00:04] Guard #739 begins shift [1518-09-11 00:34] falls asleep [1518-06-18 00:28] falls asleep [1518-05-21 00:07] falls asleep [1518-08-25 00:40] wakes up [1518-08-20 00:48] falls asleep [1518-09-30 00:00] Guard #3391 begins shift [1518-08-02 00:56] falls asleep [1518-08-13 00:57] wakes up [1518-05-23 00:00] Guard #739 begins shift [1518-05-04 00:38] wakes up [1518-08-04 00:45] wakes up [1518-02-15 00:00] Guard #3391 begins shift [1518-08-13 23:58] Guard #1663 begins shift [1518-06-04 00:55] wakes up [1518-04-08 00:04] falls asleep [1518-06-28 00:57] falls asleep [1518-08-09 00:44] wakes up [1518-06-25 00:38] wakes up [1518-03-03 00:48] falls asleep [1518-05-02 00:43] falls asleep [1518-10-10 00:51] falls asleep [1518-11-04 00:43] falls asleep [1518-08-10 00:45] wakes up [1518-09-27 00:58] wakes up [1518-04-17 23:58] Guard #3203 begins shift [1518-07-04 00:34] falls asleep [1518-03-14 00:42] wakes up [1518-10-12 00:39] wakes up [1518-08-16 00:49] wakes up [1518-10-19 23:54] Guard #997 begins shift [1518-05-17 00:00] Guard #2383 begins shift [1518-03-03 00:54] wakes up [1518-09-27 00:57] falls asleep [1518-03-30 00:41] falls asleep [1518-11-06 00:57] wakes up [1518-09-14 00:00] falls asleep [1518-09-28 00:16] falls asleep [1518-09-14 00:44] wakes up [1518-05-08 23:58] Guard #1163 begins shift [1518-09-12 00:02] Guard #859 begins shift [1518-08-11 00:15] falls asleep [1518-10-09 23:56] Guard #2221 begins shift [1518-05-01 23:53] Guard #733 begins shift [1518-07-19 00:52] wakes up [1518-11-22 00:59] wakes up [1518-11-23 00:28] falls asleep [1518-08-15 00:37] falls asleep [1518-05-02 00:52] wakes up [1518-06-25 23:58] Guard #2609 begins shift [1518-07-06 00:16] falls asleep [1518-05-30 00:03] Guard #997 begins shift [1518-03-06 00:20] falls asleep [1518-09-22 00:51] wakes up [1518-11-08 00:42] wakes up [1518-07-24 23:56] Guard #739 begins shift [1518-06-11 00:37] wakes up [1518-04-15 00:49] falls asleep [1518-07-26 00:57] wakes up [1518-02-19 23:50] Guard #2221 begins shift [1518-05-03 00:29] wakes up [1518-04-15 00:36] wakes up [1518-03-26 00:04] Guard #1163 begins shift [1518-10-18 00:15] falls asleep [1518-04-23 23:59] Guard #3391 begins shift [1518-06-28 00:35] wakes up [1518-05-04 00:37] falls asleep [1518-10-14 00:00] Guard #997 begins shift [1518-07-18 00:44] wakes up [1518-04-03 00:04] falls asleep [1518-04-13 00:36] wakes up [1518-06-09 00:01] Guard #739 begins shift [1518-03-13 00:38] falls asleep [1518-06-08 00:57] falls asleep [1518-04-21 00:10] falls asleep [1518-08-04 00:04] Guard #859 begins shift [1518-03-02 00:58] wakes up [1518-06-15 00:34] wakes up [1518-02-06 00:50] wakes up [1518-11-20 00:43] wakes up [1518-11-15 23:57] Guard #859 begins shift [1518-07-26 00:23] wakes up [1518-05-24 00:02] Guard #3391 begins shift [1518-07-18 00:22] falls asleep [1518-04-25 00:31] falls asleep [1518-08-27 00:49] falls asleep [1518-07-21 23:58] Guard #349 begins shift [1518-06-10 00:54] falls asleep [1518-09-17 00:04] Guard #733 begins shift [1518-06-20 00:39] falls asleep [1518-03-23 00:01] Guard #2297 begins shift [1518-05-21 00:59] wakes up [1518-09-24 00:17] falls asleep [1518-06-23 00:12] falls asleep [1518-05-20 00:03] falls asleep [1518-09-26 00:03] falls asleep [1518-05-31 00:37] falls asleep [1518-06-30 23:59] Guard #739 begins shift [1518-07-07 00:05] falls asleep [1518-04-19 00:17] falls asleep [1518-03-13 00:44] wakes up [1518-09-03 00:00] Guard #661 begins shift [1518-02-15 23:49] Guard #739 begins shift [1518-04-07 00:05] falls asleep [1518-02-26 00:01] Guard #661 begins shift [1518-11-17 23:57] Guard #859 begins shift [1518-08-22 00:47] wakes up [1518-09-23 00:16] falls asleep [1518-07-21 00:40] falls asleep [1518-03-31 00:00] Guard #1663 begins shift [1518-08-01 00:10] falls asleep [1518-09-30 00:52] wakes up [1518-04-14 00:08] falls asleep [1518-02-06 23:56] Guard #859 begins shift [1518-04-16 00:27] wakes up [1518-05-22 00:29] falls asleep [1518-11-01 00:31] falls asleep [1518-09-28 00:39] wakes up [1518-05-22 00:30] wakes up [1518-10-03 00:55] wakes up [1518-06-21 23:56] Guard #907 begins shift [1518-05-28 00:57] falls asleep [1518-06-06 00:40] falls asleep [1518-08-23 00:59] wakes up [1518-05-20 00:47] wakes up [1518-03-12 00:31] falls asleep [1518-07-12 00:56] wakes up [1518-08-03 00:25] wakes up [1518-05-08 00:04] Guard #419 begins shift [1518-10-09 00:00] Guard #419 begins shift [1518-10-30 00:04] Guard #733 begins shift [1518-02-09 00:37] falls asleep [1518-03-17 23:59] Guard #2297 begins shift [1518-02-21 00:08] wakes up [1518-05-10 00:47] wakes up [1518-11-20 00:01] falls asleep [1518-07-06 00:02] Guard #113 begins shift [1518-06-14 00:34] falls asleep [1518-09-11 00:39] wakes up [1518-05-27 00:27] wakes up [1518-04-07 00:36] wakes up [1518-03-27 00:03] Guard #907 begins shift [1518-07-18 00:42] falls asleep [1518-11-17 00:00] Guard #3407 begins shift [1518-04-11 00:06] falls asleep [1518-06-07 00:59] wakes up [1518-05-04 00:01] Guard #1663 begins shift [1518-05-03 00:47] wakes up [1518-10-06 00:51] wakes up [1518-03-12 00:57] wakes up [1518-03-23 00:23] falls asleep [1518-03-02 23:48] Guard #3391 begins shift [1518-05-14 23:52] Guard #733 begins shift [1518-08-15 00:55] wakes up [1518-08-14 00:54] wakes up [1518-06-08 00:30] falls asleep [1518-02-18 00:58] wakes up [1518-11-03 00:58] wakes up [1518-06-17 00:00] Guard #2221 begins shift [1518-04-05 00:14] falls asleep [1518-08-29 00:01] falls asleep [1518-05-14 00:13] wakes up [1518-10-25 00:50] wakes up [1518-06-24 00:03] Guard #739 begins shift [1518-10-26 00:54] wakes up [1518-08-17 00:14] falls asleep [1518-10-04 00:03] Guard #3407 begins shift [1518-06-05 00:30] wakes up [1518-06-09 23:59] Guard #2221 begins shift [1518-09-19 00:59] wakes up [1518-10-05 23:56] Guard #3203 begins shift [1518-05-02 00:03] falls asleep [1518-09-25 00:03] falls asleep [1518-09-11 00:42] falls asleep [1518-07-08 00:08] falls asleep [1518-05-07 00:58] wakes up [1518-07-24 00:58] wakes up [1518-04-12 00:21] wakes up [1518-10-29 00:29] falls asleep [1518-07-28 23:56] Guard #3391 begins shift [1518-07-16 00:23] falls asleep [1518-06-04 00:00] Guard #2713 begins shift [1518-08-29 00:07] wakes up [1518-08-31 00:46] falls asleep [1518-03-14 00:54] wakes up [1518-09-29 00:04] Guard #2383 begins shift [1518-08-07 00:56] wakes up [1518-06-02 00:56] falls asleep [1518-03-12 00:19] wakes up [1518-04-28 00:52] wakes up [1518-07-13 00:58] wakes up [1518-04-08 23:57] Guard #3203 begins shift [1518-04-05 00:49] wakes up [1518-07-03 00:22] falls asleep [1518-02-12 00:53] wakes up [1518-09-24 00:03] Guard #733 begins shift [1518-07-30 00:01] Guard #1163 begins shift [1518-03-16 00:00] Guard #739 begins shift [1518-08-18 00:50] wakes up [1518-03-22 00:57] wakes up [1518-06-02 00:04] Guard #3391 begins shift [1518-09-01 00:02] falls asleep [1518-09-11 00:49] wakes up [1518-04-13 00:41] falls asleep [1518-04-18 00:53] wakes up [1518-03-21 00:38] wakes up [1518-06-02 00:52] wakes up [1518-07-18 23:59] Guard #733 begins shift [1518-06-25 00:59] wakes up [1518-04-07 23:54] Guard #2713 begins shift [1518-06-28 00:14] falls asleep [1518-03-04 00:04] Guard #1663 begins shift [1518-05-27 00:04] falls asleep [1518-10-08 00:31] falls asleep [1518-11-05 00:16] falls asleep [1518-05-14 00:53] falls asleep [1518-10-04 00:47] wakes up [1518-09-07 00:11] falls asleep [1518-09-25 23:48] Guard #2297 begins shift [1518-10-26 00:00] Guard #1663 begins shift [1518-03-11 00:56] wakes up [1518-08-28 23:49] Guard #1663 begins shift [1518-08-31 00:47] wakes up [1518-09-04 00:52] falls asleep [1518-11-16 00:38] falls asleep [1518-10-19 00:59] wakes up [1518-10-19 00:23] falls asleep [1518-05-01 00:23] falls asleep [1518-05-15 23:56] Guard #3391 begins shift [1518-07-01 00:07] falls asleep [1518-07-30 00:52] falls asleep [1518-05-12 00:27] falls asleep [1518-04-04 00:07] falls asleep [1518-06-09 00:58] wakes up [1518-02-28 00:16] falls asleep [1518-09-05 00:30] falls asleep [1518-05-06 00:52] falls asleep [1518-10-21 00:02] Guard #733 begins shift [1518-07-30 00:56] wakes up [1518-09-30 00:13] falls asleep [1518-10-16 23:58] Guard #997 begins shift [1518-05-26 00:03] Guard #61 begins shift [1518-06-08 00:25] wakes up [1518-07-11 00:01] Guard #1367 begins shift [1518-07-15 00:02] Guard #61 begins shift [1518-10-26 00:50] falls asleep [1518-05-26 00:45] falls asleep [1518-07-16 00:00] Guard #739 begins shift [1518-09-18 00:04] Guard #3407 begins shift [1518-03-22 00:53] falls asleep [1518-06-25 00:16] falls asleep [1518-06-27 23:59] Guard #2609 begins shift [1518-09-16 00:41] falls asleep [1518-08-20 00:58] wakes up [1518-02-13 00:02] Guard #3407 begins shift [1518-02-23 00:50] wakes up [1518-05-28 00:00] Guard #61 begins shift [1518-04-06 00:39] wakes up [1518-11-21 00:42] wakes up [1518-07-06 00:12] wakes up [1518-08-11 00:00] Guard #2297 begins shift [1518-06-04 00:18] falls asleep [1518-09-07 00:49] wakes up [1518-06-27 00:56] wakes up [1518-09-25 00:38] wakes up [1518-04-06 00:19] wakes up [1518-09-21 00:02] falls asleep [1518-03-15 00:38] wakes up [1518-11-10 00:00] Guard #2297 begins shift [1518-08-31 00:14] falls asleep [1518-02-09 00:38] wakes up [1518-10-22 00:01] falls asleep [1518-06-11 00:52] wakes up [1518-04-20 00:39] falls asleep [1518-04-08 00:57] wakes up [1518-05-17 23:50] Guard #733 begins shift [1518-02-10 00:47] wakes up [1518-09-23 00:00] Guard #1163 begins shift [1518-10-04 00:22] falls asleep [1518-02-08 00:09] falls asleep [1518-10-16 00:44] falls asleep [1518-07-01 23:59] Guard #1367 begins shift [1518-10-16 00:50] wakes up [1518-05-15 00:17] falls asleep [1518-07-30 00:40] wakes up [1518-10-16 00:28] falls asleep [1518-04-06 00:37] falls asleep [1518-03-08 00:23] wakes up [1518-06-04 00:54] falls asleep [1518-09-12 00:45] wakes up [1518-03-15 00:12] falls asleep [1518-05-23 00:22] falls asleep [1518-07-28 00:00] Guard #907 begins shift [1518-08-22 00:56] wakes up [1518-08-24 00:33] falls asleep [1518-04-22 00:00] Guard #739 begins shift [1518-02-13 23:57] Guard #1367 begins shift [1518-07-09 00:49] falls asleep [1518-10-09 00:20] falls asleep [1518-04-01 23:56] Guard #941 begins shift [1518-10-16 00:00] Guard #113 begins shift [1518-09-21 00:34] falls asleep [1518-07-23 00:35] wakes up [1518-03-01 00:12] falls asleep [1518-02-03 23:50] Guard #661 begins shift [1518-09-09 00:56] wakes up [1518-03-07 00:22] falls asleep [1518-08-21 00:53] wakes up [1518-09-04 00:01] Guard #2297 begins shift [1518-08-10 00:58] wakes up [1518-07-03 23:56] Guard #3407 begins shift [1518-08-26 00:42] falls asleep [1518-11-13 23:56] Guard #907 begins shift [1518-10-15 00:16] falls asleep [1518-08-16 00:44] falls asleep [1518-07-18 00:01] Guard #2609 begins shift [1518-10-20 00:22] wakes up [1518-10-24 00:01] Guard #2609 begins shift [1518-04-28 00:55] falls asleep [1518-02-11 00:00] Guard #1367 begins shift [1518-06-19 00:39] wakes up [1518-09-27 00:04] falls asleep [1518-04-19 00:46] falls asleep [1518-08-10 00:31] falls asleep [1518-09-21 23:48] Guard #2713 begins shift [1518-09-10 23:57] Guard #997 begins shift [1518-10-13 00:55] falls asleep [1518-08-20 23:59] Guard #3203 begins shift [1518-06-27 00:33] falls asleep [1518-05-10 00:00] Guard #739 begins shift [1518-08-30 00:00] Guard #2609 begins shift [1518-09-05 00:24] wakes up [1518-09-11 00:58] wakes up [1518-07-08 00:39] falls asleep [1518-08-22 00:20] wakes up [1518-07-29 00:43] wakes up [1518-08-22 00:14] falls asleep [1518-08-02 00:53] wakes up [1518-11-17 00:24] falls asleep [1518-03-25 00:11] falls asleep [1518-03-06 00:48] wakes up [1518-09-12 00:43] falls asleep [1518-10-20 00:57] wakes up [1518-04-04 23:57] Guard #733 begins shift [1518-09-03 00:58] wakes up [1518-09-16 00:59] wakes up [1518-07-23 00:00] Guard #2113 begins shift [1518-09-04 00:59] wakes up [1518-09-11 00:53] falls asleep [1518-04-08 00:54] falls asleep [1518-08-07 00:03] Guard #859 begins shift [1518-08-04 23:49] Guard #2297 begins shift [1518-05-23 00:51] wakes up [1518-11-01 23:58] Guard #907 begins shift [1518-02-05 23:56] Guard #419 begins shift [1518-08-17 00:01] Guard #3391 begins shift [1518-09-27 23:58] Guard #3391 begins shift [1518-03-16 00:35] falls asleep [1518-08-17 23:57] Guard #113 begins shift [1518-02-07 00:44] wakes up [1518-08-18 00:24] falls asleep [1518-11-01 00:00] Guard #661 begins shift [1518-10-19 00:39] wakes up [1518-08-24 23:59] Guard #997 begins shift [1518-05-18 00:04] falls asleep [1518-03-17 00:30] falls asleep [1518-04-08 00:51] wakes up [1518-08-24 00:53] wakes up [1518-09-22 00:03] wakes up [1518-06-08 00:59] wakes up [1518-04-10 00:56] wakes up [1518-05-22 00:01] Guard #2383 begins shift [1518-06-01 00:00] Guard #661 begins shift [1518-08-22 23:58] Guard #997 begins shift [1518-03-22 00:42] wakes up [1518-10-21 00:51] falls asleep [1518-11-11 23:48] Guard #997 begins shift [1518-05-01 00:00] Guard #1163 begins shift [1518-05-20 23:56] Guard #3203 begins shift [1518-10-04 00:37] falls asleep [1518-08-24 00:00] falls asleep [1518-09-18 00:25] falls asleep [1518-10-13 00:49] wakes up [1518-11-23 00:53] wakes up [1518-04-20 00:00] falls asleep [1518-10-06 00:12] falls asleep [1518-08-27 00:42] wakes up [1518-09-24 00:54] falls asleep [1518-06-25 00:00] Guard #2713 begins shift [1518-07-30 00:29] falls asleep [1518-10-13 00:10] falls asleep [1518-09-22 00:18] wakes up [1518-03-06 00:00] Guard #2113 begins shift [1518-05-17 00:22] falls asleep [1518-02-17 23:50] Guard #2297 begins shift [1518-04-24 00:26] falls asleep [1518-07-26 00:21] falls asleep [1518-03-25 00:27] wakes up [1518-06-07 00:52] falls asleep [1518-04-16 00:23] falls asleep [1518-11-01 00:41] wakes up [1518-06-29 00:23] wakes up [1518-08-01 00:40] wakes up [1518-07-06 00:42] wakes up [1518-08-13 00:18] falls asleep [1518-06-13 00:50] wakes up [1518-09-15 00:38] falls asleep [1518-10-05 00:46] falls asleep [1518-10-05 00:00] Guard #3407 begins shift [1518-06-01 00:55] wakes up [1518-09-04 00:35] falls asleep [1518-09-24 00:59] wakes up [1518-09-24 00:33] wakes up [1518-02-04 00:01] falls asleep [1518-02-23 00:07] falls asleep [1518-05-03 00:38] falls asleep [1518-09-17 00:49] wakes up [1518-03-20 00:52] wakes up [1518-08-19 00:55] falls asleep [1518-04-06 00:56] wakes up [1518-05-30 00:56] wakes up [1518-09-13 23:47] Guard #1663 begins shift [1518-04-12 00:50] wakes up [1518-06-08 00:04] Guard #1663 begins shift [1518-04-12 00:09] falls asleep [1518-05-31 00:34] wakes up [1518-02-07 00:08] falls asleep [1518-09-02 00:22] falls asleep [1518-09-18 00:53] wakes up [1518-07-11 00:13] falls asleep [1518-04-25 00:56] wakes up [1518-04-19 23:50] Guard #739 begins shift [1518-03-12 00:18] falls asleep [1518-08-07 00:45] wakes up [1518-03-14 00:29] falls asleep [1518-10-30 00:45] falls asleep [1518-06-20 00:00] Guard #997 begins shift [1518-06-21 00:07] falls asleep [1518-03-05 00:13] falls asleep [1518-04-15 23:58] Guard #2383 begins shift [1518-10-27 00:25] falls asleep [1518-06-23 00:51] wakes up [1518-07-21 00:00] Guard #2221 begins shift [1518-10-01 00:33] wakes up [1518-04-24 00:44] wakes up [1518-03-21 00:27] falls asleep [1518-02-22 00:08] falls asleep [1518-10-05 00:47] wakes up [1518-03-23 00:40] wakes up [1518-11-19 00:15] falls asleep [1518-02-21 23:57] Guard #2297 begins shift [1518-09-08 00:40] wakes up [1518-11-05 00:47] falls asleep [1518-02-24 00:59] wakes up [1518-11-06 00:12] falls asleep [1518-10-28 00:23] falls asleep [1518-09-20 00:04] Guard #2713 begins shift [1518-11-15 00:33] falls asleep [1518-09-05 00:50] wakes up [1518-06-17 00:59] wakes up [1518-06-08 00:08] wakes up [1518-02-18 00:04] falls asleep [1518-08-13 00:41] wakes up [1518-09-19 00:21] falls asleep [1518-11-13 00:58] wakes up [1518-08-31 00:36] falls asleep [1518-07-02 00:53] falls asleep [1518-08-23 00:41] wakes up [1518-09-14 23:57] Guard #2713 begins shift [1518-07-24 00:44] falls asleep [1518-02-13 00:51] wakes up [1518-06-18 23:59] Guard #61 begins shift [1518-08-02 00:03] Guard #1367 begins shift [1518-06-15 00:38] falls asleep [1518-10-01 00:02] falls asleep [1518-10-16 00:39] wakes up [1518-10-11 00:50] wakes up [1518-07-02 00:25] falls asleep [1518-02-17 00:39] wakes up [1518-07-11 00:20] wakes up [1518-06-23 00:04] Guard #1367 begins shift [1518-11-11 00:27] falls asleep [1518-10-18 00:47] wakes up [1518-03-10 00:01] Guard #997 begins shift [1518-05-30 23:56] Guard #997 begins shift [1518-07-09 00:24] falls asleep [1518-02-28 23:57] Guard #859 begins shift [1518-05-08 00:29] wakes up [1518-03-08 00:41] wakes up [1518-08-25 00:57] wakes up [1518-11-03 00:56] falls asleep [1518-05-06 00:01] Guard #733 begins shift [1518-11-19 23:50] Guard #3203 begins shift [1518-06-03 00:56] wakes up [1518-10-18 00:57] falls asleep [1518-11-15 00:16] wakes up [1518-07-12 00:54] falls asleep [1518-09-19 00:57] falls asleep [1518-03-31 00:58] wakes up [1518-05-18 00:57] wakes up [1518-10-19 00:03] Guard #419 begins shift [1518-04-25 00:42] falls asleep [1518-11-10 00:59] wakes up [1518-05-14 00:57] wakes up [1518-07-31 00:16] falls asleep [1518-11-04 00:02] Guard #1367 begins shift [1518-07-02 23:59] Guard #661 begins shift [1518-06-27 00:04] Guard #661 begins shift [1518-02-06 00:18] falls asleep [1518-04-29 00:37] falls asleep [1518-05-29 00:40] wakes up [1518-08-25 00:35] falls asleep [1518-06-12 00:29] wakes up [1518-08-09 00:02] Guard #2297 begins shift [1518-06-25 00:53] falls asleep [1518-03-29 00:42] wakes up [1518-03-22 00:37] falls asleep [1518-02-14 00:34] wakes up [1518-02-12 00:52] falls asleep [1518-08-06 00:53] wakes up [1518-09-02 00:00] Guard #3407 begins shift [1518-10-02 00:34] wakes up [1518-10-27 00:01] Guard #1663 begins shift [1518-09-16 00:01] Guard #859 begins shift [1518-10-07 00:34] wakes up [1518-03-05 00:48] wakes up [1518-03-24 00:21] falls asleep [1518-03-10 00:24] falls asleep [1518-10-03 00:23] falls asleep [1518-11-03 00:49] wakes up [1518-07-15 00:53] falls asleep [1518-10-09 00:35] wakes up [1518-10-12 00:49] wakes up [1518-03-01 23:57] Guard #3407 begins shift [1518-06-05 00:46] falls asleep [1518-05-02 23:50] Guard #1163 begins shift [1518-04-06 00:01] falls asleep [1518-07-05 00:40] wakes up [1518-05-26 23:53] Guard #113 begins shift [1518-10-24 00:51] wakes up [1518-10-29 00:09] falls asleep [1518-03-07 23:57] Guard #859 begins shift [1518-06-07 00:45] wakes up [1518-03-01 00:16] wakes up [1518-06-16 00:41] falls asleep [1518-04-19 00:37] falls asleep [1518-04-25 00:11] falls asleep [1518-03-19 23:57] Guard #733 begins shift [1518-11-15 00:13] falls asleep [1518-10-13 00:00] Guard #733 begins shift [1518-02-20 00:03] falls asleep [1518-09-08 00:26] falls asleep [1518-07-25 00:58] wakes up [1518-04-23 00:03] Guard #349 begins shift [1518-06-11 00:51] falls asleep [1518-05-11 00:53] falls asleep [1518-02-20 00:11] wakes up [1518-10-29 00:16] wakes up [1518-08-17 00:55] wakes up [1518-08-01 00:35] falls asleep [1518-05-26 00:52] wakes up [1518-11-18 00:55] wakes up [1518-02-12 00:57] falls asleep [1518-02-15 00:12] falls asleep [1518-09-06 00:44] wakes up [1518-03-18 23:48] Guard #1163 begins shift [1518-10-01 00:42] falls asleep [1518-02-26 00:12] falls asleep [1518-03-28 00:56] wakes up [1518-06-06 00:46] wakes up [1518-10-10 00:54] wakes up [1518-11-18 23:59] Guard #419 begins shift [1518-10-21 00:07] falls asleep [1518-03-13 00:34] wakes up [1518-04-21 00:55] wakes up [1518-09-07 00:23] wakes up [1518-03-09 00:46] wakes up [1518-03-29 00:08] falls asleep [1518-05-11 00:42] falls asleep [1518-08-12 00:41] wakes up [1518-08-05 00:39] wakes up [1518-07-19 23:56] Guard #3391 begins shift [1518-10-08 00:03] Guard #1367 begins shift [1518-05-08 00:26] falls asleep [1518-02-05 00:53] wakes up [1518-03-11 00:10] falls asleep [1518-05-06 00:59] wakes up [1518-03-23 00:32] wakes up [1518-08-19 00:59] wakes up [1518-07-02 00:35] wakes up [1518-10-04 00:33] wakes up [1518-04-26 00:26] falls asleep [1518-04-27 00:45] falls asleep [1518-02-19 00:37] wakes up [1518-07-12 23:58] Guard #2297 begins shift [1518-09-19 00:02] Guard #1663 begins shift [1518-08-23 00:47] falls asleep [1518-03-03 00:28] wakes up [1518-05-13 00:43] wakes up [1518-09-10 00:04] Guard #859 begins shift [1518-09-27 00:28] wakes up [1518-04-11 23:56] Guard #739 begins shift [1518-04-11 00:11] wakes up [1518-05-31 00:44] wakes up [1518-06-08 00:07] falls asleep [1518-09-06 00:19] wakes up [1518-08-02 23:50] Guard #419 begins shift [1518-08-08 00:54] wakes up [1518-08-19 00:06] falls asleep [1518-10-14 00:57] falls asleep [1518-08-27 00:01] falls asleep [1518-08-24 00:07] wakes up [1518-04-26 00:03] Guard #419 begins shift [1518-08-27 00:58] wakes up [1518-07-09 00:45] wakes up [1518-07-20 00:18] falls asleep [1518-07-06 00:38] falls asleep [1518-04-22 00:39] wakes up [1518-05-11 00:58] wakes up [1518-07-04 00:50] wakes up [1518-09-09 00:01] Guard #733 begins shift [1518-07-09 00:54] wakes up [1518-10-30 23:56] Guard #733 begins shift [1518-11-13 00:00] Guard #3407 begins shift [1518-04-27 00:00] Guard #739 begins shift [1518-08-29 00:59] wakes up [1518-10-14 00:43] wakes up [1518-03-24 00:41] wakes up [1518-06-05 00:34] falls asleep [1518-05-07 00:37] falls asleep [1518-04-13 23:57] Guard #733 begins shift [1518-04-30 00:03] Guard #733 begins shift [1518-07-05 00:01] Guard #419 begins shift [1518-10-26 00:31] falls asleep [1518-08-12 00:15] falls asleep [1518-11-08 00:54] falls asleep [1518-03-06 23:59] Guard #997 begins shift [1518-06-18 00:55] wakes up [1518-11-09 00:21] falls asleep [1518-04-02 23:51] Guard #2113 begins shift [1518-06-05 00:57] wakes up [1518-08-11 23:57] Guard #997 begins shift [1518-06-18 00:39] wakes up [1518-11-12 00:46] wakes up [1518-06-03 00:46] falls asleep [1518-08-30 00:48] wakes up [1518-06-02 23:58] Guard #859 begins shift [1518-07-13 00:56] falls asleep [1518-11-03 00:36] falls asleep [1518-02-12 00:39] wakes up [1518-04-09 00:14] falls asleep [1518-07-10 00:34] wakes up [1518-06-08 00:18] falls asleep [1518-09-04 23:58] Guard #1663 begins shift [1518-05-12 00:52] wakes up [1518-09-30 23:48] Guard #3407 begins shift [1518-08-10 00:17] wakes up [1518-03-29 23:56] Guard #2221 begins shift [1518-06-29 00:55] wakes up [1518-09-10 00:57] falls asleep [1518-04-01 00:02] falls asleep [1518-07-13 00:34] falls asleep [1518-06-17 00:15] falls asleep [1518-04-19 00:00] Guard #997 begins shift [1518-10-13 00:59] wakes up [1518-10-26 00:46] wakes up [1518-02-21 00:56] wakes up [1518-04-25 00:37] wakes up [1518-03-24 00:02] Guard #113 begins shift [1518-04-26 00:49] wakes up [1518-03-18 00:50] wakes up [1518-03-08 00:37] falls asleep [1518-08-15 00:50] falls asleep [1518-03-25 00:42] wakes up [1518-02-14 00:37] falls asleep [1518-11-10 23:58] Guard #2221 begins shift [1518-06-05 00:40] wakes up [1518-07-21 00:34] wakes up [1518-10-01 00:51] wakes up [1518-09-17 00:48] falls asleep [1518-05-17 00:54] wakes up [1518-02-27 00:47] wakes up [1518-09-03 00:19] falls asleep [1518-06-16 00:58] wakes up [1518-02-10 00:16] falls asleep [1518-05-09 00:55] wakes up [1518-07-31 00:01] Guard #1367 begins shift [1518-09-05 00:11] falls asleep [1518-02-25 00:51] wakes up [1518-06-16 00:20] wakes up [1518-04-20 00:01] wakes up [1518-07-16 00:59] wakes up [1518-10-22 00:53] wakes up [1518-07-05 00:21] falls asleep [1518-08-26 23:47] Guard #3407 begins shift [1518-09-06 23:59] Guard #2297 begins shift [1518-05-12 00:00] Guard #113 begins shift [1518-06-13 00:35] wakes up [1518-07-24 00:04] Guard #2221 begins shift [1518-02-16 00:04] falls asleep [1518-09-20 00:57] wakes up [1518-10-25 00:38] falls asleep [1518-03-13 00:18] falls asleep [1518-05-25 00:26] falls asleep [1518-02-22 00:53] wakes up [1518-03-28 00:42] wakes up [1518-02-23 00:04] Guard #419 begins shift [1518-03-13 23:59] Guard #3407 begins shift [1518-10-02 00:32] falls asleep [1518-05-03 00:50] falls asleep [1518-10-27 00:54] wakes up [1518-02-08 00:00] Guard #2383 begins shift [1518-03-25 00:35] falls asleep [1518-08-19 00:40] wakes up [1518-08-07 00:53] falls asleep [1518-02-14 00:31] falls asleep [1518-08-26 00:04] Guard #2383 begins shift [1518-04-15 00:03] Guard #661 begins shift [1518-02-27 00:09] falls asleep [1518-09-04 00:41] wakes up [1518-08-20 00:00] Guard #739 begins shift [1518-03-31 23:53] Guard #419 begins shift [1518-10-17 00:58] wakes up [1518-07-24 00:56] falls asleep [1518-10-23 00:24] wakes up [1518-08-18 23:56] Guard #1163 begins shift [1518-06-05 00:12] falls asleep [1518-04-14 00:56] wakes up [1518-07-14 00:00] Guard #2713 begins shift [1518-04-28 00:57] wakes up [1518-05-07 00:02] Guard #1367 begins shift [1518-05-15 00:01] falls asleep [1518-10-11 23:59] Guard #3391 begins shift [1518-10-14 00:38] falls asleep [1518-06-12 00:17] falls asleep [1518-05-24 23:59] Guard #997 begins shift [1518-11-17 00:53] wakes up [1518-03-09 00:10] wakes up [1518-03-28 00:17] falls asleep [1518-10-30 00:50] wakes up [1518-02-13 00:35] falls asleep [1518-09-10 00:54] wakes up """.trimIndent()
0
Kotlin
0
0
ac62ce8aeaed065f8fbd11e30368bfe5d31b7033
43,059
AdventOfCode
Creative Commons Zero v1.0 Universal
src/main/kotlin/Day09.kt
AlmazKo
576,500,782
false
{"Kotlin": 26733}
import kotlin.math.abs object Day09 : Task { @JvmStatic fun main(args: Array<String>) = execute(false) override fun part1(input: Iterable<String>): Any { val rope = Rope(2) input.map(::parse).forEach(rope::move) return rope.visited.size } override fun part2(input: Iterable<String>): Any { val rope = Rope(10) input.map(::parse).forEach(rope::move) return rope.visited.size } data class Move(val direction: Dir, val steps: Int) data class Coord(var x: Int, var y: Int) enum class Dir { U, D, R, L } class Rope(len: Int) { val chain = Array(len) { Coord(0, 0) } var visited = HashSet<Coord>().apply { add(chain.last().copy()) } fun move(mv: Move) { val head = chain[0] when (mv.direction) { Dir.U -> repeat(mv.steps) { head.y += 1; rearrange() } Dir.D -> repeat(mv.steps) { head.y -= 1; rearrange() } Dir.R -> repeat(mv.steps) { head.x += 1; rearrange() } Dir.L -> repeat(mv.steps) { head.x -= 1; rearrange() } } } private fun rearrange() { (1 until chain.size).forEach { val tail = chain[it] val head = chain[it - 1] val moved = rearrange(tail, head) if (moved && it == chain.size - 1) { visited.add(tail.copy()) } if (!moved) return } } private fun rearrange(tail: Coord, head: Coord): Boolean { val distX = abs(tail.x - head.x) val distY = abs(tail.y - head.y) if (distX <= 1 && distY <= 1) { return false } if (distX == 0) { tail.y += (if (tail.y > head.y) -1 else 1) } else if (distY == 0) { tail.x += (if (tail.x > head.x) -1 else 1) } else { tail.x += (if (tail.x > head.x) -1 else 1) tail.y += (if (tail.y > head.y) -1 else 1) } return true } } // --- util fun parse(row: String): Move { val split = row.split(' ') val dir = Dir.valueOf(split[0]); val steps = split[1].toInt() return Move(dir, steps) } fun Rope.dump() { println(toDebugString()) } fun Rope.toDebugString() = buildString { (10 downTo -10).forEach { y -> (-10..10).forEach { x -> chain.forEachIndexed { i, c -> if (c.x == x && c.y == y) { if (i == 0) append('H') else append(i) return@forEach } } append('.') } append('\n') } } }
0
Kotlin
0
1
109cb10927328ce296a6b0a3600edbc6e7f0dc9f
2,861
advent2022
MIT License
2015/src/main/kotlin/com/koenv/adventofcode/Day11.kt
koesie10
47,333,954
false
null
package com.koenv.adventofcode object Day11 { public fun satisfiesRequirements(input: String): Boolean { val satisfies1 = input.mapIndexed { i, c -> if (i == 0 || i == 1) { return@mapIndexed false } val previous1 = input[i - 2].toInt() val previous2 = input[i - 1].toInt() val current = c.toInt() return@mapIndexed ((previous1 + 1) == previous2 && (previous2 + 1) == current) }.any { it } val satisfies2 = input.map { it != 'i' && it != 'o' && it != 'l' }.all { it } var pairs: MutableSet<Char> = hashSetOf() input.forEachIndexed { i, c -> if (i == 0) { return@forEachIndexed } if (c == input[i - 1] && input[i - 2] != c) { pairs.add(c) } } val satisfies3 = pairs.size >= 2 return satisfies1 && satisfies2 && satisfies3 } public fun nextPassword(input: String): String { val result = CharArray(input.length) for (i in (input.length - 1) downTo 0) { var c = input[i] if (i == (input.length - 1)) { c++ } else if (result.getOrElse(i + 1, { 'a' }) > 'z') { c++ } result[i] = c } return String( result.map { if (it > 'z') { return@map 'a' } it }.toCharArray() ) } public fun findNextPasswordSatisfyingRequirements(currentPassword: String): String { var newPassword: String = currentPassword do { newPassword = nextPassword(newPassword) } while (!satisfiesRequirements(newPassword)) return newPassword } }
0
Kotlin
0
0
29f3d426cfceaa131371df09785fa6598405a55f
1,859
AdventOfCode-Solutions-Kotlin
MIT License
src/day4/Day04.kt
dean95
571,923,107
false
{"Kotlin": 21240}
package day4 import readInput private fun main() { fun part1(input: List<String>): Int { var result = 0 input.forEach { line -> val (range1, range2) = line.split(",").map { val (s, e) = it.split("-") s.toInt() to e.toInt() } val (range1Start, range1End) = range1 val (range2Start, range2End) = range2 if (range1End - range1Start < range2End - range2Start) { if (range1Start >= range2Start && range1End <= range2End) result++ } else { if (range2Start >= range1Start && range2End <= range1End) result++ } } return result } fun part2(input: List<String>): Int { var result = 0 input.forEach { line -> val (range1, range2) = line.split(",").map { val (s, e) = it.split("-") s.toInt() to e.toInt() } val (range1Start, range1End) = range1 val (range2Start, range2End) = range2 if (range1Start < range2Start) { if (range1End >= range2Start) result++ } else { if (range2End >= range1Start) result++ } } return result } val testInput = readInput("day4/Day04_test") println(part2(testInput)) check(part1(testInput) == 2) check(part2(testInput) == 4) val input = readInput("day4/Day04") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
0ddf1bdaf9bcbb45116c70d7328b606c2a75e5a5
1,536
advent-of-code-2022
Apache License 2.0
src/Day13.kt
zt64
572,594,597
false
null
import kotlin.math.min private object Day13 : Day(13) { private fun buildPacket(string: String) = buildList<Any> { val stack = mutableListOf<MutableList<Any>>() var tempNum = "" string.forEach { char -> if (char.isDigit()) { tempNum += char.digitToInt() } else { if (tempNum.isNotBlank()) { stack.last() += tempNum.toInt() tempNum = "" } when (char) { '[' -> { val last = stack.lastOrNull() val list = mutableListOf<Any>() stack += list if (last != null) last.add(list) else add(list) } ']' -> stack.removeLast() } } } } private val pairs = input.split("\n\n").map { pairs -> val (firstPacket, secondPacket) = pairs.lines() buildPacket(firstPacket) to buildPacket(secondPacket) } override fun part1(): Int { var sum = 0 pairs.forEachIndexed { index, (firstPacket, secondPacket) -> if (firstPacket < secondPacket) sum += index + 1 } return sum } override fun part2(): Int { val dividerPacket1 = buildPacket("[[2]]") val dividerPacket2 = buildPacket("[[6]]") val sorted = buildList { pairs.forEach { (packet1, packet2) -> add(packet1) add(packet2) } add(dividerPacket1) add(dividerPacket2) sortWith(List<Any>::compareTo) } return (sorted.indexOf(dividerPacket1) + 1) * (sorted.indexOf(dividerPacket2) + 1) } } private operator fun Any.compareTo(right: Any): Int { val left = this @Suppress("UNCHECKED_CAST") // Shouldn't be needed, but Kotlin doesn't know that the lists are lists of Any return when { left is List<*> && right is List<*> -> { left as List<Any> right as List<Any> for (i in 0 until min(left.size, right.size)) { if (left[i] < right[i]) return -1 if (right[i] < left[i]) return 1 } return left.size.compareTo(right.size) // left is shorter, in right order } left is Int && right is Int -> left.compareTo(right) left is Int && right is List<*> -> listOf(left).compareTo(right as List<Any>) left is List<*> && right is Int -> (left as List<Any>).compareTo(listOf(right)) else -> throw IllegalArgumentException("Invalid input") } } private fun main() = Day13.main()
0
Kotlin
0
0
4e4e7ed23d665b33eb10be59670b38d6a5af485d
2,721
aoc-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/AverageOfLevelsInBinaryTree.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue fun interface AverageOfLevelsInBinaryTreeStrategy { operator fun invoke(root: TreeNode?): DoubleArray } // Using Depth First Search class AverageOfLevelsInBinaryTreeDFS : AverageOfLevelsInBinaryTreeStrategy { override operator fun invoke(root: TreeNode?): DoubleArray { val count: MutableList<Int> = ArrayList() val res: MutableList<Double> = ArrayList() average(root, 0, res, count) for (i in res.indices) res[i] = res[i] / count[i] return res.toDoubleArray() } fun average(t: TreeNode?, i: Int, sum: MutableList<Double>, count: MutableList<Int>) { if (t == null) return if (i < sum.size) { sum[i] = sum[i] + t.value count[i] = count[i] + 1 } else { sum.add(1.0 * t.value) count.add(1) } average(t.left, i + 1, sum, count) average(t.right, i + 1, sum, count) } } // Using Breadth First Search class AverageOfLevelsInBinaryTreeBFS : AverageOfLevelsInBinaryTreeStrategy { override operator fun invoke(root: TreeNode?): DoubleArray { val res: MutableList<Double> = ArrayList() var queue: Queue<TreeNode?> = LinkedList() queue.add(root) while (queue.isNotEmpty()) { var sum: Long = 0 var count: Long = 0 val temp: Queue<TreeNode?> = LinkedList() while (queue.isNotEmpty()) { val n: TreeNode? = queue.remove() if (n != null) { sum += n.value count++ if (n.left != null) temp.add(n.left) if (n.right != null) temp.add(n.right) } } queue = temp res.add(sum * 1.0 / count) } return res.toDoubleArray() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,520
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/FruitIntoBaskets.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 904. Fruit Into Baskets * @see <a href="https://leetcode.com/problems/fruit-into-baskets/">Source</a> */ fun interface FruitIntoBaskets { fun totalFruit(fruits: IntArray): Int } class FruitIntoBasketsSlidingWindow : FruitIntoBaskets { override fun totalFruit(fruits: IntArray): Int { val count: MutableMap<Int, Int> = HashMap() var i = 0 var j = 0 while (j < fruits.size) { count[fruits[j]] = (count[fruits[j]] ?: 0) + 1 if (count.size > 2) { count[fruits[i]] = count.getOrDefault(fruits[i], 0) - 1 count.remove(fruits[i++], 0) } ++j } return j - i } } class FruitIntoBasketsSlidingWindow2 : FruitIntoBaskets { override fun totalFruit(fruits: IntArray): Int { val count: MutableMap<Int, Int> = HashMap() var res = 0 var i = 0 for (j in fruits.indices) { count[fruits[j]] = (count[fruits[j]] ?: 0) + 1 while (count.size > 2) { count[fruits[i]] = count.getOrDefault(fruits[i], 0) - 1 if (count[fruits[i]] == 0) count.remove(fruits[i]) i++ } res = max(res, j - i + 1) } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,951
kotlab
Apache License 2.0
algorithms/src/main/kotlin/com/kotlinground/algorithms/twopointers/mergesortedarray/merge.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.algorithms.twopointers.mergesortedarray /** * Uses a 2 pointer approach to merge to sorted arrays. * The first pointer i points to the last element of the subarray of size m in the nums1 array, * the second pointer j points to the last element of the nums2 array of size n. * The pointer k points to the end of the array nums1 of size m + n. * * Until the pointer j reaches 0 (that is, until we reach the beginning of the nums2 array), we check the following * conditions: * * - If the pointer i < 0 (i.e. we have reached the beginning of the nums1 array) OR nums1[i] < nums2[j] => * write nums2[j] to nums1[k] and then decrease the value of j and k by 1 * - In all other cases, write nums1[i] to nums1[k] and then decrease the value of i and k by 1 * * Complexity * Time complexity: O(n+m) * Space complexity: O(1) */ fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int) { var i = m - 1 var j = n - 1 var k = m + n - 1 while (j >= 0) { nums1[k--] = if (i < 0 || nums1[i] < nums2[j]) { nums2[j--] } else { nums1[i--] } } }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
1,145
KotlinGround
MIT License
src/main/kotlin/day5/Solution.kt
krazyglitch
573,086,664
false
{"Kotlin": 31494}
package day5 import util.Utils import java.time.Duration import java.time.LocalDateTime import kotlin.collections.ArrayList class Solution { private val stacks = ArrayList<ArrayDeque<Char>>() private val instructionRegex = Regex("move (\\d+) from (\\d) to (\\d)") // Parse the crate diagram and return only instructions private fun parseDiagram(data: List<String>): List<String> { stacks.clear() val emptyLinePos = (data.indices).find { data[it] == "" } ?: 0 val stackBottomPos = emptyLinePos - 2 val lastBracketPos = data[stackBottomPos].lastIndexOf(']') val stackCount = (lastBracketPos)/4 + 1 (0 until stackCount).forEach { _ -> stacks.add(ArrayDeque()) } (stackBottomPos downTo 0).forEach { y -> (1 until lastBracketPos step 4).forEach { x -> if (data[y][x] != ' ') stacks[(x+3)/4 - 1].add(data[y][x]) } } val instructionsPos = emptyLinePos + 1 return data.subList(instructionsPos, data.size) } private fun processSingleInstruction(moves: Int, origin: Int, destination: Int) { if (moves == 0) return val crate = stacks[origin-1].removeLast() stacks[destination-1].add(crate) processSingleInstruction(moves-1, origin, destination) } private fun processMultipleInstructions(crates: Int, origin: Int, destination: Int) { val movingCrates = ArrayDeque<Char>() repeat(crates) { movingCrates.add(stacks[origin - 1].removeLast()) } while (movingCrates.isNotEmpty()) stacks[destination-1].add(movingCrates.removeLast()) } fun part1(data: List<String>): String { val instructions = parseDiagram(data) (instructions).forEach { val match = instructionRegex.find(it) val (movesStr, originStr, destinationStr) = match!!.destructured val moves = movesStr.toInt() val origin = originStr.toInt() val destination = destinationStr.toInt() processSingleInstruction(moves, origin, destination) } return stacks.joinToString("", "", "", -1, "") { s -> s.last().toString() } } fun part2(data: List<String>): String { val instructions = parseDiagram(data) (instructions).forEach { val match = instructionRegex.find(it) val (cratesStr, originStr, destinationStr) = match!!.destructured val crates = cratesStr.toInt() val origin = originStr.toInt() val destination = destinationStr.toInt() processMultipleInstructions(crates, origin, destination) } return stacks.joinToString("", "", "", -1, "") { s -> s.last().toString() } } } fun main() { val runner = Solution() val input = Utils.readLines(runner, "input.txt", runner.javaClass.packageName) println("Solving first part of day 5") var start = LocalDateTime.now() println("The top crates are: ${input?.let { runner.part1(it) }}") var end = LocalDateTime.now() println("Solved first part of day 5") var milliseconds = Duration.between(start, end).toMillis() println("Took $milliseconds ms to solve first part of day 5") println() println("Solving second part of day 5") start = LocalDateTime.now() println("The top crates are: ${input?.let { runner.part2(it) }}") end = LocalDateTime.now() println("Solved second part of day 5") milliseconds = Duration.between(start, end).toMillis() println("Took $milliseconds ms to solve second part of day 5") }
0
Kotlin
0
0
db6b25f7668532f24d2737bc680feffc71342491
3,604
advent-of-code2022
MIT License
src/commonMain/kotlin/advent2020/day08/Day08Puzzle.kt
jakubgwozdz
312,526,719
false
null
package advent2020.day08 import advent2020.day08.OpCode.* import advent2020.utils.binaryInsert val regex by lazy { """(nop|acc|jmp) ([+\-])(\d+)""".toRegex() } enum class OpCode { nop, acc, jmp, } data class Instruction(val opCode: OpCode, val argument: Int) private fun program(input: String): List<Instruction> = input.trim().lines() .map { regex.matchEntire(it)?.destructured ?: error("Invalid line $it") } .map { (op, sign, number) -> Instruction(OpCode.valueOf(op), if (sign == "-") -number.toInt() else number.toInt()) } class InfiniteLoopException(val ip: Int, val accumulator: Int) : Exception() private fun runProgram(lines: List<Instruction>): Int { var accumulator = 0 var ip = 0 val visited = mutableListOf<Int>() while (ip != lines.size) { // if not visited, insert. If already visited - throw exception visited.binaryInsert(ip) { _, _ -> throw InfiniteLoopException(ip, accumulator) } when (lines[ip].opCode) { acc -> accumulator += lines[ip++].argument jmp -> ip += lines[ip].argument nop -> ip++ } } return accumulator } fun part1(input: String): String { val lines = program(input) try { runProgram(lines) error("no infinite loop") } catch (e: InfiniteLoopException) { return e.accumulator.toString() } } fun part2(input: String): String { val lines = program(input) val result = lines.testWithChange(jmp, nop) ?: lines.testWithChange(nop, jmp) ?: error("no solution found") return result.toString() } private fun List<Instruction>.testWithChange(from: OpCode, to: OpCode) = asSequence() .mapIndexedNotNull { index, instruction -> if (instruction.opCode == from) index to instruction else null } .mapNotNull { (index, instruction) -> try { runProgram(withReplaced(index, instruction.copy(opCode = to))) } catch (e: InfiniteLoopException) { null } } .firstOrNull() fun <E> List<E>.withReplaced(index: Int, value: E) = subList(0, index) + value + subList(index + 1, size)
0
Kotlin
0
2
e233824109515fc4a667ad03e32de630d936838e
2,142
advent-of-code-2020
MIT License
src/main/kotlin/dayTwo/DayTwo.kt
janreppien
573,041,132
false
{"Kotlin": 26432}
package dayTwo import AocSolution import java.io.File class DayTwo : AocSolution(2) { private val input = readInput() private fun readInput(): MutableList<List<Int>> { val inputs = mutableListOf<List<Int>>() val file = File("src/main/resources/inputs/dayTwo/input.txt") file.forEachLine { inputs.add(it.split(' ').map { signToNumber(it[0]) }) } return inputs } private fun signToNumber(char: Char): Int { return when (char) { 'A' -> 1 'B' -> 2 'C' -> 3 'X' -> 1 'Y' -> 2 'Z' -> 3 else -> 0 } } private fun score(game: List<Int>): List<Int> { val input = game.toMutableList() if (input[0] == 1 && input[1] == 3) { return listOf(7,3) } if (input[0] == 3 && input[1] == 1) { return listOf(3,7) } if (input[0] < input[1]) { return listOf(input[0],input[1] + 6) } if (input[0] == input[1]) { return listOf(input[0] + 3, input[1] + 3) } if (input[0] > input[1]) { return listOf(input[0] + 6, input[1]) } return listOf() } override fun solvePartOne(): String { var sum = 0 input.forEach { sum += score(it)[1] } return sum.toString() } private fun strategy(game: List<Int>): List<Int> { if(game[1] == 1) { if(game[0] == 1) { return listOf(7,3) } return listOf(game[0]+6,game[0]-1) } if(game[1] == 2) { return listOf(game[0]+3,game[0]+3) } if(game[1] == 3) { if(game[0] == 3) { return listOf(3,7) } return listOf(game[0],game[0]+7) } return listOf() } override fun solvePartTwo(): String { return input.map{strategy(it)}.sumOf { it[1] }.toString() } }
0
Kotlin
0
0
b53f6c253966536a3edc8897d1420a5ceed59aa9
2,039
aoc2022
MIT License
src/main/kotlin/utilities/MathSample.kt
kirimin
197,707,422
false
null
package utilities import java.math.BigDecimal import java.math.MathContext import java.util.* import kotlin.math.pow object MathSample { /*** * 10^9 + 7 */ val mod: Long = (Math.pow(10.0, 9.0) + 7).toLong() /** * Doubleを使わないpow */ fun longPow(a: Long, b: Long): Long { var ans = 1L for (i in 0 until b) { ans *= a } return ans } /** * 最大公約数 */ fun computeGreatestCommonDivisor(a: Long, b: Long): Long { val big: Long val small: Long if (a > b) { big = a small = b } else { small = a big = b } if (small == 0L) return big val rest = big % small return if (rest == 0L) small else computeGreatestCommonDivisor(small, rest) } fun computeGreatestCommonDivisor(list: List<Long>): Long { var result = list[0] for (i in 1 until list.size) { result = computeGreatestCommonDivisor(result, list[i]) } return result } /** * 最小公倍数 * @param big 2つの値の大きな方 * @param small 2つの値の小さな方 */ fun computeLeastCommonMultiple(a: Long, b: Long): Long { val big: Long val small: Long if (a > b) { big = a small = b } else { small = a big = b } return small * big / computeGreatestCommonDivisor(big, small) } fun computeLeastCommonMultiple(list: List<Long>): Long { var result = list[0] for (i in 1 until list.size) { result = computeLeastCommonMultiple(result, list[i]) } return result } /** * 素因数分解 */ fun computePrimeFactorList(n: Long): List<Pair<Long, Long>> { val p = mutableListOf<Pair<Long, Long>>() var primeFactor = n for (i in 2..(Math.sqrt(n.toDouble()) + 1).toLong()) { if (primeFactor % i != 0L) continue var count = 0L while (primeFactor % i == 0L) { primeFactor /= i count++ } p.add(i to count) } if (primeFactor != 1L) p.add(primeFactor to 1L) return p } /** * 約数の総和を求める * 素因数分解を行い、各素因数の合計を求め(0乗=1も含める)、それらを掛け合わせる */ fun computeDivisorSum(n: Long): Long { val p = computePrimeFactorList(n) var ans = 1L for (i in p.indices) { val pi = p[i] for (j in 0..pi.second) { ans += Math.pow(pi.first.toDouble(), j.toDouble()).toLong() } } return ans } /** * 階乗を計算する */ fun computeFactorial(n: Long): Long { return (1..n).toList().reduce { acc, l -> acc * l } } /** * 文字列から連続した文字の個数のリストに変換する */ fun collectSameChar(string: String): List<Pair<Char, Int>> { val list = mutableListOf<Pair<Char, Int>>() var prev = ' ' string.forEach { if (prev != it) { list.add(it to 1) } else { list[list.size - 1] = it to list.last().second + 1 } prev = it } return list } /** * nに含まれる約数列挙 */ fun enumDivisors(n: Long): List<Long> { val list = mutableListOf<Long>() for (i in 1..Math.sqrt(n.toDouble()).toLong()) { if (n % i == 0L) { list.add(i) if (n / i != i) list.add(n / i) } } return list.sorted() } /** * 1からNまでの整数に含まれる約数の数の合計を求める */ fun divisorsCounts(n: Long): Long { var ans = 0L for (i in 1..n) { for (j in i..n step i) { ans++ } } return ans } /** * 素数判定 */ fun isPrime(num: Int): Boolean { if (num < 2) return false if (num == 2) return true if (num % 2 == 0) return false val sqrtNum = Math.sqrt(num.toDouble()).toInt() for (i in 3..sqrtNum step 2) { if (num % i == 0) return false } return true } /** * エラトステネスのふるい。1からnまでの素数を列挙する */ fun sieveOfEratosthenes(n: Int): List<Int> { val prime = BooleanArray(n + 1) { true } for (i in 2..n) { for (j in i * 2..n step i) { prime[j] = false } } val ans = mutableListOf<Int>() for (i in 2..n) { if (prime[i]) { ans.add(i) } } return ans } /** * 何回割り切れるか */ fun log(num: Long, base: Long): Long { var count = 0L var tmp = num while (tmp % base == 0L) { tmp /= base count++ } return count } /** * 組み合わせ */ fun nCr(n: Int, r: Int): Int { if (r == 0 || r == n) return (1); else if (r == 1) return (n); return (nCr(n - 1, r - 1) + nCr(n - 1, r)); } /** * N個の中から2個を選ぶ公式 */ fun take2ByN(n: Int): Int { return n * (n - 1) / 2 } /** * 辞書順で順列の次の組み合わせにarrayを書き換える */ fun nextPermutation(array: IntArray): Boolean { var i = array.size - 1 while (i > 0 && array[i - 1] >= array[i]) i-- if (i <= 0) return false var j = array.size - 1 while (array[j] <= array[i - 1]) j-- var temp = array[i - 1] array[i - 1] = array[j] array[j] = temp j = array.size - 1 while (i < j) { temp = array[i] array[i] = array[j] array[j] = temp i++ j-- } return true } /** * 整数を「どのアイテムを選ぶのか」を表すListに変換 * @param bit 集合を表す整数 * @param n 何個のものについて考えているか * @return n個の中から選んだものの番号のみが含まれるList */ fun integerToList(bit: Int, n: Int): List<Int> { val s = mutableListOf<Int>() for (i in 0 until n) { if (bit and (1 shl i) != 0) { s.add(i) } } return s } /** * 二分探索を使いkeyに一番近いkey未満のindex + 1を返す */ fun lowerBound(list: List<Long>, key: Long): Int { var ng = -1 var ok = list.size while (ok - ng > 1) { val mid = (ok + ng) / 2 if (list[mid] >= key) ok = mid else ng = mid } return ok } /** * 指定した値以上の要素が初めて出現する場所を取得 */ internal class LowerBoundComparator<T : Comparable<T>?> : Comparator<T> { override fun compare(x: T, y: T): Int { return if (x!!.compareTo(y) >= 0) 1 else -1 } } /** * 指定した値より大きい要素が初めて出現する場所を取得 */ internal class UpperBoundComparator<T : Comparable<T>?> : Comparator<T> { override fun compare(x: T, y: T): Int { return if (x!!.compareTo(y) > 0) 1 else -1 } } fun dpsSample(h: Int, w: Int, a: List<CharArray>): Int { val seen = Array(h) { Array(w) { "_" } } val deque = ArrayDeque<Pair<Int, Int>>() seen[0][0] = "0" deque.offer(0 to 0) while (deque.isNotEmpty()) { val v = deque.poll() fun searchPosition(yOffset: Int = 0, xOffset: Int = 0) { val y = v.first + yOffset val x = v.second + xOffset if (v.second - 1 >= 0 && a[y][x] != '#' && seen[y][x] == "_") { seen[y][x] = (seen[v.first][v.second].toInt() + 1).toString() deque.offer(y to x) } } // left if (v.second - 1 >= 0) { searchPosition(xOffset = -1) } // right if (v.second + 1 < w) { searchPosition(xOffset = 1) } // top if (v.first - 1 >= 0) { searchPosition(yOffset = -1) } // bottom if (v.first + 1 < h) { searchPosition(xOffset = 1) } } if (seen[h - 1][w - 1] == "_") return -1 var whiteCount = -1 for (i in 0 until a.size) { for (j in 0 until a[i].size) { if (a[i][j] != '#') whiteCount++ } } val minCost = seen[h - 1][w - 1] return whiteCount - minCost.toInt() } /** * 少数誤差回避sqrt */ fun sqrt(a: BigDecimal, scale: Int): BigDecimal { var x = BigDecimal(Math.sqrt(a.toDouble()), MathContext.DECIMAL64) if (scale < 17) { x = x.setScale(scale, BigDecimal.ROUND_HALF_EVEN) return x } val b2 = BigDecimal(2) var tempScale = 16 while (tempScale < scale) { x = x.subtract( x.multiply(x).subtract(a).divide( x.multiply(b2), scale, BigDecimal.ROUND_HALF_EVEN ) ) tempScale *= 2 } return x } /** * n以下の等差数列の和 * @param n 上限の数 * @param d 公差 */ fun arithmeticSequence(n: Long, d: Long): Long { return (d + n - n % d) * (n / d) / 2 } /** * 10進数未満を10進数に変換 * @param n 値 * @param b 元の進数 */ fun toBase10(n: String, b: Int): Long { var ten = 0L for (i in 0 until n.length) { fun longPow(a: Long, b: Long): Long { var ans = 1L for (i in 0 until b) { ans *= a } return ans } ten += n[n.length - i - 1].toString().toLong() * (longPow(b.toLong(), i.toLong())) } return ten } /** * 10進数を10進数未満に変換 * @param n 値 * @param b 変換後の進数 */ fun base10to(n: Long, b: Int): String { if (n == 0L) return "0" var n = n var num = "" while (n != 0L) { val mod = n % b num = mod.toString() + num n /= b } return num } // ユークリッド距離を求める fun euclidDistance(x1: Int, y1: Int, x2: Int, y2: Int): Double { return Math.sqrt((x1 - x2).toDouble().pow(2) + (y1 - y2).toDouble().pow(2)) } }
0
Kotlin
1
5
23c9b35da486d98ab80cc56fad9adf609c41a446
11,106
AtCoderLog
The Unlicense
src/Day10.kt
jmorozov
573,077,620
false
{"Kotlin": 31919}
fun main() { val inputData = readInput("Day10") part1(inputData) part2(inputData) } private fun part1(inputData: List<String>) { var cycleCounter = 0 var cycleStrengthCounter = FIRST_STRENGTH_MARK var x = 1 var signalStrength = 0 for (line in inputData) { val command = line.trim() when { command == "noop" -> { cycleCounter += 1 val (strength, nextCycleStrengthStep) = computeSignalStrength( cycleCounter, x, cycleStrengthCounter ) signalStrength += strength cycleStrengthCounter += nextCycleStrengthStep } command.startsWith("addx ") -> { cycleCounter += 1 val (strength1, nextCycleStrengthStep1) = computeSignalStrength( cycleCounter, x, cycleStrengthCounter ) signalStrength += strength1 cycleStrengthCounter += nextCycleStrengthStep1 cycleCounter += 1 val (strength2, nextCycleStrengthStep2) = computeSignalStrength( cycleCounter, x, cycleStrengthCounter ) signalStrength += strength2 cycleStrengthCounter += nextCycleStrengthStep2 x += parseAddx(command) } else -> continue } } println("The sum of signal strengths: $signalStrength") } private const val FIRST_STRENGTH_MARK = 20 private fun parseAddx(command: String): Int { val regex = """addx (?<value>-?\d+)""".toRegex() val matchResult = regex.find(command) ?: return 0 val (value) = matchResult.destructured return value.toInt() } private fun computeSignalStrength(cycleCounter: Int, x: Int, strengthCycle: Int): Pair<Int, Int> { if (strengthCycle != cycleCounter) { return Pair(0, 0) } return Pair(x * strengthCycle, CYCLE_STRENGTH_STEP) } private const val CYCLE_STRENGTH_STEP = 40 private fun part2(inputData: List<String>) { var x = 1 var crt = "" for (line in inputData) { val command = line.trim() when { command == "noop" -> { crt = draw(crt, x) } command.startsWith("addx ") -> { crt = draw(crt, x) crt = draw(crt, x) x += parseAddx(command) } else -> continue } } displayRaw(crt) } private fun getSpritePosition(x: Int): IntRange = x - 1..x + 1 private fun draw(crt: String, x: Int): String { val nextPixel= drawPixel(crt, x) return displayRaw(crt + nextPixel) } private fun drawPixel(crt: String, x: Int): String { val crtPosition = crt.length val spritePosition = getSpritePosition(x) if (crtPosition in spritePosition) { return "#" } return "." } private fun displayRaw(crt: String): String { if (crt.length < DISPLAY_LENGTH) { return crt } println(crt) return "" } private const val DISPLAY_LENGTH = 40
0
Kotlin
0
0
480a98838949dbc7b5b7e84acf24f30db644f7b7
3,258
aoc-2022-in-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/BrickWall.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.min /** * 554. Brick Wall * @see <a href="https://leetcode.com/problems/brick-wall/">Source</a> */ fun interface BrickWall { operator fun invoke(wall: List<List<Int>>): Int } /** * Approach #1 Brute Force [Time Limit Exceeded] * Time complexity : O(n*m) * Space complexity : O(m) */ class BrickWallBruteForce : BrickWall { override operator fun invoke(wall: List<List<Int>>): Int { if (wall.isEmpty()) return 0 val pos = IntArray(wall.size) var sum = 0 var res = Int.MAX_VALUE for (el in wall.first()) { sum += el } while (sum != 0) { var count = 0 for (i in wall.indices) { val row: MutableList<Int> = wall[i].toMutableList() if (row[pos[i]] != 0) count++ else pos[i]++ row[pos[i]] = row[pos[i]] - 1 } sum-- res = min(res, count) } return 2 } } /** * Approach #2 Better Brute Force[Time Limit Exceeded] * Time complexity : O(n*m) * Space complexity : O(m) */ class BrickWallBetterBruteForce : BrickWall { override operator fun invoke(wall: List<List<Int>>): Int { if (wall.isEmpty()) return 0 val pos = IntArray(wall.size) var sum = 0 var res = Int.MAX_VALUE for (el in wall[0]) { sum += el } while (sum != 0) { var count = 0 var mini = Int.MAX_VALUE for (i in wall.indices) { val row = wall[i] if (row[pos[i]] != 0) { count++ } else { pos[i]++ } mini = min(mini, row[pos[i]]) } for (i in wall.indices) { val row: MutableList<Int> = wall[i].toMutableList() row[pos[i]] = row[pos[i]] - mini } sum -= mini res = min(res, count) } return 2 } } /** * Approach #3 Using HashMap * Time complexity : O(n) * Space complexity : O(m) */ class BrickWallHashMap : BrickWall { override operator fun invoke(wall: List<List<Int>>): Int { val map: HashMap<Int, Int> = HashMap() for (row in wall) { var sum = 0 for (i in 0 until row.size - 1) { sum += row[i] if (map.containsKey(sum)) map[sum] = map.getOrDefault(sum, 0) + 1 else map[sum] = 1 } } var res: Int = wall.size for (key in map.keys) res = min(res, wall.size - map.getOrDefault(key, 0)) return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
3,294
kotlab
Apache License 2.0
src/Day17.kt
asm0dey
572,860,747
false
{"Kotlin": 61384}
val HashSet<Point17>.top get() = if (isEmpty()) -1 else maxOf(Point17::y) fun main() { fun windVector(wind: Iterator<Char>): Point17 { val windVector = when (wind.next()) { '>' -> Point17(1, 0) '<' -> Point17(-1, 0) else -> error("Unsupported wind speed") } return windVector } fun windIterator(input: String): Iterator<Char> { val wind = iterator { while (true) { yieldAll(input.toList()) } } return wind } fun shape17Iterator() = iterator { val x = buildList { add(Shape17(0, 0, 1, 0, 2, 0, 3, 0)) add(Shape17(1, 0, 0, 1, 1, 1, 2, 1, 1, 2)) add(Shape17(0, 0, 1, 0, 2, 0, 2, 1, 2, 2)) add(Shape17(0, 0, 0, 1, 0, 2, 0, 3)) add(Shape17(0, 0, 1, 0, 0, 1, 1, 1)) } while (true) { yieldAll(x) } } fun part1(input: String): Int { val wind = windIterator(input) val shapes = shape17Iterator() val occupied = hashSetOf<Point17>() repeat(2022) { val currentTop = occupied.top var cur = shapes.next().relTo(currentTop).tryMove(occupied, Point17(2, 0)) while (true) { cur = cur.tryMove(occupied, windVector(wind)) val tryFall = cur.tryMove(occupied, Point17(0, -1)) if (tryFall == cur) { occupied.addAll(cur.points) break } else cur = tryFall } } return occupied.maxOf(Point17::y) + 1 } fun part2(input: String, lastShape: Long): Long { val wind = windIterator(input) val shapes = shape17Iterator() val occupied = hashSetOf<Point17>() val diffs = StringBuilder() for (i in 0 until lastShape) { val currentTop = occupied.top var cur = shapes.next().relTo(currentTop).tryMove(occupied, Point17(2, 0)) while (true) { val windVector = windVector(wind) cur = cur.tryMove(occupied, windVector) val tryFall = cur.tryMove(occupied, Point17(0, -1)) if (tryFall == cur) { occupied.addAll(cur.points) diffs.append(occupied.top - currentTop) val periodicSequenceSearchLength = 20 if (diffs.length > periodicSequenceSearchLength * 2) { val repetitions = diffs.windowed(periodicSequenceSearchLength).count { it == diffs.takeLast(periodicSequenceSearchLength) } if (repetitions > 1) { println() println("FOUND PERIODIC SEQUENCE!!!") val (start, period) = diffs .asSequence() .withIndex() .windowed(periodicSequenceSearchLength) .map { val foundIndex = diffs.indexOf( it.map(IndexedValue<Char>::value).joinToString(""), it.last().index ) it.first().index to (foundIndex - it.first().index) } .firstOrNull { it.second >= 0 } ?: break val periodicSequence = diffs.substring(start until start + period) println("Repeating sequence is $period shapes") println("Repeating sequence is $periodicSequence") val numberOfRepetitions = (lastShape - start) / period println("There will be $numberOfRepetitions repetitions") val repetitionIncrement = periodicSequence.map(Char::digitToInt).sum() println("Each repetition adds $repetitionIncrement height") val startIncrement = diffs.substring(0 until start).map(Char::digitToInt).sum() println("Glass stabilization is ${start - 1} shapes") println("Glass stabilization is $startIncrement height") val remainder = lastShape - start - numberOfRepetitions * period println("Tail remaining after repetitions is $remainder shapes") val tailIncrement = periodicSequence.take(remainder.toInt()).map(Char::digitToInt).sum() println("Its increment is $tailIncrement") val totalIncrement = startIncrement.toLong() + numberOfRepetitions * repetitionIncrement + tailIncrement println("Total increment is $startIncrement + $numberOfRepetitions * $repetitionIncrement + $tailIncrement = $totalIncrement") return totalIncrement } } break } else cur = tryFall } } return -1L } val testInput = readInput("Day17_test")[0] check(part1(testInput) == 3068) val input = readInput("Day17")[0] println(part1(input)) check(part2(testInput, 2022) == part1(testInput).toLong()) check(part2(input, 2022) == part1(input).toLong()) check(part2(testInput, 1000000000000L) == 1514285714288) println(part2(input, 1000000000000L)) } data class Point17(val x: Int, val y: Int) { fun move(vector: Point17): Point17 { return Point17(x + vector.x, y + vector.y) } } data class Shape17(val points: List<Point17>) { constructor(vararg points: Int) : this(points.asSequence().chunked(2) { (a, b) -> Point17(a, b) }.toList()) fun relTo(currentTop: Int): Shape17 = Shape17(points.map { it.copy(y = currentTop + it.y + 4) }) fun tryMove(occupied: Set<Point17>, vector: Point17): Shape17 { val nextPos = points.map { it.move(vector) } for (point in nextPos) { if (occupied.contains(point) || point.x < 0 || point.x > 6 || point.y < 0) return this } return Shape17(nextPos) } }
1
Kotlin
0
1
f49aea1755c8b2d479d730d9653603421c355b60
6,480
aoc-2022
Apache License 2.0
src/main/kotlin/me/peckb/aoc/_2023/calendar/day22/Day22.kt
peckb1
433,943,215
false
{"Kotlin": 956135}
package me.peckb.aoc._2023.calendar.day22 import javax.inject.Inject import me.peckb.aoc.generators.InputGenerator.InputGeneratorFactory class Day22 @Inject constructor( private val generatorFactory: InputGeneratorFactory, ) { fun partOne(filename: String) = generatorFactory.forFile(filename).readAs(::brick) { input -> val bricks = input.sortedBy { it.start.z }.toList().apply { forEachIndexed { index, brick -> brick.fall(index, this) } } findDeletableBricks(bricks).size } fun partTwo(filename: String) = generatorFactory.forFile(filename).read { input -> val brickInput = input.toList() val ogBricks = brickInput.map(::brick) .sortedBy { it.start.z } // sort the items for falling .apply { forEachIndexed { index, brick -> brick.fall(index, this) } } .sortedBy { it.start.z } // re-sort after falling for disintegration + falling val deletableBricks = findDeletableBricks(ogBricks) brickInput.indices.asSequence().filterNot { deletableBricks.containsKey(ogBricks[it]) }.sumOf { indexOfBrickToRemove -> val bricksToMessWith = ogBricks.map { it.clone() } val brickToDisintegrate = bricksToMessWith[indexOfBrickToRemove] val bricksAfterDisintegration = bricksToMessWith.minus(brickToDisintegrate) bricksAfterDisintegration.withIndex().count { (index, brick) -> brick.fall(index, bricksAfterDisintegration) } } } private fun findDeletableBricks(bricks: List<Brick>): Map<Brick, List<Brick>> { val brickByZHeight = bricks.groupBy { it.start.z }.withDefault { emptyList() } val brickToSupportsMap: MutableMap<Brick, List<Brick>> = mutableMapOf() val brickToReliantMap: MutableMap<Brick, List<Brick>> = mutableMapOf() brickByZHeight.forEach { (_, bricksToCheck) -> bricksToCheck.forEach { me -> val possibleReliantBricks = brickByZHeight.getValue(me.end.z + 1) val bricksThatRelyOnMe = possibleReliantBricks.filter { b -> val xOverlap = (b.start.x <= me.end.x && b.end.x >= me.start.x) val yOverlap = (b.start.y <= me.end.y && b.end.y >= me.start.y) xOverlap && yOverlap } brickToReliantMap.merge(me, bricksThatRelyOnMe) { a, b -> a + b } bricksThatRelyOnMe.forEach { brick -> brickToSupportsMap.merge(brick, listOf(me)) { a, b -> a + b } } } } return brickToReliantMap.filter { (me, bricksThatRelyOnMe) -> me.canBeDeleted(bricksThatRelyOnMe, brickToSupportsMap) } } private fun brick(line: String): Brick { val (start, end) = line.split("~").map { coords -> val (x, y, z) = coords.split(",").map { it.toInt() } Position(x, y, z) } return Brick(start, end) } }
0
Kotlin
1
3
2625719b657eb22c83af95abfb25eb275dbfee6a
2,746
advent-of-code
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2022/2022-20.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2022 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputLines import java.util.LinkedList fun main() { val input = readInputLines(2022, "20-input") val testInput1 = readInputLines(2022, "20-test1") println("Part1:") part1(testInput1).println() part1(input).println() println() println("Part2:") part2(testInput1).println() part2(input).println() } private fun part1(input: List<String>): Long = solve(input, 1, 1) private fun part2(input: List<String>): Long = solve(input, 811589153, 10) private fun solve(input: List<String>, key: Int, times: Int): Long { val original = input.map { it.toLong() * key } val list = LinkedList(List(original.size) { it }) repeat(times) { repeat(original.size) { val x = original[it] val index = list.indexOf(it) list.removeAt(index) val newIndex = (x + index).mod(original.size - 1) list.add(newIndex, it) } } val final = List(original.size) { original[list[it]] } val zeroIndex = final.indexOf(0) val x1 = final[(zeroIndex + 1000).mod(final.size)] val x2 = final[(zeroIndex + 2000).mod(final.size)] val x3 = final[(zeroIndex + 3000).mod(final.size)] return x1 + x2 + x3 }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,358
advent-of-code
MIT License
src/day10/day10.kt
kacperhreniak
572,835,614
false
{"Kotlin": 85244}
package day10 import readInput const val NEXT_CHECK = 40 const val LIT_PIXEL = '#' const val DARK_PIXEL = '.' private fun getParams(line: String): Pair<Int, Int> { val parts = line.split(" ") val instruction = parts[0] val cycles = when (instruction) { "noop" -> 1 "addx" -> 2 else -> 0 } val value = when (instruction) { "noop" -> 0 "addx" -> parts[1].toInt() else -> 0 } return Pair(cycles, value) } private fun part1(input: List<String>): Int { var value = 1 var cycle = 0 var checkPoint = 20 var result = 0 for (line in input) { val params = getParams(line) if ((cycle + params.first) % checkPoint < cycle) { result += checkPoint * value checkPoint += NEXT_CHECK } cycle += params.first value += params.second } return result } private fun part2(input: List<String>) { var temp = "" var index = 1 for (line in input) { val params = getParams(line) for (step in 0 until params.first) { temp += if (temp.length + 1 in index until index + 3) { LIT_PIXEL } else DARK_PIXEL if (temp.length == NEXT_CHECK) { println(temp) temp = "" } } index += params.second } } fun main() { val input = readInput("day10/test-input") println(part1(input)) part2(input) }
0
Kotlin
1
0
03368ffeffa7690677c3099ec84f1c512e2f96eb
1,491
aoc-2022
Apache License 2.0
Minimum_Size_Subarray_Sum_v2.kt
xiekch
166,329,519
false
{"C++": 165148, "Java": 103273, "Kotlin": 97031, "Go": 40017, "Python": 22302, "TypeScript": 17514, "Swift": 6748, "Rust": 6579, "JavaScript": 4244, "Makefile": 349}
// Given an array of n positive integers and a positive integer s, find the minimal // length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead. // two points class Solution { fun minSubArrayLen(s: Int, nums: IntArray): Int { if (nums.isEmpty()) return 0 var res = Int.MAX_VALUE var left = 0 var sum = 0 for (i in nums.indices) { sum += nums[i] while (sum >= s) { res = Math.min(res, i - left + 1) sum -= nums[left] left++ } } return if (res == Int.MAX_VALUE) 0 else res } } fun main() { val solution = Solution() val testset = arrayOf( intArrayOf(2, 3, 1, 2, 4, 3), intArrayOf(2, 3, 1, 2, 4, 3), intArrayOf(2, 3, 1, 2, 4, 3), intArrayOf(1, 2, 3, 4, 5) ) val ss = intArrayOf(7, 8, 11, 11) for (i in testset.indices) { println(solution.minSubArrayLen(ss[i], testset[i])) } }
0
C++
0
0
eb5b6814e8ba0847f0b36aec9ab63bcf1bbbc134
1,026
leetcode
MIT License
aoc2023/src/main/kotlin/de/havox_design/aoc2023/day16/TheFloorWillBeLava.kt
Gentleman1983
737,309,232
false
{"Kotlin": 746488, "Java": 441473, "Scala": 33415, "Groovy": 5725, "Python": 3319}
package de.havox_design.aoc2023.day16 import de.havox_design.aoc.utils.kotlin.model.directions.GeoDirection import de.havox_design.aoc.utils.kotlin.model.positions.Position2d class TheFloorWillBeLava(private var filename: String) { fun solvePart1(): Long = getEnergy(parseTiles(getResourceAsText(filename)), GeoDirection.EAST, Position2d(0, 0)) .toLong() fun solvePart2(): Long { val input = getResourceAsText(filename) val startPoints = input .flatMapIndexed { row, s -> s .withIndex() .filter { row == 0 || row == input.size - 1 || it.index == 0 || it.index == s.length - 1 } .map { iv -> Position2d(iv.index, row) } } val maxRow = startPoints .maxOf { it.y } val maxColumn = startPoints .maxOf { it.x } val results = startPoints .flatMap { when { it.y == 0 && it.x == 0 -> { listOf( Pair(it, getEnergy(parseTiles(input), GeoDirection.EAST, it)), Pair(it, getEnergy(parseTiles(input), GeoDirection.SOUTH, it)) ) } it.y == maxRow && it.x == maxColumn -> { listOf( Pair(it, getEnergy(parseTiles(input), GeoDirection.WEST, it)), Pair(it, getEnergy(parseTiles(input), GeoDirection.NORTH, it)) ) } it.y == 0 -> { listOf(Pair(it, getEnergy(parseTiles(input), GeoDirection.SOUTH, it))) } it.x == 0 -> { listOf(Pair(it, getEnergy(parseTiles(input), GeoDirection.EAST, it))) } it.y == maxRow -> { listOf(Pair(it, getEnergy(parseTiles(input), GeoDirection.NORTH, it))) } it.x == maxColumn -> { listOf(Pair(it, getEnergy(parseTiles(input), GeoDirection.WEST, it))) } else -> { emptyList() } } } return results .maxOf { it.second } .toLong() } private fun getEnergy( contraption: List<List<Tile>>, enteredDirection: GeoDirection, startPoint: Position2d<Int> ): Int { traceBeam(contraption, enteredDirection, contraption[startPoint.y][startPoint.x]) return contraption .flatten() .count { it.isEnergized() } } private fun traceBeam(contraption: List<List<Tile>>, enteredDirection: GeoDirection, startTile: Tile) { val nextDirections = startTile .getNextDirections(enteredDirection) val nextLocations = nextDirections .map { nextLocation(startTile.position, it) } for (location in nextLocations.withIndex()) { when { ( location.value.y !in contraption.indices || location.value.x !in contraption[startTile.position.y].indices || nextDirections[location.index] == GeoDirection.NONE ) -> continue } traceBeam( contraption, nextDirections[location.index], contraption[location.value.y][location.value.x] ) } } private fun nextLocation(position: Position2d<Int>, direction: GeoDirection): Position2d<Int> { return when (direction) { GeoDirection.NORTH -> Position2d(position.x, position.y - 1) GeoDirection.SOUTH -> Position2d(position.x, position.y + 1) GeoDirection.EAST -> Position2d(position.x + 1, position.y) GeoDirection.WEST -> Position2d(position.x - 1, position.y) else -> Position2d(position.x, position.y) } } private fun parseTiles(input: List<String>) = input.mapIndexed { row, line -> line.mapIndexed { column, c -> Tile(Position2d(column, row), c) } } private fun getResourceAsText(path: String): List<String> = this.javaClass.classLoader.getResourceAsStream(path)!!.bufferedReader().readLines() }
4
Kotlin
0
1
35ce3f13415f6bb515bd510a1f540ebd0c3afb04
4,617
advent-of-code
Apache License 2.0
src/main/kotlin/no/uib/inf273/extra/IntArray_.kt
elgbar
237,403,030
false
{"Kotlin": 141160}
package no.uib.inf273.extra import no.uib.inf273.Main import kotlin.random.Random /** * Exchange the elements at the two given indices. */ fun IntArray.exchange(first: Int, second: Int) { //we don't change the array so do nothing if (first != second) { //swap the two elements, yes this is kotlin magic this[first] = this[second].also { this[second] = this[first] } } } /** * Swap two elements within the given range. Allows [from] to be equal to [until] */ fun IntArray.randomizeExchange(from: Int = 0, until: Int = size, rng: Random = Main.rand) { check(from <= until) { "From is strictly greater than until: $from > $until" } //Cannot randomize an empty array, so we just return if (from != until) { //generate two indices within the sub-range then swap them exchange(rng.nextInt(from, until), rng.nextInt(from, until)) } } /** * Remove exactly [amount] from this array */ fun IntArray.filter(unwanted: Int, amount: Int): IntArray { return filter(unwanted, IntArray(size - amount), amount) } /** * Filter out the unwanted integer and print collect all remaining elements in [to] * * @return [to] */ fun IntArray.filter(unwanted: Int, to: IntArray, maxRemoved: Int = Integer.MAX_VALUE): IntArray { var index = 0 var removed = 0 for (e in this) { if (e != unwanted) { to[index++] = e if (++removed == maxRemoved) { return to } } } return to } /** * Insert [element] at [index], pushing everything right of [index] to the right. The element at [IntArray.size]` - 1` will be removed */ fun IntArray.insert(index: Int, element: Int) { this.copyInto(this, index + 1, index, size - 1) this[index] = element } /** * Adapted from c-code found [here](https://www.geeksforgeeks.org/print-all-permutations-of-a-string-with-duplicates-allowed-in-input-string/) */ fun IntArray.forEachPermutation(copy: Boolean = true, action: IntArray.() -> Unit) { val arr = if (copy) this.copyOf() else this fun findCeil(arr: IntArray, first: Int, l: Int, h: Int): Int { var ceilIndex = l for (i in l + 1..h) { if (arr[i] > first && arr[i] < arr[ceilIndex]) { ceilIndex = i } } return ceilIndex; } // println("finding all permutations of arr size ${arr.size}: ${arr.contentToString()}") // Sort the string in increasing order arr.sort() // Print permutations one by one var isFinished = false; while (!isFinished) { arr.action() var i: Int = size - 2 while (i >= 0) { if (arr[i] < arr[i + 1]) break --i } // If there is no such character, all // are sorted in decreasing order, // means we just printed the last // permutation and we are done. if (i == -1) isFinished = true; else { // Find the ceil of 'first char' // in right of first character. // Ceil of a character is the // smallest character greater // than it val ceilIndex = findCeil(arr, arr[i], i + 1, size - 1); // Swap first and second characters arr.exchange(i, ceilIndex) // Sort the string on right of 'first char' arr.sort(fromIndex = i + 1) } } }
0
Kotlin
0
3
1f76550a631527713b1eba22817e6c1215f5d84e
3,441
INF273
The Unlicense
src/Day01.kt
tblechmann
574,236,696
false
{"Kotlin": 5756}
fun main() { fun part1(input: List<String>): Int { val values = arrayListOf<Int>(0) input.forEach { if (it.isEmpty()) { values.add(0) } else { values[values.lastIndex] = values.last() + Integer.parseInt(it) } } return values.max() } fun part2(input: List<String>): Int { val values = arrayListOf<Int>(0) input.forEach { if (it.isEmpty()) { values.add(0) } else { values[values.lastIndex] = values.last() + Integer.parseInt(it) } } return values.sorted().takeLast(3).sum() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
4a65f6468a0cddd8081f2f0e3c1a96935438755f
976
aoc2022
Apache License 2.0
src/main/kotlin/me/giacomozama/adventofcode2022/days/Day16.kt
giacomozama
572,965,253
false
{"Kotlin": 75671}
package me.giacomozama.adventofcode2022.days import java.io.File class Day16 : Day() { private lateinit var inputFlowRates: IntArray private lateinit var inputGraph: Array<IntArray> override fun parseInput(inputFile: File) { val inputLines = inputFile.readLines() var lastIndex = 0 val indices = hashMapOf("AA" to 0) val regex = """Valve ([A-Z]{2}) has flow rate=([0-9]+); tunnels? leads? to valves? ([A-Z, ]+)""".toRegex() val flowRates = IntArray(inputLines.size) val graph = Array(inputLines.size) { IntArray(inputLines.size) { Int.MAX_VALUE } } for (line in inputLines) { val result = regex.matchEntire(line)!! val valve = indices.getOrPut(result.groupValues[1]) { ++lastIndex } flowRates[valve] = result.groupValues[2].toInt() graph[valve][valve] = 0 for (nb in result.groupValues[3].split(", ")) { graph[valve][indices.getOrPut(nb) { ++lastIndex }] = 1 } } for (k in graph.indices) { for (i in graph.indices) { for (j in graph.indices) { if (graph[i][j] - graph[k][j] > graph[i][k]) { graph[i][j] = graph[i][k] + graph[k][j] } } } } inputFlowRates = flowRates inputGraph = graph } // time: O(n ^ 3), space: O(n ^ 2) override fun solveFirstPuzzle(): Int { val flowRates = inputFlowRates val graph = inputGraph var result = 0 fun dfs( valve: Int, visited: Long, pressure: Int, timeLeft: Int ) { var cantMove = true for (nb in 1 until graph.size) { if (flowRates[nb] == 0 || visited and (1L shl nb) != 0L || graph[valve][nb] > timeLeft - 1) continue cantMove = false val newTimeLeft = timeLeft - graph[valve][nb] - 1 dfs( valve = nb, visited = visited or (1L shl nb), pressure = pressure + flowRates[nb] * newTimeLeft, timeLeft = newTimeLeft ) } if (cantMove) result = maxOf(result, pressure) } dfs(0, 1L, 0, 30) return result } // time: O(n ^ 3), space: O(n ^ 2) override fun solveSecondPuzzle(): Int { val flowRates = inputFlowRates val distances = inputGraph var result = 0 val bestSoloPathIn30Minutes = solveFirstPuzzle() val prevStates = hashSetOf<List<Number>>() fun dfs( myValve: Int, eleValve: Int, visited: Long, pressure: Int, myTimeLeft: Int, eleTimeLeft: Int ) { // prune this branch if redundant if (!prevStates.add(listOf(myValve, eleValve, visited, pressure, myTimeLeft, eleTimeLeft))) return // prune this branch if we could have done better by going without the elephant // we have to assume going with the elephant can always yield better results if we take the right path if (myTimeLeft + eleTimeLeft <= 30 && pressure <= bestSoloPathIn30Minutes) return var cantMove = true for (mnb in 1 until distances.size) { for (enb in 1 until distances.size) { if (mnb == enb || flowRates[enb] == 0 || flowRates[mnb] == 0 || visited and (1L shl mnb) != 0L || visited and (1L shl enb) != 0L ) continue val canIMakeIt = distances[myValve][mnb] <= myTimeLeft - 1 val canEleMakeIt = distances[eleValve][enb] <= eleTimeLeft - 1 when { canIMakeIt && canEleMakeIt -> { val mt = myTimeLeft - distances[myValve][mnb] - 1 val et = eleTimeLeft - distances[eleValve][enb] - 1 cantMove = false dfs( myValve = mnb, eleValve = enb, visited = visited or (1L shl mnb) or (1L shl enb), pressure = pressure + flowRates[mnb] * mt + flowRates[enb] * et, myTimeLeft = mt, eleTimeLeft = et ) } canIMakeIt -> { val mt = myTimeLeft - distances[myValve][mnb] - 1 cantMove = false dfs( myValve = mnb, eleValve = eleValve, visited = visited or (1L shl mnb), pressure = pressure + flowRates[mnb] * mt, myTimeLeft = mt, eleTimeLeft = eleTimeLeft ) } canEleMakeIt -> { val et = eleTimeLeft - distances[eleValve][enb] - 1 cantMove = false dfs( myValve = myValve, eleValve = enb, visited = visited or (1L shl enb), pressure = pressure + flowRates[enb] * et, myTimeLeft = myTimeLeft, eleTimeLeft = et ) } } } } if (cantMove) result = maxOf(result, pressure) } dfs(0, 0, 1L, 0, 26, 26) return result } }
0
Kotlin
0
0
c30f4a37dc9911f3e42bbf5088fe246aabbee239
6,056
aoc2022
MIT License
codeforces/kotlinheroes3/f.kt
mikhail-dvorkin
93,438,157
false
{"Java": 2219540, "Kotlin": 615766, "Haskell": 393104, "Python": 103162, "Shell": 4295, "Batchfile": 408}
package codeforces.kotlinheroes3 private fun solve() { val (n, m) = readInts() data class Segment(val start: Int, val end: Int, val id: Int) val segments = List(n) { val data = readInts(); Segment(data[0], data[1], it) } val byOpening = segments.sortedByDescending { it.start }.toMutableList() val ans = MutableList(n) { 0 } val byEnding = sortedSetOf<Segment>(compareBy({ it.end }, { it.id })) var time = 0 var worstGap = 0 while (true) { if (byEnding.isEmpty()) time = byOpening.lastOrNull()?.start ?: break while (byOpening.lastOrNull()?.start == time) byEnding.add(byOpening.removeAt(byOpening.lastIndex)) for (temp in 0 until m) { val segment = byEnding.pollFirst() ?: break worstGap = maxOf(worstGap, time - segment.end) ans[segment.id] = time } time++ } println(worstGap) println(ans.joinToString(" ")) } fun main() = repeat(readInt()) { solve() } private fun readLn() = readLine()!! private fun readInt() = readLn().toInt() private fun readStrings() = readLn().split(" ") private fun readInts() = readStrings().map { it.toInt() }
0
Java
1
9
30953122834fcaee817fe21fb108a374946f8c7c
1,072
competitions
The Unlicense
solver/src/commonMain/kotlin/org/hildan/sudoku/solver/techniques/HiddenTuples.kt
joffrey-bion
9,559,943
false
{"Kotlin": 51198, "HTML": 187}
package org.hildan.sudoku.solver.techniques import org.hildan.sudoku.model.* /** * Trivially sets the digit in a cell when this is the only cell of the unit with this candidate. */ object HiddenSingles : Technique { override fun attemptOn(grid: Grid): List<HiddenSinglesStep> { val actions = grid.units.flatMap { unit -> ALL_DIGITS.mapNotNull { digit -> unit.cells.singleOrNull { it.isEmpty && digit in it.candidates }?.let { onlyCellWithDigit -> Action.PlaceDigit(digit, onlyCellWithDigit.index) } } } return if (actions.isEmpty()) emptyList() else listOf(HiddenSinglesStep(actions.distinct())) } } // TODO make each hidden single an independent step? data class HiddenSinglesStep( override val actions: List<Action.PlaceDigit>, ): Step { override val techniqueName: String = "Hidden Singles" override val description: String = "The digits ${actions.map { it.digit }} only occur once in a unit (row, column" + " or box) so they can be placed there." } object HiddenPairs : HiddenTuples("Hidden Pairs", tupleSize = 2) object HiddenTriples : HiddenTuples("Hidden Triples", tupleSize = 3) object HiddenQuads : HiddenTuples("Hidden Quads", tupleSize = 4) /** * Hidden tuples are groups of N candidates that are only present in the same N cells of a unit. * There can be other candidates in those N cells, but the no element of the tuple appears in any other cell of the * unit. * When this happens, only those N candidates can be in those N cells because they will fill them all, and thus other * candidates can be removed from those cells. */ open class HiddenTuples( private val techniqueName: String, private val tupleSize: Int, ) : Technique { override fun attemptOn(grid: Grid): List<HiddenTupleStep> { val hiddenTuples = mutableListOf<HiddenTupleStep>() grid.units.forEach { unit -> val emptyCells = unit.cells.filterTo(HashSet()) { it.isEmpty } val cellsByTuple = emptyCells.groupByPotentialHiddenTuple() cellsByTuple.forEach { (tuple, cells) -> if (cells.size == tupleSize) { // Exactly N cells with the same naked tuple of N candidates in the unit // Those N candidates must all be in those N cells and can be removed from other cells in the unit val removals = tupleCandidatesRemovalActions(cells, tuple) if (removals.isNotEmpty()) { hiddenTuples.add(HiddenTupleStep(techniqueName, unit.id, tuple, cells.mapToIndices(), removals)) } } } } return hiddenTuples } private fun Set<Cell>.groupByPotentialHiddenTuple(): Map<Set<Int>, Set<Cell>> { val allCandidates = flatMapTo(HashSet()) { it.candidates } val potentialTuples = allCandidates.allTuplesOfSize(tupleSize) return potentialTuples.associateWith { tuple -> // we consider the cells that exclusively contain the tuple in their candidates this - filterCellsWithNoCandidatesIn(tuple) } } private fun Set<Cell>.filterCellsWithNoCandidatesIn(tuple: Set<Int>) = filterTo(HashSet()) { cell -> cell.candidates.none { it in tuple } } private fun tupleCandidatesRemovalActions( cellsWithHiddenTuple: Set<Cell>, tupleCandidates: Set<Digit>, ): List<Action.RemoveCandidate> = buildList { for (cell in cellsWithHiddenTuple) { val candidatesToRemove = cell.candidates - tupleCandidates addAll(candidatesToRemove.map { Action.RemoveCandidate(it, cell.index) }) } } } data class HiddenTupleStep( override val techniqueName: String, val unit: UnitId, val tuple: Set<Digit>, val cells: Set<CellIndex>, override val actions: List<Action.RemoveCandidate>, ): Step { override val description: String = "Within $unit, the digits $tuple appear exclusively in cells ${cellRefs(cells)}. " + "All of those ${tuple.size} digits must therefore occupy those ${cells.size} cells, so no other digits can be" + " placed in those cells. We can therefore remove all other candidates from those cells." }
0
Kotlin
0
0
441fbb345afe89b28df9fe589944f40dbaccaec5
4,323
sudoku-solver
MIT License
src/Day13.kt
IvanChadin
576,061,081
false
{"Kotlin": 26282}
fun main() { val inputName = "Day13_test" fun parseLine(s: String): ArrayList<Any> { val list = ArrayList<Any>() val stack = ArrayDeque<ArrayList<Any>>() stack.addLast(list) val numBuilder = StringBuilder() for (c in s) { when (c) { '[' -> { val temp = ArrayList<Any>() stack.last().add(temp) stack.addLast(temp) } ']' -> { if (numBuilder.isNotEmpty()) { val num = numBuilder.toString().toInt() stack.last().add(num) numBuilder.clear() } stack.removeLast() } ',' -> { if (numBuilder.isNotEmpty()) { val num = numBuilder.toString().toInt() stack.last().add(num) numBuilder.clear() } } else -> { numBuilder.append(c) } } } return list } fun isCorrectOrder(l1: ArrayList<Any>, l2: ArrayList<Any>): Int { var i = 0 var j = 0 while (i in l1.indices && j in l2.indices) { if (l1[i].javaClass != l2[j].javaClass) { if (l1[i] !is ArrayList<*>) { val temp = ArrayList<Any>() temp.add(l1[i]) l1[i] = temp } if (l2[i] !is ArrayList<*>) { val temp = ArrayList<Any>() temp.add(l2[i]) l2[i] = temp } } if (l1[i] is ArrayList<*>) { val res = isCorrectOrder(l1[i] as ArrayList<Any>, l2[j] as ArrayList<Any>) when (res) { -1 -> return -1 1 -> return 1 } } else { if ((l1[i] as Int) < (l2[i] as Int)) { return 1 } else if ((l1[i] as Int) > (l2[i] as Int)) { return -1 } } i++ j++ } if (j != l2.size) { return 1 } if (i != l1.size) { return -1 } return 0 } fun part1(): Int { val input = readInput(inputName).filter { it.isNotEmpty() } var idx = 0 var mainIdx = 1 var ans = 0 while (idx in input.indices) { val l1 = parseLine(input[idx++]) val l2 = parseLine(input[idx++]) if (isCorrectOrder(l1, l2) != -1) { ans += mainIdx } mainIdx++ } return ans } fun part2(): Int { val listStr = ArrayList<String>().apply { add("[[2]]") add("[[6]]") addAll(readInput(inputName).filter { it.isNotEmpty() }) } val sortedStr = listStr.sortedWith { a, b -> isCorrectOrder(parseLine(b), parseLine(a)) } var ans = 1 for (i in sortedStr.indices) { if (sortedStr[i] == "[[2]]" || sortedStr[i] == "[[6]]") { ans *= (i + 1) } } return ans } val result = part2() println(result) }
0
Kotlin
0
0
2241437e6c3a20de70306a0cb37b6fe2ed8f9e3a
3,429
aoc-2022
Apache License 2.0
src/main/kotlin/leetcode/kotlin/unionfind/200. Number of Islands.kt
sandeep549
251,593,168
false
null
package leetcode.kotlin.unionfind private fun numIslands(grid: Array<CharArray>): Int { var seen = mutableSetOf<Pair<Int, Int>>() fun dfs(r: Int, c: Int): Boolean { if (r < 0 || r >= grid.size || c < 0 || c >= grid[0].size) return false if (grid[r][c] == '0' || seen.contains(Pair(r, c))) return false seen.add(Pair(r, c)) dfs(r, c + 1) dfs(r, c - 1) dfs(r - 1, c) dfs(r + 1, c) return true } var count = 0 for (r in grid.indices) { for (c in grid[0].indices) { if (dfs(r, c)) count++ } } return count } private fun numIslands2(grid: Array<CharArray>): Int { fun dfs(r: Int, c: Int) { if (r < 0 || r >= grid.size || c < 0 || c >= grid[0].size) return if (grid[r][c] == '0') return grid[r][c] = '0' dfs(r, c + 1) dfs(r, c - 1) dfs(r - 1, c) dfs(r + 1, c) } var count = 0 for (r in grid.indices) { for (c in grid[0].indices) { if (grid[r][c] == '1') { count++ dfs(r, c) } } } return count } // todo: do it with bfs and union find // https://leetcode.com/problems/number-of-islands/solution/
0
Kotlin
0
0
9cf6b013e21d0874ec9a6ffed4ae47d71b0b6c7b
1,265
kotlinmaster
Apache License 2.0
2023/kotlin/1.kt
maquirag
723,632,326
false
{"Kotlin": 1261}
// Advent of Code 2023, Day 1 fun Boolean.toInt() = if (this) 1 else 0 fun main() { getTestsPart1() .map(::findDigits) .map { it.first() * 10 + it.last() } .sum() .also(::println) getTestsPart2() .map(::findNumbers) .map { it.first() * 10 + it.last() } .sum() .also(::println) } fun findDigits(s: String): List<Int> = s .filter(Char::isDigit) .map(Char::digitToInt) fun findNumbers(s: String): List<Int> { val words = listOf("one", "two", "three", "four", "five", "six", "seven", "eight", "nine") val nums = mutableListOf<Int>() for (i in s.indices) { if (s[i].isDigit()) { nums.add(s[i].digitToInt()) } else { val digit = words.mapIndexed { idx, word -> s.substring(i).startsWith(word).toInt() * (idx + 1) }.sum() if (digit > 0) nums.add(digit) } } return nums } fun getTestsPart1(): List<String> = listOf( "1abc2", "pqr3stu8vwx", "a1b2c3d4e5f", "treb7uchet", ) fun getTestsPart2(): List<String> = listOf( "two1nine", "eightwothree", "abcone2threexyz", "xtwone3four", "4nineeightseven2", "zoneight234", "7pqrstsixteen", )
0
Kotlin
0
1
297f806990ee83233fda82f7d2b2d7d332611734
1,261
aoc
The Unlicense
src/main/kotlin/com/hj/leetcode/kotlin/problem2231/Solution.kt
hj-core
534,054,064
false
{"Kotlin": 619841}
package com.hj.leetcode.kotlin.problem2231 /** * LeetCode page: [2231. Largest Number After Digit Swaps by Parity](https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity/); */ class Solution { /* Complexity: * Time O(NLogN) and Space O(N) where N is the number of digits that num has; */ fun largestInteger(num: Int): Int { val digits = num.toString().map { it.toString().toInt() } val (oddDigitsSorted, evenDigitsSorted) = getSortedOddAndSortedEvenDigits(digits) var largestInteger = 0 var digitValueMultiplier = 1 var availableLeastOddDigitIndex = 0 var availableLeastEvenDigitIndex = 0 for (index in digits.indices.reversed()) { val digit = digits[index] if (digit and 1 == 0) { largestInteger += evenDigitsSorted[availableLeastEvenDigitIndex] * digitValueMultiplier availableLeastEvenDigitIndex++ } else { largestInteger += oddDigitsSorted[availableLeastOddDigitIndex] * digitValueMultiplier availableLeastOddDigitIndex++ } digitValueMultiplier *= 10 } return largestInteger } private fun getSortedOddAndSortedEvenDigits(digits: List<Int>): Pair<List<Int>, List<Int>> { val oddDigits = mutableListOf<Int>() val evenDigits = mutableListOf<Int>() for (digit in digits) { if (digit and 1 == 1) oddDigits.add(digit) else evenDigits.add(digit) } oddDigits.sort() evenDigits.sort() return Pair(oddDigits, evenDigits) } }
1
Kotlin
0
1
14c033f2bf43d1c4148633a222c133d76986029c
1,637
hj-leetcode-kotlin
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/DiagonalTraverse2.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.LinkedList import java.util.Queue /** * 1424. Diagonal Traverse II * @see <a href="https://leetcode.com/problems/diagonal-traverse-ii">Source</a> */ fun interface DiagonalTraverse2 { operator fun invoke(nums: List<List<Int>>): IntArray } /** * Approach 1: Group Elements by the Sum of Row and Column Indices */ class DiagonalTraverse2Group : DiagonalTraverse2 { override fun invoke(nums: List<List<Int>>): IntArray { val groups: MutableMap<Int, MutableList<Int>> = HashMap() var n = 0 for (row in nums.size - 1 downTo 0) { for (col in 0 until nums[row].size) { val diagonal: Int = row + col if (!groups.containsKey(diagonal)) { groups[diagonal] = ArrayList() } groups[diagonal]?.add(nums[row][col]) n++ } } val ans = IntArray(n) var i = 0 var curr = 0 while (groups.containsKey(curr)) { for (num in groups.getOrDefault(curr, mutableListOf())) { ans[i] = num i++ } curr++ } return ans } } /** * Approach 2: Breadth First Search */ class DiagonalTraverse2BFS : DiagonalTraverse2 { override fun invoke(nums: List<List<Int>>): IntArray { val queue: Queue<Pair<Int, Int>> = LinkedList() queue.offer(Pair(0, 0)) val ans: MutableList<Int?> = ArrayList() while (queue.isNotEmpty()) { val p: Pair<Int, Int> = queue.poll() val row: Int = p.first val col: Int = p.second ans.add(nums[row][col]) if (col == 0 && row + 1 < nums.size) { queue.offer(Pair(row + 1, col)) } if (col + 1 < nums[row].size) { queue.offer(Pair(row, col + 1)) } } val result = IntArray(ans.size) for ((i, num) in ans.withIndex()) { result[i] = num ?: 0 } return result } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,713
kotlab
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/LongestArithmeticSubsequence.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import kotlin.math.max /** * 1027. Longest Arithmetic Subsequence * @see <a href="https://leetcode.com/problems/longest-arithmetic-subsequence/">Source</a> */ fun interface LongestArithmeticSubsequence { fun longestArithSeqLength(nums: IntArray): Int } class LongestArithmeticSubsequenceDP : LongestArithmeticSubsequence { override fun longestArithSeqLength(nums: IntArray): Int { var res = 2 val n: Int = nums.size val dp: Array<HashMap<Int, Int>> = Array(n) { HashMap() } for (j in nums.indices) { for (i in 0 until j) { val d: Int = nums[j] - nums[i] dp[j][d] = dp[i].getOrDefault(d, 1) + 1 res = max(res, dp[j][d] ?: 0) } } return res } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,422
kotlab
Apache License 2.0
src/Day11.kt
RandomUserIK
572,624,698
false
{"Kotlin": 21278}
import java.io.File private const val WORRY_LEVEL_DIVISOR = 3 private const val TOP_ACTIVE_MONKEYS = 2 private data class InspectAndPlayResult( val worryLevel: Long, val throwTo: Int, ) private data class Monkey( val index: Int, val items: MutableList<Long> = mutableListOf(), val inspectOperation: (Long) -> Long, val test: Long, val trueMonkey: Int, val falseMonkey: Int, var activity: Long = 0, ) { fun takeTurn(monkeys: List<Monkey>, worryLevelModifier: (Long) -> Long) { items.forEach { item -> val (worryLevel, throwTo) = inspectAndPlay(item, worryLevelModifier) monkeys.first { it.index == throwTo }.items.add(worryLevel) } activity += items.size items.clear() } override fun toString(): String = "Monkey $index: ${items.map { it }.joinToString(", ")}" private fun inspectAndPlay(item: Long, worryLevelModifier: (Long) -> Long): InspectAndPlayResult { val worryLevel = worryLevelModifier(inspectOperation(item)) val throwTo = if (worryLevel % test == 0L) trueMonkey else falseMonkey return InspectAndPlayResult(worryLevel = worryLevel, throwTo = throwTo) } } private fun String.toOperation(): (Long) -> Long = split(" ").let { when { it.last() == "old" -> ({ input -> input * input }) it.first() == "*" -> ({ input -> it.last().toLong() * input }) else -> ({ input -> it.last().toLong() + input }) } } private fun String.toMonkey() = Monkey( index = substringAfter("Monkey ") .substringBefore(":") .toInt(), items = substringAfter("Starting items: ") .substringBefore("\n") .split(", ") .map { it.toLong() } .toMutableList(), inspectOperation = substringAfter("new = old ") .substringBefore("\n") .toOperation(), test = substringAfter("divisible by ").substringBefore("\n").toLong(), trueMonkey = substringAfter("If true: throw to monkey ").substringBefore("\n").toInt(), falseMonkey = substringAfter("If false: throw to monkey ").substringBefore("\n").toInt() ) fun main() { fun part1(input: List<String>) { val numberOfRounds = 20 val monkeys = input.map { it.toMonkey() } repeat(numberOfRounds) { monkeys.forEach { monkey -> monkey.takeTurn(monkeys) { worryLevel -> worryLevel / WORRY_LEVEL_DIVISOR } } } println( "Level of monkey business: ${ monkeys.map { it.activity }.sortedDescending().take(TOP_ACTIVE_MONKEYS).reduce(Long::times) }" ) } fun part2(input: List<String>) { val numberOfRounds = 10_000 val monkeys = input.map { it.toMonkey() } val modulus = monkeys.map { it.test }.reduce(Long::times) repeat(numberOfRounds) { monkeys.forEach { monkey -> monkey.takeTurn(monkeys) { worryLevel -> worryLevel % modulus } } } println( "Level of monkey business: ${ monkeys.map { it.activity }.sortedDescending().take(TOP_ACTIVE_MONKEYS).reduce(Long::times) }" ) } val input = File("src/inputs/day11_input.txt").readText().split("\n\n") part1(input) part2(input) }
0
Kotlin
0
0
f22f10da922832d78dd444b5c9cc08fadc566b4b
2,947
advent-of-code-2022
Apache License 2.0
p04/src/main/kotlin/ReposeRecord.kt
jcavanagh
159,918,838
false
null
package p04 import common.file.readLines import java.text.SimpleDateFormat import java.util.* enum class GuardEventType(val value: String) { BEGIN_SHIFT("begins shift"), FALL_ASLEEP("falls asleep"), WAKE_UP("wakes up"); companion object { fun from(search: String): GuardEventType = requireNotNull(values().find { it.value == search }) { "No TaskAction with value $search" } } } class LogMessage { val guardId: Int val dateStr: String val minute: Int val type: GuardEventType constructor(msg: String, defaultGuardId: Int) { val matches = Regex("""\[([\d-]+)\s\d+:(\d+)\]\s(?:Guard #)?(\d+)?\s?(.+)""").matchEntire(msg) this.dateStr = matches?.groups?.get(1)?.value!! this.minute = matches.groups.get(2)?.value!!.toInt() this.guardId = matches.groups.get(3)?.value?.toInt() ?: defaultGuardId this.type = GuardEventType.from(matches.groups.get(4)?.value!!) } override fun toString(): String { return "$dateStr:$minute - $guardId - $type" } } fun rangesAsleepByGuardId(logs: List<LogMessage>): Map<Int, List<Pair<Int, Int>>> { var lastSleepMinute = 0 val map = mutableMapOf<Int, MutableList<Pair<Int, Int>>>() //There's gotta be a cleaner way to deal with a nullable accumulator... logs.groupingBy { it.guardId }.aggregateTo(map) { _, total, msg, first -> if (first) { mutableListOf() } else { when (msg.type) { GuardEventType.FALL_ASLEEP -> lastSleepMinute = msg.minute GuardEventType.WAKE_UP -> total!!.add(Pair(lastSleepMinute, msg.minute - 1)) GuardEventType.BEGIN_SHIFT -> total!! } total!! } } return map } fun mostMinutesAsleep(logs: List<LogMessage>): Pair<Int, Int> { val ranges = rangesAsleepByGuardId(logs) val asTotal = ranges.mapValues { it.value.fold(Pair(it.key, 0)) { acc, pair -> val total = acc.second + pair.second - pair.first Pair(it.key, total) } } return asTotal.maxBy { foo -> foo.value.second }?.value!! } fun mostSleepyMinuteByGuardId(logs: List<LogMessage>): Map<Int, Pair<Int, Int>> { val ranges = rangesAsleepByGuardId(logs) return ranges.mapValues {range -> val minuteCounts = mostSleepyMinuteForRanges(range.value) minuteCounts.maxBy { it.value }?.toPair()!! } } fun mostSleepyMinuteForRanges(sleepiestRanges: List<Pair<Int, Int>>): Map<Int, Int> { if(sleepiestRanges.isNotEmpty()) { return sleepiestRanges.flatMap { it.first.rangeTo(it.second) }.groupingBy { it }.eachCount() } return mutableMapOf(Pair(-1, -1)) } fun parseLogDate(dateStr: String): Date { return SimpleDateFormat("yyyy-MM-dd HH:mm").parse(dateStr) } fun parseLogs(rawLogs: List<String>): List<LogMessage> { var lastGuardId = -1 return rawLogs.sortedBy { parseLogDate(it.substringBeforeLast("]").substring(1)) }.map { val msg = LogMessage(it, lastGuardId) if (msg.guardId != -1) lastGuardId = msg.guardId msg } } fun main() { val logs = parseLogs(readLines("input.txt")) val sleepyGuard = mostMinutesAsleep(logs) val sleepyMinutesByGuard = mostSleepyMinuteByGuardId(logs) val sleepyGuardMinute = sleepyMinutesByGuard[sleepyGuard.first]!! val sleepiestGuardMinute = sleepyMinutesByGuard.maxBy { it.value.second } println("Sleepiest guard: $sleepyGuard") println("Sleepiest minute for that guard: $sleepyGuardMinute") println("Sleepy guard value: ${sleepyGuard.first * sleepyGuardMinute.first}") println("Sleepiest overall minute: $sleepiestGuardMinute") println("Sleepiest overall guard value: ${sleepiestGuardMinute?.key!! * sleepiestGuardMinute.value.first}") }
0
Kotlin
0
0
289511d067492de1ad0ceb7aa91d0ef7b07163c0
3,624
advent2018
MIT License
Problems/Algorithms/410. Split Array Largest Sum/SplitArrayLargestSum1.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 294218, "Python": 237866, "C++": 97190, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
class Solution { private val results = Array(1001) { IntArray(51) } fun splitArray(nums: IntArray, m: Int): Int { val n = nums.size val prefix = IntArray(n+1) for (i in 0..n-1) { prefix[i+1] = prefix[i] + nums[i] } return getMinMax(prefix, 0, m) } private fun getMinMax(prefix: IntArray, idx: Int, count: Int): Int { val n = prefix.size - 1 if (results[idx][count] != 0) { return results[idx][count] } if (count == 1) { results[idx][count] = prefix[n] - prefix[idx] return results[idx][count] } var minMaxSum = Int.MAX_VALUE for (i in idx..n-count) { val firstSum = prefix[i+1] - prefix[idx] val maxSum = maxOf(firstSum, getMinMax(prefix, i+1, count-1)) minMaxSum = minOf(minMaxSum, maxSum) if (firstSum >= minMaxSum) break } results[idx][count] = minMaxSum return results[idx][count] } }
0
Kotlin
0
1
5e919965b43917eeee15e4bff12a0b6bea4fd0e7
1,103
leet-code
MIT License
src/main/kotlin/Day23.kt
Yeah69
317,335,309
false
{"Kotlin": 73241}
class Day23 : Day() { override val label: String get() = "23" private val initialCups by lazy { input.asSequence().mapNotNull { it.toString().toIntOrNull() }.toList() } class Node(val value: Int) { lateinit var next: Node } private fun circularlyLinkedCupsZero(): Triple<Node, Map<Int, Node>, Int> { val map = mutableMapOf<Int, Node>() val last = Node(initialCups.last()) map[last.value] = last var prev = last for(value in initialCups.reversed().drop(1)) { val node = Node(value) map[node.value] = node node.next = prev prev = node } last.next = prev return Triple(prev, map, 9) } private fun circularlyLinkedCupsOne(): Triple<Node, Map<Int, Node>, Int> { val map = mutableMapOf<Int, Node>() val start = circularlyLinkedCupsZero().first var tail = start map[tail.value] = tail (1..8).forEach { _ -> tail = tail.next map[tail.value] = tail } val millionValue = 1_000_000 val millionTail = Node(millionValue) map[millionTail.value] = millionTail val ten = (999_999 downTo 10) .fold(millionTail) { acc, i -> val next = Node(i) map[next.value] = next next.next = acc next } millionTail.next = start tail.next = ten return Triple(start, map, millionValue) } private fun Node.step(map: Map<Int, Node>, maxLabelValue: Int): Node { fun Int.nextValue(): Int = if (this == 1) maxLabelValue else this - 1 val trio = this.next val trioTail = trio.next.next val nextNonTrio = trioTail.next this.next = nextNonTrio trioTail.next = trio var seekedValue = this.value.nextValue() while (seekedValue == trio.value || seekedValue == trio.next.value || seekedValue == trioTail.value) seekedValue = seekedValue.nextValue() val nodeToAppend = map[seekedValue]!! val nextToTrioTail = nodeToAppend.next nodeToAppend.next = trio trioTail.next = nextToTrioTail return this.next } fun logic(triple: Triple<Node, Map<Int, Node>, Int>, moveCount: Int): Node { val (start, map, maxLabelValue) = triple (1..moveCount).fold(start) { acc, _ -> acc.step(map, maxLabelValue) } return map[1]!! } override fun taskZeroLogic(): String { return (1 until 8) .scan(logic(circularlyLinkedCupsZero(), 100).next) { acc, _ -> acc.next } .map { it.value }.joinToString("") } override fun taskOneLogic(): String { val one = logic(circularlyLinkedCupsOne(), 10_000_000) return (one.next.value.toLong() * one.next.next.value.toLong()).toString() } }
0
Kotlin
0
0
23121ede8e3e8fc7aa1e8619b9ce425b9b2397ec
2,884
AdventOfCodeKotlin
The Unlicense
src/main/kotlin/leetcode/advanceds/Trie1.kt
sandeep549
262,513,267
false
{"Kotlin": 530613}
package leetcode.advanceds /** * A sample Trie to store only lower case alphabets. */ class Trie { private val root = TrieNode() /** * Insert string into Trie. */ fun insert(str: String) { var node: TrieNode = root for (c in str) { val index: Int = c - 'a' // index is mark of this char presence, index null means this char absent if (node.children[index] == null) node.children[index] = TrieNode() node = node.children[index]!! } node.isEndOfWord = true } /** * Find string in Trie. */ fun search(str: String): Boolean { var node: TrieNode? = root for (c in str) { val index = c - 'a' if (node!!.children[index] == null) return false node = node.children[index] } return node != null && node.isEndOfWord } /** * This function will print all the words in the dictionary * that have given string as prefix. * 1. Check if prefix itself not present. * 2. Check if prefix end itself as word. * 3. Print all words that has this prefix. */ fun printSuggestions(prefix: String) { var node: TrieNode? = root for (c in prefix) { val index = c - 'a' if (node!!.children[index] == null) return // prefix not present node = node.children[index] } if (node != null && node.isEndOfWord) { println(prefix) return // prefix itself is word } printSuggestions(prefix, node) } private fun printSuggestions(prefix: String, node: TrieNode?) { if (node == null) return if (node.isEndOfWord) println(prefix) for (i in node.children.indices) { val ch = ('a'.toInt() + i).toChar() printSuggestions(prefix + ch, node.children[i]) } } /** * Node in Trie data structure. */ private class TrieNode { val children = arrayOfNulls<TrieNode>(SIZE) var isEndOfWord = false } companion object { private const val SIZE = 25 } } fun main() { val trie = Trie() trie.insert("sandeep") trie.insert("simar") trie.insert("daksh") trie.insert("anaya") trie.insert("howareyou") trie.insert("howdoyoudo") println("Find simar=" + trie.search("simar")) println("Find anya=" + trie.search("anaya")) trie.printSuggestions("how") }
1
Kotlin
0
0
cf357cdaaab2609de64a0e8ee9d9b5168c69ac12
2,485
leetcode-kotlin
Apache License 2.0
src/com/ssynhtn/medium/Permutations.kt
ssynhtn
295,075,844
false
{"Java": 639777, "Kotlin": 34064}
package com.ssynhtn.medium class Permutations { var swapCount = 0; fun permute(nums: IntArray): List<List<Int>> { val collect = mutableListOf<List<Int>>() permute(nums, 0, collect) return collect } fun permute2(nums: IntArray): List<List<Int>> { val collect = mutableListOf<List<Int>>() swapPermute2(nums, nums.size, collect) return collect } /** * 将最后size个进行permute, 结果添加到collect, 并且使得最后size个的顺序与输入相比为倒序 * pre: size >= 1 */ fun swapPermute2(nums: IntArray, size: Int, collect: MutableList<List<Int>>) { if (size == 1) { collect.add(nums.toList()) return } swapPermute2(nums, size - 1, collect) val index = size - 1 var j = 0; var i = index - 2 while (j < index) { if (j < index) { val temp = nums[index] nums[index] = nums[j] nums[j] = temp swapPermute2(nums, size - 1, collect) j += 2; } if (i >= 0) { val temp = nums[i] nums[i] = nums[index] nums[index] = temp swapPermute2(nums, size - 1, collect) i -= 2; } } if (j == size) { reverse(nums, 0, index - 1) } } private fun reverse(nums: IntArray, i: Int, j: Int) { var start = i var end = j while (start < end) { val temp = nums[start] nums[start] = nums[end] nums[end] = temp start++; end--; } } fun permute(nums: IntArray, fixCount: Int, collect: MutableList<List<Int>>) { if (fixCount >= nums.size - 1) { collect.add(nums.toList()) return } permute(nums, fixCount + 1, collect) for (i in fixCount + 1 until nums.size) { val temp = nums[fixCount] nums[fixCount] = nums[i] nums[i] = temp permute(nums, fixCount + 1, collect) nums[i] = nums[fixCount] nums[fixCount] = temp swapCount += 2 } } } fun main(args: Array<String>) { val nums = intArrayOf(1,2,3) val nums2 = nums.clone() val perm = Permutations() val perm2 = Permutations() // val ps = perm.permute(nums) val ps2 = perm2.permute2(nums) // println(ps) // println(nums.toList()) println("swap count " + perm.swapCount) println("==2== ") println(ps2) // println(nums2.toList()) println("swap count2 " + perm2.swapCount) }
0
Java
0
0
511f65845097782127bae825b07a51fe9921c561
2,740
leetcode
Apache License 2.0
src/main/java/challenges/cracking_coding_interview/moderate/q3_intersection/Question.kt
ShabanKamell
342,007,920
false
null
package challenges.cracking_coding_interview.moderate.q3_intersection object Question { /* Checks if middle is between start and end. */ fun isBetween(start: Double, middle: Double, end: Double): Boolean { return if (start > end) { end <= middle && middle <= start } else { start <= middle && middle <= end } } /* Checks if middle is between start and end. */ fun isBetween(start: Point, middle: Point, end: Point): Boolean { return isBetween(start.x, middle.x, end.x) && isBetween(start.y, middle.y, end.y) } fun intersection(start1: Point, end1: Point, start2: Point, end2: Point): Point? { /* Compute lines (including slope and y-intercept). */ val line1 = Line(start1, end1) val line2 = Line(start2, end2) /* If the lines are parallel, then their extended lines must have same y-intercept. * If so, check that the start or end of one point is on the other line. */if (line1.slope == line2.slope) { if (line1.yintercept != line2.yintercept) { return null } /* Check if the start or end of one line is in the other. If so, return that point*/return if (isBetween( start1, start2, end1 ) ) start2 else if (isBetween( start1, end2, end1 ) ) end2 else if (isBetween( start2, start1, end2 ) ) start1 else if (isBetween( start2, end1, end2 ) ) end1 else null } /* Compute the intersection of the infinite lines, and then check if this falls within the * boundary of the line segments. Note that at most one line is vertical. */ /* Get intersection's x coordinate. If one is vertical, always use its x coordinate. * Otherwise, compute the intersection's x coordinate based on setting each line's y = mx + b equation * equal and solving for x. */ val x: Double x = if (line1.isVertical || line2.isVertical) { /* If a line is vertical, use its x coordinate. */ if (line1.isVertical) line1.start.x else line2.start.x } else { /* Set y = mx + b equations equal and solve for x */ (line2.yintercept - line1.yintercept) / (line1.slope - line2.slope) } /* Get insection's y coordinate using a non-vertical line. Note that if line1 is vertical * then line 2 is not vertical (else it would have been caught earlier). */ val y = if (line1.isVertical) line2.getYFromX(x) else line1.getYFromX(x) /* We now have the intersection of the infinite lines. Check if it's within the boundaries * of each line segment. */ val intersection = Point(x, y) return if (isBetween( start1, intersection, end1 ) && isBetween( start2, intersection, end2 ) ) { intersection } else null } @JvmStatic fun main(args: Array<String>) { val s1 = Point(2147000000.0, 1.0) val e1 = Point(-2147000000.0, -1.0) val s2 = Point(-10.0, 0.0) val e2 = Point(0.0, 0.0) val intersection = intersection(s1, e1, s2, e2) println("Line Segment 1: $s1 to $e1") println("Line Segment 2: $s2 to $e2") println("Intersection: " + (intersection ?: "None")) if (intersection != null) { println("Intersection is on segment1: " + Tester.checkIfPointOnLineSegments(s1, intersection, e1)) println("Intersection is on segment1: " + Tester.checkIfPointOnLineSegments(s2, intersection, e2)) } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
4,064
CodingChallenges
Apache License 2.0
src/main/kotlin/com/github/davio/aoc/y2023/Day3.kt
Davio
317,510,947
false
{"Kotlin": 405939}
package com.github.davio.aoc.y2023 import com.github.davio.aoc.general.Day import com.github.davio.aoc.general.Point import com.github.davio.aoc.general.getInputAsMatrix /** * See [Advent of Code 2023 Day 3](https://adventofcode.com/2023/day/3#part2]) */ object Day3 : Day() { private val matrix = getInputAsMatrix() private val numbers: MutableList<Number> = mutableListOf() init { var start: Point? = null val sb = StringBuilder() matrix.rows.forEachIndexed { y, row -> row.forEachIndexed { x, c -> if (c.isDigit()) { if (start == null) { start = Point.of(x, y) } sb.append(c) } else if (sb.isNotEmpty()) { val number = Number(sb.toString().toInt(), start!!, Point.of(x - 1, y)) numbers.add(number) start = null sb.clear() } } if (sb.isNotEmpty()) { val number = Number(sb.toString().toInt(), start!!, Point.of(row.lastIndex, y)) numbers.add(number) start = null sb.clear() } } } override fun part1(): Int { return numbers.filter { val range = (it.start..it.end) range.any { p -> matrix.getAdjacentPoints(p).any { adjacent -> val c = matrix[adjacent] !c.isDigit() && c != '.' } } }.sumOf { it.value } } override fun part2(): Int { return matrix.getPoints().mapNotNull { p -> if (matrix[p] != '*') null else { val adjacentPartNumbers = matrix.getAdjacentPoints(p).flatMap { adjacentP -> numbers.filter { adjacentP in (it.start..it.end) } }.toSet() if (adjacentPartNumbers.size == 2) { adjacentPartNumbers.map { it.value }.reduce { a, b -> a * b } } else null } }.sum() } private data class Number( val value: Int, val start: Point, val end: Point ) }
1
Kotlin
0
0
4fafd2b0a88f2f54aa478570301ed55f9649d8f3
2,264
advent-of-code
MIT License
advent/src/test/kotlin/org/elwaxoro/advent/y2021/Dec19.kt
elwaxoro
328,044,882
false
{"Kotlin": 376774}
package org.elwaxoro.advent.y2021 import org.elwaxoro.advent.Coord3D import org.elwaxoro.advent.PuzzleDayTester import org.elwaxoro.advent.Rotation4 /** * Beacon Scanner */ class Dec19 : PuzzleDayTester(19, 2021) { override fun part1(): Any = parse().alignTheScanners().map { it.beacons }.flatten().toSet().size override fun part2(): Any = parse().alignTheScanners().map { it.translation }.let { translations -> translations.maxOf { a -> translations.minus(a).maxOf { b -> a.manhattan(b) } } } /** * Loop unaligned scanners until everyone is aligned * Modifies the scanners so the beacon positions make sense relative to the first scanner * Aligned scanners have the translation from 0,0,0 built in */ private fun List<Scanner>.alignTheScanners(): Set<Scanner> = mutableSetOf(first()).also { aligned -> val unaligned = drop(1).toMutableList() while (unaligned.isNotEmpty()) { val iter = unaligned.iterator() while (iter.hasNext()) { val candidate = iter.next() aligned.firstNotNullOfOrNull { candidate.align(it) }?.let { aligned.add(it) iter.remove() } } } } private fun parse(): List<Scanner> = load(delimiter = "\n\n").mapIndexed { idx, chunk -> chunk.split("\n").filterNot { it.isBlank() || it.startsWith("--- scanner") }.map(Coord3D::parse).let { Scanner(idx, it) } } private data class Scanner(val name: Int, val beacons: List<Coord3D>, val translation: Coord3D = Coord3D()) { private val beaconDistanceMap: Map<Int, Pair<Coord3D, Coord3D>> = beacons.map { a -> beacons.minus(a).map { b -> a.manhattan(b) to Pair(a, b) } }.flatten().distinctBy { it.first }.toMap() fun align(anchor: Scanner): Scanner? = (beaconDistanceMap.keys intersect anchor.beaconDistanceMap.keys).let { potentialBeacons -> potentialBeacons.map { distance -> val (a, b) = beaconDistanceMap[distance]!! val (aa, ab) = anchor.beaconDistanceMap[distance]!! // Difference vector everything by everything, take the best matrix if 12 or more beacons line up Rotation4.allTheThings().mapNotNull { matrix -> val ra = matrix.multiply(a) val rb = matrix.multiply(b) if (ra.subtract(aa) == rb.subtract(ab)) { aa.subtract(ra).toMatrix().multiply(matrix) } else if (rb.subtract(aa) == ra.subtract(ab)) { ab.subtract(ra).toMatrix().multiply(matrix) } else { null } } }.flatten().groupingBy { it }.eachCount().maxByOrNull { it.value }?.takeIf { it.value >= 12 } ?.let { (matrix, _) -> Scanner(name, beacons.map { (matrix.multiply(it)) }, matrix.multiply(Coord3D())) } } } }
0
Kotlin
4
0
1718f2d675f637b97c54631cb869165167bc713c
3,250
advent-of-code
MIT License
src/main/kotlin/org/rgoussey/aoc2023/day3/Main.kt
RobinGoussey
727,877,956
false
{"Kotlin": 5214}
package org.rgoussey.aoc2023.day3 import java.io.File import kotlin.math.max import kotlin.math.min fun main() { val lines = File({}.javaClass.getResource("/day3/input.txt")!!.toURI()).readLines(); process(lines); } fun process(lines: List<String>) { val characters = mutableListOf<MutableList<Char>>() val symbols = mutableListOf<MutableList<Boolean>>() val numbers = mutableListOf<MutableList<Boolean>>() val closeToSymbol = mutableListOf<MutableList<Boolean>>() for (i in lines.indices) { characters.add(i, mutableListOf()) symbols.add(i, mutableListOf()) numbers.add(i, mutableListOf()) closeToSymbol.add(i, mutableListOf()) for (j in lines[i].indices) { val currentChar = lines[i][j] characters[i].add(j, currentChar) val isSymbol = isSymbol(currentChar) symbols[i].add(j, isSymbol) numbers[i].add(j, isNumber(currentChar)) } } for (i in lines.indices) { for (j in lines[i].indices) { closeToSymbol[i].add(j, adjacentToSymbol(symbols, i, j)) } } printMap(symbols) printMap(numbers) printMap(closeToSymbol) var sum = 0; for (i in characters.indices) { var currentNumber = ""; var lastNumberIndex = 0; var numberIsValid = false; for (j in characters[i].indices) { val isNumber = numbers[i][j] if (isNumber) { numberIsValid = numberIsValid or adjacentToSymbol(symbols, i, j) lastNumberIndex = j currentNumber += characters[i][j] val endOfLine = j == characters[i].size-1 if (endOfLine) { val number = Integer.parseInt(currentNumber) if (numberIsValid) { // println("Valid number $number") sum += number; } else { // println(" Not valid number $number") } currentNumber = "" lastNumberIndex = 0; } } else { val numberEnded = lastNumberIndex + 1 == j if (numberEnded && currentNumber != "") { val number = Integer.parseInt(currentNumber) // println("Number is detected %s".format(number)) if (numberIsValid) { // println("Valid number $number") sum += number; } else { // println(" Not valid number $number") } currentNumber = ""; numberIsValid=false } lastNumberIndex = 0; } } } println("Sum is $sum") } fun printMap(map: MutableList<MutableList<Boolean>>) { for (i in map.indices) { for (j in map[i].indices) { if (map[i][j]) { print('x') } else { print('.') } } print("\n"); } print("\n"); } fun adjacentToSymbol(symbols: MutableList<MutableList<Boolean>>, x: Int, y: Int): Boolean { for (i in max(x - 1, 0)..min(x + 1, symbols.size - 1)) { for (j in max(y - 1, 0)..min(y + 1, symbols[x].size - 1)) { if (symbols[i][j]) { return true } } } return false; } fun isSymbol(char: Char): Boolean { return !isNumber(char) && char != '.'; } fun isNumber(char: Char): Boolean { return char in '0'..'9'; }
0
Kotlin
0
0
b1421c04b403755617684480a4ffabf14f125aeb
3,652
advent_of_code23
Apache License 2.0
src/main/kotlin/arr/Median.kt
yx-z
106,589,674
false
null
package arr import java.util.* fun main(args: Array<String>) { // given two sorted arrays (may be different length) // get median of their merged sorted array val test1 = intArrayOf(1, 3, 8) val test2 = intArrayOf(2, 7, 9, 10) println(Arrays.toString(test1)) println(Arrays.toString(test2)) // merge all and report middle element val merged = test1 merge test2 println(Arrays.toString(merged)) println("===== =====") println(merged.getMedian()) // merge up to middle println(getMedianByMerging(test1, test2)) // find kth smallest by removing half of elements in each time println(getMedianByComparing(test1, test2)) } // O((size1 + size2) / 2) fun getMedianByMerging(arr1: IntArray, arr2: IntArray): Double { val size1 = arr1.size val size2 = arr2.size val lenMerged = size1 + size2 val midIdx = lenMerged / 2 var i1 = 0 var i2 = 0 var curr = -1 if (lenMerged % 2 == 0) { // even length var prev = -1 (0..midIdx).forEach { prev = curr curr = when { i1 >= size1 -> arr2[i2++] i2 >= size2 -> arr1[i1++] arr1[i1] < arr2[i2] -> arr1[i1++] else -> arr2[i2++] } } return (curr + prev) / 2.0 } // odd length (0..midIdx).forEach { curr = when { i1 >= arr1.size -> arr2[i2++] i2 >= arr1.size -> arr1[i1++] arr1[i1] < arr2[i2] -> arr1[i1++] else -> arr2[i2++] } } return curr.toDouble() } fun getMedianByComparing(arr1: IntArray, arr2: IntArray): Double { val totalSize = arr1.size + arr2.size val midIdx = totalSize / 2 return if (totalSize % 2 == 0) { (kth(arr1, 0, arr2, 0, midIdx) + kth(arr1, 0, arr2, 0, midIdx + 1)) / 2.0 } else { kth(arr1, 0, arr2, 0, midIdx + 1).toDouble() } } // O(log(size1 + size2)) fun kth(arr1: IntArray, start1: Int, arr2: IntArray, start2: Int, k: Int): Int { if (start1 >= arr1.size) { return arr2[start2 + k - 1] } if (start2 >= arr2.size) { return arr1[start1 + k - 1] } if (k == 1) { return minOf(arr1[start1], arr2[start2]) } val mid1 = if (start1 + k / 2 - 1 < arr1.size) { arr1[start1 + k / 2 - 1] } else { Int.MAX_VALUE } val mid2 = if (start2 + k / 2 - 1 < arr2.size) { arr2[start2 + k / 2 - 1] } else { Int.MAX_VALUE } val kUp = k - k / 2 return if (mid1 < mid2) { kth(arr1, start1 + k / 2, arr2, start2, kUp) } else { kth(arr1, start1, arr2, start2 + k / 2, kUp) } } // O(size1 + size2) infix fun IntArray.merge(intArr: IntArray): IntArray { val retArr = IntArray(size + intArr.size) var i1 = size - 1 var i2 = intArr.size - 1 (retArr.size - 1 downTo 0).forEach { retArr[it] = when { i1 < 0 -> intArr[i2--] i2 < 0 -> this[i1--] this[i1] < intArr[i2] -> intArr[i2--] else -> this[i1--] } } return retArr } fun IntArray.getMedian() = if (size % 2 == 0) { (this[size / 2] + this[size / 2 - 1]) / 2.0 } else { this[size / 2].toDouble() }
0
Kotlin
0
1
15494d3dba5e5aa825ffa760107d60c297fb5206
2,828
AlgoKt
MIT License
src/Day24.kt
abeltay
572,984,420
false
{"Kotlin": 91982, "Shell": 191}
fun main() { val right = 0 val down = 1 val left = 2 val up = 3 data class Blizzard( var x: Int, var y: Int, val direction: Int ) fun parseInput(input: List<String>): MutableList<Blizzard> { val blizzard = mutableListOf<Blizzard>() for (y in input.indices) { if (y == 0 || y == input.size - 1) continue val line = input[y].toCharArray() for (x in line.indices) { if (x == 0 || x == line.size - 1) continue if (line[x] == '.') continue val direction = when (line[x]) { '>' -> right '<' -> left 'v' -> down else -> up } blizzard.add(Blizzard(x = x - 1, y = y - 1, direction = direction)) } } return blizzard } fun moveBlizzards(blizzards: List<Blizzard>, x: Int, y: Int) { for (it in blizzards) { when (it.direction) { right -> it.x = (it.x + 1) % x left -> { it.x-- if (it.x < 0) { it.x += x } } down -> it.y = (it.y + 1) % y else -> { it.y-- if (it.y < 0) { it.y += y } } } } } fun addIfValid( blizzards: HashSet<Pair<Int, Int>>, location: Pair<Int, Int>, x: Int, y: Int, new: HashSet<Pair<Int, Int>> ) { if (location.first < 0 || location.first >= x || location.second < 0 || location.second >= y) return if (!blizzards.contains(location)) { new.add(location) } } fun moveHuman( blizzards: HashSet<Pair<Int, Int>>, location: Pair<Int, Int>, x: Int, y: Int, newLocations: HashSet<Pair<Int, Int>> ) { addIfValid(blizzards, Pair(location.first, location.second), x, y, newLocations) addIfValid(blizzards, Pair(location.first + 1, location.second), x, y, newLocations) addIfValid(blizzards, Pair(location.first - 1, location.second), x, y, newLocations) addIfValid(blizzards, Pair(location.first, location.second + 1), x, y, newLocations) addIfValid(blizzards, Pair(location.first, location.second - 1), x, y, newLocations) } fun explore(blizzards: MutableList<Blizzard>, x: Int, y: Int, start: Pair<Int, Int>, end: Pair<Int, Int>): Int { moveBlizzards(blizzards, x, y) var possibleLocations = hashSetOf(start) var answer = 1 while (true) { answer++ moveBlizzards(blizzards, x, y) val blizzardLocations = blizzards.map { Pair(it.x, it.y) }.toHashSet() val newLocations = HashSet<Pair<Int, Int>>() for (it in possibleLocations) { if (it == end) { return answer } moveHuman(blizzardLocations, it, x, y, newLocations) } addIfValid(blizzardLocations, start, x, y, newLocations) possibleLocations = newLocations } } fun part1(input: List<String>): Int { val blizzards = parseInput(input) val x = input[0].length - 2 val y = input.size - 2 return explore(blizzards, x, y, Pair(0, 0), Pair(x - 1, y - 1)) } fun part2(input: List<String>): Int { val blizzards = parseInput(input) val x = input[0].length - 2 val y = input.size - 2 val one = explore(blizzards, x, y, Pair(0, 0), Pair(x - 1, y - 1)) val two = explore(blizzards, x, y, Pair(x - 1, y - 1), Pair(0, 0)) val three = explore(blizzards, x, y, Pair(0, 0), Pair(x - 1, y - 1)) return one + two + three } val testInput = readInput("Day24_test") check(part1(testInput) == 18) check(part2(testInput) == 54) val input = readInput("Day24") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a51bda36eaef85a8faa305a0441efaa745f6f399
4,168
advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/shtanko/algorithms/leetcode/RankTeams.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2022 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1366. Rank Teams by Votes * @see <a href="https://leetcode.com/problems/rank-teams-by-votes/">Source</a> */ fun interface RankTeams { operator fun invoke(votes: Array<String>): String } data class VoteRecord( val team: String, val teamCount: Int, ) { val ranks = IntArray(teamCount) } class RankTeamsImpl : RankTeams { override operator fun invoke(votes: Array<String>): String { if (votes.size == 1) { return votes.first() } val map = HashMap<String, VoteRecord>() for (vote in votes) { for (i in vote.indices) { val team = vote[i].toString() val record = map.getOrDefault(team, VoteRecord(team, vote.length)) record.ranks[i]++ map[team] = record } } val list = ArrayList(map.values) list.sortWith { o1, o2 -> var idx = 0 while (idx < o1.ranks.size && idx < o2.ranks.size) { if (o1.ranks[idx] == o2.ranks[idx]) { idx++ } else { return@sortWith o2.ranks[idx] - o1.ranks[idx] } } return@sortWith o1.team.compareTo(o2.team) } val sb = StringBuilder() for (voteRecord in list) { sb.append(voteRecord.team) } return sb.toString() } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
2,055
kotlab
Apache License 2.0
src/twentytwo/Day02.kt
mihainov
573,105,304
false
{"Kotlin": 42574}
package twentytwo import readInputTwentyTwo abstract class Shape { abstract val score: Int abstract fun fightWith(shape: Shape): Int abstract fun lose(): Int abstract fun draw(): Int abstract fun win(): Int companion object { fun getItem(string: String): Shape { return when (string) { "A" -> Rock() "X" -> Rock() "B" -> Paper() "Y" -> Paper() "C" -> Scissors() "Z" -> Scissors() else -> throw IllegalArgumentException() } } } } class Rock : Shape() { override val score = 1 override fun fightWith(shape: Shape): Int { return when (shape) { is Rock -> 3 + score is Paper -> 0 + score is Scissors -> 6 + score else -> throw IllegalArgumentException() } } override fun lose(): Int { return Scissors().score + 0 } override fun draw(): Int { return Rock().score + 3 } override fun win(): Int { return Paper().score + 6 } } class Paper : Shape() { override val score = 2 override fun fightWith(shape: Shape): Int { return when (shape) { is Rock -> 6 + score is Paper -> 3 + score is Scissors -> 0 + score else -> throw IllegalArgumentException() } } override fun lose(): Int { return Rock().score + 0 } override fun draw(): Int { return Paper().score + 3 } override fun win(): Int { return Scissors().score + 6 } } class Scissors : Shape() { override val score = 3 override fun fightWith(shape: Shape): Int { return when (shape) { is Rock -> 0 + score is Paper -> 6 + score is Scissors -> 3 + score else -> throw IllegalArgumentException() } } override fun lose(): Int { return Paper().score + 0 } override fun draw(): Int { return Scissors().score + 3 } override fun win(): Int { return Rock().score + 6 } } fun main() { fun part1(input: List<String>): Int { var score = 0 input.forEach { val turns = it.split(" ") score += Shape.getItem(turns[1]).fightWith(Shape.getItem(turns[0])) } return score } fun part2(input: List<String>): Int { var score = 0 input.forEach { val turns = it.split(" ") val shape = Shape.getItem(turns[0]) score += when (turns[1]) { "X" -> shape.lose() "Y" -> shape.draw() "Z" -> shape.win() else -> throw IllegalStateException() } } return score } // test if implementation meets criteria from the description, like: val testInput = readInputTwentyTwo("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInputTwentyTwo("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
a9aae753cf97a8909656b6137918ed176a84765e
3,148
kotlin-aoc-1
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year22/Day21.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year22 import com.grappenmaker.aoc.PuzzleSet import kotlin.random.Random fun PuzzleSet.day21() = puzzle { val monkeys = inputLines.associate { line -> val (name, job) = line.split(": ") val sp = job.split(" ") name to (job.toDoubleOrNull()?.let { NumberJob(it) } ?: OperatorJob( lhs = sp[0], rhs = sp[2], operator = when (sp[1]) { "+" -> Double::plus "-" -> Double::minus "/" -> Double::div "*" -> Double::times else -> error("Invalid operator $sp") } )) } fun eval(monke: String, humanValue: Long = -1L): Double = when { humanValue != -1L && monke == "humn" -> humanValue.toDouble() else -> when (val job = monkeys.getValue(monke)) { is NumberJob -> job.number is OperatorJob -> job.operator(eval(job.lhs, humanValue), eval(job.rhs, humanValue)) } } partOne = eval("root").toLong().s() fun bs(): Long { val rootJob = monkeys.getValue("root") as OperatorJob val changes = eval(rootJob.rhs, Random.nextLong()) != eval(rootJob.rhs) val target = eval(if (changes) rootJob.lhs else rootJob.rhs) val variable = if (changes) rootJob.rhs else rootJob.lhs var min = 0L var max = 1L shl 43 while (true) { val pivot = (min + max) / 2 val found = eval(variable, pivot) val s = target - found when { s < 0L -> min = pivot s > 0L -> max = pivot else -> return pivot } } } partTwo = bs().s() } sealed interface Job data class NumberJob(val number: Double) : Job data class OperatorJob(val lhs: String, val rhs: String, val operator: (Double, Double) -> Double) : Job
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
1,903
advent-of-code
The Unlicense
src/main/kotlin/com/jaspervanmerle/aoc2021/day/Day21.kt
jmerle
434,010,865
false
{"Kotlin": 60581}
package com.jaspervanmerle.aoc2021.day import kotlin.math.max class Day21 : Day("888735", "647608359455719") { private val startingPositionOne = input.lines()[0].split(" ").last().toInt() private val startingPositionTwo = input.lines()[1].split(" ").last().toInt() override fun solvePartOne(): Any { var positionOne = startingPositionOne var positionTwo = startingPositionTwo var scoreOne = 0 var scoreTwo = 0 var currentPlayerOne = true var rolls = 0 while (scoreOne < 1000 && scoreTwo < 1000) { val roll = rolls * 3 + 6 rolls += 3 if (currentPlayerOne) { positionOne = (positionOne + roll - 1) % 10 + 1 scoreOne += positionOne } else { positionTwo = (positionTwo + roll - 1) % 10 + 1 scoreTwo += positionTwo } currentPlayerOne = !currentPlayerOne } return if (scoreOne < scoreTwo) scoreOne * rolls else scoreTwo * rolls } override fun solvePartTwo(): Any { val wins = countWins(startingPositionOne, startingPositionTwo) return max(wins.first, wins.second) } private fun countWins( positionOne: Int, positionTwo: Int, scoreOne: Int = 0, scoreTwo: Int = 0, knownStates: MutableMap<Pair<Pair<Int, Int>, Pair<Int, Int>>, Pair<Long, Long>> = mutableMapOf() ): Pair<Long, Long> { if (scoreOne >= 21) { return 1L to 0L } if (scoreTwo >= 21) { return 0L to 1L } val state = (positionOne to positionTwo) to (scoreOne to scoreTwo) if (knownStates.containsKey(state)) { return knownStates[state]!! } var wins = 0L to 0L for (roll1 in 1..3) { for (roll2 in 1..3) { for (roll3 in 1..3) { val newPositionOne = (positionOne + roll1 + roll2 + roll3 - 1) % 10 + 1 val newScoreOne = scoreOne + newPositionOne val deltaWins = countWins(positionTwo, newPositionOne, scoreTwo, newScoreOne, knownStates) wins = (wins.first + deltaWins.second) to (wins.second + deltaWins.first) } } } knownStates[state] = wins return wins } }
0
Kotlin
0
0
dcac2ac9121f9bfacf07b160e8bd03a7c6732e4e
2,376
advent-of-code-2021
MIT License
src/main/kotlin/Day9.kt
ueneid
575,213,613
false
null
import kotlin.math.abs import kotlin.math.sign class Day9(inputs: List<String>) { val commands = parse(inputs) private fun parse(inputs: List<String>): List<Pair<String, Int>> { return inputs.asSequence().map { line -> val commands = line.split(" ") Pair(commands[0], commands[1].toInt()) }.toList() } enum class Direction { L, R, U, D } class Rope( knotsNumber: Int, n: Int, m: Int, private val startCell: Cell, ) { private var knots = mutableListOf<Cell>() private var grid = mutableListOf<MutableList<Char>>() private var tailVisited = mutableSetOf<Cell>() init { repeat(knotsNumber) { knots.add(startCell.copy()) } for (i in 0 until n) { val row = ".".repeat(m) grid.add(row.toMutableList()) } // println("== Initial State ==") // println(this) tailVisited.add(knots.last().copy()) } override fun toString(): String { val newGrid = grid.map { row -> row.map { it }.toMutableList() }.toMutableList() for (i in 0 until knots.size) { if (newGrid[knots[i].y][knots[i].x] == '.') { newGrid[knots[i].y][knots[i].x] = i.toString().single() } } return newGrid.joinToString("\n") { it.joinToString("") } + "\n" } // I gave up the part2 and then referring to https://gist.github.com/xzec/76bcfd20688ff34407c95c2f4e8acb8c fun move(direction: Direction, times: Int) { val vec = when (direction) { Direction.L -> Vector(-1, 0) Direction.R -> Vector(1, 0) Direction.U -> Vector(0, -1) Direction.D -> Vector(0, 1) } // println("== ${direction.toString()}$times ==") val head = knots.first() val tail = knots.last() repeat(times) { head.move(vec) for (i in 1 until knots.size) { val knot = knots[i] val prev = knots[i - 1] if (knot.isAdjacent(prev)) { break } val distance = prev - knot knot.move(distance.sign()) } tailVisited.add(tail.copy()) // println(this) } } fun getTailVisitedNum(): Int { return tailVisited.size } } data class Vector(val x: Int, val y: Int) { operator fun plus(vec: Vector): Vector { return Vector(x + vec.x, y + vec.y) } operator fun times(i: Int): Vector { return Vector(x * i, y * i) } fun sign(): Vector { return Vector(x.sign, y.sign) } } data class Cell(var x: Int, var y: Int) { fun move(vec: Vector) { x += vec.x y += vec.y } fun isAdjacent(cell: Cell): Boolean { return abs(x - cell.x) in 0..1 && abs(y - cell.y) in 0..1 } operator fun minus(cell: Cell): Vector { return Vector(x - cell.x, y - cell.y) } } fun solve1(): Int { val rope = Rope(2, 6, 6, Cell(0, 5)) for ((direction, times) in commands) { rope.move(Direction.valueOf(direction), times) } return rope.getTailVisitedNum() } fun solve2(): Int { // val rope = Rope(10, 6, 6, Cell(0, 5)) val rope = Rope(10, 22, 27, Cell(12, 15)) for ((direction, times) in commands) { rope.move(Direction.valueOf(direction), times) } return rope.getTailVisitedNum() } } fun main() { val obj = Day9(Resource.resourceAsListOfString("day9/input.txt")) println(obj.solve1()) println(obj.solve2()) }
0
Kotlin
0
0
743c0a7adadf2d4cae13a0e873a7df16ddd1577c
4,017
adventcode2022
MIT License
src/main/kotlin/info/jukov/adventofcode/y2021/Day8.kt
jukov
572,271,165
false
{"Kotlin": 78755}
package info.jukov.adventofcode.y2021 import info.jukov.adventofcode.Day import java.io.BufferedReader import kotlin.math.pow object Day8 : Day() { override val year: Int = 2021 override val day: Int = 8 override fun part1(reader: BufferedReader): String { reader.useLines { lines -> return lines .map { line -> line.substring(line.indexOf('|') + 2) } .map { line -> line .split(' ') .map { it.length } .count { count -> count in 2..4 || count == 7 } } .sum() .toString() } } /** * Indicator keys: * 0 * 1 2 * 3 * 4 5 * 6 */ override fun part2(reader: BufferedReader): String { reader.useLines { lines -> return lines .map { line -> val split = line.split(" | ") val test = split[0].split(' ').map { it.toSet() } val digitCode = HashMap<Int, Set<Char>>() val indicator = HashMap<Int, Char>() digitCode[8] = EIGHT digitCode[1] = test.first { digit -> digit.size == 2 } digitCode[7] = test.first { digit -> digit.size == 3 } digitCode[4] = test.first { digit -> digit.size == 4 } indicator[0] = digitCode[7]!!.minus(digitCode[1]!!).first() val nineKnown = digitCode[7]!! + digitCode[4]!! digitCode[9] = test.first { digit -> digit.size == 6 && digit.containsAll(nineKnown) } indicator[4] = EIGHT.minus(digitCode[9]!!).first() indicator[6] = EIGHT .minus(digitCode[4]!!) .minus(indicator[0]!!) .minus(indicator[4]!!) .first() val zeroKnown = digitCode[7]!! + indicator[4]!! digitCode[0] = test.first { digit -> digit.size == 6 && digit.containsAll(zeroKnown) } indicator[3] = EIGHT.minus(digitCode[0]!!).first() digitCode[2] = test.first { digit -> digit.size == 5 && digit.containsAll(indicator.values) } digitCode[3] = test.first { digit -> digit.size == 5 && !digit.contains(indicator[4]!!) && digit.containsAll(digitCode[1]!!) } digitCode[5] = test.first { digit -> digit.size == 5 && !digit.contains(indicator[4]!!) && !digit.containsAll(digitCode[1]!!) } digitCode[6] = test.first { digit -> digit.size == 6 && digit.contains(indicator[3]!!) && digit.contains(indicator[4]!!) } val invertedMap = digitCode.entries.associate { it.value to it.key } split[1] .split(' ') .map { it.toSet() } .map { invertedMap.getValue(it) } .reversed() .withIndex() .fold(0) { acc, indexedValue -> val (index, value) = indexedValue acc + value * 10f.pow(index).toInt() } } .sum() .toString() } } private val EIGHT = setOf('a', 'b', 'c', 'd', 'e', 'f', 'g') }
0
Kotlin
1
0
5fbdaf39a508dec80e0aa0b87035984cfd8af1bb
3,716
AdventOfCode
The Unlicense
leetcode2/src/leetcode/find-first-and-last-position-of-element-in-sorted-array.kt
hewking
68,515,222
false
null
package leetcode /** * 34. 在排序数组中查找元素的第一个和最后一个位置 * https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/ * @program: leetcode * @description: ${description} * @author: hewking * @create: 2019-10-28 14:11 * 给定一个按照升序排列的整数数组 nums,和一个目标值 target。找出给定目标值在数组中的开始位置和结束位置。 你的算法时间复杂度必须是 O(log n) 级别。 如果数组中不存在目标值,返回 [-1, -1]。 示例 1: 输入: nums = [5,7,7,8,8,10], target = 8 输出: [3,4] 示例 2: 输入: nums = [5,7,7,8,8,10], target = 6 输出: [-1,-1] 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 **/ object FindFirstAndLastPositionOfElementInSortedArray { class Solution { /** * 思路: * 因为题设要求时间复杂度O(log n) 级别,并且是已排序 * 数组,所以需要用到二分查找 * 1. 有可能找到的值处于相同值的中间部分比如 [5,7,7,7,8,10] * 二分查找找到的是三个7里面的中间一个,那么需要循环相减 * 找到first,循环相加找到last */ fun searchRange(nums: IntArray, target: Int): IntArray { val index = binarySerach(nums,target) if (index < 0) { return intArrayOf(-1,-1) } var first = index var last = index while (first > 0 && nums[first - 1] == target) { first -- } while (last < nums.size - 1 && nums[last + 1] == target) { last ++ } return intArrayOf(first,last) } fun binarySerach(nums:IntArray,target: Int) : Int { var low = 0 var high = nums.size - 1 while (low <= high) { var m = (low + high).div(2) when { nums[m] == target -> return m nums[m] < target -> low = m + 1 nums[m] > target -> high = m - 1 } } return -1 } } }
0
Kotlin
0
0
a00a7aeff74e6beb67483d9a8ece9c1deae0267d
2,391
leetcode
MIT License
src/main/kotlin/leetcode/Problem1824.kt
fredyw
28,460,187
false
{"Java": 1280840, "Rust": 363472, "Kotlin": 148898, "Shell": 604}
package leetcode import kotlin.math.min /** * https://leetcode.com/problems/minimum-sideway-jumps/ */ class Problem1824 { fun minSideJumps(obstacles: IntArray): Int { return minSideJumps(obstacles, lane = 2, index = 0, memo = Array(obstacles.size) { IntArray(4) { -1 } }) } private fun minSideJumps(obstacles: IntArray, lane: Int, index: Int, memo: Array<IntArray>): Int { if (obstacles.size == index) { return 0 } if (obstacles[index] == lane) { return Int.MAX_VALUE } if (memo[index][lane] != -1) { return memo[index][lane] } val noSideJump = minSideJumps(obstacles, lane, index + 1, memo) var hasSideJump = Int.MAX_VALUE for (l in 1..3) { if (l == lane || obstacles[index] == l) { continue } var sideJump = minSideJumps(obstacles, l, index + 1, memo) if (sideJump != Int.MAX_VALUE) { sideJump++ } hasSideJump = min(hasSideJump, sideJump) } val min = min(noSideJump, hasSideJump) memo[index][lane] = min return min } }
0
Java
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,206
leetcode
MIT License
src/main/kotlin/me/grison/aoc/y2022/Day17.kt
agrison
315,292,447
false
{"Kotlin": 267552}
package me.grison.aoc.y2022 import me.grison.aoc.* class Day17 : Day(17, 2022) { override fun title() = "Pyroclastic Flow" override fun partOne() = solve(2022) override fun partTwo() = solve(1_000_000_000_000L) // all start at x = 2 private val ROCKS = listOf( listOf(p(2L, 0), p(3L, 0), p(4L, 0), p(5L, 0)), listOf(p(3L, 2), p(2L, 1), p(3L, 1), p(4L, 1), p(3L, 0)), listOf(p(4L, 2), p(4L, 1), p(2L, 0), p(3L, 0), p(4L, 0)), listOf(p(2L, 0), p(2L, 1), p(2L, 2), p(2L, 3)), listOf(p(2L, 1), p(3L, 1), p(2L, 0), p(3L, 0)) ) private fun rock(t: Int, y: Long) = ROCKS[t].map { it.second(y + it.second) } as Rock private fun move(jet: Char, rock: Rock, allRocks: Set<LPosition>): Rock { if (jet == '>') { val next = rock.right() if (next.intersect(allRocks).isEmpty()) return next // move } else { val next = rock.left() if (next.intersect(allRocks).isEmpty()) return next // move } return rock } fun solve(rocks: Long): Long { val allRocks = mutableSetOf<LPosition>() for (x in 0L..6L) allRocks.add(p(x, 0L)) // floor val knownStates = mutableMapOf<Triple<Int, Long, Rock>, LPosition>() var (top, tick, linesSkipped) = listOf(0L, 0L, 0L) var jet = 0 while (tick <= rocks) { var rock = rock((tick % 5L).toInt(), top + 4) move@ while (true) { rock = move(inputString[jet++], rock, allRocks).down() jet %= inputString.length if (rock.intersect(allRocks).isNotEmpty()) { rock = rock.up() allRocks.addAll(rock) top = allRocks.map { it.second }.max() // save current 100 top rows pattern val currentTop = allRocks.filter { top - it.second <= 100 }.map { it.second(top - it.second) } val currentState = Triple(jet, tick % 5, currentTop) if (currentState in knownStates) { val (lastTick, lastTop) = knownStates[currentState]!! val span = (rocks - tick) / (tick - lastTick) linesSkipped += span * (top - lastTop) tick += span * (tick - lastTick) } knownStates[currentState] = p(tick, top) break@move } } tick++ } return top + linesSkipped } } typealias Rock = List<LPosition> fun Rock.left() = if (any { it.first == 0L }) this else map { it.first(it.first - 1) } fun Rock.right() = if (any { it.first == 6L }) this else map { it.first(it.first + 1) } fun Rock.down() = map { it.second(it.second - 1) } fun Rock.up() = map { it.second(it.second + 1) }
0
Kotlin
3
18
ea6899817458f7ee76d4ba24d36d33f8b58ce9e8
2,919
advent-of-code
Creative Commons Zero v1.0 Universal
src/problems/1805-numDifferentIntegers.kt
w1374720640
352,006,409
false
null
package problems /** * 1805. 字符串中不同整数的数目 https://leetcode-cn.com/problems/number-of-different-integers-in-a-string/ * * 解:遍历String,找到所有的数字,加入HashSet中,最后统计Set的大小就是不同整数的数量 * 需要注意数字可能超过Int的大小,可以用String(需要手动去除前导0)或BitInteger代替 */ fun numDifferentIntegers(word: String): Int { val set = HashSet<String>() var i = -1 var j = 0 while (true) { if (j < word.length && word[j] in '0'..'9') { if (i == -1) { i = j } } else { if (i != -1) { val numString = word.substring(i, j) var k = 0 while (k < numString.length && numString[k] == '0') { k++ } set.add(if (k < numString.length) numString.substring(k) else "") i = -1 } if (j == word.length) break } j++ } return set.size } fun main() { check(numDifferentIntegers("a123bc34d8ef34") == 3) check(numDifferentIntegers("leet1234code234") == 2) check(numDifferentIntegers("a1b01c001") == 1) check(numDifferentIntegers("167278959591294") == 1) println("check succeed.") }
0
Kotlin
0
0
21c96a75d13030009943474e2495f1fc5a7716ad
1,329
LeetCode
MIT License
src/main/kotlin/dev/shtanko/algorithms/leetcode/MinimumSwap.kt
ashtanko
203,993,092
false
{"Kotlin": 5856223, "Shell": 1168, "Makefile": 917}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode /** * 1247. Minimum Swaps to Make Strings Equal * @see <a href="https://leetcode.com/problems/minimum-swaps-to-make-strings-equal/">Source</a> */ fun interface MinimumSwap { operator fun invoke(s1: String, s2: String): Int } class MinimumSwapSimple : MinimumSwap { override operator fun invoke(s1: String, s2: String): Int { val n: Int = s1.length var x = 0 var y = 0 for (i in 0 until n) if (s1[i] != s2[i]) { if (s1[i] == 'x') ++x else ++y } val cnt = x + y return if (cnt % 2 == 1) -1 else cnt / 2 + x % 2 } }
4
Kotlin
0
19
776159de0b80f0bdc92a9d057c852b8b80147c11
1,240
kotlab
Apache License 2.0
day02/part1.kts
bmatcuk
726,103,418
false
{"Kotlin": 214659}
// --- Day 2: Cube Conundrum --- // You're launched high into the atmosphere! The apex of your trajectory just // barely reaches the surface of a large island floating in the sky. You gently // land in a fluffy pile of leaves. It's quite cold, but you don't see much // snow. An Elf runs over to greet you. // // The Elf explains that you've arrived at Snow Island and apologizes for the // lack of snow. He'll be happy to explain the situation, but it's a bit of a // walk, so you have some time. They don't get many visitors up here; would you // like to play a game in the meantime? // // As you walk, the Elf shows you a small bag and some cubes which are either // red, green, or blue. Each time you play this game, he will hide a secret // number of cubes of each color in the bag, and your goal is to figure out // information about the number of cubes. // // To get information, once a bag has been loaded with cubes, the Elf will // reach into the bag, grab a handful of random cubes, show them to you, and // then put them back in the bag. He'll do this a few times per game. // // You play several games and record the information from each game (your // puzzle input). Each game is listed with its ID number (like the 11 in Game // 11: ...) followed by a semicolon-separated list of subsets of cubes that // were revealed from the bag (like 3 red, 5 green, 4 blue). // // For example, the record of a few games might look like this: // // Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green // Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue // Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red // Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red // Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green // // In game 1, three sets of cubes are revealed from the bag (and then put back // again). The first set is 3 blue cubes and 4 red cubes; the second set is 1 // red cube, 2 green cubes, and 6 blue cubes; the third set is only 2 green // cubes. // // The Elf would first like to know which games would have been possible if the // bag contained only 12 red cubes, 13 green cubes, and 14 blue cubes? // // In the example above, games 1, 2, and 5 would have been possible if the bag // had been loaded with that configuration. However, game 3 would have been // impossible because at one point the Elf showed you 20 red cubes at once; // similarly, game 4 would also have been impossible because the Elf showed you // 15 blue cubes at once. If you add up the IDs of the games that would have // been possible, you get 8. // // Determine which games would have been possible if the bag had been loaded // with only 12 red cubes, 13 green cubes, and 14 blue cubes. What is the sum // of the IDs of those games? import java.io.* import kotlin.io.* val MAX_CUBES = mapOf( "red" to 12, "green" to 13, "blue" to 14 ) val GAME_RGX = Regex("^Game (\\d+): ") val CNT_RGX = Regex("(\\d+) (red|green|blue)") val result = File("input.txt").readLines().sumBy { val gameMatch = GAME_RGX.find(it) val valid = it.drop(gameMatch!!.range.endExclusive).splitToSequence("; ").all { it.splitToSequence(", ").all { val cntMatch = CNT_RGX.matchEntire(it)!!.groupValues MAX_CUBES.get(cntMatch[2])!! >= cntMatch[1].toInt() } } if (valid) gameMatch!!.groupValues[1].toInt() else 0 } println(result)
0
Kotlin
0
0
a01c9000fb4da1a0cd2ea1a225be28ab11849ee7
3,392
adventofcode2023
MIT License
src/main/kotlin/days/Day7.kt
teunw
573,164,590
false
{"Kotlin": 20073}
package days import kotlin.io.path.Path class Day7 : Day(7) { private fun getDirSizes(): Pair<MutableMap<String, Int>, List<Pair<String, Int>>> { var files = mutableMapOf<String, Int>() var dirs = mutableListOf<String>("/") var currentDir = "" var listingDirectory = false; inputList.forEach { command -> if (listingDirectory) { if (command.startsWith("$")) { listingDirectory = false } if (command.startsWith("dir")) { dirs.add((currentDir + "/" + command.substring("dir ".length)).replace("//", "/")) } if (!command.startsWith("$") && !command.startsWith("dir")){ val (size, fileName) = command.split(" ") val file = (currentDir + "/" + fileName).replace("//", "/") files[file] = size.toInt() } } if (command.startsWith("$ cd")) { if (command == "$ cd ..") { currentDir = currentDir.substring(0, currentDir.lastIndexOf("/")) } else { currentDir += "/" + command.substring("$ cd ".length) currentDir = currentDir.replace("//", "/") } } if (command.startsWith("$ ls")) { listingDirectory = true return@forEach } } files = files.toSortedMap().toMutableMap() val dirSizes = dirs.map { dir -> dir to files.filter { it.key.startsWith(dir) }.values.sum() } return Pair(files, dirSizes) } override fun partOne(): Int { return getDirSizes().second .filter { it.second < 100000 }.sumOf { it.second } } override fun partTwo(): Int { val (_, dirSizes) = getDirSizes() val totalSpace = 70000000 val unusedSpace = totalSpace - dirSizes.first { it.first == "/" }.second val spaceNeeded = 30000000 - unusedSpace; val dirToDelete = dirSizes.filter { it.second > spaceNeeded }.minBy { it.second } return dirToDelete.second } }
0
Kotlin
0
0
149219285efdb1a4d2edc306cc449cce19250e85
2,211
advent-of-code-22
Creative Commons Zero v1.0 Universal
src/main/kotlin/ru/timakden/aoc/year2023/Day14.kt
timakden
76,895,831
false
{"Kotlin": 321649}
package ru.timakden.aoc.year2023 import ru.timakden.aoc.util.measure import ru.timakden.aoc.util.readInput import ru.timakden.aoc.year2023.Day14.Direction.* /** * [Day 14: Parabolic Reflector Dish](https://adventofcode.com/2023/day/14). */ object Day14 { @JvmStatic fun main(args: Array<String>) { measure { val input = readInput("year2023/Day14") println("Part One: ${part1(input)}") println("Part Two: ${part2(input)}") } } fun part1(input: List<String>): Int { val rows = input.size val columns: Int = input.first().length val platform = input.map { it.toCharArray() }.toTypedArray() tiltPlatform(platform, NORTH, columns, rows) return calculateTotalLoad(platform) } fun part2(input: List<String>): Int { val rows = input.size val columns: Int = input.first().length val platform = input.map { it.toCharArray() }.toTypedArray() val wrapperToIndex = HashMap<ArrayWrapper, Int>() val indexToWrapper = HashMap<Int, ArrayWrapper>() var counter = 0 val target = 1000000000 while (true) { val wrapper = ArrayWrapper(Array(rows) { i -> platform[i].copyOf() }) val start = wrapperToIndex.put(wrapper, counter) if (start != null) { val counterDifference = counter - start val previousWrapper = indexToWrapper[start + (target - start) % counterDifference]!! for (i in 0..<rows) for (j in 0..<columns) platform[i][j] = previousWrapper.array[i][j] break } indexToWrapper[counter] = wrapper counter++ tiltPlatform(platform, NORTH, columns, rows) tiltPlatform(platform, WEST, columns, rows) tiltPlatform(platform, SOUTH, columns, rows) tiltPlatform(platform, EAST, columns, rows) } return calculateTotalLoad(platform) } private class ArrayWrapper(val array: Array<CharArray>) { override fun equals(other: Any?): Boolean = other is ArrayWrapper && array.contentDeepEquals(other.array) override fun hashCode(): Int = array.contentDeepHashCode() } private fun tiltPlatform( platform: Array<CharArray>, direction: Direction, columns: Int, rows: Int ) { if (direction == NORTH || direction == SOUTH) { repeat(columns) { columnIndex -> val column = platform.map { it[columnIndex] }.toCharArray() tilt(column, direction) for (rowIndex in 0..platform.lastIndex) { platform[rowIndex][columnIndex] = column[rowIndex] } } } else { repeat(rows) { rowIndex -> val row = platform[rowIndex] tilt(row, direction) } } } private fun tilt( chars: CharArray, direction: Direction ) { for (i in 0..<chars.lastIndex) { for (j in 0..<(chars.lastIndex - i)) { val canSwap = if (direction == NORTH || direction == WEST) { chars[j] == '.' && chars[j + 1] == 'O' } else { chars[j] == 'O' && chars[j + 1] == '.' } if (canSwap) { val temp = chars[j] chars[j] = chars[j + 1] chars[j + 1] = temp } } } } private fun calculateTotalLoad(platform: Array<CharArray>): Int { var sum = 0 for (i in platform.indices) { sum += platform[i].count { it == 'O' } * (platform.size - i) } return sum } private enum class Direction { EAST, NORTH, SOUTH, WEST } }
0
Kotlin
0
3
acc4dceb69350c04f6ae42fc50315745f728cce1
3,920
advent-of-code
MIT License
src/main/kotlin/kr/co/programmers/P12952.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package kr.co.programmers import kotlin.math.abs // https://github.com/antop-dev/algorithm/issues/535 class P12952 { fun solution(n: Int): Int { return dfs(IntArray(n), 0) } private fun dfs(arr: IntArray, row: Int): Int { if (row == arr.size) { // n번째 행까지 퀸을 다 놓았다. return 1 } var count = 0 for (col in arr.indices) { // row 행, col 열에 퀸을 배치 시켜놓고 검사한다. arr[row] = col if (valid(arr, row)) { count += dfs(arr, row + 1) } } return count } // 현재 행의 퀸 위치와 이전 행들의 퀸 위치를 비교한다. private fun valid(arr: IntArray, currRow: Int): Boolean { for (prevRow in 0 until currRow) { if (arr[currRow] == arr[prevRow]) { // 같은 열이면 안됨 return false } // 대각선 위치면 안됨 (기울기로 계산) if (abs(currRow - prevRow) == abs(arr[currRow] - arr[prevRow])) { return false } } return true } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,167
algorithm
MIT License
src/main/kotlin/com/github/ferinagy/adventOfCode/aoc2015/2015-11.kt
ferinagy
432,170,488
false
{"Kotlin": 787586}
package com.github.ferinagy.adventOfCode.aoc2015 import com.github.ferinagy.adventOfCode.println import com.github.ferinagy.adventOfCode.readInputText fun main() { val input = readInputText(2015, "11-input") val test1 = readInputText(2015, "11-test1") println("Part1:") part1(test1).println() part1(input).println() println() println("Part2:") part2(test1).println() part2(input).println() } private fun part1(input: String): String { var pwd = input while (!meetsPolicy1(pwd)) pwd = pwd.increment() return pwd } private fun part2(input: String): String { var pwd = part1(input).increment() while (!meetsPolicy1(pwd)) pwd = pwd.increment() return pwd } private fun meetsPolicy1(pwd: String): Boolean { if ('i' in pwd || 'o' in pwd || 'l' in pwd) return false val hasSequence = pwd.windowed(3) .map { it.toCharArray() } .any { (a, b, c) -> a.inc() == b && b.inc() == c } if (!hasSequence) return false val hasPairs = pwd.windowed(2) .mapIndexed { index, s -> s to index } .filter { it.first[0] == it.first[1] } .let { pairs -> when { pairs.size < 2 -> false pairs.size == 2 -> pairs[1].second - pairs[0].second >= 2 else -> true } } if (!hasPairs) return false return true } private fun String.increment(): String { if (isEmpty()) return "a" return if (last() != 'z') { substring(0, lastIndex) + last().inc() } else { substring(0, lastIndex).increment() + 'a' } }
0
Kotlin
0
1
f4890c25841c78784b308db0c814d88cf2de384b
1,615
advent-of-code
MIT License
src/Day14.kt
anisch
573,147,806
false
{"Kotlin": 38951}
private typealias Cave = Array<Array<String>> private fun Cave.isFreeDown(row: Int, col: Int) = this[row + 1][col] == "." private fun Cave.isFreeLeftDown(row: Int, col: Int) = this[row + 1][col - 1] == "." private fun Cave.isFreeRightDown(row: Int, col: Int) = this[row + 1][col + 1] == "." private fun Cave.nextIsNotFree(row: Int, col: Int) = this[row + 1][col] != "." && this[row + 1][col - 1] != "." && this[row + 1][col + 1] != "." private fun Cave.nextIsBottom(row: Int) = row >= lastIndex private const val START_COL = 500 private fun createCave(input: List<String>): Cave { val cave = Array(START_COL + 1) { Array(2 * START_COL + 1) { "." } } input .map { line -> line.split(" -> ") } .map { line -> line.map { pos -> val row = pos.substringAfter(",").toInt() val col = pos.substringBefore(",").toInt() Pair(row, col) } } .forEach { line -> for (pos in 1..line.lastIndex) { val a = line[pos - 1] val b = line[pos] if (a.first == b.first) { // row == row var f = a.second var t = b.second if (f > t) f = t.also { t = f } for (col in f..t) { cave[a.first][col] = "#" } } else { // col == col var f = a.first var t = b.first if (f > t) f = t.also { t = f } for (row in f..t) { cave[row][a.second] = "#" } } } } return cave } fun main() { fun part1(input: List<String>): Int { val cave = createCave(input) var count = 0 val startPos = Pair(0, START_COL) var current = startPos while (!cave.nextIsBottom(current.first)) { count++ while (true) { when { cave.nextIsBottom(current.first) -> break cave.isFreeDown(current.first, current.second) -> { current = Pair(current.first + 1, current.second) } cave.isFreeLeftDown(current.first, current.second) -> { current = Pair(current.first + 1, current.second - 1) } cave.isFreeRightDown(current.first, current.second) -> { current = Pair(current.first + 1, current.second + 1) } cave.nextIsNotFree(current.first, current.second) -> { cave[current.first][current.second] = "o" current = startPos break } } } } return count - 1 } fun part2(input: List<String>): Int { val cave = createCave(input) val rowMax = cave .mapIndexed { i, s -> if (s.contains("#")) i else 0 } .max() cave.also { it[rowMax + 2] = Array(2 * START_COL + 1) { "#" } } var count = 0 val startPos = Pair(0, START_COL) var current = startPos while (!cave.nextIsNotFree(startPos.first, startPos.second)) { count++ while (true) { when { cave.isFreeDown(current.first, current.second) -> { current = Pair(current.first + 1, current.second) } cave.isFreeLeftDown(current.first, current.second) -> { current = Pair(current.first + 1, current.second - 1) } cave.isFreeRightDown(current.first, current.second) -> { current = Pair(current.first + 1, current.second + 1) } cave.nextIsNotFree(current.first, current.second) -> { cave[current.first][current.second] = "o" current = startPos break } } } } return count + 1 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day14_test") val input = readInput("Day14") check(part1(testInput) == 24) println(part1(input)) check(part2(testInput) == 93) println(part2(input)) }
0
Kotlin
0
0
4f45d264d578661957800cb01d63b6c7c00f97b1
4,676
Advent-of-Code-2022
Apache License 2.0
advent-of-code2015/src/main/kotlin/day4/Advent4.kt
REDNBLACK
128,669,137
false
null
package day4 import toHex import toMD5 /** --- Day 4: The Ideal Stocking Stuffer --- Santa needs help mining some AdventCoins (very similar to bitcoins) to use as gifts for all the economically forward-thinking little girls and boys. To do this, he needs to find MD5 hashes which, in hexadecimal, start with at least five zeroes. The input to the MD5 hash is some secret key (your puzzle input, given below) followed by a number in decimal. To mine AdventCoins, you must find Santa the lowest positive number (no leading zeroes: 1, 2, 3, ...) that produces such a hash. For example: If your secret key is abcdef, the answer is 609043, because the MD5 hash of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the lowest such number to do so. If your secret key is pqrstuv, the lowest number it combines with to make an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of pqrstuv1048970 looks like 000006136ef.... Your puzzle answer was 117946. The first half of this puzzle is complete! It provides one gold star: * --- Part Two --- Now find one that starts with six zeroes. */ fun main(args: Array<String>) { println(findIndex("abcdef", 5) == 609043L) println(findIndex("pqrstuv", 5) == 1048970L) val input = "ckczppom" println(findIndex(input, 5)) println(findIndex(input, 6)) } fun findIndex(input: String, length: Int): Long { val data = "0".repeat(length) tailrec fun loop(i: Long): Long { val hash = (input + i).toMD5().toHex() if (hash.startsWith(data)) return i return loop(i + 1) } return loop(0L) }
0
Kotlin
0
0
e282d1f0fd0b973e4b701c8c2af1dbf4f4a149c7
1,621
courses
MIT License
src/datastructure/graphs/RootenOranges.kt
minielectron
332,678,510
false
{"Java": 127791, "Kotlin": 48336}
package datastructure.graphs /** * You are given an m x n grid where each cell can have one of three values: ● 0 representing an empty cell, ● 1 representing a fresh orange, * or ● 2 representing a rotten orange. Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten. * Return the minimum number of minutes that must elapse until no cell has a fresh orange. * If this is impossible, return -1. * * Example 1 Input: grid = [[2,1,1],[1,1,0],[0,1,1]] * Output: 4 * * Example 2 Input: grid = [[2,1,1],[0,1,1],[1,0,1]] * Output: -1 Explanation: * * The orange in the bottom left corner (row 2, column 0) is never rotten, because rotting only happens 4-directionally * */ import java.util.LinkedList import java.util.Queue fun orangesRotting(grid: Array<IntArray>): Int { val rows = grid.size val cols = grid[0].size // Define four possible directions (up, down, left, right) val directions = arrayOf(intArrayOf(-1, 0), intArrayOf(1, 0), intArrayOf(0, -1), intArrayOf(0, 1)) // Initialize a queue to perform BFS val queue: Queue<kotlin.Pair<Int, Int>> = LinkedList() // Initialize variables to keep track of time and fresh oranges var minutes = 0 var freshOranges = 0 // Enqueue all rotten oranges and count fresh oranges // This step also ensure to handle multiple rotten oranges at same time. for (i in 0 until rows) { for (j in 0 until cols) { if (grid[i][j] == 2) { queue.offer(Pair(i, j)) } else if (grid[i][j] == 1) { freshOranges++ } } } // Perform BFS while (queue.isNotEmpty()) { val size = queue.size for (i in 0 until size) { val (x, y) = queue.poll() for (direction in directions) { val newX = x + direction[0] val newY = y + direction[1] if (newX in 0 until rows && newY in 0 until cols && grid[newX][newY] == 1) { grid[newX][newY] = 2 freshOranges-- queue.offer(Pair(newX, newY)) } } } minutes++ } // If there are still fresh oranges left, it's impossible to rot them all return if (freshOranges == 0) minutes else -1 } fun main() { val grid1 = arrayOf( intArrayOf(2, 1, 1), intArrayOf(1, 1, 0), intArrayOf(0, 1, 2) ) val grid2 = arrayOf( intArrayOf(2, 1, 1), intArrayOf(0, 1, 1), intArrayOf(1, 0, 1) ) println(orangesRotting(grid1)) // Output: 4 println(orangesRotting(grid2)) // Output: -1 } fun printMatrix(matrix: Array<IntArray>){ for (i in matrix.indices) { for (j in matrix[i].indices) { print("${matrix[i][j]} \t") } println() } }
0
Java
0
0
f2aaff0a995071d6e188ee19f72b78d07688a672
2,889
data-structure-and-coding-problems
Apache License 2.0
day02/src/main/kotlin/Main.kt
ickybodclay
159,694,344
false
null
import java.io.File fun main() { val input = File(ClassLoader.getSystemResource("input.txt").file) // Write solution here! var checksumA = 0 var checksumB = 0 val idList = ArrayList<String>() input.readLines().map{line -> idList.add(line) val letterCountMap = HashMap<Char, Int>() val letters = line.toCharArray() letters.forEach { if (letterCountMap.containsKey(it)) { letterCountMap[it] = letterCountMap[it]!!.plus(1) } else { letterCountMap[it] = 1 } } var twiceCount = 0 var thriceCount = 0 letterCountMap.map { when (it.value) { 2 -> twiceCount++ 3 -> thriceCount++ else -> { // do nothing } } } if (twiceCount > 0) checksumA++ if (thriceCount > 0) checksumB++ } println("[part1] checksum = ${checksumA * checksumB}") var minDiff = Integer.MAX_VALUE var minIndexA = 0 var minIndexB = 0 idList.forEachIndexed { i, strA -> idList.forEachIndexed { j, strB -> if (i != j) { val d = diff(strA, strB) if (d < minDiff) { minDiff = d minIndexA = i minIndexB = j } } } } println("[part2] diff = $minDiff - ${idList[minIndexA]}, ${idList[minIndexB]}") printCommonLetters(idList[minIndexA], idList[minIndexB]) } fun diff(strA: String, strB: String) : Int { var diff = 0 for (i in 0 until strA.length) { if (strA[i] != strB[i]) { diff++ } } return diff } fun printCommonLetters(strA: String, strB: String) { for (i in 0 until strA.length) { if (strA[i] == strB[i]) { print(strA[i]) } } println() }
0
Kotlin
0
0
9a055c79d261235cec3093f19f6828997b7a5fba
1,974
aoc2018
Apache License 2.0
archive/src/main/kotlin/com/grappenmaker/aoc/year20/Day18.kt
770grappenmaker
434,645,245
false
{"Kotlin": 409647, "Python": 647}
package com.grappenmaker.aoc.year20 import com.grappenmaker.aoc.PuzzleSet import com.grappenmaker.aoc.queueOf import com.grappenmaker.aoc.removeLastN fun PuzzleSet.day18() = puzzle(day = 18) { fun lexer(l: String): List<Token> { var ptr = 0 val partials = mutableListOf<Token>() val groupStack = queueOf<Int>() while (ptr < l.length) { when (l[ptr]) { in '0'..'9' -> { val startPtr = ptr while (ptr < l.length && l[ptr] in '0'..'9') ptr++ partials += PartialLiteral(l.substring(startPtr, ptr).trim().toLong()) ptr-- } '*' -> partials += MultiplyOperator '+' -> partials += AdditionOperator '(' -> groupStack += partials.size ')' -> partials += Group(partials.removeLastN(partials.size - groupStack.removeLast())) ' ' -> {} else -> error("Impossible") } ptr++ } return partials } fun parser(tokens: List<Token>): ExprElement { var idx = 0 var currentExpression: ExprElement? = null fun value(i: Int) = when (val v = tokens[i]) { AdditionOperator, MultiplyOperator -> error("Cannot have non value token in operator") is Group -> parser(v.children) is PartialLiteral -> Literal(v.value) } while (idx < tokens.size) { // DRY folks currentExpression = when (val curr = tokens[idx]) { AdditionOperator -> Addition(currentExpression ?: value(idx - 1), value(idx + 1)) MultiplyOperator -> Multiplication(currentExpression ?: value(idx - 1), value(idx + 1)) is Group -> currentExpression ?: parser(curr.children) else -> currentExpression } idx++ } return currentExpression ?: error("Expression was never parsed") } fun partTwoTokens(tokens: List<Token>): List<Token> { val new = mutableListOf<Token>() var idx = 0 while (idx in tokens.indices) { new += when (val v = tokens[idx]) { AdditionOperator -> { val oldRHS = tokens[idx + 1] val newRHS = if (oldRHS is Group) Group(partTwoTokens(oldRHS.children)) else oldRHS Group(listOf(new.removeLast(), AdditionOperator, newRHS)).also { idx++ } } is Group -> Group(partTwoTokens(v.children)) else -> v } idx++ } return new } val lexed = inputLines.map { lexer(it) } fun solve(parse: (List<Token>) -> ExprElement) = lexed.sumOf { parse(it).eval() }.s() partOne = solve { parser(it) } partTwo = solve { parser(partTwoTokens(it)) } } sealed interface Token data object AdditionOperator : Token data object MultiplyOperator : Token @JvmInline value class Group(val children: List<Token>) : Token @JvmInline value class PartialLiteral(val value: Long) : Token sealed interface ExprElement { fun eval(): Long } data class Addition(val lhs: ExprElement, val rhs: ExprElement) : ExprElement { override fun eval() = lhs.eval() + rhs.eval() } data class Multiplication(val lhs: ExprElement, val rhs: ExprElement) : ExprElement { override fun eval() = lhs.eval() * rhs.eval() } @JvmInline value class Literal(val value: Long) : ExprElement { override fun eval() = value }
0
Kotlin
0
7
92ef1b5ecc3cbe76d2ccd0303a73fddda82ba585
3,572
advent-of-code
The Unlicense
src/Day08.kt
MatthiasDruwe
571,730,990
false
{"Kotlin": 47864}
import java.lang.Error fun main() { fun part1(input: List<String>): Int { val output = input.map { line -> line.toCharArray().map { it.toString().toInt() } } val visibleFromLeft = output. map { row-> row.mapIndexed{index, value-> var visible = true repeat(index){ if(row[index - 1 - it]>=value){ visible = false } } visible } } val visibleFromRight = output.map { row-> row.mapIndexed{index, value-> var visible = true repeat(row.size-index-1){ if(row[index + it + 1]>=value){ visible = false } } visible } } val visibleFromTop = output.transpose().map { row-> row.mapIndexed{index, value-> var visible = true repeat(index){ if(row.toList()[index - 1 - it]>=value){ visible = false } } visible } }.transpose().toList() val visibleFromBottom = output.transpose().map { row-> row.mapIndexed{index, value-> var visible = true repeat(row.toList().size-index-1){ if(row.toList()[index + it + 1]>=value){ visible = false } } visible } }.transpose().toList() val result = output.mapIndexed{ i,row-> row.mapIndexed { j, _ -> visibleFromLeft[i][j] || visibleFromRight[i][j] || visibleFromTop[i].toList()[j] || visibleFromBottom[i].toList()[j] } }.sumOf { row -> row.count { it } } return result } fun part2(input: List<String>): Int { val output = input.map { line -> line.toCharArray().map { it.toString().toInt() } } val visibleFromLeft = output. map { row-> row.mapIndexed{index, value-> var count = 0 while (index - count -1 >= 0 && row[index - count-1] < value) { count++ } if(index - count!=0){ count++ } count } } val visibleFromRight = output. map { row-> row.mapIndexed{index, value-> var count = 0 while (index+count+1 < row.size && row[index+count+1] < value) { count++ } if(index + count+1 != row.size){ count++ } count } } val visibleFromTop = output.transpose(). map { row-> row.mapIndexed{index, value-> var count = 0 while (index - count -1 >= 0 && row.toList()[index - count-1] < value) { count++ } if(index - count!=0){ count++ } count } }.transpose().toList() val visibleFromBottom = output.transpose().map { row-> row.mapIndexed{index, value-> var count = 0 while (index+count+1 < row.toList().size && row.toList()[index+count+1] < value) { count++ } if(index + count+1 != row.toList().size){ count++ } count } }.transpose().toList() val result = output.mapIndexed{ i,row-> row.mapIndexed { j, _ -> visibleFromLeft[i][j] * visibleFromRight[i][j] * visibleFromTop[i].toList()[j] * visibleFromBottom[i].toList()[j] } }.maxOf { row -> row.maxOf { it } } return result } // test if implementation meets criteria from the description, like: val testInput = readInput("Day08_example") check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
f35f01cea5075cfe7b4a1ead9b6480ffa57b4989
4,415
Advent-of-code-2022
Apache License 2.0
src/main/kotlin/dev/patbeagan/days/Day12.kt
patbeagan1
576,401,502
false
{"Kotlin": 57404}
package dev.patbeagan.days import dev.patbeagan.List2D import org.jgrapht.alg.shortestpath.DijkstraShortestPath import org.jgrapht.graph.DefaultEdge import org.jgrapht.graph.SimpleGraph /** * [Day 12](https://adventofcode.com/2022/day/12) */ class Day12 : AdventDay<Int> { override fun part1(input: String): Int { val heightMap = parseInput(input) val graph = heightMap.asGraph() val path = DijkstraShortestPath(graph) .getPath( heightMap.start, heightMap.end ) val length = path.length return -1 } override fun part2(input: String) = 0 fun parseInput(input: String): HeightMap { var start: HeightMap.Tile? = null var end: HeightMap.Tile? = null return input .trim() .split("\n") .map { strings -> strings.map { char -> HeightMap.Tile(char).also { when (it.token) { 'S' -> start = it 'E' -> end = it } } } }.let { list -> HeightMap(start!!, end!!, List2D(list)).also { println(it) } } } class HeightMap( val start: Tile, val end: Tile, private val value: List2D<Tile> ) { init { assert(value.grid.distinctBy { it.size }.size == 1) } private fun getNeighbors(x: Int, y: Int) = Neighborhood( value.grid.getOrNull(y)?.getOrNull(x), value.grid.getOrNull(y)?.getOrNull(x - 1), value.grid.getOrNull(y - 1)?.getOrNull(x), value.grid.getOrNull(y)?.getOrNull(x + 1), value.grid.getOrNull(y + 1)?.getOrNull(x), ) fun asGraph(): SimpleGraph<Tile, DefaultEdge> = SimpleGraph<Tile, DefaultEdge>(DefaultEdge::class.java).apply { value.traverse { each, _, _ -> addVertex(each) } value.traverse { each, x, y -> getNeighbors(x, y).run { left ?.takeIf { each.token.code + 1 >= it.token.code } ?.let { addEdge(self, it) } top ?.takeIf { each.token.code + 1 >= it.token.code } ?.let { addEdge(self, it) } right ?.takeIf { each.token.code + 1 >= it.token.code } ?.let { addEdge(self, it) } bottom ?.takeIf { each.token.code + 1 >= it.token.code } ?.let { addEdge(self, it) } } } } @JvmInline value class Tile(val token: Char) data class Neighborhood( val self: Tile?, val left: Tile?, val top: Tile?, val right: Tile?, val bottom: Tile?, ) } }
0
Kotlin
0
0
4e25b38226bcd0dbd9c2ea18553c876bf2ec1722
3,163
AOC-2022-in-Kotlin
Apache License 2.0
src/Day04.kt
sushovan86
573,586,806
false
{"Kotlin": 47064}
fun main() { fun String.itemsAsRange(): IntRange { val (start, end) = split("-") return start.toInt()..end.toInt() } fun String.splitByComma() = split(",") operator fun IntRange.contains(other: IntRange): Boolean = first <= other.first && last >= other.last infix fun IntRange.containsSome(other: IntRange): Boolean = last >= other.first && first <= other.last fun part1(lines: List<String>): Int = lines .map(String::splitByComma) .count { (firstElf, secondElf) -> firstElf.itemsAsRange() in secondElf.itemsAsRange() || secondElf.itemsAsRange() in firstElf.itemsAsRange() } fun part2(lines: List<String>): Int = lines .map(String::splitByComma) .count { (firstElf, secondElf) -> firstElf.itemsAsRange() containsSome secondElf.itemsAsRange() } val testInput = readInput("Day04_test") check(part1(testInput) == 2) check(part2(testInput) == 4) val actualInput = readInput("Day04") println(part1(actualInput)) println(part2(actualInput)) }
0
Kotlin
0
0
d5f85b6a48e3505d06b4ae1027e734e66b324964
1,120
aoc-2022
Apache License 2.0
puzzles/src/main/kotlin/com/kotlinground/puzzles/arrays/maxaveragesubarray/maxAverageSubarray.kt
BrianLusina
113,182,832
false
{"Kotlin": 483489, "Shell": 7283, "Python": 1725}
package com.kotlinground.puzzles.arrays.maxaveragesubarray import kotlin.math.max /** * Finds the maximum average in a sub array of length k from the provided list/array. * * Uses a sliding window to find the maximum average. * This traverses over nums just once, and on the go keep determining the sums possible for the subarrays of length k. * To understand the idea, assume that we already know the sum of elements from index i to index i+k, say it is * current_sum. * * Now, to determine the sum of elements from the index i+1 to the index i+k+1, all we need to do is to subtract the * element nums[i] from x and to add the element nums[i+k+1] to current_sum. We can carry out our process based on this * idea and determine the maximum possible average. * * Complexity Analysis: * - Time Complexity: O(n). Iterate over the given nums array of length n only once * - Space Complexity: O(1). Constant extra space is used */ fun findMaxAverage(nums: IntArray, k: Int): Double { if (nums.size <= 1 || nums.size == k) { return nums.sum().toDouble() / k.toDouble() } var currentSum = 0 for (x in 0 until k) { currentSum += nums[x] } var currentMaxSum = currentSum for (right in k until nums.size) { currentSum += nums[right] - nums[right - k] currentMaxSum = max(currentSum, currentMaxSum) } return currentMaxSum.toDouble() / k.toDouble() }
1
Kotlin
1
0
5e3e45b84176ea2d9eb36f4f625de89d8685e000
1,428
KotlinGround
MIT License
src/day_11/Day11.kt
BrumelisMartins
572,847,918
false
{"Kotlin": 32376}
package day_11 import day_04.Group import readInput fun main() { val testMonkey0 = Monkey(startingItems = ArrayDeque(listOf(79, 98)), operation = { return@Monkey it * 19 }, divisor = 23, test = { return@Monkey if (it % 23 == 0L) 2 else 3 }) val testMonkey1 = Monkey(startingItems = ArrayDeque(listOf(54, 65, 75, 74)), operation = { return@Monkey it + 6 }, divisor = 19, test = { return@Monkey if (it % 19 == 0L) 2 else 0 }) val testMonkey2 = Monkey(startingItems = ArrayDeque(listOf(79, 60, 97)), operation = { return@Monkey it * it }, divisor = 13, test = { return@Monkey if (it % 13 == 0L) 1 else 3 }) val testMonkey3 = Monkey(startingItems = ArrayDeque(listOf(74)), operation = { return@Monkey it + 3 }, divisor = 17, test = { return@Monkey if (it % 17 == 0L) 0 else 1 }) val monkey0 = Monkey(startingItems = ArrayDeque(listOf(76, 88, 96, 97, 58, 61, 67)), operation = { return@Monkey it * 19 }, divisor = 3, test = { return@Monkey if (it % 3 == 0L) 2 else 3 }) val monkey1 = Monkey(startingItems = ArrayDeque(listOf(93, 71, 79, 83, 69, 70, 94, 98)), operation = { return@Monkey it + 8 }, divisor = 11, test = { return@Monkey if (it % 11 == 0L) 5 else 6 }) val monkey2 = Monkey(startingItems = ArrayDeque(listOf(50, 74, 67, 92, 61, 76)), operation = { return@Monkey it * 13 }, divisor = 19, test = { return@Monkey if (it % 19 == 0L) 3 else 1 }) val monkey3 = Monkey(startingItems = ArrayDeque(listOf(76, 92)), operation = { return@Monkey it + 6 }, divisor = 5, test = { return@Monkey if (it % 5 == 0L) 1 else 6 }) val monkey4 = Monkey(startingItems = ArrayDeque(listOf(74, 94, 55, 87, 62)), operation = { return@Monkey it + 5 }, divisor = 2, test = { return@Monkey if (it % 2 == 0L) 2 else 0 }) val monkey5 = Monkey(startingItems = ArrayDeque(listOf(59, 62, 53, 62)), operation = { return@Monkey it * it }, divisor = 7, test = { return@Monkey if (it % 7 == 0L) 4 else 7 }) val monkey6 = Monkey(startingItems = ArrayDeque(listOf(62)), operation = { return@Monkey it + 2 }, divisor = 17, test = { return@Monkey if (it % 17 == 0L) 5 else 7 }) val monkey7 = Monkey(startingItems = ArrayDeque(listOf(85, 54, 53)), operation = { return@Monkey it + 3 }, divisor = 13, test = { return@Monkey if (it % 13 == 0L) 4 else 0 }) val listOfMonkeys = listOf(monkey0, monkey1, monkey2, monkey3, monkey4, monkey5, monkey6, monkey7) val testList = listOf(testMonkey0, testMonkey1, testMonkey2, testMonkey3) val lcm = listOfMonkeys.map { it.divisor } .reduce { acc, bigInteger -> acc * bigInteger } fun shuffleItems(divideBy: Int) { listOfMonkeys.forEach { monkey -> monkey.startingItems.forEach { item -> val newWorryLevel = monkey.operation(item) / divideBy val relief = newWorryLevel % lcm listOfMonkeys[monkey.test(newWorryLevel)].startingItems.addLast(relief) monkey.inspectionCount++ } monkey.startingItems.clear() } } fun getMonkeyBusiness(): Long { val mostActiveMonkeys = listOfMonkeys.sortedByDescending { it.inspectionCount } .take(2) return mostActiveMonkeys.first().inspectionCount * mostActiveMonkeys.last().inspectionCount } fun part1(): Long { repeat(20) { shuffleItems(3) } return getMonkeyBusiness() } fun part2(): Long { repeat(10000) { shuffleItems(1) } return getMonkeyBusiness() } println(part2()) } class Monkey(val startingItems: ArrayDeque<Long>, val divisor: Int, val operation: (input: Long) -> Long, val test: (input: Long) -> Int, var inspectionCount: Long = 0)
0
Kotlin
0
0
3391b6df8f61d72272f07b89819c5b1c21d7806f
3,707
aoc-2022
Apache License 2.0
app/src/main/java/andrew/studio/com/ultrabuddymvvm/corealgorithms/models/Circle2D.kt
levulinh
186,353,048
false
null
package andrew.studio.com.ultrabuddymvvm.corealgorithms.models import andrew.studio.com.ultrabuddymvvm.corealgorithms.constants.Const.EPS import kotlin.math.abs import kotlin.math.pow import kotlin.math.sqrt class Circle2D(val center: Point2D, val radius: Float) { constructor(center: Point2D, pointOnCircle: Point2D) : this(center, center.distance(pointOnCircle)) private fun shortestDistance(p: Point2D): Float { return abs(p.distance(center) - radius) } fun closestPoint(p1: Point2D, p2: Point2D): Point2D { val dist1 = shortestDistance(p1) val dist2 = shortestDistance(p2) return if (dist1 >= dist2) p2 else p1 } fun intersection(l: Line2D): List<Point2D> { val a = l.a val b = l.b val x0 = center.x val y0 = center.y val r = radius val m = 1 + a.pow(2) val n = -2 * x0 + 2 * a * (b - y0) val p = x0.pow(2) + (b - y0).pow(2) - r.pow(2) val delta = n.pow(2) - 4 * m * p val xr0: Float val yr0: Float val xr1: Float val yr1: Float if (delta < -EPS) return listOf() if (-EPS <= delta && delta <= EPS) { xr0 = -n / (2 * m) yr0 = a * xr0 + b return listOf(Point2D(xr0, yr0)) } xr0 = (-n + sqrt(delta)) / (2 * m) xr1 = (-n - sqrt(delta)) / (2 * m) yr0 = a * xr0 + b yr1 = a * xr1 + b return listOf(Point2D(xr0, yr0), Point2D(xr1, yr1)) } // Source: https://stackoverflow.com/questions/3349125/circle-circle-intersection-points // Get a list of intersection points of 2 circles // INPUT: c (Circle2D) // OUTPUT: (vector<Point2D>) fun intersection(c: Circle2D): ArrayList<Point2D> { val r0 = this.radius val r1 = c.radius val h: Float val P0 = this.center val P1 = c.center val P2: Point2D val d = P0.distance(P1) val a: Float val x0: Float val x1: Float val x2: Float val y0: Float val y1: Float val y2: Float val x31: Float val x32: Float val y31: Float val y32: Float if (d > r0 + r1 - EPS || d < Math.abs(r0 - r1) + EPS) { return ArrayList() } else { a = ((Math.pow(r0.toDouble(), 2.0) - Math.pow(r1.toDouble(), 2.0) + Math.pow(d.toDouble(), 2.0)) / (2 * d)) .toFloat() P2 = P0 + (P1 + -P0) * a / d x0 = P0.x y0 = P0.y x1 = P1.x y1 = P1.y x2 = P2.x y2 = P2.y h = Math.sqrt(Math.pow(r0.toDouble(), 2.0) - Math.pow(a.toDouble(), 2.0)).toFloat() x31 = x2 + h * (y1 - y0) / d y31 = y2 - h * (x1 - x0) / d x32 = x2 - h * (y1 - y0) / d y32 = y2 + h * (x1 - x0) / d return ArrayList(listOf(Point2D(x31, y31), Point2D(x32, y32))) } } fun hasIntersection(c: Circle2D): Boolean{ val r0= radius val r1 = c.radius val P0 = center val P1 = c.center val d = P0.distance(P1) return !(d> r0 + r1 -EPS || d< abs(r0-r1) + EPS) } }
0
Kotlin
0
3
30ad2172e3454498c650a67725dc67402d5fd908
3,240
UltraBuddyMVVM
Creative Commons Attribution 3.0 Unported
4_kyu/The_observed_PIN.kt
UlrichBerntien
439,630,417
false
{"Go": 293606, "Rust": 191729, "Python": 184557, "Lua": 137612, "Assembly": 89144, "C": 76738, "Julia": 35473, "Kotlin": 33204, "R": 27633, "C#": 20860, "Shell": 14326, "Forth": 3750, "PLpgSQL": 2117, "C++": 122}
/** * Generates all possible PINs based on the observed PIN. The true PIN is around the observed PIN. * Each key could be also the key around the observed key. * * @param The observed PIN. * @return All possible PINs. */ fun getPINs(observed: String): List<String> = when (observed.length) { 0 -> emptyList() 1 -> keyNeighbours[observed[0]]!!.map { it.toString() } else -> { var accu = emptyList<String>() val lhs = keyNeighbours[observed[0]]!! getPINs(observed.substring(1)).forEach { rhs -> lhs.forEach { it -> accu += it + rhs } } accu } } /** * Map from observed key to all possible input kyes. Maps to an empty array if the key is not on the * keypad. */ private val keyNeighbours: Map<Char, CharArray> = generateKeyNeighbours("123,456,789, 0 ") /** * Generates the map from observed key to possible keys. * * @param layout The layout of the keypad. Rows of the key pad are separated by comma. * @return Map observerd key -> possible keys. */ private fun generateKeyNeighbours(layout: String): Map<Char, CharArray> { var accu = HashMap<Char, CharArray>().withDefault { CharArray(0) } val keys: Array<String> = layout.split(',').toTypedArray() fun getKey(x: Int, y: Int): Char? = if (y in keys.indices && x in keys[y].indices && keys[y][x] != ' ') keys[y][x] else null for (row in keys.indices) for (col in keys[row].indices) getKey(col, row)?.let { k -> var options = emptyList<Char>() listOf(Pair(0, +1), Pair(0, -1), Pair(+1, 0), Pair(-1, 0), Pair(0, 0)).forEach { (x, y) -> getKey(col + x, row + y)?.let { options += it } } accu[k] = options.toCharArray() } return accu }
0
Go
0
0
034d7f2bdcebc503b02877f2241e4dd143188b43
1,760
Codewars-Katas
MIT License
aoc16/src/main/kotlin/io/github/ajoz/workshop/day1/solution/Day1Solution.kt
ajoz
77,487,554
false
null
package io.github.ajoz.workshop.day1.solution import io.github.ajoz.workshop.sequences.firstRepeated import io.github.ajoz.workshop.sequences.scan /** * -------------------- Part 1 ----------------------- */ /** * Describes all possible directions that we can take in a taxi cab geometry. */ private enum class Direction { NORTH, EAST, WEST, SOUTH } /** * Describes a single Instruction in terms of direction instead of terms of Left or Right turn. */ private data class Instruction(val direction: Direction, val distance: Int) /** * Allows to generate a next [Instruction] from the given instruction string representation. In the puzzle it is stated * that we can have only two types of instructions: 'R' or 'L'. There is no theoretical limit to the size of the * instruction string or if the string instructions can be incorrect (wrong letter or more letters, no number of blocks, * negative number of blocks etc). * * After looking at the input data given, I assumed: * - instruction has only one letter {'R', 'L'} * - instruction has only a positive number of blocks * - number of blocks will never reach maximum of integer ;) * * To calculate next [Instruction] we need previous [Direction] and the single string instruction. For example let's say * that the current [Direction] is [Direction.EAST] and string instruction is 'L', then if we are pointing east and we * look on the left our next direction will be [Direction.NORTH]. * * I've implemented it as an extension function to the [Instruction] type to allow shorter notation in lambdas. */ private fun Instruction.next(instruction: String): Instruction { val turn = instruction.substring(0, 1) val numOfBlocks = instruction.substring(1).toInt() return when (turn) { "R" -> when (this.direction) { Direction.NORTH -> Instruction(Direction.EAST, numOfBlocks) Direction.EAST -> Instruction(Direction.SOUTH, numOfBlocks) Direction.WEST -> Instruction(Direction.NORTH, numOfBlocks) Direction.SOUTH -> Instruction(Direction.WEST, numOfBlocks) } "L" -> when (this.direction) { Direction.NORTH -> Instruction(Direction.WEST, numOfBlocks) Direction.EAST -> Instruction(Direction.NORTH, numOfBlocks) Direction.WEST -> Instruction(Direction.SOUTH, numOfBlocks) Direction.SOUTH -> Instruction(Direction.EAST, numOfBlocks) } else -> throw IllegalArgumentException("Unknown direction for instruction: $instruction") } } /** * Class represents calculated coordinates of each step of the route to Bunny HQ. */ private data class Coordinates(val x: Int, val y: Int) { /** * Calculates the L1 distance (other names include: l1 norm, snake distance, city block distance, Manhattan * distance, Manhattan length, rectilinear distance). * * @param to [Coordinates] to which the L1 distance will be calculated. */ fun getL1distance(to: Coordinates) = Math.abs(this.x - to.x) + Math.abs(this.y - to.y) } /** * Allows to generate coordinates of the next step of the route. As we can go only in any of the four directions: North, * East, West or South then Coordinates of next step will either differ in the x or y -axis to the previous one. * * I used a copy method that helps to create a new object based on the given one (also change only set of its * properties) */ private fun Coordinates.next(direction: Direction, distance: Int) = when (direction) { Direction.NORTH -> this.copy(y = this.y + distance) Direction.EAST -> this.copy(x = this.x + distance) Direction.WEST -> this.copy(x = this.x - distance) Direction.SOUTH -> this.copy(y = this.y - distance) } /** * Allows to generate coordinates of the next step of the route. */ private fun Coordinates.next(instruction: Instruction) = next(instruction.direction, instruction.distance) /** * Calculates the shortest path from the start [Coordinates] (0, 0) to the [Coordinates] calculated by processing the * given instructions string. * * Algorithm is simple: * 1. split the instruction string into a [Sequence] of [String] (from: "L2, L3" we get: "L2", " L3") * 2. trim the white chars from the [Sequence] of [String] we got in previous step * 3. each instruction can be built only when we know what was the previous instruction, so we [scan] the whole * [Sequence] of [String]. Method [scan] for a Sequence<T> takes an initial value of type R and a lambda (R, T) -> R to * process all the elements of the sequence. As the function (R, T) -> R expects two arguments, for the first element in * the Sequence<T> the specified initial value is used. This way in our case we can easily calculate each [Instruction]. * 4. Change [Instruction] to [Coordinates] * 5. Pick last [Coordinates] from the [Sequence] */ fun getShortestPathLengthToDestination(instructions: String): Int { val startInstruction = Instruction(Direction.NORTH, 0) //after we land in the city we are pointing North val startCoords = Coordinates(0, 0) val stopCoords = instructions .splitToSequence(delimiters = ",", ignoreCase = true) .map(String::trim) .scan(startInstruction, Instruction::next) .scan(startCoords, Coordinates::next) .last() return startCoords.getL1distance(stopCoords) } /** * -------------------- Part 2 ----------------------- */ /** * Calculates a [List] of [Coordinates] for a given [Direction] and a distance. It's working through a infinite * [Sequence] of value 1 (this is the step), it takes only first few values (the amount of values taken is equal to the * distance), then it just calculates [Coordinates] on the path in the given [Direction]. * * Before I implement a nice flatScan method, we need to return a [List] because */ private fun Coordinates.path(direction: Direction, distance: Int) = generateSequence { 1 } .take(distance) .scan(this) { coordinates, value -> coordinates.next(direction, value) } .toList() /** * Calculates a [List] of [Coordinates] for a given [Instruction]. */ private fun Coordinates.path(instruction: Instruction) = path(instruction.direction, instruction.distance) /** * Calculates the shortest path from the start [Coordinates] (0, 0) to the first repeating [Coordinates] calculated by * processing the given instructions string. * * Algorithm is simple: * 1. split the instruction string into a [Sequence] of [String] (from: "L2, L3" we get: "L2", " L3") * 2. trim the white chars from the [Sequence] of [String] we got in previous step * 3. each instruction can be built only when we know what was the previous instruction, so we [scan] the whole * [Sequence] of [String]. Method [scan] for a Sequence<T> takes an initial value of type R and a lambda (R, T) -> R to * process all the elements of the sequence. As the function (R, T) -> R expects two arguments, for the first element in * the Sequence<T> the specified initial value is used. This way in our case we can easily calculate each [Instruction]. * 4. between each previous and next [Coordinates] a [List] of [Coordinates] is calculated (a path). As we are working * after [Int] values for coordinates, the calculated path will have a difference of 1 between two coordinates that are * next of each other (in terms of x or y value) * 5. we need to flatten Sequence<List<Coordinates>> to Sequence<Coordinates> * 6. we take the fist repeated coordinates */ fun getShortestPathLengthToFirstRepeatedDestination(instructions: String): Int { val startInstruction = Instruction(Direction.NORTH, 0) //after we land in the city we are pointing North val startCoords = Coordinates(0, 0) val partialPath = instructions .splitToSequence(delimiters = ",", ignoreCase = true) .map(String::trim) .scan(startInstruction, Instruction::next) .scan(listOf(startCoords)) { list, instr -> list.last().path(instr) } //flatScan?? .flatten() val fullPath = sequenceOf(startCoords) + partialPath val stopCoords = fullPath.firstRepeated() return startCoords.getL1distance(stopCoords) }
0
Kotlin
0
0
3275cb1c7638e734634dc9270b460c08b214eda5
8,269
kotlin-workshop
Apache License 2.0
src/nativeMain/kotlin/com.qiaoyuang.algorithm/round0/Questions56.kt
qiaoyuang
100,944,213
false
{"Kotlin": 338134}
package com.qiaoyuang.algorithm.round0 import kotlin.math.* fun test56() { val array1 = intArrayOf(2, 4, 3, 6, 3, 2, 5, 5) val array2 = intArrayOf(1, 3, 9, 6, 6, 8, 1, 3, 8, 0) print("重复数字:") findNumAppearOnce(array1).forEach { print("$it ") } print("\n重复数字:") findNumAppearOnce(array2).forEach { print("$it ") } println() val array3 = intArrayOf(6, 7, 6, 8, 8, 7, 5, 7, 8, 6) println(findNumberAppearingOnce(array3)) } /** * 题目一:数组中有两个数字只出现了一次,另外每个数字都出现了两次,求这两个数字 */ fun findNumAppearOnce(array: IntArray): IntArray { require(array.size % 2 == 0) { "输入的数组的长度必须是偶数" } var temp = array[0] for (i in 1 until array.size) temp = temp xor array[i] var index = 0 var bitMusk = 1 while (true) { if (temp and bitMusk != 0) break index++ bitMusk = bitMusk shl 1 } val left = ArrayList<Int>() val right = ArrayList<Int>() bitMusk = 1 array.forEach { val a = it shr index if (a and bitMusk == 0) left.add(it) else right.add(it) } val result = IntArray(2) result[0] = if (left.size == 1) { left[0] } else { var tempLeft = left[0] for (i in 1 until left.size) tempLeft = tempLeft xor left[i] tempLeft } result[1] = if (right.size == 1) { right[0] } else { var tempRight = right[0] for (i in 1 until right.size) tempRight = tempRight xor right[i] tempRight } return result } /** * 题目二:一个数组中只有一个数出现了1次,其它数都出现了3次,找出出现1次的数 */ fun findNumberAppearingOnce(array: IntArray): Int { val sum = IntArray(32) var bitMusk = 1 var result = 0 for (i in 0..31) { array.forEach { sum[i] += it and bitMusk } if (sum[i] % 3 != 0) result += 2.toFloat().pow(i.toFloat()).toInt() bitMusk = bitMusk shl 1 } return result }
0
Kotlin
3
6
66d94b4a8fa307020d515d4d5d54a77c0bab6c4f
1,875
Algorithm
Apache License 2.0
src/_2022/Day07.kt
albertogarrido
572,874,945
false
{"Kotlin": 36434}
package _2022 import printlnSuccess import readInput fun main() { runTests() runScenario(readInput("2022", "day07")) } private fun runScenario(input: List<String>) { println("Result Part 1: ${part1(input)}") println("Result Part 2: ${part2(input)}") } private fun part1(input: List<String>): Int { val dirTree: HashMap<String, Int> = parseDirectoryTree(input) var total = 0 dirTree.forEach { if (it.key != "/") { if (it.value < 100000) { total += it.value } } } return total } private fun part2(input: List<String>): Int { val totalSpace = 70000000 val spaceNeeded = 30000000 val dirTree: HashMap<String, Int> = parseDirectoryTree(input) val currentFreeSpace = totalSpace - dirTree["/"]!! val spaceToFree = spaceNeeded - currentFreeSpace val deletionCandidates = HashMap<String, Int>() dirTree.forEach { if (it.value >= spaceToFree) { deletionCandidates[it.key] = it.value } } return deletionCandidates.minBy { it.value }.value } fun parseDirectoryTree(input: List<String>): HashMap<String, Int> { val hashMap: HashMap<String, Int> = HashMap() var currentPath = "" input.forEach { line -> val lineDetails = line.split(" ") when { isCommand(lineDetails[0]) -> { if (lineDetails[1] == "cd" && lineDetails[2] != "..") { currentPath += if (lineDetails[2] == "/") { lineDetails[2] } else { "${lineDetails[2]}/" } if (!hashMap.containsKey(currentPath)) { hashMap[currentPath] = 0 } } else if (lineDetails[1] == "cd" && lineDetails[2] == "..") { currentPath = removeLastDir(currentPath) } } isFile(lineDetails[0]) -> { hashMap[currentPath] = hashMap[currentPath]!!.plus(lineDetails[0].toInt()) var tempPath = currentPath repeat((currentPath.split('/').size - 2 downTo 0).count()) { tempPath = removeLastDir(tempPath) if (hashMap.containsKey(tempPath)) { hashMap[tempPath] = hashMap[tempPath]!!.plus(lineDetails[0].toInt()) } } } } } return hashMap } fun isFile(s: String) = s.toIntOrNull() != null fun isCommand(s: String) = s == "$" fun removeLastDir(currentPath: String): String { var path = currentPath path = path.removeRange(path.lastIndex, path.lastIndex + 1) val index = path.lastIndexOf("/") path = path.removeRange(index + 1, path.lastIndex + 1) return path } private fun runTests() { var passed = true runCatching { part1(readInput("2022", "day07_test_p1")).also { check(it == 95437) { "part 1: expected 95437, obtained $it" } } }.onFailure { passed = false System.err.println("[test 1 failed] ${it.message}") }.onSuccess { printlnSuccess(">> [test 1 success] <<") } runCatching { part2(readInput("2022", "day07_test_p1")).also { check(it == 24933642) { "part 2: expected 24933642, obtained $it" } } }.onFailure { passed = false System.err.println("[test failed] ${it.message}") }.onSuccess { printlnSuccess(">> [test 2 success] <<") } runCatching { part1(readInput("2022", "day07")).also { check(it == 1792222) { "Final Result Part 1: expected 1792222, obtained $it" } } }.onFailure { passed = false System.err.println("[test final result 1 failed] ${it.message}") }.onSuccess { printlnSuccess(">> [test final result 1 success] <<") } runCatching { part2(readInput("2022", "day07")).also { check(it == 1112963) { "Final Result Part 1: expected 1112963, obtained $it" } } }.onFailure { passed = false System.err.println("[test final result 2 failed] ${it.message}") }.onSuccess { printlnSuccess(">> [test final result 2 success] <<") } if (passed) printlnSuccess(">> all tests passed <<") }
0
Kotlin
0
0
ef310c5375f67d66f4709b5ac410d3a6a4889ca6
4,461
AdventOfCode.kt
Apache License 2.0
src/day03/Day03.kt
tschens95
573,743,557
false
{"Kotlin": 32775}
package day03 import readInput fun main() { fun part1(input: List<String>): Int { var totalSum = 0 for (s in input) { val half = s.length / 2 val parts = s.chunked(half) val set1 = parts[0].toSet() val set2 = parts[1].toSet() for (c in set1) { if (set2.contains(c)) { if (c.isLowerCase()) { totalSum += (c.code - 96) break } else { totalSum += (c.code - 38) break } } } } return totalSum } fun part2(input: List<String>): Int { var totalSum = 0 var index = 0 while (index < input.size) { val s1 = input[index].toSet() val s2 = input[index + 1].toSet() val s3 = input[index + 2].toSet() var found = false while (!found) { for (c in s1) { if (s2.contains(c) && s3.contains(c)) { totalSum += if (c.isLowerCase()) { (c.code - 96) } else { (c.code - 38) } found = true break } } if (found) break } index += 3 } return totalSum } val testInput = "v<KEY>\n" + "<KEY>" + "PmmdzqPrVvPwwTWBwg\n" + "wMqvLMZHhHMvwLHjbvcjnnSBnvTQFn\n" + "ttgJtRGJQctTZtZT\n" + "CrZsJsPPZsGzwwsLwLmpwMDw" println(part1(testInput.split("\n"))) println(part2(testInput.split("\n"))) val input = readInput("03") println(part1(input)) println(part2(input)) }
0
Kotlin
0
2
9d78a9bcd69abc9f025a6a0bde923f53c2d8b301
1,980
AdventOfCode2022
Apache License 2.0
kotlin/2423_Remove_Letter_To_Equalize_Frequency/solution.kt
giovanniPepi
607,763,568
false
null
// Solution for the Leet Code problem 2423, Remove Letter To Equalize Frequency // The problem descrition is found on the following link: // https://leetcode.com/problems/remove-letter-to-equalize-frequency/description/ class Solution { fun equalFrequency(word: String): Boolean { // map for associating a char with its frequency var charCounter = mutableMapOf<Char,Int>() // loop to count chars and store in charCounter for (char in word){ // if map contains the letter as key, adds 1 to its own value if (charCounter.containsKey(char)){ charCounter[char] = charCounter[char]!! + 1 // if map does not contain the letter, must // include it in the map with value 1 (first occurence) } else charCounter[char] = 1 } //listOfValues stores a list of the map values var listOfValues = mutableListOf<Int>() charCounter.forEach {entry -> listOfValues.add(entry.value) } // a copy is created to play with listOfValues while // listOfValues is never changed var copy = mutableListOf<Int>() // for every item in the list for (i in listOfValues.indices){ // copy is reset to original listOfValues list copy = listOfValues.toMutableList() // one single item in list is reduced in 1 copy[i] = copy[i] - 1 // if that item became zero, it's removed from list if (copy[i] == 0) copy.remove(0) // if max and min are equal, all items in list are equal, so return true if (copy.max() == copy.min()) return true } // if never true, it's false return false } }
0
Kotlin
1
0
ccb853bce41206f30cbfb1ff4ca8e8f22feb0ee2
1,775
bastterCode
MIT License
src/Day01.kt
A55enz10
573,364,112
false
{"Kotlin": 15119}
fun main() { fun part1(input: List<String>): Int { return getElvesKcalList(input).maxOrNull()!! } fun part2(input: List<String>): Int { val elvesKcal = getElvesKcalList(input) elvesKcal.sortDescending() return elvesKcal[0] + elvesKcal[1] + elvesKcal[2] } // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") println(part1(testInput)) check(part1(testInput) == 1) val input = readInput("Day01") println(part1(input)) println(part2(input)) } fun getElvesKcalList(input: List<String>): MutableList<Int> { val elvesKcal = mutableListOf<Int>() var sum = 0 input.forEachIndexed { index, s -> if (s.isEmpty()) { elvesKcal.add(sum) sum = 0 } else { sum += s.toInt() if (input.size == index+1) elvesKcal.add(sum) } } return elvesKcal }
0
Kotlin
0
1
8627efc194d281a0e9c328eb6e0b5f401b759c6c
959
advent-of-code-2022
Apache License 2.0
2020/05/Solution.kt
AdrianMiozga
588,519,359
false
{"Kotlin": 110785, "Python": 11275, "Assembly": 3369, "C": 2378, "Pawn": 1390, "Dart": 732}
import java.io.File private const val FILENAME = "2020/05/input.txt" fun main() { partOne() partTwo() } private fun partOne() { val lines = File(FILENAME).readLines() var max = 0 for (line in lines) { val rows = line.slice(0..6).toList() val row = bsp(0, 127, rows) val columns = line.slice(7 until line.length).toList() val column = bsp(0, 7, columns) val seatId = row * 8 + column if (seatId > max) { max = seatId } } println(max) } private fun partTwo() { val lines = File(FILENAME).readLines() val seats = mutableListOf<Int>() for (line in lines) { val rows = line.slice(0..6).toList() val row = bsp(0, 127, rows) val columns = line.slice(7 until line.length).toList() val column = bsp(0, 7, columns) val seatId = row * 8 + column seats.add(seatId) } seats.sort() for ((index, element) in seats.withIndex()) { if (seats.size - 1 == index) { break } if (element + 1 != seats[index + 1]) { println(element + 1) } } } private fun bsp(min: Int, max: Int, directions: List<Char>): Int { if (directions.size == 1) { return if (directions.first() in charArrayOf('F', 'L')) { min } else { max } } val half = (max - min) / 2 val newDirections = directions.slice(1 until directions.size) return if (directions.first() in charArrayOf('F', 'L')) { bsp(min, min + half, newDirections) } else { bsp(min + half + 1, max, newDirections) } }
0
Kotlin
0
0
c9cba875089d8d4fb145932c45c2d487ccc7e8e5
1,669
Advent-of-Code
MIT License
src/day03/day03.kt
PS-MS
572,890,533
false
null
package day03 import readInput fun main() { val alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray() fun part1(input: List<String>): Int { return input.sumOf { val one = it.substring(0, it.length / 2) val two = it.substring(it.length / 2) val sharedIndex = one.indexOfAny(two.toCharArray()) alphabet.indexOf(one[sharedIndex]) + 1 } } fun part2(input: List<String>): Int { return input.windowed(3, 3).sumOf { group -> val (a, b, c) = group val sharedIndex = a.indexOfFirst { aChar -> b.indexOfFirst { it == aChar } != -1 && c.indexOfFirst { it == aChar } != -1 } alphabet.indexOf(a[sharedIndex]) + 1 } } // test if implementation meets criteria from the description, like: val testInput = readInput("day03/test") println("testInput 1") println(part1(testInput)) println("testInput 2") println(part2(testInput)) check(part1(testInput) == 157) val input = readInput("day03/real") println(part1(input)) check(part1(input) == 7793) println(part2(input)) check(part2(input) == 2499) }
0
Kotlin
0
0
24f280a1d8ad69e83755391121f6107f12ffebc0
1,223
AOC2022
Apache License 2.0
src/main/kotlin/com/leetcode/P130.kt
antop-dev
229,558,170
false
{"Kotlin": 695315, "Java": 213000}
package com.leetcode // https://github.com/antop-dev/algorithm/issues/313 class P130 { fun solve(board: Array<CharArray>) { val m = board.size val n = board[0].size // [0] : 방문 여부 // [1] : 'O' 여부 val visited = Array(m) { Array(n) { IntArray(2) } } for (j in 0 until n) { dfs(board, visited, 0, j) dfs(board, visited, m - 1, j) } for (i in 1 until m - 1) { dfs(board, visited, i, 0) dfs(board, visited, i, n - 1) } // 방문되지 않은 곳을 전부 'X'로 변경 for (i in 0 until m) { for (j in 0 until n) { if (visited[i][j][0] == 0) { board[i][j] = 'X' } } } } private fun dfs(board: Array<CharArray>, visited: Array<Array<IntArray>>, i: Int, j: Int) { if (i !in 0..board.lastIndex) return if (j !in 0..board[0].lastIndex) return val here = visited[i][j] if (here[0] == 1) return here[0] = 1 // visited if (board[i][j] == 'X') return here[1] = 1 // 'O' dfs(board, visited, i - 1, j) // ↑ dfs(board, visited, i + 1, j) // ↓ dfs(board, visited, i, j - 1) // ← dfs(board, visited, i, j + 1) // → } }
1
Kotlin
0
0
9a3e762af93b078a2abd0d97543123a06e327164
1,355
algorithm
MIT License
src/main/kotlin/dec2/Main.kt
dladukedev
318,188,745
false
null
package dec2 data class PasswordItem( val minInt: Int, val maxInt: Int, val targetChar: Char, val password: String ) fun parseInput(input: String): PasswordItem { val (rangeBlock, targetBlock, password) = input.split(' ') val (minCountString, maxCountString) = rangeBlock.split('-') val minCount = minCountString.toInt() val maxCount = maxCountString.toInt() val targetChar = targetBlock.first() return PasswordItem( minCount, maxCount, targetChar, password ) } fun partOneValidation(item: PasswordItem): Boolean { val targetCount = item.password.count { it == item.targetChar } return targetCount in item.minInt..item.maxInt } fun partTwoValidtion(item: PasswordItem): Boolean { val indexOne = item.minInt - 1 val indexTwo = item.maxInt - 1 val firstChar = if(item.password.length > indexOne) item.password[indexOne] else null val secondChar = if(item.password.length > indexTwo) item.password[indexTwo] else null if(firstChar == null || secondChar == null) { return false } val firstCharMatchesTarget = firstChar == item.targetChar val secondCharMatchesTarget = secondChar == item.targetChar return firstCharMatchesTarget && !secondCharMatchesTarget || !firstCharMatchesTarget && secondCharMatchesTarget } fun main() { val passwords = input.map { parseInput(it) } println("------------ PART 1 ------------") val partOneValidCount = passwords.count { partOneValidation(it) } println(partOneValidCount) println("------------ PART 2 ------------") val partTwoValidCount = passwords.count { partTwoValidtion(it) } println(partTwoValidCount) }
0
Kotlin
0
0
d4591312ddd1586dec6acecd285ac311db176f45
1,716
advent-of-code-2020
MIT License
src/Day01.kt
pydaoc
573,843,750
false
{"Kotlin": 8484}
import kotlin.math.* fun main() { fun part1(input: List<String>): Int { var referenceCalories = 0 var currentCalories = 0 for (line in input) { if (line.isEmpty()) { referenceCalories = max(referenceCalories, currentCalories) currentCalories = 0 } else { val calories = line.toInt() currentCalories += calories } } referenceCalories = max(referenceCalories, currentCalories) return referenceCalories } fun part2(input: List<String>): Int { var currentCalories = 0 val elfCalories = arrayListOf<Int>() for (line in input) { if (line.isEmpty()) { elfCalories.add(currentCalories) currentCalories = 0 } else { val calories = line.toInt() currentCalories += calories } } elfCalories.add(currentCalories) val sortedElfCalories = elfCalories.sortedDescending() return sortedElfCalories[0] + sortedElfCalories[1] + sortedElfCalories[2] } val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
970dedbfaf09d12a29315c6b8631fa66eb394054
1,250
advent-of-code-kotlin-2022
Apache License 2.0
src/day13/Day13.kt
Oktosha
573,139,677
false
{"Kotlin": 110908}
package day13 import pass import java.io.File import kotlin.math.min import kotlin.math.sign sealed class PacketElement { class Num(val value: Int) : PacketElement() { override fun toString(): String { return value.toString() } } class Lst(val elements: MutableList<PacketElement>) : PacketElement() { override fun toString(): String { return elements.joinToString(prefix = "[", postfix = "]", separator = ",") } } } fun cmpSignForList(l1: PacketElement.Lst, l2: PacketElement.Lst): Int { val len = min(l1.elements.size, l2.elements.size) for (i in 0 until len) { val currentSign = cmpSign(l1.elements[i], l2.elements[i]) if (currentSign != 0) { return currentSign } } return (l1.elements.size - l2.elements.size).sign } fun cmpSign(p1: PacketElement, p2: PacketElement): Int { return when (p1) { is PacketElement.Num -> when (p2) { is PacketElement.Num -> (p1.value - p2.value).sign is PacketElement.Lst -> cmpSign(PacketElement.Lst(mutableListOf(p1)), p2) } is PacketElement.Lst -> when (p2) { is PacketElement.Num -> cmpSign(p1, PacketElement.Lst(mutableListOf(p2))) is PacketElement.Lst -> cmpSignForList(p1, p2) } } } sealed class Token { class Num(val value: Int) : Token() { override fun toString(): String { return value.toString() } } // object Comma : Token() object OpenBracket : Token() { override fun toString(): String { return "[" } } object ClosingBracket : Token() { override fun toString(): String { return "]" } } } fun tokenize(input: String): List<Token> { val ans = mutableListOf<Token>() var currentNum = -1 for (ch in input) { if (ch.isDigit()) { currentNum = if (currentNum == -1) { ch.digitToInt() } else { currentNum * 10 + ch.digitToInt() } } else { if (currentNum != -1) { ans.add(Token.Num(currentNum)) currentNum = -1 } when (ch) { '[' -> ans.add(Token.OpenBracket) ']' -> ans.add(Token.ClosingBracket) ',' -> pass // ans.add(Token.Comma) else -> throw Exception("Invalid symbol $ch in input") } } } return ans } fun parsePacket(input: List<Token>): PacketElement { // println(input) val resultParent = PacketElement.Lst(mutableListOf()) val stack = ArrayDeque(listOf(resultParent)) for (token in input) { when (token) { Token.OpenBracket -> { val listElment = PacketElement.Lst(mutableListOf()) stack.last().elements.add(listElment) stack.addLast(listElment) } Token.ClosingBracket -> { stack.removeLast() } is Token.Num -> { stack.last().elements.add(PacketElement.Num(token.value)) } } } return resultParent.elements[0] } fun parsePacket(input: String): PacketElement { val answer = parsePacket(tokenize(input)) if (answer.toString() != input) { throw Exception("Broken parsing:\n$input\n$answer") } return answer } fun part1(input: String): List<Int> { val objectPairs = input .trim() .split("\n\n") .map { it.split("\n").map(::parsePacket) } val ans = mutableListOf<Int>() for (i in objectPairs.indices) { val (p1, p2) = objectPairs[i] val cmpResult = cmpSign(p1, p2) if (cmpResult == -1) { ans.add(i + 1) } else if (cmpResult == 0) { throw Exception("Found equals at ${i + 1}!") } } return ans } fun part2(input: String): List<Int> { val packetStrings = input.split("\n").map{it.trim()}.filter { it != "" } val dividerPacketStrings = listOf("[[2]]", "[[6]]") val packets = (packetStrings + dividerPacketStrings).map(::parsePacket) val sortedPackets = packets.sortedWith { p1, p2 -> cmpSign(p1, p2) } return dividerPacketStrings.map { divider -> sortedPackets.indexOfFirst { it.toString() == divider } + 1} } fun main() { println("Day 13") val testInput = File("src","Day13-test.txt").readText() val input = File("src","Day13.txt").readText() val testAns1 = part1(testInput) println("test part 1: ${testAns1.sum()} <- $testAns1") val realAns1 = part1(input) println("real part 1: ${realAns1.sum()} <- $realAns1") val testAns2 = part2(testInput) println("test part 2: ${testAns2[0] * testAns2[1]} <- $testAns2") val realAns2 = part2(input) println("test part 2: ${realAns2[0] * realAns2[1]} <- $realAns2") }
0
Kotlin
0
0
e53eea61440f7de4f2284eb811d355f2f4a25f8c
4,924
aoc-2022
Apache License 2.0
src/Day15.kt
GarrettShorr
571,769,671
false
{"Kotlin": 82669}
import kotlin.math.abs import kotlin.properties.Delegates import kotlin.system.measureNanoTime fun main() { data class Point(val x: Int, val y: Int) { fun manhattanDistanceTo(other: Point): Int { return abs(x - other.x) + abs(y - other.y) } } data class Sensor(val location: Point, val nearestBeacon: Point) { var range by Delegates.notNull<Int>() init { range = location.manhattanDistanceTo(nearestBeacon) } override fun toString(): String { return "Sensor(location=$location, nearestBeacon=$nearestBeacon, range=$range)" } } fun part1(input: List<String>): Int { val Y = 2000000 val sensorsText = input.map { it.split(": closest beacon is at ") }.map { it.map { it.split(", ") } } val sensors = mutableListOf<Sensor>() sensorsText.forEach { sensors.add( Sensor( Point(it[0][0].split("=")[1].toInt(), it[0][1].split("=")[1].toInt()), Point(it[1][0].split("=")[1].toInt(), it[1][1].split("=")[1].toInt()) ) ) } var cantBeThere = 0 for (x in -10_000_000..10_000_000) { // for(x in -50..50) { // println(sensors.count { Point(x, Y).manhattanDistanceTo(it.location) <= it.range }) if (sensors.count { Point(x, Y).manhattanDistanceTo(it.location) <= it.range } >= 1) { cantBeThere++ } } return cantBeThere - 1 } fun part2(input: List<String>): Long { val Y = 2000000 val sensorsText = input.map { it.split(": closest beacon is at ") }.map { it.map { it.split(", ") } } val sensors = mutableListOf<Sensor>() sensorsText.forEach { sensors.add( Sensor( Point(it[0][0].split("=")[1].toInt(), it[0][1].split("=")[1].toInt()), Point(it[1][0].split("=")[1].toInt(), it[1][1].split("=")[1].toInt()) ) ) } sensors.sortBy { it.location.x } // println(sensors) // var count = 0 // var xx = 596122 // var yy = 1712290 // for(sensor in sensors) { // println("${Point(xx, yy).manhattanDistanceTo(sensor.location)} ${sensor.range}") // } // return 0 var (realX, realY) = listOf(0, 0) // for(x in 0..20) { // for (y in 0..20) { var x = 0 var y = 0 sensors.sortBy { it.location.x } loop@ while (true) { // sensors.first { it.location.manhattanDistanceTo(Point(x, y)) <= it.range && it.location.x >= x } for (sensor in sensors) { var d = sensor.location.manhattanDistanceTo(Point(x, y)) if (d <= sensor.range) { var dx = sensor.range - d // x = abs(x - dx - sensor.location.x) + sensor.location.x + 1 x = sensor.range - abs(sensor.location.y - y) + sensor.location.x if (x >= 4000000) { x = 0 y++ continue@loop } // println("x: $x y: $y ${sensors.count { it.location.manhattanDistanceTo(Point(x, y)) >= it.range }} " + // "${x.toLong() * 4000000L + y.toLong()} sensors size: ${sensors.size}") if (sensors.count { it.location.manhattanDistanceTo(Point(x, y)) > it.range } == sensors.size) { return x.toLong() * 4000000L + y.toLong() } } else { x++ //// println( // "x: $x y: $y ${ // sensors.count { // it.location.manhattanDistanceTo( // Point( // x, // y // ) // ) >= it.range // } // } ${x.toLong() * 4000000L + y.toLong()}") if (sensors.count { it.location.manhattanDistanceTo(Point(x, y)) > it.range } == sensors.size) { return x.toLong() * 4000000L + y.toLong() } // x++ // if (x >= 4000000) { // x = 0 // y++ // } // continue@loop } } } //// println(sensors.count { Point(x, Y).manhattanDistanceTo(it.location) <= it.range }) // if (sensors.count { Point(x, y).manhattanDistanceTo(it.location) > it.range } >= sensors.size) { // realX = x // realY = y // break // } else { // continue // } // } // } println("x: $realX y: $realY") return x.toLong() * 4000000L + y.toLong() } // test if implementation meets criteria from the description, like: val testInput = readInput("Day15_test") // println(part1(testInput)) // println(part2(testInput)) val input = readInput("Day15") // output(part1(input)) println(formatNanos(measureNanoTime { output(part2(input)) })) }
0
Kotlin
0
0
391336623968f210a19797b44d027b05f31484b5
4,637
AdventOfCode2022
Apache License 2.0
code/src/main/kotlin/substring/TwoWay.kt
illarionov
500,219,308
false
{"Kotlin": 16978, "HTML": 1856, "Makefile": 561, "SCSS": 63}
package substring import java.lang.Integer.MAX_VALUE import kotlin.math.abs private val IntProgression.length get() = when (this.step) { 1, -1 -> if (!this.isEmpty()) abs(this.last - this.first) + 1 else 0 else -> count() } class TwoWay { internal data class Factorization(val pattern: String, val left: IntRange, val right: IntRange, val rightPeriod: Int) { val criticalPosition get() = left.last fun leftIsSuffixOfRight(): Boolean { return left.all { i -> pattern[i] == pattern[right.first + rightPeriod - left.length + i] } } init { check(criticalPosition >= -1) check(left.last + 1 == right.first) } } fun isSubstring(text: String, pattern: String): Boolean { when { text.isEmpty() -> return pattern.isEmpty() pattern.isEmpty() -> return true } return getAllSubstrings(text, pattern, 1).isNotEmpty() } internal fun getAllSubstrings(text: String, pattern: String, maxCount: Int = MAX_VALUE): List<Int> { when { text.isEmpty() -> return emptyList() pattern.isEmpty() -> return text.indices.toList() } val result: MutableList<Int> = mutableListOf() val factorization = factorize(pattern) if (factorization.leftIsSuffixOfRight()) { // CP1 val (_, left, right, period) = factorization var pos = 0 var memPrefix = -1 while (pos + pattern.length <= text.length) { // Сравнение правой части val i = (maxOf(right.first, memPrefix + 1) .. right.last).find { i -> pattern[i] != text[pos + i] } if (i != null) { pos = pos + i - right.first + 1 memPrefix = -1 } else { // Сравнение левой части val match = (left.last downTo memPrefix + 1).all { j -> pattern[j] == text[pos + j] } if (match) { result.add(pos) if (result.size >= maxCount) break } pos += period memPrefix = pattern.length - period - 1 } } } else { // CP2 val left = factorization.left.reversed() val right = factorization.right val q = maxOf(left.length, right.length) + 1 var pos = 0 while (pos + pattern.length <= text.length) { // Сравнение правой части val i = right.find { i -> pattern[i] != text[pos + i] } if (i != null) { pos = pos + i - right.first + 1 } else { // Сравнение левой части val match = left.all { j -> pattern[j] == text[pos + j] } if (match) { result.add(pos) if (result.size >= maxCount) break } pos += q } } } return result } private fun factorize(pattern: String): Factorization { val naturalOrder = computeMaxSuffixAndPeriod(pattern, naturalOrder()) val reverseOrder = computeMaxSuffixAndPeriod(pattern, reverseOrder()) return if (naturalOrder.right.length <= reverseOrder.right.length) naturalOrder else reverseOrder } internal fun computeMaxSuffixAndPeriod(pattern: String, comparator: Comparator<in Char>): Factorization { var maxSuffix = -1 var j = 0 var k = 1 var period = 1 while (j + k < pattern.length) { val a = pattern[j + k] val b = pattern[maxSuffix + k] val abOrder = comparator.compare(a, b) when { // a < b abOrder < 0 -> { j += k k = 1 period = j - maxSuffix } // a == b abOrder == 0 -> { if (k != period) { k += 1 } else { j += period k = 1 } } // a > b else -> { maxSuffix = j j = maxSuffix + 1 k = 1 period = 1 } } } return Factorization(pattern, 0 .. maxSuffix, maxSuffix + 1 .. pattern.lastIndex, period ) } }
1
Kotlin
0
2
2ead4380e8b6ccd92af6329a1c9a6b78ce3a5c8b
4,897
strstr
Creative Commons Zero v1.0 Universal
src/main/kotlin/days/Day2.kt
vovarova
572,952,098
false
{"Kotlin": 103799}
package days class Day2 : Day(2) { object GameRules { const val winGamePoint = 6 const val loseGamePoint = 0 const val drawGamePoint = 3 val gameElements = listOf( GameElement(name = "Rock", id = 'A', point = 1, winsFromId = 'C', looseFromId = 'B'), GameElement(name = "Paper", id = 'B', point = 2, winsFromId = 'A', looseFromId = 'C'), GameElement(name = "Scissors", id = 'C', point = 3, winsFromId = 'B', looseFromId = 'A') ).map { it.id to it }.toMap() class GameElement( val name: String, val id: Char, val point: Int, private val winsFromId: Char, private val looseFromId: Char ) { fun calcPoint(opponentMove: Char): Int { return when (opponentMove) { id -> point + drawGamePoint winsFromId -> point + winGamePoint else -> point + loseGamePoint } } fun winsFrom(): GameElement { return gameElements[winsFromId]!! } fun looseFrom(): GameElement { return gameElements[looseFromId]!! } } } class GameMove(val line: String) { fun yourMove(): Char { return line[2] } fun opponentMove(): Char { return line[0] } } override fun partOne(): Any { return inputList.map { GameMove(it) }.map { when (it.yourMove()) { 'X' -> GameRules.gameElements['A']!!.calcPoint(it.opponentMove()) 'Y' -> GameRules.gameElements['B']!!.calcPoint(it.opponentMove()) else -> GameRules.gameElements['C']!!.calcPoint(it.opponentMove()) } }.sum() } override fun partTwo(): Any { /** * X means you need to lose * Y means you need to end the round in a draw * and Z means you need to win */ return inputList.map { GameMove(it) }.map { when (it.yourMove()) { 'X' -> GameRules.gameElements[it.opponentMove()]!!.winsFrom().calcPoint(it.opponentMove()) 'Y' -> GameRules.gameElements[it.opponentMove()]!!.calcPoint(it.opponentMove()) else -> GameRules.gameElements[it.opponentMove()]!!.looseFrom().calcPoint(it.opponentMove()) } }.sum() } }
0
Kotlin
0
0
e34e353c7733549146653341e4b1a5e9195fece6
2,503
adventofcode_2022
Creative Commons Zero v1.0 Universal
src/Day08/Day08.kt
AllePilli
572,859,920
false
{"Kotlin": 47397}
package Day08 import checkAndPrint import getElementsUntilEdges import measureAndPrintTimeMillis import multOf import onEdge import readInput fun main() { fun List<String>.prepareInput() = map { line -> line.map(Char::digitToInt) } fun part1(input: List<List<Int>>): Int { fun isVisible(rowIdx: Int, colIdx: Int): Boolean { val treeHeight = input[rowIdx][colIdx] return input.onEdge(rowIdx, colIdx) || input.getElementsUntilEdges(rowIdx, colIdx).any { branch -> branch.all { it < treeHeight } } } return input.indices.sumOf { rowIdx -> input.first().indices.count { colIdx -> isVisible(rowIdx, colIdx) } } } fun part2(input: List<List<Int>>): Int { fun List<Int>.scenicScore(treeHeight: Int): Int = (takeWhile { it < treeHeight }.size + 1).coerceAtMost(size) return input.indices.maxOf { rowIdx -> input.first().indices.maxOf { colIdx -> if (input.onEdge(rowIdx, colIdx)) 0 else { val treeHeight = input[rowIdx][colIdx] input.getElementsUntilEdges(rowIdx, colIdx).multOf { it.scenicScore(treeHeight) } } } } } val testInput = readInput("Day08_test").prepareInput() check(part1(testInput) == 21) check(part2(testInput) == 8) val input = readInput("Day08").prepareInput() measureAndPrintTimeMillis { checkAndPrint(part1(input), 1776) } measureAndPrintTimeMillis { checkAndPrint(part2(input), 234416) } }
0
Kotlin
0
0
614d0ca9cc925cf1f6cfba21bf7dc80ba24e6643
1,622
AdventOfCode2022
Apache License 2.0
src/day_3.kt
gardnerdickson
152,621,962
false
null
import java.io.File fun main(args: Array<String>) { val input = "res/day_3_input.txt" val answer1 = Day3.part1(input) println("Part 1: $answer1") val answer2 = Day3.part2(input) println("Part 2: $answer2") } object Day3 { private enum class Turn { SANTA, ROBO_SANTA; fun nextTurn(): Turn { return when (this) { Turn.SANTA -> Turn.ROBO_SANTA else -> Turn.SANTA } } } fun part1(input: String): Int { val directions = File(input).readText().toCharArray() var currentPosition = Position(0, 0) val positions = mutableSetOf<Position>() positions.add(currentPosition) for (direction in directions) { val nextPosition = currentPosition.move(direction) positions.add(nextPosition) currentPosition = nextPosition } return positions.size } fun part2(input: String): Int { val directions = File(input).readText().toCharArray() var currentSantaPosition = Position(0, 0) var currentRoboSantaPosition = Position(0, 0) val positions = mutableSetOf<Position>() positions.add(currentSantaPosition) var turn = Turn.SANTA for (direction in directions) { when (turn) { Turn.SANTA -> { val nextPosition = currentSantaPosition.move(direction) positions.add(nextPosition) currentSantaPosition = nextPosition } Turn.ROBO_SANTA -> { val nextPosition = currentRoboSantaPosition.move(direction) positions.add(nextPosition) currentRoboSantaPosition = nextPosition } } turn = turn.nextTurn() } return positions.size } } data class Position(val x: Int, val y: Int) { fun move(direction: Char): Position { return when (direction) { '^' -> Position(this.x, this.y + 1) '>' -> Position(this.x + 1, this.y) 'v' -> Position(this.x, this.y - 1) '<' -> Position(this.x - 1, this.y) else -> throw IllegalArgumentException("Input contained invalid character: $direction") } } }
0
Kotlin
0
0
4a23ab367a87cae5771c3c8d841303b984474547
2,343
advent-of-code-2015
MIT License
src/main/kotlin/2.kt
torland-klev
730,585,319
false
{"Kotlin": 74157}
package klev import klev.`2`.Game.Companion.toGame import klev.`2`.Round.Companion.toRound import java.math.BigDecimal object `2` : Day { private data class Game( val id: Int, val rounds: List<Round>, ) { companion object { val gameRegex = Regex("\\d+(?=:)") fun String.toGame() = Game( id = gameRegex.find(this)!!.value.toInt(), rounds = this.split(";").map { it.toRound() }, ) } } private data class Round( val red: Int, val green: Int, val blue: Int, ) { companion object { val redRegex = Regex("\\d+(?= red)") val greenRegex = Regex("\\d+(?= green)") val blueRegex = Regex("\\d+(?= blue)") fun String.toRound() = Round( redRegex.find(this)?.value?.toInt() ?: 0, greenRegex.find(this)?.value?.toInt() ?: 0, blueRegex.find(this)?.value?.toInt() ?: 0, ) } } override fun firstSolution(input: List<String>) = input.map { it.toGame() }.filter { it.rounds.all { it.red <= 12 && it.green <= 13 && it.blue <= 14 } }.sumOf { it.id }.toString() override fun secondSolution(input: List<String>): String { return splitInput().map { it.toGame() }.sumOf { val maxRed = it.rounds.maxBy { it.red }.red val maxGreen = it.rounds.maxBy { it.green }.green val maxBlue = it.rounds.maxBy { it.blue }.blue BigDecimal(maxRed).times(BigDecimal(maxGreen)).times(BigDecimal(maxBlue)) }.toPlainString() } override fun input() = """ Game 1: 1 blue, 2 green, 3 red; 7 red, 8 green; 1 green, 2 red, 1 blue; 2 green, 3 red, 1 blue; 8 green, 1 blue Game 2: 12 blue, 3 green, 5 red; 1 green, 1 blue, 8 red; 2 green, 12 blue, 5 red; 7 red, 2 green, 13 blue Game 3: 7 red, 4 blue, 13 green; 14 green, 1 blue, 1 red; 1 red, 11 green, 5 blue; 10 green, 3 blue, 3 red; 5 red, 5 blue, 3 green Game 4: 3 red, 1 green, 17 blue; 11 red, 6 green, 18 blue; 4 red, 9 blue, 5 green; 2 blue, 2 green, 1 red; 1 red, 2 green; 7 green, 9 red, 2 blue Game 5: 1 blue, 9 green, 5 red; 12 green, 1 blue, 15 red; 17 green, 8 red, 4 blue; 7 green, 12 red Game 6: 4 blue, 9 green, 7 red; 1 red, 7 green, 4 blue; 4 blue, 8 green, 3 red; 2 green, 1 red, 2 blue Game 7: 3 green, 1 blue; 11 red, 2 blue; 2 red, 3 blue, 6 green Game 8: 8 blue, 1 red, 11 green; 11 blue, 10 red, 7 green; 4 blue, 6 green, 4 red; 3 blue, 2 green, 6 red; 4 green, 4 red, 1 blue; 5 blue, 12 red, 9 green Game 9: 2 green, 20 blue, 4 red; 3 green, 7 red, 2 blue; 3 green, 17 blue; 20 blue, 7 red, 2 green; 4 green, 6 red, 1 blue; 7 red, 5 green, 19 blue Game 10: 2 red, 9 green, 8 blue; 16 green, 1 red, 7 blue; 3 blue, 5 red, 9 green; 5 blue, 2 red, 11 green Game 11: 6 blue, 3 green, 8 red; 6 blue, 4 green; 1 red, 3 green, 4 blue Game 12: 18 red, 16 blue, 9 green; 10 green, 6 blue; 12 blue, 5 green, 15 red; 16 blue, 4 red, 8 green Game 13: 2 green; 1 blue, 4 green; 1 green, 3 blue, 6 red; 2 red, 2 blue; 3 red, 2 green; 8 red, 2 blue, 5 green Game 14: 8 red, 3 blue, 3 green; 3 green; 4 red, 7 blue, 5 green; 10 blue, 15 red, 1 green; 4 green, 14 red, 7 blue Game 15: 8 red, 9 blue; 1 green, 4 red, 3 blue; 15 red, 3 blue, 1 green; 17 red, 6 blue Game 16: 1 green, 10 blue, 13 red; 16 red, 1 green; 7 red; 9 blue, 12 red, 1 green; 6 red, 13 blue, 1 green Game 17: 6 green, 1 blue, 1 red; 2 blue, 9 green, 1 red; 6 green, 1 blue, 2 red Game 18: 5 red, 4 green, 1 blue; 5 blue, 6 red, 6 green; 12 red, 16 blue, 11 green Game 19: 6 red, 9 green; 1 blue, 4 red; 12 green; 5 green, 2 blue, 9 red Game 20: 15 blue, 15 red, 1 green; 2 green, 5 red, 13 blue; 15 red, 2 green, 15 blue; 3 green, 3 red, 13 blue; 6 blue, 1 green, 8 red Game 21: 3 red, 3 blue; 4 blue, 3 red; 4 red, 8 blue, 1 green; 1 blue, 2 red, 7 green; 3 green, 3 blue; 3 blue Game 22: 5 green, 3 blue, 7 red; 7 green, 1 blue, 5 red; 5 red, 3 blue, 3 green; 12 green, 7 red, 1 blue; 2 red, 3 blue; 7 green, 11 red, 1 blue Game 23: 9 blue, 8 red; 9 blue, 9 green, 8 red; 3 red, 6 blue, 14 green; 3 blue, 4 red; 5 red, 14 green, 9 blue; 12 blue, 8 red, 8 green Game 24: 15 green, 1 red, 1 blue; 6 red, 2 green, 7 blue; 7 blue, 2 green, 4 red; 8 blue, 5 red, 8 green; 5 blue, 3 red, 7 green; 6 blue, 12 green Game 25: 7 blue, 16 green, 1 red; 13 green; 4 red, 9 green, 2 blue; 11 green, 1 red, 1 blue; 3 blue, 5 green, 5 red Game 26: 2 blue, 11 red, 10 green; 5 green, 1 blue, 2 red; 7 green, 5 red, 14 blue; 11 green, 1 blue, 10 red Game 27: 2 green, 8 blue, 2 red; 1 blue, 1 red, 5 green; 3 green, 7 blue Game 28: 9 green, 15 red, 1 blue; 3 blue, 3 green; 18 green, 15 red, 7 blue; 3 red, 10 blue, 7 green; 6 red, 5 green, 8 blue; 2 blue, 7 red, 3 green Game 29: 5 blue, 3 red, 7 green; 17 blue, 8 red, 11 green; 6 red, 5 blue, 12 green; 3 red, 10 blue, 10 green; 4 blue, 10 green; 6 red, 2 blue, 9 green Game 30: 4 green, 5 blue, 1 red; 19 red, 18 blue, 3 green; 18 red, 18 blue, 1 green; 5 green, 14 blue, 4 red; 4 red, 3 green, 18 blue; 6 blue, 3 green, 17 red Game 31: 2 red, 2 green; 13 red, 9 blue; 4 blue, 3 green, 1 red; 12 blue, 12 red, 4 green; 9 red, 6 blue; 12 red, 1 green, 2 blue Game 32: 11 red, 5 blue, 9 green; 3 blue, 8 red, 15 green; 3 green, 7 blue, 17 red; 2 green, 9 red, 1 blue; 2 blue, 6 green, 2 red Game 33: 13 blue, 2 green; 1 green, 1 red, 14 blue; 3 green, 6 blue, 1 red; 12 blue, 1 green; 9 blue, 2 green; 4 blue, 1 red Game 34: 15 green, 2 red, 13 blue; 1 green, 6 blue; 2 red, 1 green, 7 blue Game 35: 1 green, 12 red, 2 blue; 3 red, 5 blue; 6 red; 3 red, 3 blue; 4 red Game 36: 6 blue, 8 red, 1 green; 7 green, 6 blue, 10 red; 7 blue, 9 green, 5 red; 7 green, 1 red, 1 blue Game 37: 6 blue, 2 green, 4 red; 2 green, 3 blue, 6 red; 1 green, 17 red, 14 blue; 10 red, 2 blue; 19 red, 1 green, 8 blue; 2 red, 2 green Game 38: 6 red, 1 green, 5 blue; 2 blue, 15 green, 6 red; 10 green, 3 blue, 6 red; 5 blue, 8 green, 2 red Game 39: 8 blue, 5 green, 5 red; 4 green, 5 blue; 2 red, 7 blue; 3 green, 15 blue, 4 red Game 40: 8 green, 12 red, 10 blue; 8 blue, 8 red, 9 green; 1 green, 10 blue, 9 red; 17 red, 7 green, 2 blue; 6 green, 11 red; 2 green, 2 blue, 8 red Game 41: 11 red, 5 green, 1 blue; 5 green; 3 green; 2 red Game 42: 8 blue, 11 red, 1 green; 12 red, 10 green, 6 blue; 2 red, 6 blue, 16 green; 18 blue, 2 red, 4 green; 10 blue, 10 green, 3 red Game 43: 4 red, 3 blue; 2 blue, 10 red, 4 green; 3 blue, 7 red, 5 green; 2 green, 8 red; 1 green, 3 blue; 10 red, 1 green Game 44: 1 red, 9 blue; 2 red, 19 blue; 2 green, 6 red, 15 blue; 11 blue, 8 red, 4 green Game 45: 7 green, 4 blue, 1 red; 5 blue, 8 green; 5 blue, 8 green; 5 blue, 6 green; 6 green, 3 blue Game 46: 2 red, 2 green; 6 red, 5 blue, 2 green; 13 green, 8 blue, 2 red Game 47: 1 red, 5 green; 1 blue, 15 red, 5 green; 6 red, 6 green, 3 blue; 5 blue, 4 red; 4 blue, 7 red Game 48: 16 blue, 16 red; 11 blue, 16 red; 15 red, 1 green; 6 blue, 1 green, 2 red Game 49: 9 green, 20 blue, 7 red; 16 blue, 6 red; 9 green, 1 blue, 1 red; 8 red, 12 green, 15 blue; 3 blue, 2 green, 8 red Game 50: 9 red, 6 green, 9 blue; 6 blue, 2 red, 6 green; 7 green, 4 red, 6 blue; 2 red, 7 blue, 9 green; 4 red, 8 green, 9 blue Game 51: 1 blue, 2 red, 6 green; 1 blue, 4 red; 6 red, 2 green; 6 red, 8 green, 2 blue; 2 blue, 8 green, 4 red Game 52: 10 green, 1 blue; 5 blue, 5 green; 5 blue, 2 red, 4 green; 2 blue, 12 green Game 53: 3 blue, 8 red, 7 green; 7 blue, 7 red, 12 green; 8 blue, 9 green, 7 red; 7 red, 10 blue, 1 green Game 54: 3 green, 4 blue; 1 blue, 5 red, 4 green; 7 red, 4 blue; 2 green, 4 blue; 1 red, 4 blue; 1 blue, 6 red, 5 green Game 55: 7 red, 13 blue; 7 blue, 1 red, 1 green; 3 red, 5 blue Game 56: 6 red, 3 green, 1 blue; 7 blue, 2 green, 5 red; 4 green, 4 red; 8 blue, 1 green; 6 green, 6 blue, 4 red Game 57: 14 blue, 12 green, 8 red; 1 red, 20 blue, 10 green; 4 red, 16 green, 15 blue Game 58: 3 blue, 12 red; 9 red, 3 blue, 2 green; 2 blue, 2 red; 7 red, 4 green, 5 blue; 10 red, 1 blue Game 59: 7 red, 11 blue, 17 green; 5 red, 4 green, 7 blue; 8 red, 6 blue, 17 green; 16 green, 7 red, 6 blue; 5 blue, 12 green, 9 red; 7 blue, 3 red, 9 green Game 60: 4 red, 5 green, 4 blue; 15 green, 4 red, 18 blue; 6 blue, 1 red, 1 green; 14 blue, 12 green, 1 red; 2 green, 5 red, 4 blue; 2 green, 1 blue, 5 red Game 61: 3 green, 2 blue; 4 green, 6 blue; 2 red, 12 green, 11 blue; 1 red, 9 green, 7 blue; 2 red, 11 green, 19 blue; 9 blue, 1 red, 2 green Game 62: 17 green; 3 blue, 14 red, 14 green; 17 red, 16 green, 5 blue; 17 green, 5 blue, 1 red; 4 blue, 17 red, 13 green Game 63: 4 green, 2 red, 2 blue; 10 green, 15 blue, 3 red; 5 green, 5 blue, 5 red Game 64: 9 red, 10 blue, 2 green; 1 green, 4 red, 1 blue; 5 green, 2 blue, 11 red Game 65: 1 blue, 10 red, 5 green; 1 blue, 4 green, 2 red; 3 blue, 1 green; 11 red, 2 blue, 5 green; 9 green, 11 red, 3 blue Game 66: 6 blue, 13 green, 2 red; 5 green, 1 red, 7 blue; 11 green, 3 red; 5 blue, 1 red, 2 green Game 67: 1 red, 10 green, 4 blue; 5 blue, 3 red, 9 green; 4 blue, 3 red, 1 green; 14 red, 4 blue, 10 green Game 68: 12 green, 3 red, 3 blue; 2 green, 1 red, 2 blue; 1 blue, 3 green, 3 red; 1 green, 1 red, 6 blue Game 69: 3 blue, 10 red, 4 green; 4 green, 1 blue, 6 red; 1 blue, 1 red, 6 green; 4 red, 3 blue, 5 green Game 70: 9 blue, 3 green; 1 red, 2 green, 6 blue; 9 blue, 2 green; 6 blue, 1 red; 6 green, 1 red, 6 blue; 3 blue, 1 red, 2 green Game 71: 2 blue; 2 red, 3 blue; 12 blue, 3 red, 1 green; 1 green; 1 red, 7 blue; 1 red, 9 blue Game 72: 1 red, 1 green, 5 blue; 19 blue, 1 red, 3 green; 3 green, 1 red; 1 red, 13 blue, 1 green; 1 red, 1 green, 19 blue; 6 blue Game 73: 12 blue, 5 red, 5 green; 12 blue, 1 red, 4 green; 7 green, 4 red, 6 blue; 1 green, 4 blue, 10 red; 9 blue, 14 green Game 74: 9 blue, 1 green, 2 red; 7 blue, 15 red; 5 red, 2 green, 17 blue Game 75: 8 red; 1 green, 14 red; 2 blue, 3 green, 10 red; 2 blue, 4 green Game 76: 2 red, 3 blue; 6 blue, 8 red; 6 blue, 9 red; 7 blue; 7 red, 1 green, 5 blue Game 77: 6 green, 5 red, 12 blue; 16 blue, 5 red, 11 green; 4 blue, 5 green; 10 blue, 4 red, 9 green Game 78: 7 blue, 2 red; 1 green, 5 red; 4 blue Game 79: 3 green, 4 blue; 4 blue, 1 green, 2 red; 8 blue, 3 green Game 80: 10 red, 8 green; 4 red, 1 blue; 7 red, 4 green, 4 blue; 6 green, 1 red, 3 blue; 9 red, 3 blue; 4 green, 8 blue, 13 red Game 81: 3 red, 6 green, 9 blue; 9 red, 1 blue, 3 green; 5 red, 11 green, 1 blue Game 82: 6 green, 11 blue, 8 red; 16 green, 9 red, 7 blue; 6 blue, 17 green, 4 red Game 83: 6 blue, 1 green, 8 red; 3 green, 5 blue; 4 red, 2 green, 8 blue Game 84: 2 green, 1 red, 5 blue; 1 red, 2 green, 5 blue; 2 blue; 9 blue Game 85: 9 blue, 2 red; 7 green, 13 blue, 3 red; 11 green, 17 blue Game 86: 2 green, 15 red; 12 red, 1 blue, 3 green; 2 blue, 4 red, 3 green; 5 red; 6 green, 2 blue Game 87: 17 blue, 3 red; 3 red, 4 green, 10 blue; 3 red, 14 blue, 4 green Game 88: 13 green, 10 blue, 10 red; 14 green, 3 red, 4 blue; 13 blue, 7 red, 16 green; 10 blue, 6 green, 1 red; 9 red, 4 green, 14 blue Game 89: 3 green, 16 blue, 14 red; 4 green, 13 red, 1 blue; 6 red, 17 blue, 1 green; 4 red, 7 blue Game 90: 2 blue, 2 red; 5 blue, 10 red, 6 green; 10 red, 3 green, 1 blue; 10 blue, 6 green, 7 red Game 91: 15 green, 5 blue, 12 red; 9 red, 1 green, 4 blue; 2 red, 15 green, 3 blue; 18 green, 5 blue, 2 red Game 92: 7 green, 7 blue, 12 red; 7 blue, 9 red, 2 green; 11 blue, 10 red, 10 green; 2 green, 4 red, 11 blue; 12 red, 4 blue; 2 red, 6 green Game 93: 2 green, 8 blue; 2 blue, 1 red, 3 green; 4 blue, 8 green, 1 red; 8 blue, 5 green; 3 green Game 94: 16 red, 1 green, 5 blue; 11 red, 9 blue; 5 red, 2 green, 6 blue Game 95: 4 blue, 7 red; 7 red, 10 green; 11 green; 2 red, 10 green; 6 blue, 8 red; 8 red, 2 green, 6 blue Game 96: 9 blue, 12 green; 6 green, 9 blue, 11 red; 7 blue, 5 green, 10 red Game 97: 1 green, 6 red, 1 blue; 6 red, 3 green, 6 blue; 9 green, 5 blue, 9 red; 13 red, 7 green Game 98: 9 red, 12 green, 2 blue; 1 blue, 11 green, 10 red; 10 red, 2 green Game 99: 4 red, 13 blue, 7 green; 7 green, 5 blue, 6 red; 7 green, 11 blue; 10 green, 2 red, 8 blue Game 100: 2 green, 1 blue; 9 red, 8 green, 1 blue; 4 red, 10 green, 1 blue; 17 green, 8 red; 5 green, 1 blue, 7 red; 14 red, 12 green """.trimIndent() }
0
Kotlin
0
0
e18afa4a7c0c7b7e12744c38c1a57f42f055dcdf
13,220
advent-of-code-2023
MIT License
src/main/java/challenges/educative_grokking_coding_interview/top_k_elements/_4/FrequentElements.kt
ShabanKamell
342,007,920
false
null
package challenges.educative_grokking_coding_interview.top_k_elements._4 import java.util.* /** Given an array of integers, arr, and an integer, k, return the k most frequent elements. Note: You can return the answer in any order. https://www.educative.io/courses/grokking-coding-interview-patterns-java/m2ND3J3GY2n */ internal object FrequentElements { private fun topKFrequent(arr: IntArray, k: Int): List<Int> { // Find the frequency of each number val numFrequencyMap: MutableMap<Int, Int> = HashMap() for (n in arr) numFrequencyMap[n] = numFrequencyMap.getOrDefault(n, 0) + 1 val topKElements = PriorityQueue { (_, value): Map.Entry<Int, Int>, (_, value1): Map.Entry<Int, Int> -> value - value1 } // Go through all numbers of the numFrequencyMap and push them into topKElements, which will have // the top k frequent numbers. If the heap size is more than k, we remove the smallest (top) number. for (entry in numFrequencyMap.entries) { topKElements.add(entry) if (topKElements.size > k) { topKElements.poll() } } // Create a list of top k numbers val topNumbers: MutableList<Int> = ArrayList(k) while (!topKElements.isEmpty()) { topNumbers.add(topKElements.poll().key) } topNumbers.sort() return topNumbers } @JvmStatic fun main(args: Array<String>) { // Driver code val inputs = arrayOf( intArrayOf(1, 3, 5, 12, 11, 12, 11, 12, 5), intArrayOf(1, 3, 5, 14, 18, 14, 5), intArrayOf(2, 3, 4, 5, 6, 7, 7), intArrayOf(9, 8, 7, 6, 5, 4, 3, 2, 1), intArrayOf(2, 4, 3, 2, 3, 4, 5, 4, 4, 4), intArrayOf(1, 1, 1, 1, 1, 1), intArrayOf(2, 3) ) val inputK = intArrayOf(3, 2, 1, 1, 3, 4, 2) for (i in inputK.indices) { val result = topKFrequent(inputs[i], inputK[i]) print(i + 1) println(".\tInput: (" + Arrays.toString(inputs[i]) + ", " + inputK[i] + ")") println( """ Top ${inputK[i]} frequent elements: $result""" ) println(String(CharArray(100)).replace('\u0000', '-')) } } }
0
Kotlin
0
0
ee06bebe0d3a7cd411d9ec7b7e317b48fe8c6d70
2,307
CodingChallenges
Apache License 2.0
year2021/day03/part1/src/main/kotlin/com/curtislb/adventofcode/year2021/day03/part1/Year2021Day03Part1.kt
curtislb
226,797,689
false
{"Kotlin": 2146738}
/* --- Day 3: Binary Diagnostic --- The submarine has been making some odd creaking noises, so you ask it to produce a diagnostic report just in case. The diagnostic report (your puzzle input) consists of a list of binary numbers which, when decoded properly, can tell you many useful things about the conditions of the submarine. The first parameter to check is the power consumption. You need to use the binary numbers in the diagnostic report to generate two new binary numbers (called the gamma rate and the epsilon rate). The power consumption can then be found by multiplying the gamma rate by the epsilon rate. Each bit in the gamma rate can be determined by finding the most common bit in the corresponding position of all numbers in the diagnostic report. For example, given the following diagnostic report: ``` 00100 11110 10110 10111 10101 01111 00111 11100 10000 11001 00010 01010 ``` Considering only the first bit of each number, there are five 0 bits and seven 1 bits. Since the most common bit is 1, the first bit of the gamma rate is 1. The most common second bit of the numbers in the diagnostic report is 0, so the second bit of the gamma rate is 0. The most common value of the third, fourth, and fifth bits are 1, 1, and 0, respectively, and so the final three bits of the gamma rate are 110. So, the gamma rate is the binary number 10110, or 22 in decimal. The epsilon rate is calculated in a similar way; rather than use the most common bit, the least common bit from each position is used. So, the epsilon rate is 01001, or 9 in decimal. Multiplying the gamma rate (22) by the epsilon rate (9) produces the power consumption, 198. Use the binary numbers in your diagnostic report to calculate the gamma rate and epsilon rate, then multiply them together. What is the power consumption of the submarine? (Be sure to represent your answer in decimal, not binary.) */ package com.curtislb.adventofcode.year2021.day03.part1 import com.curtislb.adventofcode.year2021.day03.diagnostic.DiagnosticReport import java.nio.file.Path import java.nio.file.Paths /** * Returns the solution to the puzzle for 2021, day 3, part 1. * * @param inputPath The path to the input file for this puzzle. */ fun solve(inputPath: Path = Paths.get("..", "input", "input.txt")): Int { val report = DiagnosticReport(inputPath.toFile().readLines()) return report.powerConsumption } fun main() { println(solve()) }
0
Kotlin
1
1
6b64c9eb181fab97bc518ac78e14cd586d64499e
2,439
AdventOfCode
MIT License
src/main/kotlin/no/chriswk/aoc2019/Point.kt
chriswk
317,863,220
false
{"Kotlin": 481061}
package com.chriswk.aoc.advent2019 import kotlin.math.abs enum class Direction { U, D, L, R; fun cmd(): Long { return when(this) { U -> 1L D -> 2L L -> 3L R -> 4L } } fun back(): Long { return when(this) { U -> D.cmd() D -> U.cmd() L -> R.cmd() R -> L.cmd() } } } data class Point(val x: Int, val y: Int) { fun manhattan(other: Point): Int { return abs(x - other.x) + abs(y - other.y) } fun route(s: String): Route { val route = s.split(",").asSequence().map { Instruction(it) } return route.fold(listOf()) { acc, (f, i) -> val point = if (acc.isEmpty()) { this } else { acc.last() } when (f) { Direction.U -> acc + point.up(i).toList() Direction.R -> acc + point.right(i).toList() Direction.L -> acc + point.left(i).toList() Direction.D -> acc + point.down(i).toList() } } } fun cardinalNeighbours(): List<Pair<Point, Direction>> { return Direction.values().map { this.move(it) to it } } fun move(d: Direction): Point { return when(d) { Direction.U -> this.up() Direction.D -> this.down() Direction.L -> this.left() Direction.R -> this.right() } } fun right(count: Int): Sequence<Point> { return generateSequence(this) { it.copy(x = it.x + 1) }.drop(1).take(count) } fun left(count: Int): Sequence<Point> { return generateSequence(this) { it.copy(x = it.x - 1) }.drop(1).take(count) } fun up(count: Int): Sequence<Point> { return generateSequence(this) { it.copy(y = it.y + 1) }.drop(1).take(count) } fun down(count: Int): Sequence<Point> { return generateSequence(this) { it.copy(y = it.y - 1) }.drop(1).take(count) } fun dx(other: Point): Int = x - other.x fun dy(other: Point): Int = y - other.y fun up(): Point = copy(y = y + 1) fun down(): Point = copy(y = y - 1) fun left(): Point = copy(x = x - 1) fun right(): Point = copy(x = x + 1) companion object { val ORIGIN = Point(0, 0) val readOrder: Comparator<Point> = Comparator { o1, o2 -> when { o1.y != o2.y -> o1.y - o2.y else -> o1.x - o2.x } } } } data class Point3D(val x: Int, val y: Int, val z: Int) { fun absSum() = abs(x) + abs(y) + abs(z) operator fun plus(b: Point3D) = Point3D(x + b.x, y + b.y, z + b.z) operator fun minus(b: Point3D) = Point3D(x - b.x, y - b.y, z - b.z) operator fun times(scale: Int) = Point3D(x*scale, y*scale, z*scale) fun opposite() = Point3D(-x, -y, -z) operator fun unaryMinus() = opposite() companion object { val ZERO = Point3D(0, 0, 0) fun fromString(s: String): Point3D { val (x, y, z) = s.replace("<", "").replace(">", "").split(",") val xCoord = x.split("=").last().toInt() val yCoord = y.split("=").last().toInt() val zCoord = z.split("=").last().toInt() return Point3D(xCoord, yCoord, zCoord) } } operator fun get(i: Int) = when(i) { 0 -> x 1 -> y 2 -> z else -> throw IndexOutOfBoundsException() } } data class Body(var location: Point3D, var velocity: Point3D) { fun newVelocity(otherBodies: List<Body>): Body { return otherBodies.fold(this) { a, nextBody -> a.copy(velocity = a.velocity + deltaV(nextBody.location)) } } fun deltaV(otherBody: Point3D): Point3D { val dX = deltaV(location.x, otherBody.x) val dY = deltaV(location.y, otherBody.y) val dZ = deltaV(location.z, otherBody.z) return Point3D(dX, dY, dZ) } private fun deltaV(bodyPoint: Int, otherBody: Int): Int { return if (bodyPoint < otherBody) { 1 } else if (bodyPoint > otherBody) { -1 } else { 0 } } fun move(): Body = this.copy(location = location + velocity) fun potentialEnergy(): Int = location.absSum() fun kineticEnergy(): Int = velocity.absSum() fun totalEnergy(): Int = potentialEnergy() * kineticEnergy() }
116
Kotlin
0
0
69fa3dfed62d5cb7d961fe16924066cb7f9f5985
4,538
adventofcode2019
MIT License
kotlinLeetCode/src/main/kotlin/leetcode/editor/cn/[665]非递减数列.kt
maoqitian
175,940,000
false
{"Kotlin": 354268, "Java": 297740, "C++": 634}
//给你一个长度为 n 的整数数组,请你判断在 最多 改变 1 个元素的情况下,该数组能否变成一个非递减数列。 // // 我们是这样定义一个非递减数列的: 对于数组中所有的 i (0 <= i <= n-2),总满足 nums[i] <= nums[i + 1]。 // // // // 示例 1: // // 输入: nums = [4,2,3] //输出: true //解释: 你可以通过把第一个4变成1来使得它成为一个非递减数列。 // // // 示例 2: // // 输入: nums = [4,2,1] //输出: false //解释: 你不能在只改变一个元素的情况下将其变为非递减数列。 // // // // // 说明: // // // 1 <= n <= 10 ^ 4 // - 10 ^ 5 <= nums[i] <= 10 ^ 5 // // Related Topics 数组 // 👍 509 👎 0 //leetcode submit region begin(Prohibit modification and deletion) class Solution { fun checkPossibility(nums: IntArray): Boolean { var res = 0 for (i in 0 until nums.size -1){ if (nums[i] > nums[i+1]){ res ++ if(i > 0 && nums[i-1] > nums[i+1]){ //赋值当前 nums[i+1] = nums[i] } } } return res < 2 } } //leetcode submit region end(Prohibit modification and deletion)
0
Kotlin
0
1
8a85996352a88bb9a8a6a2712dce3eac2e1c3463
1,260
MyLeetCode
Apache License 2.0
src/org/aoc2021/Day18.kt
jsgroth
439,763,933
false
{"Kotlin": 86732}
package org.aoc2021 import java.nio.file.Files import java.nio.file.Path object Day18 { data class TreeNode(val left: TreeNode? = null, val right: TreeNode? = null, val value: Int? = null) private fun solvePart1(lines: List<String>): Int { val snailfishNumbers = lines.map(Day18::parseSnailfishNumber) val snailfishSum = snailfishNumbers.reduce(Day18::addSnailfishNumbers) return magnitude(snailfishSum) } private fun solvePart2(lines: List<String>): Int { val snailfishNumbers = lines.map(Day18::parseSnailfishNumber) return snailfishNumbers.maxOf { snailfishNumber -> snailfishNumbers.filter { it !== snailfishNumber }.maxOf { otherNumber -> magnitude(addSnailfishNumbers(snailfishNumber, otherNumber)) } } } private fun parseSnailfishNumber(line: String): TreeNode { return parseNode(line, 0, false).first } private fun parseNode(line: String, i: Int, parsingRight: Boolean): Pair<TreeNode, Int> { return if (line[i] == '[') { val (left, j) = parseNode(line, i + 1, false) val (right, k) = parseNode(line, j + 1, true) TreeNode(left = left, right = right) to k + 1 } else { val endChar = if (parsingRight) ']' else ',' val end = line.indexOf(endChar, startIndex = i) val value = line.substring(i, end).toInt() TreeNode(value = value) to end } } private fun addSnailfishNumbers(first: TreeNode, second: TreeNode): TreeNode { return reduceSnailfishNumber(TreeNode(left = first, right = second)) } private tailrec fun reduceSnailfishNumber(number: TreeNode): TreeNode { findNodeToExplode(number)?.let { nodeToExplode -> return reduceSnailfishNumber(explode(number, nodeToExplode)) } findNodeToSplit(number)?.let { nodeToSplit -> return reduceSnailfishNumber(split(number, nodeToSplit)) } return number } private fun findNodeToExplode(number: TreeNode, depth: Int = 0): TreeNode? { if (depth == 4 && number.left != null && number.right != null) { return number } if (number.left == null || number.right == null) { return null } findNodeToExplode(number.left, depth + 1)?.let { return it } return findNodeToExplode(number.right, depth + 1) } private fun explode(number: TreeNode, nodeToExplode: TreeNode): TreeNode { val allNodes = traverse(number) val nodeToExplodeIndex = allNodes.indexOfFirst { it === nodeToExplode } val lastValueBefore = allNodes.subList(0, nodeToExplodeIndex - 1).findLast { it.value != null } val firstValueAfter = allNodes.subList(nodeToExplodeIndex + 2, allNodes.size).find { it.value != null } return doExplode(number, nodeToExplode, lastValueBefore, firstValueAfter) } private fun traverse(number: TreeNode): List<TreeNode> { return if (number.left == null || number.right == null) { listOf(number) } else { traverse(number.left).plus(number).plus(traverse(number.right)) } } private fun doExplode( number: TreeNode, nodeToExplode: TreeNode, lastValueBefore: TreeNode?, firstValueAfter: TreeNode?, ): TreeNode { if (number === nodeToExplode) { return TreeNode(value = 0) } if (number === lastValueBefore) { return TreeNode(value = number.value!! + nodeToExplode.left!!.value!!) } if (number === firstValueAfter) { return TreeNode(value = number.value!! + nodeToExplode.right!!.value!!) } if (number.left == null || number.right == null) { return number } return TreeNode( left = doExplode(number.left, nodeToExplode, lastValueBefore, firstValueAfter), right = doExplode(number.right, nodeToExplode, lastValueBefore, firstValueAfter), ) } private fun findNodeToSplit(number: TreeNode): TreeNode? { if (number.value != null && number.value >= 10) { return number } if (number.left == null || number.right == null) { return null } findNodeToSplit(number.left)?.let { return it } return findNodeToSplit(number.right) } private fun split(number: TreeNode, nodeToSplit: TreeNode): TreeNode { if (number === nodeToSplit) { return TreeNode( left = TreeNode(value = number.value!! / 2), right = TreeNode(value = number.value / 2 + (number.value % 2)), ) } if (number.left == null || number.right == null) { return number } return TreeNode( left = split(number.left, nodeToSplit), right = split(number.right, nodeToSplit), ) } private fun magnitude(number: TreeNode): Int { if (number.left == null || number.right == null) { return number.value!! } return 3 * magnitude(number.left) + 2 * magnitude(number.right) } @JvmStatic fun main(args: Array<String>) { val lines = Files.readAllLines(Path.of("input18.txt"), Charsets.UTF_8) val solution1 = solvePart1(lines) println(solution1) val solution2 = solvePart2(lines) println(solution2) } }
0
Kotlin
0
0
ba81fadf2a8106fae3e16ed825cc25bbb7a95409
5,510
advent-of-code-2021
The Unlicense
src/main/kotlin/d23/d23.kt
LaurentJeanpierre1
573,454,829
false
{"Kotlin": 118105}
package d23 import readInput enum class Directions { North, South, West, East } data class Elf (var x: Int, var y: Int) { var direction : Directions? = null var arrival : Elf? = null } fun part1(input: List<String>): Int { val elves = readPuzzle(input) repeat(10) {round -> //First Half val arrival = mutableMapOf<Elf, Int>() for (elf in elves) { elf.direction = null var free = 0 for (dir in 0..3) { var full : Boolean val direction = Directions.values()[(round + dir) % 4] full = when(direction) { Directions.North -> elves.any { it.y == elf.y - 1 && (it.x - elf.x) in -1..+1 } Directions.South -> elves.any { it.y == elf.y + 1 && (it.x - elf.x) in -1..+1 } Directions.West -> elves.any { it.x == elf.x - 1 && (it.y - elf.y) in -1..+1 } Directions.East -> elves.any { it.x == elf.x + 1 && (it.y - elf.y) in -1..+1 } } // for (d in -1..1) { // when (direction) { // Directions.North -> if (Elf(elf.x+d, elf.y-1) in elves) { full=true; break} // Directions.South -> if (Elf(elf.x+d, elf.y+1) in elves) { full=true; break} // Directions.West -> if (Elf(elf.x-1, elf.y+d) in elves) { full=true; break} // Directions.East -> if (Elf(elf.x+1, elf.y+d) in elves) { full=true; break} // } // } if (!full) { if (elf.direction == null) { elf.direction = direction val dest = when (direction) { Directions.North -> Elf(elf.x, elf.y - 1) Directions.South -> Elf(elf.x, elf.y + 1) Directions.West -> Elf(elf.x - 1, elf.y) Directions.East -> Elf(elf.x + 1, elf.y) } elf.arrival = dest } free++ } } if (free == 4) { elf.direction = null // No move ! } else if (elf.direction != null){ val dest = elf.arrival!! if (dest in arrival) arrival[dest] = arrival[dest]!! + 1 else arrival[dest] = 1 } } // sencond half for (elf in elves) { if (elf.direction != null && arrival[elf.arrival] == 1) { elf.x = elf.arrival!!.x elf.y = elf.arrival!!.y } } } val minX = elves.minOf { it.x } val maxX = elves.maxOf { it.x } val minY = elves.minOf { it.y } val maxY = elves.maxOf { it.y } return (maxX-minX+1)*(maxY-minY+1)-elves.size } private fun readPuzzle(input: List<String>): MutableSet<Elf> { val elves = mutableSetOf<Elf>() for ((noLine, line) in input.withIndex()) { line.toCharArray().withIndex().filter { (_, char) -> char == '#' }.forEach { (col, _) -> elves.add(Elf(col, noLine)) } } return elves } fun part2(input: List<String>): Int { val elves = readPuzzle(input) repeat(10000) { round -> //First Half val arrival = mutableMapOf<Elf, Int>() for (elf in elves) { elf.direction = null var free = 0 for (dir in 0..3) { var full : Boolean val direction = Directions.values()[(round + dir) % 4] full = when (direction) { Directions.North -> elves.any { it.y == elf.y - 1 && (it.x - elf.x) in -1..+1 } Directions.South -> elves.any { it.y == elf.y + 1 && (it.x - elf.x) in -1..+1 } Directions.West -> elves.any { it.x == elf.x - 1 && (it.y - elf.y) in -1..+1 } Directions.East -> elves.any { it.x == elf.x + 1 && (it.y - elf.y) in -1..+1 } } if (!full) { if (elf.direction == null) { elf.direction = direction val dest = when (direction) { Directions.North -> Elf(elf.x, elf.y - 1) Directions.South -> Elf(elf.x, elf.y + 1) Directions.West -> Elf(elf.x - 1, elf.y) Directions.East -> Elf(elf.x + 1, elf.y) } elf.arrival = dest } free++ } } if (free == 4) { elf.direction = null // No move ! } else if (elf.direction != null) { val dest = elf.arrival!! if (dest in arrival) arrival[dest] = arrival[dest]!! + 1 else arrival[dest] = 1 } } // sencond half var noMove = true for (elf in elves) { if (elf.direction != null && arrival[elf.arrival] == 1) { elf.x = elf.arrival!!.x elf.y = elf.arrival!!.y noMove = false } } if (noMove) return round+1 } return -1 } fun main() { //val input = readInput("d23/test0") //val input = readInput("d23/test") val input = readInput("d23/input1") //println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
5cf6b2142df6082ddd7d94f2dbde037f1fe0508f
5,621
aoc2022
Creative Commons Zero v1.0 Universal
src/main/kotlin/com/colinodell/advent2021/Day10.kt
colinodell
433,864,377
true
{"Kotlin": 111114}
package com.colinodell.advent2021 class Day10 (private val input: List<String>) { private val syntax = mapOf('(' to ')', '[' to ']', '{' to '}', '<' to '>') private val syntaxErrorPoints = mapOf(')' to 3, ']' to 57, '}' to 1197, '>' to 25137) private val autocompletePoints = mapOf(')' to 1, ']' to 2, '}' to 3, '>' to 4) fun solvePart1() = input.sumOf { syntaxErrorScore(it) } fun solvePart2() = input.filter { syntaxErrorScore(it) == 0 }.map { autocompleteScore(it) }.sorted().middle() private fun syntaxErrorScore(line: String): Int { val openerQueue = mutableListOf<Char>() for (char in line) when { // Is this an opener? Those can be added at any time syntax.keys.contains(char) -> openerQueue.add(char) // Otherwise, if this is a closer that doesn't match the last opener, return the error point value syntax[openerQueue.removeLast()] != char -> return syntaxErrorPoints[char]!! } return 0 } private fun autocompleteScore(line: String): Long { val openerQueue = mutableListOf<Char>() for (char in line) when { syntax.keys.contains(char) -> openerQueue.add(char) else -> openerQueue.removeLastOrNull() } var score: Long = 0 while (!openerQueue.isEmpty()) { val lastOpener = openerQueue.removeLast() score = score * 5 + autocompletePoints[syntax[lastOpener]]!! } return score } private fun <T> List<T>.middle(): T { val middle = size / 2 return if (size % 2 == 0) { get(middle - 1) } else { get(middle) } } }
0
Kotlin
0
1
a1e04207c53adfcc194c85894765195bf147be7a
1,705
advent-2021
Apache License 2.0
src/Day21.kt
fedochet
573,033,793
false
{"Kotlin": 77129}
private sealed interface MonkeyTask private data class NumberTask(val number: Long) : MonkeyTask private data class OpTask(val left: String, val op: String, val right: String) : MonkeyTask private const val ROOT = "root" private const val HUMAN = "humn" fun main() { fun compute(left: Long, op: String, right: Long) = when (op) { "+" -> left + right "-" -> left - right "*" -> left * right "/" -> left / right else -> error("Unknown op $op") } fun evalMonkey(monkeys: Map<String, MonkeyTask?>, name: String): Long? { val task = monkeys.getValue(name) ?: return null return when (task) { is NumberTask -> task.number is OpTask -> { val left = evalMonkey(monkeys, task.left) ?: return null val right = evalMonkey(monkeys, task.right) ?: return null compute(left, task.op, right) } } } fun parseMonkeys(input: List<String>) = input.associate { val (name, taskStr) = it.split(": ", limit = 2) val taskTokens = taskStr.split(" ") val task = if (taskTokens.size == 1) { NumberTask(taskTokens.single().toLong()) } else { val (left, op, right) = taskTokens OpTask(left, op, right) } name to task } fun part1(input: List<String>): Long { val monkeys = parseMonkeys(input) return evalMonkey(monkeys, ROOT) ?: error("Must be computable") } fun decompute(left: Long?, op: String, right: Long?, expectedResult: Long): Long { require((left == null) != (right == null)) return when (op) { "+" -> { if (left == null) { expectedResult - right!! } else { expectedResult - left } } "-" -> { if (left == null) { expectedResult + right!! } else { left - expectedResult } } "*" -> { if (left == null) { expectedResult / right!! } else { expectedResult / left } } "/" -> { if (left == null) { expectedResult * right!! } else { left / expectedResult } } else -> error("Unknown op $op") } } fun guessMissingMonkeyValue(monkeys: Map<String, MonkeyTask?>, monkey: String, target: Long): Long { val task = monkeys.getValue(monkey) if (task == null) return target val (leftM, op, rightM) = task as OpTask val left = evalMonkey(monkeys, leftM) val right = evalMonkey(monkeys, rightM) val nextTarget = decompute(left, op, right, target) return when { left != null -> guessMissingMonkeyValue(monkeys, rightM, nextTarget) right != null -> guessMissingMonkeyValue(monkeys, leftM, nextTarget) else -> error("None of $left or $right is computable") } } fun part2(input: List<String>): Long { val monkeys = parseMonkeys(input).mapValues { (name, task) -> if (name == HUMAN) null else task } val (leftM, _, rightM) = monkeys.getValue(ROOT) as OpTask val left = evalMonkey(monkeys, leftM) val right = evalMonkey(monkeys, rightM) return when { left != null -> guessMissingMonkeyValue(monkeys, rightM, left) right != null -> guessMissingMonkeyValue(monkeys, leftM, right) else -> error("Both root branches are not computable") } } // test if implementation meets criteria from the description, like: val testInput = readInput("Day21_test") check(part1(testInput) == 152L) check(part2(testInput) == 301L) val input = readInput("Day21") println(part1(input)) println(part2(input)) }
0
Kotlin
0
1
975362ac7b1f1522818fc87cf2505aedc087738d
4,067
aoc2022
Apache License 2.0
src/main/kotlin/aoc2018/day5/Polymer.kt
arnab
75,525,311
false
null
package aoc2018.day5 data class PolymerUnit(val type: Char, val polarity: Boolean = type.isUpperCase()) object Polymer { fun reduce(units: List<PolymerUnit>, debug: Boolean = false): List<PolymerUnit> { var reducedUnits = units var pass = 1 do { var reduced = false log(debug, "DEBUG: Pass $pass: ${reducedUnits.map(PolymerUnit::type).joinToString("")}") reducedUnits.forEachIndexed { i, unit -> val nextUnit = reducedUnits.getOrNull(i+1) if (!reduced && reacts(unit, nextUnit)) { log(debug, "DEBUG: Pass: #$pass: Found reacting units: #$i: [${unit.type}, ${nextUnit?.type}].") val previousUnits = reducedUnits.take(i) val remainingUnits = reducedUnits.drop(i+2) reducedUnits = previousUnits + remainingUnits reduced = true } } pass++ } while (reduced) return reducedUnits } fun reduceByRemovingBadUnits(units: List<PolymerUnit>, debug: Boolean = false): Pair<Char, List<PolymerUnit>> { val allTypes: List<Char> = units.map { it.type.toLowerCase() }.distinct().sorted() val reducedUnitsByRemovedType: List<Pair<Char, List<PolymerUnit>>> = allTypes.map { typeToRemove -> println("Removing $typeToRemove and reducing...") Pair(typeToRemove, reduce(removeUnitsOfType(units, typeToRemove))) } return reducedUnitsByRemovedType.minBy { it.second.size }!! } private fun removeUnitsOfType(units: List<PolymerUnit>, typeToRemove: Char): List<PolymerUnit> { return units.filter { it.type.toLowerCase() != typeToRemove.toLowerCase() } } private fun reacts(unit: PolymerUnit?, otherUnit: PolymerUnit?): Boolean { return unit != null && otherUnit != null && unit.type.toLowerCase() == otherUnit.type.toLowerCase() && unit.polarity != otherUnit.polarity } private fun log(debug: Boolean, message: String) { if(debug) println(message) } }
0
Kotlin
0
0
1d9f6bc569f361e37ccb461bd564efa3e1fccdbd
2,136
adventofcode
MIT License
src/leetcode_problems/easy/FindGivenDifference.kt
MhmoudAlim
451,633,139
false
{"Kotlin": 31257, "Java": 586}
package leetcode_problems.easy import kotlin.math.* /*Given an unsorted array, return 1 if there exists a pair or more of elements in the array whose difference is 1. else return 0 Examples: -Input: arr[] = {5, 20, 3, 2, 6} =Output: 1 -Input: arr[] = {90, 7, 2, 9, 50} =Output: 0 */ fun findPairDifference(nums: IntArray): Int { // O(N*N) Solution // nums.forEach { i -> // val list = nums.toMutableList() // list.remove(i) // list.forEach { j -> // if (abs(i - j) == 1) // return 1 // } // } // return 0 val sorted = nums.sorted() // [2, 7, 20, 21, 22] var l = 0 //2 var r = nums.size -1 //22 while (l >= r){ val middle = (l + r) / 2 // 20 if (abs(sorted[middle] - sorted[l]) == 1) return 1 else if (abs(sorted[middle] - sorted[l]) < 1) r = middle -1 else l = middle + 1 } return 0 } fun main() { val result = findPairDifference(nums = intArrayOf( 7, 2, 20, 22, 21)) println(result.toString()) }
0
Kotlin
0
0
31f0b84ebb6e3947e971285c8c641173c2a60b68
1,107
Coding-challanges
MIT License
src/me/bytebeats/algo/kt/design/FileSystem.kt
bytebeats
251,234,289
false
null
package me.bytebeats.algo.kt.design class FileSystem() { //588 private val root = File() fun ls(path: String): List<String> { val fileNames = mutableListOf<String>() var file = root if (path == "/") { fileNames.addAll(file.files.map { it.name }) } else { val dirs = path.split("/") dirs.forEach { dir -> if (dir.isEmpty()) { file = root } else { file = file.files.first { it.name == dir } } } if (file.content.isNotEmpty()) { fileNames.add(file.name) } fileNames.addAll(file.files.map { it.name }) } return fileNames.sorted() } fun mkdir(path: String) { if (path == "/") { return } val dirs = path.split("/") var file = root dirs.forEach { dir -> if (dir.isEmpty()) { file = root } else { if (file.files.map { it.name }.contains(dir)) { file = file.files.first { it.name == dir } } else { val newDir = File() newDir.name = dir file.files.add(newDir) file = newDir } } } } fun addContentToFile(filePath: String, content: String) { findFile(filePath)?.apply { this.content = "${this.content}$content" } } fun readContentFromFile(filePath: String): String { return findFile(filePath)?.content ?: "" } private fun findFile(filePath: String): File? { if (filePath == "/") { return root } val dirs = filePath.split("/") var file = root dirs.forEach { dir -> if (dir.isEmpty()) { file = root } else { if (file.files.map { it.name }.contains(dir)) { file = file.files.first { it.name == dir } } else { val newDir = File() newDir.name = dir file.files.add(newDir) file = newDir } } } return file } class File { var name = "" var content = "" var files = mutableListOf<File>() } } class FileSystem1() { //1166 val root = Trie("", -1) fun createPath(path: String, value: Int): Boolean { val paths = path.substring(1).split("/") var trie = root if (paths.size == 1) { if (trie.map.containsKey(paths[0])) { return false } else { trie.map[paths[0]] = Trie(paths[0], value) return true } } else { for (i in 0 until paths.lastIndex) { if (trie.map.containsKey(paths[i])) { trie = trie.map[paths[i]]!! } else { return false } } if (trie.map.containsKey(paths.last())) { return false } else { trie.map[paths.last()] = Trie(paths.last(), value) return true } } } fun get(path: String): Int { var trie = root val paths = path.substring(1).split("/") for (p in paths) { if (trie.map.containsKey(p)) { trie = trie.map[p]!! } else { return -1 } } return trie.value } class Trie(val path: String, var value: Int) { val map = mutableMapOf<String, Trie>() } }
0
Kotlin
0
1
7cf372d9acb3274003bb782c51d608e5db6fa743
3,790
Algorithms
MIT License