Say that you have a string like this:
abaabbbbbaabba
Count the number of times that a specified character appears in the input string, but only if the character appears only once in a row. For example, if the character is a
,
abaabbbbbaabba
^ x x ^
The total would be 2 (the aa
's wouldn't count because the a
appears two times in a row).
How is this related to FizzBuzz?
If the character appears 3 (or a multiple of 3) times in a row, or 5 (or a multiple of 5) times in a row, the counter is decremented instead. If it is a multiple of both 3 and 5 times, the counter is still incremented. Remember that the counter is also incremented if the character appears only once in a row, and it is ignored if the character appears any other number of times in a row (besides the situations described above).
To recap, if the string to match is a
,
input counter (explanation)
a 1 (single occurence)
aaa -1(multiple of 3)
aaaaa -1(multiple of 5)
aaaaaaaaaaaaaaa 1 (multiple of 15)
aa 0 (none of the above)
aba 2 (two single instances)
aaba 1 (one single occurence(+1) and one double occurence(ignored))
aaaba 0 (one single occurence(+1) and one triple (-1)
aaaaaa -1 (six is a multiple of three)
Reference (ungolfed) implementation in java:
import java.util.Scanner;
import java.util.regex.*;
public class StrMatcher {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //Scanner to get user input
int total = 0;//Running total of matches
System.out.println("Enter a string: ");
String strBeingSearched = sc.nextLine(); //String that will be searched
System.out.println("Enter string to match with: ");
String strBeingMatched = sc.nextLine(); //Substring used for searching
//Simple regex matcher
Pattern pattern = Pattern.compile("(" + strBeingMatched + ")+");
Matcher matcher = pattern.matcher(strBeingSearched);
while(matcher.find()){ //While there are still matches
int length = matcher.end() - matcher.start();
int numberOfTimes = length/strBeingMatched.length();//Calculate how many times in a row the string is matched
if((numberOfTimes == 1)||((numberOfTimes % 3 == 0) && (numberOfTimes % 5 == 0))){
total++; //Increment counter if single match or divisible by 15
} else if((numberOfTimes % 3 == 0)||(numberOfTimes % 5 == 0)) {
total--; //Decrement counter if divisible by 3 or 5 (but not 15)
}
strBeingSearched = strBeingSearched.substring(matcher.end());
matcher = pattern.matcher(strBeingSearched); //Replace string/matcher and repeat
}
System.out.println(total);
}
}
- The string that will be searched can be any length, but the pattern will only be a single character.
- Neither string will have regex special characters.
- This is code-golf; shortest program in bytes wins.
- No standard loopholes.