Friday, August 15, 2014

Creating combinations

I've been looking through some of my old NetLogo code (perhaps, feeling nostalgic) and I've discovered a method I wrote some time ago in order to create combinations of variable names. For example, using a string 'abc' one can create the following combinations: a, b, c, ab, ac, bc, abc.

For practice, I re-wrote this method in Ruby. The implementation is both cases is the same (iterating over an array using a nested loop), but it is interesting to compare the grammar of two languages. For example, NetLogo requires initializing an empty array prior to performing any further actions. It also has an interesting way of adding an element to an array (line 10). I also love the use of [?], which refers to the input in the task ordered by number . 

NetLogo:

to-report comparison [strings]
  let results []
  foreach n-values length strings [?]
  [  
    let current item ? strings    
    foreach n-values length results [?]
    [
      let next item ? results
      let combo sentence next current      
      set results lput combo results       
    ]     
    let combo []
    set combo lput current combo
    set results lput combo results
  ]
  report results
end


Ruby:

def combinatations_iterative(str)
    results = []
    (0...str.length).each do |i|
        (0...results.length).each do |j|
            results << results[j] + str[i]
        end
        results << str[i]
    end
    return results
end

No comments :

Post a Comment