Created
November 13, 2014 21:37
-
-
Save anonymous/6ebac8aca3848ef06dd6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/ruby | |
##Assignment 3 | |
###Justin Beitz | |
def create_array(data) | |
data.chomp.split(' ').map(&:to_i) | |
end | |
def calc_average(data) | |
data = (data.reduce(:+) / data.size.to_f).round(4) | |
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 | |
s_deviation = Math.sqrt(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("%-10s %-25s %-15s %-16s\n" % [average, sd, median, data]) | |
end | |
end | |
unless ARGV.size == 2 | |
STDERR.puts "Error: Incorrect number of arguements\n\nOK. Goodbye." | |
else | |
puts "Processing: #{ARGV[0]} (input), #{ARGV[1]} (output)" | |
create_writefile(ARGV[1], "Average", "Standard Deviation", "Median", "Data\n") | |
in_file = File.new(ARGV[0], 'r') | |
in_file.each_line.with_index do |line, idx| | |
data = create_array(line) | |
average = calc_average(data) | |
s_deviation = calc_standard_deviation(data) | |
median = calc_median(data) | |
puts "Row #{idx+1}: Completed" | |
create_writefile(ARGV[1], average, s_deviation, median, data) | |
end | |
in_file.close | |
puts "\nProcess: Complete" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment