Start Competitive Programming with Kotlin
The best boilerplate setup for competitive programming
When you hear Competitive Programming, you instantly think of C++ or Java, or unlikely Python (because of how slow the language is). But… have you ever thought of Kotlin?
Yes! One of the most complex languages out there and the best for developing Android applications, Kotlin has a good role to play when it comes to Competitive Programming. It roughly shares the same speed as Java; has the same features, and more; and is loved by everyone.
#0 — Pre-defined functions
Copy and Paste these pre-defined functions before you start solving your problem. They would always come in handy.
- The functions,
read*()
, simplifies the input and allows you to focus on the problem more. - Bonus: The
String.times
is an operator extension function that allows you to use"Hello" * 3
in your code to repeat the stringn
number of times.
#1— Running test cases
The first line, t (0 ≤ t ≤ 10), is the number of test cases.
Often problems have this statement. In other programming languages, you would follow:
But with Kotlin, it’s as simple as using a function.
repeat
is an in-built Kotlin function that will run a loop. The first integer will be read by readInt
. This will be sent to the repeat function, and the rest is taken care of.
#2 — Destructuring
Competitive coders using Java? Yes, I know the pain of having to separate those space-separated integers. Normally, you’d look at something like this:
I have no idea why Java has such an elaborate syntax; however, it does have its upsides. Anyway, here’s how you do the same thing in Kotlin.
#3 — Measuring time
One of the most important goals of competitive coders is the ability to produce a fast solution. If you need to measure the time it takes to run your solution, there’s an in-built function in Kotlin for that too!
Combining all that we learned here in the code above, this article has reached its “The End”
Conclusion
Kotlin may not be as fast as C++ in terms of runtime and compile time. But it gives you the interface to work quickly without focusing too much on the logistics, but more on the problem itself.
JetBrains hosts contests called Kotlin Heros on Codeforces where every coder uses Kotlin to solve problems. I believe Kotlin is a superior language, and the more you learn about it, the more you would start to agree with me.