Program to decode a given message in C++



Suppose we are given an encoded message that is a string of integer numbers. Now, these integer numbers can be mapped to a specific letter in the alphabet. a is mapped to 1, b is mapped to 2, c is mapped to 3, and so on. There is also a character '*' that can be in the message and that can be mapped to any of the numbers from 1 to 9. So given a message 'input', we have to find out how many ways it can be decoded.

So, if the input is like input = "18", then the output will be 2.

The message can be decoded to "ah", as 1 maps to "a" and 8 maps to "h". Also, the number can map to "r", as 18 maps to "r". So. there are a total of 2 ways that the input can be decoded.

To solve this, we will follow these steps −

  • n := length of input
  • Define an array dynArr of size: n+1 and initialize it with zeroes
  • p := 1
  • k := '0'
  • dynArr[0] := 1
  • for initialize i := 1, when i <= n, update (increase i by 1), do −
    • c := input[i - 1]
    • if c is same as 0 and not (k is same as '1' or k is same as '2' or k is same as '*'), then −
      • p := 0
      • Come out from the loop
    • if input[i - 1] is same as '*', then −
      • dynArr[i] := (dynArr[i - 1] * 9) mod m
      • if k is same as '1' or k is same as '*', then −
        • dynArr[i] := (dynArr[i] + dynArr[i - 2] * 9) mod m
      • if k is same as '2' or k is same as '*', then −
        • dynArr[i] := (dynArr[i] + (dynArr[i - 2] * 6) mod m) mod m
    • otherwise,
      • if c is not equal to '0', then −

        • if k is same as '1' or k is same as '*', then −
          • dynArr[i] := (dynArr[i] + dynArr[i - 2]) mod m
        • if (k is same as '2' or k is same as '*') and input[i - 1] <= '6', then −
          • dynArr[i] := (dynArr[i] + (dynArr[i - 2]) mod m) mod m
    • k := c
  • if p is non-zero, then return dynArr[n], otherwise return 0

Example

Let us see the following implementation to get better understanding −

Open Compiler
#include<bits/stdc++.h> using namespace std; const long m = 1e9 + 7; int solve(string input) { int n = input.length(); long long dynArr[n + 1] = {0}; bool p = 1; char k = '0'; dynArr[0] = 1; for (int i = 1; i <= n; i++) { char c = input[i - 1]; if (c == 0 && !(k == '1' || k == '2' || k == '*')) { p = 0; break; } if (input[i - 1] == '*') { dynArr[i] = (dynArr[i - 1] * 9) % m; if (k == '1' || k == '*') dynArr[i] = (dynArr[i] + dynArr[i - 2] * 9) % m; if (k == '2' || k == '*') dynArr[i] = (dynArr[i] + (dynArr[i - 2] * 6) % m) % m; } else { if (c != '0') dynArr[i] = dynArr[i - 1]; if (k == '1' || k == '*') dynArr[i] = (dynArr[i] + dynArr[i - 2]) % m; if ((k == '2' || k == '*') && input[i - 1] <= '6') dynArr[i] = (dynArr[i] + (dynArr[i - 2]) % m) % m; } k = c; } return p ? dynArr[n] : 0; } int main() { cout<< solve("18") <<endl; return 0; }

Input

18

Output

2
Updated on: 2021-10-19T10:59:55+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements