Passing values between methods c++ - c++

Game.h
#include "RandomNumberGenerator.h"
class Game
{
private:
int myNumbers[6];
int userRandomNumbers[6];
int lotteryRandomNumbers[6];
int prizeMoney;
public:
void generateRandomNumbersLottery();
void generateRandomNumbersUser();
void userInputNumbers();
void compareNumbers1();
void compareNumbers2();
void results();
};
Game.cpp
#include "Game.h"
void Game::compareNumbers1()
{
int k = 0;
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j)
{
if (myNumbers[i] == lotteryRandomNumbers[j])
{
k++;
}
}
}
if (k > 0)
{
std::cout << "Congratulations you matched: " << k << " number(s)";
}
if (k == 0)
{
std::cout << "Unfortunatly you matched: " << k << " numbers";
}
}
void Game::compareNumbers2()
{
int k = 0;
for (int i = 0; i < 6; ++i)
{
for (int j = 0; j < 6; ++j)
{
if (userRandomNumbers[i] == lotteryRandomNumbers[j])
{
k++;
}
}
}
if (k > 0)
{
std::cout << "Congratulations you matched: " << k << " number(s)";
}
if (k == 0)
{
std::cout << "Unfortunatly you matched: " << k << " numbers";
}
}
void Game::results()
{
if (k == 0)
{
prizeMoney = 0;
std::cout << "Unfortunatly you need to match atleast 2 numbers to win a prize.";
}
if (k == 1)
{
prizeMoney = 0;
std::cout << "Unfortunatly you need to match atleast 2 numbers to win a prize.";
}
if (k == 2)
{
prizeMoney = 3;
std::cout << "Congratulations, you have won: 3 pounds.";
}
if (k == 3)
{
prizeMoney = 30;
std::cout << "Congratulations, you have won: 30 pounds.";
}
if (k == 4)
{
prizeMoney = 3000;
std::cout << "Congratulations, you have won: 3,000 pounds.";
}
if (k == 5)
{
prizeMoney = 30000;
std::cout << "Congratulations, you have won: 30,000 pounds.";
}
if (k == 6)
{
prizeMoney = 3000000;
std::cout << "Congratulations, you have won: 3,000,000 pounds.";
}
}
Main.cpp
#include "Game.h"
std::cout << "Do you wish to enter your own numbers or generate them randomly?: ('own', 'random') ";
std::getline (std::cin, choice);
if (choice == "random")
{
play.generateRandomNumbersUser();
std::cout << std::endl << std::endl;
play.generateRandomNumbersLottery();
std::cout << std::endl << std::endl;
play.compareNumbers2();
}
if (choice == "own")
{
play.userInputNumbers();
std::cout << std::endl << std::endl;
play.generateRandomNumbersLottery();
std::cout << std::endl << std::endl;
play.compareNumbers1();
}
play.results();
system("pause");
return 0;
}
I'm aware this code has a lot of poor syntax etc in it at the moment but it currently just rough working code (i.e. no validation yet when choosing random or own numbers)
What I'm asking here is how do I get whatever value is in int k (from compareNumbers1() and compareNumbers2()) into results().
As far as my thinking goes it needs to be passed using a pointer somehow, or changing compareNumbers from void to int and return k. However after playing around with both these ways I still cannot get it to work.

One option is to use parameters. Pass the value as a parameter into results:
void results(int k);
Which leaves the question of how to get it out of compareNumbers1(). You could return it from that function:
int compareNumbers1();
If you need to put it into compareNumbers2(), let that method modify it, and then allow the caller to see the modifications you'd pass a reference to the variable:
void compareNumbers2(int& k);
And you'd clearly need to declare the variable somewhere. Since it is returned from compareNumbers1() you would declare it and assign it like this:
int k = compareNumbers1();
Put it all together at the call site and you have:
int k = compareNumbers1();
compareNumbers2(k);
results(k);
The obvious alternative to parameters is to make the variable be a private member variable of the class.

Related

Acessing elements of an array from another class

