Created
August 5, 2016 06:09
-
-
Save hiroshi-maybe/215750cb8839c41e754bc044ebd6a80e to your computer and use it in GitHub Desktop.
getNearbyWords.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
| //: Playground - noun: a place where people can play | |
| import UIKit | |
| // https://www.facebook.com/video.php?v=10152735777427200&set=vb.9445547199&type=2&theater | |
| var str = "Hello, playground" | |
| func getNearbyChars(ch: String) -> Set<String> { | |
| switch ch { | |
| case "g": return Set(["g","h","f"]) | |
| case "i": return Set(["i","o","k"]) | |
| default: return Set() | |
| } | |
| } | |
| func isWord(str: String) -> Bool { | |
| return ["hi", "go"].indexOf(str) != nil | |
| } | |
| func getNearbyWords(word: String) -> Set<String> { | |
| // "gi" -> [{g,h,f}, {i,o,k}] | |
| let sets = word.characters.map { getNearbyChars(String($0)) } | |
| return Set(permutation(sets).filter { isWord($0) }) | |
| } | |
| func permutation(sets: [Set<String>]) -> [String] { | |
| guard let set = sets.first else { return [""] } | |
| return set.flatMap { ch in | |
| return permutation(Array(sets[1..<sets.count])).map { ch + $0 } | |
| } | |
| } | |
| getNearbyWords("gi") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment