Open In App

Minimize steps to fit the carpet in box by halving its sides

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

There is a carpet of size A * B [length * breadth]. Given a box of size C * D, the task is to fit the carpet in the box in a minimum number of moves. In one move, you can either decrease the length or the breadth of the carpet by half (floor value of its half). 

Note: One can even turn the carpet by 90 degrees any number of times, won’t be counted as a move.

Examples:

Input: A = 8, B = 13, C = 6, D = 10
Output: Minimum number of moves: 1
Explanation: Fold the carpet by breadth, 13/2 i.e. 6,  so now the carpet is 6 * 8 and can fit fine.

Input: A = 4, B = 8, C = 3, D = 10
Output: Minimum number of moves: 1
Explanation: Fold the carpet by length, 4/2 i.e. 2, so now the carpet is 2 * 8 and can fit fine.

Approach: This can be solved with the following idea:

The carpet should be folded so that it fits within the box. The steps are counted. Recount by spinning once at the start and folding the carpet once more. Take at least two counts.

Steps to be followed for the above approach:

  • Make x = a and y = b. 
  • Execute a loop while iterating over x > c or y > d.
  • Divide x by 2 and increase the counter if x is more than c.
  • Divide y by 2 and raise the counter if y is higher than d, the loop closes.                                                                                                                                                                           
  • Make x = a and y = b, then count and reset the counter.
  • Start a loop while x > d or y > c, which indicates that we are rotating the carpet to check. within the ring
  • Divide x by 2 and increment the counter if x is bigger than d.
  • Divide y by 2 and increase the counter if c is more than y, the loop closes.
  • Return the minimum of the current count and the answer.

Below is the code implementation of the above approach:

C++




#include <iostream>
#include <map>
#include <utility>
 
using namespace std;
 
class Solution {
public:
    int C, D;
    map<pair<int, int>, int> dp;
    const int oo = 1e8;
 
    // Function to check whether carpets
    // fits or not
    bool fits(int a, int b, int x, int y)
    {
        if (a <= x && b <= y) {
            return true;
        }
        int tmp = a;
        a = b;
        b = tmp;
 
        // If dimensions are less
        if (a <= x && b <= y) {
            return true;
        }
        return false;
    }
 
    // Function to reduce the
    // size of carpet
    int solve(int A, int B)
    {
        if (fits(A, B, C, D)) {
            return 0;
        }
 
        if (dp.count({A, B})) {
            return dp[{A, B}];
        }
 
        int op1 = oo, op2 = oo;
        if (A != 0) {
            op1 = 1 + solve(A / 2, B);
        }
        if (B != 0) {
            op2 = 1 + solve(A, B / 2);
        }
        int ret = min(op1, op2);
        dp[{A, B}] = ret;
        return ret;
    }
 
    // Main function of solution
    int carpetBox(int A, int B, int C, int D)
    {
        this->C = C;
        this->D = D;
        dp.clear();
        int result = solve(A, B);
        return result == oo ? -1 : result;
    }
};
 
// Driver code
int main()
{
    Solution s;
    int A = 8, B = 13, C = 6, D = 10;
 
    // Function call
    int result = s.carpetBox(A, B, C, D);
    cout << result << endl;
 
    return 0;
}
 
 
//This code is contributed by Ayush Pathak


Java




// Java code for the above approach:
import java.util.*;
 
class pair implements Comparable<pair> {
    int first, second;
 
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
 
    public int compareTo(pair ob)
    {
        if (this.first != ob.first) {
            return this.first - ob.first;
        }
        return this.second - ob.second;
    }
 
    public String toString()
    {
        return first + " " + second;
    }
 
    static public pair from(int f, int s)
    {
        return new pair(f, s);
    }
}
 
class Solution {
    int C, D;
    TreeMap<pair, Integer> dp;
    final int oo = (int)1e8;
 
    // Function to check whether carpets
    // fits or not
    boolean fits(int a, int b, int x, int y)
    {
        if (a <= x && b <= y) {
            return true;
        }
        int tmp = a;
        a = b;
        b = tmp;
 
        // If dimensions are less
        if (a <= x && b <= y) {
            return true;
        }
        return false;
    }
 
    // Function to reduce the
    // size of carpet
    int solve(int A, int B)
    {
        if (fits(A, B, C, D)) {
            return 0;
        }
 
        if (dp.containsKey(pair.from(A, B))) {
            return dp.get(pair.from(A, B));
        }
 
        int op1 = oo, op2 = oo;
        if (A != 0) {
            op1 = 1 + solve(A / 2, B);
        }
        if (B != 0) {
            op2 = 1 + solve(A, B / 2);
        }
        int ret = Math.min(op1, op2);
        dp.put(pair.from(A, B), ret);
        return ret;
    }
 
    // Main function of solution
    int carpetBox(int A, int B, int C, int D)
    {
        this.C = C;
        this.D = D;
        dp = new TreeMap<>();
        int result = solve(A, B);
        return result == oo ? -1 : result;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        Solution s = new Solution();
        int A = 8, B = 13, C = 6, D = 10;
 
        // Function call
        int result = s.carpetBox(A, B, C, D);
        System.out.println(result);
    }
}


Python3




class Solution:
    def __init__(self):
        self.C = None
        self.D = None
        self.dp = {}
        self.oo = 10 ** 8
 
    # Function to check whether carpets fit or not
    def fits(self, a, b, x, y):
        if a <= x and b <= y:
            return True
        tmp = a
        a = b
        b = tmp
 
        # If dimensions are less
        if a <= x and b <= y:
            return True
        return False
 
    # Function to reduce the size of carpet
    def solve(self, A, B):
        if self.fits(A, B, self.C, self.D):
            return 0
 
        if (A, B) in self.dp:
            return self.dp[(A, B)]
 
        op1, op2 = self.oo, self.oo
        if A != 0:
            op1 = 1 + self.solve(A // 2, B)
        if B != 0:
            op2 = 1 + self.solve(A, B // 2)
        ret = min(op1, op2)
        self.dp[(A, B)] = ret
        return ret
 
    # Main function of solution
    def carpetBox(self, A, B, C, D):
        self.C = C
        self.D = D
        self.dp.clear()
        result = self.solve(A, B)
        return -1 if result == self.oo else result
 
 
# Driver code
if __name__ == '__main__':
    s = Solution()
    A, B, C, D = 8, 13, 6, 10
 
    # Function call
    result = s.carpetBox(A, B, C, D)
    print(result)
# This code is contributed by rutikbhosale


C#




// Code code implementation
 
using System;
using System.Collections.Generic;
 
public class pair : IComparable<pair> {
    public int first, second;
    public pair(int first, int second)
    {
        this.first = first;
        this.second = second;
    }
 
    public int CompareTo(pair ob)
    {
        if (this.first != ob.first) {
            return this.first - ob.first;
        }
        return this.second - ob.second;
    }
 
    public override string ToString()
    {
        return first + " " + second;
    }
 
    static public pair from(int f, int s)
    {
        return new pair(f, s);
    }
}
 
public class GFG {
 
    int C, D;
    Dictionary<pair, int> dp;
    const int oo = (int)1e8;
 
    // Function to check whether carpets fits or not
    bool fits(int a, int b, int x, int y)
    {
        if (a <= x && b <= y) {
            return true;
        }
        int tmp = a;
        a = b;
        b = tmp;
 
        // If dimensions are less
        if (a <= x && b <= y) {
            return true;
        }
        return false;
    }
 
    // Function to reduce the size of carpet
    int solve(int A, int B)
    {
        if (fits(A, B, C, D)) {
            return 0;
        }
 
        if (dp.ContainsKey(pair.from(A, B))) {
            return dp[pair.from(A, B)];
        }
 
        int op1 = oo, op2 = oo;
        if (A != 0) {
            op1 = 1 + solve(A / 2, B);
        }
        if (B != 0) {
            op2 = 1 + solve(A, B / 2);
        }
        int ret = Math.Min(op1, op2);
        dp[pair.from(A, B)] = ret;
        return ret;
    }
 
      // main function for the solution
    int carpetBox(int A, int B, int C, int D)
    {
        this.C = C;
        this.D = D;
        dp = new Dictionary<pair, int>();
        int result = solve(A, B);
        return result == oo ? -1 : result;
    }
 
    static public void Main()
    {
 
        // Code
        GFG s = new GFG();
        int A = 8, B = 13, C = 6, D = 10;
 
        // Function call
        int result = s.carpetBox(A, B, C, D);
        Console.WriteLine(result);
    }
}
 
// This code is contributed by lokesh.


Javascript




// JavaScript code for the approach
 
class Solution {
  constructor() {
    this.C = 0;
    this.D = 0;
    this.dp = new Map();
    this.oo = 1e8;
  }
 
  // Function to check whether carpets fits or not
  fits(a, b, x, y) {
    if (a <= x && b <= y) {
      return true;
    }
    let tmp = a;
    a = b;
    b = tmp;
 
    // If dimensions are less
    if (a <= x && b <= y) {
      return true;
    }
    return false;
  }
 
  // Function to reduce the size of carpet
  solve(A, B) {
    if (this.fits(A, B, this.C, this.D)) {
      return 0;
    }
 
    if (this.dp.has(`${A},${B}`)) {
      return this.dp.get(`${A},${B}`);
    }
 
    let op1 = this.oo,
      op2 = this.oo;
    if (A != 0) {
      op1 = 1 + this.solve(Math.floor(A / 2), B);
    }
    if (B != 0) {
      op2 = 1 + this.solve(A, Math.floor(B / 2));
    }
    let ret = Math.min(op1, op2);
    this.dp.set(`${A},${B}`, ret);
    return ret;
  }
 
  // Main function of solution
  carpetBox(A, B, C, D) {
    this.C = C;
    this.D = D;
    this.dp.clear();
    let result = this.solve(A, B);
    return result == this.oo ? -1 : result;
  }
}
 
// Driver code
let s = new Solution();
let A = 8,
  B = 13,
  C = 6,
  D = 10;
 
// Function call
let result = s.carpetBox(A, B, C, D);
console.log(result);


Output

1

Time Complexity: O( max( log(a), log(b) ) )
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads