Question

In: Computer Science

P-3.40 Implement a class, SubstitutionCipher, with a constructor that takes a string with the 26 uppercase...

P-3.40 Implement a class, SubstitutionCipher, with a constructor that takes a string with the 26 uppercase letters in an arbitrary order and uses that as the encoder for a cipher (that is, A is mapped to the first character of the parameter, B is mapped to the second, and so on.) You should derive the decoding map from the forward version.

P-3.41 Redesign the CaesarCipher class as a subclass of the SubstitutionCipher from the previous problem.

P-3.42 Design a RandomCipher class as a subclass of the SubstitutionCipher from Exercise P-3.40, so that each instance of the class relies on a random permutation of letters for its mapping.

Solutions

Expert Solution

Part A

public class SubstitutionCipher {

   static final int MAX = 26;
   protected char[] encoder; // Encryption array
   protected char[] decoder; // Decryption array
  
   /**
   * Constructor
   */
   public SubstitutionCipher() {
       this.encoder = new char[MAX]; // Encryption array
       this.decoder = new char[MAX]; // Decryption array
   }
  
   /**
   * Sets the encoder string and generates the decoder
   * @param encoderString
   */
   public void setEncoder (String encoderString) {
       this.encoder = encoderString.toCharArray();
      
       // Generate decoder
       for (int i = 0; i < MAX; i++) {
           char ch = (char)('A' + i);   // For each iteration ch will hold a value from A - Z
           // Find ch in the encoderString
           int pos = encoderString.indexOf(ch);
           // If pos is not found display error
           if (pos == -1) {
               System.out.println("Invalid encoder string");
               System.exit(1);
           }
          
           // If index is found
           // get the char at the pos in the original alphabet order
           // assign the char to decoder[i]
           this.decoder[i] = (char)('A' + pos);
       }
   }
  
   /**
   * Returns String representing encrypted message.
   */
   public String encrypt(String message) {
       return transform(message, encoder); // use encoder array
   }

   /**
   * Returns decrypted message given encrypted secret.
   */
   public String decrypt(String secret) {
       return transform(secret, decoder); // use decoder array
   }

   /**
   * Returns transformation of original String using given code.
   */
   private String transform(String original, char[] code) {
       char[] msg = original.toCharArray();
       for (int k = 0; k < msg.length; k++)
           if (Character.isUpperCase(msg[k])) { // we have a letter to change
               int j = msg[k] - 'A'; // will be value from 0 to 25
               msg[k] = code[j]; // replace the character
           }
       return new String(msg);
   }

   public static void main(String[] args) {
      
       String encoderString = new String("SIEXHVGFUDJTRZNPCLQBKAYWOM");
      
       // Create SubstitutionCipher object
       SubstitutionCipher subCipher = new SubstitutionCipher();
       // Set encoder
       subCipher.setEncoder(encoderString);
      
       System.out.println("Encryption code = " + new String(subCipher.encoder));
       System.out.println("Decryption code = " + new String(subCipher.decoder));
       String message = "THE EAGLE IS IN PLAY; MEET AT JOE'S.";
       String coded = subCipher.encrypt(message);
       System.out.println("Secret: " + coded);
       String answer = subCipher.decrypt(coded);
       System.out.println("Message: " + answer);
   }
}

PART B

public class CaesarCipherRedesign extends SubstitutionCipher {

   /**
   * Constructor that initializes the encryption and decryption arrays
   */
   public CaesarCipherRedesign(int rotation) {
       // For upper case
       for (int k = 0; k < 26; k++) {
           encoder[k] = (char) ('A' + (k + rotation) % super.MAX);
       }
   }

   public static void main(String[] args) {
       CaesarCipher cipher = new CaesarCipher(1);
       System.out.println("Encryption code = " + new String(cipher.encoder));
       System.out.println("Decryption code = " + new String(cipher.decoder));
       String message = "THE EAGLE IS IN PLAY; MEET AT JOE'S.";
       String coded = cipher.encrypt(message);
       System.out.println("Secret: " + coded);
       String answer = cipher.decrypt(coded);
       System.out.println("Message: " + answer); // should be plain text again
   }
}

I hope this answer helps you please upvote if both the parts helped you!!!!


Related Solutions

