CSc 404 Assignment 3

Meet Me In The Middle

Assigned
Due

Feb 26
40 pts
Mar 7
Modify Ruby's built-in array class to contain two additional methods: mean and median. Mean returns the usual mean, the sum divided by the count. Median returns the middle value of the data in numeric order (equal numbers of data points below and above). If the length is odd, that will be the middle-sized array member. If even, it will be the mean of two middle-sized values. If the array is empty, return nil. The numeric result should be floating point, even if the members are integers. If the array contains data for which numeric computations are not allowed, results are undefined.

Place your code a text file with an .rb extension so it can be brought in with load.
bennet@desktop$ irb irb(main):001> load "mean.rb" => true irb(main):002> a = [4, 18, 3, 28, 3, 15] => [4, 18, 3, 28, 3, 15] irb(main):003> a.mean => 11.833333333333334 irb(main):004> a.median => 9.5 irb(main):005> [3, 2, 11, 5, 8].mean => 5.8 irb(main):006> [3, 2, 11, 5, 8].median => 5.0 irb(main):007> [].mean => nil irb(main):008> [].median => nil irb(main):009> ["this","will","go","boom"].median mean.rb:13:in `+': String can't be coerced into Integer (TypeError) from mean.rb:13:in `sum' from mean.rb:13:in `median' from (irb):13:in `<main>' from <internal:kernel>:187:in `loop' from /usr/share/gems/gems/irb-1.13.1/exe/irb:9:in `<top (required)>' from /usr/bin/irb:25:in `load' from /usr/bin/irb:25:in `<main>' irb(main):010>

To solve this, reopen the Array class and add the the methods. Your method body can use all the existing methods of the array class. To call a method on yourself, use the object name self, which is similar to the this in Java and C++. For instance, you can subscript yourself with self[i]. For mean, of course, you add up your contents and divide by your size. For median, you need to make a sorted version of yourself, and find the middle, or middle two values. Array has a sort method. Make sure your sorted data is only a local copy; don't sort yourself. That's not part of the semantics of median.

Make use of Ruby's existing methods. This problem can be solved this without having to write any loops.

Submission

When your function works, is nicely formatted and documents, submit it using this form.