Matching The Alphanumerical Pattern In Matrix I In C++ - C++ Programming Tutorial
C++ Course / Design Patterns / Matching The Alphanumerical Pattern In Matrix I In C++

Matching The Alphanumerical Pattern In Matrix I In C++

BLUF: Mastering Matching The Alphanumerical Pattern In Matrix I In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Matching The Alphanumerical Pattern In Matrix I In C++

C++ is renowned for its efficiency. Learn how Matching The Alphanumerical Pattern In Matrix I In C++ enables low-level control and high-performance computing in the tutorial below.

Introduction:

Alphanumerical sequences break down their organized grid to merge letters and numbers like puzzles. These patterns typically demand developers to devise algorithms for recognizing and generating patterns. For C++ programmers, unraveling these sequences not only enhances coding proficiency but also boosts logical reasoning and algorithmic comprehension. This tutorial predominantly delves into a specific alphanumeric pattern sourced from Matrix I and demonstrates its C++ implementation.

Problem Statement:

Consider the following alphanumerical pattern:

Example

1A 2B 3C 4D 5E
2F 3G 4H 5I 6J
3K 4L 5M 6N 7O
4P 5Q 6R 7S 8T
5U 6V 7W 8X 9Y

The task is to write a C++ program that generates this pattern. The pattern follows a specific rule:

  • The first number in each row should increase by 1.
  • Each column starts with an alphabet letter which proceeds alphabetically.
  • These numbers and letters have been mixed together as shown.
  • Approach:

In order to generate the alphanumerical pattern, we can follow a structured approach in C++. Here are the steps we will take:

  • Declare variables and constants: We need to declare variables for keeping track of how many rows or columns are allocated so we can use them later while constants are required for defining the size of the pattern and range of characters used.
  • Write nested loops: To generate pattern elements, the nest loop will be written using increased loops over rows then columns.
  • Calculate and print out the pattern elements: In between those brackets, numbers & letters are determined subjecting themselves under specific rules of that bidirectional trend then outputting into that targeted sequence.
  • Implementation in C++ (Program 1):

Let's now translate the approach into C++ code:

Example

#include <iostream>
using namespace std;

int main() {
    const int rows = 5;
    const int cols = 5;
    char letter = 'A';

    for (int i = 0; i < rows; i++) {
        int number = i + 1;
        for (int j = 0; j < cols; j++) {
            if (j == 0) {
                cout << number;
            } else {
                cout << letter++;
            }
            cout << " ";
        }
        letter = 'A'; // Reset letter for the next row
        cout << endl;
    }

    return 0;
}

Output:

Output

1 A B C D 
2 A B C D 
3 A B C D 
4 A B C D 
5 A B C D

Explanation:

In this C++ program:

  1. Initialization:
  • The first task of the program is to initialize the pattern constants: rows and cols.
  • Also the letter gets initialized by 'A' , which is the starting character of the pattern.
  1. Outer Loop (Rows):
  • In this loop, the program starts from 0 which is the index of first row and stops at rows - 1 which represents the last row.
  • For each row, it calculates a number that corresponds with its position in the list. The pattern begins with 1 and adds one to every other line thus uses number = i + 1 where i refers to the current row index.
  1. Inner Loop (Columns):
  • Within this outer loop for rows, there is an inner loop for columns. It goes through all columns for a given row starting at column zero and going until cols-1 for that last column.
  • Inside this loop, there is a test if "current column" equals "first column" (index 0). In case it does print out this calculated "number" otherwise prints out the current "letter" then increases the letter by one alphabet letter.
  1. Printing the Pattern:
  • Numbers and letters are printed as per rule of pattern once every column has been traversed in this inside loop.
  • After printing all elements of the current row, the program moves to the next line (endl), indicating the end of that row.
  1. Resetting Letter:
  • Before moving to the next row in the outer loop, the program resets the letter variable back to 'A'. This ensures that each new row starts with the letter 'A' again, following the pattern's structure.

By iterating through the aforementioned instructions for every row and column, the software produces the intended alphanumeric arrangement as outlined in Matrix I.

Time Complexity:

This program's time complexity is determined by two nested loops, one for rows and the other for columns, each running from 0 to a fixed value (rows and columns).

