0

In Scala: Is there a way to directly split a string that contains 72 numeric values separated by ; into a 2-dimensional array of 9 rows and 8 columns with those numeric values -in numeric data type-?

2 Answers 2

4
val input = List.tabulate(72)(_.toString).mkString(";")
input.split(";").map(_.toInt).grouped(9).toArray

transforms

0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;23;24;25;26;27;28;29;30;31;32;33;34;35;36;37;38;39;40;41;42;43;44;45;46;47;48;49;50;51;52;53;54;55;56;57;58;59;60;61;62;63;64;65;66;67;68;69;70;71

into

Array(
  Array(0, 1, 2, 3, 4, 5, 6, 7, 8), 
  Array(9, 10, 11, 12, 13, 14, 15, 16, 17), 
  Array(18, 19, 20, 21, 22, 23, 24, 25, 26), 
  Array(27, 28, 29, 30, 31, 32, 33, 34, 35), 
  Array(36, 37, 38, 39, 40, 41, 42, 43, 44), 
  Array(45, 46, 47, 48, 49, 50, 51, 52, 53), 
  Array(54, 55, 56, 57, 58, 59, 60, 61, 62), 
  Array(63, 64, 65, 66, 67, 68, 69, 70, 71)
)

If you want to swap the dimensions of rows/columns, replace 9 by 8.

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

1 Comment

They can do a transpose to get column-major from row-major and vice versa
1

using Range and grouped functions

scala> val a = (0 to 71).map(_.toString).toArray.mkString(";")
a: String = 0;1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;23;24;25;26;27;28;29;30;31;32;33;34;35;36;37;38;39;40;41;42;43;44;45;46;47;48;49;50;51;52;53;54;55;56;57;58;59;60;61;62;63;64;65;66;67;68;69;70;71

scala> a.split(";").map(_.toInt).sliding(9,9).toArray
res269: Array[Array[Int]] = Array(Array(0, 1, 2, 3, 4, 5, 6, 7, 8), Array(9, 10, 11, 12, 13, 14, 15, 16, 17), Array(18, 19, 20, 21, 22, 23, 24, 25, 26), Array(27, 28, 29, 30, 31, 32, 33, 34, 35), Array(36, 37, 38, 39, 40, 41, 42, 43, 44), Array(45, 46, 47, 48, 49, 50, 51, 52, 53), Array(54, 55, 56, 57, 58, 59, 60, 61, 62), Array(63, 64, 65, 66, 67, 68, 69, 70, 71))

scala>

1 Comment

Re-read the question. You missed the part about "split a string".

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.