My problem is the following:
Consider a list of elements. To better understanding my following explanations, I would take this example:
ListA = {{a, b, c}, {d, e, f}, {g, h, i}};
ListB = {{{a, b}, {c}}, {{d, e, f}}, {{g}, {h, i}}};
Whatever the used list, I want to take an element only from the position of the previous.
To illustrate (for ListA):
An other program give me the position {1,3} which means the element c
in ListA
(ListA[[1,3]]
). So I would take the element d
(ListA[[2,1]]
).
I sketched a procedure:
step1
pos1 = {1, 3};
ListA[[ pos1[[1]] ]][[ pos1[[2]] ]]; (* c *)
step2
Listofposition =
Flatten[
Table[
{i, j},
{i, 1, Length@ListA, 1},
{j, 1, Length@ListA[[i]], 1}
],
1
];
step3
interpos1 = Position[Listofposition, {1, 3}] + 1
step4
pos2 = Flatten[Listofposition[ [interpos1[[1]] ]], 1]
final step
ListA[[ pos2[[1]] ]][[ pos2[[2]] ]] (* d *)
We can not really say that this solution is elegant. Do you have any other solution?
Knowing that most of the lists that I have to deal with have irregular dimensions as ListB. And this is, I think, the main difficulty.
Edit
Firstly thank you for your fast answer. I wrote some code from it.
(With using Block to improve performance)
Methode n°1 (Karsten 7 and Mr.Wizard) :
Index[x_] := Position[x, _, {Depth[x] - 1}, Heads -> False];
NextE1[x_, y_] := x[[Sequence @@
Index[x][[Sequence @@ Flatten[Position[Index[x], y] + 1]]]]];
TheNextE1[x_, y_] :=
Block[
{step1, Res},
step1 = Index[x];
Res = x[[Sequence @@
step1[[Sequence @@ Flatten[Position[step1, y] + 1]]]]]
];
Method n°2 (Mr.Wizard) :
Index[x_] := Position[x, _, {Depth[x] - 1}, Heads -> False];
Lookup[x_] := Dispatch@Rule @@@ Partition[Index[x], 2, 1, 1, "EOF"];
NextP2[x_, y_] := y /. Lookup[x]
NextE2[x_, y_] := x[[ Sequence @@ NextP2[x, y] ]];
TheNextE2[x_, y_] :=
Block[
{step1, step2, step3, Res},
step1 = Index[x];
step2 = Dispatch@Rule @@@ Partition[step1, 2, 1, 1, "EOF"];
step3 = y /. step2;
Res = x[[ Sequence @@ step3]]
];
Method n°3 (Mr.Wizard) (No modification) :
NextE3[expr_, pos_] :=
Module[
{f},
f[_, pos] := f[x_, _] := Return[x, MapIndexed];
MapIndexed[f, expr, {Length@pos}]
];
NextP3[expr_, pos_] :=
Module[
{f},
f[_, pos] := f[_, p_] := Return[p, MapIndexed];
MapIndexed[f, expr, {Length@pos}]
];
Method n°4 (Algohi) :
Index2[x_] := Cases[MapIndexed[f, x, {-1}], f[y__] :> {y}, {0, -1}]
NextP4[x_, y_] := Last@Index2[x][[Position[Index2[x], First@Cases[Index2[x], {_, y}]]
[[1, 1]] + 1]] ;
NextE4[x_, y_] := x[[ Sequence @@ NextP4[x, y] ]];
TheNextE4[x_, y_] :=
Block[
{step1, step2, Res},
step1 = Index2[x];
step2 = Last@step1[[Position[step1, First@Cases[ step1, {_, y}]][[1, 1]] + 1]];
Res = x[[ Sequence @@ step2]]
];
Performance
NextE3 > TheNextE1 > TheNextE2 > TheNextE4