Questions
Please convert this code written in Python to Java: import string import random #function to add...

Please convert this code written in Python to Java:

import string
import random

#function to add letters
def add_letters(number,phrase):
   #variable to store encoded word
   encode = ""
  
   #for each letter in phrase
   for s in phrase:
       #adding each letter to encode
       encode = encode + s
       for i in range(number):
           #adding specified number of random letters adding to encode
           encode = encode + random.choice(string.ascii_letters)
   #returns encoded word
   return encode
#function to remove letters
def remove_letters(number,phrase):
   #variable to store decoded word
   decode = ""
  
   #iterating each letter in phrase
   for i in range(len(phrase)):
       #if i % number + 1 is zero
       if i % (number + 1) == 0:
           #adding letters in specified position to decode
           decode = decode + phrase[i]
   #returns decoded word
   return decode

#repeat until user wants to quit
while True:
   print("")
   #prompt for user option
   userOption = input("(e)ncode, (d)ecode, (q)uit: ")
  
   #if option is encode
   if userOption == "e":
       #prompt for number
       number = int(input("Enter a number between 1 and 5: "))
      
       #repeat until number is valid
       while True:
           #if number is valid
           if number >= 1 and number <= 5:
               break
           #if number is not valid
           else:
               print("Try Again...")
              
               #prompt for number
               number = int(input("Enter a number between 1 and 5: "))
      
       #prompt for phrase to encode
       phrase = input("Enter a phrase to encode: ")
      
       #calling function add_letters and printing encoded word
       print("Your encoded word is: "+add_letters(number,phrase))
  
   #if option is decode
   elif userOption == "d":
       #prompt for number
       number = int(input("Enter a number between 1 and 5: "))
      
       #repeat until number is valid
       while True:
           #if number is valid
           if number >= 1 and number <= 5:
               break
           #if number is not valid
           else:
               print("Try Again...")
              
               #prompt for number
               number = int(input("Enter a number between 1 and 5: "))
      
       #prompt for phrase to decode
       phrase = input("Enter a phrase to decode: ")
      
       #calling function remove_letters and printing decoded word
       print("Your decoded word is: "+remove_letters(number,phrase))
      
   #if option is quit
   elif userOption == "q":
       break
      
   #if option is wrong option
   else:
       print("Try Again...")

In: Computer Science

***USE JAVA AND NO IMPORTS*** Method editString takes a string and breaks it into an array...

***USE JAVA AND NO IMPORTS***

Method editString takes a string and breaks it into an array of single
       words which are then are edited based on the command
       Possible Commands:
       remove: for the sent words, remove those from the text
       replace: replace the word in an even element of words with a word in an odd element of words
       add: add the word given word in the index indicated after the word

       editString("What is up bro", "remove", ["bro"]) returns ["What", "is", "up"]
       editString("What is up bro", "replace", ["bro", "brother"]) returns ["What", "is", "up", "brother"]
       editString("What is up", "add", ["my", "3", "friend", "4"]) returns ["What", "is", "up", "my", "friend"]
       editString("I can only do so much", "remove", ["only", "so"]) returns ["I", "can", "do", "much"]
       editString("Tis but a flesh wound", "replace", ["flesh", "scratch", "wound", "mark"]) returns ["Tis", "but", "a", "scratch", "mark"]
       editString("I can code in java", "add", ["html", "4", "and", 5]) returns ["I", "can", "code", "in", "html", "and", "java"]
       @param text String of words
       @return an array of lowercased words in alphabetical order
   */
   public static ArrayList<String> editString(String text, String command, ArrayList<String> words)
   {
       ArrayList<String> edited = new ArrayList<String>();

   return edited;
   }//end editString

In: Computer Science

using java with proper header and comments: This exercise will give you a review of Strings...

using java with proper header and comments:

This exercise will give you a review of Strings and String processing. Create a class called MyString that has one String called word as its attribute and the following methods: Constructor that accepts a String argument and sets the attribute. Method permute that returns a permuted version of word. For this method, exchange random pairs of letters in the String. To get a good permutation, if the length of the String is n, then perform 2n swaps. Use this in an application called Jumble that prompts the user for a word and the required number of jumbled versions and prints the jumbled words. For example, Enter the word: mixed Enter the number of jumbled versions required: 10 xdmei eidmx miexd emdxi idexm demix xdemi ixdme eximd xemdi xdeim Notes: 1. It is tricky to swap two characters in a String. One way to accomplish this is to convert your String into an array of characters, swapping the characters in the array, converting it back to a String and returning it. char[] chars = word.toCharArray(); will convert a String word to a char array chars. String result = new String(chars); converts a char array chars into a String. p 6 2. Use Math.random to generate random numbers. (int)(n*Math.random()) generates a random number between 0 and n-1

In: Computer Science

Each of the following represents a change from an adult pronunciation to a child's pronunciation.


Each of the following represents a change from an adult pronunciation to a child's pronunciation. By comparing the adult pronunciation with the child's pronunciation, identify the phonetic processes that have occurred in the child's form of the word. There are at least two processes for each item.

 Word Adult Pronunciation Child's Pronunciation Phonetic Processes

 a. drain

 b. shape

 c. elevator

image.png

In: Psychology

Q1. The Total Risk of an Individual Share Comprises Both Systematic and Unsystematic Risk. How are...

Q1. The Total Risk of an Individual Share Comprises Both Systematic and Unsystematic Risk. How are these Affected by increasing the Number of Shares in a Portfolio? (approx 200 word)

Q2. Why are Investors Only Focused on Market Risk When Applying the Capital Asset Pricing Model (CAPM)  to Price Risk Securities? (approx 200 word)

In: Finance

1.Assume you are a credit officer in a reputed Licensed Commercial Bank and is assigned to...

1.Assume you are a credit officer in a reputed Licensed Commercial Bank and is assigned to evaluate a credit proposal (individual). Explain the lending principles followed in evaluating the credit proposal. (maximum word limit is 750 words)

2. Define “Bank failure” and discuss the determinants of bank failures. (maximum word limit is 750 words)

In: Finance

In PYTHON: Write a function that receives a sentence and returns the last word of that...

In PYTHON:

Write a function that receives a sentence and returns the last word of that sentence. You may assume that there is exactly one space between every two words, and that there are no other spaces at the sentence.

To make the problem simpler, you may assume that the sentence contains no hyphens, and you may return the word together with punctuation at its end.

In: Computer Science

Identify and evaluate predictors & consequences of dropping out of College. Discuss any societal and family...

Identify and evaluate predictors & consequences of dropping out of College. Discuss any societal and family concerns that will impact the choice of dropping out.

Refer to any scholarly article which connects to the topic to create a Word document with a 500-750 word-count. Include factual connections, Include a minimum of two references, including the text.

In: Psychology

This program focuses on programming with Java Collections classes. You will implement a module that finds...

This program focuses on programming with Java Collections classes. You will implement a module that finds a simplified Levenshtein distance between two words represented by strings.

Your program will need support files LevenDistanceFinder.Java, dictionary.txt, while you will be implementing your code in the LevenDistanceFinder.java file.

INSTRUCTIONS

The Levenshtein distance, named for it's creator Vladimir Levenshtein, is a measure of the distance between two words. The edit distance between two strings is the minimum number of operations that are needed to transform one sting into the other. For a full implementation of the distance we would need to account for three different types of operations, removing a letter, adding a letter, or changing a letter.

For THIS program however, we are going to focus solely on the ability to change one letter to another. So, we will be thinking of changing one letter at a time, while maintaining the fact that the word is a still a valid word at all times.

So, for an example, the edit distance from "dog" to "cat" is 3. One possible path for this is

"dog" to "dot" to "cot" to cat"

Note, that there might be other paths, but they all involve at least 3 changes. Another longer example is from "witch" to "coven".

witch->watch->match->march->marcs->mares->mores->moves->coves->coven

You will be implementing a secondary class called LevenshteinFinder that will be used by the main program to solve the problem.

You are given a client program LevenDistanceFinder.java that does the file processing and user interaction. LevenDistanceFinder.java reads a dictionary text file as input and passes its entire contents to you as a list of strings. You are to write a class called LevenshteinFinder that will manage the actual work of finding the distance and the path.

The class will probably have the following necessary private fields:

  • Starting and Ending Strings

  • A map of words to a set of neighbors.

  • An integer distance that starts at -1.

  • A List of strings that is the path itself.

PUBLIC LEVENSHTEINFINDER(STRING, STRING, SET<STRING> )

Your constructor is passed a string which is the starting word of the path. A string that is the ending word of the path, and a collection of words as a set. It should use these values to initialize the class. The set of words will initially be all words from the dictionary.

You should throw an IllegalArgumentException if length of the two words is not the same.

You will want to store the starting and stopping words for later use, but you should not need to save the words list. First you will want to pull out only the words that are of the correct size. Then from this smaller list, what you will want to do is to create a map of words to their "neighbor" words. Start this by going through every word and add it and an empty set, to a map.

You will then go through the set a second time and check every word to every other word. If they are "neighbors" you will add each word to the set that goes with the other word. So if stringA and stringB are neigbors, then you add stringA to stringB's set, and vice versa.

Once the neighbor map is created, you will run the findDistacnce method and the findPath method to save those values for future delivery.

