Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Mathematical Algorithm
  • Mathematical Algorithms
  • Pythagorean Triplet
  • Fibonacci Number
  • Euclidean Algorithm
  • LCM of Array
  • GCD of Array
  • Binomial Coefficient
  • Catalan Numbers
  • Sieve of Eratosthenes
  • Euler Totient Function
  • Modular Exponentiation
  • Modular Multiplicative Inverse
  • Stein's Algorithm
  • Juggler Sequence
  • Chinese Remainder Theorem
  • Quiz on Fibonacci Numbers
Open In App
Next Article:
Generate a random permutation of 1 to N
Next article icon

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 = 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:

  • 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


Next Article
Generate a random permutation of 1 to N
author
ramuk_neevan
Improve
Article Tags :
  • Strings
  • Mathematical
  • Randomized
  • Competitive Programming
  • C++ Programs
  • C++
  • DSA
  • binary-string
  • cpp-random
Practice Tags :
  • CPP
  • Mathematical
  • Strings

Similar Reads

  • Generate a random permutation of 1 to N
    Given an integer N, the task is to generate N non-repeating random numbers. Examples: Input: N = 5 Output: 1 5 2 4 3 Input: N = 8 Output: 7 2 1 8 3 6 4 5 Approach: Create an array of N elements and initialize the elements as 1, 2, 3, 4, ..., N then shuffle the array elements using Fisher-Yates shuff
    13 min read
  • Iterative program to generate distinct Permutations of a String
    Given a string str, the task is to generate all the distinct permutations of the given string iteratively. Examples: Input: str = "bba" Output: abb bab bba Input: str = "abc" Output: abc acb bac bca cab cba Approach: The number of permutations for a string of length n are n!. The following algorithm
    15+ min read
  • 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
  • Find the number of binary strings of length N with at least 3 consecutive 1s
    Given an integer N. The task is to find the number of all possible distinct binary strings of length N which have at least 3 consecutive 1s.Examples: Input: N = 3 Output: 1 The only string of length 3 possible is "111".Input: N = 4 Output: 3 The 3 strings are "1110", "0111" and "1111". Naive approac
    9 min read
  • How to Generate Random Number in Range in C++?
    In C++, we have a <random> header that consists of standard library facilities for random number generation. In this article, we will learn how to generate a random number in range in C++. Example: Input: Range: 1 to 20Output: Random number between 1 and 20 is: 18Generating a Random Number in
    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) // C++ program to generate random number #include <bits/stdc++.h> using namespace std; // Funct
    1 min read
  • Number Guessing Game in C++ using rand() Function
    In this article, we will develop a C++ game for guessing a secret number with three difficulty levels.  In this game, the computer generates a secret number in the range of 1 to 100, and the player has to guess it.The game has three difficulty levels. A player's chances of guessing are limited by th
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences