Skip to content

Instantly share code, notes, and snippets.

@possen
Last active May 17, 2020 06:22
Show Gist options
  • Save possen/c2951816131463b5de83 to your computer and use it in GitHub Desktop.
Save possen/c2951816131463b5de83 to your computer and use it in GitHub Desktop.
takes a list of anagrams and outputs the words in the same order as they appear in original string. Also outputs all the matched words after that in the order they appear after that.
//
// Anagram finder.
//
// Description: takes a list of anagrams and outputs the words in the same order as they appear in original string.
// Also outputs all the matched words after that in the order they appear after that.
//
// Language: Swift 5
// Author: Paul Ossenbruggen
// Date: Dec 4, 2015
//
import Foundation
func printAnagrams(input: [String]) {
var sortedWordIndexes: [String: [Int]] = [:]
for (index, string) in input.enumerated() {
let key = String(string.sorted())
if var indexes = sortedWordIndexes[key] {
indexes += [index]
sortedWordIndexes[key] = indexes
} else {
let indexes = [index]
sortedWordIndexes[key] = indexes
}
}
for string in input {
let key = String(string.sorted())
if let indexes = sortedWordIndexes[key] {
let row = indexes.reduce("") {$0 + input[$1] + " "}
print(row)
sortedWordIndexes[key] = nil
}
}
}
printAnagrams(input: "raps lame male rasp spar naps pans span meal snap".split { $0 == " " } .map{String($0)})
printAnagrams(input: ["east","opts", "eats", "sate", "post","pots", "seat","stop", "tops", "teas"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment