Making a secret message reader

Now… you COULD just write an if statement for every letter.

You COULD also write the decode_single_letter() in the same way.

But there is a better way! (There usually is!)

We know that if the user enters " 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ”
it should print
"#A8fZKnVv0Tme5Eh61QGdubFt4qBsgOWM9DjIrcLzlUJ3NSaX7wpoiC2xPYRkyH”.

Look at these two strings! The first has all the letters we might want to encode. The second has their encoded result - and importantly - that encode letter is in the SAME POSITION in the string.

So to encode a single letter, if we knew the position of that letter in the first string, we could get the character at that same position from the second string, and then simple return that as a result.

Hey, THAT almost sounds like code.

char encode_single_letter( char input ){
  int position = find_position( input, first_string );
  return( second_string.charAt( position ) );
}

Whoa! We now have a function that will work for any letter - and it’s only two lines of code long! All we need to do now, really, is write the function that finds the positions. But that seems like something that people might want to do a lot. Maybe there is already a function that does it.

At this point you Google it. “Processing String find”. Top result ==> https://processing.org/reference/String_indexOf_.html
Hey, that does what we want!

char encode_single_letter( char input ){
  int position = first_string.indexOf( input );
  if( position == -1 ) return '~'; // Didn't find a matching letter... Encode to a tilde.
  return( second_string.charAt( position ) );
}

Notice that I threw in a check for the situation in which the input letter was not found.

So now we can encode one letter. But the user can input MANY letters. Oh dear. Looks like it’s time to write our encode_string() function.

How will it possible work? Well, it will need to look at each letter in turn. For each letter, we will need to encode that letter. Then we will need to append that letter to a string that we will eventually return. Hey, that sounds like code!

start with an empty result string, so result is ""
for each letter {
  result = result + encode( this_letter );
}
return the result

And that’s all the help I am willing to provide. Try to edit the above procedure so it IS code. You know how a for loop works, right? If not, look in the reference and try it yourself first. You can find how many letters are in the user’s string too - you already know which function can get that for you.

Post the complete code of your attempt for more help. Please show us that you have put some serious effort into it - I’ve probably already helped you TOO much.

1 Like