Home > OS >  how to get these following arrays with two pointer methodology in JavaScript?
how to get these following arrays with two pointer methodology in JavaScript?

Time:12-19

input [1,8,9]

output [[1],[1,8],[1,8,9],[8],[8,9],[9]]

It seems like subset array but i would like to get this output with two pointer way. let's say leftP=0, rightP=0; and then by using for loop, the rightP will increase up to the end of array until there's no more elements and then leftP move by 1...

1 -> [1], [1,8],[1,8,9]

8 -> [8],[8,9]

9 -> [9]


function solution(arr) {
   let totalArr = [];
   let leftP = 0;

   for(let rightP=0; rightP<arr.length; rightP  ) {
      totalArr.push(arr[rightP]);

      // this is where i'm kinda stuck
      while()

   }
}

CodePudding user response:

You can easily achieve this using just 2 for loop as you are doing as:

i is here leftP and j is here rightP

const arr = [1, 8, 9];

const result = [];

for (let i = 0; i < arr.length;   i) {
  let temp = [arr[i]];
  result.push([...temp]);
  for (let j = i   1; j < arr.length;   j) {
    temp.push(arr[j]);
    result.push([...temp]);
  }
  temp = [];
}

console.log(result);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }

CodePudding user response:

Simply slice the array using the two pointers!

Working solution below:

const arr = [1, 8, 9];

const solution = (arr) => {
  const resArr = [];

  for (let i = 0; i < arr.length; i  ) {
    for (let j = i   1; j <= arr.length; j  ) {
      resArr.push(arr.slice(i, j));
    }
  }

  return resArr;
};

console.log(solution(arr));

CodePudding user response:

I would just translate your logic into code, noting that you would need two nested loops.

function solution(arr) {
  let totalArr = [];
  for (let left = 0; left < arr.length; left  ) {
    totalArr.push([]);
    for (let right = left   1; right <= arr.length; right  ) {
      totalArr[left].push(arr.slice(left, right));
    }
  }
  return totalArr;
}

console.log(JSON.stringify(solution([1, 8, 9])));
.as-console-wrapper {
  max-height: 100% !important;
  top: auto;
}

(note that this groups them based on left - to make the array flat):

function solution(arr) {
  let totalArr = [];
  for (let left = 0; left < arr.length; left  ) {
    for (let right = left   1; right <= arr.length; right  ) {
      totalArr.push(arr.slice(left, right));
    }
  }
  return totalArr;
}

console.log(JSON.stringify(solution([1, 8, 9])));
.as-console-wrapper {
  max-height: 100% !important;
  top: auto;
}

  • Related