Last active
December 25, 2017 01:57
-
-
Save TerryCK/828e8813c44e2f95510443fa0ca69ade to your computer and use it in GitHub Desktop.
ChristmasTree.swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension BinaryInteger { | |
func printPyramid() { | |
guard self > 0 else { return } | |
for i in 0...up { | |
// let offset = i <= 9 ? "0" : "" | |
let spaceStr = Array(repeating: " ", count: up - i).joined() | |
let numsStr = Array(0...i).toString | |
// let numsStr = Array(repeating: "\(offset)\(i.specStringInternal)", count: i).joined() | |
print(spaceStr + numsStr) | |
} | |
} | |
} | |
extension Collection where Element: BinaryInteger { | |
var toString: String { | |
return self.map { "\($0) " }.joined() | |
} | |
} | |
extension BinaryInteger { | |
private var up: Int { return Int(self) } | |
private var powerOfTen: Int { return "\(self)".count - 1 } | |
private var toInt: Int { return Int(self) } | |
private var specStringInternal: String { | |
return "\(self) " + Array(repeating: " ", count: (up - self.toInt).powerOfTen).joined() | |
} | |
} | |
//: ## Usage | |
30.printPyramid() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment