Iterative for Loop Vice Versa

I need to generate different combinations of numbers based on the input provided. For example, if the input is 3, there would be 8 combinations as shown below:

0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1

For input 4, there would be 16 combinations. Currently, I am achieving this using nested for loops in JavaScript like so:

value1 = 2, value2 = 2, value3 = 2;
my function () {
    for(var i = 0; i<this.value1; i++) { 
      for(var j = 0; j < this.value2; j++) { 
        for(var k = 0; k < this.value3; k++) { 
           console.log(i,j,k);
        }
      }
    }
}

However, this approach works well for small inputs but becomes impractical for larger ones like 10. I believe recursion could be a better solution, but I'm not sure how to implement it in this scenario. Any assistance or guidance would be greatly appreciated.

Answer №1

Check out this awesome recursive function that tackles the task at hand.

function customFunction(arr, count, result) {
    if (count === arr.length) {
        console.log(result.join(' '));
    } else {

        for (let i = 0; i < arr[count]; i++) {
            result.push(i);
            customFunction(arr, count + 1, result);
            result.pop();
        }
    }
}

function runCustomFunction(arr) {
    customFunction(arr, 0, []);
}

runCustomFunction(new Array(10).fill(2));

Answer №2

This example demonstrates a recursive solution:

function iterateRecursively(number, limit, prefix) {
  prefix = prefix || "";
  if (number == 0)
    console.log(prefix);
  else
    for (let index = 0; index < limit; index++)
      iterateRecursively(number - 1, limit, prefix + " " + index);
}

iterateRecursively(10, 2);

Answer №3

If you're seeking combinations in binary, a simple technique is to start counting from 0 in binary with added padding for completeness.

This method utilizes function generators, but it can be easily modified into a basic function.

function * generateBinaryCombinations(n){
  for(let i = 0; i < Math.pow(2, n); i++){
    const binary = i.toString(2);
    const padding = new Array(n - binary.length + 1).join('0');
    yield padding + binary;
  }
  return null;
}

const comboIterator = generateBinaryCombinations(4);
console.log(
  Array.from(comboIterator)
)

Answer №4

If you are using the latest browsers that have support for .padStart, you can achieve the desired output by following this code snippet (although it bypasses the issue with recursion rather than solving it):

let n = 4; //or any other value
    
Array(Math.pow(2,n)).fill(0).forEach((_,i) => console.log(i.toString(2).padStart(n,'0').split('').join(' ')));

Answer №5

One way to generate combinations on the fly is by utilizing a Generator with function*.

function* binaryCombination(length, array = []) {
    if (--length) {
        yield* binaryCombination(length, [...array, 0]);
        yield* binaryCombination(length, [...array, 1]);
    } else {
        yield [...array, 0];
        yield [...array, 1];
    }
}

