Re: OT programming challenge: fastest/best/shortest C program to jumble a sentence, then restore it

Liste des GroupesRevenir à col advocacy 
Sujet : Re: OT programming challenge: fastest/best/shortest C program to jumble a sentence, then restore it
De : bowman (at) *nospam* montana.com (rbowman)
Groupes : comp.os.linux.advocacy
Date : 08. Mar 2024, 21:48:54
Autres entêtes
Message-ID : <l518d6FmepqU1@mid.individual.net>
References : 1 2 3
User-Agent : Pan/0.149 (Bellevue; 4c157ba)
On Fri, 8 Mar 2024 08:09:33 -0500, DFS wrote:

It's harder than you think to randomly shuffle the words in a shorter
sentence, so that each word ends up in a different position than it
started in.
 Bring it!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int main(int argc, char** argv)
{
    char* sentence = strdup("Once you try it, you'll see it doesn't need spice.");
    char* tokens[20];
    int token_count = 0;
    int i;
    int j;
    int slots;
    int candidate;
    int* indices;
    for (tokens[token_count] = strtok(sentence, " ");
         tokens[token_count];
         tokens[token_count] = strtok(NULL, " "))
    {
        token_count++;
    }
    indices = malloc(token_count * sizeof(int));
    for (i=0; i<token_count; i++) {
        indices = -1;
    }
    srand((unsigned int) time(NULL));
    for (i=0, slots=0; slots<token_count; i++) {
        candidate = rand() % token_count;
        for (j=0; j<token_count; j++) {
            if (indices[j] == candidate) {
                 break;
            }
            else if (indices[j] == -1) {
                indices[slots++] = candidate;
                break;
            }
        }
    }
    printf("\nshuffled:\n");
    for (i=0; i<slots; i++) {
        printf("%s ", tokens[indices]);
    }
    printf("\noriginal: \n");
    for (i=0; i<slots; i++) {
        printf("%s ", tokens);
    }
    printf("\n");
    return 0;
}
./shuffle shuffled:
doesn't you spice. try Once it, it need see you'll original: Once you try it, you'll see it doesn't need spice. ./shuffle shuffled:
need it, spice. it you you'll see Once try doesn't original: Once you try it, you'll see it doesn't need spice. Get enough monkeys running it and the shuffled sentence may be the same as the original. For production, I'd first count the tokens and allocate the tokens array but I'm lazy. Further enhancements, allow the string to be entered on the command line, read strings from a file and write shuffled strings to a file, and so on.
Of course in Python you could use split and shuffle to abstract away all the messiness.
Date Sujet#  Auteur
5 Oct 24 o 

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal