2016-05-04 8 views
-3

私は素早く動くことができます。このパズルを解決するために探している...誰かが私は別の文字列に渡すために、古いスタイルのindexOfパラメータを使用する方法を教えてくれますか?SwiftでStringを検索する方法2

Can anybody solve this?

+0

「質問そのもの」とは*テキスト*という意味で、索引付けして検索することはできません。再*。 – Matt

答えて

1

あなたは、文字列の文字をチェックする必要があります。このように:

str.characters.indexOf("a") 

これは文字列の文字「a」のインデックスを返します。

0

パート1:

hash機能:

func hash(s: String) -> Int { 
    let letters = "acdegilmnoprstuw" 
    return (s.characters.startIndex..<s.characters.endIndex).reduce(7) { (h, currentIndex) -> Int in 
    let codeUnit = s.characters[currentIndex] 
    let startIndex = letters.characters.startIndex 
    let endIndex = letters.characters.indexOf(codeUnit)! 
    let index = startIndex.distanceTo(endIndex) 
    return h * 37 + index 
    } 
} 

let sevenLetter = hash("leepadg") 
print(sevenLetter) // prints 680131659347 

パート2:

// based on https://blog.hjm.im/hashing-puzzle/ 
func reverseHash(hash: Int, allowedCharacters: [Character]) -> String { 
    var hash = hash 
    var indices = [Int: Int]() 
    var i = 0 
    while hash > 37 { 
    indices[i] = hash % 37 
    hash = hash/37 
    i += 1 
    } 
    return (indices.count - 1).stride(through: 0, by: -1).reduce("") { 
    $0 + String(allowedCharacters[indices[$1]!]) 
    } 
} 

let chars: [Character] = ["a", "c", "d", "e", "g", "i", "l", "m", "n", "o", "p", "r", "s", "t", "u", "w"] 
print(reverseHash(680131659347, allowedCharacters: chars)) // prints "leepadg" 

私は右でハッシュを交換する読者への課題として残しておきます1つ:

関連する問題