Created
November 28, 2011 05:44
-
-
Save isaksky/1399260 to your computer and use it in GitHub Desktop.
Ruby: All letter combinations of length n
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
LETTERS = (65..90).collect{|char_code| char_code.chr} | |
def letter_combos length, accum = nil | |
return accum if length == 0 | |
return accum || LETTERS if length == 1 | |
combos = (accum || LETTERS).product(LETTERS).inject([]) {|combos, product| | |
combos << product.first + product.last} | |
letter_combos(length - 1, combos) | |
end | |
#ex: | |
# letter_combos(2) => ["AA", "AB", "AC", ... "ZZ"] | |
# letter_combos(3) => ["AAA", "AAB", "AAC", ... "ZZZ"] |
Ruby:
def letter_combos(n)
letters = (combos = *'a'..'z')
(n-1).times do combos = letters.product(combos).map{|x| x.join} end
return combos
end
;D
Haskell?
letter_combos :: Int -> [[Char]]
letter_combos n = (iterate combos [[]]) !! n
where combos xs = [l:x | l <- ['a'..'z'], x <- xs]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hm gg ruby? Clojure: