Jump to content

Function help

Mr. Brovahkiin

I have to write a program that takes a users guess and matches it to a randomly generated selection.

Here is my code so far.

#include <iostream>#include <ctime>#include <time.h>#include <stdlib.h>using namespace std;void displayInstructions();void GenerateCards (int *);int main (){	const int CARDS = 24;	string deck[CARDS] = {	"red cricle",	 "red square",	 "red diamond",	 "red triangle",	 "blue circle",	 "blue square",	 "blue diamond",	 "blue triangle",	 "yellow circle",	 "yellow square",	 "yellow diamond",	 "yellow triangle",	 "orange circle",	 "orange square",	 "orange diamond",	 "orange triangle",	 "purple circle",	 "purple square",	 "purple diamond",	 "purple triangle",	 "green circle",	 "green square",	 "green diamond",	 "green triangle"};		displayInstructions();	GenerateCards (CARDS);		return 0;}void displayInstructions(){	cout <<	"The computer will generate a deck of cards.\n"		 << "There are 4 shapes: cricle, square, diamond, and trianlge.\n"		 << "There are 6 colors: red, blue, yellow, orange, purple, and green.\n"		 << "Pick a shape then pick a color.\n"		 << "Do this 5 times and see if your predictions match what the computer picked.\n";		 	 }void GenerateCards(int *){int i;	srand ( time(NULL) ); 		for( i = 0; i < 5; i++ )	(rand() % 24) << endl;}

I have to pass the function "void GenerateCards" the pointer to an array which will then pick 5 of cards in the array of strings called deck. I have the random function set but I don't know how to get the computer to actually choose the 5 cards and use it so I can then match it to a users input. Any help?

Link to comment
Share on other sites

Link to post
Share on other sites

What language is this (VB)? Its either very strange or badly typed.
e.g. your generate cards function wont work "GenerateCards(int *)" you cannot habe a * there, it needs to be a variable name.

Link to comment
Share on other sites

Link to post
Share on other sites

Sorry it's C++ and it's badly typed because I'm still a beginner. And I can't use a pointer or do I have to name it?

Link to comment
Share on other sites

Link to post
Share on other sites

What language is this (VB)? Its either very strange or badly typed.

e.g. your generate cards function wont work "GenerateCards(int *)" you cannot habe a * there, it needs to be a variable name.

This is C++ 

 

Though you are correct, you can't just say you have a pointer to an int, it still needs to take the variable name of said int.. (in this case its an int array, and arrays are always passed by reference 

 

You'd want to have GenerateCards(int deck[]);

Arch Linux on Samsung 840 EVO 120GB: Startup finished in 1.334s (kernel) + 224ms (userspace) = 1.559s | U mad windoze..?

Link to comment
Share on other sites

Link to post
Share on other sites

This is C++ 

 

Though you are correct, you can't just say you have a pointer to an int, it still needs to take the variable name of said int.. (in this case its an int array, and arrays are always passed by reference 

 

You'd want to have GenerateCards(int deck[]);

The thing is I have to use a pointer instead of an array (teachers rules not mine). So would the prototype look like GenerateCards (int *deck) or am I just doing it wrong?

Link to comment
Share on other sites

Link to post
Share on other sites

