I'm trying to build a function which is supposed to compare to arrays, one generated by itself(the lottery digits) and the second array is submitted and stored by user input.
This is supposed to count the matching digits between the lottery and the ones submitted by the user input. If they match, a message should be displayed telling the user that he has won the big prize ,etc.
This is supposed to be the function that compares both arrays; I assume is right(to make it more clear: The program is to compare the corresponding elements in the two arrays and keep a count of the digits that match)?
int compare(int user[], int lottery[]){
int matches = 0;
for (int i = 0; i < SIZE; i++) {
if (user[i] == lottery[i]) {
matches++;
}
}
return matches;
}
the problem comes when it returns to the main function which is supposed to tell if the user has won or not. Here it is the small block of code that I created in the main function:
int matches = compare(user, lottery);
if (matches) {
cout << "Congratulations, you have won the big prize" << endl;
}
else {
cout << "Please, try again" << endl;
}
The expected should be to display a message if user won and to count the user digits that match with the lottery numbers.
The actual output is the digits entered by the user. Hopefully I could explain myself.
Here is the complete code, if you feel like helping and need a bit of more information.
http://cpp.sh/8ivyc
In your case it is enough to have only one time the same value at the same index to match, but all the values must be equals
First possibility with minimal changes from your code :
int compare(int user[], int lottery[]){
int matches = 0;
for (int i = 0; i < SIZE; i++) {
if (user[i] == lottery[i]) {
matches++;
}
}
return (matches == SIZE); /* <<< modified */
}
But it is useless to continue to compare after a different value was found, so can be :
int compare(int user[], int lottery[]){
for (int i = 0; i < SIZE; i++) {
if (user[i] != lottery[i]) {
return 0;
}
}
return 1;
}
and because you are in C++ :
bool compare(int user[], int lottery[]){
for (int i = 0; i < SIZE; i++) {
if (user[i] != lottery[i]) {
return false;
}
}
return true;
}
(also changing the call to use a bool rather than an int to be more clear of course)
The simplest way is to just use std::array. If you use std::array, you can just use == to compare them!
The functions populate and show_values can be written like this:
void populate(std::array<int, SIZE>& nums) {
srand(time(0));
for (int& value : nums) {
value = rand() % 9;
}
}
void showValues(std::array<int, SIZE>& nums) {
for (int i = 0; i < SIZE; i++) {
cout << setw(3) << nums[i];
}
cout << endl;
}
And compare is especially simple:
bool compare(std::array<int, Size>& nums1, std::array<int, Size>& nums2) {
return nums1 == nums2;
}
Check for inequality rather than equality.
You'll return out of the function as soon as an user element not equal to lottery element
int compare(int user[], int lottery[]){
for (size_t i = 0; i < SIZE; i++) {
if (user[i] != lottery[i]) {
return 0;
}
}
return 1;
}
Related
I am trying to see if an array contains multiple values at any given index in the array, and if it does I want it to return true and if not return false. I want it to return true when it finds the numbers 1-9 and false if it does not.
bool isSolved(int a[], int size) {
int count = 0;
for (int i = 1; i < 10; i++) {
if (hasNum(a,size,i)) {
count++;
}
}
if (count == 9) {
return true;
}
else {
return false;
}
}
bool hasNum(int a[], int size, int num) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (a[j] == num) {
return true;
}
else {
return false;
}
}
}
}
This is what I have so far and it just gets stuck and never ends.
Man, that's C++. So use a standard vector and the count_if function from the standard library:
#include <algorithm>
#include <vector>
std::vector<int> a { /* fill vector */ };
std::count_if(std::begin(a), std::end(a), [](auto const& x){ return x == 1;});
Return the number of elements with value 1.
Also good, to question whether there's any value of 1:
std::any_of(std::begin(a), std::end(a), [](auto const& x){ return x == 1;});
I know this is strictly not an answer ...
There's no need to have 2 for loops in your hasNum function. Also, you are returning false if any of the values in the array is not equal to the number passed. You need to return false after the for loop ends.
Rewrite your hasNum function as shown below:
bool hasNum(int a[], int size, int num) {
for (int i = 0; i < size; i++) {
if (a[i] == num) {
return true;
}
}
return false;
}
I am trying to see if an array contains multiple values at any given index in the array
An array always contains exactly one value in every index.
Basically, your code is far from any C++ guidelines.
First, you don't pass array in C++ as int a[]. Use std::vector<int> instead.
Second your algorithm is badly inefficient. Consider using histogram approach.
bool isSolved(const std::vector<int>& a)
{
std::array<bool,10> hist;
for(int i=0; i<10; i++)
{
hist[i]=false;
}
for(auto x : a)
{
if(x>=0 && x<10)
{
hist[x] = true;
}
}
for(int i=0; i<10; i++)
{
if(!hist[i]) return false;
}
return true;
}
Here is a hint to the solution to your problem:
class BinaryTreeSet : public BinarySearchTree {
...
operator==
...
};
You are best off using std algorithms like find_if:
#include <algorithm>
int a[42]; // or vector<int> a(42) or any other container of any size
std::find_if(std::begin(a),std::end(a),[](auto const& v){return (v>=1)&&(v<=9);});
I am a C++ noob and I have just started learning it, and one of my assignments is to print a solution to the N-Queens problem, where the board would be N*N depending on user input. My IDE keeps showing me errors I don't understand in my code, even though to me it looks good and fine.
#include <iostream>
#include <array>
#include <stdexcept>
using namespace std;
int N;
bool safe(char board[N][N], int row, int col)
{
//checks if it's safe to place a queen
//doesn't give me any errors
}
bool placeQueen(char board[N][N], int col)
{
for (int i = 0; i < N; i++)
{
if ( safe(board, i, col) )
// says there is no matching function to call safe
{
board[i][col] = 1;
if ( placeQueen(board, col + 1) ){
//says cannot initialize parameter of type char(*)[*]
//with an Ivalue of type char(*)[N]
return true;
}
board[i][col] = 0;
}
}
return false;
}
void printAnswer(char board[N][N]){
//prints the final answer
}
int main()
{
int i, j;
try{
cout << "Enter the number of queens: ";
cin >> N;
char board[N][N];
for (int i = 0; i < N; i++){
for (int j = 0; i < N; i++){
board[i][j] = '.';
}
}
if ( placeQueen(board, 0) == false )
//no matching function to call placeQueen
{
throw runtime_error("Solution does not exist.");
return 0;
}
printAnswer(board);
//no matching function to call printAnswer
}
catch (runtime_error& excpt){
cout << excpt.what();
}
return 0;
}
It's probably me just being stupid but help would be appreciated, thanks!
char board[N][N] is not C++ when N is not a compile time constant. It's an extension by gcc that really shouldn't be on by default.
You are not defining functions that take (C style) arrays of arrays of char, but instead they take something that isn't defined in standard C++, and behaves differently to how it would in C.
You should instead define some other type as your board, e.g. using Board = std::vector<std::vector<char>>;. Then you can pass (references to) this type around.
#include <iostream>
#include <vector>
using Board = std::vector<std::vector<char>>;
bool safe(const Board & board, int row, int col)
{
//checks if it's safe to place a queen
//doesn't give me any errors
}
bool placeQueen(Board & board, int col)
{
for (int i = 0; i < N; i++)
{
if (safe(board, i, col) )
{
board[i][col] = 1;
if ( placeQueen(board, col + 1) ){
return true;
}
board[i][col] = 0;
}
}
return false;
}
void printAnswer(const Board & board){
//prints the final answer
}
int main()
{
std::cout << "Enter the number of queens: ";
int N;
std::cin >> N;
Board board{N, {N, '.'}}; // Initialise N vectors of N '.'
if (!placeQueen(board, 0))
{
std::cout << "Solution does not exist.";
return 0;
}
printAnswer(board);
return 0;
}
For the life of me I can't get this code to sort correctly. This is a recursion practice, by sorting five numbers that the user inputs, then I display those five numbers from least to greatest. It does most of it correctly, but occasionally it will mess the first or last number up, and switch it with another number in the array. I know the problem is inside the function where is does the swapping, in that second 'if' statement, but I can't figure out how to fix it, I would really appreciate some direction as to how to proceed. Here is my code:
#include <iostream>
#include <array>
using namespace std;
void mySort(int nums[], int first, int size);
int main()
{
int fiveNumbers[5];
int firstNum = 0;
int size = 5;
cout << "Please enter five numbers, pressing enter after each.\n\n";
for (int i = 0; i < 5; i++)
{
cout << "Enter a number: ";
cin >> fiveNumbers[i];
cout << endl;
}
mySort(fiveNumbers, firstNum, size);
for (int i = 0; i < size; i++)
{
cout << fiveNumbers[i] << endl;
}
system("PAUSE");
return 0;
}
void mySort(int nums[], int first, int size)
{
if (size == 0)
{
return;
}
for (int i = 0; i < 5; i++)
{
if (first < nums[i])
{
swap(nums[first], nums[i]);
}
}
first++;
size--;
return mySort(nums, first, size);
}
Changed my function to reflect the value of the array AT point 'first', instead of the variable 'first' itself. So far it has worked every time!
void mySort(int nums[], int first, int size)
{
if (size == 0)
{
return;
}
for (int i = 0; i < 5; i++)
{
if (nums[first] < nums[i])
{
swap(nums[first], nums[i]);
}
}
first++;
size--;
return mySort(nums, first, size);
}
EDIT: Got your code working but forgot the most important part, namely:
You're comparing the index to the array value, use:
if (nums[first] < nums[i])
Instead of:
if (first < nums[i])
Also, you always start swapping from the beginning when you should be starting one past first.
Instead of:
for (int i = 0; i < 5; i++)
You want:
for (int i = first + 1; i < 5; i++)
The context of the program is a game involving pegs and discs. The user inputs the amount of pegs (max of 20) and the amount of discs on each peg (max of 10). Two players go back and forth removing any amount of discs on a single peg each turn, given that there are enough discs to remove on that peg. The player to remove the last disc loses.
The number of discs are stored in an array, where the index of the array corresponds the peg number. I have a boolean function that checks whether or not the pegs are empty of discs, implying someone has won. There is some logical error in my code but I can't figure out what it is:
bool checkPegs(int array[], int size)
{
int checker(0);
for (int i = 0; i < size; i++)
{
if(array[i] = 0)
{
return true;
}
else
{
return false;
}
}
}
bool checkPegs(int array[], int size)
{
for (int i = 0; i < size; i++)
{
if(array[i] != 0)
{
return false;
}
}
return true;
}
try memcmp instead of having separate function with for loop:
int zeros[sizeof(yourArray)];
if(memcmp(yourArray,zeros,sizeof(yourArray))==0)
//do things
else
//do things
if(array[i] = 0)
That doesn't compare array[i] with 0, it assigns 0 to array[i]. You want array[i] == 0.
if(array[i] == 0)
{
return true;
}
else
{
return false;
}
The second issue is that you only check the first element, then return based on that. You should check every element to ensure they are non-zero:
for (int i = 0; i < size; i++)
{
if(array[i] != 0) {
return false;
}
}
Finally, you don't handle the case that size is 0. In that case, you should return true.
bool checkPegs(int array[], int size)
{
for (int i = 0; i < size; i++)
{
if(array[i] != 0) {
return false;
}
}
return true;
}
there are two errors here
bool checkPegs(int array[], int size)
{
int checker(0);
for (int i = 0; i < size; i++)
{
if(array[i] = 0) // the first one use '==' instead of '='
{
return true; // the second one, you are testing the first element only
}
else
{
return false;
}
}
}
here how it should be
bool checkPegs(int array[], int size)
{
for (int i = 0; i < size; i++)
{
if(array[i] )
return false; // return false at the first found
}
return true; //all elements checked
}
The way you wrote your code cannot work, for you are actually considering only the first element because of the two return statements in the if/else. Moreover, you use an assignment statement instead of a comparison.
It follows a reviewed example:
bool checkPegs(int *array, int size) {
for (int i = 0; i < size; i++) {
if(array[i] != 0) { return false; }
}
return true;
}
Keep in mind that it can be optimized and you can do the same using standard utilities, but I assume that you are learning to code and so it's worth to write it for yourself.
I am new to C++ and have just started learning functions. I have made a program to search an element in a 1-d array using a function search. But there is a logical error I can't comprehend! Is it because of the way the function is declared ?
int pos;
using namespace std;
int search(int *a, int size, int num);
int search(int *a, int size, int num)
{
int i;
for(i=0; i<size; i++)
{
if(a[i]==num)
{
pos=i; return 1;
}
else
return 0;
}
}
int main()
{
int a[5], size, num, i;
system("cls");
cout<<"Enter size(<5) \n";
cin>>size;
cout<<"Enter the elements of the array \n";
for(i=0; i<size; i++)
cin>>a[i];
cout<<"Enter the number to be searched \n";
cin>>num;
int b = search( a, size, num);
if(b==0)
{
cout<<"Element not found!"; exit(0);
}
else
cout<<"Element found at position "<<(pos+1);
system("pause");
return 0;
}
Output:
Enter size(<5)
4
Enter the elements of the array
4
3
2
1
Enter element to be searched
4
Element not found!
Your function always returns in the first loop iteration. If the first element is not the one to be searched, 0 is returned immediately. The loop never enters the second iteration.
you must return not found if you dont found any thing, with this code, you will always return zero, if the first element is not what you are searching for. something like this :
int search(int *a, int size, int num)
{
int i;
for(i=0; i<size; i++)
{
if(a[i]==num)
{
pos=i; return 1;
}
}
return 0;
}
It is in your logic
int search(int *a, int size, int num)
{
int i;
for(i=0; i<size; i++)
{
if(a[i]==num)
{
pos=i; return 1;
}
else
return 0;
}
}
Let's step through that. I'm going to give it [1, 2, 3, 4], 4, and 3.
i => 0
a[0] => 1
a[0] == 3 => false
return false
So, you check the first one, and if that doesn't work, it will immediately fail.
So try this:
int search(int *a, int size, int num)
{
for(int i = 0; i < size; ++i)
{
if(a[i]==num)
{
pos = i;
return 1;
}
}
return 0;
}
However, the better way would be to do something like this, and get rid of your global variable
int search(int *a, int size, int num)
{
for(int i = 0; i < size; ++i)
{
if(a[i]==num)
{
return i;
}
}
return -1;
}
Then if you get something != -1 you have found it.
Your search function is not doing what you think it is doing: it will return 0 as soon as a[i]!=num, thus not considering the rest of the elements of the array.
You'd better use someting like this, with a (non-global) variable returned:
#include <cstdlib>
// returns -1 if not found, else the found index
int search(int *a, int size, int num)
{
int pos = -1;
for(int i=0; i<size; i++)
{
if(a[i]==num)
{
pos = i;
break;
}
}
return pos;
}
// ... main() and parsing stuff goes here
if( (b = search( a, size, num)) == -1)
{
std::cerr<<"Element not found!";
return EXIT_FAILURE;
}
The problem is with your else statement. If the the element is not found straight away, it will automatically return 0. Furthermore, you use the integer 0 to indicate that the element is not found, but what if the element is found at position 0 (i.e it is the first element of the array)? Then you will still say that the element is not found, even though it clearly it exists in the array. Here is how I would do it.
bool search(int *a, int size, int num)
{
for (int i = 0; i < size; ++i)
{
if (a[i] == num)
{
cout << "Element found at position " << i << " of the array!" << endl;
return true;
}
}
cout << "Element not found!" << endl;
return false;
}
I hope you have learned about booleans (i.e true or false.) Since your function's main purpose is to search, it should return whether the element is found (true) or whether it is not found (false). Therefore, we loop through the array, and if we find it, we output the position of the element, and return true. Otherwise, if we exit the loop, this means the element has not been found, so we output that and return false. This gets rid of the global variable usage and the previous problems that I have mentioned.