Open In App

JavaScript Program to Generate all Binary Strings From Given Pattern

Last Updated : 06 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about Generating all binary strings from a given pattern in JavaScript. Generating all binary strings from a given pattern involves creating a set of binary sequences that follow the pattern’s structure, where specific positions in the sequences can be filled with ‘0’ or ‘1’ based on the pattern’s placeholders or rules.

Table of Content

We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Using Recursion

In this approach,

  • Recursion involves a function calling itself with modified parameters.
  • In this example, recursion generates binary strings based on the input pattern.
  • It branches at wildcard characters (‘X’) and preserves non-‘X’ characters, exploring all valid combinations.

Example: In this example, The BinaryStrings function generates binary strings by replacing ‘X’ in the input string ‘X1X’ with ‘0’ and ‘1’, recursively exploring all possibilities and printing the results.

Javascript




function BinaryStrings(str, index = '') {
    index.length === str.length
        ? console.log(index)
        : str[index.length] === 'X'
            ? (BinaryStrings(str, index + '0'),
                BinaryStrings(str, index + '1'))
            : BinaryStrings(str, index + str[index.length]);
}
  
const result = 'X1X';
BinaryStrings(result);


Output

010
011
110
111

Approach 2: Using Queue

In this approach,

  • We use a queue to iteratively generate binary strings from the ‘X’ pattern.
  • Expands the queue by appending ‘0’ and ‘1’ for ‘X’ characters or preserving non-‘X’ characters.
  • Prints valid binary strings when they reach the pattern’s length.

Example: In this example, we are using the above-explained approach.

Javascript




function generateBinaryStrings(str) {
    const queue = [''];
  
    for (let i = 0; i < queue.length; i++) {
        const current = queue[i];
  
        if (current.length === str.length) {
            console.log(current);
        } else {
            const nextIndex = current.length;
            if (str[nextIndex] === 'X') {
                queue.push(current + '0');
                queue.push(current + '1');
            } else {
                queue.push(current + str[nextIndex]);
            }
        }
    }
}
  
const result = 'X1X';
generateBinaryStrings(result);


Output

010
011
110
111


Similar Reads

JavaScript Program to Generate all Binary Strings Without Consecutive 1’s
Given an integer, K. Generate all binary strings of size k without consecutive 1’s. Examples: Input : K = 3 Output : 000 , 001 , 010 , 100 , 101 Input : K = 4 Output: 0000 0001 0010 0100 0101 1000 1001 1010Table of ContentUsing Recursive FunctionUsing Stack Data StructureUsing Iteration and padStart() MethodSo, let's see each of the approaches with
3 min read
JavaScript Program to Find all Strings that Match Specific Pattern in a Dictionary
Finding all strings in a dictionary that match a specific pattern in JavaScript involves searching for words that follow a particular structure or format within a given dictionary. The pattern can include placeholders for characters, allowing flexibility in the search. In this article, we will explore various approaches for finding all strings that
5 min read
Behavioral Design Pattern | JavaScript Design Pattern
Behavioral design patterns are a subset of design patterns in software engineering that deal with the interaction and responsibilities of objects. These patterns focus on how objects communicate and work together to achieve common tasks. Important Topics for the Behavioral Design Pattern in JavaScript Design Patterns Uses Cases of the Behavioral De
8 min read
Facade Design Pattern | JavaScript Design Pattern
Facade design pattern is a Structural design pattern that allows users to create a simple interface that hides the complex implementation details of the system making it easier to use. This pattern intends to create a simplified and unified interface for a set of interfaces hiding the implementation details making it less complex to use. Important
4 min read
Flyweight Design Pattern - JavaScript Design Pattern
The Flyweight Design Pattern is a structural design pattern used in JavaScript to minimize memory usage by sharing the data as much as possible with the related objects. Important Topics for Flyweight Design PatternDiagramatic Representation:Advantages of Flyweight design pattern:Disadvantages of Flyweight design pattern:The shared data typically c
4 min read
Mediator Design Pattern in JavaScript | Design Pattern
The Mediator pattern is a behavioral design pattern that promotes loose coupling between objects by centralizing communication between them. It's particularly useful when you have a complex system with multiple objects that need to interact and you want to avoid the tight coupling that can arise from direct object-to-object communication. Important
5 min read
Program to Print Inverted Right Half Pyramid Pattern (Star Pattern)
Given an integer N, print N rows of inverted right half pyramid pattern. In inverted right half pattern of N rows, the first row has N number of stars, second row has (N - 1) number of stars and so on till the Nth row which has only 1 star. Examples: Input: n = 5Output:*************** Input: n = 3Output:****** Approach: The problem can be solved us
3 min read
Javascript Program to Generate all rotations of a number
Given an integer n, the task is to generate all the left shift numbers possible. A left shift number is a number that is generated when all the digits of the number are shifted one position to the left and the digit at the first position is shifted to the last.Examples: Input: n = 123 Output: 231 312Input: n = 1445 Output: 4451 4514 5144 Approach:
3 min read
How to Generate Random and Unique Password in Node.js using 'generate-password' NPM Module ?
The "generate-password" module is a very useful and important external NPM module that can generate unique and random passwords for our projects. One of the main advantages of using this module is that it allows developers to easily generate passwords with various requirements, such as length, complexity, and character sets. This can save developer
2 min read
JavaScript Program to Add n Binary Strings
In this article, we are going to learn about Adding n binary strings by using JavaScript. Adding n binary strings in JavaScript refers to the process of performing binary addition on a collection of n binary strings, treating them as binary numbers, and producing the sum in binary representation as the result. There are several methods that can be
3 min read