user3747181
user3747181

Reputation: 31

Scala - read a file columnwise

I am new to Scala. I have a file with following data : 1:2:3 2:4:5 8:9:6

I need to read this file columnwise (1:2:8)(2:4:9)(3:5:6)to find out minimum of each column. How to read it column wise and put it in separate arrays?

Upvotes: 1

Views: 1226

Answers (1)

stew
stew

Reputation: 11366

Read the file in row wise, split the rows into columns, then use transpose:

scala> val file="1:2:3 2:4:5 8:9:6"
file: String = 1:2:3 2:4:5 8:9:6

scala> file.split(" ")
res1: Array[String] = Array(1:2:3, 2:4:5, 8:9:6)

scala> file.split(" ").map(_.split(":"))
res2: Array[Array[String]] = Array(Array(1, 2, 3), Array(2, 4, 5), Array(8, 9, 6))

scala> file.split(" ").map(_.split(":")).transpose
res3: Array[Array[String]] = Array(Array(1, 2, 8), Array(2, 4, 9), Array(3, 5, 6))

scala> file.split(" ").map(_.split(":")).transpose.map(_.min)
res4: Array[String] = Array(1, 2, 3)

Upvotes: 2

Related Questions