What am I doing wrong?

It wont shuffle
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
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 << " "<<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() % (i + 1)], a[i]);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <ctime>

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:

1
2
3
4
5
6
7
8
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.