Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created October 21, 2012 19:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/3928203 to your computer and use it in GitHub Desktop.
Save havenwood/3928203 to your computer and use it in GitHub Desktop.
Perl6 Book Chapter 2 Example Ported to Ruby
Beth Ana Charlie Dave
Ana Dave | 3:0
Charlie Beth | 3:1
Ana Beth | 2:3
Dave Charlie | 3:0
Ana Charlie | 3:1
Beth Dave | 0:3
Ana has won 2 matches and 8 sets
Dave has won 2 matches and 6 sets
Charlie has won 1 matches and 4 sets
Beth has won 1 matches and 4 sets
use v6;
my $file = open 'scores';
my @names = $file.get.words;
my %matches;
my %sets;
for $file.lines -> $line {
my ($pairing, $result) = $line.split(' | ');
my ($p1, $p2) = $pairing.words;
my ($r1, $r2) = $result.split(':');
%sets{$p1} += $r1;
%sets{$p2} += $r2;
if $r1 > $r2 {
%matches{$p1}++;
} else {
%matches{$p2}++;
}
}
my @sorted = @names.sort({ %sets{$_} }).sort({ %matches{$_} }).reverse;
for @sorted -> $n {
say "$n has won %matches{$n} matches and %sets{$n} sets";
}
file = File.open 'scores'
names = file.readline.split
@matches = @sets = {}
@matches.default = @sets.default = 0
file.each do |line|
pairing, result = line.split ' | '
p1, p2 = pairing.split
r1, r2 = result.split ':'
@sets[p1] += r1.to_i
@sets[p2] += r2.to_i
if r1 > r2
@matches[p1] += 1
else
@matches[p2] += 1
end
end
sorted = names.sort_by { |n| [@matches[n], @sets[n]] }.reverse
sorted.each do |n|
puts "#{n} has won #{@matches[n]} matches and #{@sets[n]} sets"
end
f = open('scores')
names = f.readline().strip().split()
# name -> [matches, sets]
nsm = dict((name,[0, 0]) for name in names)
for line in f:
pairing, result = line.strip().split(' | ')
p1, p2 = pairing.split()
r1, r2 = (int(n) for n in result.split(':'))
nsm[p1][1] += r1
nsm[p2][1] += r2
if r1 > r2:
nsm[p1][0] += 1
else:
nsm[p2][0] += 1
for name, matches_sets in reversed(sorted(nsm.items(), key=lambda x: x[1])):
matches, sets = matches_sets
print "%s has won %d matches and %d sets" % (
name, matches, sets)
@havenwood
Copy link
Author

@havenwood
Copy link
Author

burgestrand1: use the default value for hash
yxhuvud: sort_by {|..| [a,b]}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment