Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy a two-dimensional array in Kotlin?

Tags:

arrays

kotlin

This method works fine. However, I think it is not functional.

fun getCopy(array: Array<BooleanArray>): Array<BooleanArray> {
    val copy = Array(array.size) { BooleanArray(array[0].size) { false } }
    for (i in array.indices) {
        for (j in array[i].indices) {
            copy[i][j] = array[i][j]
        }
    }
    return copy
}

Is there a more functional way?

like image 554
mmorihiro Avatar asked Nov 07 '16 10:11

mmorihiro


People also ask

How do you copy a double array?

Copying Arrays Using arraycopy() method src - source array you want to copy. srcPos - starting position (index) in the source array. dest - destination array where elements will be copied from the source. destPos - starting position (index) in the destination array.

How to copy all elements of an int array in Kotlin?

This article explores different ways to copy all elements of an int array into a new array in Kotlin... The `copyOf()` function returns a new array, a copy of the original array, resized to the given size. To copy the complete array, pass the original array's length to the `copyOf()` function. TECHIE DELIGHT </> Ace your Coding Interview

How to declare and initialize two-dimensional arrays in Kotlin?

This article covers different ways to declare and initialize two-dimensional arrays in Kotlin. 1. Using arrayOf()function. The most common way to declare and initialize arrays in Kotlin is the arrayOf()function. To get a two-dimensional array, each argument to the arrayOf()function should be a single dimensional array.

What is a jagged array in Kotlin?

The resultant array is called a jagged array, whose elements can have different dimensions and sizes. Following is a simple example demonstrating the jagged arrays: This will result in the following two-dimensional ragged array: That’s all about declaring and initializing a two-dimensional array in Kotlin. Average rating 4.83 /5.

How do you use apply () method in Kotlin?

In Kotlin, you can squeeze the above method to the following single line of code: By definition, apply accepts a function, and sets its scope to that of the object on which apply has been invoked. This means that no explicit reference to the object is needed. Apply () can do much more than simply setting properties of course.


1 Answers

You can make use of clone like so:

fun Array<BooleanArray>.copy() = map { it.clone() }.toTypedArray()

or if you'd like to save some allocations:

fun Array<BooleanArray>.copy() = arrayOfNulls<ByteArray>(size).let { copy ->
    forEachIndexed { i, bytes -> copy[i] = bytes.clone() }
    copy
} as Array<BooleanArray>

or even more concise as suggested by @hotkey:

fun Array<BooleanArray>.copy() = Array(size) { get(it).clone() }
like image 161
miensol Avatar answered Oct 16 '22 20:10

miensol