### What am I doing wrong?

It wont shuffle
 ``123456789101112131415161718192021222324252627282930313233`` ``````#include using namespace std; void my_swap(int &a, int &b); void my_shuffle(int a[], int n); int main() { int a; const int arr_size = 10; int arr[arr_size] = {1,2,3,4,5,6,7,8,9,10}; for(int count = 0; count < arr_size; count++) { my_shuffle(a); cout << " "< 0; i--) { my_swap(a[rand() % (i + 1)], a[i]); } }``````
 ``1234567891011121314151617181920212223242526272829303132333435`` ``````#include #include using namespace std; void my_swap(int &a, int &b); void my_shuffle(int a[], int n); int main() { srand(time(0)); const int arr_size = 10; int arr[arr_size] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; for (int count = 0; count < arr_size; count++) { my_shuffle(arr, arr_size); cout << " " << arr[count] << endl; } } void my_swap(int &a, int &b) { int t = a; a = b; b = t; } void my_shuffle(int a[], int n) { for (int i = n - 1; i > 0; i--) { my_swap(a[rand() % n], a[i]); } }``````
So first off, your `my_shuffle(a)` is using an integer argument that hasn't been initialized; you meant to pass `my_shuffle(arr)`.

Second, your prototype for `void my_shuffle(int a[], int n);` differs from your definition:

 ``12345678`` ``````void my_shuffle(int a[]) { int n; for (int i = n - 1; i > 0; i--) { my_swap(a[rand() % (i + 1)], a[i]); } }``````

noticing the missing `int n` in the definition that is supposed to hold the array size.

Third, I'm assuming in your `my_shuffle` definition, when you're using `swap()`, you want to switch a random element within the array with the current element being looked at. The correct code looks like:

`[rand() % n]`

You're selecting an index at a random location from 0 - 9 (size of array).

Fourth, you have a redefinition of `n` in `my_shuffle` , instead of simply passing `n` as a parameter.

Fifth, you have an un-used variable `a`.

Sixth, without a seed value - the random number is pseudo-random, meaning that each time you run the program you'll get the same results. I added `srand(time(0));` to fix that.

You may want to revisit declaring functions and passing arguments.
Last edited on
Topic archived. No new replies allowed.