C++ Integer array and boolean functions - c++

I need to write in C++ a complete boolean function that will take an integer array and it's maximum size as a parameter and return whether or not that array has any elements with a value of 0.
I'm not even sure where to start.
Thanks in advance.

bool checkFunction(int *myArray, int size)
{
for (int i=0; i < size; ++i)
{
if (myArray[i] == 0)
return true;
}
return false;
}
Are you talking about something like this? This will iterate through the array and return true if there is a value of 0 anywhere.

Use std::find
#include <algorithm>
bool ContainsZero(int *arr, int size)
{
return std::find(arr, arr+size, 0) != (arr+size);
}

How about reading a tutorial on arrays in C++?

bool TestForZero(int* myArray, int maxSize)
{
for(int ii=0; ii<maxSize; ++ii)
if(myArray[ii] == 0)
return true;
return false;
}

This sounds an awful lot like a homework problem, so I'll just give you the concepts and let you learn.
You need to use a "for" loop, check the value of each item in the array, and return true if you find one, otherwise return false after the loop exits.

bool hasZeroes(int * array, int len) {
int zeroCount = 0;
for (int i = 0; i < len; i++) {
if (array[i] == 0) zeroCount++;
}
return zeroCount > 0;
}

bool foo(int* array, int size)
{
int i;
for (i = 0; i < size; i++)
{
if (array[i] == 0)
{
return true;
}
}
return false;
}
and to call it you would do something like:
int arr[] = { 1, 2, 3, 4, 0, 6};
foo(arr, 6);

Related

How can I check if a array contains multiple elements?

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);});

Compare all elements within an array with another array

So i am having difficulty understand a rather simple algorithm. If i want to compare all the elements within one array to another how would it work? For instance
For ( i = 0; i < size; i++ )
{
For ( k = 0; k < size; k++)
{
Do something if arrays are the same or not
}
}
Both i and k loops would just carry the same slot in the array. If i add a - 1 or + 1 it would just check the last or next slot... But what if i wanted to check 1 to 3 or the whole array preferably.
It really depends on what you consider "the same". If you want them to be in the same order, it can be a little simpler.
for(int i =0; i < size; i++){
if (arrayOne[i] != arrayTwo[i])
return false;
}
}
If the order doesn't matter, it can get a little more complicated.
for(int i = 0; i < size; i++){
int valueFound = 0;
for(int k = 0; k < size; k++){
if (arrayOne[i] == arrayTwo[k]){
valueFound = 1;
}
}
if (valueFound == 0)
return false;
}
return true;
But this assumes that the arrays are the same size. And it really only checks to see that all the values from arrayOne are inside arrayTwo so it is not exactly what you're looking for. I do hope that this provides some direction to you.
This is incorrect algorithm.
You can write your own function, it will be like this.
Note that a[] in function arguments will be replaced by compiler with *a
template<typename T>
bool arraycmp(T *a, size_t a_size, T *b, size_t b_size)
{
if(a_size != b_size) // If sizes is not same, we know that arrays not equal
return false;
for(size_t i = 0; i<a_size; ++i)
{
if(a[i]!=b[i]) // Just do check, and if array element mismatch return false
return false;
}
return true;
}
or like this, with one size_t
template<typename T>
bool arraycmp(T *a, T *b, size_t size)
{
for(size_t i = 0; i<size; ++i)
{
if(a[i]!=b[i]) // Just do check, and if array element mismatch return false
return false;
}
return true;
}
Or just use library function memcmp

Searching and sorting arrays

I am taking an introductory level C++ class. I have to write a boolean function that checks for duplicates along a vectors and returns true and false if no duplicates
#include<iostream>
#include<vector>
using namespace std;
bool has_duplicates(const vector <int> &v);
int main() {
vector<int> Vec(8);
Vec = { 20, 30, 40, 50, 10, 20, 5, 6 };
has_duplicates(Vec);
return 0;
}
bool has_duplicates(const vector<int>& v) {
bool duplicatefound = false;
for (int i = 0; i < 8; i++) { // Check each other number in the array
for (int j = i; j < 8; j++) { // Check the rest of the numbers
while (j != i) {// Makes sure don't check number against itself
if (v[i] == v[j]) {
cout << "duplicate found" << endl;
duplicatefound = true;
break;
}
}
}
}
return duplicatefound; // Reset the boolean after each number entered has been checked
}
There is a very simple solution to your problem:
Iterate through your array, using a loop:
for(int i=0; i < array_length; i++)
Within this loop, make use of another loop, to check whether any value prior to the one, to which i is pointing, is equal to your_array[i]. If this is the case you have found a duplicate and can return true, else the loops will just run until the end of the array is reached and then you can return false.
Thus your entire function would be something like:
bool contains_duplicates(int array[], int len) {
for(int i=0; i < len; i++) {
for(int j=0; j < i; j++) {
if(array[j]==array[i]) {
return true;
}
}
}
return false;
}
Hope I could help, cheers!
lindebear
You can use templates to extend the type contained on vector like this. This solution reduces the algorithm complexity to O(n log n) which is better than O(n^2) from your nested loop, it doesn't mean it will be faster always but it make a difference on large vectors.
template< typename T>
bool hasDuplicates(std::vector<T> vect) {
std::sort(vect.begin(), vect.end());
T last;
typename vector<T>::iterator it;
for(it = vect.begin(); it < vect.end(); it++) {
if (vect.begin() != it) {
if(last == *it) {
return true;
}
}
last = *it;
}
return false;
}

How to check if all the values of an array are equal to 0?

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.

Finding number of prime numbers in an array

I'm trying to write a function that finds the number of prime numbers in an array.
int countPrimes(int a[], int size)
{
int numberPrime = 0;
int i = 0;
for (int j = 2; j < a[i]; j++)
{
if(a[i] % j == 0)
numbPrime++;
}
return numPrime;
}
I think what I'm missing is I have to redefine i after every iteration, but I'm not sure how.
You need 2 loops: 1 over the array, 1 checking all possible divisors. I'd suggest separating out the prime check into a function. Code:
bool primeCheck(int p) {
if (p<2) return false;
// Really slow way to check, but works
for(int d = 2; d<p; ++d) {
if (0==p%d) return false; // found a divisor
}
return true; // no divisors found
}
int countPrimes(const int *a, int size) {
int numberPrime = 0;
for (int i = 0; i < size; ++i) {
// For each element in the input array, check it,
// and increment the count if it is prime.
if(primeCheck(a[i]))
++numberPrime;
}
return numberPrime;
}
You can also use std::count_if like this:
std::count_if(std::begin(input), std::end(input), primeCheck)
See it live here.