Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- ##Assignment 3
- ###Justin Beitz
- def create_array(data)
- data.chomp.split(' ').map(&:to_i) # returns array of ints
- end
- def calc_average(data)
- data = data.reduce(:+) / data.size.to_f.round(4) # returns a float
- end
- def calc_standard_deviation(data)
- average = data.reduce(:+) / data.size.to_f
- sum = data.inject(0){|accum, i| accum +(i-average)**2 }
- s_deviation = sum/(data.length - 1).to_f.round(4)
- s_deviation = Math.sqrt(s_deviation).round(4)
- s_deviation = s_deviation.round(4)
- end
- def calc_median(data)
- return nil if data.empty?
- data.sort!
- mid = (data.length-1) / 2.0
- (data[mid.floor] + data[mid.ceil]).fdiv(2)
- end
- def create_writefile(file, average, sd, median, data)
- File.open(ARGV[1], 'a') do |file|
- file.write("%s %s %s %s\n" % [average, sd, median, data])
- end
- end
- unless ARGV.size == 2
- STDERR.puts "Error: Incorrect number of arguements\n\nOK. Goodbye."
- else
- puts "Processing: input.txt(input), output.txt (output)"
- row = 0
- # set command line argument1 and argument2 to in_file and out_file respectivley
- in_file = File.new(ARGV[0], 'r')
- out_file = File.new(ARGV[1], 'w')
- out_file.puts "Average Standard Deviation Median Data"
- out_file.puts " "
- in_file.each_line do |line|
- row = row + 1
- data = create_array(line)
- average = calc_average(data)
- s_deviation = calc_standard_deviation(data)
- median = calc_median(data)
- out_file.puts average.to_s + " " + s_deviation.to_s + " " + median.to_s + " " + line
- puts "Row " + row.to_s + ": completed"
- #create_writefile(ARGV[1], average, s_deviation, median, data)
- end
- puts "Processing: Complete"
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement