skip to Main Content

let input arr=[9,4,4,8,90,4,9,4,4,4,4,4,4,4,4,4,7,9,2,4,4,4,4,4,8,4,4,4,4];

let output arr=[1,7,9,11,13,15,19,21,25,27];

Above is an input array of numbers which contain mostly 4, if there is a pair of 4 which means (Input elements has 2 of the number 4 consecutively), its array position will be displayed in the output array. I have tried my code below but I am still unsure on how to solve this :). May I know how to solve this?

console.clear();
let arr=[8,4,4,4,4,4,4,4,4,4,7,9,2,4,4,4,4,4,8,4,4,4,4];

console.log("his")
for (let i=0;i<arr.length;i++){
if (arr[i]!==arr[i+1] &&arr[i]!==4 ){
console.log(i)
}
if (arr[i]!==arr[i+1] &&arr[i+1]!==4 ){
console.log(i+1)
}

}

2

Answers


  1. You could look to the next item and if the last index is not in the result array, the add the actual index to the result.

    const
        input = [9, 4, 4, 8, 90, 4, 9, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 9, 2, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4],
        result = input.reduce((r, v, i, a) => {
            if (v === a[i + 1] && r[r.length - 1] !== i - 1) r.push(i);
            return r;
        }, []);
    
    console.log(...result);

    An approach for n elements with a closure over a counting variable c.

    const
        getIndices = (array, n) => input.reduce((c => (r, v, i, a) => {
            if (!c) {
                if (v === a[i + 1]) c = 1;
                return r;
            }
    
            c = v === a[i - 1] ? c + 1 : 0;
            
            if (c === n) {
                r.push(i - n + 1);
                c = 0;
            }
            return r;
        })(0), []),
        input = [9, 4, 4, 8, 90, 4, 9, 4, 4, 4, 4, 4, 4, 4, 4, 4, 7, 9, 2, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4];
    
    console.log(...getIndices(input, 2));
    console.log(...getIndices(input, 3));
    console.log(...getIndices(input, 4));
    console.log(...getIndices(input, 5));
    Login or Signup to reply.
  2. This is a possible solution:

    console.clear();
    let arr=[8,4,4,4,4,4,4,4,4,4,7,9,2,4,4,4,4,4,8,4,4,4,4];
    let pair = false;
    
    for (let i=0;i<arr.length;i++){
      if (pair == false) {
          if (arr[i]==arr[i+1]){
            console.log(i)
            pair = true; // show that we have found a pair
          }              // thus we skip a 'for' loop
      }
      else {
        pair = false; // reset the pair variable
      }
    }
    
    

    output: [1, 3, 5, 7, 13, 15, 19, 21]

    Do you want this pair:
    let arr=[8,4,4,4,4,4,4,4,4,4,7,9,2,4,4,4,4,4,8,4,4,4,4];

    to be counted, as well?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search