Mar 17, 2022

Random set

 #include <iostream>

using namespace std;


//Write a method to randomly generate a set of m integers from an array of size n. Each

// element must have equal probability of being chosen.


void printArray(int a[], int n)

{

    for(int i=0; i<n; i++)

    {

        cout << a[i] << " ";

    }  

    cout << endl;

}


void shuffle(int a[], int n)

{

    for(int i=n-1; i>=1; i--)

    {

        swap(a[i], a[rand()%(i)]);

    }

}


void randomSet(int a[], int n, int b[], int m)

{

    if(m>n)

        return;

        

    for(int i=n-1, j=0; i>=1 && j<m; i--, j++)

    {

        int k = rand()%(i);

        b[j] = a[k];

        swap(a[i], a[k]);

    }

}


int main() {

// your code goes here

int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

int b[100];

printArray(a, sizeof(a)/sizeof(a[0]));

// shuffle(a, sizeof(a)/sizeof(a[0]));

printArray(a, sizeof(a)/sizeof(a[0]));

randomSet(a, sizeof(a)/sizeof(a[0]), b, sizeof(a)/sizeof(a[0]) - 4);

printArray(b, sizeof(a)/sizeof(a[0]) - 4);

return 0;

}


Output :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 
2 10 14 3 4 8 12 9 11 15 13 

Shuffle a deck of cards

 #include <iostream>

using namespace std;


//Write a method to shuffle a deck of cards.


void printArray(int a[], int n)

{

    for(int i=0; i<n; i++)

    {

        cout << a[i] << " ";

    }  

    cout << endl;

}

void shuffle(int a[], int n)

{

    for(int i=n-1; i>=1; i--)

    {

        swap(a[i], a[rand()%(i)]);

    }

}

int main() {

// your code goes here

int a[] = {1, 2, 3, 4, 5, 6};

printArray(a, sizeof(a)/sizeof(a[0]));

shuffle(a, sizeof(a)/sizeof(a[0]));

printArray(a, sizeof(a)/sizeof(a[0]));

return 0;

}


Output:
1 2 3 4 5 6 
5 6 2 1 3 4