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);});
Related
There is a simple feature I would like to add to one of the members of a class: I would like to quit the function in case all the values of some boolean (2d) array are true.
In the simpler case of a 1d array I can do it this way:
int SIZE = 10;
std::vector<bool> myArray(SIZE, true);
int i = 0;
while(myArray[i] and i < SIZE){
++i;
}
if(i == SIZE){
return;
}
// rest of the code for array not all true
There is probably no quicker way to do it (minus marginal optimizations) but I find it a bit ugly. Are there nicer ways to do it?
=========================================
In the end I decided to implement:
{
bool allTrue = true;
for(int i = 0; i < SIZE1 and allTrue; ++i)
for(int j = 0; j < SIZE2 and allTrue; ++j)
allTrue &= myArray[i][j];
if(allTrue)
return;
}
You may use std::all_of from <algorithm>:
if (std::all_of(myArray.begin(), myArray.end(), [](bool b) {return b;})) {
return;
}
One of the solutions:
int my2Da[][2] = {{true, true},{true, true},{true, true}};
int *pa = my2Da[0];
bool flag=true;
for (int i=0;flag && i<(sizeof my2Da)/(sizeof (int));flag &= pa[i++]);
//flag indicates about the result
For a 2d vector, you might want to break it down :
#include <vector>
#include <algorithm>
bool all_true(const std::vector<bool>& v)
{
return std::all_of(std::begin(v), std::end(v), [](const auto& b) { return b; });
}
bool all_true(const std::vector<std::vector<bool>>& vv)
{
return std::all_of(std::begin(vv), std::end(vv), [](const auto& v) {
return all_true(v);
});
}
void test()
{
std::vector< std::vector< bool > > d2 /* = initalise 2d vector */;
while(!all_true(d2))
{
// things you want to do
}
}
May be and-ing all values? This way:
bool r = true;
for (int i=0; i<myArray.size() && r; i++) r &= myArray[i];
return r;
Or std::all_of if your are familiar with iterators and lambdas.
I am solving Project Euler Problem #3. I think I've done the first half, but I'm not sure how to find the largest number in my array of factors. Is there a way to use an array as a parameter in a function?
#include <iostream>
#include <cmath>
#include <ctime>
bool isPrime(int);
bool isPrime(int x){
if(x==2){
return true;
}
if(x%2==0){
return false;
}
for(int i=0;i<x;i++){
if(x%i==0){
return false;
}
}
}
int prime_factors(int x){
int j = 0;
int arry[900];
for(int i = 0; i<x;i++){
if(isPrime(i)==true){
if(x%i==0){
arry[j]=i;
j++;
}
}
}
}
There are many ways to pass your array around. Most consistent with you current code would be:
int largest_prime_index(int* array, int length)
{
if (length < 1)
{
return -1;
}
int largest_index = 0;
for (int i = 1; i < length; i++)
{
if (array[i] > array[largest_index])
{
largest_index = i;
}
}
return largest_index;
}
Note, if you were using your arry variable, you would use j for length, not 900.
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;
}
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 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);