pangfengliu / programmingtasks

programming tasks from my courses
68 stars 17 forks source link

Buckets and Balls, Again #341

Open littlehug opened 6 years ago

littlehug commented 6 years ago

Place balls into buckets according to first fit, best fit, and worst fit.

Task Description

We are given N buckets with index from 0 to N-1 and M balls. Each bucket has a weight limit and each ball has a weight. Now we need to put the balls one by one into buckets, and we should make sure that the total weight of balls in a bucket does not exceed the weight limit. Once we put a ball into a bucket, we record the bucket index. If we could not find a bucket for a ball because it is too heavy, then we discard the ball and record -1. Write a function to record the how we place balls into buckets.

The balls can be put into the bucket according to either of the following three rules.

First fit. We place the ball to the first bucket that can hold it. If no bucket can hold the ball, we discard it. Best fit. We place the ball into the bucket that has the smallest remaining capacity after placing the ball. If no bucket can hold this ball, we discard the ball. Note that if more than one buckets have the same smallest remaining capacity, we put the ball into the one with the smallest index.
Worst fit. We place the ball into the bucket that has the largest remaining capacity after placing the ball. If no bucket can hold this ball, we discard the ball. Note that if more than one buckets have the same largest remaining capacity, we put the ball into the one with the largest index.

We use an example to illustrate the placement. Now we have three buckets (b0, b1, and b2), and four balls. The weight limits of the buckets are {13, 11, 12}, and and the weights of the four balls are {7, 8, 4, 9}.

When we use first fit, the following will happen.

When we use best fit the following will happen.

When we use worst fit:

You may use the following main function to test your function.

#include<stdio.h>
#include"placement.h"

int main(){
    int N,M,method;
    scanf("%d%d%d",&N,&M,&method);
    int buckets[N];
    for(int i=0;i<N;i++)
        scanf("%d",&buckets[i]);
    int balls[M];
    for(int i=0;i<M;i++)
        scanf("%d",&balls[i]);
    int result[M];
    place(buckets,N,balls,M,method,result);
    for(int i=0;i<M;i++)
        printf("%d%s",result[i],i==M-1?"":" ");
    return 0;
}

The prototype of place function is as follows.

void place(int bucket[1024],int N,int ball[16384],int M,int method,int result[16384]);

The placement.h is as follow:

void place(int bucket[1024],int N,int ball[16384],int M,int method,int result[16384]);

Subtask

The second line contains N integers, and the i-th integer represents the weight limit of bucket bi. The third line contains M integers, and each integer represents the weight of a ball.