C++ ONLY! Implement the find function for the List class. It takes a string as an...
C++ ONLY! Implement the find function for the List class. It takes a string as an argument and returns an iterator to a matching node. If no matching node, it returns a null iterator. #include <iostream> #include <cstddef> #include <string> using Item = std::string; class List { private: class ListNode { public: Item item; ListNode * next; ListNode(Item i, ListNode *n=nullptr) { item = i; next = n; } };    ListNode * head; ListNode * tail;    public: class...
java NetBeans Class Entry: Implement the class Entry that has a name (String), phoneNumber (String), and...
java NetBeans Class Entry: Implement the class Entry that has a name (String), phoneNumber (String), and address (String). Implement the initialization constructor . Implement the setters and getters for all attributes. Implement the toString() method to display all attributes. Implement the equals (Entry other) to determine if two entries are equal to each other. Two entries are considered equal if they have the same name, phoneNumber, and address. Implement the compareTo (Entry other) method that returns 0 if the two...
Please write code in java and comment . thanks Item class A constructor, with a String...
Please write code in java and comment . thanks Item class A constructor, with a String parameter representing the name of the item. A name() method and a toString() method, both of which are identical and which return the name of the item. BadAmountException Class It must be a RuntimeException. A RuntimeException is a subclass of Exception which has the special property that we wouldn't need to declare it if we need to use it. It must have a default...
Complete the definitions for the following prototypes in the Time class: Time(std::string) – a constructor that...
Complete the definitions for the following prototypes in the Time class: Time(std::string) – a constructor that will take in a string with the format h:m:s and parse the h, m and s into separate int values that can be used to set the time of a new time object. int getSecond() const - return the value of the second void setSecond() - set the value of the second, making sure the new second value is valid before changing it. std::string...
Create a class named BankAccount, containing: a constructor accepting a String corresponding to the name of...
Create a class named BankAccount, containing: a constructor accepting a String corresponding to the name of the account holder. a method, getBalance, that returns a double corresponding to the account balance. a method withdraw that accepts a double, and deducts the amount from the account balance. Write a class definition for a subclass, CheckingAccount, that contains: a boolean instance variable, overdraft. (Having overdraft for a checking account allows one to write checks larger than the current balance). a constructor that...
IN JAVA PLEASE The Palindrome class will have a single constructor that accepts a String argument...
IN JAVA PLEASE The Palindrome class will have a single constructor that accepts a String argument and checks to see if the String is a palindrome. If it is a palindrome it will store the palindrome and the original String as state values. If is not a palindrome it will throw a “NotPalindromeError” and not finish the creation of the new Palindrome object. The constructor will use a single stack to evaluate if the String is a palindrome. You must...
class DoubleLinkedList { public: //Implement ALL following methods. //Constructor. DoubleLinkedList(); //Copy constructor. DoubleLinkedList(const DoubleLinkedList & rhs);...
class DoubleLinkedList { public: //Implement ALL following methods. //Constructor. DoubleLinkedList(); //Copy constructor. DoubleLinkedList(const DoubleLinkedList & rhs); //Destructor. Clear all nodes. ~DoubleLinkedList(); // Insert function. Returns true if item is inserted, // false if the item it a duplicate value bool insert(int x); // Removes the first occurrence of x from the list, // If x is not found, the list remains unchanged. void remove(int x); //Assignment operator. const DoubleLinkedList& operator=(const DoubleLinkedList & rhs); private: struct node{ int data; node* next;...
C. Design a RandomCipher class as a subclass of the substitutionCipher from exercise P-3.40, so that...
C. Design a RandomCipher class as a subclass of the substitutionCipher from exercise P-3.40, so that each instance of the class relies on a random permutation of letters for its mapping.
JAVA The class will have a constructor BMI(String name, double height, double weight). The class should...
JAVA The class will have a constructor BMI(String name, double height, double weight). The class should have a public instance method, getBMI() that returns a double reflecting the person's BMI (Body Mass Index = weight (kg) / height2 (m2) ). The class should have a public toString() method that returns a String like Fred is 1.9m tall and is 87.0Kg and has a BMI of 24.099722991689752Kg/m^2 (just print the doubles without special formatting). Implement this class (if you wish you...
Implement two functions in C language: stringLength() - Takes a pointer to a string, and a...
Implement two functions in C language: stringLength() - Takes a pointer to a string, and a pointer to an int variable. It computes the length of the string and updates the int variable with the length. stringCopy() - Copies one string onto another using pointers #include<stdio.h> #define MAX_STR_LEN 2048 void stringLength(char *str, int *len) { // This function computes the length of the string // at the address in the pointer *str. Once the length // has been determined, it...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT