Search code examples
cdev-c++

How to show characters of string in array randomly


I am making my university project in which I want the user to guess the word of that characters randomly shown from an array of strings and I achieve to show characters randomly but the problem is that some characters repeat and some never show.

I have tried to make an array to store an index to that are already shown character then check if it is already in an array or not but I stuck here program not run as I expect.

char arrWords[5][10] = { 
                                                    {"Hello"},
                                                    {"world"},
                                                };

// Seed random number generator
srand(time(NULL));

int i, j, k, r, index[5];

// for loop every word in array
for(i=0; i<=5; i++) {

    // for loop every character in i word
    for(j=0; j<=strlen(arrWords[i]); j++) {

        r = random(strlen(arrWords[i]));

        index[j] = r;

        for(k=0; k<=5; k++) {
            printf("%d ", index[k]);
        }           

    }

    printf("\n\n\n");

}

int random(int range){
    int num;
    num = rand() % range;
    return num;
}

I want to show "hello" like -> "elolh", "world" -> "dlorw"


Solution

  • You doesn't check if index is already written in index array. Try below one.

    int lock;
     // for loop every word in array
    for(i=0; i<=5; i++) {
        j=0;
        lock = 0;
        // for loop every character in i word
        while( j<=strlen(arrWords[i])) {
    
            r = random(strlen(arrWords[i]));
            for(k=0; k < j; k++)
            {
               if(index[k] == r)
                  lock++;
            }
            if(lock == 0)
            {
               index[j] = r;
               j++;
            }
            lock = 0;         
        }
    
        for(k=0; k<=5; k++) {
            printf("%d ", index[k]);
        }  
    
        printf("\n\n\n");
    
    }
    

    Above code is adapted from your original code. However this is kind of inefficient way to do that because while loop waiting until the random function return unavailable index. That's why @David Ranieri's approach is more convenient to achieve what u are trying to do.