Top rank per group: Difference between revisions

(→‎{{header|Perl 6}}: a more idiomatic solution, with explanations)
Line 380:
 
=={{header|Common Lisp}}==
 
<lang lisp>(defun top-n-by-group (n data value-key group-key predicate &key (group-test 'eql))
(let ((not-pred (complement predicate))
Line 446 ⟶ 445:
D202 (3 (("David Motsinger" E27002 19250 D202) ("Claire Buckman" E39876 27800 D202) ("Rich Holcomb" E01234 49500 D202)))
D190 (2 (("Timothy Grove" E16398 29900 D190) ("Kim Arlich" E10001 57000 D190)))</lang>
=={{header|D}}==
From the first Python version.
<lang d>import std.stdio: writeln, writefln;
import std.algorithm: min, topN;
import std.string: format;
 
struct Employee {
string name, id;
int salary;
string department;
 
int opCmp(ref const Employee other) {
return other.salary - this.salary;
}
 
string toString() {
return format("%-15s %-15s %-15s %-15s", name, id, salary, department);
}
}
 
Employee[] data = [{"Tyler Bennett", "E10297", 32000, "D101"},
{"John Rappl", "E21437", 47000, "D050"},
{"George Woltman", "E00127", 53500, "D101"},
{"Adam Smith", "E63535", 18000, "D202"},
{"Claire Buckman", "E39876", 27800, "D202"},
{"David McClellan", "E04242", 41500, "D101"},
{"Rich Holcomb", "E01234", 49500, "D202"},
{"Nathan Adams", "E41298", 21900, "D050"},
{"Richard Potter", "E43128", 15900, "D101"},
{"David Motsinger", "E27002", 19250, "D202"},
{"Tim Sampair", "E03033", 27000, "D101"},
{"Kim Arlich", "E10001", 57000, "D190"},
{"Timothy Grove", "E16398", 29900, "D190"}];
 
void main() {
Employee[][string] departments;
foreach (rec; data)
departments[rec.department] ~= rec;
 
int N = 3;
foreach (department, recs; departments) {
writeln("Department ", department);
writeln(" Employee Name Employee ID Salary Department");
topN(recs, N);
foreach (rec; recs[0 .. min($, N)])
writeln(" ", rec);
writeln();
}
}</lang>
Output:
<pre>Department D202
Employee Name Employee ID Salary Department
Rich Holcomb E01234 49500 D202
Claire Buckman E39876 27800 D202
David Motsinger E27002 19250 D202
 
Department D190
Employee Name Employee ID Salary Department
Kim Arlich E10001 57000 D190
Timothy Grove E16398 29900 D190
 
Department D101
Employee Name Employee ID Salary Department
George Woltman E00127 53500 D101
David McClellan E04242 41500 D101
Tyler Bennett E10297 32000 D101
 
Department D050
Employee Name Employee ID Salary Department
John Rappl E21437 47000 D050
Nathan Adams E41298 21900 D050 </pre>
 
=={{header|E}}==
Anonymous user