With PARI/GP, if I have a vector with unique entries:
a = [9, 7, 3, 5, 2, 8, 1, 0, 11]
how do I get the position (index) of an entry in the vector a
?
like:
i = vectorsearch(a, 8);
a[i]
%1 = 8
Converting into a set and using setsearch
doesn't work!
Just do select((x) -> x == 8, a, 1)
where flag 1
means the "index mode". In general, your function is as shown below.
position = (elt, array) -> select((x) -> x == elt, array, 1);
Please note, despite the fact that this stuff does a lambda call per each element of the array, that is very efficient. This lead to nice run-time for small/big arrays.
To prove the efficiency, we do the simple performance tests to evaluate the position
and its DIY-competitor looking just for the position of first occurrence.
position1 = (elt, array) -> for(i = 1, #array, if(array[i] == el, return(i)));
a = vector(100, i, random(200));
{ gettime(); for(i = 1, 10^4, position(8, a)); gettime() }
{ gettime(); for(i = 1, 10^4, position1(8, a)); gettime() }
This gives 87ms and 198ms correspondingly for PARI/GP 2.7.2 running at Windows 8 64bit, Intel i7-4702MQ CPU @ 2.20GHz