CLP_Core Java_E2 - Hands-on 1, Number of turns to get original word string, Two-person string manipulation

1. CLP_Core Java_E2 - Hands-on 1





John and Micheal take a word string:

 

John chooses a number P (less than the length of the string), and Micheal chooses Q (less than the length of the string). 

 

John reduces P alphabets from the end of the string, adds it to the beginning, and gives it to Micheal. 

 

Micheal reduces Q alphabets from the end of the string, adds it to the beginning, and gives it to John. 

 

This process continues until they get the original word string.
 
For a given string, and the given values of P and Q, find the number of turns to get the original word string.

 

Input Specification:
input1: Original word string
input2: Value of P
input3: Value of Q
 
Output Specification:
The number of turns to get the original word string.


Example

input: abcabc
input2: 1
input3: 1
 
Output: 3
 
Explanation:
turn 1: cabcab 
turn 2: bcabca
turn 3: abcabc 

 

All the three inputs are given as command line arguments.



Solution:-> Two-person string manipulation

public class Main {
    static String originalString = "abcabc";

    private static int operationCount(String word, int input1, int input2) {

        String updatedWord = "";
        updatedWord = checkNextIteration(originalString, input1);
        int count = 1;
        boolean flagForInput2 = true;
        while (!originalString.equals(updatedWord)) {
            if (flagForInput2) {
                updatedWord = checkNextIteration(updatedWord, input2);
                flagForInput2 = false;
                count++;
            } else {
                updatedWord = checkNextIteration(updatedWord, input1);
                flagForInput2 = true;
                count++;
            }
        }
        return count;

    }

    private static String checkNextIteration(String word, int shift) {
        String part1 = word.substring(word.length() - shift);
        String part2 = word.substring(0, word.length() - shift);
        System.out.println(part1.concat(part2));
        return part1.concat(part2);
    }

    // arguments are passed using the text field below this editor
    public static void main(String[] args) {
        originalString = args[0];
        System.out.println("Original String: " + originalString);
        System.out.println(operationCount(originalString, 1, 2));
    }
}

 

 CLP_Core Java_E2 - Hands-on 2, JSON object Count, JSON Level Count

Comments