Skip to content

Instantly share code, notes, and snippets.

@JesseRhoads
Last active March 22, 2018 21:48
Show Gist options
  • Save JesseRhoads/9bf536d7280646a8439e2b7717309f01 to your computer and use it in GitHub Desktop.
Save JesseRhoads/9bf536d7280646a8439e2b7717309f01 to your computer and use it in GitHub Desktop.
Print a diamond given a user-specified odd number
// Diamond Printer
// Prompt the user for the max number of asterisks, must be Odd
// Then print a symmetrical diamond, centered.
// Jesse Rhoads jesserhoads@gmail.com
package main
import (
"fmt"
"strings"
)
var maxNumAsterisks int
// centers a string (s) to fit within given width (w)
func center(s string, w int) string {
return fmt.Sprintf("%[1]*s", -w, fmt.Sprintf("%[1]*s", (w + len(s))/2, s))
}
// Print a specific number of asterisks, centered.
// Assumes global variable maxNumAsterisks is set.
func asteriskPrint(asterisks int, maxNumAsterisks int) {
numAsterisks := strings.Repeat(string('*'), asterisks)
fmt.Println(center(numAsterisks, maxNumAsterisks))
return
}
func main() {
fmt.Println("Diamond Printer")
for {
fmt.Print("Please Enter an Odd number: ")
var n int
fmt.Scanln(&n)
if( n % 2 == 0 ) {
fmt.Println(n,"is an Even number, please try again!")
} else {
maxNumAsterisks = n
break
}
}
// We are going to print a asterisk of *'s. assumption is that we will have a
// maxNumasterisks which is ideally an odd number
// count up to the max and then back down again, centering the string.
for i := 0; i < maxNumAsterisks; i += 1 {
if i % 2 != 0 {
asteriskPrint(i, maxNumAsterisks)
}
}
// Now we do the same, counting back down. Reverse for loops and
// decrementing by 2 does not seem to work safely!
da := maxNumAsterisks
for {
// If it is an odd number, print it.
if da % 2 != 0 {
asteriskPrint(da, maxNumAsterisks)
}
da--
if da < 1 {
break
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment