Careeroza
Real World Example
Cinema Seat Booking
A movie ticket app like BookMyShow keeps the seat map of a screen as a grid: rows and columns with a fixed size. A 2D array fits naturally. Fitness apps similarly keep 7 days of step counts in an IntArray.
Example
Booking seats on a small screen and printing the map:
fun main() {
val rows = 4
val cols = 6
val booked = Array(rows) { BooleanArray(cols) }
fun book(seat: String): Boolean {
val r = seat[0] - 'A'
val c = seat.substring(1).toInt() - 1
if (r !in 0 until rows || c !in 0 until cols) return false
if (booked[r][c]) return false
booked[r][c] = true
return true
}
println("Book B3: ${book("B3")}")
println("Book B4: ${book("B4")}")
println("Book B3 again: ${book("B3")}")
println("Book Z9: ${book("Z9")}")
println(" SCREEN THIS WAY")
for (r in 0 until rows) {
val line = booked[r].joinToString(" ") { if (it) "X" else "_" }
println("${'A' + r} $line")
}
val free = booked.sumOf { row -> row.count { !it } }
println("Seats available: $free")
}Output
Book B3: true Book B4: true Book B3 again: false Book Z9: false SCREEN THIS WAY A _ _ _ _ _ _ B _ _ X X _ _ C _ _ _ _ _ _ D _ _ _ _ _ _ Seats available: 22
Practice
Exercise: Create an IntArray of 7 daily step counts: 5000, 7200, 10400, 3000, 12000, 8000, 9500. Print the total, the average as a whole number, and on which day number (1-based) the maximum steps were walked.
Show answer
fun main() {
val steps = intArrayOf(5000, 7200, 10400, 3000, 12000, 8000, 9500)
println("Total: ${steps.sum()}") // 55100
println("Average: ${steps.average().toInt()}") // 7871
println("Best day: ${steps.indexOf(steps.max()) + 1}") // 5
}