recursion - Generating unique sorted partitions in Ruby -


i'm trying generate set of sequences shown below, not in particularly order, here shown descending sequence. note each sequence descends i'm interested in combinations, not permutations. i'd store each sequence array..or set of sequences array of arrays more preferably, first things first.

6                    5   1                4   2                4   1   1            3   3                3   2   1            3   1   1   1        2   2   2            2   2   1   1        2   1   1   1   1    1   1   1   1   1   1 

right focusing on generating these sets , i'm trying recursively. essentially..these sequences of numbers when combines give total..in case 6. notice how when first number 3, set of numbers follows set of sequences gives total of 3. in other words 6(target total) - 3 (first number) = 3 (set of sequences give total of 3). thus, should able recursively.

i tried code follows (and yes, first language , yes, i've been studying week i'm sure screwed up) far no luck. think if can core of recursion working , put values of objects screen can trace line line, think can move ahead, between logic , syntax, i'm @ stand still.

my logic is:

  • define method passes 'count' representing total being targeted.
  • create array going hold given sequence of values
  • create index represents position in array (ignoring 0 position).
  • define 'delta' , initialize value of 'count' , have represent remaining target sum of rest of array. (since there nothing in array initially, delta same count.)

then, cycle through possibilities next(first) value of sequence starting 1 , ending, obviously, maximum possible, value of 'count' itself. determine new delta each value in cycle.

if delta 0, done otherwise determine new sequence give new delta. need append new sequence current sequence well.

i=0      def seq(count)         cvc=array.new  # array hold number values         i=i+1  # position index array         puts 'i ' + i.to_s         delta=count          puts ' delta ' + delta.to_s          value in 1..delta  # value represents number value                 cvc[i]=value                 puts 'cvc[i] ' + cvc[i].to_s                 delta = delta-cvc.sum                 puts 'new delta '+ delta.to_s             if delta >1  count=delta                     seq(count)             end         end     end 

here's solution:

def expand(n, max = n)   return [[]] if n == 0   [max, n].min.downto(1).flat_map |i|     expand(n-i, i).map{|rest| [i, *rest]}   end end  expand(6) # => [[6], [5, 1], [4, 2], [4, 1, 1], [3, 3], [3, 2, 1], [3, 1, 1, 1], [2, 2, 2], [2, 2, 1, 1], [2, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1]]  

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -