Download Analog and digital C - Brute force and more Study notes Digital & Analog Electronics in PDF only on Docsity! Brute Force Brute Force A straightforward approach, usually based directly on the problem’s statement and definitions of the concepts involved Brute-Force String Matching • pattern: a string of m characters to search for • text: a (longer) string of n characters to search in • problem: find a substring in the text that matches the pattern Brute-force algorithm Step 1 Align pattern at beginning of text Step 2 Moving from left to right, compare each character of pattern to the corresponding character in text until • all characters are found to match (successful search); or • a mismatch is detected Step 3 While pattern is not found and the text is not yet exhausted, realign pattern one position to the right and repeat Step 2 Examples of Brute-Force String Matching 1. Pattern: 001011 Text: 10010101101001100101111010 2. Pattern: happy Text: It is never too late to have a happy childhood. Pseudocode and Efficiency Time efficiency:Θ(mn) comparisons (in the worst case) Closest-Pair Problem Find the two closest points in a set of n points (in the two-dimensional Cartesian plane). Brute-force algorithm Compute the distance between every pair of distinct points and return the indexes of the points for which the distance is the smallest. Closest-Pair Brute-Force Algorithm (cont.) Efficiency: How to make it faster? Θ(n^2) multiplications (or sqrt) Using divide-and-conquer! Brute-Force Strengths and Weaknesses • Strengths – wide applicability – simplicity – yields reasonable algorithms for some important problems (e.g., matrix multiplication, sorting, searching, string matching) • Weaknesses – rarely yields efficient algorithms – some brute-force algorithms are unacceptably slow – not as constructive as some other design techniques TSP by Exhaustive Search Tour Cost a→b→c→d→a 2+3+7+5 = 17 a→b→d→c→a 2+4+7+8 = 21 a→c→b→d→a 8+3+4+5 = 20 a→c→d→b→a 8+7+4+2 = 21 a→d→b→c→a 5+4+3+8 = 20 a→d→c→b→a 5+7+3+2 = 17 Efficiency: Θ((n-1)!) Example 2: Knapsack ProblemGiven n items: – weights: w1 w2 … wn – values: v1 v2 … vn – a knapsack of capacity W Find most valuable subset of the items that fit into the knapsack Example: Knapsack capacity W=16 item weight value 1 2 $20 2 5 $30 3 10 $50 4 5 $10 Knapsack Problem by Exhaustive SearchSubset Total weight Total value {1} 2 $20 {2} 5 $30 {3} 10 $50 {4} 5 $10 {1,2} 7 $50 {1,3} 12 $70 {1,4} 7 $30 {2,3} 15 $80 {2,4} 10 $40 {3,4} 15 $60 {1,2,3} 17 not feasible {1,2,4} 12 $60 {1,3,4} 17 not feasible {2,3,4} 20 not feasible {1,2,3,4} 22 not feasibleEfficiency: Θ(2^n)