{const int CARDS = 24; // CARDS is an intGenerateCards (CARDS); // which you are passing to GenerateCards}void GenerateCards(int *) // GenerateCards however expects its argument to be a pointer!{}

See my comments in your code, I'm a bit rusty in C++ and pointers, but that's

the thing that stuck out to me at first glance. I hope I remember this correctly,

otherwise my apologies.

EDIT: Ninja'd :ph34r:

BUILD LOGS: HELIOS - Latest Update: 2015-SEP-06 ::: ZEUS - BOTW 2013-JUN-28 ::: APOLLO - Complete: 2014-MAY-10
OTHER STUFF: Cable Lacing Tutorial ::: What Is ZFS? ::: mincss Primer ::: LSI RAID Card Flashing Tutorial
FORUM INFO: Community Standards ::: The Moderating Team ::: 10TB+ Storage Showoff Topic

Link to comment
Share on other sites

Link to post
Share on other sites

See my comments in your code, I'm a bit rusty in C++ and pointers, but that's

the thing that stuck out to me at first glance. I hope I remember this correctly,

otherwise my apologies.

EDIT: Ninja'd :ph34r:

Yeah I figured that was wrong. Still learning this stuff lol

Link to comment
Share on other sites

Link to post
Share on other sites

Take a read here, you always are passing by reference (a pointer) for arrays as parameters http://www.cplusplus.com/doc/tutorial/arrays/

Arch Linux on Samsung 840 EVO 120GB: Startup finished in 1.334s (kernel) + 224ms (userspace) = 1.559s | U mad windoze..?

Link to comment
Share on other sites

Link to post
Share on other sites

The thing is I have to use a pointer instead of an array (teachers rules not mine). So would the prototype look like GenerateCards (int *deck) or am I just doing it wrong?

GenerateCards(string* )int maint() {/* code */GenerateCards(deck);}
Deck is a string array, not an int array.

This compiles for me without error in main, although GenerateCards it not yet

working for me.

EDIT: Disregard, forgot about teacher's rule :lol:

BUILD LOGS: HELIOS - Latest Update: 2015-SEP-06 ::: ZEUS - BOTW 2013-JUN-28 ::: APOLLO - Complete: 2014-MAY-10
OTHER STUFF: Cable Lacing Tutorial ::: What Is ZFS? ::: mincss Primer ::: LSI RAID Card Flashing Tutorial
FORUM INFO: Community Standards ::: The Moderating Team ::: 10TB+ Storage Showoff Topic

Link to comment
Share on other sites

Link to post
Share on other sites

I'm posting this up to try to clear any confusion that my poor descriptive skills have conveyed. Read: I do not want anyone to do this for me. Just help with the generate cards function for the time being

You now have a good foundation of C++ programming skills that you can use to develop a larger project. You will implement a program that simulates ESP:  Extra Sensory Perception (or, mind-reading)  Here's a program you can show off to your friends!  Good luck and have fun!The rules of ESP are:There is a deck of 24 cards that looks like this:Each card has a color and a shape.There are 4 shapes:  CIRCLES, SQUARES, DIAMONDS, and TRIANGLESThere are 6 colors:  RED, BLUE, YELLOW, ORANGE, PURPLE, GREENFor example:  one card is BLUE SQUAREThe computer will choose 5 cards from this deck.The player will try to guess as many of the cards as possible.The program will display the player’s “ESP Level” based on the number of correct guesses. (see below)You can represent each of the possible cards with a unique integer.Create an array for lookup and display purposes, i.e. to map each integer to a shape/color pair.At the beginning of the program, the computer will choose 5 cards from the deck.Then, in each round, the player guesses one card by entering a color and a shape.The program will display whether or not this card matches any of the computer’s 5 cards. If the player’s card guess matches one of the computer’s cards, the player gets a point.make sure there are no duplicate cards generated for the computermake sure there are no false positives, i.e. RED CIRCLE should not be a match if the computer chose RED DIAMOND and GREEN CIRCLE.Don’t let the player get duplicate points for guessing the same correct card several times!Remember that the cards do not have to be in order to win.One game continues for 5 rounds, unless the player wants to quit.  The program gives the player the opportunity to quit after each round.    At the end of 5 rounds or whenever the player quits, the program displays:the five cards the computer chose (color/shape of each card)the cards the player guessed (color/shape of each card)the player’s ESP Level (you must have these 4 levels, but you can make up your own messages)	   0 points: “Level 1: No ESP at all!”	1-2 points:  “Level 2: Some ESP, keep working on it!”	3-4 points:  “Level 3: Lots of ESP, try Powerball!”	   5 points:  “Level 4: ESP expert! Host a TV show!”	The program must match this specification. Your program must meet the code header and documentation rules, including specifying one full example of input and output for one complete run of the program (0 credit for the project if this is missing)Please read this specification carefully and thoroughly.  Please ask questions if you are not sure what it means.Extra credit: (20 points)Create a Poster of your project and present it at the MCC STEM Poster Session on 4/30/13 in Lowell, 12:30-2:00.  (It doesn’t have to be perfect to be presented.)  Your project should be running fairly well, and you must run it on a laptop at the Poster Session. Free poster boards may be available.You must tell me by 4/25/13 at the latest if you are doing this.  Pointer Notation requiredUse only pointer notation to access array elements throughout your code – i.e. do not use [ ] brackets anywhere except to declare the arrays.  If this program uses array notation with brackets, there will be a 20 point deduction.You may use global constants for the size of the arrays. No global variables!  No global arrays!Declare, implement and call the following functions exactly as specified below.  int main( ) :   (25 points)Declare an array to hold the computer’s 5 random card selectionsDeclare another array to hold the player’s 5 card guessesDeclare an array to be used to map the card descriptions (shape/color) to unique integer representationsCall each of the functions specified below to do the following stepsDisplay instructions (call DisplayInstructions() )Generate the computer’s selections randomly (call GenerateCards() )In a loop:get a card guess from the player (call GetGuess()), and store it into the player array,check to see if the guessed card matches one of the computer’s cards (call CheckMatch () )display a message stating whether or not the guessed card matches keep score of the player’s matches.Display the two sets of cards side by side. (call DisplayCards () )Display the appropriate ESP Level message (call DisplayESP () )void DisplayInstructions ( );  (5 points)DisplayInstructions will display a description of the game, how to play, and how to win.void GenerateCards (int *);  (15 points)GenerateCards is passed an array, which it fills with integers representing randomly generated cards.Make sure there are no duplicate cards.int GetGuess ( );  (15 points)GetGuess prompts the player to guess a card.   The player enters a shape and a color.  This function converts that to an integer that represents that card and returns that integer.bool  CheckMatch (int , int *); (15 points)CheckMatch is passed an integer representing the player’s guessed card, and the computer’s choice array.  It returns true if it matches, false if it doesn’t.void DisplayCards (int *, int *); (15 points)DisplayCards is passed the computer’s and the player’s card arrays. It displays the two sets of cards side by side, using color/shape.void DisplayESP (int); (10 points)DisplayESP is passed the player’s score.  It displays the appropriate ESP Level message.Present your code to the class. (20 points)You will introduce the program with a summary, including what areas presented challenges and how they were resolved.  We will go through a "code review" where I and the members of the class will ask questions about the code and give feedback and constructive suggestions about your code. You should be able to explain every line of code that is a part of your program and how your program works.  I strongly suggest that you practice presenting your code before you do it in class.  If you miss class when it is your turn to present, you will have to present to me in order to get credit for your project.
Link to comment
Share on other sites

Link to post
Share on other sites

Ahh okay i see the issue

 

Have the function prototype as 

GenerateCards(int * generatedCards);

 

And declare the array generateCards[24];

 

Then when you call it have

GenerateCards(&generatedCards);

 

That should work as requested... though its the oddest thing i've seen as arrays are passed by reference like that anyway..

 

Edit: Im doubting this now.. let me test this is the oddest thing I've seen

Edited by lutzee

Arch Linux on Samsung 840 EVO 120GB: Startup finished in 1.334s (kernel) + 224ms (userspace) = 1.559s | U mad windoze..?

Link to comment
Share on other sites

Link to post
Share on other sites

 

Ahh okay i see the issue

 

Have the function prototype as 

GenerateCards(int * generatedCards);

 

And declare the array generateCards[24];

 

Then when you call it have

GenerateCards(&generatedCards);

 

That should work as requested... though its the oddest thing i've seen as arrays are passed by reference like that anyway..

I'm well aware haha. She's stressing us using pointers in the ENTIRE thing instead of using arrays in some places and pointers in others.

 

Now I have a question though. When I declare the array generateCards[24], won't that just setup an array with 24 numbers only and not the strings I need to match?

Link to comment
Share on other sites

Link to post
Share on other sites

Well this is what I think. So in the for loop you should grab 5 cards by their index number using the random number, then return them to the user.

Do you want to know what grinds my gears?
The old forum.

Link to comment
Share on other sites

Link to post
Share on other sites

void GenerateCards (int *); (15 points)
GenerateCards is passed an array, which it fills with integers representing randomly generated cards.
Make sure there are no duplicate cards.

 

You want an array of ints too

 

also forget the & in the function call... gets passed by reference anyway..

 

Also arrays are always passed as the memory location so save memory when the arrays are massive.. 

They are literally a pointer anyway.. 

Personally you should be sticking to what the C++ reference says you should do as its good practice and also easier to understand

Arch Linux on Samsung 840 EVO 120GB: Startup finished in 1.334s (kernel) + 224ms (userspace) = 1.559s | U mad windoze..?

Link to comment
Share on other sites

Link to post
Share on other sites

void GenerateCards (int *);  (15 points)GenerateCards is passed an array, which it fills with integers representing randomly generated cards.Make sure there are no duplicate cards.

Question: Why are you trying to pass the entire deck to GenerateCards? (at least that's

the impression I'm getting). If I understand the above sentence correctly, you don't need

to pass the entire deck to GenerateCards. Personally, this sounds to me like I would

have to pass an empty array to GenerateCards and GenerateCards would then write 5 random

numbers into that array.

After that I would compare those numbers against the user's selections.

EDIT: Of course I didn't mean "pass the array" but its corresponding pointer, since

that's what the teacher seems to want. In any case, I'm sure you know by now that an array's

name variable is merely a constant pointer to its first element. Hence, when you do

cout << yourarray[0];cout << *yourarray;
you will get the same result, namely the array's first element is displayed. And just to be

sure I've actually tried this, one never knows what kind of errors rustiness can breed :lol:

BUILD LOGS: HELIOS - Latest Update: 2015-SEP-06 ::: ZEUS - BOTW 2013-JUN-28 ::: APOLLO - Complete: 2014-MAY-10
OTHER STUFF: Cable Lacing Tutorial ::: What Is ZFS? ::: mincss Primer ::: LSI RAID Card Flashing Tutorial
FORUM INFO: Community Standards ::: The Moderating Team ::: 10TB+ Storage Showoff Topic

Link to comment
Share on other sites

Link to post
Share on other sites

void GenerateCards (int *); (15 points)

GenerateCards is passed an array, which it fills with integers representing randomly generated cards.

Make sure there are no duplicate cards.

 

You want an array of ints too

 

also forget the & in the function call... gets passed by reference anyway..

 

Also arrays are always passed as the memory location so save memory when the arrays are massive.. 

They are literally a pointer anyway.. 

Personally you should be sticking to what the C++ reference says you should do as its good practice and also easier to understand

Fair enough. If she has a problem I'll tell her to screw or something cause :P I'm just gonna pass it as an array

 

I'm sadly still not understanding how to actually get it to choose the 5 string choices. I know I have to make an array and have it filled with the 5 random choices but I don't know how to apply it. I get confused easily with this shit :(

Link to comment
Share on other sites

Link to post
Share on other sites

Fair enough. If she has a problem I'll tell her to screw or something cause :P I'm just gonna pass it as an array

 

I'm sadly still not understanding how to actually get it to choose the 5 string choices. I know I have to make an array and have it filled with the 5 random choices but I don't know how to apply it. I get confused easily with this shit :(

1. In your code you have to have a for loop that runs 5 times.

2. Generate random number

3. Next you can return one string with the random number generated

Do you want to know what grinds my gears?
The old forum.

Link to comment
Share on other sites

Link to post
Share on other sites

I'm sadly still not understanding how to actually get it to choose the 5 string choices. I know I have to make an array and have it filled with the 5 random choices but I don't know how to apply it. I get confused easily with this shit :(

What do you mean you don't understand how to apply it? As in, you don't know what to

do with those 5 choices once you have them in an array?

In the meantime, to clear up any misunderstandings (even if they're on my part),

the following code will manipulate an array in a separate function without using

any brackets. It's still no random generator of course, but it should give an

idea about how to pass and manipulate arrays between functions:

 

#include <iostream>#include <ctime>#include <time.h>#include <stdlib.h>using namespace std;void displayInstructions();void GenerateCards (int*);int main (){    int generatedCards[5];    GenerateCards(generatedCards);    cout << *generatedCards;    return 0;}void GenerateCards(int* generatedCards){    *generatedCards = 29;}
This compiles and outputs 29 on my machine. I'm still not entirely sure

if this is what your teacher has in mind, but it does not use brackets except

for the array creation, as she specified.

BUILD LOGS: HELIOS - Latest Update: 2015-SEP-06 ::: ZEUS - BOTW 2013-JUN-28 ::: APOLLO - Complete: 2014-MAY-10
OTHER STUFF: Cable Lacing Tutorial ::: What Is ZFS? ::: mincss Primer ::: LSI RAID Card Flashing Tutorial
FORUM INFO: Community Standards ::: The Moderating Team ::: 10TB+ Storage Showoff Topic

Link to comment
Share on other sites

Link to post
Share on other sites

Well you are passing an array

 

say: int generatedCards[5]; //5 size of 5 because 5 choices

 

then in the function you would have

srand(time(NULL)):for(int i = 0; i > 5; ++i){    int temp;        temp = rand()%24;    //check for duplicates, you should use a function for this, then you can deal with adding to the loop    deck[i] = temp;}

That should be enough, but you need to make sure you get the checking stuff correct

Arch Linux on Samsung 840 EVO 120GB: Startup finished in 1.334s (kernel) + 224ms (userspace) = 1.559s | U mad windoze..?

Link to comment
Share on other sites

Link to post
Share on other sites

I think I'm just an idiot because I'm not understanding it. I'm just gonna go get tutoring at school tomorrow. Thanks for trying guys I really do appreciate it.

Link to comment
Share on other sites

Link to post
Share on other sites

This is C++ 

 

Though you are correct, you can't just say you have a pointer to an int, it still needs to take the variable name of said int.. (in this case its an int array, and arrays are always passed by reference 

 

You'd want to have GenerateCards(int deck[]);

Ah i see, i have not used C++. My skills are of no use here. xD

Link to comment
Share on other sites

Link to post
Share on other sites

I think I'm just an idiot because I'm not understanding it. I'm just gonna go get tutoring at school tomorrow. Thanks for trying guys I really do appreciate it.

Aaargh! Went off to do some work and missed that post until now :lol: Not that that's

your fault of course, I should have checked back more often.

Anyway, I've come up with a small prog that selects five random numbers between 1

and 24 and checks for doubles. It also works without any square brackets, as per

your teacher's demand.

Disclaimer: It's been two years since I've last done C++. This code is rather ugly

IMO (and I'm not saying that in the hopes of fishing for compliments, it does what

it's supposed to as far as I can tell, but it's not really very good code; quite

inelegant I think). So don't think this will knock anyone's socks off, but it might

provide a starting point for further work or insight.

I have run this program in a loop 400 times on my machine and checked the result (don't

worry, it's not as much work as it sounds if you do it cleverly ;)), so to the best of

my abilities this should do what I claim it to do.

The basic trick with avoiding square brackets is pointer arithmetic, if you need

some further explanations just ask.

 

EDIT: Improved version in another post below, but I'll leave this here for

posterity.

#include <iostream>#include <ctime>#include <time.h>#include <stdlib.h>using namespace std;void displayInstructions();void GenerateCards (int*);int main (){    int generatedCards[5];    GenerateCards(generatedCards);    // Just checking the results by outputting them.    for (int k=0;k<5;k++) {        cout << generatedCards[k];        cout << "\n";    }    return 0;}void GenerateCards(int* generatedCards){    int i;    int selectedInt;    int alreadyPresent = 0;    int successfulSelections = 0;    srand ( time(NULL) );     while (successfulSelections < 5) {        selectedInt = (rand() % 24) + 1;        // This statement should not be necessary with an improved for loop        // from below, but I haven't yet managed to eliminate it. It fills        // the very first array element which the loop below does not pick        // up.        if (successfulSelections==0) {            *(generatedCards)=selectedInt;        }                // This should be improved so that the above if-statement is not        // necessary, however my rusty C++ skills have not yet enabled        // me to do that (I'm running into infinite loops...).        for (int l=0;l<successfulSelections;l++) {            if (*(generatedCards+l)==selectedInt) {                alreadyPresent=1;                break;            } else {                alreadyPresent=0;                // This is the pointer arithmetic I mentioned.                *(generatedCards+successfulSelections)=selectedInt;            }        }        if (alreadyPresent==0) {            successfulSelections++;        }    }}

BUILD LOGS: HELIOS - Latest Update: 2015-SEP-06 ::: ZEUS - BOTW 2013-JUN-28 ::: APOLLO - Complete: 2014-MAY-10
OTHER STUFF: Cable Lacing Tutorial ::: What Is ZFS? ::: mincss Primer ::: LSI RAID Card Flashing Tutorial
FORUM INFO: Community Standards ::: The Moderating Team ::: 10TB+ Storage Showoff Topic

Link to comment
Share on other sites

Link to post
Share on other sites

alpenwasser pretty much has it done there, now branch from that and hope that your teacher doesn't care about plagiarism, at university its a big issue. 

And Its bad when it comes to code as efficient code using good practices can be picked up as plagiarised even if its good practice, its a case of then explaining correctly why you did it.

Arch Linux on Samsung 840 EVO 120GB: Startup finished in 1.334s (kernel) + 224ms (userspace) = 1.559s | U mad windoze..?

Link to comment
Share on other sites

Link to post
Share on other sites

alpenwasser pretty much has it done there, now branch from that and hope that your teacher doesn't care about plagiarism, at university its a big issue.

True. Although where I'm going to college this can depend on the professor. Many don't

care too much if you copy something from the web for an exercise. Papers of course are

an entirely different story. ;)

 

But since this seems to be graded I would indeed be careful about this.

 

And Its bad when it comes to code as efficient code using good practices can be picked up as plagiarised even if its good practice, its a case of then explaining correctly why you did it.

Yes, in the end the only thing that will get you through exams is practice and understanding.

In any case, that ugly loop just bugged the hell out of me, so here's an improved version.

I also tested it, and it still seems to work. I apologize about mixing variable naming styles,

but I'm just so much more used to underscores than camelcase.

The main change is that I created an additional function whose sole purpose is to check

whether an element is in the first n members of an array. To clarify a bit: You can pass

an array (well, the pointer to its first member) with 10 slots to it. Not all slots need

yet to be filled. You also pass the element which you would like to test and the number

of elements to be tested (so, for example, 7). The number of elements to test should be

lower or equal to the number of filled slots, otherwise you will test an empty slot and

results might be unpredictable afaik. So, long ramble short:

is_in_array(4,7,array_with_10_members); will test if "4" is in one of the first 7 elements

out of an array that could contain up to 10 members.

If anyone spots an error, don't spare my pride and feel free to point it out, no point to

this if we're propagating errors :lol:

EDIT: I just tried this out, and it does not seem to make a difference whether you

test a slot that has not yet been populated properly. Not entirely sure about this, but

so far I have not been able to produce an error with always testing the entire array, even

including the slots that are not yet filled with selected numbers.

 

#include <iostream>#include <ctime>#include <time.h>#include <stdlib.h>using namespace std;void displayInstructions();void GenerateCards (int*);bool is_in_array(int,int,int*);int main (){    int generatedCards[5];    GenerateCards(generatedCards);    // Just checking the results by outputting them.    for (int k=0;k<5;k++) {        cout << generatedCards[k];        cout << " ";    }    cout << "\n";    return 0;}void GenerateCards(int* generatedCards){    int proposed_int;    int successful_selections = 0;    srand ( time(NULL) );     while (successful_selections < 5) {        proposed_int = (rand() % 24) + 1;        if (is_in_array(proposed_int,successful_selections,generatedCards)==false) {/*      Just out of curiosity, I tried both versions, they seem both to work ok.        This version always tests the entire array:        if (is_in_array(proposed_int,5,generatedCards)==false) {*/            *(generatedCards+successful_selections)=proposed_int;            successful_selections++;        }    }}bool is_in_array(int to_test,int elements,int* array) {    // to_test: element to test array for    // elements: the number of elements in an array that are to be    // tested. Does not need to be as high as the array element    // count.    for (int i=0;i<elements;i++) {        if (*(array+i)==to_test) {            return true;        }    }    return false;}

BUILD LOGS: HELIOS - Latest Update: 2015-SEP-06 ::: ZEUS - BOTW 2013-JUN-28 ::: APOLLO - Complete: 2014-MAY-10
OTHER STUFF: Cable Lacing Tutorial ::: What Is ZFS? ::: mincss Primer ::: LSI RAID Card Flashing Tutorial
FORUM INFO: Community Standards ::: The Moderating Team ::: 10TB+ Storage Showoff Topic

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×