CSc 404 Assignment 4

Run Away! Run Away!

Assigned
Due

Mar 6
45 pts
Mar 22
Add a method each_run to the Ruby Array class which takes a code block expecting two arguments. It calls the code block once for each contiguous run of equal items in the array, sending the length of the run and the item repeated. (Of course, an item which is not repeated constitutes a run of length 1, with the single item “repeated” once.) Place your code in a file which can be loaded or required. To wit:
[bennet@m-mcc-csc-01456 ruby]$ irb irb(main):001:0> load "eachrun.rb" irb(main):002:0> [5,9,3,3,4,4,4,5,5,5,7,4,4,4,7,7,7,7].each_run { |n,x| irb(main):003:0> print x, " appearing ", n, " times\n" } 5 appearing 1 times 9 appearing 1 times 3 appearing 2 times 4 appearing 3 times 5 appearing 3 times 7 appearing 1 times 4 appearing 3 times 7 appearing 4 times => nil irb(main):004:0> [3,3,3,3,7].each_run { |ct,v| print v,"[",ct,"]\n" } 3[4] 7[1] => nil irb(main):005:1* ["sam","mike","mike","mike",3,9,9,"joe"].each_run { |n,x| irb(main):006:0> print n," of ",x,"\n" } 1 of sam 3 of mike 1 of 3 2 of 9 1 of joe => nil irb(main):007:0> [5,6,7].each_run { |ct,v| print v,"[",ct,"]\n" } 5[1] 6[1] 7[1] => nil irb(main):008:0> ct = 0 => 0 irb(main):009:0> tot = 0 => 0 irb(main):010:1* [5,9,3,3,4,4,4,5,5,5,7,4,4,4,7,7,7,7].each_run { |n,x| irb(main):011:1* ct += 1 irb(main):012:0> tot += n } => nil irb(main):013:0> print ct, " runs, average ", tot.to_f/ct,"\n" 8 runs, average 2.25 => nil
Make sure that your method does not modify the array that it is called on. Note that “Run” means an isolated repetition, so a separated use is a different run. See the first example. Also note that your method should not contain any printing. Most examples here print because they were sent code blocks that print, but the function does not do that itself.

Note that in many of the examples, the for_each code is mostly printing. But your code should not print anything. It should just run the code, which would do any printing.

Submission

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