Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read in numbers from n lines into a Scala list?

Tags:

list

scala

This is for an online judge. I am trying to learn some Scala in the process.

The input format looks like

4
543534
6756
4564
363773

So the first line is n, and then the next n lines contain elements that need to go into a list.

Right now I read n by using readInt() but I don't know how to then say "now read the next n lines and place everything into a list".

like image 515
Sean Hill Avatar asked Jun 08 '15 14:06

Sean Hill


2 Answers

Try this:

val n = io.StdIn.readInt
val list = ( 0 to n ).map( (x) -> io.StdIn.readLine ).toList
//...
like image 61
integer-j Avatar answered Nov 15 '22 05:11

integer-j


You can do this in one line if you trust the input and ignore that first range value.

val list = io.StdIn.getLines.drop(1).map(_.toInt).toList
like image 30
Ben Che Avatar answered Nov 15 '22 05:11

Ben Che