Atbash Cipher not Working

This seems pretty straight forward but I am not even passing the first test which is yes. It seems to work in my local environment but not in exercism. Am I missing something obvious?

text="${2}"
length=${#text}
message=""
declare -A dictionary
alphabet=$(echo {a..z} | tr -d ' ')
j=0
for i in {z..a}; do dictionary[$i]="${alphabet:$j:1}";  ((j++)) ; done

for ((i=0; i < $length; i++)); 
do 
originalLetter=${text:$i:1}; 

convertedLetter=$dictionary[$originalLetter]; 

message="${message}${convertedLetter}"; 

done

echo "$message"

Are you running the unit tests locally or testing some other way?

I tested in my local shell by doing text=“yes” before running my code.

Not that it can always be trusted, but I also asked chatGPT if my code should work and it said yes. :man_shrugging:

If you haven’t run the tests, there’s no reason to assume the code does anything close to what the tests actually run and check.

What’s the test output?

text="${2}"

This means that the programs uses the 2nd argument for the value. The tests invoke the program like

bash abash_cipher.sh encode "yes"

Setting the text variable in your own shell will have no effect on the program: in the program text gets the value of the 2nd argument, or the empty string if the program doesn’t get 2 args.


Invoking that on your code outputs

[y][e][s]

This line

convertedLetter=$dictionary[$originalLetter]

is missing the braces for the variable expansion:

convertedLetter=${dictionary[$originalLetter]}
# ...............^...........................^

Additionally, your code does not handle uppercase letters, and it does not add spaces into the output for encoding.

Sorry, I think I was unclear. I was doing the commands directly in shell, not a script. I was doing text=yes because correct me if I’m wrong, that would be the same as myscript.bat encode "yes" + text=${1}.

It was simply a fast way of testing.

convertedLetter=${dictionary[$originalLetter]}, thank you, this was the fix. I will have to do more learning on variable expansion because it’s often times not clear to me when braces are needed.

And yes I will definitely add the bits to handle case, punctuation, spaces, etc. Was just starting with basic functionality.

1 Like

The sooner you run the unit tests, the faster you’ll be able to see what’s actually working as expected and, if not, how it differs from expectations. You can run tests before you even start writing any code!