DEV Community

Discussion on: Daily Challenge #52 - Building a Pyramid

Collapse
 
dak425 profile image
Donald Feury • Edited

I have no Go pun this time. Sorry, I need coffee for that.

pyramid.go

package pyramid

// Pyramid creates a text pyramid of the given height
func Pyramid(height int) string {
    if height <= 0 {
        return ""
    }

    // Determine width of pyramid base
    width := (height * 2) - 1

    // Get middle of pyramid
    middle := int(width / 2)
    row := 0

    // Initialize a base row with only spaces
    base := make([]rune, width, width)
    for i := range base {
        base[i] = ' '
    }

    // Set the top row 'block'
    base[middle] = '*'

    var pyramid string

    // Build the pyramid starting from the top
    for row < height {
        base[middle+row] = '*'
        base[middle-row] = '*'
        pyramid += string(base) + "\n"

        row++
    }

    return pyramid
}

pyramid_test.go

package pyramid

import "testing"

func TestPyramid(t *testing.T) {
    testCases := []struct {
        description string
        input       int
        expected    string
    }{
        {
            "small pyramid",
            3,
            "  *  \n *** \n*****\n",
        },
        {
            "no height",
            0,
            "",
        },
        {
            "negative height",
            -3,
            "",
        },
        {
            "big pyramid",
            7,
            "      *      \n     ***     \n    *****    \n   *******   \n  *********  \n *********** \n*************\n",
        },
    }

    for _, test := range testCases {
        if result := Pyramid(test.input); result != test.expected {
            t.Fatalf("FAIL: %s - Pyramid(%d): %s, expected: %s", test.description, test.input, result, test.expected)
        }
        t.Logf("PASS: %s", test.description)
    }
}