Note that this is all done in the constructor, so that all the work is done when it is “newed”/created.

PRIVATE INT DIFFERENTLETTERS(STRING A, STRING B)

This method should take two strings and find the number of letters that are different from each other and return that number.

PUBLIC INT GETDISTANCE()

This method is called by the main program to get the distance between the two words. Note that you found this in a different method. So this should just return a saved value. If it is longer than 2 lines, you are doing it wrong.

PUBLIC STRING GETPATH()

This method returns a string that is the path from the first word to the second word, assuming it exists. If the path distance is negative one, then return back an error message, if the path distance is zero or higher, then take the pathArray and convert it to a string with arrows in between.

Example: love->lave->late->hate

PRIVATE INT FINDDISTANCE(STRING A, STRING B)

This method finds the distance between two strings. (Note, only the distance, not the path itself). Start by creating two empty sets. Add the staring word to the second set. Set a counter to zero. Then while the sets are different sizes and the 2nd set does not contain the ending word, add everything from set 2 into set one, clear the 2nd set, and then take every word from set1 AND the neighbor of every word from set1 into set 2. Increment the loop counter.

When the loop finishes, if the 2nd set contains the final word return the counter because it was found, if the 2nd set doesn't contain the word, return -1 because there is no path.

PRIVATE VOID FINDPATH(STRING A, STRING B)

This method will find the path between two words. It should probably be the last method you work on. In fact I would create it, and have it do nothing until you are ready for it.

When running this method should only be run after findDistance() so that the distance has already been found and stored in a private int value.

When you are ready for it, this method should do the following.
Initialize the class path List to a new empty List.
Check the distance, if it is negative, store an error message in the path List and then exit the method. If the distance is zero or positive add the first element to the list.

Now in a loop that starts at the distance minus 1, and goes down until 1, look at the set of neighbors of the word in the last box of the list. Find one that has a distance to the ending word that matches the current loop counter. There may be multiples, but there has to be at least one. Find this word, and add it to the list.

Now repeat the loop until the for loop quits. Then add the ending word to the list. You are done.
Here is an example for the path from love -> hate.

The distance from love to hate is 3, so that is bigger than -1. So add love to the list. The list is now size one. Now start your loop from distance -1 (2) to 1. So i is currently 2. Find any word in the neighbor of love, that has a distance to hate of size 2. Use your findDistance method here!. One of those words is "lave". So add that to the array.

Next round, i is one. The list is now [love, lave]. So find a neighbor of "lave" that has a distance to "hate" of one. One possible word is "late". So add "late" to the list which now looks like [love, lave, late]

That should finish the loop, add "hate" to the list. The final list looks like [love, lave, late, hate]. Store that list in the class field. And you are done.

Your program should exactly reproduce the format and general behavior demonstrated on the previous pages.

You may assume that the list of words passed to your constructor will be a nonempty list of nonempty strings composed entirely of lowercase letters.

Use the TreeMaps, TreeSets and ArrayLists implementations for all of your ADT's.

HINTS

If you have not had to deal with exceptions before the proper way to throw and exception is the following: throw new IlleagalStateException() or IllegalArgumentEXception() as appropriate. This will end your method and return back to the primary program.

In: Computer Science

**** PLEASE DO NOT COPY AND PASTE FROM ANOTHER SOURCE BECAUSE THE ANSWER IS INCOMPLETE********* Introduction:...

**** PLEASE DO NOT COPY AND PASTE FROM ANOTHER SOURCE BECAUSE THE ANSWER IS INCOMPLETE*********

Introduction: IN C PROGRAMMING

For this assignment you will write an encoder and a decoder for a modified "book cipher." A book cipher uses a document or book as the cipher key, and the cipher itself uses numbers that reference the words within the text. For example, one of the Beale ciphers used an edition of The Declaration of Independence as the cipher key. The cipher you will write will use a pair of numbers corresponding to each letter in the text. The first number denotes the position of a word in the key text (starting at 0), and the second number denotes the position of the letter in the word (also starting at 0). For instance, given the following key text (the numbers correspond to the index of the first word in the line)

[0] 'Twas brillig, and the slithy toves Did gyre and gimble in the wabe;

[13] All mimsy were the borogoves, And the mome raths outgrabe.

[23] "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!

[36] Beware the Jubjub bird, and shun The frumious Bandersnatch!"

[45] He took his vorpal sword in hand: Long time the manxome foe he sought—

The word "computer" can be encoded with the following pairs of numbers:

35,0 catch!

5,1 toves

43,3 frumious

48,3 vorpal

22,1 outgrabe.

34,3 that

23,6 "Beware

7,2 gyre

Placing these pairs into a cipher text, we get the following:

35,0,5,1,43,3,48,3,22,1,34,3,23,6,7,2

If you are encoding a phrase, rather than just a single word, spaces in the original english phrase will also appear in the ciphered text. So, the phrase "all done" (using the above Jabberwocky poem) might appear as: 0,3,1,4,13,1 6,0,46,2,44,2,3,2

Only spaces in the key text should be considered delimiters. All other punctuation in the key text are to be considered part of a key word. Thus the first word in the Jabberwocky poem, 'Twas, will have the following characters and positions for key word 0:

Position 0: '

Position 1: T

Position 2: w

Position 3: a

Position 4: s

Developing the Program:

You should approach this assignment in several parts. The first part will be to write a menu driven program that prompts the user for the following actions:

  1. Read in the name of a text file to use as a cipher key
  2. Create a cipher using the input text file (and save the result to a file)
  3. Decode an existing cipher (prompt user for a file to read containing the cipher text)
  4. Exit the program

For each choice, create a stub function that will be completed in the remaining steps.

After testing your menu, continue to fill in the stub functions with the following specifications:

Choice #1

For this menu choice, you will prompt the user for the name of a cipher text file (such as the Declaration of Independence). You will read this text file line by line, and place each word, in order, in an array of char strings. As you copy each word into the array, you will keep a running count of the number of words in the text file and convert the letters of each word to lower case. You may assume that you will use no more than the first 5,000 words in the text, and no more than the first 15 characters in a word. However, there is no guarantee that the text will have 5000 words or less and any word in the text is 15 characters or less.

Choice #2

If no file has been chosen for Choice #1 (i.e. the user goes directly to Choice #2 without first choosing Choice #1), you will first prompt the user to enter a cipher text and read it into memory (presumably by calling the function that would be called by Choice #1). You will prompt the user to enter a secret message (in plain text - such as "Computer Science is the best major at GMU!") that is terminated by pressing the "Enter" key. You can assume that the length of this message will be less than 1500 characters (including the carriage return and NULL terminator). You will then parse this message, character by character, converting them to lower case as you go, and find corresponding characters in the words found in the key text word array. You can do this by going through each word in the word array, and then each character in each word, until you find a match with the current message character. There are more efficient ways to perform this operation, and you are encouraged to implement them instead of the given method. Once a character match is found, you will write the index of the word and the index of the character to a character string that you will later write out to a text file. Spaces are to be placed into the text as found in the message and will be used to delimit the separate words in the secret message. Once the message has been encoded, prompt the user for the name of a file to save the encoded message to, and save it to that file.

Choice #3

You will prompt the user for the name of a file containing an encoded text (i.e. a file containing number pairs). Your program will read the file and decode the the text using the indexes pairs given for each character in the word and the text file chosen for Choice #1. If no file has been chosen for Choice #1 (i.e. the users goes directly to Choice #3 without first choosing Choice #1), you will prompt the user to enter a cipher text and read it into memory (presumably by calling the function that would be called by Choice #1). Spaces found in the file are to be treated as spaces in the decoded text. You can assume that the number of characters in the encoded text file is 5000 or less, including any carriage returns or NULL terminator characters. Once the text is decoded, print the message to standard output.

Choice #4

Exit the program.

Additional Specifications:

  • In order to introduce some "randomness" in the specific character encoding, you will generate a random number i from 0..9 inclusive (use the last four digits of your G Number as the seed), and use the ith instance of that character found in the text. (If fewer than i instances of the character is found in the text, loop back and continue the search from the beginning of the document.)
    • Example: Suppose the letter to encode is a 'c'. Using the sentences just above, we find that there are the following 'c' characters:
      • In order to introduCe some "randomness" in the speCifiC CharaCter enCoding, you will generate a random number i from 0..9 inClusive (use the last four digits of your G Number as the seed), and use the ith instanCe of that CharaCter found in the text.
      • If the random number returns 6, then you will use the 'c' from the word "inclusive." (Start counting from 0). If the random number returns 2, you would the second c found in the word "specific."
  • If a given character in the secret message is not found in any word of the text, replace that character with the '#' character in the encoded text (a single '#' character replaces a word/position pair).
  • Files and filenames will follow the standard CS262 conventions (username, lab section, etc. at top of file, and as part of filename).
  • Each menu choice (except #4) should call a separate function to perform the operation.
  • You can assume that the message to encrypt or decrypt will be less than 1500 characters.
  • Your program will be compiled using a Makefile

Predefined C functions that may be useful for this project:

strtok()

strlen()

tolower()

atoi()

Options for extra credit:

  1. Use dynamic memory for the arrays (up to 5 points additional credit)
  2. Finding the original Beale treasure and sharing it with your professor (up to 1000 points additional credit)

In: Computer Science