Generate all possible arrangements of zeros and ones in a two-dimensional matrix with dimensions of n by n

Looking to create a function that will generate an array of all possible 2D arrays consisting of 0s and 1s in JavaScript within a square 2D array. Essentially, this is similar to the question posed here: Make every possible combination in 2D array

However, I want to achieve this in Javascript without using any external packages. Also, I would like to include a parameter for the size of the array. For example, a 2x2 grid would look like this:

let arr = new Array(2).fill(0).map(() => new Array(2).fill(0))
combinations(arr, 2) { ... }

returns : 
[
    [ 
        [0, 0],
        [0, 0]
    ],
    [
        [0, 0],
        [0, 1]
    ],
    [...],
    [
        [1, 1],
        [1, 1]
    ]
]

I have attempted recursion but haven't been successful so far. Any assistance on this matter would be greatly appreciated.

Edit :

I am working on writing a recursive solution for this issue.

Currently, my method looks like this:

let arr = new Array(2).fill(0).map(() => new Array(2).fill(0))
const generateCombination = (arr, n) => {
    let ret = [];
    let tmp;
    for (let i = 0; i < n; i++) {
      for (let j = 0; j < n; j++) {
        ret.push(arr)
        arr[i][j] = 1;
        generateCombination(arr.slice(), n-1)
      }
    }
    return ret;
};

This implementation currently produces the following output :

[
  [ [ 1, 1 ], [ 1, 1 ] ],
  [ [ 1, 1 ], [ 1, 1 ] ],
  [ [ 1, 1 ], [ 1, 1 ] ],
  [ [ 1, 1 ], [ 1, 1 ] ],
]

Answer №1

Interestingly, a unique way to represent different combinations for an argument n is by generating binary sequences ranging from 0 to 2n2-1.

To handle the challenge of potentially large numbers, the code snippet provided utilizes the relatively new BigInt data type for number representation. It processes each number within that range, ensures the binary string is of fixed length through padding, and then organizes the strings into a two-dimensional array.

Although performance may not be stellar due to the magnitude of the calculations involved, the methodology employed in this implementation is certainly intriguing.

const generateCombinations = (n) => {
  const binaryDigits = n ** 2;
  const upperLimit = 2n ** BigInt(binaryDigits);
  const combinationsArray = [];
  
  for (let i = 0n; i  < upperLimit; i++) {
    const currentNumber = i.toString(2).padStart(binaryDigits, '0');
    
    combinations.push([...currentNumber].map(Number).reduce((accumulator, _, index, array) => (index % n)
        ? accumulator
        : [...accumulator, array.slice(index, index + n)], []));
  }
  return combinationsArray;
}

console.log(generateCombinations(2));


Note: The usage of BigInt relies on ECMAScript 2020, so compatibility may vary depending on your environment.

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

Using 'pointers manipulation' for efficient Quicksort algorithm in Python

When implementing quicksort in idiomatic C style, it can be done simply with two arguments: void quicksort(int inputArray[], int numelems); To handle later subdivisions (or partitions) safely, we can utilize pointer arithmetic with the two arguments: // ...

CSS3 Transform can sometimes cause unpredictable z-index or depth arrangements

Could there possibly be a glitch in CSS3, or am I just making a simple mistake? Take a look at the page I'm currently working on: View Page I wish I could demonstrate the error, but its behavior seems to be completely unpredictable. Here's what ...

Error Alert: Attempting to access the 'prototype' property of an undefined value has resulted in a TypeError after switching to react-scripts version 4.0.3

I encountered a problem where I received the following error message: (Uncaught Error: Module build failed (from ./node_modules/source-map-loader/dist/cjs.js)). After attempting to resolve it by using npm install, a new error popped up in the console: path ...

Is there a way to display only the specific child div within the parent div using JavaScript without affecting the others?

   **** Sorry for the lengthy title **** Today I encountered a problem that I would like to discuss with all of you. When I click on a "COMMENT" button, instead of triggering JavaScript code to display a CHILD.div inside the corresponding ...

Stylus remains undefined even after a successful npm installation

I've been following a tutorial to learn more about node.js, but I keep encountering a strange error. After running npm install stylus, I receive the following output: npm http GET https://registry.npmjs.org/stylus npm http 304 https://registry.npmjs. ...

