Home > Mobile >  How to merge two 2d array
How to merge two 2d array

Time:10-30

I have two 2d arrays of type Array<Array>, but when I combine it with plus method I get output like:

cells.plus(states.last().board.cells) —>

My output (cells here is my array of Array<Array<Char>>)
|     |
|  X  |
|     |
|X    |
|     |
|     |

How to merge it correctly?

For example I have:

val board3x3Array = arrayOf(
    arrayOf(' ', ' ', ' '),
    arrayOf(' ', 'X', ' '),
    arrayOf(' ', ' ', '0')
)

val board3x3Array2 = arrayOf(
    arrayOf('0', ' ', ' '),
    arrayOf(' ', ' ', ' '),
    arrayOf(' ', ' ', ' ')
)

And I need after merge:

val merged = arrayOf(
    arrayOf('0', ' ', ' '),
    arrayOf(' ', 'X', ' '),
    arrayOf(' ', ' ', '0')
)

CodePudding user response:

You can archieve by following code:

    val mergedArray = board3x3Array2.mapIndexed { index, array ->
    array.mapIndexed { index2, c ->
        if (c == ' ') board3x3Array[index][index2] else c
    }.toTypedArray()
}.toTypedArray()

here above simply you're checking if the value of board3x3Array2 in cell is empty string ' ' then you're replacing that cell with value of board3x3Array

CodePudding user response:

Assumptions: both 2D arrays have the same dimensions, and if both arrays have a non-' ' character at a coordinate, the first array wins.

I think the easiest way would be to use the Array constructor to create the merged array while iterating the sizes from one of the source arrays, like this. Might as well use CharArray for performance.

val merged = Array(source1.size) { i ->
    CharArray(source1[i].size) { j ->
        if (source1[i][j] != ' ') source1[i][j] else source2[i][j]
    }
}
  • Related