4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Scala] 標準入力取得方法について 個人的まとめ

Last updated at Posted at 2019-08-20

普段の業務では標準入力の値を取得することがないのですが、paizaのスキルチェックをやったときに、Aランクあたりから標準入力の形式が複雑になり、手間取ったので、方法をまとめてみました。

「もっと良い方法があるよ!」という方はコメント頂けると幸いです。

一行取得

Dランク~Bランクでよくある

// 一行取得
val line = scala.io.StdIn.readLine

// 1文字ずつ分割
val split = line.toList

複数行取得

Bランク~でよくある

全行同一の型、入力数

入力例

10 1 30
33 3 3
22 1 4
13 4 5
object Main extends App {
  // 受け取りたい型に合わせて型を指定
  val tempList: Seq[(Int, Int, Int)] = {
    for(line <- io.Source.stdin.getLines()) yield {
      // Stringのリストを作る場合は、.map(_.toInt)を抜く
      val rowData = line.split(' ').map(_.toInt)
      (rowData(0), rowData(1), rowData(2))
    }
  }.toSeq

  // 標準入力を変数にセット
  val (l, m, n) = tempList.head
  val list = tempList.tail

  println("l:" + l + ", m:" + m + ", n:" + n)
  println(list)
}

// 出力
// l:10, m:1, n:30
// List((33,3,3), (22,1,4), (13,4,5))

一行目と二行目以降で扱いが違うケース

入力例

A B C D
33 3 3
22 1 4
13 4 5
object Main extends App {
  // 受け取りたい型に合わせて型を指定
  val tempList: Seq[Seq[String]] = {
    for (line <- io.Source.stdin.getLines()) yield {
      line.split(' ').toSeq
    }
  }.toSeq

  // 標準入力を変数にセット
  val (k, l, m, n) = (tempList(0)(0), tempList(0)(1), tempList(0)(2), tempList(0)(3))
  val list = tempList.tail.map(l => l.map(_.toInt))

  println("k:" + k + ", l:" + l + ", m:" + m + ", n:" + n)
  println(list)
}

// 出力
// k:A, l:B, m:C, n:D
// List(List(33, 3, 3), List(22, 1, 4), List(13, 4, 5))

区切り文字がない場合

入力例

10 3
000100
110000
111100
object Main extends App{
  // 受け取りたい型に合わせて型を指定
  val firstRow = scala.io.StdIn.readLine.split(' ').map(_.toInt)
  // 標準入力を変数にセット
  val (m, n) = (firstRow(0), firstRow(1))

  // nが行数を表しているとする
  val list = for (i <- 1 to n) yield (scala.io.StdIn.readLine.toList)

  println("m:" + m + ", n:" + n)
  println(list)
}


// 出力
// m:10, n:3
// Vector(List(0, 0, 0, 1, 0, 0), List(1, 1, 0, 0, 0, 0), List(1, 1, 1, 1, 0, 0))
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?