looping through a string and checking if certain conditions are met

Viewed 92

I need to write a piece of code which accepts an input string parameter and determine if exactly 3 question marks exist between every pair of numbers that add up to 10. If so, return true, otherwise return false.Some examples test cases are below

"arrb6???4xxbl5???eee5"      => true
"acc?7??sss?3rr1??????5"     => true
"5??aaaaaaaaaaaaaaaaaaa?5?5" => false
"9???1???9???1???9"          => true
"aa6?9"                      => false

I already tried to implement it in Java as below but the result is not as expected

public static String QuestionsMarks(String str) { 
str = str.replaceAll("[a-z]+","");
Pattern pattern = Pattern.compile("([0-9])([?])([?])([0-9])");
Pattern pattern01 = Pattern.compile("([0-9])([?])([?])([0-9])");
Matcher matcher01 = pattern01.matcher(str);
Pattern pattern02 = Pattern.compile("([0-9])([0-9])");
Matcher matcher02 = pattern02.matcher(str);
Matcher matcher = pattern.matcher(str);

if (matcher01.find() || matcher02.find()) {
return "false";
} else if (matcher.find()) {
  return "true";
 }

return "false";
}
1 Answers

The regular expression to detect overlapping numbers separated with a number of question marks is as follows:

(?=((\d)([^?\d]*\?[^?\d]*)*(\d))) It uses a positive lookahead (?=) to handle overlapping numbers between adjacent matches of this pattern:
(\d)([^?\d]*\?[^?\d]*)*(\d): two digits separated by any number of question marks with other optional characters.

Online demo of the regexp

So, the regular expression provides a stream of matches in the form: Group1=StringWithQuestionMarks, Group2=Digit, Group4=Digit which should be validated against the rules: count the sum of the digits to be 10 and count the question marks between to be 3.

Example implementation using Stream API:

private static final Pattern DIGS = Pattern.compile("(?=((\\d)([^?\\d]*\\?[^?\\d]*)*(\\d)))");

public static boolean hasTotal10Around3QMarks(String str) {
    
    Supplier<Stream<MatchResult>> ss = () -> DIGS
        .matcher(str)
        .results()
        .filter(r -> r.groupCount() == 4 
            && 10 == Integer.parseInt(r.group(2)) + Integer.parseInt(r.group(4))
        );
    
    return ss.get().findAny().isPresent() &&
           ss.get().allMatch(r -> 3 == r.group(1).chars()
                                                 .filter(c -> c == '?')
                                                 .count()
    );
}

Supplier<Stream> helps to reuse stream of MatchResult to handle the last test case when there's no matching pair of digits with 3 question marks between (allMatch for empty stream returns true).

Tests:

String[] tests = {
    "arrb6???4xxbl5???eee5",
    "acc?7??sss?3rr1??????5",
    "5??aaaaaaaaaaaaaaaaaaa?5?5",
    "9???1???9???1???9",
    "aa6?9",
    ""
};

Arrays.stream(tests)
      .forEach(t -> System.out.printf("'%s' => %s%n", t, hasTotal10Around3QMarks(t)));

Output:

'arrb6???4xxbl5???eee5' => true
'acc?7??sss?3rr1??????5' => true
'5??aaaaaaaaaaaaaaaaaaa?5?5' => false
'9???1???9???1???9' => true
'aa6?9' => false
'' => false
Related