I need an algorithm that takes a string of characters and a number as parameters. It will output a string.

The numeric parameter is the maximum number of identical characters that can be consecutive in the output string.

The output string should contain the same characters, and be the same length, as the input string. The only difference is that the order of the characters in the output is such that the maximum consecutive characters is not exceeded.

For example, F("aaaabbac", 2) = "aabaabac" would be a valid result.


My thinking so far is along these lines:

PHP Code:
do loop
    start from left of string
    count consecutive characters
    
if count max_consecutive then
        swap current character with next 
(differentcharacter (may have to wrap round to the start of the string to find this)
    endif
until no set of consecutive characters exceeds max_consecutive 
I'd be grateful for comments and also some ideas on how to test the algorithm.