Generate a random Binary String of length N Last Updated : 13 Mar, 2023 Comments Improve Suggest changes Like Article Like Report Given a positive integer N, the task is to generate a random binary string of length N. Examples: Input: N = 7Output: 1000001 Input: N = 5Output: 01001 Approach: The given problem can be solved by using the rand() function that generates a random number over the range [0, RAND_MAX] and with the help of the value returned by this function, any number in any range [L, R] can be generated as (rand() % (R - L + 1)) + L. Follow the steps below to solve the problem: Initialize an empty string, say S.Iterate over the range [0, N - 1] and perform the following steps:Store a random number in the range [0, 1] using rand() function.Append the randomly generated 0 or 1 to the end of the string S.After completing the above steps, print the string S as the resulting binary string. Below is the implementation of the above approach: C++ // C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to find a random // number between 0 or 1 int findRandom() { // Generate the random number int num = ((int)rand() % 2); // Return the generated number return num; } // Function to generate a random // binary string of length N void generateBinaryString(int N) { srand(time(NULL)); // Stores the empty string string S = ""; // Iterate over the range [0, N - 1] for (int i = 0; i < N; i++) { // Store the random number int x = findRandom(); // Append it to the string S += to_string(x); } // Print the resulting string cout << S; } // Driver Code int main() { int N = 7; generateBinaryString(N); return 0; } Java // Java program for the above approach class GFG{ // Function to find a random // number between 0 or 1 static int findRandom() { // Generate the random number int num = (1 + (int)(Math.random() * 100)) % 2; // Return the generated number return num; } // Function to generate a random // binary string of length N static void generateBinaryString(int N) { // Stores the empty string String S = ""; // Iterate over the range [0, N - 1] for(int i = 0; i < N; i++) { // Store the random number int x = findRandom(); // Append it to the string S = S + String.valueOf(x); } // Print the resulting string System.out.println(S); } // Driver Code public static void main (String[] args) { int N = 7; generateBinaryString(N); } } // This code is contributed by AnkThon Python3 # Python3 program for the above approach import random # Function to find a random # number between 0 or 1 def findRandom(): # Generate the random number num = random.randint(0, 1) # Return the generated number return num # Function to generate a random # binary string of length N def generateBinaryString(N): # Stores the empty string S = "" # Iterate over the range [0, N - 1] for i in range(N): # Store the random number x = findRandom() # Append it to the string S += str(x) # Print the resulting string print(S) # Driver Code N = 7 generateBinaryString(N) # This code is contributed by sanjoy_62 C# // C# program for the above approach using System; using System.Collections.Generic; using System.Linq; public class GFG { // Function to find a random // number between 0 or 1 static int findRandom() { // For random generator Random rand = new Random(); // Generate the random number int num = rand.Next() % 2; // Return the generated number return num; } // Function to generate a random // binary string of length N static void generateBinaryString(int N) { // Stores the empty string string S = ""; // Iterate over the range [0, N - 1] for(int i = 0; i < N; i++) { // Store the random number int x = findRandom(); // Append it to the string S = S + x.ToString(); } // Print the resulting string Console.WriteLine(S); } // Driver Code public static void Main (string[] args) { int N = 7; generateBinaryString(N); } } // This code is contributed by code_hunt. JavaScript <script> // Javascript program for the above approach // Function to find a random // number between 0 or 1 function findRandom() { // Generate the random number let num = (1 + parseInt((Math.random() * 100))) % 2; // Return the generated number return num; } // Function to generate a random // binary string of length N function generateBinaryString(N) { // Stores the empty string let S = ""; // Iterate over the range [0, N - 1] for (let i = 0; i < N; i++) { // Store the random number let x = findRandom(); // Append it to the string S += (x).toString(); } // Print the resulting string document.write(S) } // Driver Code let N = 7; generateBinaryString(N); // This code is contributed by Hritik </script> Output: 0101101 Time Complexity: O(N) In the above-given approach, there is one loop for iterating over string which takes O(N) time in worst case. Therefore, the time complexity for this approach will be O(N).Auxiliary Space: O(N)// an extra variable store all the characters of the string and in worst case all characters will be unique hence algorithm takes up linear space Comment More infoAdvertise with us Next Article Generate a random Binary String of length N ramuk_neevan Follow Improve Article Tags : Strings Mathematical Randomized Competitive Programming C++ Programs C++ DSA binary-string cpp-random +5 More Practice Tags : CPPMathematicalStrings Similar Reads How to Create a Random Alpha-Numeric String in C++? Creating a random alpha-numeric string in C++ means generating random characters from the set of alphanumeric characters (i.e., âAâ-âZâ, âaâ-âzâ, and â0â-â9â) and appending them to a string. In this article, we will learn how to create a random alpha-numeric string in C++. Example Output:a8shg1laCre 2 min read How to generate a vector with random values in C++? Generating a vector with random values means creating a vector of n elements and initialize each element some random values. In this article, we will learn different methods to initialize a vector with random values in C++.The recommended method to initialize a vector with random values is by using 3 min read How to Seed a Random Number Generator in C++? In C++, seeding a random number generator is important for generating different sequences of random numbers on each program run. This process consists of initializing the generator with a starting value, known as a seed. This ensures the randomness and unpredictability required for various applicati 2 min read Program to generate random alphabets Prerequisite : rand() and srand() Given all alphabets in a character array, print a string of random characters of given size.We will use rand() function to print random characters. It returns random integer values. This number is generated by an algorithm that returns a sequence of apparently non-r 4 min read C++ program to generate random number The below implementation is to generate random number from 1 to given limit. The below function produces behavior similar to srand() function. Prerequisite : random header in C++ | Set 1(Generators) CPP // C++ program to generate random number #include <bits/stdc++.h> using namespace std; // F 1 min read Generate n-bit Gray Codes | Set 2 Given a number n, generate bit patterns from 0 to 2^n-1 such that successive patterns differ by one bit. Examples: Input: n=2Output: 00 01 11 10Explanation:Every adjacent element of gray code differs only by one bit. So the n bit grey codes are: 00 01 11 10 Input: n=3Output: 000 001 011 010 110 111 6 min read Generate all the binary strings of N bits Given a positive integer number N. The task is to generate all the binary strings of N bits. These binary strings should be in ascending order.Examples: Input: 2Output:0 00 11 01 1Input: 3Output:0 0 00 0 10 1 00 1 11 0 01 0 11 1 01 1 1Approach: The idea is to try every permutation. For every positio 8 min read Generate all Binary Strings of length N with equal count of 0s and 1s Given an integer N, the task is to generate all the binary strings with equal 0s and 1s. If no strings are possible, print -1 Examples: Input: N = 2 Output: â01â, â10âExplanation: All possible binary strings of length 2 are: 01, 10, 11, 00. Out of these, only 2 have equal number of 0s and 1s Input: 6 min read Generate all binary numbers in range [L, R] with same length Given two positive integer numbers L and R. The task is to convert all the numbers from L to R to binary number. The length of all binary numbers should be same. Examples: Input: L = 2, R = 4Output:010011100Explanation: The binary representation of the numbers: 2 = 10, 3 = 11 and 4 = 100.For the num 6 min read Generate all binary strings from given pattern Given a string containing of '0', '1' and '?' wildcard characters, generate all binary strings that can be formed by replacing each wildcard character by '0' or '1'. Example : Input: str = "1??0?101"Output: 1000010110001101101001011010110111000101110011011110010111101101 Recommended PracticeGenerate 13 min read Like