As an assignment I need to re-implement Position
. I've managed to do this except for one small thing, the resulting list is not in the current format. The following piece of code is what I have so far.
findPosition[lst_, x_] :=
Module[{output = {}, index = 1},
For[index = 1, index <= Length[lst], index++,
If[lst[[index]] == x,
AppendTo[output, {index}],
False,
If[MemberQ[lst[[index]], x],
AppendTo[output, Map[{index, #} &, findPosition[lst[[index]], x]]];
False
]; (* If *)
] (* If *)
]; (* For *)
Return[output]
] (* Module *)
This gives the following output:
findPosition[{1, 2, {3, 2, 1}, {1, {4, 2, 1}, 2, {2, 6}}, {2, 6}}, 2]
{{2}, {{3, {2}}}, {{4, {{2, {2}}}}, {4, {3}}, {4, {{4, {1}}}}}, {{5, {1}}}}
While the original gives:
Position[{1, 2, {3, 2, 1}, {1, {4, 2, 1}, 2, {2, 6}}, {2, 6}}, 2]
{{2}, {3, 2}, {4, 2, 2}, {4, 3}, {4, 4, 1}, {5, 1}}
Am I doing something wrong or is there a way to make my result match the one from the original?
I've tried things using Flatten
, but it's hard to control what is flattened and what is not. The closest I've come to is {{2}, {{3, 2}}, {{4, 2, 2}, {4, 3}, {4, 4, 1}}, {{5, 1}}}
using
AppendTo[output, Map[Flatten[{index, #}] &, FindPosition[lst[[index]], x]]];
findPosition[lst_, x_]
in terms offindPosition[Most[lst], x]
andfindPosition[Rest[lst], x]
. $\endgroup$