Finding entry of vector in PARI/GP?

别等时光非礼了梦想. 提交于 2020-01-04 06:23:12

问题


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!


回答1:


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




回答2:


you may try:

position = select(x->x==8,a,1)[1];


来源:https://stackoverflow.com/questions/27753897/finding-entry-of-vector-in-pari-gp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!