Kotlinlearncs.online LogoJava

Multidimensional Arrays

var pixels = Array(32) { IntArray(32) }
for (i in pixels.indices) {
for (j in pixels[i].indices) {
pixels[i][j] = i + j
}
}
println(pixels[8][18])

This is another extremely exciting lesson, because we’ll learn how to work with even more data. We’ll break free from our linear shackles into full multi-dimensional splendor. Let’s get started!

Debugging Practice
Debugging Practice

But first, let’s get a bit more debugging practice!

Let's get some practice working with Kotlin Strings: an incredibly useful data type for working with text.

Write a function called reformatPhoneNumber. It should take a String containing a phone number in the format 111-222-3333 and return it reformatted as (111) 222-3333.

You will want to explore the various String methods to help you with this task. In particular, you may find split and substring helpful. There are solutions that use split, others that use substring, and probably others that use neither!

Multidimensional Data
Multidimensional Data

So far we’ve worked with single data values, arrays of values, and Strings—which on some level or just character arrays with features. But all of the plural data that we’ve worked with so far has been linear. We’ve learned how to put things in order. But just try linearizing this guy:

It turns out that a lot of the data around us is multidimensional. Photos are just one example.

Multidimensional Arrays
Multidimensional Arrays

Of course Kotlin has a way to work with multidimensional data. In some ways it’s a straightforward extension of what we’ve been doing, but in other ways in introduces some new syntax.

Here’s our first multidimensional array:

var values = Array(8) { IntArray(8) }

We see both familiar and unfamiliar bits here. IntArray(8) is how we created an empty array of Int values. Array(8) looks similar, except it’s not prefixed with a type. But what is happening with the rest of the syntax? Let’s investigate!

var values = Array(8) { IntArray(8) }

How would we create an empty three-dimensional array?

var values = Array(8) { Array(88) { IntArray(8) } }

Similar idea. The 3-d array shown above has size 8 in the first dimension, 88 in the second dimension, and 8 in the third dimension. And it contains Ints, since the inner array is an IntArray. If we wanted the same size array but containing Doubles, it would look like this:

var values = Array(8) { Array(88) { DoubleArray(8) } }

Array indexing in multidimensional arrays works just the same as we’ve seen in the past:

var values = Array(8) { Array(4) { IntArray(2) } }
println(values[4][2][1])
values[2][2][1] = 10
println(values[2][2][1])

And we can still have problems with our bounds if we’re not careful:

var values = Array(8) { Array(4) { IntArray(2) } }
println(values[4][2][2])

Forget Rows and Columns
Forget Rows and Columns

A bi-yearly rant. Forget about rows and columns. Do you want to work with spreadsheets your entire life? This limited mental model will utterly fail you when you need it most!

var samples = Array(2) { IntArray(64) }

Arrays of Arrays of Arrays
Arrays of Arrays of Arrays

Let’s explore how multidimensional arrays in Kotlin actually work. Specifically, we’ll examine the following piece of code:

var twod = arrayOfNulls<IntArray>(2)
var oned = IntArray(8)
twod[1] = oned
twod[0] = IntArray(4)
println(twod.size)
println(twod[0]?.size) // Note the safe call operator here!
println(twod[1]?.size)
var twod = arrayOfNulls<IntArray>(2)

Non-Rectangular Arrays
Non-Rectangular Arrays

Note one important consequence of the fact that Kotlin arrays are arrays of arrays. They do not need to be rectangular! As demonstrated above, an inner array can have a different size at each index. Some may even be null!

If this doesn’t make perfect sense to you, don’t worry. Next we’ll show you patterns that you can use below to work with any array, rectangular or non.

Array Initializers
Array Initializers

Let’s look a bit more closely at the syntax for declaring multidimensional arrays in Kotlin. Specifically, let’s start our investigation here:

var values = IntArray(8) { 4 }
println(values.contentToString())

What’s going on? Didn’t we previously say that arrays of Ints were initialized to zero? Why does this one seem to contain all 4s? And what’s going on with the { block following the IntArray(8)?

That block contains what is called an array initializer. Each element in the array is initialized by evaluating that expression. Which can contain any expression that evaluates to an Int:

var values = IntArray(8) { 2 * 2 + 4 }

We won’t use this feature often. But it’s helpful to understand when examining Kotlin’s syntax for working with multidimensional arrays. Specifically:

var values = Array(8) { IntArray(2) }

Initializes values to an array of 8 elements (Array(8)) where each of the 8 elements is the result of evaluating { IntArray(2) }, meaning each result is an IntArray(2), or an array of Ints of size 2. Whew!

Multidimensional Array Literals
Multidimensional Array Literals

These exist as a fairly straightforward extension of what we’ve seen already. But don’t worry: we don’t use these often!

var values = arrayOf(arrayOf(intArrayOf(1, 2), intArrayOf(3)))
println(values[0][1][0])

The difficulty with this syntax is that it’s hard if not impossible to tell what value ends up where by reading the initialization. That’s why we tend to avoid this syntax.

Practice: Array Sum (Two Dimensional)

Created By: Geoffrey Challen
/ Version: 2020.9.0

Declare and implement a function called arraySum that receives a nullable two-dimensional double array (Array<DoubleArray>?) values as its only parameter and returns the sum of the values in the array as a Double. If the array is null you should return 0 (as a Double). None of the inner arrays will be null.

Multidimensional Array Programming Patterns
Multidimensional Array Programming Patterns

Just like single-dimensional arrays, we can develop similar programming patterns for working with multidimensional arrays. Let’s look at an example together.

var values = Array(8) { IntArray(8) }

Homework: 2D Array Max Subarray Sum

Created By: Geoffrey Challen
/ Version: 2021.8.0

Write a function maxSubarraySum that, given a non-rectangular two-dimensional non-nullable Int array, returns the sum of the subarray that sums to the largest value.

So given the following array, with each subarray on a separate line:

1, 2, 4
4, 1, -1
6, 8, -10, -9
-1

You would return 7. The passed array will contain no empty subarrays.

One hint for this problem is that you may need both an Int variable to store the max and a Boolean variable to record whether the maximum value has been initialized. Once you have summed each subarray, check whether either your Boolean value is false or the sum is larger than the largest you've seen so far. After you check the sum of the first subarray, set your Boolean value to true. Another approach is to use the counter that you use to proceed through each subarray to determine whether you have initialized the max value.

More Practice

Need more practice? Head over to the practice page.