Search code examples
smlsmlnjssmlsysml

How to Implement LPT (Longest Processing Time) Scheduling Algorithm function in SML


Suppose that we have a list with the processing time of some tasks,like this [13,8,7,6,4,2,2,1]. we want to divide this list into two list by LPT Scheduling Algorithm.here is the algorithm procedure:

with a given Descending sorted list like above,at fist we put the largest element(first element in the sorted list) into list1 and then we put second element into list2. then we insert the next element into one of two list ,with smaller sum of elements. and we do this job until all elements in the initial list will get divided between two list.

for example for the mentioned list, two lists will be [13,6,2,1],[8,7,4,2](we see that the element 7 has inserted into second list because ListSum([13]>ListSum([8]) and then because of ListSum([13])


Solution

  • You could use a tail-recursive helper function:

    fun lpt xs = let 
        fun lpt' ([],l1,l2,s1,s2) = (rev l1, rev l2)
        |   lpt' (x::xs,l1,l2,s1,s2) = 
                if s1 <= s2 then lpt' (xs,x::l1,l2,s1+x,s2)
                else lpt' (xs,l1,x::l2,s1,s2+x)
        in
            lpt' (xs,[],[],0,0)
        end;
    

    The helper function takes the source list and the lists being built up, together with their sums, and tacks the head of the source list onto the appropriate list, adjusting the appropriate sums, and recursively calls itself on the tail of the list with these adjusted lists/sums. This method of building up the lists constructs them backwards (not uncommon when defining tail-recursive list constructors), so the basis case of nothing left to process reverses them. The main function simply calls the helper function with properly initialized lists/sums.