我又借用你的题目(钻石)在本地论坛发问,结果有人用Go语言写了一个:
- package main
- import (
- "fmt"
- )
- // ASCII codes for asterisk and space
- const (
- star = 42
- space = 32
- )
- func main() {
- fmt.Println("Height: 10")
- printDiamondH(10)
- }
- func printDiamondH(h int) {
- if h%2 == 0 {
- printDiamondW(h + 1)
- } else {
- printDiamondW(h)
- }
- }
- func printDiamondW(w int) {
- row := make([]byte, w)
- for i, _ := range row {
- row[i] = space
- }
- // Starting positions for the star(s)
- l, r := w/2, w/2
- if w%2 == 0 {
- l = r - 1
- } // When the width is even, the first and last row will have 2 stars instead of 1
- // Grow downward until the middle row
- for l >= 0 && r < len(row) {
- row[l], row[r] = star, star
- fmt.Println(string(row))
- row[l], row[r] = space, space // reset the array
- l--
- r++
- }
- // Manually move the pointers so the middle row isn't printed twice
- l = 1
- r = len(row) - 2
- // Shrink it back
- for l <= r {
- row[l], row[r] = star, star
- fmt.Println(string(row))
- row[l], row[r] = space, space // reset the array
- l++
- r--
- }
- }
复制代码
|