Reinforce your understanding of array memory addressing, boundary validation, and coordinate translation through hands-on calculation problems.
Problem 1: Calculating 1D Physical Addresses
Specification
You have an array of 64-bit floating-point numbers (Double, size = 8 bytes per element).
- Base Address:
0x5000 - Array Size: 100 elements (indices
0through99)
Questions:
- What is the physical hexadecimal address of element at index
0? - What is the physical hexadecimal address of element at index
12? - If an access requests index
100, what happens at the hardware and runtime levels?
Solution & Breakdown:
- Index 0:
Address = 0x5000 + (0 × 8) = 0x5000
- Index 12:
12 × 8 = 96 bytes (decimal) = 0x60 (hexadecimal) Address = 0x5000 + 0x60 = 0x5060
- Index 100:
Index 100 is out of bounds. In unmanaged languages (C/C++), this computes
0x5000 + 800 = 0x5320, leading to a buffer overflow or Segmentation Fault. In managed runtimes (Kotlin/Java/C#), bounds checks throw anArrayIndexOutOfBoundsExceptionbefore accessing the address.
Problem 2: 2D Matrix Coordinate Flattening
Specification
A high-resolution image has dimensions:
- Width (
W) = 1920 pixels - Height (
H) = 1080 pixels - Flattened into a 1D
IntArray(1920 * 1080).
Tasks:
- Write the mathematical formula to convert a 2D coordinate (x, y) into the corresponding 1D index.
- Calculate the 1D index for pixel (x = 450, y = 200).
- Write the inverse function: given 1D index
1,000,000, find its (x, y) coordinates.
Solution & Breakdown:
- Flattening Formula:
Index = (y × W) + x
- Calculate (450, 200):
Index = (200 × 1920) + 450 = 384,000 + 450 = 384,450
- Inverse Unflattening Formula:
y = floor(Index / W) x = Index mod W For index
1,000,000: y = floor(1,000,000 / 1920) = 520 x = 1,000,000 mod 1920 = 1,000,000 - (520 × 1920) = 1,000,000 - 998,400 = 1600 Coordinates: (x = 1600, y = 520).
Challenge Implementation in Kotlin
class Matrix2D(val width: Int, val height: Int) {
private val buffer = IntArray(width * height)
fun get(x: Int, y: Int): Int {
require(x in 0 until width && y in 0 until height) { "Out of bounds!" }
return buffer[(y * width) + x]
}
fun set(x: Int, y: Int, value: Int) {
require(x in 0 until width && y in 0 until height) { "Out of bounds!" }
buffer[(y * width) + x] = value
}
fun getCoordinates(index: Int): Pair<Int, Int> {
require(index in buffer.indices) { "Index out of range!" }
val y = index / width
val x = index % width
return Pair(x, y)
}
}