Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to generate N random numbers that include specific digit X times in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h> 

void generate_numbers_that_include_specific_digit_x_times(int N, int xtims, int digit, int rndtimes, int to) {
    srand(time(NULL));
    
    int total_numbers = 0;
     
    for (int i = 1; i <= rndtimes; i++) {
        int n = rand() % to + 1;
        int copy_n = n;
        int count = 0;
        
        if (N == total_numbers) {
            return;
        }
        
        while (n > 0) {
            if (n % 10 == digit)
                count++;
            n = n / 10;
        }
        
        if (count == xtims) {
            total_numbers++;
            printf("%d\n", copy_n);
        }
    }
}

int main(void)
{
    generate_numbers_that_include_specific_digit_x_times(5, 3, 7, 2000, 1000000);

    return 0;
}
 
 
 
/*
run:
 
776367
995777
752177
727472
775970
 
*/

 



answered Mar 7, 2024 by avibootz
...