Skip to content

Instantly share code, notes, and snippets.

@theevo
Created March 18, 2020 16:06
Show Gist options
  • Save theevo/39c976af8b3b3b86ec92c3e30ac3d78e to your computer and use it in GitHub Desktop.
Save theevo/39c976af8b3b3b86ec92c3e30ac3d78e to your computer and use it in GitHub Desktop.
Print a pyramid of stars given the height
import UIKit
//Write a function that accepts an Int and prints out a sideways pyramid of that height.
func pyramid(height: Int) {
for i in 1...height {
printStarline(height: i)
}
for i in stride(from: height-1, to: 0, by: -1) {
printStarline(height: i)
}
}
func printStarline(height: Int) {
var starline = ""
for _ in 1...height {
starline += "*"
}
print(starline)
}
func reversePyramid(height: Int) {
var space = height - 1
for i in 1...height {
rightAlignStarline(space: space, stars: i)
space -= 1
}
space += 2
for i in stride(from: height-1, to: 0, by: -1) {
rightAlignStarline(space: space, stars: i)
space += 1
}
}
func rightAlignStarline(space: Int, stars: Int) {
let spaces = String(repeating: " ", count: space)
let stars = String(repeating: "*", count: stars)
let starline = spaces + stars
print(starline)
}
pyramid(height: 5)
reversePyramid(height: 5)
// *
// **
// ***
// ****
// *****
// ****
// ***
// **
// *
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment