Coding Bat Logic Problems – Day 2

Last class we looked at the first of 4 logic problems on Coding Bat in Computer Science 1 ( http://funmultiplies.com/coding-bat-logic-problems-day-1 ). We’re now looking at the last 4 logic problems of that Coding Bat set in CS1 as we get ready to depart for Spring Break.

alarm clock

http://codingbat.com/prob/p119867

Here is the setup of this problem:

Given a day of the week encoded as 0=Sun, 1=Mon, 2=Tue, …6=Sat, and a boolean indicating if we are on vacation, return a string of the form “7:00” indicating when the alarm clock should ring. Weekdays, the alarm should be “7:00” and on the weekend it should be “10:00”. Unless we are on vacation — then on weekdays it should be “10:00” and weekends it should be “off”.

def alarm_clock(day, vacation):
  if (day == 0 or day == 6) and vacation == True:
    return "off"
  elif (day == 0 or day == 6) and vacation == False:
    return "10:00"
  elif (day == 1 or day == 2 or day == 3 or day == 4 or day == 5) and vacation == False:
    return "7:00"
  else:
    return "10:00"

This one is not hard, but just involved with conditional statements. The major things to keep an eye out for are the spelling of the return “off” is all lower-case and the week starts on day 0 with Sunday.

love 6

http://codingbat.com/prob/p100958

Here is the setup for this problem:

The number 6 is a truly great number. Given two int values, a and b, return True if either one is 6. Or if their sum or difference is 6. Note: the function abs(num) computes the absolute value of a number.

def love6(a, b):
  if (a) == 6 or (b) == 6:
    return True
  elif (a) + (b) == 6 or (b) + (a) == 6:
    return True
  elif (a) - (b) == 6 or (b) - (a) == 6:
    return True
  else:
    return False

I personally do not like this problem because of the “Note” at the end. It throws many programmers off. Yes, you can solve this using absolute values, but it’s not necessary.

Once you get other that “distractor”, this is a simple conditional logic problem.

In 1 to 10

http://codingbat.com/prob/p158497

Here is the setup for this problem:

Given a number n, return True if n is in the range 1..10, inclusive. Unless outside_mode is True, in which case return True if the number is less or equal to 1, or greater or equal to 10.

def in1to10(n, outside_mode):
  if outside_mode == False and (n >= 1 and n <= 10):
    return True
  elif outside_mode == True and (n <= 1 or n >= 10):
    return True
  else:
    return False

This is a pretty simple conditional logic problem. If the Boolean flag is False, we are looking for numbers between 1 and 10 (inclusive) and if the Boolean flag is True, we are looking for numbers outside of 1 and 10 (inclusive).

On this particular question, I awarded extra credit if my students could explain mathematically why when the outside_mode Boolean flag is True, the Boolean operator must be OR.

The reason is that while the Boolean flag is False, num is to be between 1 and 10 inclusive. A number can be simultaneously between 1 and 10. As such, the Boolean AND is used in this statement.

Conversely, when the Boolean flag is True, num is to be outside of 1 and 10 inclusive. A number CANNOT be simultaneously less than 1 and greater than 10. As such, the Boolean OR is needed for this statement.

near ten

http://codingbat.com/prob/p165321

Here is the setup for this problem:

Given a non-negative number “num”, return True if num is within 2 of a multiple of 10. Note: (a % b) is the remainder of dividing a by b, so (7 % 5) is 2.

def near_ten(num):
  if num % 10 == 0 or num % 10 == 1 or num % 10 == 2 or num % 10 == 8 or num % 10 == 9:
    return True
  else:
    return False

This particular one needs a little bit of explanation on the algorithm that was used. The general concept is pretty straightforward, but the formula may not be.

Here, we are looking at the modulus of num by 10. In this case, that will always return a 0, 1, or 2 if the number is a multiple of 10, or 1 greater than a multiple of 10, or 2 greater than a multiple of 10 respectively.

On the other side, we will always return an 8 or 9 if the number is 2 less than a multiple of 10, or 1 less than a multiple of 10 respectively.

Beyond the algorithm, the problem is a simple logic conditional program.

Coding Bat Logic Problems – Day 1

Today, we looked at logic problems in Coding Bat in Computer Science 1. Students had to use Boolean logic operators and conditional if/else an if/elif/else statements.

Cigar Party

http://codingbat.com/prob/p195669

Here is the setup of the problem:

When squirrels get together for a party, they like to have cigars. A squirrel party is successful when the number of cigars is between 40 and 60, inclusive. Unless it is the weekend, in which case there is no upper bound on the number of cigars. Return True if the party with the given values is successful, or False otherwise.

def cigar_party(cigars, is_weekend):
  if is_weekend == True and cigars >=40:
    return True
  elif is_weekend == False and cigars >=40 and cigars <=60:
    return True
  else:
    return False

Here, we used the Boolean AND operator to check the number of cigars in relation to the value of is_weekend.

Lines 2 – 3 address if it is a weekend AND are there at least 40 cigars. If so, a TRUE is returned.

Lines 4 – 5 address if is is NOT a weekend AND there are between 40 and 60 cigars. If so, a TRUE is returned.

Lines 6 – 7 address everything else as the default case and return a FALSE.

Date Fashion

http://codingbat.com/prob/p129125

Here is the setup of the problem:

You and your date are trying to get a table at a restaurant. The parameter “you” is the stylishness of your clothes, in the range 0..10, and “date” is the stylishness of your date’s clothes. The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes. If either of you is very stylish, 8 or more, then the result is 2 (yes). With the exception that if either of you has style of 2 or less, then the result is 0 (no). Otherwise the result is 1 (maybe).

def date_fashion(you, date):
  if you <=2 or date <=2:
    return 0
  elif you >= 8 or date >= 8:
    return 2
  else:
    return 1

Here, the order of the conditions is EXTREMELY important. Let’s look at the case of you = 9 and date = 1.

In the code above, we would reach the first the first conditional statement with you <=2 is FALSE but date <=2 is TRUE. Since a Boolean OR is being used, only one of them must be true for the associated code to run. So, we return a value of 0 and exit the conditional loop, which is the correct response for the problem.

Now, let’s change the code to the following:

def date_fashion(you, date):
  if you >= 8 or date >= 8:
    return 2
  elif you <=2 or date <=2:
    return 0
  else:
    return 1

All that we have done is swap the conditions between lines 2 and 4 with each other. Let’s examine the case of you = 9 and date = 1 again.

We enter at the first conditional statement with you >= 8 is TRUE but date >= is FALSE. Since a Boolean OR is being used, only one of them must be true for the associated code to run. So, we return a value of 2 and exit the conditional loop, which is the incorrect response for the problem.

The order of our conditional statements is EXTREMELY important!

Squirrel Play

http://codingbat.com/prob/p135815

Here is the setup of the problem:

The squirrels in Palo Alto spend most of the day playing. In particular, they play if the temperature is between 60 and 90 (inclusive). Unless it is summer, then the upper limit is 100 instead of 90. Given an int temperature and a boolean is_summer, return True if the squirrels play and False otherwise.

def squirrel_play(temp, is_summer):
  if is_summer == True and temp >= 60 and temp <= 100:
    return True
  elif is_summer == False and temp >= 60 and temp <= 90:
    return True
  else:
    return False

Lines 2 – 3 check if it is summer. If it is, we then check to see if the temperature is between 60 and 100 degrees inclusive. If it passes all 3 of these tests (Boolean AND), we return the value of TRUE.

Lines 4 – 5 check if it is NOT summer. If it is NOT summer, we then check to see if the temperature is between 60 and 90 degrees inclusive. If it passes all 3 of these tests (Boolean AND), we return the value of TRUE.

Lines 6 -7 are the default case if neither of the above tests can be passed and returns the value of FALSE.

Caught Speeding

http://codingbat.com/prob/p137202

Here is the setup of the problem:

You are driving a little too fast, and a police officer stops you. Write code to compute the result, encoded as an int value: 0=no ticket, 1=small ticket, 2=big ticket. If speed is 60 or less, the result is 0. If speed is between 61 and 80 inclusive, the result is 1. If speed is 81 or more, the result is 2. Unless it is your birthday — on that day, your speed can be 5 higher in all cases.

def caught_speeding(speed, is_birthday):
  if is_birthday == True and speed <= 65:
    return 0
  elif is_birthday == False and speed <= 60:
    return 0
  elif is_birthday == True and speed >= 66 and speed <=85:
    return 1
  elif is_birthday == False and speed >=61 and speed <= 80:
    return 1
  else:
    return 2

Much like the problem before earlier, we a set of Boolean AND statements. When using the Boolean AND we must remember that ALL conditions must be satisfied for the statement to be considered TRUE and to thereby execute the associated instructions.

Lines 2 – 3 and 6 – 7 are working with when is_birthday is TRUE while lines 4 – 5 and 8 – 9 are working with when is_birthday is FALSE. All of these lines are using comparative operators for the speeds.

Coding Bat Recursive Problems – Day 1

Today, we are looking at a primer for recursion using problems in CodingBat in Computer Science 2. We looked at 3 different problems from CodingBat.

Bunny Ears

http://codingbat.com/prob/p183649

Here is the setup of the problem:

We have a number of bunnies and each bunny has two big floppy ears. We want to compute the total number of ears across all the bunnies recursively (without loops or multiplication).

public int bunnyEars(int bunnies) {
  if (bunnies == 0){
    return 0;
  } else {
    return 2 + bunnyEars(bunnies-1);
  }
}

Let’s use an input of 6. With this, we would anticipate the output to be 12, since each bunny has 2 ears.

Line 3 will not be run since the condition set in line 2 is FALSE. Currently, bunnies is set to 6.

So, we move on to line 4, which is the start of the default case, and is executed on line 5. So with bunnies set to 6, we return a 2 and then add that to the number of bunny ears from the next bunny (bunnies – 1), which is bunny #5.

Now, bunnies = 5, so line 2 is still FALSE, so we run the default case on line 6. We return a 2 and add that to the number of bunny ears from the next bunny (bunnies – 1), which is bunny #4.

Now, bunnies = 4, so line 2 is still FALSE, so we run the default case on line 6. We return a 2 and add that to the number of bunny ears from the next bunny (bunnies – 1), which is bunny #3.

Now, bunnies = 3, so line 2 is still FALSE, so we run the default case on line 6. We return a 2 and add that to the number of bunny ears from the next bunny (bunnies – 1), which is bunny #2.

Now, bunnies = 2, so line 2 is still FALSE, so we run the default case on line 6. We return a 2 and add that to the number of bunny ears from the next bunny (bunnies – 1), which is bunny #1.

Now, bunnies = 1, so line 2 is still FALSE, so we run the default case on line 6. We return a 2 and add that to the number of bunny ears from the next bunny (bunnies – 1), which is 0.

Now, bunnies = 0, so line 2 is now TRUE, so we return a 0 and exit the loop.

We now add the following together:

  • 0 from when bunnies = 0 (cumulative total = 0)
  • 2 from when bunnies = 1 (cumulative total = 2)
  • 2 from when bunnies = 2 (cumulative total = 4)
  • 2 from when bunnies = 3 (cumulative total = 6)
  • 2 from when bunnies = 4 (cumulative total = 8)
  • 2 from when bunnies = 5 (cumulative total = 10)
  • 2 from when bunnies = 6 (cumulative total = 12)

The total is returned as 12 ears.

Bunny Ears 2

http://codingbat.com/prob/p107330

Here is the setup of the problem:

We have bunnies standing in a line, numbered 1, 2, … The odd bunnies (1, 3, ..) have the normal 2 ears. The even bunnies (2, 4, ..) we’ll say have 3 ears, because they each have a raised foot. Recursively return the number of “ears” in the bunny line 1, 2, … n (without loops or multiplication).

public int bunnyEars2(int bunnies) {
  if (bunnies == 0){
    return 0;
  } else if (bunnies % 2 != 0){
    return 2 + bunnyEars2(bunnies-1);
  } else{
    return 3 + bunnyEars2(bunnies-1);
  }
}

For this one, let’s use an input of 5. We would expect the output to be 12 since bunnies 1, 3, & 5 have a total 6 ears and bunnies 2 & 4 have a total of 6 ears.

Line 3 will not be run since the condition set in line 2 is FALSE. Currently, bunnies is set to 5.

So, we move on to line 4. This condition is looking to see if we are working with an even numbered or odd numbered bunny. We have set the condition to use the modulus of 2 of the integer of bunnies. If the modulus is NOT 0, then the statement is TRUE and therefore it is an ODD numbered bunny.

Line 6 is the start of the default case which is used if we are working with an EVEN numbered bunny.

Now, bunnies = 5, so line 2 is FALSE, and line 4 is TRUE. We return a 2 and add that to the number of bunny ears from the next bunny (bunnies – 1), which is bunny #4.

Now, bunnies = 4, so line 2 is FALSE, line 4 is FALSE, so we run the default case at line 6. We return a 3 and add that to the number of bunny ears from the next bunny (bunnies -1), which is bunny #3.

Now, bunnies = 3, so line 2 is FALSE, and line 4 is TRUE. We return a 2 and add that to the number of bunny ears from the next bunny (bunnies – 1), which is bunny #2.

Now, bunnies = 2, so line 2 is FALSE, line 4 is FALSE, so we run the default case at line 6. We return a 3 and add that to the number of bunny ears from the next bunny (bunnies -1), which is bunny #1.

Now, bunnies = 1, so line 2 is FALSE, and line 4 is TRUE. We return a 2 and add that to the number of bunny ears from the next bunny (bunnies – 1), which is 0.

Now, bunnies = 0, so line 2 is now TRUE, so we return a 0 and exit the loop.

We now add the following together:

  • 0 from when bunnies = 0 (cumulative total = 0)
  • 2 from when bunnies = 1 (cumulative total = 2)
  • 3 from when bunnies = 2 (cumulative total = 5)
  • 2 from when bunnies = 3 (cumulative total = 2)
  • 3 from when bunnies = 4 (cumulative total = 10)
  • 2 from when bunnies = 5 (cumulative total = 12)

The total is returned as 12 ears.

Triangle

http://codingbat.com/prob/p194781

Here is the setup of the problem:

We have triangle made of blocks. The topmost row has 1 block, the next row down has 2 blocks, the next row has 3 blocks, and so on. Compute recursively (no loops or multiplication) the total number of blocks in such a triangle with the given number of rows.

public int triangle(int rows) {
 if (rows == 0){
   return 0;
 } else {
   return rows + triangle(rows - 1);
 }
}

Here, we are building something that looks like this:

Like the cases before it, line 2 is a condition looking for when we are to row 0. If line 2 is FALSE, we will move to line 4. For this example, let’s use rows = 4. With this, the output should be 10 as there are 10 cubes needed to complete a 4 row triangle.

So, we start with rows = 4. Line 2 is FALSE, so we move to line 4 to execute line 5, where we return the row number and add it to the number of cubes on the next row (rows – 1), which is row #3.

We are returning the row number as that is equal to the number of cubes of each row (e.g. row 7 = 7 cubes, row 4 = 4 cubes, etc…).

We now move to rows = 3. Line 2 if FALSE, so we move to line 4 to execute line 5, where we return the row number and add it to the number of cubes on the next row (rows – 1), which is row #2.

We now move to rows = 2. Line 2 if FALSE, so we move to line 4 to execute line 5, where we return the row number and add it to the number of cubes on the next row (rows – 1), which is row #1.

We now move to rows = 1. Line 2 if FALSE, so we move to line 4 to execute line 5, where we return the row number and add it to the number of cubes on the next row (rows – 1), which is 0.

Now, rows = 0, so line 2 is now TRUE, so we return a 0 and exit the loop.

We now add the following together:

  • 0 from when rows = 0 (cumulative total = 0)
  • 1 from when rows = 1 (cumulative total = 1)
  • 2 from when rows = 2 (cumulative total = 3)
  • 3 from when rows = 3 (cumulative total = 6)
  • 4 from when rows = 4 (cumulative total = 10)

Coding Bat – rotateLeft3

This exercise requires that the program look at an array with 3 integers and shift their positions one index to the left (down) and place first integer (index 0) at the end.

Here is the code that you start with:

public int[] rotateLeft3(int[] nums) {

}

As you can see, we start with an empty integer array named “nums”.

public int[] rotateLeft3(int[] nums) {
  int[] rotatedArray = new int[]{nums[1],nums[2],nums[0]};
  return rotatedArray;
}

 

This solution creates a new integer array named “rotatedArray” and assigns it the values of each index from the original array. (Line 2)

We return the new array on line 3 to solve the problem.

Coding Bat – posNeg

This exercise requires that the program look at two given integers and a boolean. If the Boolean is TRUE AND both integers are negative, then TRUE is returned. If the Boolean is FALSE only 1 integer can be negative for to return TRUE.

Here is the code that you start with:

public boolean posNeg(int a, int b, boolean negative) {

}

As you can see, we start with 2 integer variables named “a” and “b” and a boolean named “negative”.

public boolean posNeg(int a, int b, boolean negative) {
  if (negative){
    if (a < 0 && b < 0){
      return true;
    } else {
      return false;
    } 
  } else if ((a < 0 && b > 0) || (a > 0 && b < 0)) {
    return true;
  } else {
    return false;
  }
}

This solution utilizes a nested if/then structure. Starting on line 2, we say IF the Boolean negative is TRUE, then proceed to line 3. If it is FALSE, we would jump to line 8.

On line 3, we now check to see if both “a” AND “b” are negative (less than 0). If they are, TRUE is returned (line 4). If they are not, FALSE is returned (lines 5-7).

Line 8 is executed if the Boolean on line 3 is FALSE. Line 8 looks to see if “a” is negative and “b” is positive OR “a” is positive and “b” is negative. If either case is TRUE, then TRUE is returned (line 9). If neither statement on line 8 is TRUE, then FALSE is returned (lines 10-12).

Coding Bat presents the following as their solution:

public boolean posNeg(int a, int b, boolean negative) {
  if (negative) {
    return (a < 0 && b < 0);
  }
  else {
    return ((a < 0 && b > 0) || (a > 0 && b < 0));
  }
}

In this solution, line 2 is identical to our line 2. However, their line 3 is shorter version of our lines (3-7). If both “a” AND “b” are not negative, then a FALSE is returned, otherwise a TRUE is returned.

Their lines 5-7 are our lines 8-12 and work the same way.

Coding Bat – Arrays Cluster 1

Today, while I was attending meetings, I assigned my students to complete 4 Coding Bat logic exercises.

CODING BAT – COMMONEND

This exercise requires that the program return TRUE if the first integers or last integers of two given arrays are the same, otherwise, FALSE will be returned.

Here is the code that you start with:

public boolean commonEnd(int[] a, int[] b) {

}

We start with two integer arrays named “a” and “b”.

public boolean commonEnd(int[] a, int[] b) {
  int arrayALength = a.length;
  int arrayBLength = b.length;
  int lastA = a[arrayALength - 1];
  int lastB = b[arrayBLength - 1];
  int firstA = a[0];
  int firstB = b[0];
  if(firstA == firstB || lastA == lastB){
    return true;
  }
  return false;
}

The solution above starts by calculating the length of each array (lines 2 and 3). Remember, whenever you are asked to do anything with the “end” or “last” items, you will almost always need to calculate the length.

On lines 4 & 5, we are establishing variables to hold the last index of each array and lines 6 & 7 are holding the first index of each array.

Finally, lines 8 through 10 are a conditional statement comparing the first indices of each array and the last indices of each array. If either of them are equal, a TRUE is returned. However, if neither is TRUE, then FALSE is returned.

CODING BAT – MAKELAST

This exercise requires that the program calculate the length of a given array and create a new array that is double that length populated with zeros with the exception of the last index. The last index is to populated with the last index of the first array.

Here is the code that you start with:

public int[] makeLast(int[] nums) {

}

We start with a single integer variable named “nums”.

public int[] makeLast(int[] nums) {
 int arrayLength = nums.length;
 int arrayFinalLength = arrayLength * 2;
 int arrayLast = nums[arrayLength - 1];
 int[] num = new int[arrayFinalLength];
 num[arrayLength - 1] = arrayLast;
 return num;
}

As always, since we are asked to do some operation with the “last” or “end”, we must calculate the length of the array. This is done on line 2.

On line 3, we created a variable to hold the length of the new array, which is double the length of the original array.

Line 4 is where we capture the last index of the original array.

On line 5, we create a new integer array named “num” which has a size assigned by the variable that was created on line 3.

On line 6, we replace the last index of the new array with the value of the variable created on line 4.

Finally, on line 7, we return the new array.

CODING BAT – MAKEPI

This exercise requires that the program return the first 3 digits of PI in an array.

Here is the code that you start with:

public int[] makePi() {

}

We start with just the basic class declaration and no variables.

public int[] makePi() {
  int pi[] = {3,1,4};
  return pi;
}

The solution above starts by creating a new integer array named “pi” which is assigned the integers of 3, 1, and 4 on line 2.

On line 3, the array is returned.

Many students struggle to make this problem more challenging than it needs to be. Some try to take the Math.PI constant and populate the array one index at a time. However, this is not necessary and is not outlined as a requirement in the problem.

 

Coding Bat – firstLast6

This exercise requires that the program analyze an array of integers and return TRUE if either the first or last integer is a 6. The array is guaranteed to have a minimum length of 1.

Here is the code that you start with:

public boolean firstLast6(int[] nums) {

}

As you can see, we have a single integer array named nums.

public boolean firstLast6(int[] nums) {
 int first = nums[0];
 int last = nums[nums.length-1];
 if (first == 6 || last == 6){
   return true;
 }
 return false;
}

This solution utilizes a conditional if with the Boolean OR to solve the problem.

We start my declaring an integer variable named “first” to retrieve the value of index 0 (line 2).

We then declare an integer variable named “last” to retrieve the value of the last letter (Line 3)

As was the case when working with strings, to retrieve the last index of the array, we must first calculate its length and then subtract 1 from the total length. This will give us the value of the last index of the array.

Lines 4 through 6 are the conditional Boolean OR looking to see if either the first or last number are 6. If the Boolean is TRUE, then TRUE is returned.

Coding Bat – sameFirstLast

This exercise requires that the program analyze an array of integers and return TRUE if the array has a length greater than 1 and the first index is the same as the last index.

Here is the code that you start with:

public boolean sameFirstLast(int[] nums) {

}

As you can see, we have a single integer array named nums.

public boolean sameFirstLast(int[] nums) {
 if (nums.length >= 1){
   int first = nums[0];
   int last = nums[nums.length-1];
   if (first == last){
     return true;
   }
   return false;
   }
 return false;
}

We start on line 2 checking to see if the array has a minimum length of 1. If is does not, we skip to line 10 and return FALSE. If the Boolean on line 2 is true, we proceed to line 3.

We then declare an integer variable named “first” to retrieve the value of index 0 (line 3).

We then declare an integer variable named “last” to retrieve the value of the last letter (Line 4)

As was the case when working with strings, to retrieve the last index of the array, we must first calculate its length and then subtract 1 from the total length. This will give us the value of the last index of the array.

Lines 5 through 7 are the conditional Boolean looking to see if the first and last index are the same value. If the Boolean is TRUE, then TRUE is returned.

Coding Bat – delDel

This exercise requires that the program analyze a string to see if it contains the word “del” starting at index position 1. If it does, it is to remove it and display the word with the “del” removed.

Here is the code that you start with:

public String delDel(String str) {

}

As you can see, we have a single string variable named “str”.

public String delDel(String str) {
 if(str.length()>=4 && str.substring(1,4).equals("del")){
 return str.substring(0, 1) + str.substring(4);
 }
 return str;
}

This solution utilizes a conditional if with the Boolean AND to solve the problem.

We start by looking to see if the string is 4 or more characters in length AND if the string starting at index 1 to 4 is “del”.

If this Boolean is TRUE, then we return the string from index 0 to 1 concatenated with the string from index 4 to the end.

If this Boolean is FALSE, then we simply return the string unmodified.

Coding Bat – Cluster 2

Today, while I was working with the FTC 11242 (ERROR 404) robotics team at Ferris Intermediate School for our community outreach efforts, my Computer Science class was assigned to complete 4 different Coding Bat assignments.

CODING BAT – firstTwo

This exercise requires that the program return only the first two characters of a provided string.

Here is the code that you start with:

public String firstTwo(String str) {
 
}

We start with a single string variable named str.

public String firstTwo(String str) {
 if (str.length() < 2){
 return str;
 }
 String firstTwo = str.substring(0,2);
 return firstTwo;
}

The solution above first uses the length method of the String class to determine if the string is less than 2 characters long. If it is, then the entered string is returned as the solution (lines 2 – 4).

Lines 5 – 6 are executed if the string is 2 or more characters in length and uses the substring method of the String class to capture the characters from index 0 to index 2 (first 2 letters of the string) and assigns them to the variable named firstTwo and then returns the value of that variable.

CODING BAT – extraEnd

This exercise requires that the program take the last two letters of the provided string and create a new string that repeats them 3 times.

Here is the code that you start with:

public String extraEnd(String str) {
 
}

We start with a single string variable named str.

public String extraEnd(String str) {
 int strLength = str.length();
 String lastTwo = str.substring(strLength - 2, strLength);
 String extraEnd = lastTwo + lastTwo + lastTwo;
 return extraEnd;
}

Whenever we are doing something involving the end of a string, we must first calculate the length of the string (line 2).

Once we know the length of the string, we can come back 2 characters (line 3).

We then use concatenate to repeat the last 2 characters 3 times (line 4) and output the final solution (line 5).

CODING BAT – conCat

This exercise requires that the program take two entered strings and concatenate the first with the last. However, if the last character of the first string and the first character of the last string are the same, they are NOT to be repeated and one is to be removed.

Here is the code that you start with:

public String conCat(String a, String b) {
 
}

We start with two string variables named “a” and “b”.

public String conCat(String a, String b) {
 int aLength = a.length();
 int bLength = b.length();
 if (aLength == 0 || bLength == 0){
 return a + b;
 }
 String aLastLetter = a.substring(aLength - 1, aLength);
 String bFirstLetter = b.substring(0,1);
 if (aLastLetter.equals(bFirstLetter)){
 return a + b.substring(1, bLength);
 }
 return a + b;
}

The solution above first determines the length of the two strings (lines 2 – – 3). We then look to see if either of the strings is empty (lines 4 – 6) and return the strings as they are.

If both of the strings have text, we then look to see what the last letter of string a is (line 7) and the first letter of string b (line 8). We then compare these two letters to see if they are the same (line 9). If they are, we return string a concatenated with string b with the first letter of string b removed.

If line 9 is false, then we simply return string a concatenated with string b.

CODING BAT – theEnd

This exercise requires that the program display either the first letter of the string (if the Boolean front is true) or the last letter of the string (if the Boolean front is false).

Here is the code that you start with:

public String theEnd(String str, boolean front) {
 
}

As you can see, we have a string variable named str and a Boolean with the value of front.

public String theEnd(String str, boolean front) {
 int strLength = str.length();
 String strFirstLetter = str.substring (0,1);
 String strLastLetter = str.substring (strLength - 1, strLength);
 if (front == true){
 return strFirstLetter;
 }
 return strLastLetter;
}

As always, when we’re asked to do anything with the end of a string, we must first calculate the length of the string (line 2).

We then create variables for the first letter and last letter of the string using the substring method of the String class (lines 3 – 4).

Line 5 looks to see if the Boolean is true. If it is, we return the value of the variable for the first letter of the string (line 6). Otherwise, we return the value of the variable for the last letter of the string (line 8).