swift 通过使用算术的基本定理,找出2个单词是否是字谜

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了swift 通过使用算术的基本定理,找出2个单词是否是字谜相关的知识,希望对你有一定的参考价值。

// SNIPPET
// Quick test inspired by @fermatslibrary's algorithm idea (https://twitter.com/fermatslibrary/status/988399621402656773) 

//: - Dictionary with a prime number assigned to each character
var primesOfChars: [String: Int] = ["a":2, "b":3, "c":5, "d":7, "e":11, "f":13, "g":17, "h":19, "i":23, "j":29, "k":31, "l":37, "m":41, "n":43, "o":47, "p":53,"q":59, "r":61, "s":67, "t":71,"u":73, "v":79, "w":83, "x":89, "y":97, "z":101]


//: - Fundamental theorem of arithmetic
func arithmetic(word: String) -> Int {
    var product = 1
    for char in word {
        product = product * primeOfChars["\(char)"]!
    }
    return product
}

//: - Compare **unique** prime products
func anagram(string1: String, string2: String) -> Bool {
    return arithmetic(word: string1.lowercased()) == arithmetic(word: string2.lowercased())
}

anagram(string1: "lukas", string2: "sulak") // true
anagram(string1: "elon", string2: "tony") // false

以上是关于swift 通过使用算术的基本定理,找出2个单词是否是字谜的主要内容,如果未能解决你的问题,请参考以下文章

基本数论定理

51nod 1189 算术基本定理/组合数学

Aladdin and the Flying Carpet (LightOJ - 1341)简单数论算术基本定理分解质因数(未完成)

小航的算法日记算术基本定理

算术基本定理

hdu4479 (数学题)(算术基本定理)