Consequently, the time complexity can be denoted as O(rows * columns).

Space Complexity:

  • The program uses a few variables such as rows, cols, letter, number, i and j which all require constant space regardless of the input size.
  • Additionally, the program prints the pattern directly to the standard output without storing it in any data structure.
  • Hence, the space complexity remains constant and it is denoted by O(1).
  • Program 2:

Let's consider a different scenario to demonstrate how to identify the alphanumeric pattern within matrix I in the C++ programming language.

Example

#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;

// Function to check if the pat matches at a given
// starting position in the mat.
bool matchPattern(const vector<vector<int> >& mat,
                  const vector<string>& pat, int row,
                  int col)
{
    const int m1 = mat.size(), n1 = mat[0].size(),
              m2 = pat.size(), n2 = pat[0].length();

    // Create a map to store the mapping between characters
    // in the pat and their corresponding values in the
    // mat.
    unordered_map<char, int> charToValue;

    // Iterate over the rows and columns of the pat.
    for (int i = 0; i < m2; ++i) {
        for (int j = 0; j < n2; ++j) {
            const char c = pat[i][j];
            const int v = mat[row + i][col + j];

            // Check if the character is a digit.
            if (isdigit(c)) {
                // If the character is a digit, it must
                // match the corresponding value in the
                // mat.
                if (c != v + '0') {
                    return false;
                }
            }
            else {
                // If the character is not a digit, it must
                // have been mapped to a value in the mat
                // previously.
                if (charToValue.count(c)) {
                    // If the character has been mapped to a
                    // different value, it's a mismatch.
                    if (charToValue[c] != v) {
                        return false;
                    }
                }
                else {
                    // If the character has not been mapped
                    // before, map it to the current value.
                    charToValue[c] = v;
                }
            }
        }
    }

    return true; // Return true if the pat matches at
                 // the given starting position.
}

vector<int> findPattern(vector<vector<int> >& mat,
                        vector<string>& pat)
{
    const int m1 = mat.size(), n1 = mat[0].size(),
              m2 = pat.size(), n2 = pat[0].length();

    // Iterate over all possible starting positions for the
    // pat in the mat.
    for (int i = 0; i + m2 <= m1; ++i) {
        for (int j = 0; j + n2 <= n1; ++j) {
            // Check if the pat matches at the current
            // starting position.
            if (matchPattern(mat, pat, i, j)) {
                return {
                    i, j
                }; // Return the starting position if a
                   // match is found.
            }
        }
    }

    return { -1,
             -1 }; // Return {-1, -1} if no match is found.
}

// Main code
int main()
{
    vector<vector<int> > mat
        = { { 1, 2, 2 }, { 2, 2, 3 }, { 2, 3, 3 } };
    vector<string> pat = { "ab", "bb" };
    ;

    // Call the findPattern method to find the starting
    // position of the pat in the mat.
    vector<int> result = findPattern(mat, pat);

    // Print the result.
    cout << "Starting position of the pat: (" << result[0]
         << ", " << result[1] << ")" << endl;

    return 0;
}

Output:

Output

Starting position of the pat: (0, 0)

Explanation:

  1. Iterate over possible starting positions:
  • In this example, loop through all possible starting positions for the pat in the mat.
  1. For each starting position:
  • Call the matchPattern function to check if the pat matches at that position.
  • If the pat matches, return the starting position.
  • If no match is found, return {-1, -1}.
  • In matchPattern function, iterate over pat rows and columns:
  • Loop through each row and column of the pat.
  1. For each character in the pat:
  • If the character is a digit: Check if the corresponding value in the mat matches the digit.
  • If the character is not a digit: Check if the character has been mapped to a value in the mat previously.
  • If not, map the character to the corresponding value in the mat.
  • If the character has been mapped to a different value, return false.
  • If all characters in the pat match, return true.
  • Conclusion:

In summary, we have explored the process of creating an alphanumeric pattern Matrix I through the provided C++ code. This task showcases the utilization of nested loops and control mechanisms in C++, along with the programming principles employed to tackle intricate pattern challenges. Adapting this pattern or engaging with more intricate patterns can enhance programming abilities and foster innovative problem-solving approaches.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience