Reputation: 3
I have a function that shuffles the elements of an array (possible duplicates). My code for the function is below:
int shuffle_values(int *array, int max_value){
int i, j;
int new_array[MAX_VALUE_ALLOWED];
for (i = 0; i < max_value; ++i){
new_array[i] = array[i];
}
if (max_value > MAX_VALUE_ALLOWED){
return 0;
}else{
for (j = 0; j < max_value; ++j){
array[j] = new_array[(random_value(max_value) - 1)];
}
}return 1;
}
Here is the code that tests my functions:
#define MAX_VALUE_ALLOWED 200
int random_value(int max_value){
int rand_val;
rand_val = (rand() % max_value) + 1;
return rand_val;
}
void print_values(int *array, int max_value){
int i;
for (i = 0; i < max_value; ++i){
printf("%d|", array[i]);
} printf("\n");
}
int main() {
unsigned int seed = 20;
int values[MAX_VALUE_ALLOWED], max_value;
srand(seed);
max_value = 8;
shuffle_values(values, max_value);
print_values(values, max_value);
shuffle_values(values, max_value);
print_values(values, max_value);
max_value = 20;
shuffle_values(values, max_value);
print_values(values, max_value);
shuffle_values(values, max_value);
print_values(values, max_value);
return 0;
}
The expected output is:
5|4|3|1|8|6|7|2|
3|4|7|5|8|2|1|6|
11|7|20|4|9|19|13|12|10|14|6|2|16|1|15|5|8|18|17|3|
6|3|5|9|14|15|20|2|10|11|16|8|7|17|1|19|18|12|4|13|
But I'm getting:
32517|-940709567|0|32517|0|0|-938539808|0|
32517|-940709567|-938539808|0|0|-940709567|32517|-940709567|
-940709567|-940709567|32517|32517|-940709567|0|-940709567|0|32767|32767|32517|0|1|0|0|32517|1|0|-940709567|0|
0|-940709567|-940709567|32767|0|0|1|-940709567|32517|32767|32767|-940709567|32517|-940709567|-940709567|1|0|0|32517|-940709567|
However when I test the same code here:
#include <stdio.h>
#include <stdlib.h>
#define MAX_VALUE_ALLOWED 200
int random_value(int max_value){
int rand_val;
rand_val = (rand() % max_value) + 1;
return rand_val;
}
int main(){
int max_value = 8;
int array[8] = {1,2,3,4,5,6,7,8};
int i, m;
printf("Original array:");
for (i = 0; i < max_value; ++i){
printf("%d|", array[i]);
}printf("\n");
printf("Shuffled array:");
shuffle_values(array, max_value);
for (m = 0; m < max_value; ++m){
printf("%d|", array[m]);
}printf("\n");
return 0;
}
The output I get is correct:
Original array:1|2|3|4|5|6|7|8|
Shuffled array:8|7|2|4|2|8|3|5|
Any thoughts?
Upvotes: 0
Views: 88
Reputation: 269
You have random values left in memory for your values array in main. It is working the way it's supposed to. However, you are using it on the data you don't want to work on.
Try initializing your values array before shuffling. Eg.:
for (i = 0; i < max_value; ++i){
array[i] = i;
}
Upvotes: 3