checking specific condition in array - c++

have a little problem in exercise in arrays and functions.
I need to write a code that checks every cell in the array for two conditions. The first is that every cell value left to the index exist to the right of the index, and the second is the opposite, every cell value on the right exist to the left.
If those two conditions exist then the cell is "good" and I will add it to the counter of the good cells.
for example: input is 38 79 38 38 17 79 38
For this input I expect that cell #4 will answer the conditions and it will print 1. It will answer the conditions because 38 and 79 exist on the left of #4 and the opposite. Currently for this input it's printing 0 for some reason.
I will gladly use some hints on where the problem is because currently I'm stuck.
Thank you!
// include section
#include <iostream>
#include <cstdlib>
// using section
using std::cin;
using std::cout;
using std::endl;
// constant section
const int N = 7;
// functions section
void input(int arr[]);
bool check_cell(int array[], int cell_index);
bool check_cond_left_to_right(int array[], int cell_index);
bool check_cond_left_to_right(int array[], int cell_index);
bool check_cond_right_to_left(int array[], int cell_index);
bool search_cell_on_the_right(int array[], int cell_value, int original_cell_index);
bool search_cell_on_the_left(int array[], int cell_value, int original_cell_index);
int main() {
int array[N],
cell_counter = 0;
input(array);
for (int index = 1; index < N - 1; index++) {
if (check_cell(array, index)) {
cell_counter++;
}
}
cout << cell_counter;
}
void input(int arr[]) { // input function
for (int index = 0; index < N; index++)
cin >> arr[index];
}
bool check_cell(int array[], int cell_index) {
if (check_cond_left_to_right(array, cell_index) &&
check_cond_right_to_left(array, cell_index))
return true;
else
return false;
}
bool check_cond_left_to_right(int array[], int cell_index) { // check the cells on the left and send them to the right
for (int i = 0; i < cell_index; i++) {
if (search_cell_on_the_right (array, array[i], cell_index) == false)
return false;
}
return true;
}
bool check_cond_right_to_left(int array[], int cell_index) {
for (int i = N; i > cell_index; i--) {
if (search_cell_on_the_left(array, array[i], cell_index) == false)
return false;
else
continue;
}
return true;
}
bool search_cell_on_the_right(int array[], int cell_value, int original_cell_index) { // getting cells on the left and checks if they exist on the right
for (int i = original_cell_index + 1; i < N; i++) {
if (cell_value == array[i])
return true;
}
return false;
}
bool search_cell_on_the_left(int array[], int cell_value, int original_cell_index) {
for (int i = 0; i < original_cell_index; i++) {
if (cell_value == array[i])
return true;
}
return false;
}
I have tried to identified where the problem is but couldn't find it. Will gladly use some help.

You have an Index out of bounds in one of your functions. If you want to iterate through an array backwards, you have to start at N-1, because N isn't a valid index.
Below is a corrected code
bool check_cond_right_to_left(int array[], int cell_index) {
for (int i = N - 1; i > cell_index; i--) {
if (search_cell_on_the_left(array, array[i], cell_index) == false)
return false;
else
continue;
}
return true;
}

Related

Longest Palindrome in integer array

