Question

In: Computer Science

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.

Solutions

Expert Solution

#include <iostream>

#include <string>

#include <ctime>

#include <stdlib.h>

#include <vector>

using namespace std;

class SubstitutionCipher

{

public:

    //Define your key which is a permutation of 26 alphabets

    string key;

    SubstitutionCipher()

    {

    }

    //Constructor to create an instance which initializes the key with the given permutation

    SubstitutionCipher(string k)

    {

        key = k;

    }

    //function to encode a string

    string encode(string data)

    {

        //initialize encoded data

        string encodedData = data;

        //replace each character in encodedData with the corresponding mapped data in key. We subtract a char with 'A' to get its position

        for (int i = 0; i < data.length(); i++)

            encodedData[i] = key.at(data.at(i) - 'A');

        //return the encoded data

        return encodedData;

    }

    //function to decode a string

    string decode(string data)

    {

        //initialize decoded data

        string decodedData = data;

        //replace each character in decodedData with the corresponding reverse mapped data in key. We add the position with 'A' to get the corresponding char

        for (int i = 0; i < data.length(); i++)

            decodedData[i] = key.find(data.at(i)) + 'A';

        //return the decoded data

        return decodedData;

    }

};

//RandomCipher is a subclass of SubstitutionCipher which initializes the key with random permutation

class RandomCipher : public SubstitutionCipher

{

public:

    RandomCipher()

    {

        key = getRandomKey();

    }

    string getRandomKey()

    {

        int m = 26;

        srand(time(NULL));

        bool repeat = false;

        string key = "abcdefghijklmnopqrstuvwxyz";

        char letter;

        for (int i = 0; i < m; i++)

        {

            do

            {

                repeat = false;

                letter = rand() % 26 + 65;   // generate new random number

                for (int j = 0; j <= i; j++) // iterate through the already generated numbers

                {

                    if (letter == key[j])

                    { // if the generated number already exists, do the while again

                        repeat = true;

                        break;

                    }

                }

            } while (repeat);

            key[i] = letter; // assign the unique number

            repeat = false;

        }

        return key;

    }

};

int main()

{

    RandomCipher cipher;

    string data = "DEBAJYOTI";

    string encodedData = cipher.encode(data);

    cout << data << " encoded as " << encodedData << endl;

    string decodedData = cipher.decode(encodedData);

    cout << encodedData << " decoded as " << decodedData;

}

//SAMPLE OUTPUT:

PLEASE LIKE IT RAISE YOUR THUMBS UP
IF YOU ARE HAVING ANY DOUBT FEEL FREE TO ASK IN COMMENT SECTION


Related Solutions

IN C++!!! Exercise #1: Design and implement class Rectangle to represent a rectangle object. The class...
IN C++!!! Exercise #1: Design and implement class Rectangle to represent a rectangle object. The class defines the following attributes (variables) and methods: Two Class variables of type double named height and width to represent the height and width of the rectangle. Set their default values to 0 in the default constructor. A non-argument constructor method to create a default rectangle. Another constructor method to create a rectangle with user-specified height and width. Method getArea() that returns the area. Method...
Week 3 In-Class Exercise C++ Payroll Design a PayRoll class that is an abstract data type...
Week 3 In-Class Exercise C++ Payroll Design a PayRoll class that is an abstract data type for payroll. It has data members for an employee’s hourly pay rate, number of hours worked, and total pay for the week. Your class must include the following member functions: a constructor to set the hours and pay rate as arguments, a default constructor to set data members to 0, member functions to set each of the member variables to values given as an...
1 .RuntimeException class is a subclass of the Exception class. Fill in the blanks to complete...
1 .RuntimeException class is a subclass of the Exception class. Fill in the blanks to complete the declaration of the RuntimeException class. _____________   ________________    _________________ . . . 3. RuntimeException is a subclass of Exception. The constructor RuntimeException(String message) calls the parent class's constructor with the message argument. Which of the following makes the call correctly? this(message); super(message); super.Exception(message); Exception(message); 4. RuntimeException has overloaded constructors: the 1-argument constructor RuntimeException(String message) and the 2-argument constructor RuntimeException(String message, Throwable cause). The 2-argument...
Python Clean up the code Recall that once a subclass inherits from a parent class, it...
Python Clean up the code Recall that once a subclass inherits from a parent class, it automatically has access to all of the parents' methods. Sometimes, the subclass needs to do extra things within a method which the parent does not do. For example, both UserPlayer and BasicMonster have their specialized __init__ methods which override the one from Player. Discuss the following question with your partner: What are the other methods that are being overridden by a subclass in the...
Programming Exercise Implement the following class design: class Tune { private:    string title; public:   ...
Programming Exercise Implement the following class design: class Tune { private:    string title; public:    Tune();    Tune( const string &n );      const string & get_title() const; }; class Music_collection { private: int number; // the number of tunes actually in the collection int max; // the number of tunes the collection will ever be able to hold Tune *collection; // a dynamic array of Tunes: "Music_collection has-many Tunes" public: // default value of max is a conservative...
Instructions: In this exercise, you’ll design a role playing character class. The Character class attributes should...
Instructions: In this exercise, you’ll design a role playing character class. The Character class attributes should include the characters’s name, gender, class* and race (can be human, elf or dwarf), and additional integer attributes of Strength, Dexterity, Constitution, Intelligence, Wisdom, Charisma. Your class should have a constructor that receives this data. For each attribute, provide setters and getters. The class should include methods that calculate and return the user’s total attributes (sums 6 attributes). Write a Java application that prompts...
c++ E2b: Design a class named Rectangle to represent a rectangle. The class contains:
using c++E2b: Design a class named Rectangle to represent a rectangle. The class contains:(1) Two double data members named width and height which specifies the width and height of the rectangle .(2) A no-arg constructor that creates a rectangle with width 1 and height 1.(3) A constructor that creates a rectangle with the specified width and height .(4) A function named getArea() that returns the area of this rectangle .(5) A function named getPerimeter() that returns the perimeter of this...
Suppose our IS/LM model from class is adjusted so that y = c (y – T,...
Suppose our IS/LM model from class is adjusted so that y = c (y – T, confidence) + I (I + premium, confidence) + G m/p= L (i, y) i = Federal Funds rate Suppose the government takes action to improve the solvency of the financial system. Assume that there is an unusually high premium added to the federal funds interest rate when firms borrow at the moment. If the government action is successful, and banks become more willing to...
Java Apply inheritance to write a super class and subclass to compute the triangle area and...
Java Apply inheritance to write a super class and subclass to compute the triangle area and the surface area of triangular pyramid, respectively. Assume that each side has the same length in the triangle and triangular pyramid. You need also to override toString() methods in both of super class and subclass so they will return the data of an triangle object and the data of the pyramid object, respectively. Code a driver class to test your classes by creating at...
Write a class that extends the LeggedMammal class from the previous laboratory exercise.
C++ code on Visual Studio Code:Write a class that extends the LeggedMammal class from the previous laboratory exercise. The class will represent a Dog. Consider the breed, size and is registered. Initialize all properties of the parent class in the new constructor. This time, promote the use of accessors and mutators for the new properties. Instantiate a Dog object in the main function and be able to set the values of the properties of the Dog object using the mutators....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT