Snippets

Here we archive snippets for input/output handling on different languages.

Contributing

The official repository is https://github.com/coding-gym/snippets

Anyone is encouraged to contribute, adding new languages or typical input/output cases.

C#

Reading an array of N elements

The first line contains N, the number of elements.

The next line contains N space-separated integers.

1
2
int N = Convert.ToInt32(Console.ReadLine());
int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), Convert.ToInt32);

C++

Premise To be more exact, we should include all the needed headers first. For example: 1 2 3 4 #include <iostream> // for I/O#include <iterator> // for istream_iterator#include <vector> // for vector#include <string> // for string Actually, since we are usually hosted on machines with GCC, we can include only: 1 #include <bits/stdc++.h> Which makes everything from the STL available. Remember this header is not standard. [Read More]

Haskell

The interact function The interact function takes a function of type String -> String as its argument. The entire input from the standard input device is passed to this function as its argument, and the resulting string is output on the standard output device. Predicate on strings Example: Balanced Brackets Input: 1 2 3 4 3 {[()]} {[(])} {{[[(())]]}} Output: 1 2 3 YES NO YES The first line contains a single integer n, the number of strings. [Read More]

PHP

Reading strings We can read a single line string using the built-in functions fscanf() where %s operator casts input stream as a string: 1 2 $s = ''; fscanf(STDIN, "%s\n", $s); or fgets() 1 $s = trim(fgets(STDIN)); Reading an array of integers When you need to read an array of integers, you have to read the entire string line and then convert it in array using explode() built-in function. [Read More]

Python

Reading strings We can read a single line string using the built-in functions input(): 1 a_line_read = input() Reading an array of integers When you need to read an array of integers, you have to read the entire line, split it and the convert each element to an int: 1 a_list_of_nums = map(int, input().split()) Reading n rows made up of a single integer 1 2 for n in range(10): single_int = map(int, input()) Writing on STDOUT When you need to write on stdout use: [Read More]

Rust

Premise At to date, HackerRank does not give you anything more than a Write you code here. If you take into account that the version of the compiler is a bit old, it is a bit slow to compile, no completion or rustfmt… It is not exactly a pleasure to code in Rust on HackerRank. So… let’s open your favorite IDE/Editor on steroids and copy-paste your solution to HR! You can also try The Rust Playground! [Read More]