Skip to content

Instantly share code, notes, and snippets.

@isaksky
Created November 28, 2011 05:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaksky/1399260 to your computer and use it in GitHub Desktop.
Save isaksky/1399260 to your computer and use it in GitHub Desktop.
Ruby: All letter combinations of length n
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"]
@jimpo
Copy link

jimpo commented Oct 2, 2012

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