Top rank per group: Difference between revisions

Updated to work with Nim 1.4: added missing parameter type. Renamed "top" as "printTop". Added a parameter "people" to the proc. Miscellaneous other changes.
(Added 11l)
(Updated to work with Nim 1.4: added missing parameter type. Renamed "top" as "printTop". Added a parameter "people" to the proc. Miscellaneous other changes.)
Line 3,242:
<lang nim>import algorithm
 
type Record = tuple[name, id: string,; salary: int,; department: string]
 
var people: seq= [Record]("Tyler =Bennett", "E10297", 32000, "D101"),
@[ ("TylerJohn BennettRappl", "E10297E21437", 3200047000, "D101D050"),
("JohnGeorge RapplWoltman", "E21437E00127", 4700053500, "D050D101"),
("GeorgeAdam WoltmanSmith", "E00127E63535", 5350018000, "D101D202"),
("AdamClaire SmithBuckman", "E63535E39876", 1800027800, "D202"),
("ClaireDavid BuckmanMcClellan", "E39876E04242", 2780041500, "D202D101"),
("DavidRich McClellanHolcomb", "E04242E01234", 4150049500, "D101D202"),
("RichNathan HolcombAdams", "E01234E41298", 4950021900, "D202D050"),
("NathanRichard AdamsPotter", "E41298E43128", 2190015900, "D050D101"),
("RichardDavid PotterMotsinger", "E43128E27002", 1590019250, "D101D202"),
("DavidTim MotsingerSampair", "E27002E03033", 1925027000, "D202D101"),
("TimKim SampairArlich", "E03033E10001", 2700057000, "D101D190"),
("KimTimothy ArlichGrove", "E10001E16398", 5700029900, "D190"),]
("Timothy Grove", "E16398", 29900, "D190")]
 
proc pcmp(a, b: Record): int =
result = cmp(a.department, b.department)
if result !== 0: return
result = cmp(b.salary, a.salary)
 
proc top(n) =
sort(people, pcmp)
 
proc printTop(people: openArray[Record]; n: Positive) =
sortvar people = sorted(people, pcmp)
var rank = 0
for i, p in people:
if i > 0 and p.department != people[i-1].department:
rank = 0
echo ""()
 
if rank < n:
echo p.department, " ", p.salary, " ", p.name
inc rank
 
people.printTop(2)</lang>
inc rank
 
{{out}}
top(2)</lang>
Output:
<pre>D050 47000 John Rappl
D050 21900 Nathan Adams
Anonymous user