Dec 202008

Taking the code from this other blog … It’s pretty elegant Ruby!

I won’t waste your time repeating what the guy wrote in his blog – you’re welcome to go read it. I just felt that I should help spread a little this elegant implementation of the standard permutation algorithm, fixing a small bug within it in the process. If, like me, you have issues understanding how to use this, well – you have to use this function and call a block of code on it. It runs the block of code on each permutation it finds.

def permutations array
  if array.size < 2
    yield array
    array.each do |element|
      permutations( {|n| n != element}) \
      {|val| yield([element].concat val)}

  One Response to “(Lexicographic) Permutations in Ruby”

  1. […] completely clean, but it works. I had, almost a year ago (362 days ago), written a blog post about lexicographic permutations. That was about permutations of elements within one array. Someone on ruby-forum asked about […]

%d bloggers like this: