Saturday, May 16, 2015

make a love/ransom note from magazine(s)

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

// 1+ magazines
(ransom, magazines):
    wordcountmap = (ransom)
    if wordcountmap.keys.count() == 0:
        return true
    for magazine in magazines:
        for word in magazine:
            if wordcountmap.has(word):
                if --wordcountmap[word] == 0:
                    wordcountmap.removekey(word)
                    if wordcountmap.keys.count() == 0:
                        break
        if wordcountmap.keys.count() == 0:
            break
    return wordcountmap.keys.count() == 0

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

[Hat tip to GL]

No comments:

Post a Comment