Question

In: Computer Science

Similar to in HW1, you'll implement a left shift of decimals in a string, with combining...

Similar to in HW1, you'll implement a left shift of decimals in a string, with combining of multiple like digits into a single digit of double the value. The main difference between HW1 and this is that now the string representing a row in 2048 can be of any length! You'll implement a Combine class in a comparable .java file.

As before, the input string can only include the characters '_', '2', and '4'. Unlike before, it can be of any length (including length 0). Any '2's that have no other characters or any number of '_'s between them combine to become a '4'(i.e. two '2's disappear, and a '4' is left in one of their space). Likewise, '4's become '8's. Any digit that is the result of a combination cannot be combined with another digit. All digits are combined in this way and shifted to the far left so that any '_' appear on the right of the string. The length of the string remains unchanged.

Your classes will implement the Combinable interface. Note that we're attaching an updated version so be sure to use the new one. You will implement multiple methods from the interface Combinable:

  • public boolean validateChar(char ch)

    The requirements remain unchanged from HW1.

  • public boolean validateRow(String s)

    The string must include only the characters discussed above, but it can be of any length. Return true if it includes only valid characters, false otherwise. You must invoke validateChar to determine validity of each character.

  • public String repeat(char ch, int num)

    Create a string that consists of num, ch characters.

  • public String eliminateUnderscores(String s)

    Given a String s, return a new String that has all '_' characters removed. You cannot use the replace method in the String Class. Note that the returned string will be of the same or lesser length than the argument.

  • public String moveLeft(String s)

    All non-'_' characters in the input string are shifted to the left of the string, leaving only '_'s on the right-hand side of the string. The resulting "left-shifted" String is returned. It is highly suggested that you first use eliminateUnderscores to cluster all the non-'_' characters, and then to use repeat to concatenate the appropriate number of '_' on to the right of the String that is returned. Most other ways to implement this method are far more complicated.

    You must invoke the validateRow method to test if
    the input String is valid. If it is not, return the input string directly without change.

  • public String combineLeft(String s)

    Given the input string, the output should be a string of the same length, with all '_'s removed from the left side of the string, and with all pairs of like digits with only '_'s in between them, combined into a digit of twice the value. Return the resulting String.

    It is highly suggested that you use the moveLeft method to help you with this implementation. When generating your new string, it is much easier to be able to ignore all '_' between digits.

    You must invoke the validateRow method to test if the input String is valid. If it is not, return the input string directly without change.

Some example assertions:

assert validateChar('_');
assert !validateChar(' ');

assert validateRow("2222");
assert validateRow("_24_");
assert !validateRow("2234_");
assert validateRow("");
assert !validateRow("*");

assert "***".equals(repeat('*', 3));
assert "".equals(repeat('*', 0));
assert "44444444".equals(repeat('4', 8));

assert "4".equals(eliminateUnderscores("__4__"));
assert "244".equals(eliminateUnderscores("2_4_4_"));
assert "".equals(eliminateUnderscores("___"));
assert "242442".equals(eliminateUnderscores("242442"));

assert "4____".equals(moveLeft("__4__"));
assert "244___".equals(moveLeft("2_4_4_"));
assert "___".equals(moveLeft("___"));
assert "_3_".equals(moveLeft("_3_")); 
assert "242442".equals(moveLeft("242442"));

assert "484___".equals(combineLeft("224422"));
assert "484________".equals(combineLeft("2_2_4_4_2_2"));
assert "242424__".equals(combineLeft("242_42_4"));
assert "828____".equals(combineLeft("__44244"));
assert "".equals(combineLeft(""));
assert "22344".equals(combineLeft("22344"));

assert "88__________".equals(combineLeft(combineLeft("_2_22_222_4_")));

Here is the first code:

public class Combine implements Combinable {

   public boolean validateChar(char ch)
   {
//Write your Code Here
       return true;
   }
  
   public boolean validateRow(String row)
{
//Write your Code Here
       return true;
   }
  
   public String repeat(char ch, int num)
{
//Write your Code Here
        return "";
   }

   public String eliminateUnderscores(String row)
{
//Write your Code Here
return "";  
}

   public String moveLeft(String row)
{
//Write your Code Here
       return "";
   }

   public String combineLeft(String row)
{
//Write your Code Here
       return "";
   }
  
    public static void main(String[] args)
{
Combine CM=new Combine();
       assert CM.validateChar('_');
       assert !CM.validateChar(' ');

       assert CM.validateRow("2222");
       assert CM.validateRow("_24_");
       assert !CM.validateRow("2234_");
       assert CM.validateRow("");
       assert !CM.validateRow("*");

       assert "***".equals(CM.repeat('*', 3));
       assert "".equals(CM.repeat('*', 0));
       assert "44444444".equals(CM.repeat('4', 8));

       assert "4".equals(CM.eliminateUnderscores("__4__"));
       assert "244".equals(CM.eliminateUnderscores("2_4_4_"));
       assert "".equals(CM.eliminateUnderscores("___"));
       assert "242442".equals(CM.eliminateUnderscores("242442"));

       assert "4____".equals(CM.moveLeft("__4__"));
       assert "244___".equals(CM.moveLeft("2_4_4_"));
       assert "___".equals(CM.moveLeft("___"));
       assert "_3_".equals(CM.moveLeft("_3_"));
       assert "242442".equals(CM.moveLeft("242442"));

       assert "484___".equals(CM.combineLeft("224422"));
       assert "484________".equals(CM.combineLeft("2_2_4_4_2_2"));
       assert "242424__".equals(CM.combineLeft("242_42_4"));
       assert "828____".equals(CM.combineLeft("__44244"));
       assert "".equals(CM.combineLeft(""));
       assert "22344".equals(CM.combineLeft("22344"));

       assert "88__________".equals(CM.combineLeft(CM.combineLeft("_2_22_222_4_")));

       System.out.println("All tests passed.");
   }
}

Here is the second code:

public interface Combinable {
//checking if the character is a valid character
   public boolean validateChar(char ch);
  
//checking if a row contains the correct set of characters
   public boolean validateRow(String row) ;

//Create a string that consists of num, ch characters.
   public String repeat(char ch, int num) ;
  
//Removing the undescore from the row
   public String eliminateUnderscores(String row) ;
  
//Shifting the numbers to the left if there is any open spance
   public String moveLeft(String row) ;

//Combining the equal numbers in the row 22_ > 4__
   public String combineLeft(String row) ;

}

Solutions

Expert Solution

Combine.java

===================================

package hw;

public class Combine implements Combinable {
  
   public boolean validateChar(char ch) {
       // char can only be '_' , '2' or '4'
       return ch == '_' || ch == '2' || ch == '4';
   }
  
   public boolean validateRow(String row) {
       // loop the entire string
       for(int i=0; i<row.length(); i++) {
           // get individual character from string
           char c = row.charAt(i);
           // use validateChar to determine validity of each character
           if(!validateChar(c)) {
               // return false, if any of character in string is not valid
               return false;
           }
       }
       // return true if all characters are valid(empty string is valid!)
       return true;
   }
  
   public String repeat(char ch, int num) {
       // create a string to return
       String str = "";
       // loop for num times to add char ch
       for(int i=0; i<num; i++) {
           // use + operator to concatenate string
           str = str + ch;
       }
       return str;
   }

   public String eliminateUnderscores(String row) {
       // create a new string to return
       String result = "";
       // loop the given string
       for(int i=0; i<row.length(); i++) {
           // get individual char from string
           char c = row.charAt(i);
           // if it not '_' then add the char to result
           if(c != '_') {
               // add the give char to result this will ignore all '_' from the given string
               result = result + c;
           }
       }
       // return the result string
       return result;
   }
  
   // All non-'_' characters in the input string are shifted to the left of the string,
   // leaving only '_'s on the right-hand side of the string.
   // The resulting "left-shifted" String is returned
   public String moveLeft(String row) {
       // check for input validity
       if(!validateRow(row)) {
           return row;
       }
      
       // first use eliminateUnderscores to remove all '_' characters
       String result = eliminateUnderscores(row);
       // number of '_' removed is length of row - length of result
       int numUnderscores = row.length() - result.length();
       // now create underscore string
       String underscores = repeat('_', numUnderscores);
       // return the result by concatenation
       return result + underscores;
   }
  
   public String combineLeft(String row) {
       // check for input validity
       if(!validateRow(row)) {
           return row;
       }
      
       // use the moveLeft method to cluster all the non '_' characters on left side
       String str = moveLeft(row);
       // create string to return
       String result = "";
       // create a result by combining all numbers with same value from left to larger number(double value)
       // loop through the string
       for(int i=0; i<str.length(); i++) {
           // get individual char from the string
           char c = str.charAt(i);
           // look for next char from string
           if(i<str.length()-1) {
               char c2 = str.charAt(i + 1);
               // compare two char if they are equal try adding them together
               if(c == c2) {
                   // convert char to integer to compare
                   int value = c - '0';
                   // maximum value a char can have in single digit is 9
                   // check if current char value can be doubled
                   value = value * 2;
                   if(value <= 9) {
                       // convert value to new char
                       char newChar = (char) (value + '0');
                       // add current char to result
                       result = result + newChar;
                       // move to next location in string
                       i++;
                       // value of chat at i'th location already added by doubling
                       // the previous char so add '_' as place holder
                       // make current char '_'
                       c = '_';
                   }
               }
           }
           // current chat does not need to be modified just add it to result
           result = result + c;
       }
       // move digit to left side and all underscores on right side
       int len = result.length();
       // first use eliminateUnderscores to remove all '_' characters
       result = eliminateUnderscores(result);
       // number of '_' removed is length of row - length of result
       int numUnderscores = len - result.length();
       // now create underscore string
       String underscores = repeat('_', numUnderscores);
       // return the result by concatenation
       return result + underscores;
   }
  
