Question

Neo needs to break into the server room, but he has only partial information about the...

Neo needs to break into the server room, but he has only partial information about the code that opens the door. Parts of the code are known, and other parts have been narrowed down to several options, which are listed inside parentheses. He also knows the sum of all of the digits in the code. Write a recursive method that will find the correct code.

If the given pattern was “1(2,34)5(3,2)”, then the code must start with 1 and have a 5 in the middle. The numbers in parentheses are different choices for those parts of the code. The possible codes in this case would be 1253, 1252, 13453, and 13452. If the target sum was 11, then the answer would be 1253. Some possible inputs would not lead to a unique code. In that case, return any code that adds up to the correct total.

Hints:

  1. Assume that the input is well-formed. You don’t need to worry about patterns where the parentheses don’t match up, for example.
  2. Since the characters for 0-9 are in order in the ASCII standard, you can easily get the value of a character as an int by doing this: achar - ‘0’
  3. To approach this problem recursively, your code needs to make a decision, and then attempt to solve the rest of the problem. There are two key questions: How can you make the problem smaller? How can you backtrack to change your decision if it turns out to be wrong?

public class CodeBreaker {
public String breakCode(String pattern, int target) {
return null;
}
}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

// CodeBreaker.java

public class CodeBreaker {

      // required method, returns the pattern in which sum of digits equals

      // target, or null if no such patterns exist

      public String breakCode(String pattern, int target) {

            // checking if pattern contains "("

            if (pattern.contains("(")) {

                  // finding the first indices of ( and )

                  int index1 = pattern.indexOf("(");

                  int index2 = pattern.indexOf(")");

                  // taking String before ( from pattern

                  String before = pattern.substring(0, index1);

                  // taking String after )

                  String after = pattern.substring(index2 + 1);

                  // taking String between ( and ), splitting by comma to get an array

                  // of values containing choices that can be used

                  String values[] = pattern.substring(index1 + 1, index2).split(",");

                  // looping through each value in the array

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

                        // calling breakCode method recursively, using values[i] as

                        // subsititute (i.e concatenated before,values[i] and after)

                        String str = breakCode(before + values[i] + after, target);

                        //if the resultant string is non null, returning it

                        if (str != null) {

                              return str;

                        }

                  }

            }

            //if string does not contain "(", checking if sum of digits equals target

            else if (sumDigits(pattern) == target) {

                  //found, returning pattern

                  return pattern;

            }

            //not found, returning null

            return null;

      }

      // private helper method to find the sum of digits in a string, assuming str

      // consist of digits only

      private int sumDigits(String str) {

            if (str.length() == 0) {

                  // base case, returning 0

                  return 0;

            }

            // finding digit at first index

            int i = str.charAt(0) - '0';

            // adding to the sum of digits of remaining String, after taking a

            // substring ignoring the first character

            return i + sumDigits(str.substring(1));

      }

}

Add a comment
Know the answer?
Add Answer to:
Neo needs to break into the server room, but he has only partial information about the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • JAVA Recursion: For this assignment, you will be working with various methods to manipulate strings using...

    JAVA Recursion: For this assignment, you will be working with various methods to manipulate strings using recursion. The method signatures are included in the starter code below, with a more detailed explanation of what function the method should perform. You will be writing the following methods: stringClean() palindromeChecker() reverseString() totalWord() permutation() You will be using tools in the String class like .substring(), .charAt(), and .length() in all of these methods, so be careful with indices. If you get stuck, think...

  • I need help making this work correctly. I'm trying to do an array but it is...

    I need help making this work correctly. I'm trying to do an array but it is drawing from a safeInput class that I am supposed to use from a previous lab. The safeInput class is located at the bottom of this question I'm stuck and it is not printing the output correctly. The three parts I think I am having most trouble with are in Bold below. Thanks in advance. Here are the parameters: Create a netbeans project called ArrayStuff...

  • this needs to be in Java: use a comparator class which is passed into the sort...

    this needs to be in Java: use a comparator class which is passed into the sort method that is available on the ArrayList. import java.util.Scanner; public class Assign1{ public static void main(String[] args){ Scanner reader = new Scanner (System.in); MyDate todayDate = new MyDate(); int choice = 0; Library library = new Library(); while (choice != 6){ displayMainMenu(); if (reader.hasNextInt()){ choice = reader.nextInt(); switch(choice){ case 1: library.inputResource(reader, todayDate); break; case 2: System.out.println(library.resourcesOverDue(todayDate)); break; case 3: System.out.println(library.toString()); break; case 4: library.deleteResource(reader,...

  • In C++ Having heard you have gotten really good at programming, your friend has come to...

    In C++ Having heard you have gotten really good at programming, your friend has come to ask for your help with a simple task. She would like you to implement a program to encrypt the messages she exchanges with her friends. The idea is very simple. Every letter of the alphabet will be substituted with some other letter according to a given key pattern like the one below. "abcdefghijklmnopqrstuvwxyz" "doxrhvauspntbcmqlfgwijezky" // key pattern For example, every 'a' will become a...

  • Computer Science C++ Help, here's the question that needs to be answered (TASK D): Task D....

    Computer Science C++ Help, here's the question that needs to be answered (TASK D): Task D. Decryption Implement two decryption functions corresponding to the above ciphers. When decrypting ciphertext, ensure that the produced decrypted string is equal to the original plaintext: decryptCaesar(ciphertext, rshift) == plaintext decryptVigenere(ciphertext, keyword) == plaintext Write a program decryption.cpp that uses the above functions to demonstrate encryption and decryption for both ciphers. It should first ask the user to input plaintext, then ask for a right...

  • Cryptography, the study of secret writing, has been around for a very long time, from simplistic...

    Cryptography, the study of secret writing, has been around for a very long time, from simplistic techniques to sophisticated mathematical techniques. No matter what the form however, there are some underlying things that must be done – encrypt the message and decrypt the encoded message. One of the earliest and simplest methods ever used to encrypt and decrypt messages is called the Caesar cipher method, used by Julius Caesar during the Gallic war. According to this method, letters of the...

  • JAVAFX ONLY PROGRAM!!!!! SORTING WITH NESTED CLASSES AND LAMBDA EXPRESSIONS. DIRECTIONS ARE BELOW: DIRECTIONS: The main...

    JAVAFX ONLY PROGRAM!!!!! SORTING WITH NESTED CLASSES AND LAMBDA EXPRESSIONS. DIRECTIONS ARE BELOW: DIRECTIONS: The main point of the exercise is to demonstrate your ability to use various types of nested classes. Of course, sorting is important as well, but you don’t really need to do much more than create the class that does the comparison. In general, I like giving you some latitude in how you design and implement your projects. However, for this assignment, each piece is very...

  • Lab 1.java only Goal: This lab will give you experience with defining and using classes and...

    Lab 1.java only Goal: This lab will give you experience with defining and using classes and fields, and with conditionals and recursive functions. Getting Started --------------- Read the Fraction.java class into a text editor and compile it filling in the command javac -g Fraction.java. The program should compile without errors. In a shell window, run the program using "java Fraction". The program should run, although it will print fractions in a non-reduced form, like 12/20. Part I: Constructors (1 point)...

  • Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into...

    Hash Tables. (Hint: Diagrams might be helpful for parts a) and b). ) When inserting into hash table we insert at an index calculated by the key modulo the array size, what would happen if we instead did key mod (array_size*2), or key mod (array_size/2)? (Describe both cases). Theory answer Here Change your hashtable from the labs/assignments to be an array of linkedlists – so now insertion is done into a linkedlist at that index. Implement insertion and search. This...

  • Lab #4 – Recursive Methods for Generic ArrayList ----- JAVA The problem Use recursion to implement...

    Lab #4 – Recursive Methods for Generic ArrayList ----- JAVA The problem Use recursion to implement some list functionalities on an ArrrayList of generic type using type parameters in method definition Our goal for this lab is to continue using the divide and conquer approach of splitting a list into its head and tail and keep recursing on the tail (which happens to be smaller). However, instead of trying the approach on a string (a list of characters) we would...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT