How to read inputs using JAVASCRIPT V8 ?

Правка en4, от atulgairola08, 2020-05-21 11:21:13

All the web developers here who love javascript have always faced some difficulty in using it in competitive programming. Code forces has made vanilla javascript available for competitive programming using V8 compiler of chrome.

To start with javascript v8 in codeforces you need to be able to read inputs and give outputs.

HERE we can use readline() and print(), which reads input and gives output respectively

readline()

This function reads the first line of the input as a string including all the whitespaces.

print()

this prints the provided parameter to the console output.

for ex:

INPUT

2 3 4 5

var x = readline();

print(x);

--------------------- OUTPUT

2 3 4 5

If you want each number separately, we use split() cause the input is nothing but a string. So..

INPUT

2 3 4 5


var x = readline().split(' '); // x is an array now [2,3,4,5] print(x);

OUTPUT

2,3,4,5

to take multiline inputs

Mostly in the questions there are more than one lines of input. readline() just reads one line per call.

So, we have to call it again if we need another line input.

INPUT

2

3 4 5


var x = readline(); var y = readline().split(" "); print(x); print(y);

OUTPUT

2

3,4,5

Looping through multiple lines to take input

We usually loop through multiple lines of inputs instead of hardcoding one for each. But we need to be careful that we first declare the var for storing the input outside of the loop else the readline() will keep reading the same line again and again in each loop.

INPUT

3

3 4 5

6 7 8

9 10 11


var x = readline(); // first line of input usually gives the no. of test cases,i.e, the no. of lines ahead. var inp; // declaring the variable outside the loop for(var i = 0 ; i < x ; i++) { inp = readline().split(" "); print(inp); }

OUTPUT

3,4,5

6,7,8

9,10,11

Now you are ready to start your cp journey with js.

Теги codeforce javascript, input read, file input, #how

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en6 Английский atulgairola08 2020-05-21 11:24:46 8
en5 Английский atulgairola08 2020-05-21 11:23:36 74
en4 Английский atulgairola08 2020-05-21 11:21:13 51
en3 Английский atulgairola08 2020-05-21 11:19:19 38
en2 Английский atulgairola08 2020-05-21 11:17:33 50
en1 Английский atulgairola08 2020-05-21 11:15:13 2132 Initial revision (published)