public void shuffle() -- This method will re-arrange the cards that are in the d
ID: 3567710 • Letter: P
Question
public void shuffle() -- This method will re-arrange the cards that are in the deck. The idea is that the deck will be divided into two "packets" -- the top half and the bottom half. The new array of cards will consist of: the first card from the bottom packet, followed by the first card from the top packet, followed by the second card from the bottom packet, followed by the second card from the top packet, etc. Important: If there are an odd number of cards, the top packet should have one more card than the bottom packet. Remember that the top of the deck is considered to be the front of the array.
I really need help with this. I have looked at the other google search results but none of the pass the test. so dont copy and paste.
Explanation / Answer
#include <iostream>
using namespace std;
int arr[] = {1,2,3,4,5,6,7,8,9,10,11};
void shuffle()
{
int n = sizeof(arr)/sizeof(arr[0]);
int *temp = new int[n];
int firstHalf = 0;
int secondHalf = n - (n/2);
for(int i=0; i<(n - (n%2)); i++)
{
if(i%2 == 0)
{
temp[i] = arr[secondHalf++];
}
else
{
temp[i] = arr[firstHalf++];
}
}
if(n%2 == 1)
temp[n-1] = arr[firstHalf++];
for(int i=0; i<n; i++)
{
arr[i] = temp[i];
}
}
int main()
{
int n = sizeof(arr)/sizeof(arr[0]);
cout<<"Before shuffling: ";
for(int i=0; i<n; i++)
{
cout<<arr[i]<<", ";
}
shuffle();
cout<<" After shuffling: ";
for(int i=0; i<n; i++)
{
cout<<arr[i]<<", ";
}
return 0;
}
-------------------
OUTPUT
(with sample output considering an integer array as array type was not provided to me, but logic doesnot differ)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.