8
$\begingroup$

Consider the table

Table1 = {1,1,-1,0,0,0};

How can the list combinations be obtained with positions of all non-repeating pairs of elements for which the values are either {1, -1}, or {0,0}? I.e.,

combinations={{1,3},{2,3},{4,5},{4,6},{5,6}}

In general, Table1 may consist of both even and odd numbers of elements.

This is my attempt:

PairCombinations = {{}};
PairCombinationsTemp[i_, j_] := 
 If[Table1[[i]] + Table1[[j]] == 
   0, {{i, j}}, {{}}]
Do[PairCombinations = 
  Join[PairCombinations, PairCombinationsTemp[i, j]], {i, 1, 
  Length[Table1]}, {j, i + 1, 
  Length[Table1]}]
Select[PairCombinations, UnsameQ[#, {}] &]

But it seems to me that it is not well.

$\endgroup$

5 Answers 5

8
$\begingroup$
Table1 = {1,1,-1,0,0,0};

SequencePosition[Table1, {1, ___, -1} | {0, ___, 0}, 
  Overlaps -> All] // SortBy[Last]

{{1, 3}, {2, 3}, {4, 5}, {4, 6}, {5, 6}}

$\endgroup$
7
$\begingroup$
Select[Total @ Table1[[#]] == 0 &] @ Subsets[Range @ Length @ Table1, {2}]
{{1, 3}, {2, 3}, {4, 5}, {4, 6}, {5, 6}}
Select[MatchQ[{1, -1} | {0, 0}] @ Table1[[#]] &] @
 Subsets[Range @ Length @ Table1, {2}]  (* thanks: @IAmANaif *)
{{1, 3}, {2, 3}, {4, 5}, {4, 6}, {5, 6}}
$\endgroup$
1
  • 3
    $\begingroup$ Your command structure and the actual specified test: Select[Subsets[Range[Length[Table1]], {2}], MemberQ[{{1, -1}, {0, 0}}, Table1[[#1]]] & ]. $\endgroup$
    – anon
    May 6, 2023 at 23:03
6
$\begingroup$
SubsetPosition[{1, 1, -1, 0, 0, 0}, {1, -1} | {0, 0}]

{{1, 3}, {2, 3}, {4, 5}, {4, 6}, {5, 6}}

$\endgroup$
5
$\begingroup$

According to @kglr and @Anon's answers, another variant to doing this using GroupBy and Extract is as follows:

l1 = {1, 1, -1, 0, 0, 0};

Extract[GroupBy[Subsets[Range@Length@l1, {2}],MatchQ[{1, -1}|{0, 0}]@l1[[#]] &],Key[True]]

(*{{1, 3}, {2, 3}, {4, 5}, {4, 6}, {5, 6}}*)

According to @Syed's answer, a little variant is as follows:

Catenate@(SubsetPosition[l1, #] & /@ {{1, -1}, {0, 0}})

(*{{1, 3}, {2, 3}, {4, 5}, {4, 6}, {5, 6}}*)
$\endgroup$
4
$\begingroup$
list = {1, 1, -1, 0, 0, 0};

p = {{1, -1}, {0, 0}};

A variant of E. Chan-López answer using MapApply (new in 13.1) and Splice (new in 12.1)

MapApply[Splice @ SubsetPosition[list, #] &, List /@ p]

{{1, 3}, {2, 3}, {4, 5}, {4, 6}, {5, 6}}

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.