Search code examples
summinimummaple

Sum the minimum values in Maple


I have a list A := [3,1,7,2,4,9] in Maple.

How can I get the n minimum values?

I need to sum the n minimum values, so I guess I should use something like

n := 3:
A := [3, 1, 7, 2, 4, 9]:
add( [ seq( min( A ), i=1..n) ] );

but it will just sum 1 + 1 + 1, since the minimum value is 1 every time. I need to remove the minimum value when it is first occurred.


Solution

  • A simple approach is to first sort A.

    restart;
    
    A := [3,1,7,2,4,9]:
    n := 3:
    
    B := sort(A);
                           B := [1, 2, 3, 4, 7, 9]
    
    add(B[i], i=1..n);
                                      6
    

    What do you want to happen if some value occurs more than once?

    [edited] The followup question involved how 0 may be removed from a list. Here are few ways.

    restart;
    
    A := [3,1,0,7,2,0,4,0,9]:
    
    remove(x->x=0, A);
    
                        [3, 1, 7, 2, 4, 9]
    
    remove(type, A, identical(0));
    
                        [3, 1, 7, 2, 4, 9]
    
    map(x->`if`(x=0,NULL,x), A);
    
                        [3, 1, 7, 2, 4, 9]
    

    BTW, you didn't clarify what you wanted done when non-zero values occur more than once.