Generate a random Binary String of length N

01 Dec, 2021
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.
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++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find a random// number between 0 or 1int 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 Nvoid 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 Codeint main(){    int N = 7;    generateBinaryString(N);     return 0;}
// Java program for the above approachclass GFG{     // Function to find a random// number between 0 or 1static 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 Nstatic 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 Codepublic static void main (String[] args){    int N = 7;         generateBinaryString(N);}} // This code is contributed by AnkThon
# Python3 program for the above approachimport random # Function to find a random# number between 0 or 1def 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 Ndef 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 CodeN = 7 generateBinaryString(N) # This code is contributed by sanjoy_62
// C# program for the above approachusing System;using System.Collections.Generic;using System.Linq; public class GFG {     // Function to find a random// number between 0 or 1static 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 Nstatic 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 Codepublic static void Main (string[] args){         int N = 7;    generateBinaryString(N);}} // This code is contributed by code_hunt.
<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>
0101101
 
Time Complexity: O(N)Auxiliary Space: O(N)
sanjoy_62
ankthon
hritikrommie
code_hunt
binary-string
cpp-random
Mathematical
Randomized
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modular multiplicative inverse
Find first and last digits of a number
Find cubic root of a number
Program to add two binary strings
Count all possible paths from top left to bottom right of a mXn matrix
K'th Smallest/Largest Element in Unsorted Array | Set 2 (Expected Linear Time)
Shuffle a given array using Fisher–Yates shuffle Algorithm
QuickSort using Random Pivoting
Shuffle or Randomize a list in Java
Generating Random String Using PHP