How to select random two digits from anywhere in a number with C

1 Answer

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

// Function to select random two distinct digits from a number
// Caller provides buffer of size >= 3 (2 chars + '\0')
void getRandomTwoDigits(long long number, char *result) {
    char numStr[32];  // enough for long long
    snprintf(numStr, sizeof(numStr), "%lld", number);

    size_t len = strlen(numStr);
    if (len < 2) {
        strcpy(result, "E");  // error indicator
        return;
    }

    // Generate two distinct random indices
    int i = rand() % len;
    int j;
    do {
        j = rand() % len;
    } while (j == i);

    // Form the two-digit string
    result[0] = numStr[i];
    result[1] = numStr[j];
    result[2] = '\0';
}

int main(void) {
    srand((unsigned)time(NULL));

    long long num = 1234567;
    char randomTwo[3];
    getRandomTwoDigits(num, randomTwo);

    if (randomTwo[0] == 'E') {
        printf("Error: number must have at least 2 digits\n");
    } else {
        printf("Random two digits: %s\n", randomTwo);
    }

    return 0;
}


   
/* 
run:
   
Random two digits: 75
 
*/

 



answered Nov 26, 2025 by avibootz
...