int main() {
int x;
const int Maxword = 5;
char Guess[Maxword] {};
std::string words[Maxword] = {
"Hello",
"World",
"Shift",
"Green",
"Seven"
};
srand(time(NULL));
int iSecret = rand() % Maxword;
std::string Word(words[iSecret]);
for (int i = 0; i < 5; i++) {
std::cout << Word[i] << std::endl;
}
for (int i = 0; i < 5; i++) {
std::cout << ("Please enter the letters you would like to guess") << std::endl;
std::cin >> Guess[i];
std::cout << Guess[i] << std::endl;
}
for (int i = 0; i < 5; i++) {
if (Guess[i] == Word[i]) {
std::cout << Guess[i] << "\t" << "Is in the right place" << std::endl;
} else if (Guess[i] != Word[i]) {
std::cout << Guess[i] << "\t" << "Isnt in the right place" << std::endl;
} else {
}
}
void InTheWord() {
for (int i = 0; i < 5; i++) {
}
}
I want to use elements of arrays Guess[] and Word[] how would I access them from the other function. So like I want to check if a letter from Guess[] is in the array of Word[] so id have to pass down each letter and check guess against every letter in word then return to the other function to then print out whether the letter that the person guessed was in the word that the program generated.

Hi, i have a problem with this code. ODD and EVEN numbers

I have a problem with this piece of code, I'm trying to print the EVEN and ODD numbers, but there is a problem when it comes to show them, the vectors don't save the numbers as I'm expecting.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n]; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[i] = vect[i]; // I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[i] == vect[i];
}
}
for(int i = 1; i <= n; ++i) {
cout << even[i] << " " << endl; /// PRINTING THE ODD AND EVEN numbers.
cout << odd[i] << " " << endl;
}
return 0;x
}
I have fixed the problem, thanks all for help.
Now it works perfectly.
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int vect[n], even[n], odd[n], z = 0, x = 0; // CREATING VECTORS LIMIT AFTER "n"
for(int i = 1; i <= n; ++i) { // ENTERING The ELEMENS IN VECTOR
cin >> vect[i];
}
for(int i = 1; i <= n; ++i) {
if(vect[i] % 2 != 0) {
odd[1+z] = vect[i];
z++;
// I think that here's the problem, the vectors don't save the right numbers.
} /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
else if (vect[i] % 2 == 0) {
even[1+x] = vect[i];
x++;
}
}
for(int i = 1; i <= x; i++) {
cout << even[i] << " ";
}
cout << endl;
for(int i = 1; i <= z; i++) {
cout << odd[i] << " ";
}
return 0;
}
Considering the hints of the comments, your program shall be changed into this:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, number;
cin >> n;
vector<int> vect, even, odd; // CREATING DYNAMIC VECTORS
for(int i = 0; i < n; ++i) { // ENTERING THE ELEMENTS IN VECTOR
cin >> number;
vect.push_back(number);
}
for(int i = 0; i < n; ++i) {
if(vect[i] % 2 != 0) { /// VERIFYING IF THE NUMBER IS ODD OR EVEN.
odd.push_back(vect[i]);
}
else {
even.push_back(vect[i]);
}
}
for (int i = 0; i < n; ++i)
cout << vect[i] << " ";
cout << endl;
/// PRINTING THE ODD AND EVEN NUMBERS.
for (auto& val : odd)
cout << val << " ";
cout << endl;
for (auto& val : even)
cout << val << " ";
cout << endl;
return 0;
}
It uses the vector container of STL for your arrays, start the indexing at 0 and prints out the resulting arrays separately, as the number of odd and of even entries might be different.
Hope it helps?
With standard, you might use std::partition (or stable version) to solve your problem:
void print_even_odd(std::vector<int> v)
{
auto limit = std::stable_partition(v.begin(), v.end(), [](int n){ return n % 2 == 0; });
std::cout << "Evens:";
// Pre-C++20 span:
// for (auto it = v.begin(); it != limit; ++it) { int n = *it;
for (int n : std::span(v.begin(), limit)) {
std::cout << " " << n;
}
std::cout << std::endl;
std::cout << "Odds:";
for (int n : std::span(limit, v.end())) {
std::cout << " " << n;
}
std::cout << std::endl;
}
Demo

Find all triplets in an array that sum to a given value.There are duplicates in the array

