Home > database >  How to divide array in different consecutive sequences
How to divide array in different consecutive sequences

Time:06-09

How to divide this array:- [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15] into two different arrays with one set of consecutive sequences in one array and another set of consecutive in another array.

for eg : array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15]

Desired output [0, 1, 2, 3, 4, 5, 6, 7, 8] and [12, 13, 14, 15]

The array should split into a number of consecutive sequences present in the array. If there are 3 consecutive sequences then the array should split into 3 different arrays with consecutive values and so on.

Another example = [1 ,2 ,3 ,4 5, 14, 15, 16, 22, 23, 24, 25]

Desired output [1, 2, 3, 4, 5] and [14, 15, 16] and [22, 23, 24, 25]

let arrnew = [0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 14, 15] 
   let arr2 = []

for (let j = 0; j < arrnew.length; j  ) {
    if (arrnew[j   1] - 1 === arrnew[j]) {
        arr2.push(arrnew[j])
    }
}

Tried this but not working.

CodePudding user response:

const arr = [1, 2, 3, 4, 5, 14, 15, 16, 22, 23, 24, 25];
const canSplit = (arr = []) => {
    const count = arr.reduce((acc, num) => {
      acc[num] = (acc[num] || 0)   1
      return acc
    }, {})
    const needed = {}
  
    for (const num of arr) {
      if (count[num] <= 0) {
        continue
      }
      count[num] -= 1
      if (needed[num] > 0) {
        needed[num] -= 1
        needed[num   1] = (needed[num   1] || 0)   1
      } else if (count[num   1] > 0 && count[num   2]) {
        count[num   1] -= 1
        count[num   2] -= 1
        needed[num   3] = (needed[num   3] || 0)   1
      } else {
        return false
      }
    }
    return true
}
console.log(canSplit(arr));

CodePudding user response:

var arr = [1,2,3,4,6,7,8,9,10]
var result = []

for (var i = 0; i < arr.length; i  ) {
    if (i === 0) {
        result.push([arr[0]])
    } else if (arr[i] != arr[i-1]   1) {
        result.push([arr[i]])
    } else {
        tmp = result[result.length - 1]
        tmp.push(arr[i])
        result[result.length - 1] = tmp
    }
}

console.log(result) // [ [ 1, 2, 3, 4 ], [ 6, 7, 8, 9, 10 ] ]

Here we loop through arr. For the first element, the only thing we need to do is append to result a new array with the first number.

Now, for every number after the first one, if the current number is not equal to the previous number 1, we need to append a new array to result that contains the current number. Otherwise, we simply append the current number to the last array in result.

  • Related