2
$\begingroup$

This might be a basic question, but it has me stumped. I have two arrays, and I wish to output the uniques of the first and sum of the respective components of the second

Input

Xin = {{0, 0}, {1, 1}, {1, 0}, {1, 1}, {0, 1}, {1, 1}, {1, 1}, {1, 1}};
Yin = {n[1], n[2], n[3], n[4], n[5], n[6], n[7], n[8]}

Output:

Xout = {{0, 0}, {1, 1}, {1, 0}, {0, 1}}
Yout = {n[1], n[2] + n[4] + n[6] + n[7] + n[8], n[3], n[5]}

I know Xout=DeleteDuplicates[Xin], but can't figure out how to determine Yout (for general Xin and Yin)

$\endgroup$

2 Answers 2

3
$\begingroup$

You can use Merge:

Values @ Merge[Total] @ Thread[Xin -> Yin]

{n[1], n[2] + n[4] + n[6] + n[7] + n[8], n[3], n[5]}

Alternatively, you can use GroupBy:

Values @ GroupBy[Thread[{Xin, Yin}], First -> Last, Total]

{n[1], n[2] + n[4] + n[6] + n[7] + n[8], n[3], n[5]}

Further alternatives:

Map[Total[Yin[[#]]] &] @ Values @ PositionIndex[Xin]

{n[1], n[2] + n[4] + n[6] + n[7] + n[8], n[3], n[5]}

or

Values @ Map[Total[Yin[[#]]] &] @ PositionIndex[Xin]

{n[1], n[2] + n[4] + n[6] + n[7] + n[8], n[3], n[5]}

$\endgroup$
1
$\begingroup$

The resource function "GroupByList" seems well suited for this problem:

ResourceFunction["GroupByList"][Yin, Xin, Total]
Values @ %

<|{0, 0} -> n[1], {1, 1} -> n[2] + n[4] + n[6] + n[7] + n[8], {1, 0} -> n[3], {0, 1} -> n[5]|>

{n[1], n[2] + n[4] + n[6] + n[7] + n[8], n[3], n[5]}

$\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.