This is the code I wrote-
void FindTriplet(int arr[], int size, int x) {
sort(arr,arr+size);
for(int i=0;i<size-2;i++)
{
int l=i+1;
int r=size-1;
while(l<r)
{
int sum=arr[i]+arr[l]+arr[r];
if(sum==x)
{
cout << arr[i] << " " << arr[l] << " " << arr[r] << endl;
l++;
r--;
}
else if(sum<x)
{
l++;
}
else
{
r--;
}
}
}
}
The complexity of O(n^3) is not acceptable.
But this code is failing on cases like-
1 1 1 1 where required sum is 3.
Ans. 1 1 1 repeated 4 times
You have do handle duplicates when you found correct sum:
if (sum==x)
{
// skip and count duplicates
const auto oldL = l;
do {
++l;
} while (l <= r && arr[oldL] == arr[l]);
const auto oldR = r;
do {
--r;
} while (l <= r && arr[oldR] == arr[r]);
// resulting count
const auto count = (arr[oldL] == arr[oldR]
? (l - oldL) * (l - oldL - 1) / 2
: ((l - oldL) * (oldR - r)));
for (int j = 0; j != count; ++j) {
std::cout << arr[i] << " " << arr[oldL] << " " << arr[oldR] << std::endl;
}
}
Demo
You'd better make use of STL classes. I wrote some code for you.
#include <iostream>
#include <vector>
#include <map>
using namespace std;
void findTripletSums(const std::vector<int>& arr, int tripleSum)
{
std::map<int,int> arrMap; // counts the number of times the number is repeated
for(auto a : arr)
{
arrMap[a]++;
}
for(auto itrI = arrMap.begin(); itrI != arrMap.end(); ++itrI)
{
int arrI = itrI->first;
if(arrI*3 == tripleSum && itrI->second >= 3)
{
cout << arrI << " " << arrI << " " << arrI << "; ";
return;
}
auto itrJ = itrI;
for(++itrJ; itrJ != arrMap.end(); ++itrJ)
{
int arrJ = itrJ->first;
int complement = tripleSum-arrI-arrJ;
if(complement < itrJ->first)
{
break;
}
if(complement == arrJ)
{
if(itrJ->second >= 2)
{
cout << arrI << " " << arrJ << " " << arrJ << "; ";
}
break;
}
if(arrMap.find(complement) != arrMap.end())
{
cout << arrI << " " << arrJ << " " << complement << "; ";
}
}
}
}
int main()
{
findTripletSums({0,1,3,3,2,4,6}, 7);
cout << "\n";
findTripletSums({1,2,3,4,5,6}, 7);
cout << "\n";
findTripletSums({0,1,1,1,1,2}, 3);
return 0;
}
It prints:
0 1 6; 0 3 4; 1 2 4; 1 3 3;
1 2 4;
0 1 2; 1 1 1;

Printing a hollow right-triangle

