Top rank per group: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 26:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">V data = [(‘Tyler Bennett’, ‘E10297’, 32000, ‘D101’),
(‘John Rappl’, ‘E21437’, 47000, ‘D050’),
(‘George Woltman’, ‘E00127’, 53500, ‘D101’),
Line 50:
L(rec) sorted(recs, key' rec -> rec[2], reverse' 1B)[0 .< n]
print(‘ #<15 #<15 #<15 #<15 ’.format(rec[0], rec[1], rec[2], rec[3]))
print()</langsyntaxhighlight>
 
{{out}}
Line 78:
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">DEFINE PTR="CARD"
DEFINE ENTRY_SIZE="8"
 
Line 182:
Sort()
TopRank(3)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Top_rank_per_group.png Screenshot from Atari 8-bit computer]
Line 207:
=={{header|Ada}}==
top.adb:
<langsyntaxhighlight Adalang="ada">with Ada.Containers.Vectors;
with Ada.Text_IO;
 
Line 277:
end;
end loop;
end Top;</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department D050
John Rappl | E21437 | 47000
Line 294:
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">Add_Employee(record employees, text name, id, integer salary, text department)
{
employees[name] = list(name, id, salary, department);
Line 347:
 
0;
}</langsyntaxhighlight>Run as:
<pre>aime rcs/top_rank_per_group c N 5</pre>{{out}}
<pre style="height:30ex;overflow:scroll">Department D050
Line 370:
It looks as if this task's requirements have changed — possibly more than once — since it was first set and named. As at the end of May 2021, it specifies the return of the top N ''salaries'' in each department and makes no mention at all of any of the other employee details. This makes it easier to decide how to handle the other thing it doesn't mention: what to return when two or more people in the same department are on the same pay. The interpretation here is "top N ''discrete'' salary values" (or of course fewer if a department doesn't have that many).
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.3.1" -- Mac OS X 10.9 (Mavericks) or later for these 'use' commands!
use sorter : script "Custom Iterative Ternary Merge Sort" -- <https://macscripter.net/viewtopic.php?pid=194430#p194430>
 
Line 464:
end demo
 
demo()</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">"Top 4 salaries per department:
D050: 47000 21900 - -
D101: 53500 41500 32000 27000
D190: 57000 29900 - -
D202: 49500 27800 19250 18000"</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">printTopEmployees: function [count, entries][
data: read.csv.withHeaders entries
departments: sort unique map data 'row -> row\Department
Line 505:
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
}</langsyntaxhighlight>
 
{{out}}
Line 534:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang="autohotkey">Departments = D050, D101, D190, D202
StringSplit, Department_, Departments, `,, %A_Space%
 
Line 589:
Employee_%m%_Salary := Salary
Employee_%m%_Dept := Department
}</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department: D050
---------------------------
Line 613:
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f TOP_RANK_PER_GROUP.AWK [n]
#
Line 659:
exit(0)
}
</syntaxhighlight>
</lang>
<p>Sample command and output:</p>
<pre>
Line 683:
=={{header|Bracmat}}==
Bracmat has no dedicated sorting functions. However, when evaluating algebraic expressions, Bracmat sorts factors in products and terms in sums. Moreover, Bracmat simplifies products by, amongst other transformations, collecting exponents of the same base into a single exponent, which is the sum of the collected exponents: <code>a^b*a^c</code> &rarr; <code>a^(b+c)</code>. This built-in behaviour is made use of in this solution.
<langsyntaxhighlight lang="bracmat"> (Tyler Bennett,E10297,32000,D101)
(John Rappl,E21437,47000,D050)
(George Woltman,E00127,53500,D101)
Line 722:
)
& toprank$(!employees.3)
& ;</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Top 3 salaries per department.
Department D050:
Line 740:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Line 794:
top(2);
return 0;
}</langsyntaxhighlight>{{out}}
<pre>D050 47000: John Rappl
D050 21900: Nathan Adams
Line 809:
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Linq;
Line 878:
}
}
}</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">
Department: D101
Line 900:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <string>
#include <set>
#include <list>
Line 1,013:
 
return 0;
}</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">In department D050
Name ID Salary Department
Line 1,037:
 
=={{header|Ceylon}}==
<langsyntaxhighlight lang="ceylon">class Employee(name, id, salary, dept) {
shared String name;
shared String id;
Line 1,078:
for (dept -> staff in employees.group(Employee.dept))
dept -> staff.sort(byDecreasing(Employee.salary)).take(n)
};</langsyntaxhighlight>
 
=={{header|Clojure}}==
 
<langsyntaxhighlight lang="lisp">(use '[clojure.contrib.seq-utils :only (group-by)])
 
(defstruct employee :Name :ID :Salary :Department)
Line 1,107:
(doseq [e (take 3 (reverse (sort-by :Salary emps)))]
(println e)))
</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department: D050
{:Name John Rappl, :ID E21437, :Salary 47000, :Department D050}
Line 1,125:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun top-n-by-group (n data value-key group-key predicate &key (group-test 'eql))
(let ((not-pred (complement predicate))
(group-data (make-hash-table :test group-test)))
Line 1,158:
(second entry) (insert datum (second entry))))))
(dolist (datum data group-data)
(update-entry (entry (funcall group-key datum)) datum)))))</langsyntaxhighlight>
Example
<langsyntaxhighlight lang="lisp">> (defparameter *employee-data*
'(("Tyler Bennett" E10297 32000 D101)
("John Rappl" E21437 47000 D050)
Line 1,187:
D050 (2 (("Nathan Adams" E41298 21900 D050) ("John Rappl" E21437 47000 D050)))
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)))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.conv, std.range;
 
struct Employee {
Line 1,224:
writefln("Department %s\n %(%s\n %)\n", dep, recs.take(n));
}
}</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department D202
Employee("Rich Holcomb", "E01234", 49500, "D202")
Line 1,245:
=={{header|Dyalect}}==
 
<langsyntaxhighlight lang="dyalect">type Employee(name,id,salary,department) with Lookup
func Employee.ToString() {
Line 1,285:
for e in seq {
print(e)
}</langsyntaxhighlight>
 
{{out}}
Line 1,297:
 
=={{header|E}}==
<langsyntaxhighlight lang="e">/** Turn a list of arrays into a list of maps with the given keys. */
def addKeys(keys, rows) {
def res := [].diverge()
Line 1,335:
out.println()
}
}</langsyntaxhighlight>
 
Note: This uses an append-and-then-sort to maintain the list of top N; a sorted insert or a proper [[wp: selection algorithm|selection algorithm]] would be more efficient. As long as <var>N</var> is small, this does not matter much; the algorithm is O(n) with respect to the data set.{{out}}
Line 1,363:
=={{header|EchoLisp}}==
We use the '''sql.lib''' to select, sort and group records from the table 'emps'. The output is appended in a new table, 'high'.
<langsyntaxhighlight lang="scheme">
(lib 'struct) ;; tables are based upon structures
(lib 'sql) ;; sql-select function
Line 1,378:
group-by emp.dept
order-by emp.salary desc limit N into high))
</syntaxhighlight>
</lang>
{{out}}
<langsyntaxhighlight lang="scheme">
(define emps_file
'(("Tyler Bennett" E10297 32000 D101)
Line 1,420:
[3] D202 Rich Holcomb 49500
[4] D666 Simon Gallubert 42
</syntaxhighlight>
</lang>
 
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang="elena">import system'collections;
import system'routines;
import extensions;
Line 1,488:
console.readChar()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,511:
=={{header|Elixir}}==
Quick implementation using piping and anonymous functions.
<langsyntaxhighlight Elixirlang="elixir">defmodule TopRank do
def per_groupe(data, n) do
String.split(data, ~r/(\n|\r\n|\r)/, trim: true)
Line 1,546:
Timothy Grove,E16398,29900,D190
"""
TopRank.per_groupe(data, 3)</langsyntaxhighlight>
 
{{out}}
Line 1,567:
 
=={{header|Erlang}}==
<langsyntaxhighlight Erlanglang="erlang"><-module( top_rank_per_group ).
 
-export( [employees/0, employees_in_department/2, highest_payed/2, task/1] ).
Line 1,606:
[io:fwrite( "~p ~p: ~p~n", [Department, Salery, Name]) || #employee{department=Department, salery=Salery, name=Name} <- Highest_payeds],
io:nl().
</langsyntaxhighlight>{{out}}
<pre><14> top_rank_per_group:task(2).
"D050" 53500: "George Woltman"
Line 1,621:
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let data =
[
"Tyler Bennett", "E10297", 32000, "D101";
Line 1,640:
let topRank n =
Seq.groupBy (fun (_, _, _, d) -> d) data
|> Seq.map (snd >> Seq.sortBy (fun (_, _, s, _) -> -s) >> Seq.take n)</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: accessors assocs fry io kernel math.parser sequences
sorting ;
IN: top-rank
Line 1,684:
] first-n-each
nl
] assoc-each ;</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">
Department D101:
Line 1,706:
 
=={{header|Forth}}==
<syntaxhighlight lang="forth">
<lang Forth>
\ Written in ANS-Forth; tested under VFX.
\ Requires the novice package: http://www.forth.org/novice.html
Line 1,836:
 
test-data kill-employee
</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 1,871:
 
=={{header|Fortran}}==
The example data can easily be declared via DATA statements, as with <langsyntaxhighlight Fortranlang="fortran"> DATA EMPLOYEE(1:3)/
1 GRIST("Tyler Bennett","E10297",32000,"D101"),
2 GRIST("John Rappl","E21437",47000,"D050"),
3 GRIST("George Woltman","E00127",53500,"D101")/
</syntaxhighlight>
</lang>
(just showing the first three), however this does not allow the preparation of the header line, because <code>GRIST("Employee Name","Employee ID","Salary","Department")</code> would be invalid since the "salary" entry is a floating-point number in the data aggregate, not text. The header line could be discarded, but this is in violation of the ideas of properly-described data files. So, the plan is to read the data from an input file containing the full example input, with its header line given special treatment. No attempt is made to detect or report improperly-formatted data. The READ statements could refer to an internally-defined block of text, but reading an actual disc file is more normal. Ad-hoc decisions are made for the size of the CHARACTER variables, that are "surely big enough" for the example data, likewise with the size of the array to hold all the records.
 
Line 1,886:
If the requirement had been to report the highest-ranked salary, the deed could have been done via the F90 function MAXLOC, which locates the array index of the (first-encountered?) maximum value of an array of values; further, it allows an additional MASK parameter which could be used to select only those entries having a particular "department" code. However, aside from the multiple scans that would be required for multiple departmental codes, there is the requirement for the top N salaries, and anyway, there would still be the need to identify the different departmental codes once only. Accordingly, the way ahead is the classic: sort the data and then work through the sorted sequence. Since standard Fortran provides no "sort" function in its standard libraries nor does it offer a pre-processor that might include a sort generator and the like to generate the specific code needed for a particular data aggregate and sort key specification, one must engage in some repetition. For this purpose, the "comb" sort is convenient with its code requiring just one comparison and one "swap" action, so in-line code is not troublesome. On the other hand, when dealing with compound sort keys, a three-way IF statement (or equivalent) is necessary whereby the first field of the sort key is compared with appropriate action for the < and > cases, but for the = case the comparison moves on to the second key. ''Three'' different consequences from the one comparison. Despite the deprecations of the modernisers this is still possible for numerical comparisons, but alas, character comparisons are not allowed in an arithmetic-IF statement - though one could struggle with ICHAR action. Thus, two comparisons are made where only one should suffice.
 
Finally, standard Fortran does not offer a means of receiving parameters as might be supplied when a code file is activated in a command-line environment. There may be special library routines with names such as GETARG, but they're not standard. So, a READ statement is employed. Or, one could rewrite this routine as a subroutine having one parameter so as to approximate the form of the specification more closely. Extra statements... <langsyntaxhighlight Fortranlang="fortran"> PROGRAM TOP RANK !Just do it.
CHARACTER*28 HEADING(4) !The first line is a header.
TYPE GRIST !But this is the stuff.
Line 1,954:
 
END !That was straightforward.
</syntaxhighlight>
</lang>
 
As ever, some tricky sizing of fields in the FORMAT statements, and a collection of ad-hoc constants. Cross-linking the integers via PARAMETER statements and the like would add a whole lot of blather, so if field sizes are changed, a fair amount of fiddling would follow. A more accomplished data processing routine would include this.
Line 1,982:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">#define N 3 'show the top three employees of each rank
 
'here is all the data to be read in
Line 2,038:
next x
print
next d</langsyntaxhighlight>
 
{{out}}<pre>
Line 2,061:
 
=={{header|FunL}}==
<langsyntaxhighlight lang="funl">data Employee( name, id, salary, dept )
 
employees = [
Line 2,087:
printf( " %-16s %6s %7d\n", e.name, e.id, e.salary )
println()</langsyntaxhighlight>
{{out}}
Line 2,110:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 2,230:
}
}
}</langsyntaxhighlight>
{{out|Output (with additional data demonstrating ties)}}
<pre style="height:30ex;overflow:scroll">
Line 2,253:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def displayRank(employees, number) {
employees.groupBy { it.Department }.sort().each { department, staff ->
println "Department $department"
Line 2,280:
[Name: 'Timothy Grove', ID: 'E16398', Salary: 29900, Department: 'D190']
]
displayRank(employees, 3)</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department D050
Name ID Salary
Line 2,306:
====Data.List====
{{Works with|GHC|7.10.3}}
<langsyntaxhighlight lang="haskell">import Data.List (sortBy, groupBy)
 
import Text.Printf (printf)
Line 2,384:
putStrLn $ replicate 31 '='
mapM_ (traverse ((printf "%-16s %3s %10.2g\n" . name) <*> dep <*> sal)) $
firstN 3 dep sal employees</langsyntaxhighlight>
{{out}}
<pre>NAME DEP TIP
Line 2,406:
Alternatively, if we store the data in key-value maps, rather than in a cons list, we can use Map.lookup and Map.filter, Map.keys and Map.elems, to pull out the data and shape reports fairly flexibly.
 
<langsyntaxhighlight Haskelllang="haskell">import Data.List (intercalate, nub, sort, sortBy, transpose)
import qualified Data.Map as M
import Data.Maybe (fromJust)
Line 2,503:
)
<$> transpose rows
)</langsyntaxhighlight>
{{Out}}
<pre>de Bont C.A. AB 65000
Line 2,519:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">CHARACTER source="Test.txt", outP='Top_rank.txt', fmt='A20,A8,i6,2x,A10'
CHARACTER name*20, employee_ID*10, department*10, temp*10
REAL :: idx(1), N_top_salaries=3
Line 2,548:
ENDDO
 
END</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">John Rappl E21437 47000 D050
Nathan Adams E41298 21900 D050
Line 2,566:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight lang="icon">record Employee(name,id,salary,dept)
 
procedure getEmployees ()
Line 2,609:
every show_employee (!employeesInGroup[1:(1+min(N,*employeesInGroup))])
}
end</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">
$ ./top-rank-by-group 2
Line 2,644:
 
=={{header|IS-BASIC}}==
<langsyntaxhighlight ISlang="is-BASICbasic">100 PROGRAM "Employee.bas"(N)
110 LET NR=100:LET X=0
120 STRING NAME$(1 TO NR)*20,ID$(1 TO NR)*6,DEPT$(1 TO NR)*4
Line 2,694:
580 IF J<=N THEN PRINT " ";NAME$(I);TAB(23);ID$(I),SALARY(I):LET J=J+1
590 NEXT
600 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
J has a rich set of primitive functions, which combine the power of an imperative language with the expressiveness of a declarative, SQL-like language:
 
<langsyntaxhighlight lang="j">NB. Dynamically generate convenience functions
('`',,;:^:_1: N=:{.Employees) =:, (_&{"1)`'' ([^:(_ -: ])L:0)"0 _~ i.# E =: {: Employees
NB. Show top six ranked employees in each dept
N , (<@:>"1@:|:@:((6 <. #) {. ] \: SALARY)/.~ DEPT) |: <"1&> E</langsyntaxhighlight>
<pre style="height:30ex;overflow:scroll">
+-----+-----+-----------------+------+
Line 2,763:
Named as a function where the (maximum) number of employees in each department is a parameter:
 
<langsyntaxhighlight lang="j">reportTopSalaries=: 3 :'N , (<@:>"1@:|:@:((y <. #) {. ] \: SALARY)/.~ DEPT) |: <"1&> E'</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">
reportTopSalaries 2
Line 2,784:
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import java.io.File;
import java.util.*;
 
Line 2,832:
});
}
}</langsyntaxhighlight>
 
