This lab is designed to introduce students to the Bash Command Line Interface (CLI) and the concept of CLI arguments and give them practice writing classes. The cowsay utility is a popular Unix program from the 20th century (see https://en.wikipedia.org/wiki/Cowsay). You will write a slightly simplified cowsay program that takes in several arguments and prints out different text depending on the arguments.Please note that you are strongly recommended to use a text editor and the terminal to edit and run your program and its directories. It is advised students learn/review basic Unix shell commands before beginning; a good run-through can be found here: https://linuxjourney.com/lesson/the-shell. You are also allowed to use PyCharm and its terminal to write and run your program. Follow these steps to get started on the lab: 1. Open a terminal and enter the pwd command to identify the path to the working (current) directory (folder) 2. Enter ls to list the contents of the current directory 3. Use the mkdir command to make a new directory called CowLab. 4. Use ls to see the change, then cd to change to the directory CowLab. 5. Do your lab work in that folder. Use your google skills to find more commands. You can read more information about some of these commands here: https://www.howtogeek.com/howto/42980/the-beginners-guide-to-nano-the-linux-command-line-text-editor/ https://pythonbasics.org/execute-python-scripts/Students will write two files: a driver file with a main() entry point (cowsay) and a data class (cow). Note that heifer_generator.py is provided for you; your code must use this class to create the cow objects. Provided For Students – HeiferGenerator get_cows() Static method which returns a Python list of cow objects from the built-in data set. This will use the Cow constructor and image property of the cow class to properly initialize new cow objects uniquely for each data set. This means it is dependent on your Cow class, so you should write that before working on main! cowsay.py (Program Driver) The command line arguments that must be supported are as follows (use python command for Windows and python3 for mac): python cowsay.py -l Lists the available cows python cowsay.py MESSAGE Prints out the MESSAGE using the default COW python cowsay.py -n COW MESSAGE Prints out the MESSAGE using the specified COW If a user calls for a cow that does not exist, the program should print out “Could not find [COWNAME] cow!” Output SamplesSuggested Functions The following functions are suggested to make development easier, but are not required: list_cows(cows) Displays the available cows from a Python list of Cow objects. find_cow(name, cows) Given a name and a Python list of Cow objects, return the Cow object with the specified name. If no such Cow object can be found, return None. Cow Class The Cow class facilitates the creation and use of cow objects by providing the following methods (which students must implement): __init__(self, name) Initializes a cow object with name and image to be None get_name(self) Returns the name of the cow. Note: the name property should NOT have a setter. get_image(self) Returns the image used to display the cow (this should be called after the message has been displayed). set_image(self, image) Sets the image used to display the cow.NOTE: Your output must match the example output *exactly*. If it does not, you will not receive full credit for your submission! Files: cowsay.py, cow.py>python3 cowsay.py Hello World! Hello World! ^__^ (oo)_______ (__) )/ ||—-w | || || >python3 cowsay.py -n kitteh Hello World! Hello World! (“`-‘ ‘-/”) .___..–‘ ‘ “`-._ ` *_ * ) `-. ( ) .`-.__. `) (_Y_.) ‘ ._ ) `._` ; `` -. .-‘ _.. `–‘_..-_/ /–‘ _ .’ ,4 ( i l ),-” ( l i),’ ( ( ! .-‘ >python3 cowsay.py -l Cows available: heifer kitteh >python3 cowsay.py -n ninja Hello world! Could not find ninja cow! >python3 cowsay.py Hello -n kitteh Hello -n kitteh ^__^ (oo)_______ (__) )/ ||—-w | || ||
Calculate the equivalent resistance (R) of three resistors in parallel, given:Program Inputs• What is the value of R1? • What is the value of R2? • What is the value of R3? – You can safely assume the user will always enter positive numbers for the resistors. Program Outputs• The equivalent resistance is XXX ohms – Replace XXX with the equivalent resistance value Sample OutputTest Case 1: What is the value of R1? 10 What is the value of R2? 10 What is the value of R3? 20 The equivalent resistance is 4.0 ohms Test Case 2: What is the value of R1? 75 What is the value of R2? 10 What is the value of R3? 2200 The equivalent resistance is 8.79 ohms Test Case 3: What is the value of R1? 5000 What is the value of R2? 100 What is the value of R3? 22.5 The equivalent resistance is 18.3 ohms For a given length and width of a rectangle, write a program to calculate and display the perimeter, area and the length of the diagonal of the rectangle. Program Inputs• Enter the length: • Enter the width: – You can safely assume the user will always enter real numbers for all questions. Program Outputs• Rectangle perimeter: XXX – Replace XXX with the perimeter with at most 2 decimal places • Rectangle area: YYY – Replace YYY with the area with at most 2 decimal places • Rectangle diagonal: ZZZ – Replace ZZZ with the length of diagonal with at most 2 decimal places Sample OutputTest Case 1: Enter the length: 3 Enter the width: 8 Rectangle perimeter: 22.0 Rectangle area: 24.0 Rectangle diagonal: 8.54 Test Case 2: Enter the length: 12.5 Enter the width: 35 Rectangle perimeter: 95.0 Rectangle area: 437.5 Rectangle diagonal: 37.17 Test Case 3: Enter the length: 5.5 Enter the width: 6.3 Rectangle perimeter: 23.6 Rectangle area: 34.65 Rectangle diagonal: 8.36 You are given two lines in slope-intercept form (y = mx + b) and must find their intersection point. For example, if Line 1 is y = x and Line 2 is y = 3, then the intersect point is (3,3). Develop a program to find the intersection of any two lines (you can assume there will always be an intersection!). Program Inputs• Enter m for Line 1: • Enter b for Line 1: • Enter m for Line 2: • Enter b for Line 2: – You can safely assume the user will always enter real numbers for all questions. Program Outputs• The intersection point is (XXX,YYY) – Replace XXX with correct x coordinate and YYY with the y coordinate with at most 2 decimal places Sample OutputTest Case 1: Enter m for Line 1: 1 Enter b for Line 1: 0 Enter m for Line 2: 0 Enter b for Line 2: 3 The intersection point is (3.0,3.0) Test Case 2: Enter m for Line 1: 0.5 Enter b for Line 1: 1 Enter m for Line 2: -2 Enter b for Line 2: 20 The intersection point is (7.6,4.8)Test Case 3: Enter m for Line 1: 3 Enter b for Line 1: -5 Enter m for Line 2: 0.01 Enter b for Line 2: 2 The intersection point is (2.34,2.02) Test Case 4: Enter m for Line 1: 20 Enter b for Line 1: 0 Enter m for Line 2: -5.5 Enter b for Line 2: 50 The intersection point is (1.96,39.22)
Overview This homework will provide students with practice building and working with object-oriented programming constructs including classes and objects by building classes to represent creatures and a cataloging system. Scenario NOTE: This homework concept is a work of satire. To state the obvious: we do not advise one to go around imprisoning creatures in small receptacles held in one’s pockets and/or having them fight for sport. Requirements Students will construct three classes: a driver class with a main() entry point (pakuri_program) and two data object classes (pakuri and pakudex). All attributes / methods must be private unless noted in the specification! Welcome to Pakudex: Tracker Extraordinaire! Enter max capacity of the Pakudex: 30 The Pakudex can hold 30 species of Pakuri. Pakudex Main Menu —————– 1. List Pakuri 2. Show Pakuri 3. Add Pakuri 4. Evolve Pakuri 5. Sort Pakuri 6. Exit What would you like to do? pakuri_program.py (Driver / Program) When run, the program should… 1) Display a welcome message 2) Prompt for / read pakudex capacity & confirm 3) Display the menu 4) Prompt for input Listing Pakuri This should number and list the critters in the pakudex in the order contained. For example, if “Pikaju” and “Charasaurus” were added to the pakudex (in that order), before sorting, the list should be: Success Failure Pakuri In Pakudex: 1. Pikaju 2. Charasaurus No Pakuri in Pakudex yet! Pakudex Main Menu Show Pakuri The program should prompt for a species and collect species information, then display it: Success Failure Enter the name of the species to display: PsyGoose Species: PsyGoose Attack: 65 Defense: 57 Speed: 61 Enter the name of the species to display: PsyDuck Error: No such Pakuri! Pakudex Main Menu —————– 1. List Pakuri Adding Pakuri When adding a pakuri, a prompt should be displayed to read in the species name, and a confirmation displayed following successful addition (or failure). Success Failure – Duplicate Enter the name of the species to add: PsyGoose Pakuri species PsyGoose successfully added! Pakudex Main Menu —————– Enter the name of the species to add: PsyGoose Error: Pakudex already contains this species! Error: Pakudex is full! Failure – Full Evolve Pakuri The program should prompt for a species and then cause the species to evolve if it exists: Success Failure Enter the name of the species to evolve: PsyGoose PsyGoose has evolved! Enter the name of the species to evolve: PsyDuck Error: No such Pakuri! Sort Pakuri Sort pakuri in Python standard lexicographical order: Pakuri have been sorted! (Hint: Use Sort() Function) Exit Thanks for using Pakudex! Bye! Quit the program: Pakuri Class This class will be the blueprint for the different critter objects that you will create. You will need to store information about the critter’s species, attack level, defense level, and speed. All variables storing information about the critters must be private (accessible from outside of the class). We recommend (but do not mandate) the following variable types and names: species; (Type: String) attack, defense, speed; (Type: Int) These attack, defense, and speed levels should have the following initial values when first created: Attribute Value attack (len(species) * 7) + 9 defense (len(species) * 5) + 17 speed (len(species) * 6) + 13 The class must also have the following methods and behaviors (this is mandatory): __init__(self, species) Initialize the pakuri object with species attribute def get_species(self) Returns the species of this critter def get_attack(self) Returns the attack value for this critter def get_defense(self) Returns the defense value for this critter def get_speed(self) Returns the speed of this critter def set_attackself, new_attack) Changes the attack value for this critter to new_attack def evolve(self) Will evolve the critter as follows: a) double the attack; b) quadruple the defense; and c) triple the speed Pakudex Class The Pakudex class will contain all the pakuri that you will encounter as Pakuri objects. Note: The pakudex will have a set size determined by user input at the beginning of the program’s run; the number of species contained in the pakudex will never grow beyond this point. The class must also have the following methods and behaviors (this is mandatory): def __init__(self, capacity=20) Initializes this object to contain exactly capacity objects when completely full. The default capacity for the pakudex should be 20 def get_size(self) Returns the number of critters currently being stored in the pakudex def get_capacity(self) Returns the number of critters that the pakudex has the capacity to hold at most def get_species_array(self) Returns a string list containing the species of the critters as ordered in the pakudex; if there are no species added yet, this method should return None def get_stats(self, species) Returns an int list containing the attack, defense, and speed statistics of species at indices 0, 1, and 2 respectively; if species is not in the pakudex, returns None def sort_pakuri(self) Sorts the pakuri objects in this pakudex according to Python standard lexicographical ordering of species name def add_pakuri(self, species) Adds species to the pakudex; if successful, return True, and False otherwise def evolve_species(self, species) Attempts to evolve species within the pakudex; if successful, return True, and False otherwise Submissions NOTE: Your output must match the example output *exactly*. MAKE SURE YOUR CLASSES ARE DEFINED WITH LOWERCASE LETTERS AS SHOWN BELOW! Files: pakuri_program.py, pakuri.py, pakudex.py Method: Submit it on Canvas
COP 3330- HW on File I/O Lines in lec.txt are of the form: 89745,COT6578,Advanced Computer theory,Graduate,F2F,PSY-108,No 32658,COT6578,Advanced Computer theory,Graduate,Mixed,LPS-35,NoThat means that the CSD offers two sections of COT6578, one is F2F and the other is online. Both of those sections don’t have labs.Example: 69745,COP5698, Programming Languages,Graduate,F2F,CB2-122,YES 19745,MSB-123 36598,PSY-100 20315,HSA1-116That means the COP5698 with crn 69745 has three labs. 19745, 36598 and 20315 are the crns of the labs. MSB-123, PSY-100 and HSA1-116 are the building-room numbers where those labs are scheduled to take place.Note that if the Modality is Online, then the line of the lec.txt has the form: 89745,COP4578,Software Engineering,Undergraduate,OnlineWrite a Java program that: 1) Counts how many online classes offered at the CSD 2) Displays the crns of the lectures and Labs that are being held in a given classroom that you ask the user for. 3) Create a textfile (name it lecturesOnly.txt) that lists the online and the no-lab lectures. See sample run belowSample Run:– There are 4 online lectures offered – Enter the classroom: MSB-123 The crns held in MSB-123 are: 19745 – lecturesOnly.txt is createdGoodbye !Given the content of lec.txt, lecturesOnly.txt should be:Online Lectures 66636,DIG2158,Introduction to Digital Systems,Undergraduate,Online 36636,SOF2058,Introduction to Software,Undergraduate,Online 51180,CDL2587,Introduction to Computers,Undergraduate,online 36637,SOF2058,Introduction to Software,Undergraduate,OnlineLectures with No Lab 89745,COT6578,Advanced Computer theory,Graduate,F2F,PSY-108,No 32658,COT6578,Advanced Computer theory,Graduate,Mixed,LPS-35,No
HW 3 and 4: RLE with Images PythonOverview In this project students will develop routines to encode and decode data for images using run-length encoding (RLE). Students will implement encoding and decoding of raw data, conversion between data and strings, and display of information by creating procedures that can be called from within their programs and externally. This project will give students practice with loops, strings, Python lists, methods, and type-casting.Run-Length Encoding RLE is a form of lossless compression used in many industry applications, including imaging. It is intended to take advantage of datasets where elements (such as bytes or characters) are repeated several times in a row in certain types of data (such as pixel art in games). Black pixels often appear in long “runs” in some animation frames; instead of representing each black pixel individually, the color is recorded once, following by the number of instances.0 0 2 2 2 0 0 0 0 0 0 2 2 0_ 2 0 3 2 6 0 2 2 1 0_ For example, consider the first row of pixels from the pixel image of a gator (shown in Figure 1). The color black is “0”, and green is “2”:Flat (unencoded) data:Run-length encoded data: . Figure 1 – Gator Pixel Image The encoding for the entire image in RLE (in hexadecimal) – width, height, and pixels – is:2 0 3 2 6 0 2 2 2 0 1 2 1 F 1 0 7 2 1 A F 2 1 0 9 2 3 0 1 2 1 0 3 2 6 0 3 2 3 0 8 2 5 0 1 E |1 6 W/ H/ ——————————————PIXELS———————————————–/Image Formatting The images are stored in uncompressed / unencoded format natively. In addition, there are a few other rules to make the project more tractable:1. Images are stored as a list of numbers, with the first two numbers holding image width and height. 2. Pixels will be represented by a number between 0 and 15 (representing 16 unique colors).For example, the chubby smiley image (Figure 2) would contain the data shown in Figure 3.Figure 2 Figure 3 – Data for “Chubby Smiley” NOTE: Students do not need to work with the image file format itself – they only need to work with lists and encode or decode them. Information about image formatting is to provide context. Requirements Student programs must present a menu when run in standalone mode and must also implement several methods, defined below, during this assignment.Standalone Mode (Menu) When run as the program driver via the main() method, the program should:1) Display welcome message 2) Display color test (ConsoleGfx.test_rainbow) 3) Display the menu 4) Prompt for inputNote: for colors to properly display, it is highly recommended that student install the “CS1” theme on the project page.There are five ways to load data into the program that should be provided and four ways the program must be able to display data to the user.Loading a File Accepts a filename from the user and invokes ConsoleGfx.load_file(filename): Select a Menu Option: 1 Enter name of file to load: testfiles/uga.gfxLoading the Test Image Loads ConsoleGfx.test_image: Select a Menu Option: 2 Test image data loaded.Reading RLE String Reads RLE data from the user in decimal notation with delimiters (smiley example): Select a Menu Option: 3 Enter an RLE string to be decoded: 28:10:6B:10:10B:10:2B:10:12B:10:2B:10:5B:20:11B:10:6B:10Reading RLE Hex String Reads RLE data from the user in hexadecimal notation without delimiters (smiley example): Select a Menu Option: 4 Enter the hex string holding RLE data: 28106B10AB102B10CB102B105B20BB106B10Reading Flat Data Hex String Reads raw (flat) data from the user in hexadecimal notation (smiley example): Select a Menu Option: 5 Enter the hex string holding flat data: 880bbbbbb0bbbbbbbbbb0bb0bbbbbbbbbbbb0bb0bbbbb00bbbbbbbbbbb0bbbbbb0Displaying the Image Displays the current image by invoking the ConsoleGfx.display_image(image_data) method.Displaying the RLE String Converts the current data into a human-readable RLE representation (with delimiters): Select a Menu Option: 7 RLE representation: 28:10:6b:10:10b:10:2b:10:12b:10:2b:10:5b:20:11b:10:6b:10Note that each entry is 2-3 characters; the length is always in decimal, and the value in hexadecimal! Displaying the RLE Hex Data Converts the current data into RLE hexadecimal representation (without delimiters): Select a Menu Option: 8 RLE hex values: 28106b10ab102b10cb102b105b20bb106b10Displaying the Flat Hex Data Displays the current raw (flat) data in hexadecimal representation (without delimiters): Select a Menu Option: 9 Flat hex values: 880bbbbbb0bbbbbbbbbb0bb0bbbbbbbbbbbb0bb0bbbbb00bbbbbbbbbbb0bbbbbb0Class Methods Student classes are required to provide all of the following methods with defined behaviors. We recommend completing them in the following order:1. to_hex_string(data) Translates data (RLE or raw) a hexadecimal string (without delimiters). This method can also aid debugging.Ex: to_hex_string([3, 15, 6, 4]) yields string “3f64”.2. count_runs(flat_data) Returns number of runs of data in an image data set; double this result for length of encoded (RLE) list.Ex: count_runs([15, 15, 15, 4, 4, 4, 4, 4, 4]) yields integer 2.3. encode_rle(flat_data) Returns encoding (in RLE) of the raw data passed in; used to generate RLE representation of a data.Ex: encode_rle([15, 15, 15, 4, 4, 4, 4, 4, 4]) yields list [3, 15, 6, 4].4. get_decoded_length(rle_data) Returns decompressed size RLE data; used to generate flat data from RLE encoding. (Counterpart to #2)Ex: get_decoded_length([3, 15, 6, 4]) yields integer 9.5. decode_rle(rle_data) Returns the decoded data set from RLE encoded data. This decompresses RLE data for use. (Inverse of #3)Ex: decode_rle([3, 15, 6, 4]) yields list [15, 15, 15, 4, 4, 4, 4, 4, 4, 4].6. string_to_data(data_string) Translates a string in hexadecimal format into byte data (can be raw or RLE). (Inverse of #1)Ex: string_to_data (“3f64”) yields list [3, 15, 6, 4].7. to_rle_string(rle_data) Translates RLE data into a human-readable representation. For each run, in order, it should display the run length in decimal (1-2 digits); the run value in hexadecimal (1 digit); and a delimiter, ‘:’, between runs. (See examples in standalone section.)Ex: to_rle_string([15, 15, 6, 4]) yields string “15f:64”.8. string_to_rle(rle_string) Translates a string in human-readable RLE format (with delimiters) into RLE byte data. (Inverse of #7)Ex: string_to_rle(“15f:64”) yields list [15, 15, 6, 4].Submissions NOTE: Your output must match the example output *exactly*. If it does not, you will not receive full credit for your submission!File: initials_HW{nu m}.py Method: Submit on CanvasDo not submit any other files!HW 3A (10 points) For this assignment, students will set up the standalone menu alongside the 4 requirements listed on page 2 of this document. In addition to this, students should also set up menu options 1 (loading an image), 2 (loading specifically the test image), and 6 (displaying whatever image was loaded) in order to help grasp the bigger picture of the project.This involves correctly setting up the console_gfx.py file and utilizing its methods. You will use ConsoleGfx.display_image(…) to display images. Notice how it takes in a decoded list. This is the format in which you will locally (in your program) store any image data that you are working with. When the document mentions that something is “loaded” it means that something is stored as a list of flat (decoded) data.HW 3B (90 points)HW 4 (100 points) For this assignment, students will now complete the final 2 methods on page 3 of this document as well as the remainder of the project involving the menu options and understanding how all the individual methods are intertwined with each other. You will submit your whole program including the 8 methods listed above and the main method. We will only test your remaining 2 methods and the main method in HW4 .
Any class that implements the Java’s CharSequence interface must override the following abstract methods: charAt, length and subSequence. For example, the class String implements CharSequence. That is why you see the three methods (charAt, length and subSequence) appear (as overriden methods) in the list of public methods of the class String.In this HW, you will be asked to implement the built-in Java interface CharSequence. You will be provided with two classes: The DriverClass class and the Code class that implements CharSequence (from the util package). The class Code has int [][] codeArray, int numRows, int numColumns as its private fields, and it is already equipped with the code that loads and print the array codeArray. Your task is to override the methods charAt, length and subSequence as indicated below:Assume that the array codeArray is:125 53 63 63 78 59 71 45 69 90 95 93Then override the : 1- char charAt (int index) to return the character whose ascii/Unicode code is at index. Given the array above, if index is 6, the element of the array code to consider is 71, and the character to return is G (the ascci code for the G is 71).Want to check? System.out.println((char) 71);2- int length() to return how many characters are loaded in the array (which is the number of integers in the array). In the case of the array provided here, length returns 123- String subSequence(int start, int end) returns the string formed by concatenating all the characters corresponding to the integers from index start to index end. For example subsequence(1,5) returns 5??N;A scatelon code is provided at the end of this HW. Once again, your task is to provide the code for the three methods: charAt, length and subSequence. (Do not change the Driver class!)Sample Run 1:Enter row 1: 125 53 63 63 Enter row 2: 78 59 71 45 Enter row 3: 69 90 95 93 Testing charAt: Enter your index [a number greater or equal to 0 and less or equal to 11]: 6 Enter how many rows and how many columns to load: 3 4 Assume that the user will enter numbers between 1 and 20The character located at index 6 is: GTesting length: there are 12 characters.Testing subSequence: Enter start and end indexes: 1 5 The subsequuence is: 5??N;Goodbye!Assume that the user will enter a numbers between 0 and (number of rows times number of columns – 1) Assume that the user will enter two nonnegative integers sunch that the first one is less or equal to the second one, and that both of the entered numbers are between 0 and (number of rows times number of columns – 1)Sample Run 2:Enter how many rows and how many columns to load: 2 8 Enter row 1: 195 63 63 63 69 92 85 95 Enter row 2: 78 59 71 45 85 67 70 33Testing charAt: Enter your index [a number greater or equal to 0 and less or equal to 11]: 0 The character located at index 0 is: ÃTesting length: there are 16 characters.Testing subSequence: Enter start and end indexes: 12 15 The subsequuence is: UCF!Goodbye!import java.util.Scanner;public class DriverClass { public static void main(String args[]) { int numRows, numColumns; int index, start, end; char charAtIndex; int length; String subSequence;Scanner myScan = new Scanner(System.in);System.out.print(“Enter how many rows and how many columns to load: “); numRows = myScan.nextInt(); numColumns = myScan.nextInt();Code codeObject = new Code(numRows, numColumns);codeObject.loadCodeArray(numRows, numColumns); codeObject.printCodeArray(numRows, numColumns); // __________________________________________ System.out.print(“ Testing charAt: Enter your index [a number greater or equal to 0 and less or equal to “); System.out.print((numRows * numColumns – 1) + “]:”); index = myScan.nextInt();charAtIndex = codeObject.charAt(index);System.out.println(“The character located at index ” + index + ” is: ” + charAtIndex);// __________________________________________ length = numRows * numColumns;System.out.println(“ Testing length: there are ” + length + ” characters.”);// __________________________________________ System.out.print(“ Testing subSequence: Enter start and end indexes: “); start = myScan.nextInt(); end = myScan.nextInt();subSequence = codeObject.subSequence(start, end); System.out.println(“The subsequuence is: ” + subSequence); // __________________________________________ System.out.println(“ Goodbye!”);} }//_____________________________________ class Code implements CharSequence {private int[][] codeArray; private int numRows, numColumns;public Code(int numRows, int numColumns) { this.numRows = numRows; this.numColumns = numColumns; codeArray = new int[numRows][numColumns]; }public void loadCodeArray(int numRows, int numColumns) { Scanner myScan = new Scanner(System.in); int i, j; for (i = 0; i < numRows; i++) { System.out.print(“Enter Row ” + (i + 1) + “: “); for (j = 0; j < numColumns; j++) { codeArray[i][j] = myScan.nextInt(); } }}public void printCodeArray(int numRows, int numColumns) {int i, j; System.out.println(“ _____________ ”); for (i = 0; i < numRows; i++) {for (j = 0; j < numColumns; j++) { System.out.print(codeArray[i][j] + “t”); } System.out.println(“”); }}// ______________THE CODE ABOVE IS TO REMAIN UNCHANGED______________________ @Override public char charAt(int index) { // Add your code here… }@Override public int length() { // Add your code here… }@Override public String subSequence(int start, int end) { // Add your code here… }}
– The goal of this coding exercise is to wite the code for two classes BookstoreBook and LibraryBook. Both classes have these fields: author: String tiltle: String isbn : String– The BookstoreBook has an additional data member to store the price of the book, and whether the book is on sale or not. If a bookstore book is on sale, we need to add the reduction percentage (like 20% off…etc). For a LibraryBook, we add the call number (that tells you where the book is shelved in the library) as a string. The call number is automatically generated by the following procedure:– In each of the classes, add the setters, the getters, at least three constructors (of your choosing) and override the toString method (see sample run below).– Your code should display the list of all books keyed in by the user– Create an abstract class that you name Book. The class Book should have the fields and the code that is shared by both the BookstoreBook and the LibraryBook classes. Both of those classes extend the Book class. Test your code with an array of 100 elements of Book. Call that array list (You can’t have an array to store the BookstoreBook objects and another one to store the LibraryBook objects. One array (list) to hold all the book objects that your code creates). – Create a class that you call BookList in which you put list as a private field. Your code must have the following structure:public class Main { public static void main(String args[]) { // Instantiate the class BookList here … } } //___________________________ abstract class Book { //code of the abstract class Book } //___________________________ class BookstoreBook extends Book { // fields and specific code to the BookstoreBook class goes here } //___________________________ class LibraryBook extends Book { // fields and specific code to the LibraryBook class goes here } //___________________________ class BookList { private Book[] list; public BookList() { list = new Book[100]; // Additional code goes here if needed… } }Sample Run The user’s entry is marked in boldfaceWelcome to the book program! Would you like to create a book object? (yes/no): yEs Please enter the author, title ad the isbn of the book separated by /: Ericka Jones/Java made Easy/458792132 Got it! Now, tell me if it is a bookstore book or a library book (enter BB for bookstore book or LB for library book): BLB Oops! That’s not a valid entry. Please try again: Bookstore Oops! That’s not a valid entry. Please try again: bB Got it! Please enter the list price of JAVA MADE EASY by ERICKA JONES: 14.99 Is it on sale? (y/n): y Deduction percentage: 15% Got it!Here is your bookstore book information [458792132-JAVA MADE EASY by ERICKA JONES, $14.99 listed for $12.74] Would you like to create a book object? (yes/no): yeah I’m sorry but yeah isn’t a valid answer. Please enter either yes or no: yesPlease enter the author, title and the isbn of the book separated by /: Eric Jones/Java made Difficult/958792130 Got it! Now, tell me if it is a bookstore book or a library book (enter BB for bookstore book or LB for library book): LB Got it!Here is your library book information [958792130-JAVA MADE DIFFICULT by ERIC JONES-09.ERI.0]Would you like to create a book object? (yes/no): yesPlease enter the author, title and the isbn of the book separated by /: Erica Jone/Java made too Difficult/958792139 Got it! Now, tell me if it is a bookstore book or a library book (enter BB for bookstore book or LB for library book): LB Got it!Here is your library book information [958792139-JAVA MADE TOO DIFFICULT by ERICA JONE-86.ERI.9] Would you like to create a book object? (yes/no): no Sure!Here are all your books… Library Books (2) [958792130-JAVA MADE DIFFICULT by ERIC JONES-09.ERI.0] [958792139-JAVA MADE TOO DIFFICULT by ERICA JONE-86.ERI.9] _ _ _ _ Bookstore Books (1) [458792132-JAVA MADE EASY by ERICKA JONES, $14.99 listed for $12.74] _ _ _ _ Take care now!
In Java, Implement a simple weekly payroll program. The input will consist of the employee’s full name, employee’s ID (String), the number of hours worked per week (double), the hourly rate (double), the income tax is 6%. Your program should calculate the total gross pay, and the net pay and display a paycheck similar to:————————————————————————— Employee’s name: John Smith Employee’s number: js1200 Hourly rate of pay: 10.50 Hours worked: 36.00 Total Gross Pay:Deductions $378.00 Tax (6 %): $22.68 Net Pay: 355.32 Dollars —————————————————————————In the rest of this HW, Salary means the Gross Pay= hoursWorked times hourlyRateYour program must include the class Employee whose private fields are: – fullName: String – employeeNumber: String – payRate: double – hoursWorked: double(Don’t add any fields to the class Employee)In addition to that, equip the class Employee with these methods: – Employee (String fullName, String employeeNumber, double payRate, double hoursWorked) This constructor assigns the parametres fullName, employeeNumber, payrate, hoursWorked to the data members.– For each of the private data members above, add a Setter and a Getter– Override the toString() method to return the String of the form: [Employee Number/Full Name, x Hours @ y per hour] where x is the number of hours worked and y is the pay rate. As an example, [js1200/John Smith, 36 Hours @ 10.5 per hour]– double netPay (), the private method that returns the net pay of the employee. The net pay is calculated by deducting 6% from the gross pay. See sample check above. – void printCheck (), the method that prints the paycheck of the employee as shown above. The printCheck method calls the private netPay method to get the net pay of the employee. So do not recalculate net pay in this printCheck methodAfter completing the code of the class Employee, work on the class Company whose skeleton is provided below. Have all the three classes in one .java file (DriverClass.java) and submit!What is being asked to code is marked in comments throughout the DriverClass.java file. See it below.Note well that whether you work with a group of students or solo, you must submit your .java on Webcourses. (This is going to be the case for all the future HWs and the final project).One more thing… If you want to ask someone to write the code for you, go for it! If you want to add someone’s name to your code as a favor, go for it! But we truly hope that you don’t. Be an honest learner!All students must use DriverClass.java shown below.//Names of Students who worked togetherpublic class DriverClass {public static void main(String[] args) {String fullName = “Erika T. Jones”; String employeeNumber = “ej789”; double payRate = 100.0, hoursWorked = 1.0; Employee e; e = new Employee(fullName, employeeNumber, payRate, hoursWorked); System.out.println(e); // To Test your toString methode.printCheck(); // This prints the check of Erika T. JonesCompany company = new Company();company.hire ( new Employee (“Saeed Happy”, “sh895” , 2 , 200) ); company.hire (e);company.printCompanyInfo();company.hire( new Employee(“Enrico Torres” , “et897” , 3 , 150) );//Make sure that each employee of company has a unique employeeNumbercompany.printCheck(“ab784”);company.deleteEmployeesBySalary(256.36);company.reverseEmployees();System.out.println( company.SearchByName(“WaLiD WiLLiAms”) );company.printEmployees();System.out.println(“Bye!”);}}//____________________________ class Employee {//Add the private attributes and the methods as mentioned above… }//____________________________ class Company {private ArrayList employeeList; private String companyName; private static String companyTaxId;//Add static Setters and Getters for companyTaxId. We assume that //Add Setter and Getter for the companyName //No need to add a Setter and Getter for employeeListpublic Company() { employeeList = new ArrayList(); companyName = “People’s Place”; companyTaxId = “v1rtua7C0mpan1”; } public boolean hire ( Employee employee ) { //Add empoyee to employeeList //Note well that we can’t add an employee whose employeeNumber already //This method returns true otherwise}public void printCompanyInfo() { //This method prints the compay name, the tax id and the current number //of employees }public void printEmployees() { //This methods prints all employees (One employee per line) //Note that you already have toString in Employye }public int countEmployees( double maxSalary ) { //This method returns the number of employees paid less than maxSalary}public boolean SearchByName (String fullName ) { //This method returns true if fullName exists as an employee. //It returns false otherwise //this is a not a case sensitive search. }public void reverseEmployees () { //This method reverses the order in which the employees were added to //the list. The last employee is swapped with the first employee, the //second last with the second and so on.. }public void deleteEmployeesBySalary (double targetSalary ) { //This method deletes all employees who are paid targetSalary as a gross //salary }public void printCheck ( String employeeNumber) { //This method prints the check of the employee whose employee number is //employeeNumber. It prints NO SUCH EMPLOYEE EXISTS if employeeNumber is //not a registered employee number. }}//end of class Company
– Input/output using the Scanner class – Output formating – Basic arithmetic – String class basics, and the split methodUCF-COP 3330-HW1After inputting all the necessary data (see sample run below), a fee invoice as shown below should be printed to the screen.ORLANDO FL 10101 ************************* Fee Invoice Prepared for: [Ericka J. Jones][V5656]1 Credit Hour = $120.25CRN CREDIT HOURS 4587 4 $481.00 4599 3 $360.75Health & id fees $35.00—————————————- Total Payments $876.75Sample Run (The user’s entry is marked in bold)Enter the Student’s Id: V5656 Enter the Student’s full name: Ericka J. Jones Enter crn/credit hours for the first class(like 5665/3: 4587/4 Enter crn/credit hours for the second class(like 5665/3): 4599/3Thank you! Fee invoice prepared for: Ericka J. JonesORLANDO FL 10101 ************************* Fee Invoice Prepared for: [Ericka J. Jones][V5656]1 Credit Hour = $120.25CRN CREDIT HOURS 4588 4 $481.00 4599 3 $360.75Health & id fees $35.00—————————————- Total Payments $876.75String data =”UCF-COP-3330″; String [] array;String str1 , str2 , str3; int number;array = data.split(“-“);str1 = array[0]; str2 = array[1]; str3 = array[2];number = Integer.parseInt(str3);System.out.println(str1); System.out.println(str2); System.out.println(number); System.out.println(data);
1) Projects can be completed in groups (max 4 per group) but submission onto WebCourses is individual. Once again, don’t copy anybody’s work nor give your code to anybody unless you seriously worked together on the project.2) Please Submit one .java file. It should look like this:public class FinalProject {public static void main(String[] args){ //Test code goes here }}//————————— class Abc{}//————————— class Xyz{}3) If you work with a classmate(s), your .java file must contain the following comment:/* – Final Project */ Example: /* – Final Project – Hatim Boustique, Ericka Edwards and Jamal Dubois */ public class FinalProject {public static void main(String[] args){ //Test code goes here }} //————————— inteface Int1 {} //————————— class Abc{}//————————— class Xyz{}Submissions by email will not be considered for a grade. Students must submit their projects on Webcourses by uploading the .java file. It is the responsibility of the students to check their submissions to make sure that the file they submitted is indeed the right file (and it is readable .java file!)Final Project StatementPlease read this entire statement carefully before you start doing anything…For each of any class data member, your program must include the getters and the setters, and each class must include at least two constructors. The main goal of this Project is to demonstrate the use of inheritance, abstract classes, abstract methods, and method overriding.The Student class has the private attributes: – full name : String – id: String – gpa: double – Number of credit hours currently taken: intFor a faculty, we need a: – full name: String – id: StringFor a staff, we need a: – full name: String – id: String – department (mathematics, engineering or english): String – status (part time or full time): StringYour code should implement the following inheritance hierarchy:Both classes Student and Employee inherit from the abstract class Person. The abstract class Person has what is common to a Student and an Employee (Faculty or Staff). The class Person must include the signature: public abstract void print(); The abstract method print is overridden to print the fee invoice for a student and to print the information for a faculty or a staff member. It is left to you (the programmer) to come up with other abstract methods if you see fit(this is optional).The class Employee should also be abstract, and it is supposed to include what is common to a staff and a faculty. The sample run below should give you a clear idea about how your code should run. The user’s entry is marked in bold so you can tell what your code should display to the screen and what the user enters.3) Your code should handle all exceptions. 4) Note that any person’s id must be of the form LetterLetterDigitDigitDigitDigit like ek7894. See sample run below. We require that ids are checked for duplication. That is: No two persons can have the same id!Sample Run: (Below is how your code should run) Welcome to my Personal Management ProgramChoose one of the options: 1- Enter the information a faculty 2- Enter the information of a student 3- Print tuition invoice for a student 4- Print faculty information 5- Enter the information of a staff member 6- Print the information of a staff member 7- Delete a person 8- Exit Program Enter your selection: 2Enter the student info: Name of Student: Julia Alvarez ID: j1254 Invalid ID format. Must be LetterLetterDigitDigitDigitDigitID: ju1254Gpa: 3.26 Credit hours: 7 Student added!1- Enter the information a faculty 2- Enter the information of a student 3- Print tuition invoice for a student 4- Print faculty information 5- Enter the information of a staff member 6- Print the information of a staff member 7- Delete a person 8- Exit Program Enter your selection: 2Enter the student info: Name of Student: Matt Jones ID: ma0258 Gpa: 2.78 Credit hours: 0 Student added!1- Enter the information of the faculty 2- Enter the information of the two students 3- Print tuition invoice 4- Print faculty information 5- Enter the information of the staff member 6- Print the information of the staff member 7- Delete a person 8- Exit Program Enter your selection: A Invalid entry- please try again1. Enter the information of a faculty 2. Enter the information of a students 3. Print tuition invoice 4. Print faculty information 5. Enter the information of a staff member 6. Print the information of a staff member 7. Delete a person 8. Exit Program Enter your selection: 1Enter the faculty info: Name of the faculty: John Miller ID: jo7894Department: EngineeringFaculty added!1. Enter the information of a faculty 2. Enter the information of a students 3. Print tuition invoice 4. Print faculty information 5. Enter the information of a staff member 6. Print the information of a staff member 7. Delete a person 8. Exit Program Enter your selection: 3Enter the student’s is: ju1254Here is the tuition invoice for Julia Alvarez:————————————————————————— Julia Alvarez ju1254 Credit Hours:7 ($236.45/credit hour) Fees: $52Total payment (after discount): $1,707.15 ($0 discount applied) —————————————————————————1. Enter the information of a faculty 2. Enter information of a students 3. Print tuition invoice 4. Print faculty information 5. Enter the information of a staff member 6. Print the information of a staff member 7. Delete a person 8. Exit Program Enter your selection: 3Enter the student’s is: ja1954 No student matched!1. Enter the information of the faculty 2. Enter information of the two students 3. Print tuition invoice 4. Print faculty information 5. Enter the information of the staff member 6. Print the information of the staff member 7. Delete a person 8. Exit Program Enter your selection: 4 Enter the Faculty’s id: jo7894 ————————————————————————— John Miller jo7894 —————————————————————————1. Enter the information of a faculty 2. Enter information of a students 3. Print tuition invoice 4. Print faculty information 5. Enter the information of a staff member 6. Print the information of a staff member 7. Delete a person 8. Exit Program Enter your selection: 6Enter the Staff’s id: ha5879 No Staff member matched!1. Enter the information of a faculty 2. Enter information of a students 3. Print tuition invoice 4. Print faculty information 5. Enter the information of a staff member 6. Print the information of a staff member 7. Delete a person 8. Exit ProgramEnter your selection: 5Department: English Status, Enter P for Part Time, or Enter F for Full Time: fStaff member added!1. Enter the information a faculty 2. Enter information of a students 3. Print tuition invoice 4. Print faculty information 5. Enter the information of a staff member 6. Print the information of a staff member 7. Delete a person 8. Exit ProgramEnter your selection: 6—————————————————————————————————————————————————— 1. Enter the information a faculty 2. Enter information of a students 3. Print tuition invoice 4. Print faculty information 5. Enter the information of a staff member 6. Print the information of a staff member 7. Delete a person 8. Exit ProgramEnter your selection: 7 Enter the id of the person to delete: ab1234 (If ID exists then remove that person from your array) Sorry no such person exists.1. Enter the information a faculty 2. Enter information of a students 3. Print tuition invoice 4. Print faculty information 5. Enter the information of a staff member 6. Print the information of a staff member 7. Delete a person 8. Exit ProgramEnter your selection: 8Would you like to create the report? (Y/N): y Would like to sort your students by descending gpa or name (1 for gpa, 2 for name): 1 Report created and saved on your hard drive! Goodbye!Sample Report (report.txt)***********************Faculty Members ————————- 1. John Miller ID: jo7894Staff Members ——————- 1. Jamal Kareem ID: ja6980 English, Full TimeStudents (Sorted by gpa in descending order) ———– 1. Julia Alvarez ID: ju1254 Gpa: 3.26 Credit hours: 72. Matt Jones ID: ma0258 Gpa: 2.78 Credit hours: 0
0. Extra Credit This project can be submitted up to 10 days early for up to 10% extra credit. A project submitted 11 days early will still only accrue 10% extra credit. Note that the assignment is not designed to make 10% extra credit easy to obtain. The 10% will be multiplied by the final score 1. Project Overview In this project, you are asked to read an input set of 2D integer points in a coordinate plane. The goal is to find the median coordinate point, whose -coordinate is equal to the median of the -coordinates of the input points and its -coordinate is equal to the median of their coordinates. Finding the median – and -coordinates is done by sorting the points separately by the corresponding coordinate. You need to read the input points four times, each time using one of the following four sorting algorithms: selection sort, insertion sort, merge sort, and quicksort. Note that the same sorting algorithm must be used in both rounds of sorting after the points have been read. We make the following two assumptions: a) All input points have integer coordinates ranging between −50 and 50 inclusive. The rectangular range [−50, 50] × [−50, 50] is big enough to contain 10,201 points with integer coordinates. The input points will be either generated randomly or read from an input file. 1.1 Point Class and Comparison Methods The Point class implements the Comparable interface. Its compareTo() method compares the – or – coordinates of two points. In case two points have the same value along one coordinate, compare the values of the other coordinate. 1.2 Sorter Classes Selection sort, insertion sort, merge sort, and quicksort are respectively implemented by the classes SelectionSorter, InsertionSorter, MergeSorter, and QuickSorter, all of which extend the abstract class AbstractSorter. The abstract class has one constructor awaiting your implementation: protected AbstractSorter(Point[] pts) throws IllegalArgumentException The constructor takes an existing array pts[] of points, and copies it over to the array points[]. It throws an IllegalArgumentException if pts == null or pts.length == 0. Besides having an array points[] to store points, AbstractSorter also includes two instance variables. • algorithm: type of sorting algorithm to be initialized by a child constructor. • pointComparator: comparator used for point comparison. Set by calling setComparator(). It compares two points by their -coordinates or -coordinates The method sort() conducts sorting, for which the algorithm is determined by the dynamic type of the AbstractSorter. The method setComparator() must have been called beforehand to generate an appropriate comparator for sorting by the -coordinate or -coordinate. The class also provides two methods getPoints() to get the contents of the array points[], and getMedian() to return the element with the median index in points[]. Each of the four subclasses SelectionSorter, InsertionSorter, MergeSorter, and QuickSorter has a constructor that needs to call the superclass constructor. 1.3 PointScanner Class This class has two constructors. Both accept one type of sorting algorithm. The first constructor reads points from an array. The second one reads points from an input file of integers, where every pair of integers represents the and -coordinates of one point. A FileNotFoundException will be thrown if no file by the inputFileName exists, and an InputMismathException will be thrown if the file consists of an odd number of integers. There is no need to check if the input file contains unneeded characters like letters since they can be taken care of by the hasNextInt() and nextInt() methods of a Scanner object. 0 0 -3 -9 0 -10 8 4 3 3 -6 3 -2 1 10 5 -7 -10 5 -2 7 3 10 5 -7 -10 0 8 -1 -6 -10 0 5 5 There are 34 integers in the file. A call PointScanner(“points.txt”, Algorithm.QuickSort) will initialize the array points[] to store 17 points below: (0, 0) (-3, -9) (0, -10) (8, 4) (3, 3) (-6, 3) (-2, 1) (10, 5) (-7, -10) (5, -2) (7, 3) (10, 5) (-7, -10) (0, 8) (-1, -6) (-10, 0) (5, 5) Note that the points (-7, -10) and (10, 5) each appear twice in the input. The 17 points have -coordinates in the following sequence: 0, -3, 0, 8, 3, -6, -2, 10, -7, 5, 7, 10, -7, 0, -1, -10, 5 which, after sorted in the non-decreasing order, becomes, -10, -7, -7, -6, -3, -2, -1, 0, 0, 0, 3, 5, 5, 7, 8, 10, 10 Since the largest index in the private array points[] storing the points is 16, the median is 0 at the index 16 / 2 = 8. (Note that integer division in Java truncates the fractional part, if any, of the result.) Similarly, the above points have -coordinates in the following sequence: 0, -9, -10, 4, 3, 3, 1, 5, -10, -2, 3, 5, -10, 8, -6, 0, 5 which is in the non-decreasing order below: -10, -10, -10, -9, -6, -2, 0, 0, 1, 3, 3, 3, 4, 5, 5, 5, 8 The median y-coordinate is 1 at the index 8. The median coordinate point is therefore (0, 1), colored blue in Fig. 1, which does not coincide with any of the input points.Fig. 1. Sample input set containing 15 different points with median coordinate point at (0, 1). Determination of the median coordinate point is carried out by the method scan() of the class by sorting the points by – and -coordinates, respectively. After these two sorting rounds, the method sets the value of medianCoordinatePoint to the MCP. Besides using an array points[] to store points and medianCoordinatePoint to store the MCP, the PointScanner class also includes several other instance variables. • sortingAlgorithm: type of sorting algorithm. Initialized by a constructor. • scanTime: sorting time in nanoseconds. This sums up the times spent on two rounds of sorting per algorithm. Within sort() use the System.nanoTime() method. 2. Compare Sorting Algorithms The class CompareSorters uses the class PointScanner to scan points randomly generated or read from files four times, each time using a different sorting algorithm. Multiple input rounds are allowed. In each round, the main() method compares the execution times of the four scans of the same input sequence. The round proceeds as follows: a) Create an array of randomly generated integers, if needed. b) Construct four PointScanner objects over the point array, each with a different algorithm (i.e., a different value for the parameter algo of the constructor). c) Have every created PointScanner objects call scan(). d) At the end of the round, output the statistics by having every PointScanner object call the stats() method. Below is a sample execution sequence with running times. Performances of Four Sorting Algorithms in Point Scanning keys: 1 (random integers) 2 (file input) 3 (exit) Trial 1: 1 Enter number of random points: 1000 algorithm size time (ns) ———————————- SelectionSort 1000 49631547 InsertionSort 1000 22604220 MergeSort 1000 2057874 QuickSort 1000 1537183 ———————————- Trial 2: 2 Points from a file File name: points.txt algorithm size time (ns) ———————————- SelectionSort 1000 3887008 InsertionSort 1000 9841766 MergeSort 1000 1972146 QuickSort 1000 888098 ———————————- … Your code needs to print out the above text messages for user interactions. Entries in every column of the output table should be aligned. 3. Random Point Generation Project 1. Import the Java package java.util.Random. Next, declare and initiate a Random object like below Random generator = new Random(); Then, the expression generator.nextInt(101) – 50 will generate a pseudo-random number between -50 and 50 every time it is executed. 4. Submission Write your classes in the edu.iastate.cs228.hw2 package. Turn in the zip file, not your class files. Please follow the guideline in submission_guide.pdf. You are not required to submit any JUnit test cases. Nevertheless, you are encouraged to write JUnit tests for your code. Since these tests will not be submitted, feel free to share them with other students. Include the Javadoc tag @author in every class source file you have made changes to. Your zip file should be named Firstname_Lastname_HW2.zip.
1. Problem Description The objective of this exercise is to reconstruct/unzip a message archived with a binary-treebased algorithm. The program should ask for a single filename at the start: “Please enter filename to decode: “, decode the message in the file and print it out to the console. The name of the compressed message file will end in .arch, e.g. “monalisa.arch”. The file consists of two or three lines: the first one or two lines contain the encoding scheme, and the second or third line contains the archived message. 2. Encoding The archival algorithm uses a binary tree. The edges of the tree represent bits, and the leaf nodes contain one character each. Internal nodes are empty. An edge to a left child always represents a 0, and an edge to a right child always represents a 1. Characters are encoded by the sequence of bits along a path from the root to a particular leaf. The below tree serves as an example. Character Encoding a 0 ! 100 d 1010 c 1011 r 110 b 111 The tree on the left encodes these characters: With the above encoding, the bit string: 10110101011101101010100 is parsed as 1011|0|1010|111|0|110|1010|100 which is decoded as: cadbard! With this encoding, we can automatically infer where one character ends and another begins. That is because no character code can be the start of another character code. For example, if you have a character with the code 111, you cannot have the codes 1 and 11, as they would be internal nodes. The following steps decode one character from the bit string: Start at root Repeat until at leaf Scan one bit Go to left child if 0; else go to right child Print leaf payload 3. Input Format The archive file consists of two lines: the first line contains the encoding scheme, and the second line contains the compressed string. For ease of development and to make the archive file human-readable, each bit is represented as the character ‘0’ or ‘1’, rather than as an actual bit from a binary file. The encoding scheme can be represented as a string. For example, the tree from section 2 can be represented as: ^a^^!^dc^rb where ^ indicates an internal node. The above code represents a preorder traversal of the tree. The cadbard! message is encoded in the following file (“cadbard.arch”): ^a^^!^dc^rb 10110101011101101010100 4. Task 4.1. Read in the first line (and possibly second line, if newline is part of the tree) of the file and construct the character tree. Convert the line input into a MsgTree structure using preorder traversal. The tree should be in a class MsgTree with the following members: public class MsgTree{ public char payloadChar; public MsgTree left; public MsgTree right; /*Can use a static char idx to the tree string for recursive solution, but it is not strictly necessary*/ private static int staticCharIdx = 0; //Constructor building the tree from a string public MsgTree(String encodingString){} //Constructor for a single node with null children public MsgTree(char payloadChar){} //method to print characters and their binary codes public static void printCodes(MsgTree root, String code){} } When building the tree, try a recursive solution where staticCharIdx tracks the location within the tree string. You can pass the same tree string during recursive calls, and update the staticCharIdx to point to the next character to be read. Note: if you decide to implement an iterative solution, you will receive a 15% bonus, as it is considerably more difficult. In that case, you cannot get the 5% bonus for printing statistics. printCodes() performs recursive preorder traversal of the MsgTree and prints all the characters and their bit codes: character code ———————— c 1011 r 110 b 111 You are allowed to print the header of the table (character, code, —-) in main(). 4.2. Write a method public void decode(MsgTree codes, String msg) to decode the message. It would print the decoded message to the console: MESSAGE: The quick brown fox jumped over the lazy dog. You are allowed to print “MESSAGE:” in main(). The overall output of the program should be the output of printCodes() followed by the output of decode(): character code ———————— c 1011 r 110 b 111 MESSAGE: The quick brown fox jumped over the lazy dog. 5. Submission Put your classes in the edu.iastate.cs228.hw4 package. Turn in the zip file and not your class files. Please follow the guideline in submission_guide.pdf. Include the Javadoc tag @author in each class source file. Your zip file should be named Firstname_Lastname_HW4.zip. No template files will be provided other than the skeleton in Section 4.1. 6. Extra credit (5% or 15%) Print the following statistics after the rest of the program output: STATISTICS: Avg bits/char: Total characters: 8.0 1180 Space savings: 50.0% The space savings calculation assumes that an uncompressed character is encoded with 16 bits. It is defined as (1 – compressedBits/uncompressedBits)*100. To earn a 15% non-cumulative bonus (either 5% for statistics or 15%), you can create an non-recursive, iterative solution for building the tree, but be advised that it will require hours of extra effort compared to the recursive solution. The bonus for early submission will stack with the 5/15% bonus. Name your submission Firstname_Lastname_HW4_extra.zip if you completed the iterative solution.
CIS 4301 – Spring 2025 Submission Format You will submit a soft copy of your solution using e-Learning (http://elearning.ufl.edu) by the end of the day (23:59 / 11:59 PM) on the assigned date (March 14th). Save your solution as a PDF file and name it hw4.pdf. Description Students must use the database they created in Homework 3, including all relations and inserted data. In this homework, students must create the new relations listed in the schema below and populate them with data. Step 1: Start MariaDB (0 pts) Ensure MariaDB is running on your system before executing the SQL queries. Step 2: Create New Relations and Insert Data (0 pts) Using the schema below, create and populate the new relations: • GoesOn(ssn: integer, id: integer)• Leg(Trip id: integer, startLocation: String, endLocation: String,• Owns(ssn: integer, passport number: integer, country: String)holderName: String) Populate the relations with sample data: — GoesOn (101, 201), (101, 208), (102, 202), (102, 205), (103, 203), (103, 206), (106, 206), (106, 201), (107, 207), (108, 208); — Leg (201, ‘New York’, ‘London’, ‘2025-07-10’, ‘2025-07-12’), (201, ‘London’, ‘Paris’, ‘2025-07-13’, ‘2025-07-20’), (202, ‘Tokyo’, ‘Seoul’, ‘2025-08-01’, ‘2025-08-05’), (202, ‘Seoul’, ‘Sydney’, ‘2025-08-06’, ‘2025-08-15’), (203, ‘London’, ‘Berlin’, ‘2025-09-05’, ‘2025-09-08’), (203, ‘Berlin’, ‘Rome’, ‘2025-09-09’, ‘2025-09-15’), (204, ‘Miami’, ‘Atlanta’, ‘2025-06-15’, ‘2025-06-17’), (204, ‘Atlanta’, ‘New York’, ‘2025-06-18’, ‘2025-06-20’), (205, ‘San Francisco’, ‘Frankfurt’, ‘2025-10-01’, ‘2025-10-06’), (205, ‘Frankfurt’, ‘Berlin’, ‘2025-10-07’, ‘2025-10-10’), (206, ‘Chicago’, ‘Denver’, ‘2025-09-10’, ‘2025-09-11’), (206, ‘Denver’, ‘Los Angeles’, ‘2025-09-12’, ‘2025-09-12’), (207, ‘Boston’, ‘Dubai’, ‘2025-07-05’, ‘2025-07-10’), (208, ‘New York’, ‘Istanbul’, ‘2025-09-10’, ‘2025-09-12’), (208, ‘Istanbul’, ‘Dubai’, ‘2025-09-13’, ‘2025-09-15’); — Owns (101, 5001, ‘USA’), (102, 5002, ‘Canada’), (103, 5003, ‘UK’), (104, 5004, ‘Germany’), (105, 5005, ‘France’), (106, 5006, ‘Australia’), (107, 5007, ‘Japan’), (108, 5008, ‘India’); — Passport (5001, ‘USA’, ‘2030-01-01’, ‘David Harris’), (5002, ‘Canada’, ‘2027-06-15’, ‘Sarah Connor’), (5003, ‘UK’, ‘2026-12-30’, ‘Mike Johnson’), (5004, ‘Germany’, ‘2028-05-10’, ‘Laura White’), (5005, ‘France’, ‘2029-11-20’, ‘James Miller’), (5006, ‘Australia’, ‘2027-03-25’, ‘Emma Watson’), (5007, ‘Japan’, ‘2031-09-10’, ‘Chris Evans’), (5008, ‘India’, ‘2025-07-05’, ‘Sophia Brown’); Step 3: SQL Query Exercises (100 pts) Students must solve the following SQL exercises: 3. [10 Points] Retrieve the names of travel agents who have more experience than any agent whose name starts with ’John’. 4. [10 Points] Find the SSNs of travelers who both own a passport and have gone on multiple trips. Use INTERSECT to solve this question. 5. [10 Points] Find the start and end locations of trips booked by each travel agent. You must use natural join in your query. 6. [10 Points] Find the names of travel agents who have fewer years of experience than any agent with more than 10 years of experience. 8. [10 Points] List all travel agents and the number of trips they have booked. Only show agents who have booked more than 1 trip. Use GROUP BY and HAVING to solve this question. 9. [10 Points] List the travelers who have not gone on any trips. 10. [10 Points] Find all the trips booked by travel agents with fewer than 5 years of experience. What to Submit For this assignment, submit a single PDF file named hw4.pdf containing: • Step 3: SQL Query Exercises. For each question, submit the following: – The SQL query in text format. – A screenshot of the SQL query in MariaDB. – A screenshot of the query output.
Problem Description: You were hired by a fictional internet provider called Blaze to compute yearly profits. Customers pay fixed monthly fees. Blaze makes a profit when customers do not use all the bandwidth they are allowed. Such users are called “Casual’ users. The region to which Blaze supplies internet is in the form of an n x m grid. Blaze can provide internet to each cell in the grid if desired. Each cell in the grid has either customers (one of three types as given below) or is in “Empty” or “Outage” states. Therefore, a cell can have one of five states: C: Casual customer: Instagram and TikTok S: Streamer customer: an aspiring e-celebrity with an appetite for bandwidth R: Reseller customer: provides lower-cost, lower-bandwidth internet to users off the grid E: Empty grid cell O: Outage grid cell For example, below is a 4 x 4 grid: O R O R E E C O E S O S E O R R Row and column indices start from 0. The top left cell is at coordinates (0,0). Coordinates are in the form (RowIndex,ColumnIndex). In the example above, the cell at coordinates (1,1) is E (Empty). It has a 3 x 3 neighborhood centered at the square: O R O E E C E S O Cells which are on the edge of the grid will have smaller neighborhoods. In the above example, the cell at the upper left corner, (0, 0), has 3 neighbors in a 2 x 2 neighborhood: O R E E Similarly, the cell at (3, 2), Reseller, has a 2 x 3 neighborhood which is: S O S O R R In the example neighborhood, a cell with a 3 x 2 neighborhood is (1,0): O R E E E S 2. Cell Update Rules: Each month, the state of the cell can change depending on its current state and the state of its neighbors. The rules for those are: 1. C: Casual: If the current cell is occupied by a casual user and a. If there is any reseller in its neighborhood, then the reseller causes outage in the casual user cell. Thus, the state of the cell changes from C (Casual) to O (Outage). b. Otherwise, if there is any neighbor who is a streamer, then the casual user also becomes a streamer, in the hopes of making it big on the internet. 2. S: Streamer: a. If there is any reseller in the neighborhood, the reseller causes outage for the streamer as well. b. Otherwise, if there is any Outage in the neighborhood, then the streamer leaves and the cell becomes Empty. 3. R: Reseller a. If there are 3 or fewer casual users in the neighborhood, then Reseller finds it unprofitable to maintain the business and leaves, making the cell Empty. b. Also, if there are 3 or more empty cells in the neighborhood, then the Reseller leaves, making the cell Empty. Resellers do not like unpopulated regions. 4. O: Outage: An Outage cell becomes an Empty cell, meaning internet access is restored on the billing cycle after an outage. 5. E: Empty: If the cell was empty, then a Casual user takes it and it becomes a C. 6. Additional rules: a. Any cell that (1) is not a Reseller or Outage and (2) and has (Number of Empty + Number of Outage neighbors less than or equal to 1) converts to Reseller. b. If none of the above rules apply, any cell with 5 or more casual neighbors becomes a Streamer. 7. If none of the rules apply, then the cell state remains unchanged for the next iteration. All cells update concurrently: each new state of a cell is based on the previous state of its neighbors. 3. Determining Profit: Blaze makes a profit of $1 from casual customers. Blaze does not make a profit from streamers or resellers. Profit utilization is calculated as a percentage of potential profit for each billing cycle. For example If the region grid is 12×10, then potential profit is $120 per month, as each cell is occupied by a casual user. Thus, in a single month, profit utilization is 100*C/120, where C is the number of Casual cells. The software for this project needs to compute the profit utilization over 12 billing cycles (equivalent to one year), as a percentage of maximum profit, e.g. 23. 4. Implementation Details: 1. Implement the abstract class TownCell to represent a generic cell. It has five subclasses, one for each cell type, specifically: Casual, Streamer, Reseller, Empty and Outage. These 5 subclasses need to be implemented as well. 2. The Town class has a public member variable named grid, which is a 2D array of TownCell. It stores the state of each cell and holds the objects of subclasses of TownCell. 4. Implement an ISPBusiness class, which simulates the changes in the grid for an entire year (12 monthly cycles). Note that all its functions are static. This class should: 4.1. Create the Town object and populate the grid inside it. 4.2. The main method needs to ask the user about grid generation: “How to populate grid (type 1 or 2): 1: from a file. 2: randomly with seed” 4.2.1. If the user chooses Option 1, take a file path as input. “Please enter file path:” The format of the file is given in ISP4x4.txt. The first line contains the number of rows and columns, separated by space. After the first line, the file contains lines equal to the number of rows, and each line contains as many characters as there are columns. Each character can be: C, S, R, E, or O (upper case only). The file will not deviate from this format. 4.2.2. To generate the grid randomly, ask the user for three integer values for number of rows, number of columns and seed for random number generator (in order). “Provide rows, cols and seed integer separated by spaces: “ Populate the grid with an array of size: rows x cols. Then assign each cell in it using random number generator with the given seed. Java provides a random number generator. To use it, you need to import the package java.util.Random. Next, declare and initiate a Random object like below: Random generator = new Random(); Then, random numbers can be obtained by: int newRandomValue = generator.nextInt(5); The above instruction will generate a random number between 0 and 4 that corresponds to one of the cell type as given by static variables in the TownCell class. ● Templates are provided for all classes, except subclasses. You should create 5 subclasses extending TownCell. Names of those 5 classes should be exactly: Casual, Streamer, Reseller, Empty and Outage, including case. Also use the package name exactly as: edu.iastate.cs228.hw1. ● Below is state of the grid as it changes for 12 billing cycles. This is just for illustration – you should not output the grid state but just the profit percentage. That is only output 38 for this case. How to populate grid (type 1 or 2): 1: from a file. 2: randomly with seed 2 Provide rows, cols and seed integer separated by space: 4 4 10 Start: O R O R E E C O E S O S E O R R Profit:1 After itr: 1 E E E E C C O E C O E O C E E E Profit: 4 After itr: 2 R C C C C C E C C E C E C C C C Profit: 12 After itr: 3 E R R R R O C C R R S R R R C R Profit: 3 After itr: 4 R E E E E E R R E E R E E E R E Profit: 0 After itr: 5 E C C R C C E E C C E R C C E R Profit: 8 After itr: 6 R C O E R S C C R S C E R C R E Profit: 5 After itr: 7 E R E R E R S C E R O R E R E R Profit: 1 After itr: 8 R E R E C E O O C E E E R E R E Profit: 2 After itr: 9 E C E C O C E E O C C C E C E C Profit: 8 After itr: 10 R C C C E C C C E C S C R C R R Profit: 9 After itr: 11 E R R R R O R R R O R R E R E E Profit: 0 27.60% //output a double rounded to two digits after //decimal point, followed by a percentage sign ● The only value printed by your program is profit utilization in %, as a formatted double. ● You need not worry about validating the values of rows and columns input by the user. We are assuming that user is only providing positive integers for these. 5. Junit Classes: JUnit classes include CasualTest, StreamerTest, ResellerTest, EmptyTest, OutageTest, ISPBusinessTest, TownTestand TownCellTest. You also need to create all these classes. There should be at least one test method for each function for the respective classes. You should use jUnit5. 6. Submission Write your classes and JUnit test classes in the edu.iastate.cs228.hw1 package. Also submit the text files with your JUnit tests. Your text files should be directly inside the project folder (i.e., along with src folder). Turn in the zip file, not your class files. Please follow the guideline posted in submission_guide.pdf. Include the Javadoc tag @author in each class source file. Your zip file should be named Firstname_Lastname_HW1.zip.
CIS 4301 – Spring 2025 Submission Format You will submit a soft copy of your solution using e-Learning (http://elearning.ufl.edu) by the end of the day (23:59 / 11:59 PM) on the assigned date (February 21st). Save your solution as a PDF file and name the file hw3.pdf. At the top of every solution file you submit this semester, include your name, the assignment number, and the due date. Before submitting, carefully review the ”What to Submit” section at the end of this assignment to ensure that you have included all required components. Failure to follow the submission guidelines can result in point deductions. Important Instructions Before starting this homework, **students must study the SQL 1 slides and recorded lectures** found in the **SQL 1 module** on Canvas: https://ufl.instructure.com/courses/ 527757/pages/sql-i?module_item_id=11692841 After studying the slides, **watch the SQL 1 session video** in the same module. Follow along with the video using your MariaDB to practice writing SQL queries. This will help you complete the homework successfully. Step 1: Start MariaDB (0 pts) Ensure MariaDB is running on your system before executing the SQL queries. Step 2: Create Tables and Insert Data (20 pts) Schema Use the following schema to create the necessary tables: • Booking(agent: String, traveler ssn: integer, trip id: integer)• TravelAgent(name: String, years experience: integer, phone: String)Insert Sample Data After creating the tables, insert the following records: — TravelAgent (‘Alice Brown’, 12, ‘123-456-7890’), (‘John Smith’, 8, ‘234-567-8901’), (‘Michael Johnson’, 5, ‘345-678-9012’), (‘Sarah Williams’, 15, ‘456-789-0123’), (‘Daniel Lee’, 20, ‘567-890-1234’), (‘Rachel Green’, 3, ‘678-901-2345’); — Traveler (‘David Harris’, 101, ‘1985-06-12’), (‘Sarah Connor’, 102, ‘1992-03-05’), (‘Mike Johnson’, 103, ‘1998-09-17’), (‘Laura White’, 104, ‘1995-04-23’), (‘James Miller’, 105, ‘2000-08-14’), (‘Emma Watson’, 106, ‘1997-11-30’), (‘Chris Evans’, 107, ‘1993-06-21’), (‘Sophia Brown’, 108, ‘1999-02-25’); — Trip (201, ‘New York’, ‘Paris’, ‘2025-07-10’, ‘2025-07-20’), (202, ‘Tokyo’, ‘Sydney’, ‘2025-08-01’, ‘2025-08-15’), (203, ‘London’, ‘Rome’, ‘2025-09-05’, ‘2025-09-15’), (204, ‘Miami’, ‘New York’, ‘2025-06-15’, ‘2025-06-20’), (205, ‘San Francisco’, ‘Berlin’, ‘2025-10-01’, ‘2025-10-10’), (206, ‘Chicago’, ‘Los Angeles’, ‘2025-09-10’, ‘2025-09-12’), (207, ‘Boston’, ‘Dubai’, ‘2025-07-05’, ‘2025-07-18’), (208, ‘New York’, ‘Dubai’, ‘2025-09-10’, ‘2025-09-15’); — Booking (‘Alice Brown’, 101, 201), (‘John Smith’, 102, 202), (‘Michael Johnson’, 103, 203), (‘Sarah Williams’, 104, 204), (‘Daniel Lee’, 105, 205), (‘Alice Brown’, 106, 206), (‘Rachel Green’, 107, 207), (‘John Smith’, 108, 201), (‘Alice Brown’, 101, 208); Step 3: SQL Query Exercises (80 pts) 1. [8 pts] Retrieve the names and phone numbers of all travel agents who have more than 10 years of experience. Additionally, include a new column in the output labeled 3. [8 pts] Find all trips that start in ’New York’ and end in ’Paris’. 4. [8 pts] Retrieve all information about trips that start in either ’New York’ or ’Miami’. 5. [8 pts] Retrieve all information about trips that start after ’2025-08-01’. 6. [8 pts] Retrieve the traveler SSN and trip ID for all trips booked by the travel agent ”Alice Brown”. 7. [8 pts] Find all travelers whose names have ’a’ as the second letter. You must use Patterns to solve this question. 8. [8 pts] Find all travelers who are NOT named ’David Harris’. You must use Patterns to solve this question. 9. [8 pts] Find all travel agents whose phone number starts with ’456’. You must use Patterns to solve this question. 10. [8 pts] Find all trips that start between ’2025-07-01’ and ’2025-09-30’. You must use the Keyword BETWEEN for this question. Check the SQL 1 session video to see how to use this keyword. What to Submit For this assignment, submit a single PDF file named hw3.pdf containing: • Step 2: Table Creation and Data Insertion – The SQL statements used to create tables. – The SQL statements used to insert data. – A screenshot showing successful table creation. – A screenshot showing successful data insertion. • Step 3: SQL Query Exercises. For each questions submit the following: – The SQL query in text format. – A screenshot of the SQL query in MariaDB. – A screenshot of the query output.
Programming Assignment 2 8, 16, & 32 bit checksums1 Checksum In this assignment you’ll write a program that calculates the checksum for the text in a file. Your program will take two command line parameters. The first parameter will be the name of the input file for calculating the checksum. The second parameter will be for the size of the checksum (8, 16, or 32 bits). The program must generate output to the console (terminal) screen as specified below. 1.1 Command line parameters 1. Your program must compile and run from the command line. 3. Your program should open the input text files, echo the processed input to the screen, make the necessary calculations, and then output the checksum to the console (terminal) screen in the format described below. Note All of the test data files contain a termination character LF represented as a hexadecimal ’0A’. This character is included in all the checksum calculations. 1.2 Checksum size The checksum size is a single integer, passed as the second command line argument. The valid values are the size of the checksum, which can be either 8, 16, or 32 bits. Therefore, if the second parameter is not one of the valid values, the program should advise the user that the value is incorrect with a message formatted as shown below: fprintf(stderr, “Valid checksum sizes are 8, 16, or 32 ”); The message should be sent to STDERR . 1.2.1 Format of the input file The input file specified as the first command line argument, will consist of the valid 8 bit ASCII characters normally associated with the average text file. This includes punctuation, numbers, special characters, and whitespace. 1.2.2 Output Format The program must output the following to the console (terminal) screen, also known as STDOUT: 1. Echo the text from the input file. 3. Print the checksum. 4. The checksum line should be formatted as follows : printf(“%2d bit checksum is %8lx for all %4d chars ”, checkSumSize, checksum, characterCnt); 1.3 Submission instructions You must submit this assignment in Webcourses as a source file upload. Note that all submissions will be via Webcourses. The submitted programs will be tested and graded on Eustis. 1.3.1 Code Requirements • Header – the following Header Usage instructions/comments comment block should be at the beginning of the source file. /*============================================================================= | Assignment: pa02 – Calculating an 8, 16, or 32 bit | checksum on an ASCII input file | | Author: Your name here | Language: c, c++, Java, GO, Python | | To Compile: javac pa02.java | gcc -o pa02 pa02.c | g++ -o pa02 pa02.cpp | go build pa02.go | python pa02.py //Caution – expecting input parameters | | To Execute: java -> java pa02 inputFile.txt 8 | or c++ -> ./pa02 inputFile.txt 8 | or c -> ./pa02 inputFile.txt 8 | or go -> ./pa02 inputFile.txt 8 | or python-> python3 pa02.py inputFile.txt 8 | where inputFile.txt is an ASCII input file | and the number 8 could also be 16 or 32 | which are the valid checksum sizes, all | other values are rejected with an error message | and program termination | | Note: All input files are simple 8 bit ASCII input | | +=============================================================================*/ /*============================================================================= | I [your name] ([your NID]) affirm that this program is | entirely my own work and that I have neither developed my code together with | any another person, nor copied any code from any other person, nor permitted | my code to be copied or otherwise used by any other person, nor have I +============================================================================*/ 1.4 Program Notes and Hints One possible breakdown to solve this problem is as follows: 1. Collect the command line input arguments and print them to the console. Remember to remove or comment out this test code when running the testing scripts. 2. Read the file and print it out to the console. 3. Adjust the output to print 80 characters per line. 4. Calculate the 8 bit checksum. Remember that the checksum is a running total with no overflow. 5. Resolve the calculations and padding for both 16 and 32 bit checksums. 1.5 Grading Scoring will be based on the following rubric: Table 1.1: Grading Rubric Deduction Description -100 Cannot compile on eustis -100 Program source filename is not pa02 with the appropriate language extension of .c, .cpp, .java, .go or .py. -100 Your program does not successfully compile from the command line with one of these commands: C program: prompt$gcc -o pa02 pa02.c C++ program: prompt$g++ -o pa02 pa02.cpp go: prompt$go build pa02.go python: prompt$python3 pa02.py Java program: prompt$javac pa02.java Note: • If you are submitting a Java program, the class file must be named “pa02.java” and the class name must be “pa02”. • If you are submitting a Python program, the version of Python running on Eustis is Python 3. • Make sure to submit all your code in a single source file. -100 Cannot read input parameters specified on command line -100 Cannot write output to stdout – 90 The program does not run from the command line without error or produces no output. – 70 The program compiles, runs, and outputs the input file, but crashes thereafter or produces no checksum output. – 50 Cannot write output to stderr – 20 Fails to produce valid 8 bit checksum – 20 Fails to produce valid 16 bit checksum – 20 Fails to produce valid 32 bit checksum – 25 Does not have Header Usage instructions/comments statement 1.6 Testing 1.6.1 Baseline There are 5 baseline files included in the ZIP file. (Additional test files are described in the next section.) The filename and their corresponding checksums are shown in the table below: Table 1.2: Baseline Test Schema Filename 8 bit checksum 16 bit checksum Pad 32 bit checksum Pad Input (hex) i1.txt 6b 610a – 610a5858 XX 610a i2.txt cc 6bb9 X 61610a58 X 61610a i3.txt 2d c26b – 6161610a – 6161610a i4.txt 8e cd1a X 6bb9b9b9 XXX 616161610a i5.txt ef 23cc – c26bb9b9 XX 61616161610a Results were obtained using the command: bash basetest.sh pa02.|c|cpp|java|py 1.7 Testscript output This script (pa02test.sh) is run on Eustis or other bash supported terminal command lines as shown below. Successful output is also shown below. ./pa02test.sh pa02.java Compile of pa02 succeded. -> Case #1 – in10A.txt – 8 bit checksum -> Case #1 – in10A.txt – 16 bit checksum -> Case #1 – in10A.txt – 32 bit checksum -> Case #2 – in17A.txt – 8 bit checksum -> Case #2 – in17A.txt – 16 bit checksum -> Case #2 – in17A.txt – 32 bit checksum -> Case #3 – in18A.txt – 8 bit checksum -> Case #3 – in18A.txt – 16 bit checksum -> Case #3 – in18A.txt – 32 bit checksum -> Case #4 – inRF2.txt – 8 bit checksum -> Case #4 – inRF2.txt – 16 bit checksum -> Case #4 – inRF2.txt – 32 bit checksum -> Case #5 – inWC2.txt – 8 bit checksum -> Case #5 – inWC2.txt – 16 bit checksum -> Case #5 – inWC2.txt – 32 bit checksum Checksum testing completed 1.7.1 Advanced Testing There are eight input test files of significantly more varied content than used in the Baseline Test Schema shown above. 1. Every input file has a single line of text terminated by the hexadecimal character ’0A’ or the NEWLINE character. 2. Some input files are less than 80 characters long, others aren’t. 3. More testing files are supplied than are used in the pa02test.sh script. 4. After uploading the testing shell script (and corresponding files) remember to execute the command chmod +x *.sh to grant execution privileges for the script. 5. The script is executed at the command line by the command bash pa02test.sh pa02.c or ./pa02test.shpa02.c where the checksum program filename has the correct extension for your submission. Valid extensions are .c for C, .cpp for C++, .java for Java, .go for Go, and .py for Python. 1.7.2 Simple test cases 1. simple input files a) i1.text contains a single lowercase a followed by the hexadecimal character ’0A’ or the NEWLINE character. i. All three possible checksum sizes would output as shown below: hw/pa2$java pa02 i1.txt 8 a 8 bit checksum is 6b for all hw/pa2$java pa02 i1.txt 16 a 2 chars 16 bit checksum is 610a for all hw/pa2$java pa02 i1.txt 32 a XX 2 chars 32 bit checksum is 610a5858 for all hw/pa2$ 4 chars
Programming Assignment 1 Hill Cipher1 Hill Cipher In this assignment you’ll write a program that encrypts the alphabetic letters in a file using the Hill cipher where the Hill matrix can be any size from 2×2 up to 9×9. Your program will take two command line parameters containing the names of the file storing the encryption key and the file to be encrypted. The program must generate output to the console (terminal) screen as specified below. 1.1 Command line parameters 1. Your program mustcompile and run from the terminalcommandline. 3. Your program should open the two files, echo the processed input to the screen, make the necessary calculations, and then output the ciphertext to the console (terminal) screen in the format described below. 4. Your program must be named pa01 for whichever language you choose. For example, pa01.c, pa01.cpp, pa01.java, pa01.py, or pa01.go. Note If the plaintext file to be encrypted doesn’t have the proper number of alphabetic characters to match the key size, pad the last block as necessary with the lowercase letter x. Make sure that all the input characters are lower case only. 1.2 Formats 1.2.1 Encryption Key File Formats The encryption key file will contain a single positive integer, n where (1 < n < 10), on the first line, indicating the number of rows and columns in the encryption matrix. The following n lines will contain n integers, in each row, in order, of the encryption matrix, separated by spaces. 1.2.2 Encryption Plaintext File Formats 1.2.3 Output Format The program must output the following to the console (terminal) screen, also known as stdout: 1. Echo the numbers from the input key file. 2. Echo the lowercase alphabetic text derived from the input plaintext file. • Remember to pad with x if the processed plaintext does not match the block size of the key. 3. Ciphertext output produced from encrypting the input key file against the input array specified in the key file.1.2.4 Program Execution The program, pa01, expects two inputs at the command line. • The first parameter is the name of the key file,which contains a single positive integer, n where (1 < n < 10), on the first line, indicating the number of rows and columns in the encryption matrix. The following n lines will contain the contents of each row, in order, of the encryption matrix, separated by spaces. 1.2.5 Program execution – example Notethatthecommandsbelowarealsooutlinedlateroninthisdocumentforeitherc,c++,Java, Go, or Python. Also note that the first parameter is the key filename and the second parameter is the plaintext filename. systemPrompt$ gcc -o pa01 pa01.c systemPrompt$ ./pa01 kX.txt pX.txt A sample program execution with outputs is shown below. It is explained in more detail later on in the Section Sample inputs and outputs on page 6. systemPrompt$./pa01 k1.txt p1.txt Key matrix: 2 4 3 5 Plaintext: notonlyistheuniversestrangerthanwethinkitisstrangerthanwecanthinkwernerheisenber gx Ciphertext: efqxsqciitepovwzytawitizyrytooaniiooqlassteocmancmgqovktqwanooqlekytqhkioaawesyt ad 1.3 Submission instructions You must submit this assignment in Webcourses as a source file upload. Note that all submissions will be via Webcourses. The submitted programs will be tested and graded on Eustis. 1.3.1 Code Requirements • Program name – the program name must be pa01 in order to work with the shell scripts the graders use to grade your assignment. As mentioned before, the program must be named pa01 for whichever language you choose. For example, pa01.c, pa01.cpp, pa01.java, pa01.py, or pa01.go. • Header – the following Header Usage instructions/comments comment block should be at the beginning of the source file. /*============================================================================ | Assignment: pa01 – Encrypting a plaintext file using the Hill cipher | | Author: Your name here | Language: c, c++, Java, go, python | | To Compile: javac pa01.java | gcc -o pa01 pa01.c | g++ -o pa01 pa01.cpp | go build pa01.go | | To Execute: java -> java pa01 kX.txt pX.txt | or c++ -> ./pa01 kX.txt pX.txt | or c -> ./pa01 kX.txt pX.txt | or go -> ./pa01 kX.txt pX.txt | or python -> python3 pa01.py kX.txt pX.txt | where kX.txt is the keytext file | and pX.txt is plaintext file | Note: | All input files are simple 8 bit ASCII input | All execute commands above have been tested on Eustis | +===========================================================================*/ /*============================================================================= | I [your name] ([your NID]) affirm that this program is | entirely my own work and that I have neither developed my code together with | any another person, nor copied any code from any other person, nor permitted | my code to be copied or otherwise used by any other person, nor have I +=============================================================================*/ 1.4 Program Notes and Hints One possible breakdown to solve this problem is as follows: 1. Write a section of code or function that reads only the upper and lower case letters in the input file into an char array of size 10,000, storing only the appropriate lowercase letters in the character array. 2. Write a section of code or function that takes as input the array from section 1 and the encryption key and produces an array of ciphertext storing only lowercase letters. 3. Write a section of code or function that takes as input the array storing the ciphertext and outputs it to the screen in the format specified. Additional functions or code will be needed to echo the input key and plaintext files. 1.5 Sample inputs and outputs 1.5.1 Sample Key File 2 2 4 3 5 This is k1.txt in the Programming Assignment 1 ZIP file. 1.5.2 Sample Plaintext File “Not only is the Universe stranger than we think, it is stranger than we can think.” Werner Heisenberg This is p1.txt in the Programming Assignment 1 ZIP file. 1.5.3 Sample Ciphertext Output File efqxsqciitepovwzytawitizyrytooaniiooqlassteocmancmgqovktqwanooqlekytqhkioaawesyt ad 1.5.4 Sample console output (stdout) systemPrompt$./pa01 k1.txt p1.txt Key matrix: 2 4 3 5 Plaintext: notonlyistheuniversestrangerthanwethinkitisstrangerthanwecanthinkwernerheisenber gx Ciphertext: efqxsqciitepovwzytawitizyrytooaniiooqlassteocmancmgqovktqwanooqlekytqhkioaawesyt ad Notes • The file type titles (Key matrix, Plaintext, & Ciphertext) are preceded by a newline or . Likewise after the titles, there is a newline or . • Each 80 character plaintext or ciphertext line is likewise terminated by a newline or . 2 Matrix multiplication review A quick review of matrix multiplication: In mathematics, particularly in linear algebra, matrix multiplication is a binary operation that produces a matrix from two matrices. For matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix. The resulting matrix, known as the matrix product, has the number of rows of the first and the number of columns of the second matrix. The product of matrices A and B is denoted as AB. In the pseudocode below, the product AB is C.1 Remember that in the HillCipher the key matrix has the same number of columns as rows, and is also known a square matrix.Algorithm1 MATRIX-MULTIPLY(A, B)1: if A.columns 6= B.rows then 2: error incompatible dimensions 3: else 4: let C be a new A.rows X B.columns matrix 5: for i = 1 → A.rows do 6: for j = 1 → B.columns do 7: ci j = 0 8: for k = 1 → A.columns do2.1 Grading Scoring will be based on the following rubric: Table 2.1: Grading Rubric Deduction Description -100 Cannot compile on eustis -100 Your program does not successfully compile from the command line with one of these commands: C program: systemPrompt$gcc -o pa01 pa01.c C++ program: systemPrompt$g++ -o pa01 pa01.cpp Go program: systemPrompt$go build pa01.go Python program: systemPrompt$python3 pa01.py Java program: systemPrompt$javac pa01.java Note: IfyouaresubmittingaJavaprogram,theclassfilemustbenamed“pa01.java” and the class name must be “pa01”. If you are submitting a Python program, the version of Python running on Eustis is Python 3. -100 Cannot read input files specified on command line -100 Program source filename is not pa01 with the appropriate language extension of .c, .cpp, .java, .go or .py. -100 Cannot write output to stdout – 90 Your program does not run from the command line without error or produces no output. – 70 The program compiles, runs, and outputs the key and input file, but crashes thereafter or produces no encryption output. – 50 Runs without crashing but produces nomeaningful encryption output – 20 Fails to produce valid square matrix key based on the input key file – 20 Fails to produce valid all lowercase alphabetic plain text – formatted to 80 columns per line – 25 Does not have Header Usage instructions/comments statement
The ProblemUsing C programming language write a program that simulates a variant of the Tiny Machine Architecture. In this implementation memory (RAM) is split into Instruction Memory (IM) and Data Memory (DM). Your code must implement the basic instruction set architecture (ISA) of the Tiny Machine Architecture:1 → LOAD 2 → ADD 3 → STORE 4 → SUB 5 → IN 6 → OUT 7 → END 8 → JMP 9 → SKIPZEach piece of the architecture must be accurately represented in your code (Instruction Register, Program Counter, Memory Address Registers, Instruction Memory, Data Memory, Memory Data Registers, and Accumulator). Data Memory will be represented by an integer array. Your Program Counter will begin pointing to the first instruction of the program.Hint: Implementing a struct for your Instructions and an array of these structs as your Instruction Memory greatly simplifies this program.Example:typedef struct { int opCode, device Or Address; } Instruction;Instruction IM[MAXPROGRAMSIZE];Note: IM, MDR1, and IR are of type Instruction. All other CPU registers and Data Memory (DM) are of type int.Input SpecificationsYour simulator must run from the command line with a single input file as a parameter to main. This file will contain a sequence of instructions for your simulator to store in “Instruction Memory” and then run via the fetch/execute cycle. In the input file each instruction is represented with two integers: the first one represents the opcode and the second one a memory address or a device number depending on the instruction.Example:Input File 5 5 //IN 5 6 7 //OUT 7 3 0 //STORE 0 5 5 //IN 5 6 7 //OUT 7 3 1 //STORE 1 1 0 //LOAD 0 4 1 //SUB 1 3 0 //STORE 0 6 7 //OUT 7 1 1 //LOAD 1 6 7 //OUT 7 7 0 //ENDOutput SpecificationsYour simulator should provide output according to the input file. Along with this output your program should provide status messages identifying details on the workings of your simulator. Output text does not have to reflect my example word-for-word, but please provide detail on the program as it runs in a readable format that does not conflict with the actual output of your simulator. After each instruction print the current state of the Program Counter, Accumulator, and Data Memory. The INPUT instruction is the only one that should prompt an interaction from the user.Example:Assembling Program… Program Assembled.Run.PC = 10 | A = NULL | DM = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]/* input value */ XPC = 11 | A = X | DM = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]/* outputting accumulator to screen */ X PC = 12 | A = X | DM = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]/* storing accumulator to memory location 0 */ PC = 13 | A = X | DM = [X, 0, 0, 0, 0, 0, 0, 0, 0, 0]… etcProgram complete.GradingFor instance, to implement FETCH and instruction LOAD you must implement each step:FETCH MAR PC PC PC + 1 MDR IM [MAR] // IM stands for Instruction Memory (program memory) IR MDRCase IR.OP = 1 Load is executed.LOAD (Execute cycle) MAR2 IR.ADDR MDR2 DM [MAR2] //DM stands for Data Memory A MDR2SubmissionYour program must be submitted as a C file. For example: NameMyProgram.c Please check and double check your submission.Note: you can use one or two MARs, MAR for IM and MAR2 for DM.Tiny Machine ISA:FETCH MAR PC PC PC + 1 MDR IM [MAR] // IM stands for Instruction Memory (program memory) IR MDRDepending on IR.OP one of the following instructions will be executed: (Execute cycle)LOAD MAR2 IR.ADDR MDR2 DM[MAR2] A MDR2ADD MAR2 IR.ADDR MDR2 DM[MAR2] A A + MDR2STORE MAR2 IR.ADDR MDR2 A DM[MAR2] MDR2SUB MAR2 IR.ADDR MDR2 DM[MAR2] A A – MDR2IN A Input value from keyboardOUT Screen AEND Run 0 // In your program Run must be initialized to 1 to control the instruction cycle.JMP PC IR.ADDRSKIP IF (A == 0) PC PC + 1