In: Computer Science
MATLAB PROBLEM
You are given an array, weights, that contains the weights of some cargo items in pounds. You want to load a truck with items from the list, up to its capacity. The truck has a maximum capacity of 1,000 pounds. For this problem use a "greedy" algorithm. That is, always load the heaviest item that will still fit on the truck. Keep loading until the remaining capcity of the truck is less than any of the remaining cargo items. For example, if the weights were {700, 400, 250, 100, 60}, you would load the 700-pound item, then the 250-pound item. The remaining items would be too heavy to fit on the truck. The weights will be generated randomly, so you cannot hard-code the answer - you must write a general algorithm to do it. Once the loading is complete, print a message indicating how many pounds of cargo were loaded onto the truck. NOTE: To satisfy the auto-grader, update the variable capacity so that it contains the remaining capacity of the truck. For example, if 943 pounds of cargo are loaded, capacity should be 57.
CODE PROVIDED BELOW
%The weights of the cargo items are generated at random
%They are sorted in descending order
weights = sort(randi(500, 1, randi(10)), 'descend')
capacity = 1000; %cargo capacity of the truck
n=input('Enter how many cargo items: ')
maximum=input('Enter maximum value of cargo items: '
weights = randi(maximum,n,1);
weights = sort(weights);
fprintf("The randomly generated weights of cargo items are: \n")
disp(weights)
capacity=input('Enter capacity of truck: ')
loaded = 0;
i=n;
while(i>0)
if (weights(i)<=capacity)
loaded = loaded + weights(i); %adding the weight to loaded
capacity = capacity - weights(i);%removing weight from the loaded
end
i=i-1;
end