SoFunction
Updated on 2025-03-04

Go language novices beginners to brush questions and print out hourglass

Question explanation

[PTA Group Programming Ladder Competition] L1-002 Print Hourglass (20 points) Go Language|Golang

This question requires you to write a program to print the given symbol into the shape of an hourglass. For example, given 17 "*", please print in the following format

*****
 ***
  *
 ***
*****

The so-called "hourglass shape" refers to the output of odd symbols per row; the centers of each row are aligned; the symbol numbers of adjacent two rows are 2; the symbol numbers are first reduced from large to small to 1, and then increased from small to large; the number of the symbols at the beginning and tail is equal.

Given any N symbols, it may not necessarily form an hourglass. It is required that the printed hourglass can use as many symbols as possible.

Input format:

The input gives 1 positive integer N (≤1000) and a symbol on a line, separated by spaces.

Output format:

First print out the largest hourglass shape composed of the given symbol, and finally output the remaining number of symbols in one line.

Enter sample:

19 *

There is no empty line at the end

Output sample:

*****
 ***
  *
 ***
*****
2

There is no empty line at the end

Ideas

Basic output. If you think this question is not friendly, you can skip it and wait and come back to understand it.

It is to find the rules and first calculate how much you need. Subtract and get the remaining amount. Then print the hourglass according to the rules, it is actually an aberration sequence~

The code is as follows

package main
import (
	"fmt"
)
func  main() {
	var n int
	var tag byte
	var sum, nextSum int
	_, _ = ("%d %c", &n, &tag)
	sum = 1
	nextSum = 1
	i := 1
	last := 0
	for true { // First calculate how many symbols you need		i += 2
		nextSum += i * 2
		if nextSum <= n {
			sum += i * 2
		} else {
			i -= 2
			last = n - sum
			break
		}
	}
	for j:=i; j>=1; j=j-2 {  // Print the upper part first		var space = (i - j) / 2
		for k:=0; k<i-space; k++ {
			if k < space {
				(" ")  // Print space first			} else {
				("%c", tag)  //Print again*			}
		}
		() // Finally remember to change the line	}
	for j:=3; j<=i; j=j+2 {
		var space = (i - j) / 2  //Print the lower part again		for k:=0; k<i-space; k++ {
			if k < space{
				(" ")  //Print again*			} else {
				("%c", tag)
			}
		}
		()
	}
	(last)
}

The above is the detailed content of the introduction to Go Novice’s introductory questions and print out hourglass. For more information about Go’s printing hourglass, please pay attention to my other related articles!