Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finding sequential in string using javascript

I am going to find sequential string of numbers in string which starts from 1. For example I have this string.

"456000123456009123456780001234000"

Here sequential strings would be

"123456", "12345678", "1234"

How can I get above result using Javascript efficiently? The code looks like this.

findSequential("456000123456009123456780001234000");
//expected output
"123456", "12345678", "1234"

***note: "1" itself is not sequential, for example:

"3938139" - has no sequence
"39381249" - has "12"

With any language's solution would be appreciated but prefer Javascript or C. Thanks for your help!

like image 864
Bojan Avatar asked Jun 18 '20 23:06

Bojan


People also ask

How do you determine if a string contains a sequence of repeated letters?

push(char[i]); } else { tempArry[char[i]] = []; tempArry[char[i]]. push(char[i]); } } console. log(tempArry); This will even return the number of repeated characters also.

How to escape in string JavaScript?

Using the Escape Character ( \ ) We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

What is a string sequence?

A string is a sequence of characters. You can access the characters one at a time with the bracket operator: >>> fruit = 'banana' >>> letter = fruit[1] The second statement extracts the character at index position 1 from the fruit variable and assigns it to the letter variable.


1 Answers

A simple for loop should be able to achieve this. In JavaScript:

function findSequential(s) {
    const res = []
    let current = []
    let num = 1
    for(let char of s) {
      if (char == num) {
        current.push(char)
        num ++
      } else if (current.length > 1) {
        res.push(current.reduce((acc, cur) => acc += cur, ''))
        if (char == 1) {
          current = ['1']
          num = 2
        } else {
          current = []
          num = 1
        }
      } else if (current.length === 1) {
        current = []
        num = 1
      }
    }
    if (current.length > 1) {
      res.push(current.reduce((acc, cur) => acc += cur, ''))
    }
    return res
}

console.log(findSequential('31234121'))
like image 102
Daniel Elkington Avatar answered Oct 12 '22 11:10

Daniel Elkington