Below are two slightly different methods for listing all lexicographic permutations of N objects. I can't understand why the first method works fine for smallish N, but fails above a certain limit and results in 'stack overflow'. The second method; however, works just fine up to my tested limit of 10**6. Thanks in advance for your help and insight!
$count = 0
$permutations = []
  def perms(array)  
     $permutations = array
     $count += 1
     if array.length <= 1
        return $permuations
     end
     i = (array.length - 2)
     until array[i] < array[i+1]
        i -= 1    
     end
     if i < 0
        return $permutations
     end
     j = (array.length - 1)
     until array[j] > array[i]
        j -= 1
     end
     array[i], array[j] = array[j], array[i]
     i += 1
     j = (array.length - 1)
     until j < i
        array[i], array[j] = array[j], array[i]
        i += 1
        j -= 1
     end
     while $count <= (10**6)-2
        perms(array)
     end
  end
  perms([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
  print $permutations
And here's the second method...
perm_limit = (10**6)
$count = 1 
def perms(array)
   if array.length <= 1
      return false
   end
   i = (array.length - 2)
   until array[i] < array[i+1]
      i = (i - 1)
   end
   if i < 0
      return false
   end
   j = (array.length - 1)
   until array[j] > array[i]
      j = (j - 1)
   end
   array[i], array[j] = array[j], array[i]
   i = (i + 1)
   j = (array.length - 1) 
   until j < i
      array[i], array[j] = array[j], array[i]
      i = (i + 1)
      j = (j - 1)
   end
   $count += 1 
   return true
end
array = [0,1,2,3,4,5,6,7,8,9]
while perms(array) == true
   if $count == perm_limit
      print array
   end
end    
Again, thanks.
 
     
    