diff --git a/05-a.kts b/05-a.kts new file mode 100644 index 0000000..8c88f89 --- /dev/null +++ b/05-a.kts @@ -0,0 +1,39 @@ +import java.util.Scanner + +val scanner = Scanner(System.`in`) + +val rules = HashMap>() + +while (scanner.hasNextLine()) { + val line = scanner.nextLine() + if (line == "") { + break; + } + + val (before, after) = line.split("|").map(String::toInt) + if (!rules.contains(before)) { + rules[before] = HashSet() + } + rules[before]!!.add(after) +} + +var sum = 0 +while (scanner.hasNextLine()) { + val line = scanner.nextLine() + val pages = line.split(",").map(String::toInt) + + val result = pages.fold(Pair(HashSet(), true)) { (appeared, isSafe), page -> + val shouldBeAfter = rules[page]?.toSet() ?: emptySet() + val violateRule = appeared.intersect(shouldBeAfter) + val stillSafe = isSafe && violateRule.isEmpty() + + appeared.add(page) + Pair(appeared, stillSafe) + } + + if (result.second) { + val pagesArray = pages.toIntArray() + sum += pagesArray[pagesArray.size / 2] + } +} +println(sum) \ No newline at end of file diff --git a/05-b.kts b/05-b.kts new file mode 100644 index 0000000..34e2db2 --- /dev/null +++ b/05-b.kts @@ -0,0 +1,31 @@ +import java.util.Scanner + +val scanner = Scanner(System.`in`) + +val rules = HashMap>() + +while (scanner.hasNextLine()) { + val line = scanner.nextLine() + if (line == "") { + break; + } + + val (before, after) = line.split("|").map(String::toInt) + if (!rules.contains(before)) { + rules[before] = HashSet() + } + rules[before]!!.add(after) +} + +var sum = 0 +while (scanner.hasNextLine()) { + val line = scanner.nextLine() + val pages = line.split(",").map(String::toInt) + val fixed = pages.sortedWith { l, r -> if (l == r) 0 else if (rules[l]?.contains(r) == true) -1 else 1 } + + if ("$pages" != "$fixed") { + val fixedArray = fixed.toIntArray() + sum += fixedArray[fixedArray.size / 2] + } +} +println(sum) \ No newline at end of file