blog posts

What Is Brute Force Algorithm? Along With A Practical Example

What Is Brute Force Algorithm? Along With A Practical Example

Brute Force Algorithm Is A Simple And Direct Method To Solve Problems, Based On Which We Check All Possible States To Reach The Final Solution. 

This algorithm examines all the states in order without using the specific properties of the problem. In other words, the Brute Force algorithm tries all modes crudely and carelessly.

To use a brute force algorithm, you typically have an iteration loop that checks all possible states. This loop can change based on the number of inputs, sets, conditions, or any other parameter your problem has.

The brute force algorithm is usually used in minor problems with limited states. As the number of states increases, the execution time of the Brute Force algorithm increases significantly and may become inefficient. In this case, other methods, such as optimization, approximation, or recursive algorithms, are better.

An example of a Brute Force algorithm can be a linear search in an array. In this case, we check all the elements of the collection to reach the desired part or find out that the selected element does not exist.

When is the above algorithm used?

Typically, the Brute Force algorithm is used in the following cases:

  • Minor problems: When your problem is small and the number of states is limited, you can use the Brute Force algorithm. In this case, the execution time of the algorithm may be acceptable, and the exact answer will be reached.
  • Analysis and testing: The Brute Force algorithm can be used in the initial stages of problem analysis and testing. Using this algorithm, you can find a quick way to check the correctness and feasibility of the problem. If the brute force algorithm works correctly, you can later implement more optimal methods based on the specific properties and patterns of the problem.
  •  Travel problems: In some travel problems, the Brute Force algorithm may be a reasonable method. For example, in combinatorial issues with limited combinations and states, you can use the Brute Force algorithm to check all states and arrive at the solution.

It is important to remember that the Brute Force algorithm eventually reaches the exact answer but has a high time cost. Therefore, if your problem is significant and the number of states is vast, it is better to use more optimized methods and more advanced algorithms with less execution time.

A practical example of the above algorithm

A practical example of the Brute Force algorithm can be the problem of finding all sequences of an integer. Suppose you want to see all lines of integers from 1 to n. You can use the Brute Force algorithm to solve this problem. A simple way to implement the Brute Force algorithm for this problem is:

  1.  Get the initial value for n.

  2.  Define an empty array called “sort”.

  3.  Add the integers from 1 to n sequentially to the “sort” array using an iterate loop.

  4.  For each number in the “sort” array:

– Define another array called “current_order.”

– Add all the “sort” array elements to the “current_sort” collection using another iteration loop.

– At each stage, if the length of the “current_order” array becomes equal to n, a complete order has been obtained. If so, print current_order.

5. The algorithm ends.

Using the Brute Force algorithm, this method checks all possible arrangements and reaches the answer. Unfortunately, the running time of this algorithm will be very high for large values ​​of n, e.g., longer than 3.6 million orders for n = 10. Therefore, for large values ​​of n, it is better to use more optimal methods, such as recursive or combinatorial algorithms.

What are the advantages and disadvantages of the above algorithm?

The Brute Force algorithm, like other existing algorithms, has its advantages and disadvantages, some of which are as follows:

Advantages:

  • Ease of implementation: A brute force algorithm is usually the easiest way to solve a problem. Its performance is relatively easy and does not require complex algorithms and optimization.
  • Certainty: You can definitively reach the exact answer using the Brute Force algorithm. This algorithm examines all modes and gets the final solution.
  • Conceptual: The Brute Force algorithm is handy for understanding the problem and its solution method. By examining all the modes, you can better understand the patterns and properties of the problem and use them in designing more optimal algorithms.

Disadvantages:

  • Execution time: The most significant disadvantage of the Brute Force algorithm is the high execution time. The execution time of this algorithm increases exponentially with the input size (number of states). For significant inputs, implementing the Brute Force algorithm is impractical and inefficient.
  • Resource consumption: The brute force algorithm requires more memory and resources to check all the states. For significant inputs, this can cause problems.
  • Inefficiency in complex problems: In problems with many states, the Brute Force algorithm will be inefficient. This algorithm cannot find the most optimal solution and must check all modes to reach the solution.

The brute force algorithm will be acceptable if your problem is small and the number of states is limited. However, more optimal methods and algorithms are better for more extensive and complex issues.

What is the difference between the above algorithm and other algorithms?

The difference between the Brute Force algorithm and other algorithms, including optimization algorithms and recursive algorithms, can be mentioned in the following cases:

  1. How it works: A brute force algorithm examines all cases, while optimization and recursive algorithms usually work with specific methods to reduce the search space and perform more efficient calculations.
  2.  Running time: The brute force algorithm generally runs well for significant inputs because it checks all states. In contrast, optimization and recursion algorithms usually drastically reduce execution time using more innovative and optimized methods.
  3.  Optimality: Optimization and recursive algorithms usually aim at optimization and try to reach the optimal solution. While the Brute Force algorithm only checks all modes and may not get the optimal solution.
  4.  Computational complexity: Optimization and recursion algorithms usually have less computational complexity than the Brute Force algorithm. Because they use more innovative methods to reduce search space and optimization.

The main difference between the Brute Force and other algorithms is the working method, execution time, optimality, and computational complexity. The Brute Force algorithm is simple and easy to understand, but for larger and more complex problems, more optimized and recursive algorithms generally provide the best solution.

A short comparison between optimization and regression algorithms with the Brute Force algorithm

Optimization and recursive algorithms are usually compared with brute force algorithms for optimal solutions. In the following, I will provide a comparison between these two types of algorithms:

1. Work method:

  •     Brute Force Algorithm: This algorithm checks all modes and finds the best solution. This method is straightforward but becomes impractical for complex problems with many states.
  •     Optimization and recursive algorithms: These algorithms use unique methods to reduce the search space and optimization. They approach the optimal solution using more intelligent methods, techniques like divide and solve, dynamic programming, linear programming, clustering gen, etic algorithms, etc.

2. Execution time:

  •    Brute Force Algorithm: The execution time of this algorithm increases exponentially for significant inputs. For problems with large dimensions, the implementation of this algorithm is impractical.
  •    Optimization and recursion algorithms: Using more intelligent methods in optimization and recursion algorithms usually dramatically reduces the execution time. Optimization techniques such as reducing the search space, online calculation, and cache memory allow these algorithms to reach the optimal solution with less execution time.

3. Optimism:

  •  Brute Force Algorithm: This algorithm only checks all modes and may not reach the optimal solution. In some cases, the output of the Brute Force algorithm is only an acceptable solution and not the best possible solution.
  •   Optimization and recursive algorithms: These algorithms aim at optimization and try to get close to the optimal solution. They use more intelligent techniques like divide and solve, dynamic programming, linear programming, clustering, genetic algorithms, etc., to improve the resolution and optimization.

4. Computational complexity:

  •   Brute Force Algorithm: This algorithm has exponential computational complexity in the worst case. For significant inputs, the execution time becomes very high.
  •   Optimization and recursive algorithms: These algorithms usually have better computational complexity than the Brute Force algorithm. By using more innovative and more optimized methods, they drastically reduce the execution time.

The Brute Force algorithm is generally simple and understandable but impractical for larger and more complex problems. Optimization and recursive algorithms use more innovative methods to improve the solution and reduce the execution time, but they may not reach the optimal solution. Choosing the correct algorithm depends on the type of problem, input size, and desired goals.

How do you implement the above algorithm in Python?

To implement the Brute Force algorithm in Python, you can use an iteration loop to check all possible states and find the best solution. The Brute Force algorithm is straightforward to implement. In the following, you can see an example of implementing the Brute Force algorithm in Python:
def brute_force_algorithm(items):
    best_value = float(‘-inf’) # We equal the value of the best answer to the minimum value
    # Browse through all possible modes
    for i in range(2 ** len(items)): # The number of modes is equal to 2 times the number of items
        current_value = 0
        current_subset = []
        # Check the active bits in the current mode number
        for j in range(len(items)):
            if (i >> j) & 1: # Check the jth bit
                current_value += items[j].value
                current_subset.append(items[j])
        # Checking the best available answer
        if current_value > best_value:
            best_value = current_value
            best_subset = current_subset
    return best_value, best_subset

In this example, it is assumed that each item has a “value” attribute that represents the value of that item. The Brute Force algorithm checks all possible states using a binary loop. The current value and corresponding subset are calculated and compared to each state’s best solution. Finally, the best answer and the corresponding subset are returned.

Note that the Brute Force algorithm is very time-consuming for problems with many states and becomes impractical in some cases. You may need more optimized algorithms, such as recursive or optimization algorithms, for more complex issues.

Another example of how to implement the above algorithm in the Python programming language

For example, suppose you have a list of objects and know each object’s weight and value. We aim to select a subset of items whose weight does not exceed the total allowed weight and maximize their value. Next, we examine how to implement the Brute Force algorithm :
Class Item:
    def __init__(self, weight, value):
        self.weight = weight
        self.value = value
def brute_force_knapsack(items, max_weight):
    best_value = float(‘-info)
    best_subset = []
    for i in range(2 ** len(items)):
        current_weight = 0
        current_value = 0
        current_subset = []
        for j in range(len(items)):
            if (i >> j) & 1:
                current_weight += items[j].weight
                current_value += items[j].value
                current_subset.append(items[j])
        if current_weight <= max_weight and current_value > best_value:
            best_value = current_value
            best_subset = current_subset
    return best_value, best_subset
# Example of using the Brute Force algorithm for the backpack problem
items = [
    Item(2, 10),
    Item(5, 20),
    Item(1, 8),
    Item(6, 15),
    Item(4, 12)
]
max_weight = 10
best_value, best_subset = brute_force_knapsack(items, max_weight)
print(“Best Value:”, best_value)
print(“Best Subset:”)
for item in best_subset:
    Print (“Weight:” item. weight, “Value:” item. value)

In this example, a knapsack problem is modeled. Each item has two attributes: “weight” and “value.” We aim to select a subset of items whose weight does not exceed the total allowed weight and maximize their value. The Brute Force algorithm examines all possible states, finds the best subset that satisfies the condition, has the maximum value, and displays the result.

Please note that the Brute Force algorithm has a long execution time and high memory consumption for problems with large items and weights. More optimal methods, such as recursive or optimization algorithms, are better in issues with more significant inputs.

Now, let us refer to another example.

For example, suppose you have a list of numbers and want to find a subset of these numbers that sum to a certain number. Here, the Brute Force algorithm can be used to find this subset. In the following, we will examine how to implement the Brute Force algorithm
def find_subset_with_sum(numbers, target_sum):
    subset_count = len(numbers)
    for i in range(2 ** subset_count):
        subset = [numbers[j] for j in range(subset_count) if (i & (1 << j))]
        if sum(subset) == target_sum:
            return subset
    return None
# Example of using the Brute Force algorithm to find a subset with a certain sum
numbers = [1, 2, 3, 4, 5]
target_sum = 9
result = find_subset_with_sum(numbers, target_sum)
If the result is None:
    print(“Subset with sum”, target_sum, “found:”, result)
Else:
    print(“No subset with sum”, target_sum, “found.”)

In this example, we have a list of numbers called numbers, and we want to find a subset of these numbers whose sum is equal to the given value target_sum. The brute force algorithm examines all possible states, fin, ds a subset that satisfies and returns t, he condition. The function returns None if there is no subset with the requested sum.

Note that the Brute Force algorithm can be time-consuming and inefficient for problems with large input sizes. In such cases, it may be necessary to use more optimal algorithms, such as recursive or optimization algorithms.