Home > database >  decoding message using c
decoding message using c

Time:12-16

I was solving a codewars problem called "decoding a message" using C.

My code passed the sample tests but can't pass the random tests as it adds random chars after the required chars like in the image enter image description here

What's the problem here?

problem's link : [https://www.codewars.com/kata/565b9d6f8139573819000056]

#include <string.h>
#include <ctype.h>

char *decode (const char *encoded, char *decoded)
{
  for (int i = 0; i < strlen(encoded); i  )
  {
    if (isalpha(encoded[i]))
    {
      if (encoded[i] <= 109)
      {
          decoded[i] = encoded[i]   25 - ((encoded[i] - 'a')*2);  
      }
      else if (encoded[i] >= 110)
      {
          decoded[i] = encoded[i] - 25   (('z' - encoded[i])*2);
      } 
    }
    else
    {
      decoded[i] = encoded[i];
    }
  }
    return decoded; // return it
}

CodePudding user response:

As indicated in the comments, the symptom described by the OP suggests the receiving buffer is not terminated properly to make a C string.

Further, one should avoid using "magic numbers" like 109 and 110 in code... What do those numbers mean?? They certainly won't work if the constraint of being "all lowercase" is lifted. Would one then copy/paste/adapt many lines of code merely to deal with both upper and lower case alphabets?

Below is LESS code that not only deals with the OP problem (unterminated string) but also deals with both upper and lower case letters (recognising that 'case' would weaken any encryption. Included here to demonstrate technique, only.)

Have fun with these learning challenges.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

char *decode( const char *s, char *d ) {
    for( size_t i = 0; ( d[i] = s[i] ) != '\0'; i   ) { // copy every byte
        if( isalpha( d[i] ) ) { // transform needed ?
            char c = islower( d[i] ) ? 'a' : 'A'; // basis to transpose ASCII char to 0-25
            d[i] = (char)( c   ( 25 - ( d[i] - c ) ) ); // 0->25 ==> 25->0
        }
    }
    return d; // return it
}

int main() {
    char *hidden = "R slkv MLYLWB wvxlwvh gsrh nvhhztv";
    char buf[ 128 ];

    printf( "%s\n%s\n", hidden, decode( hidden, buf ) );
    return 0;
}
R slkv MLYLWB wvxlwvh gsrh nvhhztv
I hope NOBODY decodes this message

If any of this is unclear, please post a question below...

  • Related