<pre style="height:30ex;overflow:scroll">Department D050
Line 2,855:
 
===Iterative Solution===
<langsyntaxhighlight lang="javascript">var data = [
{name: "Tyler Bennett", id: "E10297", salary: 32000, dept: "D101"},
{name: "John Rappl", id: "E21437", salary: 47000, dept: "D050"},
Line 2,913:
 
top_rank(3);
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">D101
Line 2,937:
===Map and reduce===
====ES5====
<langsyntaxhighlight lang="javascript">var collectDept = function (arrOfObj) {
var collect = arrOfObj.reduce(function (rtnObj, obj) {
if (rtnObj[obj.dept] === undefined) {
Line 2,967:
return list.slice(0,n);
});
};</langsyntaxhighlight>
====ES6====
By composition of generic functions:
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 3,127:
topNSalariesPerDept(3, xs)
);
})();</langsyntaxhighlight>
{{Out}}
<pre>[
Line 3,144:
=={{header|jq}}==
The task description invites use of the "language-native" data structure, which for jq is JSON, and so the following assumes that the file data.json contains an array of objects, each having as keys the strings on the header line. Thus, the first object in the array looks like this:
<langsyntaxhighlight lang="json"> {
"Employee Name": "Tyler Bennett",
"Employee ID": "E10297",
"Salary": "32000",
"Department": "D101"
}</langsyntaxhighlight>
===Program===
<langsyntaxhighlight lang="jq">def top_rank_per_department(n):
group_by(.Department)
| reduce .[] as $dept
Line 3,161:
| ($dept[0] | .Department) as $dept
| . + [ { "Department": $dept, "top_salaries": $max } ] );
</syntaxhighlight>
</lang>
 
