How to create an alphabet rangoli (geometric and character pattern) of size N in Kotlin

1 Answer

0 votes
/*
    Alphabet Rangoli Generator in Kotlin

    This program constructs a geometric alphabet pattern of size N.
    It uses small helper functions, clear logic, and Kotlin's built‑in
    collection operations to keep the implementation concise and efficient.
*/

fun main() {
    val n = 5
    println(makeRangoli(n))
}

/*
    Builds the entire rangoli as a multi-line string.
    The pattern is symmetric vertically, so we iterate from -(n-1) to +(n-1).
*/
fun makeRangoli(n: Int): String {
    if (n <= 0) return ""

    val totalWidth = 4 * n - 3   // Width formula identical to the reference implementation

    // Build each row and join them with newline characters
    return (-(n - 1)..(n - 1))
        .joinToString("\n") { offset ->
            buildRow(n, kotlin.math.abs(offset), totalWidth)
        }
}

/*
    Builds a single row of the rangoli.

    currentDist = distance from the center row.
    totalWidth  = final width after padding with hyphens.
*/
fun buildRow(n: Int, currentDist: Int, totalWidth: Int): String {

    // Number of descending characters (e.g., e d c ...)
    val count = n - currentDist

    // Descending characters: e d c b a (for n=5)
    val descending = (0 until count).map { j ->
        ('a' + (n - 1 - j))
    }

    // Ascending characters: b c d e (excluding the center)
    val ascending = (0 until count - 1).map { j ->
        ('a' + (n - 1 - j))
    }.reversed()

    // Combine both sides and insert hyphens
    val row = (descending + ascending).joinToString("-")

    // Compute padding to center the row
    val padding = (totalWidth - row.length) / 2
    val hyphens = "-".repeat(padding)

    return hyphens + row + hyphens
}



/*
run:

--------e--------
------e-d-e------
----e-d-c-d-e----
--e-d-c-b-c-d-e--
e-d-c-b-a-b-c-d-e
--e-d-c-b-c-d-e--
----e-d-c-d-e----
------e-d-e------
--------e--------

*/

 



answered 1 day ago by avibootz
...