KX Community

Find answers, ask questions, and connect with our KX Community around the world.
KX Community Guidelines

Home Forums kdb+ how to solve this allocation problem Re: how to solve this allocation problem

  • Laura

    Administrator
    May 16, 2022 at 12:00 am

     

    q)show people:([]pickSeq:neg[n]?n;person:`$"person",/:string 1+til n;allowedToPick:n?01b) 
    pickSeq person allowedToPick 
    ------------------------------ 
    1 person1 0 
    8 person2 1 
    5 person3 0 
    7 person4 1 
    0 person5 0 
    3 person6 1 
    6 person7 0 
    4 person8 0 
    2 person9 1 
    9 person10 0 
    
    q)show prize:100*1+til 8 
    100 200 300 400 500 600 700 800

     

    The winners in order:

     

    q)`pickSeq xasc select from people where allowedToPick 
    pickSeq person allowedToPick 
    ----------------------------- 
    2 person9 1 
    3 person6 1 
    7 person4 1 
    8 person2 1

     

    And their rewards:

     

    q){select person,reward:count[x]#desc prize from x}`pickSeq xasc people where people`allowedToPick 
    person reward 
    -------------- 
    person9 800 
    person6 700 
    person4 600 
    person2 500

     

    Or in vector form:

     

    q){x!count[x]#desc prize}{x iasc y}. flip people[where people`allowedToPick;`person`pickSeq] 
    person9| 800 
    person6| 700 
    person4| 600 
    person2| 500

     

    Above, where people`allowedToPick finds the winners; and {x iasc y}. sorts the winners names by pick order. The vector form has less work to do:

    q)ts:1000 {select person,reward:count[x]#desc prize from x}`pickSeq xasc people where people`allowedToPick 
    12 3184 
    
    q)ts:1000 {x!count[x]#desc prize}{x iasc y}. flip people[where people`allowedToPick;`person`pickSeq] 
    3 3312