Skip to content

Instantly share code, notes, and snippets.

@gmarik
Created May 13, 2012 03:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gmarik/2675199 to your computer and use it in GitHub Desktop.
Save gmarik/2675199 to your computer and use it in GitHub Desktop.
group combinations
# solution for problem 1.27 from https://sites.google.com/site/prologsite/prolog-problems/1
def gcombo(list, ns, acc, q = [], rest = list, qg = [])
if ns.sum != list.size && acc.empty?
raise ArgumentError, "Impossible to group #{list} into groups of #{ns} elements"
end
if ns.empty?
acc << qg
return
end
return if list.empty?
n,*nt = ns
h,*t = list
return if n == 0 || n > list.size
s = q + [h]
1 == n &&
gcombo(rest - s, nt, acc, [], rest - s, qg + [ s ])
gcombo(t, [n - 1] + nt, acc, s, rest, qg)
gcombo(t, ns, acc, q, rest, qg)
end
gcombo((1..5).to_a, [2,2,1], acc = [])
pp acc; ''
# =>
# [[[1, 2], [3, 4], [5]],
# [[1, 2], [3, 5], [4]],
# [[1, 2], [4, 5], [3]],
# [[1, 3], [2, 4], [5]],
# [[1, 3], [2, 5], [4]],
# [[1, 3], [4, 5], [2]],
# [[1, 4], [2, 3], [5]],
# [[1, 4], [2, 5], [3]],
# [[1, 4], [3, 5], [2]],
# [[1, 5], [2, 3], [4]],
# [[1, 5], [2, 4], [3]],
# [[1, 5], [3, 4], [2]],
# [[2, 3], [1, 4], [5]],
# [[2, 3], [1, 5], [4]],
# [[2, 3], [4, 5], [1]],
# [[2, 4], [1, 3], [5]],
# [[2, 4], [1, 5], [3]],
# [[2, 4], [3, 5], [1]],
# [[2, 5], [1, 3], [4]],
# [[2, 5], [1, 4], [3]],
# [[2, 5], [3, 4], [1]],
# [[3, 4], [1, 2], [5]],
# [[3, 4], [1, 5], [2]],
# [[3, 4], [2, 5], [1]],
# [[3, 5], [1, 2], [4]],
# [[3, 5], [1, 4], [2]],
# [[3, 5], [2, 4], [1]],
# [[4, 5], [1, 2], [3]],
# [[4, 5], [1, 3], [2]],
# [[4, 5], [2, 3], [1]]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment