I am able to craft a function that takes in an integer and produces an array filled with pairs of integers [a, b] arranged in ascending order of both a and b

I'm currently stuck on a practice problem in my software engineering bootcamp and could really use some help to steer me in the right direction.

The task is to create a function called generatePairs that takes an integer as input and returns an array containing pairs of integers [a, b]. The pairs should be sorted first by increasing values of 'a', then by increasing values of 'b'. Below are examples of the expected outputs for various inputs:

generatePairs(3) // [ [0, 0], [0, 1], [0, 2], [0, 3], [1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 3] ]
generatePairs(2) // [ [0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2] ]
generatePairs(1) // [ [0, 0], [0, 1], [1, 1]]
generatePairs(0) // [ [0, 0]]

Below is the code I have so far:

function generatePairs (num){
  array = [];
  
  for (i = 0; i<=num; i++){
    array.push([i,i]);
    if ((i+1)<=num) {
        array.push([i,i+1])
    }

    if ( num - i <= num && i===0 && num < i ) {
      array.push([i,num])
      if (num + i < i) {
        array.pop();
      }
    }

  } 
  return array;
}

generatePairs(2) // [ [0, 0], [0, 1], [0, 2], [1, 1], [1, 2], [2, 2] ]

The issue I am facing is when testing it with 2, I noticed that I am missing the [0,2] subarray. My attempts at resolving this involved additional conditional statements, but none of them managed to work flawlessly. They either resulted in higher than expected subarrays at the end or only worked for the number 2 but not for any other possible input.

Answer №1

Isn't it much more straightforward than that?

function createPairs(number) {
  let array = []
  for (let x = 0; x <= number; x++) {
    for (let y = x; y <= number; y++) {
      array.push([x, y])
    }
  }
  return array
}
console.log(createPairs(2));

Answer №2

solution: (secret ninja code)

const generatePairs = n => Array.apply(null,{length:((n+1)*(n+2)/2)}).reduceRight((a,c,i)=>{
  a.r.push([...a.p])
  if(++a.p[1]>n) a.p[1]=++a.p[0]
  return i?a:a.r
},{p:[0,0],r:[]})

for (let x=4;x--;) document.write(x,'->',JSON.stringify(generatePairs(x)), '<br>')

Answer №3

This is the solution you've been looking for. By iterating through numbers, you can generate pairs starting from the first number up to a specified number.

function generatePairs(num) {
    var output = []

    for (var i = 0; i < num + 1; i++) {
       for (var k = i; k < num + 1; k++) {
          output.push([i, k])
       }
    }

    return output
}

Answer №4

recursion

We have the ability to implement the function generatePairs in a hopeful manner -


const generatePairs = (n = 0) =>
  chooseN(2, range(0, n))

The function range is a basic one that creates an array from a to b -


const range = (a = 0, b = 0) =>
  a > b
    ? []
    : [ a, ...range(a + 1, b) ]

and chooseN is a general function that generates all combinations of size n from array a -


const chooseN = (n = 0, a = []) =>
  n <= 0
    ? [[]]
: a.length <= 0
    ? []