I'm having issues with this c++ code. It is supposed to print a hollow right isosceles triangle, but instead just prints asterisks over and over, so the for loops seem to be stuck.
#include "pch.h"
#include <string>
#include <iostream>
int main() {
int row;
std::string s = " ";
std::string a = " *";
int rows = 10;
for (int i = 0; i < rows; i++) {
if (i = 0) {
std::cout << a << std::endl;
}
while (i > 2 && i < rows) {
std::cout << a;
for (int pos = 0; pos < i; pos++) {
std::cout << s;
}
std::cout << a << std::endl;
}
std::cout << a << a << a << a << a << a << a << a << a << std::endl;
}
}
your while loop condition will never become false, AND you need to use comparison (==) instead of assignment in this line:
if (i = 0) {
Supposing that what you want to print is something of the following form:
Eg. for rows = 5
*
**
* *
* *
*****
Your code should have the following structure:
for (int i = 1; i <= rows; ++i)
{
//special case for the first line
if (i == 1)
std::cout << asterisk << std::endl;
//for each of the other lines print 2 asterisks and the rest spaces
if (i > 1 && i <= rows - 1)
{
//one at the start of the line
std::cout << asterisk;
//print line - 2 spaces
for (int j = 0; j < i - 2; ++j)
std::cout << space;
//one at the end of the line
std::cout << asterisk << std::endl;
}
//special case for the last line
if (i == rows)
{
for (int j = 1; j <= i; ++j )
std::cout << asterisk;
std::cout << endl;
}
}
https://ideone.com/peGRUG
Your while loop condition is the issue here, also you should use == instead of = inside if condition. Anyways,Here is a small fix in your solution..
void printTriangle() {
int row;
std::string s = " ";
std::string a = " *";
int rows = 10;
for (int i = 1; i < rows-1; i++) {
for (int j = 1; j <= i; ++j)
{
if (j == 1 || j == i)
std::cout << a;
else
std::cout << s;
}
std::cout << std::endl;
}
for (int i = 1; i < rows; ++i)
std::cout << a;
}

How To Change Multidimensional Array Size In Program?

Hey I was wondering how I could have settings in-game which would allow the user to set the size of the 'game-board' by changing the array values. Here is the code. I know the code is messy and over the place but it is my first program.
#include "stdafx.h"
#include "iostream"
#include "string"
#include "cstdlib"
#include "ctime"
int xRan;
int choicei = 17;
int choicej = 17;
const int row = 15;
const int col = 16;
int play = 0;
void fill(char Array[row][col]);
int main()
{
int play = 0;
char Array[row][col];
srand((unsigned int)time(0));
xRan = rand() % 15 + 1;
if (play == 0)
{
std::cout << "1. To Play Treasure Hunt!" << std::endl;
std::cout << "2. How To Play Treaure Hunt!" << std::endl;
std::cout << "3. Treaure Hunt Settings! (Comming Soon)\n" << std::endl;
std::cin >> play;
std::cout << "-----------------------------------------------------------------------" << std::endl;
}
if (play == 2)
{
std::cout << "1. Select a row number. Be sure to make it less than or equal to " << row << "!" << std::endl;
std::cout << "2. Select a column number. Be sure to make it less than or equal to " << col << "!" << std::endl;
std::cout << "3. If you see the 'X' you have won! If you see the 'O' you lose!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
if (play == 3)
{
std::cout << "\nComming Soon!" << std::endl;
std::cout << "-----------------------------------------------------------------------\n" << std::endl;
std::cin >> play;
}
while (choicei > row || choicej > col || choicei < 1 || choicej < 1)
{
std::cout << "\nEnter The Row Number Less Than Or Equal To " << row << "!" << std::endl;
std::cin >> choicei;
std::cout << std::endl;
std::cout << "Enter The Column Number Less Than Or Equal To " << col << "!" << std::endl;
std::cin >> choicej;
std::cout << "\n-----------------------------------------------------------------------" << std::endl;
if (choicei > row || choicej > row)
{
std::cout << "Make Sure The Row And Column Numbers Are Less Than Or Equal To " << row << "and" << col << "!\n" "---------------------------------------------------------------------- - " << std::endl;
}
if (choicei < 1 || choicej < 1)
{
std::cout << "Make Sure The Row And Column Numbers Are More Than Or Equal To 1" << "!\n" "-----------------------------------------------------------------------" << std::endl;
}
}
fill(Array);
std::cout << std::endl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
std::cout << Array[i][j] << " ";
}
std::cout << std::endl;
}
if (xRan > 11)
{
std::cout << "\nCongratulations! You Won!\n" << std::endl;
}
else
{
std::cout << "\nBetter Luck Next Time!\n" << std::endl;
}
}
void fill(char Array[row][col])
{
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
Array[i][j] = '*';
}
}
if (xRan > 11)
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'X';
}
}
}
else
{
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < col; j++)
{
Array[choicei - 1][choicej - 1] = 'O';
}
}
}
}
Thank you in advance.
you can't do that with ordinary arrays. you should use dynamic arrays, for example std::vector http://www.cplusplus.com/reference/vector/vector/
Actually, what you want to do can be done in C, not in C++: C++ requires array dimensions to be compile time constants, C can use any runtime value.
If you stay in C++, you should take a look at vector<>. If, however, you choose to use C you can simply remove the const from the declaration of row and col.
You may find this answer useful. It lists several methods to create dynamic arrays.
Quoting the answer :
In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard)
Based on the suggestions, here are some ways you could initialize it (ignoring how you take the input value) :-
vector<vector<char>> Array(row, vector<char>(col));
or
char **Array = new char*[row];
for(int i = 0; i < row; i++)
{
Array[i] = new char[col];
}
UPDATE
Based on the comments, I am adding how to use the vector method and use it with the function 'fill'. fill uses reference while fill_with_ptr makes use of pointer. Although I list both the methods, I strongly recommend the one using reference.
void fill(vector<vector<char> >& array);
void fill_with_ptr(vector<vector<char> >* array);
int main()
{
...
cin >> row;
cin >> col;
vector<vector<char> > Array(row, vector<char>(col));
...
fill (Array); // or fill_with_ptr(&Array);
}
void fill(vector<vector<char> >& array)
{
... // access elements as array[i][j]
}
void fill_with_ptr(vector<vector<char> >* array)
{
... // access elements as (*array)[i][j]
}