Scala构造一个“List”,从stdin读取,输出到stdout

时间:2013-11-26 08:46:12

标签: scala functional-programming purely-functional

我正在尝试使用Scala从stdin读取格式化输入:

等效的C ++代码在这里:

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;
}

在Scala代码中,我想使用

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

存储这些数据。

有人可以提供示例代码吗?

或者,让我知道如何:

  1. “main()”函数在scala中的工作原理
  2. 从stdin
  3. 读取格式化文本
  4. 从输入中有效地构建一个列表(因为列表是不可变的,也许有一种更有效的方法来构造它?而不是每个元素都有一个新的列表?)
  5. 将格式化文本输出到stdout
  6. 感谢!!!

1 个答案:

答案 0 :(得分:1)

我不懂C ++,但这样的事情应该有效:

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
    }
  }