Sum of one array compared to uniques of another

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)

2 Answers

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]}

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]}