# Fitting Shelves Problem in C++

C++Server Side ProgrammingProgramming

In this problem, we are given three integer values W, n, m denoting the length of wall W, size of shelves n, and m. Our task is To Create a Program to solve the Fitting Shelves Problem.

We need to find a way to fit shelves in such a way that the space left after fitting shelves is minimized. A secondary constrain while solving is the cost of making, the larger shelves are more cost-effective so, we need to give them a priority.

The output should be in the following form,

Number of n size shelves number of m size shelves space left

Let’s take an example to understand the problem

Input: W = 12, n = 5, m = 3
Output: 0 4 0

Explanation

Here, we will can fit exactly 4, 3 sized shelves in the wall.

This will make the total length = 4*3 = 12

So, no length in the wall is remaining after fitting.

## Solution Approach

A simple solution to the problem is by using the brute force approach which is by checking for each possible combination of fitting shelves in the wall and finding the ones which minimize or eliminate the space length in the wall. For the secondary task, we will be starting with fitting the larger-length shelf fist, this will give the larger one a priority. We will see which combination gives the minimum result with the maximum possible large shelves for the optimum solution.

## Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;

void solveFittingShelves(int wall, int m, int n){

int numM = 0, numN = 0, minSpaceLeft = wall;
int p = wall/m, q = 0, rem = wall%m;
numM = p;
numN = q;
minSpaceLeft = rem;
while (wall >= n) {
q += 1;
wall = wall - n;
p = wall / m;
rem = wall % m;
if (rem <= minSpaceLeft) {
numM = p;
numN = q;
minSpaceLeft = rem;
}
}
cout<<numM<<" "<<numN<<" "<<minSpaceLeft<<endl;
}

int main(){
int W = 29, m = 3, n = 9;
cout<<"Length of wall : "<<W<<endl;
cout<<"Length of shelves : "<<m<<"\t"<<n<<endl;
cout<<"Optimal Shelves fitting : ";
solveFittingShelves(W, m, n);
return 0;
}

## Output

Length of wall : 29
Length of shelves : 3 9
Optimal Shelves fitting : 0 3 2
Updated on 31-Jan-2022 12:22:51