Here's a an iterator to generate combinations. iterator choose*[T](a: openarray[T], num_choose: int): seq[T] = var chosen: seq[T] i = 0 i_stack = newSeqOfCap[int](num_choose) while true: if chosen.len == num_choose: yield chosen discard chosen.pop() i = i_stack.pop() + 1 elif i != a.len: chosen.add(a[i]) i_stack.add(i) inc i elif i_stack.len > 0: discard chosen.pop() i = i_stack.pop() + 1 else: break Run
Example use: for choice in choose(@[11, 22, 33, 44, 55, 66], 3): echo choice Run Outputs: @[11, 22, 33] @[11, 22, 44] @[11, 22, 55] @[11, 22, 66] @[11, 33, 44] @[11, 33, 55] @[11, 33, 66] @[11, 44, 55] @[11, 44, 66] @[11, 55, 66] @[22, 33, 44] @[22, 33, 55] @[22, 33, 66] @[22, 44, 55] @[22, 44, 66] @[22, 55, 66] @[33, 44, 55] @[33, 44, 66] @[33, 55, 66] @[44, 55, 66] Run