473,581 Members | 2,666 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C++ Write shuffle function to shuffle an array - exercise

542 Contributor
I`m trying to write a shuffle function to shuffle a sorted array with an even number of elements but it won`t print past the first 2 elements as shown below.
When i print the temp[] array it only prints the first 2 elements also. So i presume the loop is is stopping after 2 iterations.
Can anyone see my error?.

Expand|Select|Wrap|Line Numbers
  1. #include<iostream>
  2. using namespace std;
  3. void print(int a[],int n);
  4. void shuffle(int a []);
  5. int main()
  6. {
  7. int a[8]={22,33,44,55,66,77,88,99};    
  8. cout<<"\nArray a[] is: ";
  9. print(a,8);    
  10. shuffle( a);
  11. cout<<"\nArray a[] is: ";
  12. print(a,8);
  13. cout<<"after shuffle";
  14. cout<<"\n\n\n";
  15. system("pause");
  16. return 0;   
  17. void shuffle(int a[])
  18. { int SIZE=8;
  19.   int temp[8]={0};
  20.   const int half=SIZE/2;
  21.   for(int i=0;i< SIZE;i++)// i have tried using 'half' ILO 'SIZE' also deleting i++
  22.       {   temp[2*i]=a[i];// and revising this line to temp[2*i++] to no avail
  23.            temp[2*i+1]=a[half+i];
  24.  
  25.           for(i=0;i<SIZE;i++)
  26.           a[i]=temp[i];
  27.  
  28.       }    
  29. }
  30. void print(int a[],int n)
  31. {
  32.      for(int i=0;i<n;i++)
  33.      cout<<a[i]<<" ";
  34. }
/*This is the output i get.
Array a[] is: 22 33 44 55 66 77 88 99
Array a[] is: 22 66 0 0 0 0 0 0 after shuffle
it should be
Array a[] is: 22 66 33 77 44 88 55 99 after shuffle*/
Feb 27 '08 #1
11 12964
sicarie
4,677 Recognized Expert Moderator Specialist
Okay, I'd go back to your algorithm here, I'm not entirely sure on what basis you are "shuffling" .

What is the goal of a shuffle? Are you trying to get those values randomly assorted, or sorted in a specific fashion (ie, after a specific algorithm)? Or did I just totally miss your question?
Feb 27 '08 #2
whodgson
542 Contributor
Its meant to interleave the lower value elements between the four higher value ones as shown below "it should be".
Feb 27 '08 #3
sicarie
4,677 Recognized Expert Moderator Specialist
Okay, so it looks like you had in mind a mathematical representation of the shift? I'm seeing that the first one stays in its place, the second moves one places up, the third moves two places up, and the fourth moves three places up...
Feb 27 '08 #4
whodgson
542 Contributor
Sorry I don`t know anything about `shift'
I didn`t want to move anything.i wanted to copy the first element from a to temp position 0 (temp is initialized with 0`s) to replace the zero then the fifth element of a to temp position 1, then the third element from a to temp position 2 and so on...... so that the eighth and last element of a is copies to position 7 in temp.
Then copy the temp array to a[].
Also i would like to ask weaknessforcats a question about another matter but i don`t how to send him a private message. Do you know how to do this?
Thanks for yor interest.
Feb 27 '08 #5
sicarie
4,677 Recognized Expert Moderator Specialist
Well, I think you will want to be careful about PM'ing questions to Moderators.
Do NOT PM questions to individual Experts, Moderators or Administrators

This is not fair on them and we instruct our experts to ignore any such PMs completely, there are also some very good reasons why it is not a good idea:

* You have no guarantee that the expert you have PM'd knows anything about the subject you are asking about.
* You have no guarantee that the expert in question hasn't just gone on holiday for 4 weeks to Hawaii resulting in a delay to the answer to your question.
* If you post the question in the forums then everyone gets to see it. This means that there is a far higher chance that someone who already knows the answer will see the question than if you just ask 1 person.
* It's good to spread questions and knowledge. Remember if you have a question then it is likely that someone else in the world has a very similar question. By asking your question in the open forum and getting a reply there the information is available for everyone to read and learn from.
However, as you seem to not desire my assistance, I will leave you with: your issue in your for loop is that you are not correctly calculating the space you want to move the array into. You are currently calculating the index * 2 or index * 2 + 1.

Oh, and as you know this is going to run 4 times, why not hardcode 4 in there? At least until you get it working, then play around with setting that in the beginning or through another variable. Then you'll be sure it runs 4 times.
Feb 27 '08 #6
whodgson
542 Contributor
I overlooked the requirement on personal messages and will in future cease and desist. Am not sure how u concluded that I didn`t want your help and emphasise that I do. Will play round with your suggestion on hard coding but can`t see how it can be anything less than 8. Will let you know.
Feb 27 '08 #7
sicarie
4,677 Recognized Expert Moderator Specialist
You want to move 4 elements. You can move all 8 if you want, but the first won't move, and the last won't move, so it's rather pointless to try to move them. (I did get it confused with vectors, you will probably want to iterate 8 times)

What I was attempting to say above was that there is a mathematical relation to each array index, and how much you want it to move in the array. As soon as you can figure out that mathematical relationship, you can code your for loop. The key here is the modulus operator, % . You said you wanted the first half of the elements to become every other element. How do you figure out which place it is in? Obviously, you look at the index, but what about the index tells you that you want to put one of the first four elements in there?

As we are dealing with arrays, the first element is actually at number 0, and then you will want your second element to be at number 2. Your third at number 4, and so on. There is a pattern there. There's also a pattern where you want your last four - you want the first of the last four in array[1] spot, the second in the array[3] spot, and so on ending at array[7].

Are you familiar with the modulus operator and what it does?

And you show that you do not want a certain person's help when you ask them how to get another person to help on an issue the first person is already attempting to help you with.
Feb 27 '08 #8
whodgson
542 Contributor
I said that I wanted to get in touch with the person "on another matter". That means nothing to do with the matter (read thread) which you were helping me with. I have also taken your warning in relation to messaging guide lines on board and scrubbed my question your QED
Feb 27 '08 #9
sicarie
4,677 Recognized Expert Moderator Specialist
I said that I wanted to get in touch with the person "on another matter". That means nothing to do with the matter (read thread) which you were helping me with. I have also taken your warning in relation to messaging guide lines on board and scrubbed my question your QED
Okay. So you are done with this thread?

It's really just about 10 lines inside your main. Check if the index is a multiple of two, if so, assign it to the value of the proper index of the original array. Increment the second index properly.
Feb 27 '08 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

15
2335
by: Bob | last post by:
I've tried everything; and I can't seem to get past this VERY (seemingly) simply problem. I want to work with an array variable within a function(s). I can't get it to work; if I: 1) global $arr=array(); (syntax err) 2) global $arr; in "main", the var isn't global 3) global $arr; in function, the array is cleared each time
23
12925
by: JC | last post by:
I am very new to programming and learning on my own. Why do I keep getting duplicate values using this code? I want to shuffle a deck of 52 cards. The logic seems right to me. Randomize For C = 0 To 1000 C1 = Cards(Int(Rnd * 52)) ' returns a number from 0 to 51
24
7274
by: Joerg Schuster | last post by:
Hello, I am looking for a method to "shuffle" the lines of a large file. I have a corpus of sorted and "uniqed" English sentences that has been produced with (1): (1) sort corpus | uniq > corpus.uniq corpus.uniq is 80G large. The fact that every sentence appears only
6
6181
by: CaseyB | last post by:
If I wanted to create a game like Solitaire that would first randomly shuffle a deck of cards, I figured out that all I had to use is the Random() class or rnd and make sure I use the Randomize function so as not to get the same card twice. BUT I noticed that some Solitaire games allow you to select one of the 4,294,967,296 possibilities in a...
13
2218
by: arnuld | last post by:
this does not work, i know there is some problem in the "for loop" of "print_arr" function. i am not able to correct the weired results i am getting. i have no compile time error, it is only semantic-bug that is causing the trouble: EXPECTED: january, february, march....december GOT: january, january, january.........january ...
9
5331
by: Tuxedo | last post by:
I'd like to reorganize the third, fourth, fifth and sixth, as well as any elements thereafter in an array in random order: var a = new Array('first','second','third','fourth','fifth','sixth','etc') In other words, the first, second and third element should remain in position 0, 1 and 2, while the fourth, fifth and sixth, etc. should appear...
1
4215
by: vishum1291 | last post by:
i want to shuffle the elements of an array without using random and shuffle functions.any one please help me. ex: input:a ouput:a
2
3336
by: rubyhuang | last post by:
the problem is A standard pack of cards can be represented as an array of 52 integers with each number representing a standard card. Thus: 0 1 2 3 4 5 6 7 8 9 10 11 12.....39 40 41 42 43 44 45 46 47 48 49 50 51 We can shuffle this pack of cards by randomly generating two indexes and swapping those two cards. For example if we randomly generate...
16
2027
by: wokeup2sleep | last post by:
im a beginner at comp science, and my prof is using python, which is totally new tom me i had a few questions with the program im writing, im having a few problems. brief summary i have to do a project where there are nine boxes filled with number 1-8, and 1 space is empty, the game needs to be scrambled, also all the moves need to be saved....
0
8137
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8299
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7890
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8163
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6545
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5355
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3799
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
2297
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1397
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.