Java Code to Count Possible Decoding Of A Given Digit Sequence

Possible decoding of a given digit sequence in Java

Count Possible Decoding Of A Given Digit Sequence in Java

Here we will discuss how to count all the possible decoding of a given digit sequence in Java. Before counting the number of decodings first let’s see how the numbers are assumed to be coded.

1 = A, 2 = B, 3 = C, . . . . , 26 = Z.
The decoding programs are the most possible questions asked and are largely practiced in Java programming. The program counts the number of possible decodings of the entered digit by the user of the given sequence.

For example, if the digit sequence is “12” then there are two possible decodings for this – One of them is ‘AB’ when we decode 1 as ‘A’ and 2 as ‘B’. Now we can also decode this digit sequence “12” as ‘L’ when we decode digits 1 and 2 taken together as an integer 12.

Now let’s take another example for reference,

Sequence = 131

  • Possible decoding (1, 3, 1,)    = ACA
  • Possible decoding (13, 1)   = MA
    So, the total possible decodings of sequence 131 is 2.

 

Algorithm:-

  • Step 1: Start
  • Step 2: input given
  • Step 3: Set count = 0
  • Step 4: If the last number is not a zero, then return for the next remaining (n-1) numbers and add the results then to the total count.
  • Step 5: If the last two digits form a valid variable (or smaller than 27), return for the remaining (n-2) numbers and add the outcome to the total calculation.
  •  Step 6: Stop
Count Possible Decoding java

Code to count Possible decoding of a given digit sequence in Java

import java.io.*;

class PREPINSTA{

    public static int cnt_decoding_digits(char[] dig, int a)

    {

        int cnt[] = new int[a+ 1];

         cnt[0] = 1;

         cnt[1] = 1;

         for (int k = 2; k <= a; k++) 

         { 

             cnt[k] = 0; 

             cnt[k] = cnt[k-1];

             if (dig[k-2] == '1' || (dig[k-2] == '2' && dig[k-1] < '7') )

                  cnt[k] += cnt[k-2];

         }

         return cnt[a];

    }

    public static void main (String[] args) {

       String s="123";

       char[] dig= s.toCharArray();

       System.out.println(cnt_decoding_digits(dig, 6));

        }

    }

Output:

3