ruby - Generate all way of arranging a given number of elements -


i generate possible way of arranging of number of elements number_of_elements. now, want print every possibility possibility upto.

edit: number_of_elements 3, want possible ways of arranging 0, 1 , 2. a number can appear 0 or many times, , order important. 0 != 00 != 01 != 10 != 11.

for example, all_combinations(3, 14) should print:

0 1 2 00 01 02 10 11 12 20 21 22 000 # updated. put 100 here mistake. 001 ... 

i tried this:

def all_combinations(number_of_elements, upto)   0.upto upto |n|     puts n.to_s(number_of_elements)   end end  all_combinations(3, 10) 

my idea integers, convert them base number_of_elements , interpret number possibilities. works, except missing elements.

(this output code above) :

0 1 2    # 00 missing    # 01 missing    # 02 missing 10 11 12 20 21 22    # 0.. elements missing 100 101 ... 

any idea or other simple method those?

confer this question. following slight modification of answer there.

class numeric   def sequence b     s, q = "", self     (q, r = (q - 1).divmod(b)) && s.prepend(r.to_s) until q.zero?     s   end end  def foo(number_of_elements, upto)   1.upto upto |n|     puts n.sequence(number_of_elements)   end end  foo(3, 14) 

result:

0 1 2 00 01 02 10 11 12 20 21 22 000 001 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -