PetreAdi has asked for the wisdom of the Perl Monks concerning the following question:

I have the following array:

@array = (-150, -5, 50, 0, 7, 0, 2 ,4, 3, 8, -1)

How do i a make a new array(@final_array) that contains percentages of @array

For example

@sorted_array = (-150, -5, -1, 0, 0, 2, 3, 4, 7, 8, 50) The percentage of "@sorted_array[0]" is 1%. The result will be: @final_array[0]=1 The percentage of "@sorted_array[-1]" is 100%. The result will be: @final_array[2]=100 The percentage of "@sorted_array[3]" is 75%. The result will be: @final_array[3]=75;@final_array[5]=75
What would be the best and fastest way to get the the percentage of @array

Replies are listed 'Best First'.
Re: How to convert array key values into percentages (arithmetic)
by tye (Sage) on Jan 26, 2014 at 20:54 UTC

    Making a few guesses at what you might mean:

    use List::Util qw< min max >; my @array = ( -150, -5, 50, 0, 7, 0, 2 ,4, 3, 8, -1 ); my $min = min(@array); my $max = max(@array); my @final_array = map 100*($_-$min)/($max-$min), @array; for( 0..$#array ) { printf "%5.1f%% %5d\n", $final_array[$_], $array[$_]; } __END__ 0.0% -150 72.5% -5 100.0% 50 75.0% 0 78.5% 7 75.0% 0 76.0% 2 77.0% 4 76.5% 3 79.0% 8 74.5% -1

    - tye        

      Thank you very much

Re: How to convert array key values into percentages
by ww (Archbishop) on Jan 26, 2014 at 21:01 UTC
    As AnonyMonk notes, you've left us guessing about the nature of the rule(s) by which you are planning to derive your various products, namely:
    percentage of "@sorted_array[0]" is 1%. result will be: @final_array[0]=1

    Whatever your method is, it eludes me (and given the lack of answers on a day with few new question, possibly is a mystery to others as well) especially since there's no obvious (again, 'to me') common path for transforming

    • "@sorted_array[0], -150," to 1%
            and
    • "@sorted_array[3], 0," to 75%.

    And then there is the trailing @final_array[5]=75 on line 7: Whence came that inexplicable entry? Is it a mere typo or cut'n'paste error or does it have some significance to your problem and if so, what? If it's somehow related to @sorted_array[5] (which is "2"), pray explain.

    I won't claim that explanation is good for the soul, but yours would surely be a good aid to those of interesting in helping people learn Perl... which is one key to what this site is about. See I know what I mean. Why don't you?

    Come, let us reason together: Spirit of the Monastery

    If I've misconstrued your question or the logic needed to answer it, I offer my apologies to all those electrons which were inconvenienced by the creation of this post.
Re: How to convert array key values into percentages (maths)
by Anonymous Monk on Jan 26, 2014 at 20:28 UTC

    How to convert array key values into percentages

    Maths, naturlly :)

    How does -150 translate to 1%?

    A reply falls below the community's threshold of quality. You may see it by logging in.