So I need to create a template function that shuffles a dynamic array of dynamic objects. The exercise is guiding me a bit by giving me a starting point.

#include<iostream>

using namespace std;

template < class X > void shuffle(X ** myArray, int myArraySize) {
  // TODO: Implement here the shuffle algorithm 
}

I'm kinda lost on how I should use the pointer inside the function but have a general idea on how the code should be. I know it has a lot of mistakes but it's just an idea.

for (int i = myArraySize - 1; i > 0; i--) {
  int index = //a random index in the span [0,i]
  int a = myArray[index];

  myArray[index] = myArray[i];
  myArray[i] = a;
}

2 Answers

0
Community On

Actually there is already a example on how to shuffle a array in the c++ reference at http://www.cplusplus.com/reference/algorithm/random_shuffle/ and http://www.cplusplus.com/reference/algorithm/shuffle/ which describe how std::random_shuffle and std::shuffle are implemented

0
Scott On

Do you mean something like this?

#include <iostream>
#include <stdlib.h>
using namespace std;

template< class T >
void shuffle(T* myArray, int myArraySize){
    int index;
    T temp;
    for (int i = myArraySize - 1; i > 0; i--) {
        index = rand() % myArraySize;

        temp = myArray[index];
        myArray[index] = myArray[i];
        myArray[i] = temp;
    }
}

int main(){
    int* ints = new int[10];

    for(int i=0; i<10; i++){
        ints[i] = i+1;
    }
    for(int i=0; i<10; i++){
        cout << ints[i] << "-";
    }
    cout << " Before Shuffle" << endl;


    shuffle<int>(ints, 10);


    for(int i=0; i<10; i++){
        cout << ints[i] << "-";
    }
    cout << " After Shuffle" << endl;
}