Step-by-step guide
Step 1 - Algorithm
readLines
readLines()
: open the file and return each line as String- for each value (one value by line), find another value with a result of 2020 for the addition
- display the result of their multiplication
Step 2 - What do we need ?
- Function to run our code
- Variables to store the lines
- For loop to iterate over the lines
- If statement to test if addition equals to 2020
- String template to print the final result
Then go back to main course
Step 3 - simple/naive implementation
- Read lines from the input file to a variable
val lines = File("src/main/kotlin/day1/input.txt") .readLines()
- Convert to
Int
val lines = File("src/main/kotlin/day1/input.txt") .readLines().map { it.toInt() }
- Iterate over the lines
for (line1 in lines) { for(line2 in lines) { println(line1 + " " + line2) } }
- Test if the addition of two numbers are equal
for (line1 in lines) { for(line2 in lines) { if(line1 + line2 == 2020) { println("OK") return } } }
- Display the multiplication of the two previously found numbers
for (line1 in lines) { for(line2 in lines) { if(line1 + line2 == 2020) { println(line1 * line2) return } } }
Congratulations we have solved the challenge !!!
Step 4 - Refactor / improve our code
- Store the result of the current number minus 2020 associated to the current number
val complements = lines.associateWith { 2020 - it }
- Find one resulting numbers in the lines
val pair = lines.firstNotNullOf { number ->
val complement = complements[number]
if(complement != null)
Pair(number, complement)
else null
}
- Print the first value
println(pair.first * pair.second)
Based on JetBrains work available here