Home > Software design >  Check for a single consecutive character in an array
Check for a single consecutive character in an array

Time:11-10

I have an array of numbers which can be a value of either 1 or 0. I need to create a function that detects if there is one instance where there is a consecutive 1 and no other 1 exist outside of that instance, returns true else false

So to sum it up here's a clearer view of the constraints to return true:

  1. must have only one set of consecutive 1
  2. there must be no other 1 outside of that one instance of consecutive 1

Test cases:

[0, 0, 1, 1, 0, 0] true

[1, 0, 1, 0, 0, 0] false

[1, 0, 1, 1, 0, 0] false

[1, 1, 0, 1, 1, 0] false

[0, 1, 1, 1, 1, 0] true

[0, 0, 1, 1, 1, 1] true

CodePudding user response:

Here's a simple while loop.

It'll also stop if it encounters multiple consecutive 1's to avoid extra iterations.

function oneRepeat(array) {
  let consecs = 0;
  let i = 0;
  while(consecs < 2 && i   < array.length - 2) {
    if (array[i] === 1 && array[i 1] === 1) consecs  
  }
  return consecs === 1;
}

console.log(oneRepeat([0,1,1,0,0,1]))
console.log(oneRepeat([0,1,0,1,0]))
console.log(oneRepeat([1,1,0,0]))

This can also be done with a for loop and break.

CodePudding user response:

function hasOneRun(arr) {
  let switches = 0;
  for (let i = 0; i < arr.length; i  ) {
    switches  = arr[i] ^ arr[i-1];
    if (switches > 2) return false;
  }
  return switches > 0;
}

Counts how many times it switches from 0 to 1 or 1 to 0. arr[i] ^ arr[i-1] is 1 only if the value changes from the previous value. If it's 0, there were only 0s, so false. If it's greater than 2, then it switched to 1, then to 0, then back to 1, so there were too many runs.

Here's a fun one-liner :D

Math.ceil(arr.reduce((switches, val, i) => switches   (val ^ arr[i-1]))) === 1;
  • Related