Pattern Matching

Learn to identify similarities and patterns across different problems and solutions. Pattern matching is a fundamental computational thinking skill that helps you recognize when a new problem is similar to problems you’ve solved before.

Key Concept: Pattern matching involves identifying similarities, differences, and connections between problems, solutions, and data. This allows you to reuse successful approaches and avoid reinventing solutions.

What is Pattern Matching?

Pattern matching is the process of identifying regularities, similarities, and recurring structures in problems, data, or solutions. It’s about recognizing when something you’re facing is similar to something you’ve encountered before.

Core Elements of Pattern Matching

🔍 Recognition

Identifying when problems share similar structures or characteristics

🔗 Connection

Linking new problems to familiar patterns and existing solutions

📋 Classification

Grouping similar problems or data into categories based on shared features

Types of Patterns in Problem Solving

1. Problem Structure Patterns

Recognizing similar problem structures across different domains:

Pattern: Finding specific items in a collection

  • Finding a book in a library
  • Locating a file on a computer
  • Searching for a word in a document
  • Finding a contact in your phone

Common Solution Pattern:

  1. Define what you're looking for
  2. Determine where to search
  3. Choose a search strategy (linear, binary, etc.)
  4. Apply the search method
  5. Handle found/not found cases
Pattern: Arranging items in a specific order
  • Organizing books by author
  • Ranking students by grade
  • Arranging tasks by priority
  • Sorting files by date

Common Solution Pattern:

  1. Define the sorting criteria
  2. Choose comparison method
  3. Select sorting algorithm
  4. Apply systematic rearrangement
  5. Verify the result
Pattern: Finding the best solution among many possibilities
  • Finding the shortest route to work
  • Scheduling tasks to minimize time
  • Packing a suitcase efficiently
  • Budgeting money for maximum benefit

Common Solution Pattern:

  1. Define what "best" means
  2. Identify constraints
  3. Generate possible solutions
  4. Evaluate and compare options
  5. Select optimal solution
### 2. Data Patterns

Recognizing patterns in data helps predict behavior and make decisions:

Example: Website Traffic Analysis

Daily Visitors:
Monday:    1,200
Tuesday:   1,350
Wednesday: 1,400
Thursday:  1,450
Friday:    1,800
Saturday:    900
Sunday:      750

Patterns Identified:
- Weekday Pattern: Steady increase Mon-Thu
- Weekend Pattern: Significant drop Sat-Sun
- Peak Pattern: Friday has highest traffic
- Weekly Cycle: Pattern repeats each week

Applications:
- Staff scheduling based on expected traffic
- Server capacity planning
- Marketing campaign timing
- Content publishing schedule

3. Solution Patterns

Recognizing when similar solution strategies apply:

Divide and Conquer Pattern

When to Use: When you can break a problem into smaller, similar subproblems

Examples:

  • Organizing a large event → Break into smaller tasks (venue, catering, entertainment)
  • Learning a new language → Separate into vocabulary, grammar, pronunciation
  • Cleaning a house → Room by room approach
  • Debugging code → Isolate sections and test individually

Pattern Steps:

  1. Divide the problem into smaller subproblems
  2. Solve each subproblem independently
  3. Combine solutions to solve the original problem
Trial and Error Pattern

When to Use: When the solution space is small or when learning from failures is valuable

Examples:

  • Finding the right password combination
  • Adjusting recipe ingredients to taste
  • Troubleshooting technical problems
  • Learning a new skill through practice

Pattern Steps:

  1. Make an educated guess
  2. Test the solution
  3. Analyze the result
  4. Adjust based on feedback
  5. Repeat until successful
Template Pattern

When to Use: When you have a proven framework that can be adapted to similar problems

Examples:

  • Writing essays using introduction-body-conclusion structure
  • Following a recipe template for different dishes
  • Using project management frameworks for different projects
  • Applying coding design patterns to different programs

Pattern Steps:

  1. Identify the general template or framework
  2. Adapt the template to specific requirements
  3. Fill in the details specific to your problem
  4. Execute following the adapted template

Pattern Matching in Programming

Recognizing Code Patterns

 1# Pattern: Input Validation
 2# Appears whenever you need to check user input
 3
 4# Pattern Template:
 5def validate_input(user_input, validation_criteria):
 6    if not meets_criteria(user_input, validation_criteria):
 7        return error_message
 8    return processed_input
 9
10# Applied to different contexts:
11
12# Email validation
13def validate_email(email):
14    if "@" not in email or "." not in email:
15        return "Invalid email format"
16    return email.lower()
17
18# Age validation  
19def validate_age(age_str):
20    try:
21        age = int(age_str)
22        if age < 0 or age > 120:
23            return "Age must be between 0 and 120"
24        return age
25    except ValueError:
26        return "Age must be a number"
27
28# Password validation
29def validate_password(password):
30    if len(password) < 8:
31        return "Password must be at least 8 characters"
32    if not any(c.isdigit() for c in password):
33        return "Password must contain at least one number"
34    return password

