[[+content_image]]
A
A
Alexander Wolf2016-01-28 14:04:35
JavaScript
Alexander Wolf, 2016-01-28 14:04:35

How to quickly select all combinations from an array (combinatorics)?

Good afternoon! standard task. There is an array [1,2,3] , there is n = 2 . You need to select all combinations from the array by n. That is, they should get: [[1,2], [1,3], [2, 3]] .
You can, of course, loop in a loop, but as the array size and n increase, the calculations will take too long due to the large number (> 66%) of eliminating unnecessary combinations.
So the question is how to implement it correctly?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
Alexander Ruchkin, 2016-01-28
@mannaro

> [(i, j) for i in range(1, 4) for j in range(i + 1, 4)]
[(1, 2), (1, 3), (2, 3)]

More general code, but in Haskell.
The idea is this:
For each element of the list, we get n-1 combinations of all that come after it, and add the element itself.
comb ∷ Int → [a] → [[a]]
comb 0 _ = [[]] -- из нуля элементов можно составить только пустой список
comb n [] = [] -- из пустого списка нельзя составить ничего
comb n lst = do -- списочная монада, работает как вложенные for
  -- tails для [1,2,3] вернёт [[1,2,3], [2,3], [3], []], т.е. все возможные хвосты
  -- мы перебираем все хвосты, кроме последнего пустого
  -- и дербаним его на голову l и остаток ls
  (l:ls) ← filter (not ∘ null) $ tails lst
  -- перебираем сочетания из n - 1 элементов от ls
  ls' ← comb (n - 1) ls
  -- и присобачиваем l к каждому
  return (l:ls')

R
Roman Kitaev, 2016-01-28
@deliro

Stop screwing around here.

>>> from itertools import combinations
>>> combinations([1, 2, 3], 2)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question