Skip to content

Instantly share code, notes, and snippets.

@unixzii
Created June 19, 2016 06:33
Show Gist options
  • Save unixzii/4ad463fc232cb678dbb182f0d64bc5c7 to your computer and use it in GitHub Desktop.
Save unixzii/4ad463fc232cb678dbb182f0d64bc5c7 to your computer and use it in GitHub Desktop.
A simple solution for an interview question.
//: Playground - noun: a place where people can play
import Cocoa
import CoreGraphics
//: Sample input: `100, 100, 200, 200, 300, 300`
let inputFilepath = "/Users/unixzii/Desktop/test.csv"
let outputFilepath = "/Users/unixzii/Desktop/test.png"
func pointsFromSequence(sequence: String) -> [CGPoint]? {
var points = [CGPoint]()
let numbers = sequence.characters.split(",").map { subSequence -> Double in
let formattedSubSequence = String(subSequence).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
return Double(formattedSubSequence) ?? 0
}
if (numbers.count % 2 == 0) {
for i in 0..<Int(numbers.count / 2) {
let x = CGFloat(numbers[i * 2])
let y = CGFloat(numbers[i * 2 + 1])
points.append(CGPoint(x: x, y: y))
}
} else {
return nil
}
return points
}
func cgContextForBitmapWithSize(size: CGSize) -> CGContext? {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGImageAlphaInfo.PremultipliedLast.rawValue // FIXME: other flags may lead to undefined behaviors.
return CGBitmapContextCreate(nil, Int(size.width), Int(size.height), 8, Int(size.width) * 4, colorSpace, bitmapInfo)
}
func main() {
guard let fileContent = try? String(contentsOfFile: inputFilepath, encoding: NSUTF8StringEncoding) else {
fatalError("Cannot open file.")
}
guard let points = pointsFromSequence(fileContent) else {
fatalError("Invalid input.")
}
// Begin drawing the bitmap.
let size = CGSize(width: 600, height: 600)
let context = cgContextForBitmapWithSize(size)
CGContextSetFillColorWithColor(context, NSColor.whiteColor().CGColor)
CGContextFillRect(context, CGRect(origin: CGPointZero, size: size))
points.forEach { point in
CGContextSetFillColorWithColor(context, NSColor.redColor().CGColor)
CGContextBeginPath(context)
CGContextAddPath(context, CGPathCreateWithEllipseInRect(CGRect(origin: point, size: CGSize(width: 10, height: 10)), nil))
CGContextFillPath(context)
}
// Finally, create and save the bitmap.
if let cgImage = CGBitmapContextCreateImage(context) {
let image = NSImage(CGImage: cgImage, size: size)
image.lockFocus()
let imageRep = NSBitmapImageRep(focusedViewRect: NSRect(origin: CGPointZero, size: size))
image.unlockFocus()
imageRep?.representationUsingType(.NSPNGFileType, properties: [:])?.writeToFile(outputFilepath, atomically: true)
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment