quarta-feira, 15 de novembro de 2006

Scrambling a sorted array.


/*
* File: newmain.c
* Author: cassius
*
* Created on 15 de Novembro de 2006, 13:22
*/

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

const char ptr[] ="string";

typedef struct
{
const char *c;
int i;
}test_struct;

test_struct s={ptr,10};


/* Only to take control of it */
#define DEFAULT_ARRAY_SIZE 10
#define MAX_ARRAY_PERMITED_SIZE 1024

/*
*
*/
int
main(int argc, char** argv) {
int *array = NULL;
int k = 0;
int length = DEFAULT_ARRAY_SIZE;
int arg_pos = 1;
double n;

/* If you want to force the same resoults, use -seed num to set a seed
to the pseudo random sequence.
*/
while(arg_pos < argc) {
if( (strcmp(argv[arg_pos],"--seed") == 0) && (argc - arg_pos >= 2 ) ) {
int seed;

arg_pos++;
seed = atoi(argv[arg_pos]);
srand(seed);
} else if( (strcmp(argv[arg_pos],"--length") == 0) && (argc - arg_pos >= 2 ) ) {
int user_length;
arg_pos++;
user_length = atoi(argv[arg_pos]);
if( (user_length < 1) || (user_length > MAX_ARRAY_PERMITED_SIZE ) )
fprintf(stdout, "Invalid length. Assuming default value of %d.\n",length);
else
length = user_length;

}
arg_pos++; /* bypass argment name or last args processed */
}

/* Suppouse we use only 100 positons, for now */
array = (int*)malloc(sizeof(int)*length);

if(array == NULL)
{
fprintf(stderr, "No memory could be allocated. Exiting... ");
return (EXIT_FAILURE);
}

for(k = 0; k < length; k++ )
array[k] = k;

/* Now, scramble the array. The process is simple. The k variable points to
the end of the array. We choose randomically between all positions bellow
k. This position must be swapped with k. And the process goes on until
the the start of the array.
Warning: Although */


for(k = (length-1); k > 0;k-- )
{
int temp_int = array[k];
int old_pos = rand() % k;

array[k] = array[old_pos];
array[old_pos] = temp_int;
}

/* Print the array. */

fprintf(stdout, "[");
for(k = 0; k < length; k++)
{
char term = k == (length -1) ? ']' : ',';

fprintf(stdout, "%d%c",array[k],term);
}
fprintf(stdout, "\n");

return (EXIT_SUCCESS);
}


Nenhum comentário:

Quem sou eu

Minha foto
I used to work with embedded software and digital design. Now my career is about to turn in a complete different direction ...