I need to identify the position inside list
of the elements in target
. Straightforward solution:
Timing[target // Map[Position[list, #] &] ;
15s
I needed a faster algorithm for my real case. Here is my try but any completely different solution is also very welcome. I assigned a score to each element, compared scores first, then look for the specific element within the candidates.
Timing[target // Map[identifyTerms];]
2.5s
But this is still not fast enough (in the real case)
Here my dummy example I made for this question:
(*list and target*)
list = {a, b, c, d, e, f, g, h} // Permutations[#, {2, 7}] & //
RandomSample // Map[Dot @@ # &];
target = {a, b, c, d, e, f} // Permutations[#, {2, 5}] & //
Map[Dot @@ # &];
(*simple target: target={a.b.c}*)
(*simple list: list={a, b.f, a.b.c}*)
(*functions*)
getScore[expr_] :=
expr /. {a -> 1, b -> 2, c -> 3, d -> 4, e -> 5, f -> 6, g -> 7,
h -> 8} /. Dot -> Times
listScores = list // getScore;
identifyTerms[expr_] := Module[{cand, p},
cand = Position[listScores, getScore[expr]] // Flatten;
p = Position[list[[cand]], expr] // Flatten;
cand[[p]]];
FirstPosition[list, #, {1}, Heads -> False] & /@ target
? Or alternativelyLookup[PositionIndex[list], target]
$\endgroup$Lookup[PositionIndex[list], target]
should do what you need, but much faster (basically instantaneously for me). Does that answer your question? $\endgroup$