Last active
May 20, 2016 14:20
-
-
Save vapidbabble/1772d6649b3a84accb50 to your computer and use it in GitHub Desktop.
haskell example in ruby
This file contains hidden or 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
| #first stab | |
| h=Hash.new | |
| (File.read "grades.txt").split("\n").each do |pair| | |
| (person, grade)=pair.split ' ' | |
| if h[person] | |
| h[person] << grade.to_i | |
| else | |
| h[person]=[grade.to_i] | |
| end | |
| end | |
| (h.sort).to_h.each_pair do |key,value| | |
| print "#{key} #{value} Average: #{value.reduce(:+)/(value.length).to_f}\n" | |
| end | |
| #second attempt | |
| h=Hash.new | |
| (File.read "grades.txt"). | |
| split("\n"). | |
| map {|ele| ele.split}. | |
| sort.each do |pair| | |
| h[pair.first] ? | |
| h[pair.first] << pair.last.to_i : | |
| h[pair.first]=[pair.last.to_i] | |
| end | |
| h.each_pair do |key,value| | |
| print "#{key} #{value} Average: #{value.reduce(:+)/(value.length).to_f}\n" | |
| end | |
| #third | |
| h=Hash.new | |
| (File.read "grades.txt"). | |
| split("\n"). | |
| map {|ele| ele.split}. | |
| sort. | |
| each do |pair| | |
| (person,grade)=pair | |
| h[person] ? | |
| h[person] << grade.to_i : | |
| h[person]=[grade.to_i] | |
| end | |
| h.each_pair do |key,value| | |
| print "#{key} #{value} Average: #{value.reduce(:+)/(value.length).to_f}\n" | |
| end | |
| #fourth | |
| (File.open("grades.txt") do |file| | |
| file | |
| .map {|line| {person: line.split[0], grade: line.split[1]}} | |
| .group_by {|record| record[:person] } | |
| .each {|person,record| record.map! {|r| r[:grade]}} | |
| end) | |
| .sort | |
| .each_pair do |key,value| | |
| print "#{key} #{value} Average: #{value.reduce(:+)/(value.length).to_f}\n" | |
| end | |
| #Alonzo [70] Average: 70.0 | |
| #Bob [80] Average: 80.0 | |
| #Eugenio [69] Average: 69.0 | |
| #Henk [79, 90] Average: 84.5 | |
| #Nick [90, 98, 100] Average: 96.0 | |
| #Oleg [77] Average: 77.0 | |
| #Philip [73, 73] Average: 73.0 | |
| #Shlomo [90, 92, 95] Average: 92.33333333333333 | |
| #Simor [94] Average: 94.0 | |
| #Vered [100] Average: 100.0 |
This file contains hidden or 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
| Shlomo 90 | |
| Nick 90 | |
| Vered 100 | |
| Alonzo 70 | |
| Henk 79 | |
| Simor 94 | |
| Philip 73 | |
| Nick 98 | |
| Shlomo 92 | |
| Eugenio 69 | |
| Bob 80 | |
| Shlomo 95 | |
| Henk 90 | |
| Oleg 77 | |
| Philip 73 | |
| Nick 100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment