lathspell
lathspell

Reputation: 3310

Generate n*m array

I'm learning Kotlin and wonder if there is a functional way e.g. "in one line" to create a n*m array and map it to a flat list.

E.g. the following would create a list of 20*30=600 Seat objects. The row/col variables start with 1. Preferably the variable name "it" could be replaced by the names "row"/"col" directly.

val screen = Array(20, {
  val row = it + 1
  Array(30, {
    val col = it + 1
    Seat(row, col)
  }
}).flatten()

Upvotes: 0

Views: 83

Answers (1)

Ewan Mellor
Ewan Mellor

Reputation: 6847

val screen = (1..20).flatMap { row -> (1..30).map { col -> Pair(row, col) } }
// screen = [ Pair(1, 1), Pair(1, 2), ... ]

Upvotes: 1

Related Questions