2013-11-26 31 views
2

我试图使用Scala的阅读从标准输入格式输入:斯卡拉构建“列表”,从标准输入读取,输出到stdout

等价的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; 
} 

凡斯卡拉代码,我想用

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

来存储这些数据。

有人可以提供一个示例代码?

或者,只是让我知道如何:

  1. 如何“主()”函数在Scala中工作从标准
  2. 高效地构建从输入列表(如列表
  3. 读取格式的文本是不可改变的,或许还有构建呢?而不是一个新的列表,每个元素是在一个更有效的方式?)
  4. 输出格式化文本到stdout

谢谢!

+0

关于读/解析二进制数据,我建议看看这里:http://stackoverflow.com/questions/2667714/parsing- of-binary-data-with-scala – dmitry

+2

1.和4.查看Google 2.'java.util.Scanner' 3.基本上,'ListBuffer',假设你使用的是命令式的风格,这可能是最适合这种类型的的东西。否则(因为你标记了这个“功能编程”),你可以使用折叠或递归。但是如果你正在追加,'Vector'可能比'List'更适合。 –

回答

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

如果你定义了Application的一个子类,那么你不需要定义一个main方法,并且你可以直接在大括号中作为脚本进行编码。 – loloof64