Skip to content

Instantly share code, notes, and snippets.

@douglascodes
Last active December 15, 2015 12:39
Show Gist options
  • Save douglascodes/5261284 to your computer and use it in GitHub Desktop.
Save douglascodes/5261284 to your computer and use it in GitHub Desktop.
A controlled permutation. Cycles an array of arrays calling the proc with each possible set of the sub arrays whilst preserving the positions of the original array. Basically gets every combination of "One from column A, one from column B, ..." and so on.
a_of_a = [["Jazz", "Soul", "Rock"],["Cheeseburgers", "Hot dogs", "Milkshakes"], ["cable", "radio", "internet"]]
result = Array.new(a_of_a.length)
procky = Proc.new { |arg|
print arg.join(" and "), " are my favorite things. \n"
}
def controlled_perm(x, a_of_a, result, procky)
x += 1
if a_of_a.length == x
procky.call(result)
return
end
a_of_a[x].each { |pointer|
result[x] = pointer
controlled_perm(x, a_of_a, result, procky)
}
end
controlled_perm(-1, a_of_a, result, procky)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment