[FIXED] Konvertieren Sie IndexedSeq in Array

Ausgabe

Ich habe ein 2D-Array, sagen wir eine 3×3-Matrix, und möchte alle Elemente mit einem bestimmten Wert multiplizieren. Das ist, was ich bisher habe:

val m = Array(
  Array(1,2,3),
  Array(4,5,6),
  Array(7,8,9)
)

val value = 3

for ( i <- m.indices) yield m(i).map(x => x*value)

//Result:
//IndexedSeq[Array[Int]] = Vector(Array(3, 6, 9), Array(12, 15, 18), Array(21, 24, 27))

Das Problem ist, dass ich jetzt eine habe IndexedSeq[Array[Int]], aber ich brauche dies, um Array[Array[Int]]genau wie zu sein val m.

Ich weiß, dass das zum Beispiel for (i <- Array(1, 2, 3)) yield izu einem führt Array[Int], aber ich kann nicht herausfinden, wie ich das alles zusammensetzen soll.

Nur anhängen .toArraygeht auch nicht

Lösung

ArrayWenn Sie neue Instanzen erstellen möchten (kopieren):

  val m = Array(
    Array(1,2,3),
    Array(4,5,6),
    Array(7,8,9)
  )
  val value = 3
  val newM = m.map{ array => array.map{x => x * value}}

Oder, wenn Sie die ursprünglichen Arrays “in-place” ändern möchten:

  val m = Array(
    Array(1,2,3),
    Array(4,5,6),
    Array(7,8,9)
  )
  val value = 3  
  for (arr <- m; j <- arr.indices) {
    arr(j) *= value
  }


Beantwortet von –
BccHnw


Antwort geprüft von –
Timothy Miller (FixError Admin)

0 Shares:
Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like