How to split string on substrings determined by function p5.js

1.1k Views Asked by At

I managed to find all n-digit sequence that repeat in a given digit string. Though my problem is how do i split the string on the repeated sequences, as shown on this example:

string 123543512

searching for 2-digit sequences

duplicates "12","35"

splitedstring 12 35 4 35 12

    var n = 2; 
    var a = 0;
    var b = n;
    var arr =[];

    function newText(input) {
      var str1 = textfield.value(); //given string
      while (a <= str1.length & b < str1.length+1) { 
        res = str1.substring(b, a);
        arr[a]=res;
        push();
        a = a + 1
        b = b + 1
      }         
        var potnij = arr.slice().sort();
        var takisam = []; //duplicates
        for (var i = 0; i < arr.length - 1; i++) {
            if (potnij[i + 1] == potnij[i]) {
                takisam.push(potnij[i]);
            }
        }
        console.log(takisam);
        }
2

There are 2 best solutions below

2
On BEST ANSWER

Your first stop should be the P5.js reference.

Specifically, the splitTokens() function does exactly what you describe. You give it a string and then a list of tokens (substrings) to split on, and it returns an array of strings that were separated by those tokens.

0
On

You can find all sequences like this(Just a rough example)

const sequence = (str, len) => {
    return str.split('').reduce((acc, current) => {
        const last = acc[acc.length - 1];
        if (last) {
            const biggest = parseInt(last.slice(-1));
            if (current > biggest && last.length < (len || 2)) {
                acc.splice(-1, 1, "" + last + current);
                return acc
            }
        }
        acc.push(current);
        return acc;
    }, []);
};

You may add data validation and other checks if needed. Then you can use another function to remove duplicates. Please check a working fiddle https://jsfiddle.net/5vy6k4hp/3/