使用Scala解析矩阵数据

tim*_*c31 1 arrays parsing scala matrix

我有一个日志文件,格式如下:

3
1 2 3
1 2 3 
1 2 3
1 2 3
4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
Run Code Online (Sandbox Code Playgroud)

单个数字表示矩阵的宽度,因为它们始终具有相同的高度.并且在同一日志文件中可以有多个矩阵.我不想将矩阵数据解析成数组.我阅读了这些行scala.io.Source.fromFile(f).getLines.mkString,但我正在努力填充数组.

for(i <- 0 to 3) {
    for(j <- 0 to N-1) {
        matrix(i)(j) = ...
    }
}
Run Code Online (Sandbox Code Playgroud)

如果这些行的索引方式与我想要的矩阵一样,那就不会那么难了.但是当行(n)包含空格,换行符时..我做错了什么?

ste*_*hke 6

您可以通过几个简单的步骤轻松完成此操作:

  1. 首先将输入分成List一行
  2. 然后分解各行成ListString小号
  3. 然后将String列表中的每个转换为Int
  4. 最后总结本ListListLists到一个ListArrays(使用简单的状态机)

状态机非常简单.

  1. 它首先读取下一个矩阵中的行数并记住它
  2. 然后它将该行数读入当前矩阵
  3. 在读取了记忆的行数后,它将当前矩阵添加到读取矩阵列表中并返回步骤1

代码看起来像这样:

    import io.Source

    def input = Source.fromString(
       """|3
          |1 2 1
          |1 2 2 
          |1 2 3
          |4
          |1 2 3 1
          |1 2 3 2
          |1 2 3 3
          |1 2 3 4""".stripMargin) // You would probably use Source.fromFile(...)

    type Matrix = List[Array[Int]]

    sealed trait Command
    case object ReadLength extends Command
    case class ReadLines(i: Int, matrix: Matrix) extends Command

    case class State(c: Command, l: List[Matrix])

    val parsedMatrixes = input.getLines().map(_.split(" ")).map(_.map(_.toInt)).foldLeft(State(ReadLength, List())) {
       case (State(ReadLength, matrixes), line) => State(ReadLines(line(0), List()), matrixes)
       case (State(ReadLines(1, currentMatrix), matrixes), line) => State(ReadLength,((line::currentMatrix).reverse)::matrixes)
       case (State(ReadLines(i, currentMatrix), matrixes), line) => State(ReadLines(i - 1, line::currentMatrix), matrixes)
    }.l.reverse
Run Code Online (Sandbox Code Playgroud)

并给你以下结果:

parsedMatrixes: List[Matrix] = 
List(
  List(Array(1, 2, 1), 
       Array(1, 2, 2), 
       Array(1, 2, 3)), 
  List(Array(1, 2, 3, 1), 
       Array(1, 2, 3, 2), 
       Array(1, 2, 3, 3), 
       Array(1, 2, 3, 4)))
Run Code Online (Sandbox Code Playgroud)

请注意,这不是最终解决方案,因为它没有任何错误处理.并且它不会释放其资源(关闭源代码).