Jesús Gabriel y Galán
6/3/2008 6:14:00 AM
On Sat, May 31, 2008 at 2:27 AM, Matthew Moss <matthew.moss@gmail.com> wrote:
> ## Price Ranges
>
> _Quiz description by James Edward Gray II_
>
> You have a list of price ranges from different vendors like:
>
> Company A: $1,000 - $3,000
> Company B: $6,000 - $10,000
> Company C: $500 - $2,500
>
> Given such a list and the desired price range a shopper wishes to pay,
> return the companies the shopper should examine. For example, if the
> shopper's price range was:
>
> Low: $2,500
> High: $5,000
>
> the companies returned would be:
>
> Company A
> Company C
>
> The shopper should also be allowed to provide just a low or just a high
> value instead of both, should they prefer to do so.
Here's my solution. I use codeforpeople's main, so the program accepts
a --help that explains the params. I expected a file in CSV format for
the company data:
company1, low, high
company2, low, high
and the shopper's low and high are passed as options to the program:
require 'main'
require 'fastercsv'
Main {
argument('file')
option('low', 'l') {
argument_required
cast :int
default 0
}
option('high', 'g') {
argument_required
cast :int
}
def run
file = params[:file].value
low = params[:low].value
have_high = params[:high].given?
high = params[:high].value if have_high
values = []
FasterCSV.foreach file do |line|
cmp_values = [line[0]]
cmp_values << line[1].to_i
cmp_values << line[2].to_i
values << cmp_values
end
unless have_high
companies = values.select {|x| x[2] >= low}
else
companies = values.reject {|x| (x[1] > high) || (x[2] < low)}
end
companies.map! {|x| x[0]}
puts companies
end
}
For example for this company_data.csv file:
company1, 1000, 3000
company2, 6000, 10000
company3, 500, 2500
these are some runs:
$ ruby quiz164.rb company_data.csv
company1
company2
company3
$ ruby quiz164.rb company_data.csv -l 4000
company2
$ ruby quiz164.rb company_data.csv -l 4000 -g 5000
$ ruby quiz164.rb company_data.csv -g 1500
company1
company3
$ ruby quiz164.rb company_data.csv -g 750
company3
$ ruby quiz164.rb --help
NAME
quiz164.rb
SYNOPSIS
quiz164.rb file [options]+
PARAMETERS
file (1 -> file)
--low=low, -l (0 ~> int(low=0))
--high=high, -g (0 ~> int(high))
--help, -h
Thanks for the quiz.
Jesus.