# Identifying transitions in an array

I have two arrays of elements. The second array is generated by the transfer of one or more element to another position. I want to know which element is transferred to which position. Following is the simple example

A1 = {a, a, a, a, a, a};
A2 = {2a, 0, 2a, 0, a, a};


In this example the o/p I am looking for is {2->1 and 4->3}. How to achieve this ? Also, I want to have preference order in transitions. For example above example could also give {2->3, 4-> 1}. But I want to put conditions suggesting some transitions are less likely than others. So in above case, 2-> 3 is less probable than 2-> 1. so the o/p should be {2->1 and 4->3}.

Will be thankful for any suggestion.

This works for the simple example in OP:

Rule @@@ Transpose[PositionIndex[A2] /@ {0, 2 a}]


{2 -> 1, 4 -> 3}

A generalization for cases where A1 is a constant array:

ClearAll[posMap]
posMap = Module[{pos1 = Flatten[Position[#, 0]],
pos2 = Flatten @ MapIndexed[ConstantArray[#2[[1]], #] &,
Ramp[Coefficient[#, Variables[#][[1]]] - 1]]},


Examples:

posMap[A2]


{2 -> 1, 4 -> 3}

posMap[{3 a, 0, a, 0, a, a}]


{2 -> 1, 4 -> 1}

posMap[{3 a, 0, 0, a, 0, 2 a, a}]


{2 -> 1, 3 -> 1, 5 -> 6}

• Thanks. It works, but I how to make it more general. For example if A2 = {3a, 0, 0, a, a, a}. It should give {2-> 1, 3-> 1} – user49535 Dec 18 '19 at 7:12
• @user49535, please see the update. – kglr Dec 18 '19 at 7:42
• Thanks, it is working. A confession - After spending more than two hours, I am still not able to understand how it is working. Specially the part # /.{k_Integer x_ :> ConstantArray[#2[[1]], k - 1], _ -> Nothing} It is very naive, but can you please tell what this step is doing ! I tried to run this part with a separate array but no clue what is going on. I understand that k_Integer restricts the values of k to integers but what does "k_Integer x_" mean ? Could not find anything similar anywhere else also! Thanks – user49535 Dec 18 '19 at 11:17
• @user49535, k_Integer x_ is a pattern that matches 2a, 5 b, 10 xxx etc. The replacement rule works as follows: If, say, 4a appears in the 2nd position of input list, it is replaced with {2,2,2} if it appears in the 5th position it is replaced with {5,5,5}; and element that does not match the pattern is removed (this is the _ -> Nothing part). – kglr Dec 18 '19 at 11:32
• Two points to understand 1. ConstantArray[#2[[1]], k-1] is generating an array of k-1 elements with each element being same as first element of A2, which is 2a – user49535 Dec 18 '19 at 11:56