I want to find the largest palindrome in an integer array. I tried making my own algorithm and not looking at the online ones. But this is not working. I tried doing debugging but couldn't get it to work.
Sample input:
"1367611342142412431113424823782"
Output: 113421424124311
void palindrome()
{
int max = 0;
int len;
int start;
int end;
int st=0,en=0;
bool palin = false;
for(int i=0;i<size;i++)
{
for(int j=size-1; j>=0;j--)
{
if(array[i] == array[j])
{
start = i;
end = j;
while(j==i+1 || j+1 == i || j == i )
{
if(array[i] == array[j])
{
i++;
j--;
palin = true;
}
else
{
palin = false;
break;
}
}
i= start;
j= end;
}
if(palin == true)
{
len = end - start;
if(len>max)
{
cout<<" "<<st<<" "<<en<<endl;
st=i;
en =j;
max = len;
}
}
}
}
cout<<endl;
cout<<st<<" "<<en<<endl;
ofstream file("output.txt");
for(int i=st;i<=en;i++)
{
file<<array[i];
}
}
There is solution
#include <iostream>
#include <string>
struct Result
{
int fromIndex, toIndex;
Result(int fromIndex, int toIndex){
this->fromIndex = fromIndex;
this->toIndex = toIndex;
}
int length(){
return toIndex - fromIndex;
}
};
bool isPalindrome(std::string &s, int left, int right){
while(left <= right){
if(s[left] != s[right]){
return false;
}
left ++;
right --;
}
return true;
}
std::string solve(std::string &s){
int startIndex = 0;
int toIndex = s.size() - 1;
Result result(0,0);
while(true){
if(isPalindrome(s, startIndex, toIndex)){
if(result.length() < (toIndex - startIndex)){
result.fromIndex = startIndex;
result.toIndex = toIndex;
}
}
toIndex --;
if(toIndex <= startIndex){
toIndex = s.size() - 1;
startIndex++;
}
if(startIndex == s.size() - 1){
break;
}
}
std::string str = "";
for (int i = result.fromIndex; i <= result.toIndex; ++i)
{
str += s[i];
}
return str;
}
int main()
{
std::string s = "1367611342142412431113424823782";
std::string result = solve(s);
std::cout << "Longest palindrome is: "<< result;
return 0;
}
You need to think in more structural way. Split your task in to sub-tasks first. In this case there are to sub-tasks:
1. go over all possible combinations
2. check if this combination is a palindrome.
Each task is another function - this way it is easier to think, read code and debug.
(In case you want to write it to file - it is a third task!)
Here is the code for the "go over all possible combinations". I guess you will find yourself how to check a single array if it is a palindrome.
#include <iostream>
using namespace std;
bool isPalindrome(int* arr, int size);
bool findLargestPalindrome(int* arr, int size);
int main()
{
int arr[] = { 1,3,6,7,6,1,1,3,4,2,1,4,2,4,1,2,4,3,1,1,1,3,4,2,4,8,2,3,7,8,2 };
int arrSize = 31;
findLargestPalindrome(arr, arrSize);
}
bool findLargestPalindrome(int* arr, int size)
{
for (int testSize = size; testSize > 0; testSize--)
{
int startIndex = 0;
while (testSize + startIndex <= size)
{
int* arrayToTest = &(arr[startIndex]);
if (isPalindrome(arr, testSize))
{
//TODO: you found it - do with it whatever you want
return true;
}
startIndex++;
}
}
return false;
}
bool isPalindrome(int* arr, int size)
{
//TODO: your code for single palindrome
return false;
}

Can I use an array as a parameter in a function in C++?

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.

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.

Runtime error in code (C++)

i am a beginner to c++ but i wouldn't have asked this question if i didnt spend hours on it.
The code is about finding primes between two numbers in the most efficient way where maximum limit is 10^9.
The following code gives me runtime error but i have no idea why.. help
#include <iostream>
#include <stdio.h>
#include <math.h>
using namespace std;
long int prime[32000];
bool isprime(long int a){
for(long int i = 3; i <= 32000; i+=2){
if(a%i == 0){
return false;
}
}
return true;
}
void generateprimes(){
long int a = 0;
for(long int i = 3; i < 31623 ; i+=2){
if(isprime(i)){
prime[a] = i;
a++;
}
}
}
bool newisprime(long int a){
long int x =0;
for(long int i = prime[x]; i <= sqrt(a); i = prime[++x]){
if(a%i == 0){
return false;
}
}
return true;
}
void generateprimes_inbetween(long int n,long int m){
if(n%2 == 0){
++n;
}
if(n == 1){
printf("2\n");
n = 3;
}
for(long int i = n; i <= m ; i+=2){
if(newisprime(i)){
printf("%d\n",i);
}
}
}
int main() {
long int a,b,c;
scanf("%ld",&a);
generateprimes();
for(long int i = 0; i < a ; i++){
scanf("%ld %ld",&b,&c);
generateprimes_inbetween(b,c);
printf("\n");
}
return 0;
}
In isprime() you loop through ALL numbers in your array prime[]. But at startup, as it's global data, most of them will be 0, so that a%i will result in a fatal divide by 0.
You have somewhere to keep track of the numer of primes that you've stored in your array and only test against the primes that you've stored there.
Supposing that it's homework and you're not allowed to use vectors, you could do it as follows:
const size_t max_primes = 32000; // avoid hard coded values
unsigned long prime[max_primes] {2, 3}; // prefilled values
size_t nprimes = 2; // number of primes in the array
bool isprime(unsigned long a){
for(size_t i = 0; i < nprimes; i++){
if(a%prime[i] == 0)
return false;
}
return true;
}
void generateprimes(){
nprimes = 2;
for(unsigned long i = 3; nprimes<max_primes && i < ULONG_MAX; i += 2){
if(isprime(i)){
prime[nprimes] = i;
nprimes++;
}
}
}
bool newisprime(unsigned long a){
size_t x = 0;
for(unsigned long i = prime[x]; i <= sqrt(a) && x<nprimes; i = prime[++x]){
if(a%i == 0)
return false;
}
if(x == nprimes) {
cout << "Attention: Reaching end of prime table !!" << endl;
}
return true;
}
Some remarks:
for the index, it's safer to use the unsigned type size_t.
make sure that whenever you use an index, it remains within the bounds
as you work with positive numbers, it could make sense to use unsigned long

finding elements in an array using a function c++

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.