Saturday, May 16, 2015

make a love/ransom note from magazine(s)

Using word->count map for ransom.
// 1 magazine
(ransom, magazine):
    ransomMap = (ransom)
    if ransomMap.keys.count() == 0:
        return true
    for word in magazine:
        if ransomMap.hasKey(word):
            if --ransomMap[word] == 0:
                ransomMap.removekey(word)
                if ransomMap.keys.count() == 0:
                    break
    return ransomMap.keys.count() == 0

// 1+ magazines
(ransom, magazines):
    // null checks
    ransomMap = (ransom)
    if ransomMap.keys.count() == 0:
        return true
    for magazine in magazines:
        if (ransomMap, magazine):
            break
    return ransomMap.keys.count() == 0

(ransom):
    wordcountmap = new
    for word in ransom:
        if wordcountmap.hasKey(word):
            wordcountmap[word]++
        else:
            wordcountmap[word] = 1
    return wordcountmap

[Hat tip to GL]

No comments:

Post a Comment