Algorithm Patterns

 1# Pattern: Accumulator Pattern
 2# Used when building up a result over multiple iterations
 3
 4# Template:
 5result = initial_value
 6for item in collection:
 7    result = update_result(result, item)
 8return result
 9
10# Applied Examples:
11
12# Sum of numbers
13def sum_numbers(numbers):
14    total = 0  # initial_value
15    for num in numbers:
16        total = total + num  # update_result
17    return total
18
19# Build a string
20def create_greeting(names):
21    greeting = "Hello "  # initial_value
22    for name in names:
23        greeting = greeting + name + ", "  # update_result
24    return greeting[:-2]  # remove last comma
25
26# Count occurrences
27def count_vowels(text):
28    count = 0  # initial_value
29    for char in text:
30        if char.lower() in "aeiou":
31            count = count + 1  # update_result
32    return count

Practical Pattern Matching Exercises

Exercise 1: Identify the Pattern

For each scenario, identify what type of problem pattern it represents:

  1. Scenario: You need to find the best route from your home to three different stores, visiting each once.

    • Pattern Type: _______________
    • Similar Problems: _______________
  2. Scenario: You’re organizing your email inbox by creating folders and moving emails to appropriate categories.

    • Pattern Type: _______________
    • Similar Problems: _______________
  3. Scenario: You notice your monthly electricity bill follows a predictable pattern based on seasonal weather.

    • Pattern Type: _______________
    • Applications: _______________
Exercise 1 Solutions
  1. Optimization Pattern - Similar to traveling salesman problem, scheduling tasks, resource allocation
  2. Classification/Sorting Pattern - Similar to filing documents, organizing books, categorizing data
  3. Data Pattern Recognition - Applications include budgeting, energy planning, seasonal business forecasting

Exercise 2: Apply Solution Patterns

Choose the best solution pattern for each problem:

  1. Problem: Learning to play guitar

    • Options: Divide and Conquer, Trial and Error, Template Pattern
    • Best Choice: _______________
    • Reasoning: _______________
  2. Problem: Debugging a complex software issue

    • Options: Divide and Conquer, Trial and Error, Template Pattern
    • Best Choice: _______________
    • Reasoning: _______________
Exercise 2 Solutions
  1. Template Pattern + Divide and Conquer - Use proven learning methods (scales, chords, songs) and break into smaller skills
  2. Divide and Conquer - Isolate different parts of the system to identify where the bug occurs

Pattern Libraries for Programmers

Common Programming Patterns

When to Recognize: You need to repeat an action or process multiple items

Variations:

  • For Each: Process every item in a collection
  • While: Repeat until a condition is met
  • Counting: Repeat a specific number of times
  • Search: Repeat until you find what you're looking for

Pattern Recognition:

  • Keywords: "for each", "every", "all", "until", "while"
  • Context: Collections, lists, repetitive tasks
When to Recognize: Different actions based on different conditions

Variations:

  • If-Then: Simple decision making
  • If-Then-Else: Binary choices
  • Multiple Conditions: Several possible paths
  • Nested Conditions: Decisions within decisions

Pattern Recognition:

  • Keywords: "if", "when", "depending on", "in case of"
  • Context: Decision points, branching logic
When to Recognize: Converting data from one form to another

Variations:

  • Mapping: Transform each item individually
  • Filtering: Select items that meet criteria
  • Reducing: Combine many items into one result
  • Grouping: Organize items by shared characteristics

Pattern Recognition:

  • Keywords: "convert", "transform", "filter", "group", "combine"
  • Context: Data processing, format changes
## Building Your Pattern Library

Steps to Develop Pattern Recognition Skills

  1. Study Examples: Look at how similar problems are solved in different contexts
  2. Document Patterns: Keep notes on patterns you discover
  3. Practice Application: Try applying known patterns to new problems
  4. Reflect on Solutions: After solving problems, identify which patterns you used
  5. Build Templates: Create reusable templates for common patterns

Pattern Documentation Template

Pattern Name: _______________
Problem Type: _______________
When to Use: _______________
Key Characteristics:
- _______________
- _______________
- _______________

Solution Steps:
1. _______________
2. _______________
3. _______________

Examples:
- _______________
- _______________
- _______________

Variations:
- _______________
- _______________

Next Steps

Pattern matching becomes more powerful when combined with the other computational thinking skills:

  • With Decomposition: Break complex patterns into simpler components
  • With Abstraction: Focus on essential pattern features while ignoring irrelevant details
  • With Algorithms: Create step-by-step procedures for applying patterns

The more patterns you recognize and document, the faster you’ll be able to solve new problems by connecting them to familiar solutions.


← Previous: Abstraction Next: Algorithmic Design →