1

Let a

Seq( Seq(1, 2, 5) , Seq(3, 4, 5) , Seq(2, 1, 0) ) 

I'd want to get :

Seq( Seq(1, 3, 2) , Seq(2, 4, 1) , Seq(5, 5, 0) ) 

For the moment I wrote this :

points.reduce((point_1, point_2) => point_1.zip(point_2)) 

With : points the Seq[Seq[Double]] and point_1 and point_2 the Seq[Double].

It returns an error because Scala's interpreter seems to try to make a pair with a Seq[(Double, Double)] and Double (I think). In my example, it tries to make a pair with Seq( (1, 3) ) and 2. I can be wrong but it's my interpretation of the problem for now.

Well, how to solve this bug ? I feel like I need to use flatten, no ?

2 Answers 2

4

The standard library can do that for you.

Seq( Seq(1, 2, 5) , Seq(3, 4, 5) , Seq(2, 1, 0) ).transpose //res0: Seq[Seq[Int]] = List(List(1, 3, 2), List(2, 4, 1), List(5, 5, 0)) 

update

If you're intent on doing it yourself, in a functional fashion, here's one way.

val ssi: Seq[Seq[Int]] = Seq(Seq(1, 2, 5), Seq(3, 4, 5), Seq(2, 1, 0)) ssi.zipWithIndex.map{case (s,x) => s.indices.map(ssi(_)(x)) } 
Sign up to request clarification or add additional context in comments.

2 Comments

In functional paradigm, e.g. with only map and reduce (my teacher said every program can be written thanks to these both methods, so it's possible to do what I want with only these functions)
As you can see, it can be done with map and zip.
1

If you want to do it using map and fold,

val seqInput = Seq( Seq(1, 2, 5) , Seq(3, 4, 5) , Seq(2, 1, 0) ) // seqInput: Seq[Seq[Int]] = List(List(1, 2, 5), List(3, 4, 5), List(2, 1, 0)) val seqOutput = seqInput .map(s => Seq(s)) .fold( seqInput.head.map(_ => Seq.empty[Int]) )({ case (acc, seq) => acc.zipWithIndex.map({ case (accSeq, i) => accSeq :+ seq.head(i) }) }) // seqOutput: Seq[Seq[Int]] = List(List(1, 3, 2), List(2, 4, 1), List(5, 5, 0)) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.