2

I'm trying to read formatted inputs from stdin using Scala:

The equivalent C++ code is here:

int main() {
  int t, n, m, p;
  cin >> t;
  for (int i = 0; i < t; ++i) {
    cin >> n >> m >> p;
    vector<Player> players;
    for (int j = 0; j < n; ++j) {
      Player player;
      cin >> player.name >> player.pct >> player.height;
      players.push_back(player);
    }
    vector<Player> ret = Solve(players, n, m, p);
    cout << "Case #" << i + 1 << ": ";
    for (auto &item : ret) cout << item.name << " ";
    cout << endl;
  }
  return 0;
}

Where in the Scala code, I'd like to Use

players: List[Player], n: Int, m: Int, p: Int

to store these data.

Could someone provide a sample code?

Or, just let me know how to:

  1. how the "main()" function work in scala
  2. read formatted text from stdin
  3. efficiently constructing a list from inputs (as list are immutable, perhaps there's a more efficient way to construct it? rather than having a new list as each element comes in?)
  4. output formatted text to stdout

Thanks!!!

2
  • Regarding reading/parsing binary data I recommend to look here: stackoverflow.com/questions/2667714/… Commented Nov 26, 2013 at 12:10
  • 2
    1. and 4. look on Google 2. java.util.Scanner 3. basically, ListBuffer, assuming you're using imperative style, which is probably best for this type of thing. Otherwise (since you tagged this "functional-programming"), you can use folds or recursion. However Vector may be more suitable than List if you're appending. Commented Nov 26, 2013 at 16:09

1 Answer 1

1

I don't know C++, but something like this should work :

def main(args: Array[String]) = {
    val lines = io.Source.stdin.getLines
    val t = lines.next.toInt
    // 1 to t because of ++i
    // 0 until t for i++
    for (i <- 1 to t) {
      // assuming n,m and p are all on the same line
      val Array(n,m,p) = lines.next.split(' ').map(_.toInt)
      // or (0 until n).toList if you prefer
      // not sure about the difference performance-wise
      val players = List.range(0,n).map { j =>
        val Array(name,pct,height) = lines.next.split(' ')
        Player(name, pct.toInt, height.toInt)
      }
      val ret = solve(players,n,m,p)
      print(s"Case #${i+1} : ")
      ret.foreach(player => print(player.name+" "))
      println
    }
  }
Sign up to request clarification or add additional context in comments.

1 Comment

If you define a subclass of Application, then you don't need to define a main method, and you can code as a script directly in the curly braces.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.