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

I have no experience with Perl. I am trying to write a Perl program that will find the median of an array after an infinite loop that ends when the user inputs a negative number. I have been trying to figure it out for days and am just lost. I can't use anything too fancy so the method an experienced user of Perl may use (being the most efficient method) is probably not right for me. Think back to the basics.

I already have my loop and the numbers are being stored correctly in the array. I even sorted the array already so that the numbers are in ascending order. I just can't wrap my head around how to tell it to look at the middle numbers without knowing beforehand how many numbers will be input into the array.

  • Comment on Finding Median of an Array after an Infinite Loop

Replies are listed 'Best First'.
Re: Finding Median of an Array after an Infinite Loop
by haukex (Archbishop) on Nov 27, 2019 at 19:21 UTC

    Could you show the code you've already got? See also How do I post a question effectively?

    I just can't wrap my head around how to tell it to look at the middle numbers without knowing beforehand how many numbers will be input into the array.

    But after the loop ends you know how many elements the array contains. Using the array in scalar context will return the number of elements it contains, and $#array will return the index of the last element (-1 if the array is empty) - see perlintro. So that should be enough info to help you find the middle element, I think?

Re: Finding Median of an Array after an Infinite Loop
by BillKSmith (Monsignor) on Nov 27, 2019 at 21:07 UTC

    Did you search ? You will find several modules that will do the computation for you. Even if you do not use them, they should be great examples.

    If you wish to do it yourself for the learning experience, sort the array. (Be sure to use numeric sort. It is not the default) If you have an odd number of elements, choose the middle one. Otherwise, take the average of the middle two elements. You will probably find the function int useful in finding the middle.

    Bill