Created
October 1, 2015 13:29
-
-
Save jakubpetrik/abe85eaa1ea009fda0ab to your computer and use it in GitHub Desktop.
Ordered words in 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
/** | |
http://rosettacode.org/wiki/Ordered_words | |
Define an ordered word as a word in which the letters of the word appear in alphabetic order. Examples include 'abbey' and 'dirt'. | |
The task is to find and display all the ordered words in this dictionary that | |
have the longest word length. | |
(Examples that access the dictionary file locally assume that you have downloaded this file yourself.) | |
The display needs to be shown on this page. | |
*/ | |
import Foundation | |
guard | |
let url = NSURL(string: "http://www.puzzlers.org/pub/wordlists/unixdict.txt"), | |
let input = try? NSString(contentsOfURL: url,encoding: NSUTF8StringEncoding) as String | |
else { exit(EXIT_FAILURE) } | |
let words = input.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) | |
let group: ([Int: [String]], String) -> [Int: [String]] = { | |
var d = $0; let g = d[$1.characters.count] ?? [] | |
d[$1.characters.count] = g + [$1] | |
return d | |
} | |
let ordered: ([String], String) -> [String] = { | |
guard String($1.characters.sort()) == $1 else { return $0 } | |
return $0 + [$1] | |
} | |
let groups = words | |
.reduce([String](), combine: ordered) | |
.reduce([Int: [String]](), combine: group) | |
guard | |
let maxLength = groups.keys.maxElement(), | |
let maxLengthGroup = groups[maxLength] | |
else { exit(EXIT_FAILURE) } | |
maxLengthGroup.forEach { print($0) } | |
/** | |
outputs: | |
======== | |
abbott | |
accent | |
accept | |
access | |
accost | |
almost | |
bellow | |
billow | |
biopsy | |
chilly | |
choosy | |
choppy | |
effort | |
floppy | |
glossy | |
knotty | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment