Re: question on compare functions for the vecsort command

Loïc Grenié <[email protected]>
Newsgroups gmane.comp.mathematics.pari.user
Message-ID <CAMLkfFSbZmbC3-a6oZiAAL9VkKwYyJXtK9bw13PWMm7Sy+_iMA@mail.gmail.com>
On Mon 12 May, 2025, at 05:50, American Citizen wrote:

> Hello:
>
> Suppose we have a small vector composed of 4 component vectors, say
>
> V = [ [1,7,5,2], [3,7,1,4], [2,0,6,9], [8,0,5,1], etc...]
>
> What is the compare function for vecsort(V, compare_function, flag) so
> that I can
>
> 1. sort the 2nd column by ascending size, then sort the 3rd column by
> descending size?
>

V = [ [1,7,5,2], [3,7,1,4], [2,0,6,9], [8,0,5,1] ];
vcmp(a,b)=if(a[2]!=b[2],a[2]-b[2],b[3]-a[3]);
vecsort(V,vcmp)
\\ [[2, 0, 6, 9], [8, 0, 5, 1], [1, 7, 5, 2], [3, 7, 1, 4]

    I interpreted "then" as "if the 2nd components are equal, then
  consider the 3rd"

    You can inline the function as well:

vecsort(V,(a,b)->if(a[2]!=b[2],a[2]-b[2],b[3]-a[3]))
\\ [[2, 0, 6, 9], [8, 0, 5, 1], [1, 7, 5, 2], [3, 7, 1, 4]]


> 2. add the 3rd column to the 4th column, if the 2nd column > 1st column?
>

     You want to change the elements of the vector? This is not a work
  for vecsort, but for apply

apply(a->if(a[2]>a[1],a[4]+=a[3]);a,V)

  (or vecsor(V,vcmp), or you can vecsort afterwards)

       Hope this helps,

             Loïc
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.