简体   繁体   中英

Greedy Makespan algorithm

I am needing to implement this greedy algorithm in python, but am having trouble understanding how to find the 'processor' for which M[j] is the least. Algorithm provided below...

greedy_min_make_span(T, m):
  # T is an array of n numbers, m >= 2
  A = [Nil, ... , Nil] # Initialize the assignments to nil (array size n)
  M = [ 0, 0, ...., 0] # initialize the current load of each processor to 0 (array size m)
  for i = 1 to n
    find processor j for which M[j] is the least.
    A[i] = j
    M[j] = M[j] + T[i]
 # Assignment achieves a makespan of max(M[1], .. M[m])
 return A


def greedy_makespan_min(times, m):
    # times is a list of n jobs.
    assert len(times) >= 1
    assert all(elt >= 0 for elt in times)
    assert m >= 2
    n = len(times)
    # please do not reorder the jobs in times or else tests will fail.
    # Return a tuple of two things: 
    #    - Assignment list of n numbers from 0 to m-1
    #    - The makespan of your assignment
    A = n*[0]
    M = m*[0]
    
    i = 1
    for i in range(i, n):
        j = M.index(min(M))
        A[i] = j
        M[j] = M[j] + times[i]
    return (A, M)

FIXED: The error i'm getting right now is "list assignment index out of range" when I am trying to assign A[i] to j.

Utility function:

def compute_makespan(times, m, assign):
    times_2 = m*[0]
    
    for i in range(len(times)):
        proc = assign[i]
        time = times[i]
        times_2[proc] = times_2[proc] + time
    return max(times_2)

Test cases that I have...

def do_test(times, m, expected):
    (a, makespan) = greedy_makespan_min(times,m )
    print('\t Assignment returned: ', a)
    print('\t Claimed makespan: ', makespan)
    assert compute_makespan(times, m, a) == makespan, 'Assignment returned is not consistent with the reported makespan'
    assert makespan == expected, f'Expected makespan should be {expected}, your core returned {makespan}'
    print('Passed')
print('Test 1:')
times = [2, 2, 2, 2, 2, 2, 2, 2, 3] 
m = 3
expected = 7
do_test(times, m, expected)

print('Test 2:')
times = [1]*20 + [5]
m = 5
expected =9
do_test(times, m, expected)

Right now I am failing the test cases. My assignment returned is not consistent with the reported makespan. My assignment returned is: [0, 0, 1, 2, 0, 1, 2, 0, 1] and my claimed makespan is: [6, 7, 4]. My compute makespan is returning 8 when it is expecting 7. Any ideas where I'm implementing this algorithm wrong?

Change A = n*[] to A = n*[0] .

Instead of creating a list with length n , A = n*[] would create an empty list. Since you're assigning A[i] = j in each iteration, the change would functionally make no difference to the output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM