Journey through 2D Arrays in Kotlin: Finding Ideal Positions for Game Pieces

Introduction

Hello, and welcome, code explorer! Today's journey takes us through the intricate paths within a 2-dimensional array, often likened to a game board. Our mission is to identify ideal spots for game piece placement. Sounds like an adventure, doesn't it? Let's embark!

Task Statement

Visualize a chessboard in the form of a 2D array, where each cell could be marked E for empty or P for a piece. Our quest involves creating a Kotlin function named findPositions(). Upon examining this 2D array, this function identifies all the spots where a new piece could be placed so that it can move to another empty cell in one move. The catch is that a piece can move only to an immediately neighboring cell directly above, below, to the left, or right, but not diagonally.

Consider this 4x4 board, for instance:

P E E P
E P E P
P E P P
P E P E

The function should output the following pairs representing positions: (0, 1), (0, 2), (1, 2), (2, 1), (3, 1). This output represents the positions where a new piece can fit perfectly and then be able to move in the next turn.

Solution Building: Step 1

Let's step right into action by starting with an empty positions list to help us log the sought positions. Understanding the dimensions of our "board" is key to defining boundaries in our exploration mission. In Kotlin, we determine the size of a 2D array using the size property.

Using a list is crucial here because we don't know beforehand how many positions will be found. A MutableList in Kotlin is dynamic and can resize itself to accommodate any number of elements, making it a perfect choice for storing an unknown number of positions.

fun findPositions(board: Array<CharArray>): MutableList<IntArray> {
    val positions = mutableListOf<IntArray>()

    val rows = board.size
    val cols = board[0].size
    // Further exploration follows

Solution Building: Step 2

With our boundary map, we begin our expedition across the board using two nested for loops to do this, traversing the entire board one cell at a time.

fun findPositions(board: Array<CharArray>): MutableList<IntArray> {
    val positions = mutableListOf<IntArray>()

    val rows = board.size
    val cols = board[0].size

    for (i in 0 until rows) {
        for (j in 0 until cols) {
            // ensuing exploration
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal