Question

This is probably going to end up being very simple, but I ask more to help me learn better Scala idioms (Python guy by trade looking to learn some scala tricks.)

I'm doing some hacker rank problems and the method of input requires is a read over lines from stdin. The spec is quoted below:

The first line contains the number of test cases T. T test cases follow. Each case contains two integers N and M.

So in the input passed to the script looks something like this:

4
2 2
3 2
2 3
4 4

I'm wondering what would be the proper, idiomatic way to do this. I've thought of a few:

  • Use io.Source.stdin.readLines.zipWithIndex, then from within a foreach, if the index is greater than 0, split on whitespace and map to (_.toInt)
  • Use the same readLines function to get the input and then pattern match against the index.
  • Split on whitespace and newlines to make a single list of digits, map toInt, pop the first element (problem size) and then modulo 2 to make tuples of arguments for my problem function.

I'm wondering what more experienced scala programmers would consider the best way to parse these args, where the 2 element lines would be args to a function and the first, single digit line is just the number of problems to solve.

Was it helpful?

Solution

Maybe you're looking for something like this?

def f(x: Int, y: Int) = { f"do something with $x and $y" }

io.Source.stdin.readLines
  .map(_.trim.split("\\s+").map(_.toInt))    // split and convert to ints
  .collect { case Array(a, b) => f(a, b) }   // pass to f if there are two arguments
  .foreach(println)                          // print the result of each function call

OTHER TIPS

Another way to read the input for Hacker Rank problems is with scala.io.Stdin

import scala.io.StdIn
import scala.collection.mutable.ArrayBuffer

object Solution {
  def main(args: Array[String]) = {
    val q = StdIn.readInt
    var lines = ArrayBuffer[Array[Int]]()
    (1 to q).foreach(_ => lines += StdIn.readLine.split(" ").map(_.toInt))
    for (a <- lines){
      val n = a(0)
      val m = a(1)
      val ans = n * m
      println(ans)
    }
  }
}

I have tested it on Hacker Rank platform today and the output is:

4
6
6
16
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top