Last active
December 10, 2016 21:41
-
-
Save hebertialmeida/d447903dbfc1cd85ae5d to your computer and use it in GitHub Desktop.
Given a set of names, sort them in the following manner the next word should start with the last letter of the previous word. Swift implementation.
This file contains 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
import UIKit | |
var names = ["Luis", "Hector", "Selena", "Emmanuel", "Amish", "Rawle"] | |
var firsts = [String: String]() | |
var lasts = [String: String]() | |
var output = [String]() | |
for name in names { | |
var key = (name as NSString).substringFromIndex(name.utf16Count-1) | |
lasts[key] = name | |
key = (name as NSString).substringToIndex(1).lowercaseString | |
firsts[key] = name | |
} | |
for (key, val) in firsts { | |
if lasts[key] == nil { | |
output.append(val) | |
} | |
} | |
while output.count < names.count { | |
if output.count == 0 { | |
output.append(names[0]) | |
} | |
var last = output.last! | |
var key = (last as NSString).substringFromIndex(last.utf16Count-1) | |
output.append(firsts[key]!) | |
} | |
println(output) | |
// Returns ["Luis", "Selena", "Amish", "Hector", "Rawle", "Emmanuel"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment