Search code examples
openedgeprogress-4gl

Algorithm to count instances of a value from a file


I am reading through a file of financial data with beneficiaries. I need to count the number of beneficiaries and then calculate their allocated percentage. If there is 1 beneficiary, the allocation is 100%, if there are 2, if there are 3, 33.33%, etc. The file is sorted by investment then beneficiary, so if there is more than one beneficiary per investment they will be in order in the file. Here's an example:

input file data

beneficiary input file

the output that I want

enter image description here

Here is my code, but it's wrong because this way I am assigning 100% to the first beneficiary, 50% to the second beneficiary, 33.333% to the third, etc. How can I change it to do the count, then create the beneficiaries with the right count? (There is an outer loop which is a table of investments.)

iBeneficiaryCount = 0.
dTempPercentage = 100.
FOR EACH ttJointData WHERE ttJointData.inv-num EQ ttInvestment.inv-num:
    IF ttJointData.Joint_Type EQ "Joint" THEN DO:
        cTemp = "JT".
        RUN CreateOwner (....).
   END.
   ELSE IF ttJointData.Joint_Type EQ "Beneficiary" THEN DO:
        iBeneficiaryCount = iBeneficiaryCount + 1.
        dTempPercentage = 100 / iBeneficiaryCount.
        RUN AddBeneficiary(ttJointData.investment-num,ttInvestment.benficiary-id,dTempPercentage).
    END.
END.

What are the best ways to capture that beneficiary percentage? I am thinking that I need to read through the data and put that value into the ttJointData table. Or is there a way to do it on the loop? Regardless, I need a neat algorithm to count up the instances from an input file and create and assign a percentage value.


Solution

  • You can use a query to calculate the number of beneficiaries before you loop through them.

    Something like

    DEFINE VARIABLE dTempPercentage  AS DECIMAL NO-UNDO.
    DEFINE VARIABLE iBeneficiaryCount AS INTEGER NO-UNDO.
    DEFINE QUERY qryJD FOR ttJointData.
    
    dTempPercentage = 100.
    FOR EACH ttInvestment:
        // calculate how many beneficiaries; must use PRESELECT here
        OPEN QUERY qryJD PRESELECT EACH ttJointData WHERE ttJointData.inv-num EQ ttInvestment.inv-num.
        iBeneficiaryCount = QUERY qryJD:NUM-RESULTS.
        dTempPercentage = 100 / iBeneficiaryCount.
    
        GET FIRST qryJD .
        DO WHILE AVAILABLE ttJointData :
           IF ttJointData.Joint_Type EQ "Joint" THEN DO:
                cTemp = "JT".
                RUN CreateOwner (....).
           END.
           ELSE IF ttJointData.Joint_Type EQ "Beneficiary" THEN DO:
                RUN AddBeneficiary(ttJointData.investment-num,ttInvestment.benficiary-id,dTempPercentage).
            END.    
    
            GET NEXT qryJD .
        END.
    
        CLOSE QUERY qryJD.
    END.