Advertisement
Guest User

Untitled

a guest
Nov 9th, 2014
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. ##Assignment 3
  3. ###Justin Beitz
  4.  
  5. def create_array(data)
  6. data.chomp.split(' ').map(&:to_i) # returns array of ints
  7. end
  8.  
  9. def calc_average(data)
  10. data = (data.reduce(:+) / data.size.to_f).round(4)
  11. end
  12.  
  13. def calc_standard_deviation(data)
  14. average = data.reduce(:+) / data.size.to_f
  15. sum = data.inject(0){|accum, i| accum +(i-average)**2 }
  16. s_deviation = sum/(data.length - 1).to_f
  17. s_deviation = Math.sqrt(s_deviation).round(4)
  18. end
  19.  
  20. def calc_median(data)
  21. return nil if data.empty?
  22. data.sort!
  23. mid = (data.length-1) / 2.0
  24. (data[mid.floor] + data[mid.ceil]).fdiv(2)
  25. end
  26.  
  27. def create_writefile(file, average, sd, median, data)
  28. File.open(ARGV[1], 'a') do |file|
  29. file.write("%-10s %-25s %-15s %-16s\n" % [average, sd, median, data])
  30. end
  31. end
  32.  
  33. unless ARGV.size == 2
  34. STDERR.puts "Error: Incorrect number of arguements\n\nOK. Goodbye."
  35. else
  36. puts "Processing: " + ARGV[0] + " (input), " + ARGV[1] + " (output)"
  37. row = 0
  38. # set command line argument1 and argument2 to in_file and out_file respectivley
  39. in_file = File.new(ARGV[0], 'r')
  40. out_file = File.new(ARGV[1], 'w')
  41. # out_file.puts "Average Standard Deviation Median Data"
  42. out_file.puts " "
  43. in_file.each_line do |line|
  44. row = row + 1
  45. data = create_array(line)
  46. average = calc_average(data)
  47. s_deviation = calc_standard_deviation(data)
  48. median = calc_median(data)
  49.  
  50. create_writefile(ARGV[1], average, s_deviation, median, data)
  51. end
  52. puts "Processing: Complete"
  53. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement