Website-Icon DED9

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:

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:

Disadvantages:

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:

2. Execution time:

3. Optimism:

4. Computational complexity:

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.

Die mobile Version verlassen