okaryo.log

Competitive Programming with Dart: Input and Output | okaryo.log

Competitive Programming with Dart: Input and Output

    #Dart#CompetitiveProgramming#AtCoder

Introduction

I was quite active in competitive programming during my university days. However, after entering the workforce, I found myself dedicating more time to work-related studies, leaving little to no time for competitive programming. Consequently, my performance in contests began to wane, prompting me to take a step back.

Recently, as I’ve become more accustomed to my job and can afford some leisure time, I’ve been thinking of aiming for a cyan rank in AtCoder once again.

In this post, I’ll introduce how to handle input and output in competitive programming using Dart, which I often work with in my day-to-day job.

AtCoder, the competitive programming site I usually use, supports Dart version 2.7.2 as of July 14, 2022. This is before the introduction of Null Safety in version 2.12, so be mindful of that.

Output

In Dart, standard output is typically handled using the print function, although the Stdout class also provides write, writeAll, and writeln methods. Both writeln and print automatically append a newline at the end.

Input

For input, the Stdin class’s readLineSync method is used. It reads input line by line as strings.

import 'dart:io';

// A single integer
final n = int.parse(stdin.readLineSync());

// Multiple integers separated by spaces
final a = stdin.readLineSync().split(' ').map((x) => int.parse(x)).toList();

// Multiple integers over N lines
// Example for 2 lines:
// 5
// 10
final a = List.generate(N, (_) => int.parse(stdin.readLineSync()));

// Multiple sets of integers over N lines
// Example for 2 lines:
// 5 10
// 10 20
final ab = List.generate(N, (_) => stdin.readLineSync().split(' ').map((x) => int.parse(x)).toList());

// A string
final s = stdin.readLineSync();

Writing this every time can be tedious, so it seems prudent to encapsulate these operations in functions.

import 'dart:io';

int inputInt() => int.parse(stdin.readLineSync());

List<int> inputIntList() => stdin.readLineSync().split(' ').map((x) => int.parse(x)).toList();

List<int> inputIntListWithLine(int n) => List.generate(N, (_) => int.parse(stdin.readLineSync()));

List<List<int>> inputMultipleIntListWithLine(int n) => List.generate(N, (_) => stdin.readLineSync().split(' ').map((x) => int.parse(x)).toList());

String inputString() => stdin.readLineSync();

Conclusion

This has been an overview of commonly used input and output techniques in competitive programming with Dart.

I previously participated in competitive programming using Ruby, and it reminded me how concise and convenient Ruby is.

If I continue to participate in competitive programming with Dart, I might write more on the topic.


Related Posts
Related Posts
Promotion

This site uses Google Analytics.