: chooseN(n - 1, a)
    .map(r => [a[0], ...r])
    .concat(chooseN(n, a.slice(1))

You can see how generatePairs operates in your own browser below -


const range = (a = 0, b = 0) =>
  a > b
    ? []
    : [ a, ...range(a + 1, b) ]

const chooseN = (n = 0, a = []) =>
  n <= 0
    ? [[]]
: a.length <= 0
    ? []
: chooseN(n - 1, a)
    .map(r => [a[0], ...r])
    .concat(chooseN(n, a.slice(1)))

const generatePairs = (n = 0) =>
  chooseN(2, range(0, n))

const log = x =>
  console.log(JSON.stringify(x))

log(generatePairs(3))
// [[0,0],[0,1],[0,2],[0,3],[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]]

log(generatePairs(2))
// [[0,0],[0,1],[0,2],[1,1],[1,2],[2,2]]

log(generatePairs(1))
// [[0,0],[0,1],[1,1]]

log(generatePairs(0))
// [[0,0]]


generators

Due to the large solution spaces involved in combinatorial problems, it is common practice to lazily generate combinations. JavaScript allows us to achieve this using generators -


const chooseN = function* (n = 0, a = [])
{ if (n <= 0)
    return yield []

  if (a.length <= 0)
    return

  for (const r of chooseN(n - 1, a))
    yield [a[0], ...r]

  yield* chooseN(n, a.slice(1))
}

Notice the structural similarity between this program and the previous one mentioned above -


const chooseN = function* (n = 0, a = [])
{ if (n <= 0)                         
    return yield []                   

  if (a.length <= 0)                   
    return                            

                                      
  for (const r of chooseN(n - 1, a))  
    yield [a[0], ...r]                

  yield* chooseN(n, a.slice(1))       
}

For instance, we could create a solver function that identifies the first pair, [ a, b ] where a > 3 and 3*a equals 2*b. Importantly, no extra pairs will be generated after discovering the initial solution -


const solver = (size = 0) =>
{ for(const [a, b] of generatePairs(size))
    if (a > 3)
      if (3 * a === 2 * b)
        return [a, b]
}

console.log(solver(10))
// [ 4, 6 ]

The solution with a = 4, b = 6 is accurate: 4 > 3 is true, and 3*4 equals 2*6 (12).

Below, we have the option to generate the entire array of pairs using Array.from -


const allPairs =
  Array.from(generatePairs(3)) 

console.log(allPairs)
// [[0,0],[0,1],[0,2],[0,3],[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]]

Click on the snippet below to create pairs using JavaScript's generators -


const range = (a = 0, b = 0) =>
  a > b
    ? []
    : [ a, ...range(a + 1, b) ]
    
const chooseN = function* (n = 0, a = [])
{ if (n <= 0)
    return yield []
    
  if (a.length <= 0)
    return
    
  for (const r of chooseN(n - 1, a))
    yield [a[0], ...r]
    
  yield* chooseN(n, a.slice(1))
}

const generatePairs = (n = 0) =>
  Array.from(chooseN(2, range(0, n)))
    
const log = x =>
  console.log(JSON.stringify(x))
  
log(generatePairs(3))
// [[0,0],[0,1],[0,2],[0,3],[1,1],[1,2],[1,3],[2,2],[2,3],[3,3]]

log(generatePairs(2))
// [[0,0],[0,1],[0,2],[1,1],[1,2],[2,2]]

log(generatePairs(1))
// [[0,0],[0,1],[1,1]]

log(generatePairs(0))
// [[0,0]]

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

What steps should I take to resolve the Heroku TypeScript and Node.js build error I'm experiencing?

This is my first time using Heroku. I encountered multiple errors in the Heroku logs when trying to deploy my project: 2023-02-03T09:02:57.853394+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=tech- ...

Pattern matching for ' ... '

I've been struggling to make a regular expression work properly: I need it to match anything that starts with __(' or __(" and ends with ') or ") I attempted using /__\(['"][^']*['"]\)/g and /__\([&apos ...

Sending Javascript Variable through Form

I'm a newcomer to JavaScript and struggling to solve a particular issue in my script. I need help passing the variable "outVal" to a PHP script when the submit form is clicked. The value of "outVal" should come from the "output" value in the script. I ...

jQuery's AJAX feature fails to identify the newly modified div classes

For my new website, I am developing a simple checklist feature. To handle the check and uncheck requests from users, I'm using jQuery's $.ajax() function. Whenever a user clicks on the check or uncheck buttons, jQuery retrieves the validation tok ...

There is a syntax error in the SQL query near the "if"

When I incorporate an if condition into my SQL select query, it results in a syntax error. select a.QM_ID,a.QM_QCM_ID,a.QM_Question,a.QM_Type,a.QM_Parent_Id,c.AM_Answer, c.AM_Comments from question_master a INNER JOIN Assessment_master c on (c.AM ...

Is it possible to configure node js to send an array instead of a string?

How can I modify the code to return a 2D array of the results? For example: clothes = [[1, "name", "desc"], [2, "name2", "desc2]] Can the 'res' variable send a list directly or do I need to create a list after returning it? app.get('/post&ap ...

Encountering difficulties loading .mtl and .obj files using react-three-renderer

I'm currently utilizing react-three-renderer to load .obj and .mtl files, but I'm encountering difficulties in rendering the model. Instead, a cube is being rendered inside the div. My goal is to replace the cube with my desired .obj model. Inst ...

Experiencing excessive CPU usage while utilizing a progress bar in Angular

Whenever I try to load a page with 2 progress bars, my CPU usage goes through the roof... I decided to investigate and found that once I removed them, the site's speed improved significantly. Here's a code snippet of one of the progress bars: ...

Node.js: Calculating the number of requests processed per second in the http.get()

In my node.js project, I am creating a simple application for sending HTTP requests. var http = require('http'); var options = { host: 'www.example.com', port: 80, path: '/index.html' }; for(var i = 0; i < 500; i++ ...

The timer is malfunctioning

I am new to JavaScript and looking to create a simple countdown. I came across this script: http://codepen.io/scottobrien/pen/Fvawk However, when I try to customize it with my own settings, nothing seems to happen. Thank you for any assistance! Below is ...

Develop an npm package that includes necessary dependencies

I am working on a distributed node.js project and I want to package the project's domain in a standalone file. To start, I created a package named "common" which contains some utilities by using the following command: npm pack This created the commo ...

What are the benefits of ensuring my Redux store is serializable?

While going through the redux documentation, I came across this important point: Still, you should do your best to keep the state serializable. Don't put anything inside it that you can't easily turn into JSON. This got me thinking, what are t ...

What is the process for attaching an iterator to the name value of every element within a cloneNode?

Consider the following scenario: <div id="addNewMenuElementPart2"> Numerous elements with a name attribute are present here. </div> <div id="addNewMenuElementPart3Optional"></div> Additionally, t ...

Issue a response with an error message when making an $http request

When using Angular, I encounter a situation where I need to handle error messages returned from an $http request. However, I am unsure of the best approach. In my Express code, I typically handle errors like this: res.send(400, { errors: 'blah' ...

PostgreSQL error: table column does not exist in Sequelize

Currently, I'm in the process of developing a compact webservice utilizing Node.js, Express, PostgreSQL database while incorporating Sequelize. The initial step involved setting up the database using the following SQL queries in psql: CREATE TABLE Con ...

Is ReactJS known for its exceptional performance in rendering large matrices?

Although I have no prior experience with ReactJS, I've heard about a great feature it offers called virtual DOM. It reminds me of the concept of virtual elements in Silverlight where invisible elements are removed from the tree to enhance user-perceiv ...

Animating a child element while still keeping it within its parent's bounds

I have researched extensively for a solution and it seems that using position: relative; should resolve my issue. However, this method does not seem to work in my specific case. I am utilizing JQuery and AnimeJS. My goal is to achieve the Google ripple eff ...

What is the best way to invoke a function in a class from a different class in Angular 6?

Below is the code snippet: import { Component, OnInit, ViewChild } from '@angular/core'; import { AuthService } from '../core/auth.service'; import { MatRadioButton, MatPaginator, MatSort, MatTableDataSource } from '@angular/mater ...

Advanced routing in Next.js

I'm currently grappling with the concept of dealing with nested levels in Next.js and finding it quite challenging to grasp the way it functions. The desired structure should follow this pattern: /[rootCat]/[subCat1]/[subCat2]/[productId] I'm w ...

Transform the arrow function into a standard JavaScript function

Here is the React return code snippet I'm working with: return ( <div className='App'> <form onSubmit={this.submit.bind(this)}> <input value={this.state.input} onChange={(e) ...