===Example===
With the above program, the top two salaries in each dapartment can be found as shown in the following transcript:<langsyntaxhighlight lang="json">
$ jq 'top_rank_per_department(2) data.json
[
Line 3,195:
]
}
]</langsyntaxhighlight>
 
=={{header|Jsish}}==
Based on Javascript, imperative solution
<langsyntaxhighlight lang="javascript">#!/usr/bin/env jsish
/* Top rank per group, in Jsish */
function top_rank(n) {
Line 3,270:
 
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 3,296:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia"># v0.6.0
 
using DataFrames
Line 3,354:
println("\n$cl:\n$data")
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 3,394:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.2
 
data class Employee(val name: String, val id: String, val salary: Int, val dept: String)
Line 3,424:
println()
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,448:
 
=={{header|Ksh}}==
<langsyntaxhighlight lang="ksh">
#!/bin/ksh
exec 2> /tmp/Top_rank_per_group.err
Line 3,523:
(( j++ ))
fi
done</langsyntaxhighlight>
{{out}}<pre>
D050 47000 E21437 John Rappl
Line 3,535:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">N = 2
 
lst = { { "Tyler Bennett","E10297",32000,"D101" },
Line 3,570:
end
print ""
end</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department: D050
John Rappl E21437 47000
Line 3,588:
 
=== Object-Oriented ===
<langsyntaxhighlight lang="lua">--Employee Class
local EmployeeMethods = {
Line 3,681:
print("\t"..tostring(Employee))
end
end</langsyntaxhighlight>
{{out}}
<pre>
Line 3,699:
 
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module Checkit {
' erase stack of values, so we can add data
Line 3,772:
}
Checkit
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 3,797:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">InitialList ={{"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"},
Line 3,810:
 
Scan[((Print["Department ",#[[1,4]],"\n","Employee","\t","Id","\t","Salary"]&[#])&[#];
(Scan[Print[#[[1]],"\t",#[[2]],"\t",#[[3]]]&,#] )& [#])&,TrimmedList]</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll"><pre>Department D101
Line 3,833:
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">import algorithm
 
type Record = tuple[name, id: string; salary: int; department: string]
Line 3,867:
inc rank
 
people.printTop(2)</langsyntaxhighlight>
 
{{out}}
Line 3,883:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">open StdLabels
 
let to_string (name,_,s,_) = (Printf.sprintf "%s (%d)" name s)
Line 3,932:
let () =
toprank data 3;
;;</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department: D190
Kim Arlich (57000), Timothy Grove (29900)
Line 3,953:
Then sort each department by salaries and keep only the first n elements.
 
<langsyntaxhighlight Oforthlang="oforth">Object Class new: Employee(name, id, salary, dep)
Employee method: initialize := dep := salary := id := name ;
Line 3,979:
#dep employees sortBy groupWith( #dep )
map(#[ sortBy(#[ salary neg ]) left(n) ]) apply(#println) ; </langsyntaxhighlight>
 
{{out}}
Line 3,991:
 
=={{header|Oz}}==
<langsyntaxhighlight lang="oz">declare
%% Create a list of employee records.
Data = {Map
Line 4,036:
end
in
{Inspect {TopEarners Data 3}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
{{PARI/GP select}}
<langsyntaxhighlight lang="parigp">{V=[["Tyler Bennett","E10297",32000,"D101"],
["John Rappl","E21437",47000,"D050"],
["George Woltman","E00127",53500,"D101"],
Line 4,067:
};
 
top(2,V)</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|Free_Pascal}}
{{libheader|Classes}} {{libheader|Math}}
<langsyntaxhighlight lang="pascal">program TopRankPerGroup(output);
 
uses
Line 4,141:
end;
end.
</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">% ./TopRankPerGroup
Enter the number of ranks: 3
Line 4,164:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">sub zip {
my @a = @{shift()};
my @b = @{shift()};
Line 4,210:
}
print "\n";
}</langsyntaxhighlight>
{{out}}
<pre>D050
Line 4,231:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">N</span><span style="color: #0000FF;">=</span><span style="color: #000000;">3</span>
Line 4,274:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre>
Line 4,295:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">$data = Array(
Array("Tyler Bennett","E10297",32000,"D101"),
Array("John Rappl","E21437",47000,"D050"),
Line 4,342:
echo '</pre>';
}
top_sal(3);</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">D050
Name ID Salary
Line 4,367:
 
=={{header|Picat}}==
<langsyntaxhighlight Picatlang="picat">go =>
Emp = [
% Employee Name,Employee ID,Salary,Department
Line 4,396:
end,
nl
end.</langsyntaxhighlight>
 
{{out}}
Line 4,419:
 
===Using data as facts===
<langsyntaxhighlight Picatlang="picat">go2 =>
Emp = findall([Name,ID,Salary,Dept],emp(Name,ID,Salary,Dept)),
print_top_ranks(Emp,3),
Line 4,436:
emp("Tim Sampair","E03033","27000","D101").
emp("Kim Arlich","E10001","57000","D190").
emp("Timothy Grove","E16398","29900","D190").</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp"># Employee Name, ID, Salary, Department
(de *Employees
("Tyler Bennett" E10297 32000 D101)
Line 4,465:
(prinl) ) ) )
 
(topEmployees 3)</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department D101:
Name ID Salary
Line 4,489:
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">(subrg, stringrange, stringsize):
rank: procedure options (main); /* 10 November 2013 */
 
Line 4,571:
end;
put skip list ('FINISHED');
end rank;</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">How many highest-paid employees do you want?
 
Line 4,607:
 
=={{header|PL/SQL}}==
<langsyntaxhighlight lang="plsql">create or replace procedure "Top rank per group"(TOP_N in pls_integer default 3) as
cursor CSR_EMP(TOP_N pls_integer) is
select case LINE
Line 4,714:
DBMS_OUTPUT.PUT_LINE(v_emp."Top rank per group");
end loop;
end;</langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">function New-Employee ($Name, $ID, $Salary, $Department) {
New-Object PSObject `
| Add-Member -PassThru NoteProperty EmployeeName $Name `
Line 4,748:
} `
| Format-Table -GroupBy Department
}</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">PS> Get-TopRank 2
 
Line 4,780:
 
=={{header|Prolog}}==
<langsyntaxhighlight lang="prolog">% emp(name,id,salary,dpt)
emp('Tyler Bennett','E10297',32000,'D101').
emp('John Rappl','E21437',47000,'D050').
Line 4,832:
writef(' ID: %w\t%w\tSalary: %w\n', [Id,Name,Sal]),
fail.
topDeps(_).</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">?- topDeps(2).
Department: D101
Line 4,850:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Structure Employees
Name$
ID$
Line 4,907:
NewList MyEmployees.Employees()
 
displayTopEarners(MyEmployees(), 3)</langsyntaxhighlight>
 
'''Save this as 'DataFile.txt and let the program open this file'''<pre>
Line 4,957:
=={{header|Python}}==
Python 2.7/3.x compatible.
<langsyntaxhighlight lang="python">from collections import defaultdict
from heapq import nlargest
Line 4,986:
for rec in nlargest(N, recs, key=lambda rec: rec[-2]):
print (format % rec)
print('')</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department D050
Employee Name Employee ID Salary Department
Line 5,015:
Uses namedtuples for database records, and groupby builtin to group records by Department:
{{Works with|Python|3.7}}
<langsyntaxhighlight lang="python">from collections import namedtuple
from itertools import groupby
 
Line 5,048:
lambda record: record.Department
)
))</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">D050
DBRecord(Employee_Name='John Rappl', Employee_ID='E21437', Salary='47000', Department='D050')
Line 5,067:
=={{header|R}}==
First, read in the data.
<langsyntaxhighlight Rlang="r">dfr <- read.csv(tc <- textConnection(
"Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
Line 5,081:
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190")); close(tc)</langsyntaxhighlight>
To just return the top salary, it's very simple using tapply.
<langsyntaxhighlight Rlang="r">with(dfr, tapply(Salary, Department, max))</langsyntaxhighlight>
To return N salaries, we replace max with our own function.
<langsyntaxhighlight Rlang="r">get.top.N.salaries <- function(N)
{
with(dfr, tapply(Salary, Department,
Line 5,097:
}
 
get.top.N.salaries(3)</langsyntaxhighlight>
$D050
[1] 47000 21900
Line 5,111:
 
To return the whole record for each of the top salaries, a different tack is required.
<langsyntaxhighlight Rlang="r">get.top.N.salaries2 <- function(N)
{
#Sort data frame by Department, then by Salary
Line 5,125:
})
}
get.top.N.salaries2(3)</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll"> $D050
Employee.Name Employee.ID Salary Department
Line 5,151:
With the dplyr package we can use group_by and top_n to select the top n records in each group.
 
<syntaxhighlight lang="r">
<lang R>
library(dplyr)
dfr %>%
group_by(Department) %>%
top_n(2, Salary)
</syntaxhighlight>
</lang>
Provides:
<pre style="height:30ex;overflow:scroll">
Line 5,172:
 
=={{header|Racket}}==
<langsyntaxhighlight Racketlang="racket">#lang racket
 
(struct employee (name id salary dept))
Line 5,203:
(employee-name e)
(employee-id e))))
</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department D101:
$53500: George Woltman (E00127)
Line 5,225:
This program also makes heavy use of method calls that start with dot. In Raku this means a method call on the current topic, <tt>$_</tt>, which is automatically set by any <tt>for</tt> or <tt>map</tt> construct that doesn't declare an explicit formal parameter on its closure.
 
<syntaxhighlight lang="raku" perl6line>my @data = do for q:to/---/.lines -> $line {
E10297 32000 D101 Tyler Bennett
E21437 47000 D050 John Rappl
Line 5,253:
say .< Dept Id Salary Name > for @es[^$N]:v;
}
}</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">
D050 E21437 47000 John Rappl
Line 5,271:
=={{header|REXX}}==
===version 1===
<langsyntaxhighlight lang="rexx">/*REXX program displays the top N salaries in each department (internal table). */
parse arg topN . /*get optional # for the top N salaries*/
if topN=='' | topN=="," then topN= 1 /*Not specified? Then use the default.*/
Line 5,307:
dept.h= /*make sure we see the employee again. */
end /*topN*/
end /*dep*/ /*stick a fork in it, we're all done. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the input: &nbsp; &nbsp; <tt> 2 </tt>}}
<pre>
Line 5,354:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 12.02.2014 Walter Pachl
*--------------------------------------------------------------------*/
Line 5,428:
exit: Say arg(1)
help: Say 'Syntax: rexx topsal [topn]'
Exit</langsyntaxhighlight>
'''output'''
<pre>13 employees, 4 departments: D101 D050 D202 D190
Line 5,447:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Top rank per group
 
Line 5,507:
ok
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 5,543:
Without much thought to report formatting:
{{works with|Ruby|2.2+}}
<langsyntaxhighlight lang="ruby">require "csv"
 
data = <<EOS
Line 5,575:
end
 
show_top_salaries_per_group(data, 3)</langsyntaxhighlight>
 
{{out}}
Line 5,599:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">perSal$ = "Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050;
George Woltman,E00127,53500,D101
Line 5,637:
end if
print word$(depSal$(i),1,",");chr$(9);word$(depSal$(i),2,",");chr$(9);word$(depSal$(i),3,",")
next i</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Employee Name ID Salary
 
Line 5,668:
The implementation counts with ties.
 
<langsyntaxhighlight Rustlang="rust">#[derive(Debug)]
struct Employee<S> {
// Allow S to be any suitable string representation
Line 5,760:
 
Ok(())
}</langsyntaxhighlight>
 
{{out}}
Line 5,786:
=={{header|Scala}}==
===Application idiomatic version===
<langsyntaxhighlight lang="scala">import scala.io.Source
import scala.language.implicitConversions
import scala.language.reflectiveCalls
Line 5,843:
.map(_.toString).mkString("\t", "\n\t", ""))
}
}</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Reporting top 3 salaries in each department.
 
Line 5,866:
===using SLICK ORM===
{{libheader|H2 Database Engine}} Version 1.3.1
<langsyntaxhighlight lang="scala">import scala.slick.driver.H2Driver.simple._
import scala.slick.lifted.ProvenShape
 
Line 6,017:
plainQuery.foreach(println(_))
} // session
} // TopNrankSLICK</langsyntaxhighlight>
{{out}}
<pre style="height:30ex;overflow:scroll">Tot.15 Employees in 4 deps.Avg salary: 33336.67
Line 6,052:
=={{header|Scheme}}==
{{works with|Gauche Scheme}}
<langsyntaxhighlight Schemelang="scheme">(use gauche.record)
 
;; This will let us treat a list as though it is a structure (record).
Line 6,108:
(for-each
(pa$ print-record col-widths)
(take* matches n))))))</langsyntaxhighlight>
<b>Testing:</b>
<pre>
Line 6,153:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">var data = <<'EOF'.lines.map{ <name id salary dept> ~Z .split(',') -> flat.to_h }
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
Line 6,179:
}
print "\n"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 6,205:
The following [[SMEQL]] example returns the top 6 earners in each department based on this table schema:
 
<langsyntaxhighlight lang="smeql">table: Employees
----------------
empID
dept
empName
salary</langsyntaxhighlight>
Source Code:
<langsyntaxhighlight lang="smeql">srt = orderBy(Employees, [dept, salary], order)
top = group(srt, [(dept) dept2, max(order) order])
join(srt, top, a.dept=b.dept2 and b.order - a.order < 6)</langsyntaxhighlight>
 
Note: Since SMEQL is a query language, it has no built-in I/O capability to prompt the user for the threshold number ("6" in this example). However, it would be possible to retrieve the threshold from another table, but would make the example a bit confusing. In practice, an application language would most likely pass the value to it as a parameter.
 
=={{header|SQL}}==
<langsyntaxhighlight lang="sql">create table EMP
(
EMP_ID varchar2(6 char),
Line 6,257:
insert into EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
values ('E16400','Timothy Grive','D190',29900);
COMMIT;</langsyntaxhighlight>
<langsyntaxhighlight lang="sql">select case LINE
when 10 then
'Tot.' || LPAD(POPULATION, 2) || ' Employees in ' || TIE_COUNT ||
Line 6,351:
where EMP4.DEPT_ID = EMP3.DEPT_ID
and EMP4.SALARY >= EMP3.SALARY))
order by DEPT_ID ,LINE ,SALARY desc, EMP_ID;</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Tot.15 employees in 4 deps.Avg salary: 33336.67
-
Line 6,384:
 
Since there is no requirement for the layout - using the data from the table above
<langsyntaxhighlight lang="sql">WITH ranked_emp AS (
SELECT emp_name
,dept_id
Line 6,397:
FROM ranked_emp
WHERE ranking <= 2
ORDER BY dept_id, ranking;</langsyntaxhighlight>
 
<pre style="height:30ex;overflow:scroll">
Line 6,415:
=={{header|Stata}}==
The following shows the top k salaries. If there are less than k employees in a department, this will print all salaries.
<langsyntaxhighlight lang="stata">import delimited employees.csv
local k 2
bysort department (salary): list salary if _N-_n<`k'</langsyntaxhighlight>
 
=={{header|Swift}}==
 
<langsyntaxhighlight Swiftlang="swift">struct Employee {
var name: String
var id: String
Line 6,466:
 
print("\(dept)'s highest paid employees are: \n\t\(employeeString)")
}</langsyntaxhighlight>
 
{{out}}
Line 6,487:
=={{header|Tcl}}==
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
set text {Tyler Bennett,E10297,32000,D101
Line 6,520:
}
 
top_n_salaries 3 $data</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department D101
George Woltman E00127 53500
Line 6,544:
Version using built-in database-like functionality.
 
<langsyntaxhighlight lang="scheme">#lang transd
 
 
Line 6,581:
limit: N)
(for rec in recs do (textout rec "\n")))))))
}</langsyntaxhighlight>{{out}}
<pre>
[D050, E21437, John Rappl, 47000]
Line 6,594:
 
