0

I want process to two dimension list in scala: eg:

Input:

List(
  List(‘John’, ‘Will’, ’Steven’),
  List(25,28,34),
  List(‘M’,’M’,’M’)
)

O/P:

John|25|M
Will|28|M
Steven|34|M
4
  • 4
    What's the problem? Commented Jun 6, 2022 at 10:32
  • Welcome to SO @Ankit, can you edit your post to add a precise question and the code you tried so far? Commented Jun 6, 2022 at 10:52
  • Sounds like transpose? Commented Jun 6, 2022 at 13:59
  • I got the expected using for loop, I have posted the logic. Commented Jun 6, 2022 at 14:20

2 Answers 2

1

You need to work with indexes, and while working with indexes List is not probably the wisest choice, and also your input is not a well-structured two dimensional list, I would suggest you to have a dedicated data structure for this:

// you can name this better
case class Input(names: Array[String], ages: Array[Int], genders: Array[Char])
val input = Input(Array("John", "Will", "Steven"), Array(25, 28, 34), Array('M', 'M', 'M'))

By essence, this question is meant to use indexes with, so this would be a solution using indexes:

input.names.zipWithIndex.map {
    case (name, index) => 
      (name, inp.ages(index), inp.genders(index))
  } 
// or use a for instead

But always try to keep an eye on IndexOutOfBoundsException while working with array indexes. A safer and more "Scala-ish" approach would be zipping, which also take care of arrays with non-equal sizes:

input.names zip inp.ages zip inp.genders map { // flattening tuples
  case ((name, age), gender) => (name, age, gender)
}

But this is a little bit slower (one iteration per zipping, and an iteration in mapping stage, I don't know if there's an optimization for this).
And in case you didn't want to go on with this kind of modeling, the algorithm would stay just the same, except for explicit unsafe conversions you will need to do from Any to String and Int and Char.

Sign up to request clarification or add additional context in comments.

Comments

0

I got the expected o/p from for loop

for(i<-0 to 2)
{
 println()
   for(j<-0 to 2)
      {
         print(twodlist(j)(i)+"|")
      }
}

Note: In loop we can use list length instead of 2 to make it more generic.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.