Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of rootulp

rootulp's solution

to Atbash Cipher in the Java Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Create an implementation of the atbash cipher, an ancient encryption system created in the Middle East.

The Atbash cipher is a simple substitution cipher that relies on transposing all the letters in the alphabet such that the resulting alphabet is backwards. The first letter is replaced with the last letter, the second with the second-last, and so on.

An Atbash cipher for the Latin alphabet would be as follows:

Plain:  abcdefghijklmnopqrstuvwxyz
Cipher: zyxwvutsrqponmlkjihgfedcba

It is a very weak cipher because it only has one possible key, and it is a simple monoalphabetic substitution cipher. However, this may not have been an issue in the cipher's time.

Ciphertext is written out in groups of fixed length, the traditional group size being 5 letters, and punctuation is excluded. This is to make it harder to guess things based on word boundaries.

Examples

  • Encoding test gives gvhg
  • Decoding gvhg gives test
  • Decoding gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt gives thequickbrownfoxjumpsoverthelazydog

Java Tips

Since this exercise has difficulty 5 it doesn't come with any starter implementation. This is so that you get to practice creating classes and methods which is an important part of programming in Java. It does mean that when you first try to run the tests, they won't compile. They will give you an error similar to:

 path-to-exercism-dir\exercism\java\name-of-exercise\src\test\java\ExerciseClassNameTest.java:14: error: cannot find symbol
        ExerciseClassName exerciseClassName = new ExerciseClassName();
        ^
 symbol:   class ExerciseClassName
 location: class ExerciseClassNameTest

This error occurs because the test refers to a class that hasn't been created yet (ExerciseClassName). To resolve the error you need to add a file matching the class name in the error to the src/main/java directory. For example, for the error above you would add a file called ExerciseClassName.java.

When you try to run the tests again you will get slightly different errors. You might get an error similar to:

  constructor ExerciseClassName in class ExerciseClassName cannot be applied to given types;
        ExerciseClassName exerciseClassName = new ExerciseClassName("some argument");
                                              ^
  required: no arguments
  found: String
  reason: actual and formal argument lists differ in length

This error means that you need to add a constructor to your new class. If you don't add a constructor, Java will add a default one for you. This default constructor takes no arguments. So if the tests expect your class to have a constructor which takes arguments, then you need to create this constructor yourself. In the example above you could add:

ExerciseClassName(String input) {

}

That should make the error go away, though you might need to add some more code to your constructor to make the test pass!

You might also get an error similar to:

  error: cannot find symbol
        assertEquals(expectedOutput, exerciseClassName.someMethod());
                                                       ^
  symbol:   method someMethod()
  location: variable exerciseClassName of type ExerciseClassName

This error means that you need to add a method called someMethod to your new class. In the example above you would add:

String someMethod() {
  return "";
}

Make sure the return type matches what the test is expecting. You can find out which return type it should have by looking at the type of object it's being compared to in the tests. Or you could set your method to return some random type (e.g. void), and run the tests again. The new error should tell you which type it's expecting.

After having resolved these errors you should be ready to start making the tests pass!

Running the tests

You can run all the tests for an exercise by entering

$ gradle test

in your terminal.

Source

Wikipedia http://en.wikipedia.org/wiki/Atbash

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

AtbashTest.java

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class AtbashTest {

    private Atbash atbash;

    @Before
    public void setup() {
        atbash = new Atbash();
    }

    @Test
    public void testEncodeYes() {
        assertEquals("bvh", atbash.encode("yes"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testEncodeNo() {
        assertEquals("ml", atbash.encode("no"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testEncodeOmgInCapital() {
        assertEquals("lnt", atbash.encode("OMG"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testEncodeOmgWithSpaces() {
        assertEquals("lnt", atbash.encode("O M G"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testEncodeMindBlowingly() {
        assertEquals("nrmwy oldrm tob", atbash.encode("mindblowingly"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testEncodeNumbers() {
        assertEquals("gvhgr mt123 gvhgr mt", atbash.encode("Testing,1 2 3, testing."));
    }

    @Ignore("Remove to run test")
    @Test
    public void testEncodeDeepThought() {
        assertEquals("gifgs rhurx grlm", atbash.encode("Truth is fiction."));
    }

    @Ignore("Remove to run test")
    @Test
    public void testEncodeAllTheLetters() {
        assertEquals("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt",
                atbash.encode("The quick brown fox jumps over the lazy dog."));
    }

    @Ignore("Remove to run test")
    @Test
    public void testDecodeExercism() {
        assertEquals("exercism", atbash.decode("vcvix rhn"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testDecodeASentence() {
        assertEquals("anobstacleisoftenasteppingstone", atbash.decode("zmlyh gzxov rhlug vmzhg vkkrm thglm v"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testDecodeNumbers() {
        assertEquals("testing123testing", atbash.decode("gvhgr mt123 gvhgr mt"));
    }

    @Ignore("Remove to run test")
    @Test
    public void testDecodeAllTheLetters() {
        assertEquals("thequickbrownfoxjumpsoverthelazydog",
                atbash.decode("gsvjf rxpyi ldmul cqfnk hlevi gsvoz abwlt"));
    }

}
public class Atbash {

  private static final String PLAIN = "abcdefghijklmnopqrstuvwxyz";
  private static final String CIPHER = "zyxwvutsrqponmlkjihgfedcba";
  private static final int GROUP_SIZE = 5;

  public static String encode(String input) {

    // clean input
    String str = input.toLowerCase().replaceAll("[^\\w\\d]", "");
    String result = "";

    for (int i = 0, n = str.length(); i < n; i++) {

      // add space after every GROUP_SIZE num of chars
      if (i != 0 && i % GROUP_SIZE == 0) { result += " "; }

      result += cipherChar(str.charAt(i));
    }

    return result;
  }

  private static char cipherChar(char c) {
    int index = PLAIN.indexOf(c);

    // return original char if it doesn't exist in PLAIN (i.e nums)
    return index >= 0 ? CIPHER.charAt(index) : c;
  }

}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other peopleโ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?