Generate a random Binary String of length N
Last Updated :
13 Mar, 2023
Given a positive integer N, the task is to generate a random binary string of length N.
Examples:
Input: N = 7
Output: 1000001
Input: N = 5
Output: 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:
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int findRandom()
{
int num = (( int ) rand () % 2);
return num;
}
void generateBinaryString( int N)
{
srand ( time (NULL));
string S = "" ;
for ( int i = 0; i < N; i++) {
int x = findRandom();
S += to_string(x);
}
cout << S;
}
int main()
{
int N = 7;
generateBinaryString(N);
return 0;
}
|
Java
class GFG{
static int findRandom()
{
int num = ( 1 + ( int )(Math.random() * 100 )) % 2 ;
return num;
}
static void generateBinaryString( int N)
{
String S = "" ;
for ( int i = 0 ; i < N; i++)
{
int x = findRandom();
S = S + String.valueOf(x);
}
System.out.println(S);
}
public static void main (String[] args)
{
int N = 7 ;
generateBinaryString(N);
}
}
|
Python3
import random
def findRandom():
num = random.randint( 0 , 1 )
return num
def generateBinaryString(N):
S = ""
for i in range (N):
x = findRandom()
S + = str (x)
print (S)
N = 7
generateBinaryString(N)
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
public class GFG {
static int findRandom()
{
Random rand = new Random();
int num = rand.Next() % 2;
return num;
}
static void generateBinaryString( int N)
{
string S = "" ;
for ( int i = 0; i < N; i++)
{
int x = findRandom();
S = S + x.ToString();
}
Console.WriteLine(S);
}
public static void Main ( string [] args)
{
int N = 7;
generateBinaryString(N);
}
}
|
Javascript
<script>
function findRandom() {
let num =
(1 + parseInt((Math.random() * 100))) % 2;
return num;
}
function generateBinaryString(N) {
let S = "" ;
for (let i = 0; i < N; i++) {
let x = findRandom();
S += (x).toString();
}
document.write(S)
}
let N = 7;
generateBinaryString(N);
</script>
|
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...