Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

flipEachK should take a String and an int as input and returns a String. Let k b

ID: 3726068 • Letter: F

Question

flipEachK should take a String and an int as input and returns a String.
Let k be the name of the input integer. The output string should contain the first k characters of the input string in order, the next k characters of the input string in reverse order, the next k characters of the input string in normal order, and so on. The output string should have all the characters of the input string and no others.
flipEachK("abcdefghijklmn", 4) should return "abcdhgfeijklnm"

You are allowed to use the following from the Java API:

class String

length

charAt

class StringBuilder

length

charAt

append

toString

class Character

any method

Explanation / Answer


public class FlipTest {
   public static void main(String[] args) {

       System.out.println(flipEachK("abcdhgfeijklnm", 4));
   }

   /***
   *
   * @param s
   * @param k
   * @return first find k characters from String and append to builder , then find
   *         next k chars and reverse using reverse method (if less characters are
   *         there , get whatever is remaining and reverse that and append. remove
   *         first 2k characters from string in each loop
   *
   *         e.g abcdhgfeijklnm is a string . first we divide size by k and Ceil
   *         up we will get 14/4=3.5 but Ceil will return 4 . We will loop 4/2 =2
   *         times because each time we are processing 2k characters Remove abcd
   *         and append to builder.length of String is enough to get next 4 chars
   *         and reverse them , sb.append(s.substring(k, 2 * k));
   *         builder.append(sb.reverse()); now remove first 8 chars from string
   *         and remaining string will be ijklnm check if we can get k chars true
   *         then get k chars and append to builder find next remaining chars and
   *         reverse and append
   */
   static String flipEachK(String s, int k) {
       StringBuilder builder = new StringBuilder();
       int loops = (int) Math.ceil(s.length() / (double) k);
       for (int i = 0; i < Math.ceil(loops / 2.0); i++) {
           StringBuilder sb = new StringBuilder();
           // first find first k characters and add to String builder
           if (s.length() < k) {
               builder.append(s.substring(0));
               break;
           } else {
               builder.append(s.substring(0, k));
           }

           // reverse next k chars and append
           if (s.length() < 2 * k) {
               sb.append(s.substring(k));
               s = s.substring(k);
           } else {
               sb.append(s.substring(k, 2 * k));
               s = s.substring(2 * k);
           }
           builder.append(sb.reverse());

       }
       return builder.toString();
   }
}

output

abcdefghijklmn