Programming Challenge-Chunk the string and reverse

-->

Programming Challenge Description:

Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time. If the number of elements is not a multiple of k, then the remaining items in the end should be left as is.

Input:

Your program should read lines from standard input. Each line contains a list of numbers and the number k, separated by a semicolon. The list of numbers are comma delimited.

Output:

Print out the new comma separated list of numbers obtained after reversing.

Test 1
Test Input
1,2,3,4,5;2
Expected Output
2,1,4,3,5

Test 2
Test Input
1,2,3,4,5;3
Expected Output
3,2,1,4,5

 

Program:

package com.emexo.programmingchallenge;

import java.util.Arrays;

public class ChunkTheStringAndReverse {

    public static void main(String[] args) {

        String input = "1,2,3,4,5;3";

        String response = chunkAndReverse(input);

        System.out.println(response);
    }

    public static String chunkAndReverse(String input) {

        String response = null;

        String[] inputArray = input.split(";");

        int index = Integer.parseInt(inputArray[1]);

        String array = inputArray[0];

        String[] stringArray = array.split(",");
        int noOfChunk = (int) Math.ceil((double) stringArray.length / index);

        int start = 0;

        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < noOfChunk; i++) {
            int end = Math.min(start + index, stringArray.length);

            String[] outputArray = Arrays.copyOfRange(stringArray, start, end);

            if (outputArray.length == index) {
                for (int j = outputArray.length - 1; j >= 0; j--) {
                    builder.append(outputArray[j]);
                    builder.append(",");
                }
            } else {
                for (int k = 0; k < outputArray.length; k++) {
                    builder.append(outputArray[k]);
                    builder.append(",");
                }
            }

            start += index;

        }

        if (builder.toString().endsWith(",")) {
            response = builder.toString().substring(0, builder.toString().length() - 1);
        }

        return response;
    }

}