Version using untyped vectors.
<langsyntaxhighlight lang="scheme">
#lang transd
 
Line 6,638:
))
}
</langsyntaxhighlight>{{out}}
<pre>
[[John Rappl, E21437, 47000, D050]]
Line 6,651:
 
=={{header|TUSCRIPT}}==
<langsyntaxhighlight lang="tuscript">$$ MODE TUSCRIPT
MODE DATA
$$ SET dates=*
Line 6,697:
PRINT " "
ENDLOOP
ENDCOMPILE</langsyntaxhighlight>{{out}}
<pre style='height:30ex;overflow:scroll'>
Department D050
Line 6,737:
The data is in a file, exactly as given in the problem. Parameter N is accepted from command line.
 
<langsyntaxhighlight lang="txr">@(next :args)
@{n-param}
@(next "top-rank-per-group.dat")
Line 6,759:
@ (end)
@ (end)
@(end)</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">Department: D101
George Woltman (E00127) $ 53500
Line 6,779:
Descend into argument list:
 
<syntaxhighlight lang ="txr">@(next :args)</langsyntaxhighlight>
 
Collect first argument as <code>n-param</code> variable:
 
<syntaxhighlight lang ="txr">@{n-param}</langsyntaxhighlight>
 
Drill into data file:
 
<langsyntaxhighlight lang="txr">@(next "top-rank-per-group.dat")</langsyntaxhighlight>
 
Match header exactly:
 
<langsyntaxhighlight lang="txr">Employee Name,Employee ID,Salary,Department</langsyntaxhighlight>
 
Now iterate over the data, requiring a variable called <code>record</code> to be bound in each iteration, and suppress all other variables from emerging. In the body of the collect, bind four variables. Then use these four variables to create a four-element list which is bound to the variable <code>record</code>. The <code>int-str</code> function converts the textual variable <code>salary</code> to an integer:
 
<langsyntaxhighlight lang="txr">@(collect :vars (record))
@name,@id,@salary,@dept
@(bind record (@(int-str salary) dept name id))
@(end)
</syntaxhighlight>
</lang>
 
Next, we bind five variables to the output of some TXR Lisp code, which will return five lists:
 
<langsyntaxhighlight lang="txr">@(bind (dept salary dept2 name id)
@(let* ((n (int-str n-param))
(dept-hash [group-by second record :equal-based])
Line 6,809:
(ranked (collect-each ((rec (hash-values dept-hash)))
[apply mapcar list [[sort rec > first] 0..n]])))
(cons dept [apply mapcar list ranked])))</langsyntaxhighlight>
 
This code binds some successive variables. <code>n</code> is an integer conversion of the command line argument.
Line 6,820:
The reason for these transpositions is to convert the data into individual nested lists, once for each field. This is the format needed by the TXR <code>@(output)</code> clause:
 
<langsyntaxhighlight lang="txr">@(output)
@ (repeat)
Department: @dept
Line 6,827:
@ (end)
@ (end)
@(end)</langsyntaxhighlight>
 
Here, all these variables are individual lists. The <code>dept</code> variable is a flat list; one nesting of <code>@(repeat)</code> iterates over it. The other variables are nested lists; a nested repeat drills into these.
Line 6,837:
The output is identical to the previous version.
 
<langsyntaxhighlight lang="txr">@(next :args)
@{n-param}
@(next "top-rank-per-group.dat")
Line 6,854:
(put-line `Department: @d`)
(each ((r dept-recs))
(put-line ` @{r[2] 15} (@{r[3]}) $@{r[0] -6}`)))))</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 6,860:
sort each partition descending by the second to last, take the first
n strings in each partition, and display the list of them in a reasonably understandable form.
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 6,885:
#show+
 
main = top3 data</langsyntaxhighlight>{{out}}
<pre style="height:30ex;overflow:scroll">D190
Kim Arlich,E10001,57000
Line 6,906:
=={{header|VBA}}==
Creating an Excel pivot table to display the top n salaried employees per department. Data is read from a file.
<langsyntaxhighlight lang="vb">Private Sub top_rank(filename As String, n As Integer)
Workbooks.OpenText filename:=filename, Comma:=True
Dim ws As Worksheet
Line 6,942:
Public Sub main()
top_rank filename:="D:\data.txt", n:=3
End Sub</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 6,950:
{{libheader|Wren-seq}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "/dynamic" for Tuple
import "/sort" for Sort, Cmp
import "/seq" for Lst
Line 6,987:
topRanked.each { |e| Fmt.print("$-15s $s $d", e.name, e.id, e.salary) }
System.print()
}</langsyntaxhighlight>
 
{{out}}
Line 7,011:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">proc Sort(Array, Field, Size); \Sort Array in descending order by Field
int Array, Field, Size, I, J, T;
[for J:= Size-1 downto 0 do
Line 7,061:
if Data(I,0) = 0 then quit;
];
]</langsyntaxhighlight>
 
{{out}}
Line 7,084:
=={{header|zkl}}==
This reads a data file, the contents of which are as given by the task description (minus the header). To protect privacy, identifying information has been stripped from the output (aka laziness enhanced coding).
<langsyntaxhighlight lang="zkl">fcn setAppend(d,[(key,data)]){ d[key]=d.find(key,T).append(data) } //-->(key,(data,data...))
 
fcn topNsalaries(n){
Line 7,097:
"%s: %s".fmt(d,ss.concat(",")).println();
}
}(3);</langsyntaxhighlight>
{{out}}
<pre>
10,327

edits