Advertisement
Guest User

Untitled

a guest
Nov 9th, 2014
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 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) # returns a float
  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.round(4)
  17. s_deviation = Math.sqrt(s_deviation).round(4)
  18. s_deviation = s_deviation.round(4)
  19. end
  20.  
  21. def calc_median(data)
  22. return nil if data.empty?
  23. data.sort!
  24. mid = (data.length-1) / 2.0
  25. (data[mid.floor] + data[mid.ceil]).fdiv(2)
  26. end
  27.  
  28. def create_writefile(file, average, sd, median, data)
  29. File.open(ARGV[1], 'a') do |file|
  30. file.write("%s %s %s %s\n" % [average, sd, median, data])
  31. end
  32. end
  33.  
  34. unless ARGV.size == 2
  35. STDERR.puts "Error: Incorrect number of arguements\n\nOK. Goodbye."
  36. else
  37. puts "Processing: input.txt(input), output.txt (output)"
  38. row = 0
  39. # set command line argument1 and argument2 to in_file and out_file respectivley
  40. in_file = File.new(ARGV[0], 'r')
  41. out_file = File.new(ARGV[1], 'w')
  42. out_file.puts "Average Standard Deviation Median Data"
  43. out_file.puts " "
  44. in_file.each_line do |line|
  45. row = row + 1
  46. data = create_array(line)
  47. average = calc_average(data)
  48. s_deviation = calc_standard_deviation(data)
  49. median = calc_median(data)
  50.  
  51. out_file.puts average.to_s + " " + s_deviation.to_s + " " + median.to_s + " " + line
  52. puts "Row " + row.to_s + ": completed"
  53.  
  54.  
  55. #create_writefile(ARGV[1], average, s_deviation, median, data)
  56. end
  57. puts "Processing: Complete"
  58. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement