Search code examples
aggregateanswer-set-programmingclingo

Count Aggregates in clingo


Test data

addEmployee(EmplID, Name1, Name2, TypeOfWork, Salary, TxnDate)
addEmployee("tjb1998", "eva", "mcdowell", "ra", 55000, 20).
addEmployee("tjb1987x", "ben", "xena", "cdt", 68000, q50).
addEmployee("tjb2112", "ryoko", "hakubi", "ra", 63000, 60).
addEmployee("tjb1987", "ben", "croshaw", "cdt", 68000, 90).
addEmployee("tjb3300m", "amane", "mauna", "ma", 61000, 105).

I want to group by employees as per the type of work and count of employees for the particular type of work. e.g:

ra 4
cdt 2
ma 1

below is the query I am trying to run

employee(TOW) :- addEmployee(_,_,_,TOW,_,_).
nmbrEmployeesOfSameType (N) :- N = #count { employee(TOW) }.

Please advise, I am at the beginner level for Clingo


Solution

  • Try this:

    addEmployee("tjb1998", "eva", "mcdowell", "ra", 55000, 20).
    addEmployee("tjb1987x", "ben", "xena", "cdt", 68000, q50).
    addEmployee("tjb2112", "ryoko", "hakubi", "ra", 63000, 60).
    addEmployee("tjb1987", "ben", "croshaw", "cdt", 60000, 90).
    addEmployee("tjb3300m", "amane", "mauna", "ma", 61000, 105).
    
    
    getType(P, X) :- addEmployee(X, _, _, P, _, _).
    
    type(P) :- addEmployee(_, _, _, P, _, _).
    
    result(P, S) :- S = #count{ I : getType(P,I)}, type(P).
    
    #show result/2.
    

    And the output will look like:

    clingo version 4.5.3
    Reading from test.lp
    Solving...
    Answer: 1
    result("ra",2) result("cdt",2) result("ma",1)
    SATISFIABLE
    

    You can also copy my code and run it here to see if it works.