]> gitweb.factorcode.org Git - factor.git/blob - extra/rosetta-code/top-rank/top-rank.factor
e9cdba9734ce2f3d4b3e9449650db86a1c5a941c
[factor.git] / extra / rosetta-code / top-rank / top-rank.factor
1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors assocs io kernel math.parser sequences
4 sorting ;
5 IN: rosetta-code.top-rank
6
7 ! http://rosettacode.org/wiki/Top_rank_per_group
8
9 ! Find the top N salaries in each department, where N is
10 ! provided as a parameter.
11
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:
15
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
30
31 TUPLE: employee name id salary department ;
32
33 CONSTANT: employees {
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" }
47     }
48
49 : prepare-departments ( seq -- departments )
50     [ department>> ] collect-by
51     [ [ salary>> ] inv-sort-with ] assoc-map ;
52
53 : first-n-each ( seq n quot -- )
54     [ cramp head-slice ] dip each ; inline
55
56 : top-rank-main ( -- )
57     employees prepare-departments [
58         [ "Department " write write ":" print ] dip
59         3 [
60             [ id>> write "  $" write ]
61             [ salary>> number>string write "  " write ]
62             [ name>> print ] tri
63         ] first-n-each
64         nl
65     ] assoc-each ;
66
67 MAIN: top-rank-main