Find the number of occurrences of a specific string in a WITH A CATCH character group

I am trying to figure out how to calculate the number of occurrences of a specific string in a group of characters. The trick is that the letters in the string don't have to be next to each other, but must appear in sequential order.

For example, the sequence "aabcc" contains four occurrences of the string "abc"

as well bc with

a a b c c

a ABC with

a AB c c

I was thinking about using regex, but this only matches the first match.

+3


source to share


1 answer


Caveat : This is JavaScript (sorry!). It's also probably a lot more complicated than it needs to be, but my OCD won't leave him alone.

function search(needle, haystack) {
    var needles = needle.split('');
    var haystacks = haystack.split('');
    var matches = [];
    var nI = 0;
    var hI = 0;
    for (hI = 0; hI < haystacks.length; hI++) {
        for (nI = 0; nI < needles.length; nI++) {
            if (haystacks[hI] === needles[nI]) {
                matches.push(nI);
            } else {
                continue;
            }
        }
    }
    matches = matches.reduce(function (acc, el, index) {
        var cur = acc.map[el];
        if (!cur) {
            acc.map[el] = cur = [];
            acc.res.push(cur);
        }
        cur.push(index);
        return acc;
    }, {
        res: [],
        map: {}
    }).res;
    return matches;
}

function allPossibleCases(arr) {
    return combinations(arr).map(function (combination) {
        return combination.join(" ");
    });
}

function combinations(array) {
    if (!array.length) {
        return [];
    }

    array = array.map(function (item) {
        return item instanceof Array ? item : [item];
    });

    function combine(list) {
        var prefixes, combinations;

        if (list.length === 1) {
            return list[0];
        }
        prefixes = list[0];
        combinations = combine(list.slice(1));
        return prefixes.reduce(function (memo, prefix) {
            return memo.concat(combinations.map(function (combination) {
                return [prefix].concat(combination);
            }))
        }, []);
    }

    return combine(array);
}

var r = allPossibleCases(search("abc", "aabcc"));

// r.length = 4, r = array of matches

      



Here's a fiddle to play with.

Note: got some code from this answer that counts the remaining objects.

+1


source







All Articles