Home > Enterprise >  C program that generates a string of alphanumericals and then sorts
C program that generates a string of alphanumericals and then sorts

Time:12-08

I am trying to write a script in c that generates a string of alphanumerical values,based on the desired size of the user input, and then it sorts it.

#include <stdio.h>
#include <stdlib.h>

#define FIRST_CHAR 'a'
#define LAST_CHAR 'z'
#define NULL_CHAR '\0'


char *randomString( int minSize, int maxSize){
int i,strSize;
char *newStr;
    strSize = minSize   ( rand() % (maxSize-minSize   1 ) );
    newStr = (char*)malloc(strSize   1 );
    if (newStr == NULL) {
        printf( " \n Error in memory allocation. Cannot create random string. \n " );
        return NULL;
    }
    for (i = 0; i < strSize; i  ) {
        newStr[i] = FIRST_CHAR   (rand() % (LAST_CHAR - FIRST_CHAR   1));
    }
    newStr[i] = NULL_CHAR;
return newStr;
}

void printStrings(char **strArray, int strArraySize)
{
    int i;
    for(i=0;i<strArraySize;  i)
    {
        printf("%s",strArray[i]);
    }
    printf("/n");
}
char *sort(char **strArray, int strArraySize)
{int i,j;
 char *sortedArray;
    for(i=0;i<strArraySize;  i)
    {
        for(j=FIRST_CHAR;j<=LAST_CHAR;  i)
        {
            if(strArray[i]==j)
            {
                strArray[i]=sortedArray[i];
            }
        }
    }
    sortedArray[i]= NULL_CHAR;
return sortedArray;
}

int main()
{int size,minSize=5,maxSize=20;
 char** str;
    printf("Dwse plithos alpharithmitikon\n");
    scanf("%d",&size);
    **str=*randomString(minSize,maxSize);

    printf("Seira pou dimiourgithike.\n");
    printStrings(str,size);

    printf("Seira pou taksinomithike.\n");
    printStrings(sort(str,size),size);

    return 0;
}

the main issue is that i cant wrap my head around the proper use of pointers in c. I am aware that it is of important use,especially while working with alphanumerical strings, but i am just not there yet. Thanks in advance !

CodePudding user response:

Here is an example of a program that generates a string of alphanumeric characters then sorts it:

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

#define LENGTH 10

// Generate a random alphanumeric string
char* gen_str() {
  char* str = malloc(LENGTH   1);
  static const char alphanum[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

  for (int i = 0; i < LENGTH; i  ) {
    str[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
  }
  str[LENGTH] = 0;
  return str;
}

// Compare two strings for sorting
int str_cmp(const void* a, const void* b) {
  const char* str1 = *(const char**) a;
  const char* str2 = *(const char**) b;

  return strcmp(str1, str2);
}

int main() {
  srand(time(0));

  // Generate an array of random alphanumeric strings
  char** str_arr = malloc(LENGTH * sizeof(char*));
  for (int i = 0; i < LENGTH; i  ) {
    str_arr[i] = gen_str();
  }

  // Print the unsorted array
  printf("Unsorted:\n");
  for (int i = 0; i < LENGTH; i  ) {
    printf("%s\n", str_arr[i]);
  }

  // Sort the array using qsort
  qsort(str_arr, LENGTH, sizeof(char*), str_cmp);

  // Print the sorted array
  printf("\nSorted:\n");
  for (int i = 0; i < LENGTH; i  ) {
    printf("%s\n", str_arr[i]);
  }

  return 0;
}

This program uses the rand() function to generate random numbers, the malloc() function to dynamically allocate memory, and the qsort() function to sort the array of strings.

CodePudding user response:

While the following generator is not truly random (what is?), it delivers a random number of random length ASCII "strings" (actually, just one string sprinkled with LF characters) created in sorted order. If nothing else, it provides a starting point from which to refine a better solution.

char palette[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

int main( void ) {
    srand( time( 0 ) );

    // some constants
    const int obufsz = 512;
    const int maxStrLen = 15;

    // the output buffer
    char obuf[ obufsz ], *op = obuf;

    // random number of strings (min: 5, max 20) 
    int nStrs = 5   rand()%(obufsz/maxStrLen);
    if( nStrs > 20 ) nStrs = 20;

    // increment so that successive first chars are always larger
    int incr = sizeof palette / nStrs;

    for( int strNo = 0; strNo < nStrs; strNo   ) {
        // assign the 'ascending' first char
        *op   = palette[ strNo * incr   (rand() % incr) ];

        // assign more chars (variable length)
        for( int charNo = 1   rand()%(maxStrLen-2); charNo; charNo-- )
            *op   = palette[ rand() % (sizeof palette - 1 ) ];

        // a LF for eventual printing
        *op   = '\n';
    }
    *op   = '\0';

    puts( obuf );

    return 0;
}

If you want to wrap your head around using C's pointers, grab a pencil and paper and start drawing boxes and arrows. A box would be a memory location (a pointer variable) that contains the address of another box that is (often) the first element of a contiguous array of boxes each holding either a 'primitive' datatype (ie: a 'char' or an 'int', etc.), or holding a pointer to another memory location (ie: a pointer to a pointer.) "Boxes and arrows" - that's how most people come-to-terms with C's pointers.

  • Related