Anders Pedersen
Anders Pedersen

Reputation: 2385

Count all sequences of characters

I have an Array of Characters ' A ' and ' B '

Whats a smart way to count the ' Runs '

example :

AABBBAAAABBAB

should be 6 because there are 6 runs as seen below.

1    2    3     4   5  6
AA   BBB  AAAA  BB  A  B 

tried something like:

if (!(sortedRuns.get(i) == sortedRuns.get(i+1))) {
    runsAmount++;
}

but obviously run into 'out of bound problems'

Upvotes: 0

Views: 92

Answers (4)

user3688900
user3688900

Reputation: 36

You could use a regular expression. /(.)\1*/ gives 6 matches.

(.) matches any character. \1* then matches as many of the first character as possible.

Java Example:

final String regex = "(.)\\1*";
final String string = "AABBBAAAABBAB";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

int count = 0;
while (matcher.find()) {
    count ++;
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}
System.out.println("Match count: " + count);

This has the advantage of working with any character string.

Upvotes: 0

MSD
MSD

Reputation: 1407

u can try this easy one-liner:

public static void main(String[] args) {
    String s="AABBBAAAABBAB";

    int charCount = s.length() - s.replaceAll("A", "").length();
    System.out.println(charCount);
    System.out.println(s);
}

Upvotes: 0

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

Issue

e.g char array      A A B B C C
    array positions 0 1 2 3 4 5

when you reach at the position 5 then sortedRuns.get(i+1) mean 5+1=6 which doesn't exist hence the exception

Solution

1.) Traverse the array

2.) Increment run if char changes and assign new char to temp char

String s="AABBBAAAABBAB";
int run=1;
// fetch first char
char temp=s.charAt(0);

// traverse char array
for (char ch : s.toCharArray()) {
    // assign value of new char to temp and increment run 
    // when value of char changes
    if (ch!=temp) {
        run++;
        temp=ch;
    }

}
System.out.println(run);

Output:

6

Upvotes: 4

jpadilladev
jpadilladev

Reputation: 1946

I would use an auxiliar variable to save the last character. Then increment when a new character is different from my auxiliar variable, then update this variable. Easy and not out of bounds exceptions.

Upvotes: 0

Related Questions