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"]
@isaksky
Copy link
Author

isaksky commented Nov 28, 2011

Hm gg ruby? Clojure:

(def letters
  (into [] (for [char-code (range 65 91)] (char char-code))))

(defn letter-combos [len]
  (map str/join (apply clojure.math/cartesian-product (repeat len letters))))

@fny
Copy link

fny commented Oct 2, 2012

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

@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