What is the best way to display the remaining items in an array when a user clicks the next button?

Having a total of 12 cameras, I want to be able to select 4 cameras from a drop-down menu option and have only those 4 cameras displayed. Then, when I click on the next button, I need to show the remaining cameras in the selected layout format. How can thi ...

Terminating the HTTP connection in Node.js after a set period of time

I am working on a program in nodejs that needs to retrieve json data from existing services. However, due to real time constraints in my application, I need to ensure that the response is prepared within a maximum of 2 seconds. If the response preparation ...

Fragmentize lengthy string into smaller sections while maintaining the integrity of both HTML tags and words

Utilizing a loop, I am segmenting lengthy text into smaller portions. Within my string are HTML code snippets which should remain hidden from the user. The contents of my template string are as follows: var text = "I love Stackoverflow. It helps me l ...

Automatically adjust the size of embedded video streams within DIV elements

My application is quite simple, it displays four video streams in a quadrant layout. Users can double click on each video to switch to full-screen mode and then again to go back to the quadrant view, which all works perfectly. The issue I'm facing in ...

Achieving nested routes without the need for nested templates

My Ember routes are structured like this: App.Router.map(function() { this.resource("subreddit", { path: "/r/:subreddit_id" }, function() { this.resource('link', { path: '/:link_id'} ); }); }); However, ...

Exploring the possibilities with Rollbar and TypeScript

Struggling with Rollbar and TypeScript, their documentation is about as clear as AWS's. I'm in the process of creating a reusable package based on Rollbar, utilizing the latest TS version (currently 4.2.4). Let's delve into some code snipp ...

Having trouble with Gulp hanging on the task named 'some_task_name' when using gulp.parallel or gulp.series?

Out of the blue, my gulp configuration suddenly stopped working. It gets stuck on 'Starting...' when I use tasks with gulp.parallel or gulp.series. Just yesterday, the same config was running smoothly. Why did this sudden change occur? Here is a ...

The onClick event handler is executed during every rendering process

Initially, my default state is set as follows: this.state = { selectedTab : 'tab1' } When it comes to rendering, this is how I define it: render(){ const { selectedTab } = this.state; return( <li>tab1</li><li>ta ...

Can I substitute custom tags for the traditional <p> tag?

My HTML with CSS has an issue where a custom HTML tag is not displaying the text while my CSS picks up another tag. Interestingly, replacing <title>Layout Controls</title> with <p>Layout Controls</p> resolves the problem and shows t ...

Having issues with default sorting and searching not functioning in Datatables with Angularjs

Utilizing a directive to facilitate database building once ng-repeat has completed: app.directive('repeatDone', function() { return function(scope, element, attrs) { if (scope.$last) { scope.$eval(attrs.repeatDone); ...

Utilize Three.js to trace user mouse clicks and project them onto the Fabric.js canvas being employed as the texture

I am currently working on creating a 3D product configurator. Initially, I import the .gltf model and render it using Three.js. Next, I generate an SVG onto a Fabric.js canvas and utilize that canvas to create a THREE.CanvasTexture, which is then used to ...

Collapsing Bootstrap menu bar causing logo overlap

When the navbar collapses (when it shows the toggle icon), the menu items (home, services, portfolio, about, contact) overlap with the logo. If I remove the position:absolute from the logo (navbar-brand), the menu appears in the center. Is there a way to h ...

Verifying the presence of JSON data loaded directly from the server to decide whether the factory should initiate a request to retrieve the same data if it is not already available

I am currently developing an Angular application that is designed to load a JSON object from the server on page load, either freshly or if it doesn't already exist. I'm wondering how one could use a service or factory to check for the presence of ...

Is it possible to include a JavaScript file in another JavaScript file synchronously?

Is there a way to import external JavaScript files into my HTML file without causing any issues? Similar to how @import works in CSS. I've seen suggestions like appending a script tag to the DOM on websites like StackOverflow, but this method loads t ...

Using jQuery to create a seamless scrolling experience to both the top of a page and to

I've been looking for solutions on how to add both jQuery scroll to top and scroll to anchors, but haven't found any integrated options. Is it possible to achieve this here? We currently have a jQuery function in place to add a scroll-to-top fea ...