The Wayback Machine - https://web.archive.org/web/20240811095609/https://www.geeksforgeeks.org/implementation-of-exhaustive-search-algorithm-for-set-packing/
Open In App

Implementation of Exhaustive Search Algorithm for Set Packing

Last Updated : 16 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Exhaustive Search Algorithm:

Exhaustive Search is a brute-force algorithm that systematically enumerates all possible solutions to a problem and checks each one to see if it is a valid solution. This algorithm is typically used for problems that have a small and well-defined search space, where it is feasible to check all possible solutions.

Examples:

Input: Items[] =  {1, 2, 3, 4, 5, 6};
List of sets = {1, 2, 3}, {4, 5}, {5, 6}, {1, 4}
Output: Maximum number of sets that can be packed: 3

Input: Items[] =  {1, 2};
List of sets = {1}, {4, }, {5}, {1}
Output: Maximum number of sets that can be packed: 1

Approach: 

Loop through all the sets  and check if the current item is in the current set If the item is in the set, increment the number of sets that can be packed and Update the maximum number of sets that can be packed

Here is a step-by-step description of how the algorithm works in this code:

  • The program defines a maxPackedSets() function that takes a set of items and a list of sets as input.
  • The function initializes the maximum number of sets that can be packed to 0.
  • The function loops through all the sets in the list of sets. For each set, it initializes the number of sets that can be packed to 0.
  • The function then loops through all the items in the set of items. For each item, it checks if the item is in the current set. If the item is in the set, the number of sets that can be packed is incremented and the item is removed from the set of items so that it is not counted again.
  • The function then updates the maximum number of sets that can be packed by taking the maximum of the current maximum and the number of sets that can be packed for the current set.
  • The function repeats steps 3-5 for all the sets in the list of sets.
  • Once all the sets have been processed, the function returns the maximum number of sets that can be packed as the result.
  • The main() function of the program creates a set of items and a list of sets and then calls the maxPackedSets() function to find the maximum number of sets that can be packed into the given set of items.
  • The result of the maxPackedSets() function is printed to the console, indicating the maximum number of sets that can be packed.

Thus, the code uses the Exhaustive Search algorithm to systematically enumerate and check all the sets in the list of sets to find the maximum number of sets that can be packed into the given set of items. This is a simple and straightforward approach to solving the Set Packing problem, but it can be slow and computationally expensive for problems with a large search space.

Here is a Java program that implements the Exhaustive Search algorithm for the Set Packing problem:

C++




#include <bits/stdc++.h>
using namespace std;
 
int maxPackedSets(vector<int>& items,
                  vector<set<int> >& sets)
{
 
  // Initialize the maximum number of sets that can be
  // packed to 0
  int maxSets = 0;
 
  // Loop through all the sets
  for (auto set : sets) {
    // Initialize the number of sets that can be packed
    // to 0
    int numSets = 0;
 
    // Loop through all the items
    for (auto item : items) {
      // Check if the current item is in the current
      // set
      if (set.count(item)) {
        // If the item is in the set, increment
        // the number of sets that can be packed
        numSets += 1;
 
        // Remove the item from the set of items,
        // so that it is not counted again
        items.erase(remove(items.begin(),
                           items.end(), item),
                    items.end());
      }
    }
 
    // Update the maximum number of sets that can be
    // packed
    maxSets = max(maxSets, numSets+1);
  }
 
  return maxSets;
}
 
int main()
{
 
  // Set of items
  vector<int> items = { 1, 2, 3, 4, 5, 6 };
 
  // List of sets
  vector<set<int> > sets
    = { { 1, 2, 3 }, { 4, 5 }, { 5, 6 }, { 1, 4 } };
 
 
  // Find the maximum number of sets that
  // can be packed into the given set of items
  int maxSets
    = maxPackedSets(items, sets);
 
  // Print the result
  cout << "Maximum number of sets that can be packed: "
    << maxSets << endl;
 
  return 0;
}
 
// This code is contributed by poojaagarwal2.


Java




// Package whatever
// do not write package name here
 
import java.io.*;
import java.util.ArrayList;
import java.util.List;
 
public class SetPacking {
 
    // Function to find the maximum number
    // of sets that can be packed into the
    // given set of items
    public static int maxPackedSets(int[] items,
                                    List<int[]> sets)
    {
 
        // Initialize the maximum number of
        // sets that can be packed to 0
        int maxSets = 0;
 
        // Loop through all the sets
        for (int[] set : sets) {
 
            // Initialize the number of sets
            // that can be packed to 0
            int numSets = 0;
 
            // Loop through all the items
            for (int item : items) {
 
                // Check if the current item
                // is in the current set
                if (contains(set, item)) {
 
                    // If the item is in the
                    // set, increment the
                    // number of sets that
                    // can be packed
                    numSets++;
 
                    // Remove the item from
                    // the set of items, so
                    // that it is not counted again
                    items = remove(items, item);
                }
            }
 
            // Update the maximum number
            // of sets that can be packed
            maxSets = Math.max(maxSets, numSets);
        }
 
        return maxSets;
    }
 
    // Function to check if an array
    // contains a given value
    public static boolean contains(int[] array, int value)
    {
        for (int element : array) {
            if (element == value) {
                return true;
            }
        }
        return false;
    }
 
    // Function to remove a given
    // value from an array
    public static int[] remove(int[] array, int value)
    {
        List<Integer> result = new ArrayList<>();
        for (int element : array) {
            if (element != value) {
                result.add(element);
            }
        }
        return result.stream().mapToInt(i -> i).toArray();
    }
 
    public static void main(String[] args)
    {
 
        // Set of items
        int[] items = { 1, 2, 3, 4, 5, 6 };
 
        // List of sets
        List<int[]> sets = new ArrayList<>();
        sets.add(new int[] { 1, 2, 3 });
        sets.add(new int[] { 4, 5 });
        sets.add(new int[] { 5, 6 });
        sets.add(new int[] { 1, 4 });
 
        // Find the maximum number of sets
        // that can be packed into the
        // given set of items
        int maxSets = maxPackedSets(items, sets);
 
        // Print the result
        System.out.println(
            "Maximum number of sets that can be packed: "
            + maxSets);
    }
}


Python3




# Python code for the above approach
def maxPackedSets(items, sets):
   
    # Initialize the maximum number of sets that can be packed to 0
    maxSets = 0
 
    # Loop through all the sets
    for set in sets:
        # Initialize the number of sets that can be packed to 0
        numSets = 0
 
        # Loop through all the items
        for item in items:
            # Check if the current item is in the current set
            if item in set:
                # If the item is in the set, increment
                # the number of sets that can be packed
                numSets += 1
 
                # Remove the item from the set of items,
                # so that it is not counted again
                items = [i for i in items if i != item]
 
        # Update the maximum number of sets that can be packed
        maxSets = max(maxSets, numSets)
 
    return maxSets
 
# Set of items
items = [1, 2, 3, 4, 5, 6]
 
# List of sets
sets = [
    [1, 2, 3],
    [4, 5],
    [5, 6],
    [1, 4]
]
 
# Find the maximum number of sets that
# can be packed into the given set of items
maxSets = maxPackedSets(items, sets)
 
# Print the result
print(f"Maximum number of sets that can be packed: {maxSets}")
 
# This code is contributed by Potta Lokesh


C#




// C# code implementation:
using System;
using System.Linq;
using System.Collections.Generic;
 
public class GFG {
 
  // Function to find the maximum number
  // of sets that can be packed into the
  // given set of items
  public static int MaxPackedSets(int[] items,
                                  List<int[]> sets)
  {
    // Initialize the maximum number of
    // sets that can be packed to 0
    int maxSets = 0;
 
    // Loop through all the sets
    foreach(int[] set in sets)
    {
      // Initialize the number of sets
      // that can be packed to 0
      int numSets = 0;
 
      // Loop through all the items
      foreach(int item in items)
      {
        // Check if the current item
        // is in the current set
        if (Contains(set, item)) {
          // If the item is in the
          // set, increment the
          // number of sets that
          // can be packed
          numSets++;
 
          // Remove the item from
          // the set of items, so
          // that it is not counted again
          items = Remove(items, item);
        }
      }
 
      // Update the maximum number
      // of sets that can be packed
      maxSets = Math.Max(maxSets, numSets);
    }
 
    return maxSets;
  }
 
  // Function to check if an array
  // contains a given value
  public static bool Contains(int[] array, int value)
  {
    foreach(int element in array)
    {
      if (element == value) {
        return true;
      }
    }
    return false;
  }
 
  // Function to remove a given
  // value from an array
  public static int[] Remove(int[] array, int value)
  {
    List<int> result = new List<int>();
    foreach(int element in array)
    {
      if (element != value) {
        result.Add(element);
      }
    }
    return result.ToArray();
  }
 
  static public void Main()
  {
 
    // Code
    // Set of items
    int[] items = { 1, 2, 3, 4, 5, 6 };
 
    // List of sets
    List<int[]> sets = new List<int[]>();
    sets.Add(new int[] { 1, 2, 3 });
    sets.Add(new int[] { 4, 5 });
    sets.Add(new int[] { 5, 6 });
    sets.Add(new int[] { 1, 4 });
 
    // Find the maximum number of sets
    // that can be packed into the
    // given set of items
    int maxSets = MaxPackedSets(items, sets);
 
    // Print the result
    Console.WriteLine(
      "Maximum number of sets that can be packed: "
      + maxSets);
  }
}
 
// This code is contributed by lokesh.


Javascript




function maxPackedSets(items, sets) {
  // Initialize the maximum number of sets that can be packed to 0
  let maxSets = 0;
 
  // Loop through all the sets
  for (let set of sets) {
    // Initialize the number of sets that can be packed to 0
    let numSets = 0;
 
    // Loop through all the items
    for (let item of items) {
      // Check if the current item is in the current set
      if (set.includes(item)) {
        // If the item is in the set, increment the number of sets that can be packed
        numSets++;
 
        // Remove the item from the set of items, so that it is not counted again
        items = items.filter(i => i !== item);
      }
    }
 
    // Update the maximum number of sets that can be packed
    maxSets = Math.max(maxSets, numSets);
  }
 
  return maxSets;
}
 
// Set of items
let items = [1, 2, 3, 4, 5, 6];
 
// List of sets
let sets = [
  [1, 2, 3],
  [4, 5],
  [5, 6],
  [1, 4]
];
 
// Find the maximum number of sets that can be packed into the given set of items
let maxSets = maxPackedSets(items, sets);
 
// Print the result
console.log(`Maximum number of sets that can be packed: ${maxSets}`);


Output

Maximum number of sets that can be packed: 3

Characteristics of Exhaustive Search Algorithm:

  • The Exhaustive Search algorithm is a simple and straightforward approach to solving problems. 
  • However, it can be slow and computationally expensive, especially for problems with a large search space. 
  • It is also not guaranteed to find the optimal solution to a problem, as it only checks solutions that are explicitly enumerated by the algorithm. 
  • Despite these limitations, Exhaustive Search can be a useful technique for solving certain types of problems.

Complexity Analysis: 

Time Complexity: The complexity of the maxPackedSets function is O(nm) where n is the length of the items array and m is the number of sets in the sets list. This is because the function loops through all the items (n) and all the sets (m) in two separate loops.

  • The complexity of the contains function is O(n) because it loops through all the elements in the array (n).
  • The complexity of the remove function is O(n) because it loops through all the elements in the array (n) and adds them to a new list if they are not the value to be removed.
  • Overall, the complexity of the entire program is O(n*m)

Auxiliary Space: O(n*m)
The space complexity of the maxPackedSets function is O(nm) because it creates a new list for the result of the remove function for each item in the items array and each set in the sets list.

  • The space complexity of the contains function is O(1) because it only uses a fixed number of variables regardless of the size of the input.
  • The space complexity of the remove function is O(n) because it creates a new list with a size equal to the number of elements in the input array that are not the value to be removed.
  • Overall, the space complexity of the entire program is O(n*m)


Similar Reads

Bin Packing Problem (Minimize number of used Bins)
Given n items of different weights and bins each of capacity c, assign each item to a bin such that number of total used bins is minimized. It may be assumed that all items have weights smaller than bin capacity.Example: Input: weight[] = {4, 8, 1, 4, 2, 1} Bin Capacity c = 10 Output: 2 We need minimum 2 bins to accommodate all items First bin cont
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N).  Table of Content What is Binary Search Algorithm?Conditions to apply Binary Search Algorithm in a Data S
15+ min read
Difference Between Dijkstra's Algorithm and A* Search Algorithm
Dijkstra's Algorithm and A* Algorithm are two of the most widely used techniques. Both are employed to the find the shortest path between the nodes in a graph but they have distinct differences in their approaches and applications. Understanding these differences is crucial for the selecting the appropriate algorithm for the given problem. What is
3 min read
Implementation of Chinese Remainder theorem (Inverse Modulo based implementation)
We are given two arrays num[0..k-1] and rem[0..k-1]. In num[0..k-1], every pair is coprime (gcd for every pair is 1). We need to find minimum positive number x such that: x % num[0] = rem[0], x % num[1] = rem[1], ....................... x % num[k-1] = rem[k-1] Example: Input: num[] = {3, 4, 5}, rem[] = {2, 3, 1} Output: 11 Explanation: 11 is the sm
11 min read
Hungarian Algorithm for Assignment Problem | Set 2 (Implementation)
Given a 2D array, arr of size N*N where arr[i][j] denotes the cost to complete the jth job by the ith worker. Any worker can be assigned to perform any job. The task is to assign the jobs such that exactly one worker can perform exactly one job in such a way that the total cost of the assignment is minimized. Example Input: arr[][] = {{3, 5}, {10,
7 min read
Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation)
We strongly recommend to refer below post as a prerequisite.Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction) There are few important things to note before we start implementation. We need to find an augmenting path (A path that alternates between matching and not matching edges and has free vertices as starting and ending points)
13 min read
Peterson's Algorithm for Mutual Exclusion | Set 1 (Basic C implementation)
Problem: Given 2 processes i and j, you need to write a program that can guarantee mutual exclusion between the two without any additional hardware support. Solution: There can be multiple ways to solve this problem, but most of them require additional hardware support. The simplest and the most popular way to do this is by using Peterson's Algorit
11 min read
Push Relabel Algorithm | Set 2 (Implementation)
We strongly recommend to refer below article before moving on to this article. Push Relabel Algorithm | Set 1 (Introduction and Illustration) Problem Statement:  Given a graph that represents a flow network where every edge has a capacity. Also given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with
15+ min read
Implementation of Search, Insert and Delete in Treap
We strongly recommend to refer set 1 as a prerequisite of this post.Treap (A Randomized Binary Search Tree)In this post, implementations of search, insert and delete are discussed.Search: Same as standard BST search. Priority is not considered for search. C/C++ Code // C function to search a given key in a given BST TreapNode* search(TreapNode* roo
15+ min read
Implementation of Binary Search Tree in Javascript
In this article, we would be implementing the Binary Search Tree data structure in Javascript. A tree is a collection of nodes connected by some edges. A tree is a non linear data structure. A Binary Search tree is a binary tree in which nodes that have lesser value are stored on the left while the nodes with a higher value are stored at the right.
9 min read
Practice Tags :
three90RightbarBannerImg