patternjavaMinor
Find no of swaps needed to club identical elements of array together
Viewed 0 times
neededelementsarrayidenticaltogetherswapsfindclub
Problem
I have created a solution for the problem as below:
Given a string S consisting of letters 'O' and 'Z'. Calculate the
minimum number of changes required such that all O's are adjacent to
each other and all Z's are adjacent to each other. One change is
equivalent to swapping two neighbouring letters
for e.g for a given array: oozozo desired array is : oooozz so,min no
of swap would be 3,which should be the desired output.
Let me know if the solution has any bad practices.
My Code:
Given a string S consisting of letters 'O' and 'Z'. Calculate the
minimum number of changes required such that all O's are adjacent to
each other and all Z's are adjacent to each other. One change is
equivalent to swapping two neighbouring letters
for e.g for a given array: oozozo desired array is : oooozz so,min no
of swap would be 3,which should be the desired output.
Let me know if the solution has any bad practices.
My Code:
package com.test.practice;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class TestClass {
public static void main(String args[]) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String numberOfInputs = br.readLine();
for (int i = 0; i < numberOfInputs.length(); i++) {
String inputString = br.readLine();
findNumberOfTurns(inputString);
}
}
private static void findNumberOfTurns(String inputString) {
int count = 0;
char[] input = inputString.toCharArray();
char firstCharacter = input[0];
char secondCharacter;
boolean secondCharEncountered = false;
int countSecondChar = 0;
for (int i = 1; i < input.length; i++) {
if (firstCharacter == input[i]) {
if (!secondCharEncountered) {
countSecondChar=0;
} else {
count+=countSecondChar;
secondCharEncountered=false;
}
} else {
secondCharEncountered=true;
countSecondChar+=1;
}
}
System.out.println(count);
}
}Solution
Bug
Your method doesn't calculate the correct number of swaps. Using the input string
Single resopsonsibility principle
The
Your method doesn't calculate the correct number of swaps. Using the input string
oozzoo the correct result should be 4 but your algorithm gets a result of 2. Single resopsonsibility principle
The
findNumberOfTurns() method is calculating the number of swaps and prints the output which is too much. Let the method return the number of swaps needed. Printing the result shouldn't be in that method.Context
StackExchange Code Review Q#115307, answer score: 3
Revisions (0)
No revisions yet.