Created
April 28, 2023 11:05
-
-
Save kchromik/cda156e03372c7dbdca97c169eca3676 to your computer and use it in GitHub Desktop.
Coding Interview Video
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
import Foundation | |
class RandomWordGenerator { | |
private var graph: [Character: Set<Character>] = [:] | |
private var firstLetters: Set<Character> = [] | |
private var lastLetters: Set<Character> = [] | |
func insert(words: [String]) { | |
words.forEach { word in | |
guard !word.isEmpty else { return } | |
firstLetters.insert(word.first!) | |
lastLetters.insert(word.last!) | |
word.enumerated().forEach { (index, currentChar) in | |
let nextChar = index < word.count - 1 ? word[word.index(word.startIndex, offsetBy: index + 1)] : nil | |
if graph[currentChar] == nil { | |
graph[currentChar] = Set<Character>() | |
} | |
if let nextChar = nextChar { | |
graph[currentChar]?.insert(nextChar) | |
} | |
} | |
} | |
} | |
func generateRandomWord() -> String { | |
guard var currentLetter = firstLetters.randomElement() else { return "" } | |
var randomWord: [Character] = [] | |
while true { | |
randomWord.append(currentLetter) | |
if let nextLetter = graph[currentLetter]?.randomElement() { | |
if lastLetters.contains(nextLetter) && Bool.random() { | |
randomWord.append(nextLetter) | |
return String(randomWord) | |
} else { | |
currentLetter = nextLetter | |
} | |
} else { | |
return String(randomWord) | |
} | |
} | |
} | |
} | |
let words = ["apple", "banana", "cabbage"] | |
let generator = RandomWordGenerator() | |
generator.insert(words: words) | |
let randomWord = generator.generateRandomWord() | |
print(randomWord) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment