Search code examples
javascriptalgorithmnumberssequence

Find consecutive numbers sequence in a string


I have a string of numbers, and in it, there is always a random sequence, like:

891011 -> 8, 9, 10, 11
123124 -> 123, 124

how can i find the sequence? my current code is this:

var digits = [8, 9, 1, 0, 1, 1];
var number;

for (var j = 0; j < digits.length; j++) {
  number = digits.slice(0, j + 1).join("");
  if (
    Number(number) === Number(digits.slice(j, number.length).join("")) &&
    digits
    .join("")
    .match(new RegExp(".{1," + number.length + "}", "g"))
    .every(function(num, index) {
      return index === digits.length - 1 || num < digits[index + 1];
    })
  ) {
    break;
  }
}

console.log(number)


Solution

  • You can increment the number of digits of the starting number and see if we can generate a matching output with consecutive numbers. Try like below:

    const findSequence = (input) => {
      // starting number cannot be more than half of the length
      let maxLengthOfStartingNumber = input.length / 2;
      for(let i = 1; i <= maxLengthOfStartingNumber; i++) {
        // starting number can be a number with a few digits
        let startingNumber = parseInt(input.substring(0, i));
        // data holder for consecutive numbers we generate
        let generatedNumbers = [startingNumber]
        // current string we create by concatinating generated numbers
        let currentString = startingNumber.toString();
        // we can generate integers until we surpass the length of the actual input and check
        while(currentString.length < input.length){
          const nextNumber = generatedNumbers[generatedNumbers.length-1]+1;
          generatedNumbers.push(nextNumber)
          currentString += nextNumber;
        }
        // check whether we could generate a string with consecutive numbers which matches with the input
        if(currentString === input){
          return generatedNumbers;
        }
      }
      // input is invalid and return null
      return null;
    }
    
    const testInputs = ["891011", "123124", "9991000", "123454"]
    
    testInputs.forEach(testInput => {
      console.log(findSequence(testInput));
    })