-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay07.kt
More file actions
83 lines (69 loc) 路 2.42 KB
/
Copy pathDay07.kt
File metadata and controls
83 lines (69 loc) 路 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
private sealed class FileTree {
abstract val name: String
abstract val size: Int
}
private data class File(override val name: String, override val size: Int) : FileTree()
private data class Directory(
override val name: String,
val parent: Directory?,
val fileTrees: MutableMap<String, FileTree> = mutableMapOf(),
) : FileTree() {
override val size: Int
get() = fileTrees.values.sumOf { it.size }
fun add(fileTree: FileTree) {
fileTrees[fileTree.name] = fileTree
}
fun asSequence(): Sequence<FileTree> =
fileTrees
.values
.asSequence()
.flatMap {
when (it) {
is Directory -> it.asSequence() + it
is File -> sequenceOf(it)
}
}
}
private fun getFileTree(): Directory {
val root = Directory("/", null)
getFullInput()
.splitToSequence("\n$ ")
.drop(1)
.map {
val splittedLaunch = it.split('\n')
splittedLaunch.firstOrNull().unwrap() to splittedLaunch.drop(1)
}
.fold(root) { currentDirectory, (command, output) ->
when {
command.startsWith("cd") -> {
when (val name = command.split(' ', limit = 2).getOrNull(1).unwrap()) {
".." -> currentDirectory.parent.unwrap()
else -> Directory(name, currentDirectory).also(currentDirectory::add)
}
}
command.startsWith("ls") -> {
output.asSequence()
.filter { !it.startsWith("dir") }
.map {
val (sizeString, fileName) = it.split(' ', limit = 2)
val size = sizeString.toIntOrNull().unwrap()
File(fileName, size)
}
.forEach { currentDirectory.add(it) }
currentDirectory
}
else -> expect()
}
}
return root
}
fun main() {
val root = getFileTree()
val first = root.asSequence().filter { it is Directory }.map { it.size }.filter { it <= 100_000 }.sum()
val second = root.asSequence()
.filter { it is Directory }
.map { it.size }
.filter { it + 70_000_000 - root.size > 30_000_000 }
.min()
println("$first $second")
}