What is the approach for obtaining the specified arrays using two pointer methodology in JavaScript?

input [1,8,9]

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

It appears to be a subset array, but I am aiming to achieve this output using a two-pointer approach. Let's assign leftP=0, rightP=0; and then utilizing a for loop, the rightP will iterate until the end of the array and then the leftP will 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 am encountering an obstacle
      while()

   }
}

Answer №1

To achieve this task, you can utilize two for loops as demonstrated below:

i represents leftP and j represents rightP

const sampleArray = [1, 8, 9];

const outcome = [];

for (let i = 0; i < sampleArray.length; ++i) {
  let tempArr = [sampleArray[i]];
  outcome.push([...tempArr]);
  for (let j = i + 1; j < sampleArray.length; ++j) {
    tempArr.push(sampleArray[j]);
    outcome.push([...tempArr]);
  }
  tempArr = [];
}

console.log(outcome);
/* This CSS snippet is not related to the solution. It is only for formatting purposes. Please disregard it */
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To solve this problem, simply utilize the two pointers technique!

Here is a functional solution:

const arr = [1, 8, 9];

const solve = (arr) => {
  const resultArr = [];

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

  return resultArr;
};

console.log(solve(arr));

Answer №3

To convert your reasoning into code, I would suggest using two nested loops.

function generateSubarrays(arr) {
  let allSubarrays = [];
  for (let start = 0; start < arr.length; start++) {
    allSubarrays.push([]);
    for (let end = start + 1; end <= arr.length; end++) {
      allSubarrays[start].push(arr.slice(start, end));
    }
  }
  return allSubarrays;
}

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

(Please note that this organizes the subarrays based on the starting index to flatten the array):

function generateSubarrays(arr) {
  let allSubarrays = [];
  for (let start = 0; start < arr.length; start++) {
    for (let end = start + 1; end <= arr.length; end++) {
      allSubarrays.push(arr.slice(start, end));
    }
  }
  return allSubarrays;
}

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way for me to showcase information?

I am currently facing an issue with displaying user information retrieved from my database using AngularJS. The code snippet below shows how I am trying to get the user data: angular.module('listController',[]) .controller('listCtrl' ...

Using router.get with a redirect in Express

Can you directly invoke a router.get(...) function in Express? Let's say I have a router.get('/my-route', function(req, res) { ... });, is it feasible to then, within another part of my code, use res.redirect('my-route'); with the ...

Is it necessary to use Hapi.js on the client side in order to establish a websocket connection using the Hapi.js protocol?

Currently, I am in the process of developing an API using Hapi and requiring WebSocket functionality. After some research, it appears that Nes is the preferred choice to integrate with Hapi for this purpose. Fortunately, Nes simplifies the process signific ...

The color scheme detection feature for matching media is malfunctioning on Safari

As I strive to incorporate a Dark Mode feature based on the user's system preferences, I utilize the @media query prefers-color-scheme: dark. While this approach is effective, I also find it necessary to conduct additional checks using JavaScript. de ...

Having issues with the functionality of Bootstrap 4 popover?

In my Spring MVC web project, a Bootstrap popover appears when the help icon is clicked. However, on the first click, the popover opens and moves away from the icon. After closing it and clicking again, the popover correctly positions itself. When I chan ...

Utilize PHP Sub-Arrays with Key References

Currently, I am experimenting with PHP 5.4 to handle data received from an HTTP API in XML format. To convert this XML data into an array, I utilize the following process: $xml = simplexml_load_string($resp); $json = json_encode($xml); $arr = json_decode( ...

What is the process for establishing a dependency on two distinct JavaScript files, similar to the depends-on feature found in TestNG?

I am faced with a scenario where I have two separate JS files containing test methods, namely File1 and File2. The requirement is that File2.js should only be executed if File1.js has successfully completed its execution. My current setup involves using ...

Embedding Array into Mongodb is an efficient way to store and

Whenever I attempt to store array data within MongoDB using the query below, it always shows a success message without actually storing any data in an empty array inside MongoDB. My goal is to successfully store array data inside MongoDB as shown in the f ...

What is the process to obtain the download URL for an image stored in Firebase Storage?

I have encountered an issue while trying to upload an image to Firebase storage and then retrieve the download URL. Here is the code snippet that I am using: const response = await fetch(selectedImage.uri); const file = await response.blob(); const storag ...

Guide on incorporating arrays into an array using JavaScript

Is there a way to achieve the specified outcome in JavaScript? I attempted to find a method for it on MDN but was unsuccessful. let a, b let allNumbers = [] for (a = 10; a < 60; a = a + 10) { for (b = 1; b <= 3; b++) { allNumbers.push(a ...

Is the original object cloned or passed by reference when passing it to a child React component through props?

When passing an object to a child component through the components props in React, does the object get cloned or does it simply pass a reference to the original object? For instance, in my App.js, I am importing a JSON object called ENTRY_DATA. Then, I pa ...

Understanding how to access POST content in Meteor.js is an important aspect

In my Meteor app, I am trying to retrieve data using POST requests. Here is the code snippet I am using on the server side: __meteor_bootstrap__.app.stack.splice (0, 0, { route: '/input', handle: function(req, res, next) { req.on(' ...

Custom pagination with onSelectionModelChange in React Material UI Data Grid

Has anyone encountered a problem with using the DataGrid component's onSelectionModelChange prop? I can successfully retrieve the selected rows for a single page, but when I implement custom pagination and navigate to the next page, the previous selec ...

JS | How can we make an element with style=visibility:hidden become visible?

HTML: <div id="msg-text"><p><b id="msg" name="msg" style="visibility:hidden; color:#3399ff;">This is a hidden message</b></p></div> JS: $('#url').on('change keyup paste', function() { $('# ...

How do you transform data stored in map to string format?

The main objective is to take a large txt file and replace all words according to the information in a csv file. This process will generate a new txt file as well as a new csv file that shows the frequency of each word. I'm currently struggling with ...

Executing NPM commands in a sequential manner

If I have the following npm scripts: "scripts": { "pre-build": "echo \"Welcome\" && exit 1", "build_logic": "start cmd.exe @cmd /k \"yo esri-appbuilder-js:widget && exit 1\"", "post_build": "start C:\ ...

Updating an iframe's content URL

I am currently working on building a website using Google Web Design and everything is going well so far. I have added an iFrame to the site and now I am trying to figure out how to change its source when a button is pressed. Most of the information I fo ...

What is the best way to refresh a Windows 7 command prompt screen before executing a new function in Node.js?

I attempted system calls for cls and also tested out this code snippet: function clear() { process.stdout.write('\u001B[2J\u001B[0;0f'); } Unfortunately, none of the options seem to be effective. ...

Permit the use of the "&" character in mailto href links

When including an email mailto href link and using a & character in the subject, it can cause issues with code rendering. For example, if the subject is "Oil & Gas," only "Oil" may show up. In most cases, you could simply replace the & with th ...

AngularJS remove a row from a table disrupts the formatting

Hello! I am attempting to delete rows from a table in Angular. I want the first two rows to have a red background and the rest to have a white background. If I try to delete the last row, it gets deleted but the color remains for the first row only (it sh ...