Created
March 7, 2016 16:15
-
-
Save eyeplum/64979c2297907c1cae7f to your computer and use it in GitHub Desktop.
Simple command to draw a rect.
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
/* | |
Tested on OS X 10.11 and Ubuntu 15.10 | |
Exmaple: `$ drawRect 4 3` should output this: | |
┌──┐ | |
│ │ | |
└──┘ | |
*/ | |
// MARK: - Data Structures | |
struct Size { | |
static let zero = Size(width: 0, height: 0) | |
let width: Int | |
let height: Int | |
} | |
struct Rect { | |
static let space = " " | |
static let newline = "\n" | |
static let corners = Corners() | |
static let lines = Lines() | |
struct Corners { | |
let topLeft = "┌" | |
let topRight = "┐" | |
let bottomLeft = "└" | |
let bottomRight = "┘" | |
} | |
struct Lines { | |
let vertical = "│" | |
let horizontal = "─" | |
} | |
} | |
// MARK: - Argument Parsing | |
func processInput() -> Size? { | |
let argc = Process.argc | |
let args = Process.arguments | |
guard argc == 3, | |
let width = Int(args[1]), | |
let height = Int(args[2]) else { | |
return nil | |
} | |
return Size(width: width, height: height) | |
} | |
// MARK: - Output | |
func printUsage() { | |
print("Usage: drawRect width height") | |
} | |
func drawRect(size size: Size) { | |
guard size.width > 1 && size.height > 1 else { | |
print(Rect.corners.topLeft + Rect.corners.topRight + Rect.newline + | |
Rect.corners.bottomLeft + Rect.corners.bottomRight) | |
return | |
} | |
var image = "" | |
for y in 0..<size.height { | |
for x in 0..<size.width { | |
if x == 0 { | |
if y == 0 { | |
image += Rect.corners.topLeft | |
} else if y == size.height - 1 { | |
image += Rect.corners.bottomLeft | |
} else { | |
image += Rect.lines.vertical | |
} | |
} else if x == size.width - 1 { | |
if y == 0 { | |
image += Rect.corners.topRight | |
} else if y == size.height - 1 { | |
image += Rect.corners.bottomRight | |
} else { | |
image += Rect.lines.vertical | |
} | |
image += Rect.newline | |
} else { | |
if y == 0 || y == size.height - 1 { | |
image += Rect.lines.horizontal | |
} else { | |
image += Rect.space | |
} | |
} | |
} | |
} | |
print(image) | |
} | |
// MARK: - Flow | |
if let size = processInput() { | |
drawRect(size: size) | |
} else { | |
printUsage() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment