Split an array into two parts in Kotlin
This article explores different ways to split an array into two parts in Kotlin. For an odd length array, the middle item should become part of the first array.
1. Custom Routine
We can write our custom routine for this simple task. The idea is to construct two arrays, and fill the first array with elements from the first half and the second array with elements from the second half of the original array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun main() { val arr = intArrayOf(1, 2, 3, 4, 5) val n = arr.size val a = IntArray((n + 1) / 2) val b = IntArray(n - a.size) for (i in 0 until n) { if (i < a.size) a[i] = arr[i] else b[i - a.size] = arr[i] } println(a.contentToString()) println(b.contentToString()) } |
Output:
[1, 2, 3]
[4, 5]
2. Using System.arraycopy() function
The System.arraycopy() copies an array from a specified position in an array to a specified position in another array. We can use this as:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val arr = intArrayOf(1, 2, 3, 4, 5) val n = arr.size val a = IntArray((n + 1) / 2) val b = IntArray(n - a.size) System.arraycopy(arr, 0, a, 0, a.size) System.arraycopy(arr, a.size, b, 0, b.size) println(a.contentToString()) println(b.contentToString()) } |
Output:
[1, 2, 3]
[4, 5]
3. Using copyOfRange() function
Instead of manually creating the new array, you can call the copyOfRange() function that automatically declares the array and copies the elements.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val arr = intArrayOf(1, 2, 3, 4, 5) val n = arr.size val a = arr.copyOfRange(0, (n + 1) / 2) val b = arr.copyOfRange((n + 1) / 2, n) println(a.contentToString()) println(b.contentToString()) } |
Output:
[1, 2, 3]
[4, 5]
That’s all about splitting an array into two parts in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)