Skip to content

Instantly share code, notes, and snippets.

@AdrianFerreyra
Created November 1, 2017 22:07
Show Gist options
  • Save AdrianFerreyra/7207a96863d3fe827aa6b386947a4c64 to your computer and use it in GitHub Desktop.
Save AdrianFerreyra/7207a96863d3fe827aa6b386947a4c64 to your computer and use it in GitHub Desktop.
Resolution of a Facebook iOS Code Challenge.
import Foundation
/*
A telephone keypad has letters associated with each number (e.g. 2 = abc, 3 = def).
Given a passphrase of "fb1" (e.g. one that you might use to log into a bank account),
come up with an algorithm that would assemble an array that contains all the different
possible letter combinations that, when typed into a telephone dial pad, would be equivalent
to the original passphrase. That is, "fb1" equals "321" numerically; matching equivalent
combinations include: "da1", "db1", "dc1", "ea1", "eb1", "ec1", "fa1" and "fc1".
*/
func getEquivalentStrings(for string: String) -> [String] {
let keypadDictionary = [1: ["1"],
2: ["a","b","c"],
3: ["d","e","f"],
4: ["g","h","i"],
5: ["j","k","l"],
6: ["m","n","o"],
7: ["p","q","r","s"],
8: ["t","u","v"],
9: ["w","x","y","z"],
0: ["0"]]
let characterStrings = string.map { "\($0)" } //[String]
let relatedLettersArray = characterStrings.map { characterString in Array(keypadDictionary.values).filter { $0.contains { $0 == characterString }}.first! } //[[String]]
func allCombinations(for array: [[String]]) -> [String] {
guard let firstArray = array.first else {
return [""]
}
return firstArray.flatMap { string in allCombinations(for: Array(array.dropFirst())).map { string + $0 } }
}
return allCombinations(for: relatedLettersArray).filter { $0 != string } //[String]
}
let pass = "fb1"
let equivalentPassStrings = getEquivalentStrings(for: pass)
print(equivalentPassStrings)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment