1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors assocs fry io kernel math.parser sequences
4 sorting math.statistics ;
5 IN: rosetta-code.top-rank
7 ! http://rosettacode.org/wiki/Top_rank_per_group
9 ! Find the top N salaries in each department, where N is
10 ! provided as a parameter.
12 ! Use this data as a formatted internal data structure (adapt it
13 ! to your language-native idioms, rather than parse at runtime),
14 ! or identify your external data source:
16 ! Employee Name,Employee ID,Salary,Department
17 ! Tyler Bennett,E10297,32000,D101
18 ! John Rappl,E21437,47000,D050
19 ! George Woltman,E00127,53500,D101
20 ! Adam Smith,E63535,18000,D202
21 ! Claire Buckman,E39876,27800,D202
22 ! David McClellan,E04242,41500,D101
23 ! Rich Holcomb,E01234,49500,D202
24 ! Nathan Adams,E41298,21900,D050
25 ! Richard Potter,E43128,15900,D101
26 ! David Motsinger,E27002,19250,D202
27 ! Tim Sampair,E03033,27000,D101
28 ! Kim Arlich,E10001,57000,D190
29 ! Timothy Grove,E16398,29900,D190
31 TUPLE: employee name id salary department ;
34 T{ employee f "Tyler Bennett" "E10297" 32000 "D101" }
35 T{ employee f "John Rappl" "E21437" 47000 "D050" }
36 T{ employee f "George Woltman" "E00127" 53500 "D101" }
37 T{ employee f "Adam Smith" "E63535" 18000 "D202" }
38 T{ employee f "Claire Buckman" "E39876" 27800 "D202" }
39 T{ employee f "David McClellan" "E04242" 41500 "D101" }
40 T{ employee f "Rich Holcomb" "E01234" 49500 "D202" }
41 T{ employee f "Nathan Adams" "E41298" 21900 "D050" }
42 T{ employee f "Richard Potter" "E43128" 15900 "D101" }
43 T{ employee f "David Motsinger" "E27002" 19250 "D202" }
44 T{ employee f "Tim Sampair" "E03033" 27000 "D101" }
45 T{ employee f "Kim Arlich" "E10001" 57000 "D190" }
46 T{ employee f "Timothy Grove" "E16398" 29900 "D190" }
49 : prepare-departments ( seq -- departments )
50 [ department>> ] collect-by
51 [ [ salary>> ] inv-sort-with ] assoc-map ;
53 : first-n-each ( seq n quot -- )
54 [ short head-slice ] dip each ; inline
56 : top-rank-main ( -- )
57 employees prepare-departments [
58 [ "Department " write write ":" print ] dip
60 [ id>> write " $" write ]
61 [ salary>> number>string write " " write ]