   public static void main(String[] args) {
       Combine CM=new Combine();
        assert CM.validateChar('_');
        assert !CM.validateChar(' ');
      
        assert CM.validateRow("2222");
        assert CM.validateRow("_24_");
        assert !CM.validateRow("2234_");
        assert CM.validateRow("");
        assert !CM.validateRow("*");

       assert "***".equals(CM.repeat('*', 3));
       assert "".equals(CM.repeat('*', 0));
       assert "44444444".equals(CM.repeat('4', 8));
      
       assert "4".equals(CM.eliminateUnderscores("__4__"));
       assert "244".equals(CM.eliminateUnderscores("2_4_4_"));
       assert "".equals(CM.eliminateUnderscores("___"));
       assert "242442".equals(CM.eliminateUnderscores("242442"));
      
       assert "4____".equals(CM.moveLeft("__4__"));
       assert "244___".equals(CM.moveLeft("2_4_4_"));
       assert "___".equals(CM.moveLeft("___"));
       assert "_3_".equals(CM.moveLeft("_3_"));
       assert "242442".equals(CM.moveLeft("242442"));
      
       assert "484___".equals(CM.combineLeft("224422"));
       assert "484________".equals(CM.combineLeft("2_2_4_4_2_2"));
       assert "242424__".equals(CM.combineLeft("242_42_4"));
       assert "828____".equals(CM.combineLeft("__44244"));
       assert "".equals(CM.combineLeft(""));
       assert "22344".equals(CM.combineLeft("22344"));
      
       assert "88__________".equals(CM.combineLeft(CM.combineLeft("_2_22_222_4_")));
      
       System.out.println("All tests passed.");
   }
}

==================================

Combinable.java

==================================

package hw;

public interface Combinable {
   //checking if the character is a valid character
       public boolean validateChar(char ch);
  
   //checking if a row contains the correct set of characters
       public boolean validateRow(String row) ;

   //Create a string that consists of num, ch characters.
       public String repeat(char ch, int num) ;
  
   //Removing the undescore from the row
       public String eliminateUnderscores(String row) ;
  
   //Shifting the numbers to the left if there is any open spance
       public String moveLeft(String row) ;

   //Combining the equal numbers in the row 22_ > 4__
       public String combineLeft(String row) ;

}

let me know if you have any problem or doubts. thank you.

Project Explorer X 7 - > sold project v Other Projects GHW2 > JRE System Library (JavaSE-12] v src #hw > Combinable.java > D Combine.java Combine.java X Combinable.java 148 149 assert "***".equals(CM.repeat('*', 3)); 150 assert "'.equals(CM.repeat('*', 0)); 151 assert "44444444".equals(CM.repeat('4', 8)); assert "4".equals(CM.eliminateUnderscores ("_4_")); assert "244".equals(CM.eliminateUnderscores ("24.4 ")); assert "'.equals(CM.eliminateUnderscores ("__")); assert "242442".equals(CM.eliminateUnderscores ("242442")); 156 157 . . . . . . . . . . . . NO CO OWNO 00 OWNA A A A A A A A A A A 4 assert "4 ".equals(CM.moveLeft(" 4 ")); assert "244___".equals(CM.moveLeft("2_4_4_")); assert "_".equals(CM.moveLeft("__")); assert "_3_".equals(CM.moveLeft("_3_")); assert "242442".equals(CM.moveLeft("242442")); 161 163 164 165 assert "484 ".equals(CM.combineLeft("224422")); assert "484 ".equals(CM.combineLeft("2_2_4_4_2_2")); assert "242424__".equals(CM.combineLeft("242_42_4")); assert "828_ ".equals(CM.combineLeft("_44244")); assert "'.equals(CM.combineLeft("")); assert "22344".equals(CM.combineLeft("22344")); 167 168 169 assert "88 ".equals(CM.combineLeft(CM.combineLeft("_2_22_222_4_")); 172 173 System.out.println("All tests passed."); 174 175 } X% al 9 - - @ Javadoc Declaration Console X <terminated> Combine (Java Application) C:\Program FilesVava\jdk-12.0.2\bin\javaw.exe (05-Mar-2020, 11:34:55 am) All tests passed.


Related Solutions

You'll implement a completely generic version of an algorithm to find the maximum of an array....
You'll implement a completely generic version of an algorithm to find the maximum of an array. Unlike in the past, when our algorithm only worked for int[] or double[], this version will work on any Java objects that are comparable, specifically any Java object that implements the Comparable interface. Create a public class named Max with a single class method named max. max should accept an array of Objects that implement Comparable and return the maximum. If the array is...
You'll notice that in the LearnAboutLanguages class there are a few todos. You need to implement...
You'll notice that in the LearnAboutLanguages class there are a few todos. You need to implement the three missing classes ( RussianSpeaker, JapaneseSpeaker and SwahiliSpeaker ). Then uncomment all the stuff marked "todo" and run the code! Submit 1. Your three new .java files 2. A screenshot of your correct code running on your computer. -- public class EnglishSpeaker implements LanguageSpeaker{    @Override    public String GetMyLanguage() {        return "English";    }    @Override    public String GetHi()...
Behold, the power of interfaces! On this homework problem you'll implement a completely generic version of...
Behold, the power of interfaces! On this homework problem you'll implement a completely generic version of an algorithm to find the maximum of an array. Unlike in the past, when our algorithm only worked for int[] or double[], this version will work on any Java objects that are comparable, specifically any Java object that implements the Comparable interface. Create a public class named Max with a single class method named max. max should accept an array of Objects that implement...
for java, Behold, the power of interfaces! On this homework problem you'll implement a completely generic...
for java, Behold, the power of interfaces! On this homework problem you'll implement a completely generic version of an algorithm to find the maximum of an array. Unlike in the past, when our algorithm only worked for int[] or double[], this version will work on any Java objects that are comparable, specifically any Java object that implements the Comparable interface. Create a public class named Max with a single class method named max. max should accept an array of Objects...
Write a function addStrings(string1, string2) that takes in two decimals as strings and returns a string...
Write a function addStrings(string1, string2) that takes in two decimals as strings and returns a string of their sum. *Simply converting strings to numbers and adding them together isn’t acceptable.* The program must be able to handle large decimals. Be sure to touch on these when solving for the solution: Pad the right side Pad the left side Make sure string is same length by putting 0’s where it was missing (be careful w/ decimal points) Make sure to remove...
Write the Verilog code for a 12-bit shift register with ability to shift left or right,...
Write the Verilog code for a 12-bit shift register with ability to shift left or right, synchronized parallel load, asynchronous reset, and serial output? The register is able to load the 12-bit input value (at the positive edge of the clock) if the load signal is one, shift the value in register one bit to the right (at the positive edge of the clock) if the rss signal is one, shift the value in register one bit to the left(at...
Predict how the equilibrium will shift (to the left, to the right or no change) with...
Predict how the equilibrium will shift (to the left, to the right or no change) with each of the following stresses: a. 2H2 (g) + 2NO (g) → N2 (g) + 2H2O (g) i. Increase [H2] ii. Decrease [NO] iii. Decrease the pressure (by increasing the volume) b. CO (g) + 1/2O2 (g) → CO2 (g) + 283 kJ i. Decrease temperature ii. Increase pressure (by adding He (g)) c. H2O (l) → H + (aq) + OH− (aq) i....
These changes will either cause demand to increase (shift right) or decrease (shift left). Use either...
These changes will either cause demand to increase (shift right) or decrease (shift left). Use either word as applicable, for the short answer. 1. If the price of a good increases because the demand for it increases, What would you expect the demand for its complement to do? 2. If the demand for coffee beans increases, then what is likely to happen to the demand for land on which to grow coffee? 3. If advertising expenditures for the good being...
4- a) Draw a 4-Bit Shift Register that shifts from right to left instead of left...
4- a) Draw a 4-Bit Shift Register that shifts from right to left instead of left to right using D-Flip flops. b) Draw the serial transfer from shift register A on the right to the shift register B on the left in block form including the timing diagrammes. c) Draw the serial transfer table in the following form, assuming an initial value of 1101 in the register A and 0110 in the register B. Timing Pulse Shift Register B Shift...
Which of the following changes will shift the demand curve for Advil to the left? (a)...
Which of the following changes will shift the demand curve for Advil to the left? (a) Increase in the price of Advil (b) Increase in family income (c) Increase in the price of a substitute for Advil (d) Increase in the price of a complement to Advil 5. (e) None of the above
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT