Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,236 questions

56,139 answers

573 users

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 Jul 13 by avibootz
...