Update:
ClearAll[addIndices, addOrderings, standardize]
Append to each entry of the input list its index and the length of its parent sublist:
addIndices[a_] := {#, #4, {#2, #3}} & @@@ Join @@
(Flatten /@ Thread[{#, Length @ #}] & /@ MapIndexed[List, a, {2}]);
Use SortBy[{First, f2, f3,...}]
to sort the annotated list using sorting functions f2
, f3
,..., that represent your rules, and add the orderings obtained to the annotated list.
In the implementation below, the sorting functions #[[2]] - #[[3, 2]] &
and -#[[2]] &
capture your rules:
addOrderings = MapIndexed[{#[[1]], #2[[1]], #[[3]]} &]@
SortBy[{First, #[[2]] - #[[3, 2]] &, -#[[2]] &}]@# &;
Compose the addOrderings
with addIndices
:
standardize = addOrderings @* addIndices;
to generate a list of triples {a, number_assigned_to_a, {row, column}}
.
Example:
standardize[A2]
{{1, 1, {5, 3}},
{1, 2, {1, 2}},
{1, 3, {4, 1}},
{1, 4, {5, 2}},
{1, 5, {3, 1}},
{2, 6, {2, 2}},
{2, 7, {3, 2}},
{2, 8, {1, 1}},
{2, 9, {2, 1}},
{2, 10, {5, 1}}}
DeleteCases[0] /@ Normal[SparseArray[#3 -> #2 & @@@ standardize[A2]]]
{{8, 2}, {9, 6}, {5, 7}, {3}, {10, 4, 1}}
SparseArray[Reverse@#3 -> # & @@@ standardize[A2]] // Reverse //
Grid[Normal[#] /. 0 -> "", Frame -> All] &
SparseArray[Reverse@#3 -> #2 & @@@ standardize[A2]] // Reverse //
Grid[Normal[#] /. 0 -> "", Frame -> All] &
Original answer:
ClearAll[f]
f = TakeList[Ordering@Ordering@Flatten@#, Length /@ #] &;
Examples:
A1 = {{1, 3, 4}, {2, 3, 5}, {1, 6}};
f @ A1
{{1, 4, 6}, {3, 5, 7}, {2, 8}}
A2 = {{2, 1}, {2, 2}, {1, 2}, {1}, {2, 1, 1}};
f @ A2
{{6, 1}, {7, 8}, {2, 9}, {3}, {10, 4, 5}}
Update:
ClearAll[pad]
pad = Reverse[Transpose[PadRight[#, Automatic, ""]]] &;
pad @ A2 // Grid[#, Frame -> All] &
If we use f
on pad @ A
non-numeric entries will be assigned numbers greater than Length@Flatten@A
, Removing non-numeric elements from f @ pad @ A
gives the desired result:
f[pad @ A2] /. x_ /; x > Length[Flatten @ A2] -> "" // Grid[#, Frame -> All] &
ClearAll[g]
g[a_] := Select[# <= Length @ Flatten @ a &] /@ Transpose @ Reverse @ f @ pad @ a
g @ A2
{{8, 2}, {9, 6}, {4, 7}, {5}, {10, 3, 1}}