Skip to content

Instantly share code, notes, and snippets.

@hiroshi-maybe
Created August 5, 2016 06:09
Show Gist options
  • Select an option

  • Save hiroshi-maybe/215750cb8839c41e754bc044ebd6a80e to your computer and use it in GitHub Desktop.

Select an option

Save hiroshi-maybe/215750cb8839c41e754bc044ebd6a80e to your computer and use it in GitHub Desktop.
getNearbyWords.swift
//: 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