[...binaryCombination(3)].map(combination => console.log(...combination));
.as-console-wrapper { max-height: 100% !important; top: 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

Executing JavaScript functions with Python and BeautifulSoup

My current project involves web scraping to extract data from a website. While I can successfully retrieve information present in the DOM, I am facing a challenge with data that is rendered through a JavaScript onClick function. One potential solution is ...

The file input modification event is disregarded if the identical filename is selected for upload

In my Vue.js application, I am utilizing Vuetify's v-file-input component. The file uploaded is connected to formData.file and its validation is controlled by the rules prop. <v-file-input :rules="fileValidationRules" v-model="fo ...

The promise is coming back as undefined

I am encountering an issue where the value returned from a promise is coming back as undefined in my template. In the getLabel function, I am receiving a label as a promise and resolving it before returning it to the title in the getMenuItems function. H ...

Executing javascript code that has been inserted into inner HTML is not functioning as expected

Trying to retrieve a response from another page, specifically named ajaxresponse.php, through an AJAX request. I also aim to execute some JavaScript actions on that ajaxresponse.php page, but the JavaScript code is not functioning as expected. Although I a ...

Integrate an external directory with Electron-Builder

Currently, I am working on developing multiple electron apps and have a designated directory for storing common images and files. My goal is to include these common resources in each app during the electron-builder build process. According to the documenta ...

Attempting to Retrieve Information from a Get Request using Axios

I am attempting to retrieve SQL data from a GET request using axios. My backend is set up with an express server, and the front end is built with React. In my React component, I have a function that contains the axios GET call, which I then invoke within t ...

Heroku NodeJS - Page Not Found: Error 404

I recently set up a Heroku server with BootBot running on it, but I'm facing challenges while trying to render an HTML page from it. Here is what I have in my code: var app = express(); var path = require('path'); app.use(express.static(pat ...

Transitioning to Material-ui Version 4

During the process of upgrading material-ui in my React Application from version 3.9.3 to version 4.3.2, I encountered an error message stating TypeError: styles_1.createGenerateClassName is not a function. I am feeling lost when it comes to transitioning ...

Switching back and forth between two different numbers with the help of React.useState hooks

Can someone help me with the logic using React.useState hooks? I'm trying to toggle the "volume" option in the state of the "PlayOn" object between 0 and 0.75. I am not very experienced with React. I need help with the function logic for soundChange ...

What is the best method for storing byte arrays within an object in Couchbase?

Is there a preferred method for storing byte arrays (less than 1 MB) as a field value? I am aware of the ByteArrayDocument and storing binary data separately as a non-JSON object. When storing a field as a byte array, should I simply use com.couchbase.cli ...

When utilizing the built-in filter in Angular 2 ag-grid, the Clear Filter button efficiently removes any text from the filter box without needing to refresh the

When using ag-Grid's default filter feature, I noticed that the clear filter button only clears the text box and does not automatically refresh the column, even when the 'clearButton' and 'applyButton' parameters are set to true. T ...

Obtain a pointer to the timestamp within a embedded Kibana chart on an HTML webpage

The image at the specified link shows a black box labeled @timestamp displaying date and time information. Unfortunately, viewing the image requires a reputation of 10. Link to image: https://www.elastic.co/assets/bltde09cbafb09b7f08/Screen-Shot-2014-09-3 ...

Loading the JS file after waiting on Lib (IronRouter) causes the HTML not to load properly

Currently, I am utilizing wait-on-lib along with IRLibLoader.load() in conjunction with Iron-Router, following the instructions provided in the tutorial found at: . My objective is to load external javascript code. Below is a snippet of my routing code: R ...

Tips for fixing CORS error when working with the fetch API

I'm having trouble retrieving data from the metaweather.com API using JavaScript's fetch function. I attempted to include before the API URL, but it has not resolved the issue. I followed a video tutorial on how to fetch data, but I'm stil ...

The element 'stripe-pricing-table' is not a recognized property of the 'JSX.IntrinsicElements' type

I am currently trying to incorporate a pricing table using information from the Stripe documentation found at this link. However, during the process, I encountered an issue stating: "Property 'stripe-pricing-table' does not exist on type &ap ...

How to dynamically activate menu tabs using Vanilla JavaScript?

I have been exploring this Codepen project and am attempting to replicate it using vanilla JS (as my company does not use jQuery). My progress so far includes adjusting the line width correctly when clicking on a menu item. However, I am struggling to mak ...

"Encountered an error: The function is not defined for password and re-entering password

I ran into this error message even after adding the javascript to my html code for registration. Unfortunately, none of the javascript functions or event listeners seem to be working as intended. As a beginner in learning about javascript and html, I would ...

What is the most effective method for utilizing v-model with a pre-populated form in Vue.js?

Need some help with a form and looping through items in a module to generate textfields. Take a look at the photo for context: Link: https://i.sstatic.net/MPAVq.jpg Currently, I'm using a structure like this... <v-row class=" ...

Retrieve Javascript data from JSON only if the specified parameter is set to true

I'm currently utilizing the TMDB API for fetching movie details and I want to extract the trailer from YouTube. If my JSON data appears as follows... { id: 568124, results: [ { iso_639_1: "en", iso_3166_1: "US", ...

What is the best way to transfer an ID from one ngRepeat to another?

I'm currently working on a project where I am using ngRepeat for posts and another one for comments. However, I am facing an issue with retrieving the comments for each post as I need to somehow pass the post ID into the comments ngRepeat. <div ng ...