JoeDortman
JoeDortman

Reputation: 185

(Scala) initialize val by looping a list of strings

I'm having trouble looping threw my list of strings. I have a list of strings and i want to iterate threw each elements i'th char: first iteration would be 0 so i would take each strings first element and add them all together, then goes 1, 2 and so on. Basically output goes verticaly from top to bottom.

For example i have a list of strings like this:

"ABC
 DEF
 GHI"

So my out put would be:

"ADG
 BEH
 CFI"

Could anyone point me in the right direction?

In C# or C++ i could simply make two for loops and take myList[y][x] - how do i do this in scala without using muttable variables? I come from C# and C++ background - i could do this blindfolded but scala - im so frustrated, i cannot find any good tutorials online i feel like its a desert out there(Or Maybe ironically enough the one blind here:))

-Thank you! ^^

Upvotes: 0

Views: 231

Answers (2)

Brian
Brian

Reputation: 20285

The transpose method on collections does what you are trying to achieve.

List("ABC", "DEF", "GHI").transpose.map(xs => xs.mkString)
s: List[String] = List(ADG, BEH, CFI)

Upvotes: 7

Dennis Hunziker
Dennis Hunziker

Reputation: 1293

You could use a Range for the index:

val result = <yourlist>.headOption.map { head =>
    (0 until head.length).map { i =>
        <yourlist>.map(_(i))
    }
}

This would result in Some(Vector(List(A, D, G), List(B, E, H), List(C, F, I)))

Upvotes: 0

Related Questions