Function call statement in main function not actually calling the function - c++

The question is to find the largest subarray with contiguous
elements. For example if the given array is a[ ]={7,1,3,2} then
it's subarray would be {1,3,2} because the difference of maximum
element and the minimum element is equal to the difference of the
indexes of the first and the last element of the subarray and the
subarray contains all the numbers between 1 and 3.
Here's a code that I have written for this problem but the thing is that in the main function somehow the function call line longestConsecutiveNumsSubarray(); is not actually calling the function. I checked this in python tutor and it says that the whole program finished executing in only 1 step which should not be the case. So, can someone tell me what is wrong with my code.
3.Code:
#include<iostream>
using namespace std;
const int Nmax= 100005;
int a[Nmax],n;
int longestConsecutiveNumsSubarray()
{
int ans = 1;
for(int left = 0; left<(n-1) ; left++)
{
int Min, Max;
Min=a[left];
Max=a[left];
for(int right = left+1 ; right<n ; right++)
{
Min = min(Min , a[right]);
Max = max(Max , a[right]);
if(Min-Max == right-left)
ans = max(ans , Min-Max+1);
}
}
return ans;
}
int main()
{
cin>>n;
for(int i=1 ; i<=n ; i++)
cin>>a[i];
cout<< longestConsecutiveNumsSubarray();
return 0;
}
PS: I don't know why I had to indent my code with 4 spaces to get my code into the code block. I clicked on the code button and then I pasted the whole code but somehow all the tabs and spaces that were originally in my code disappeared.

Related

C++ : Longest Arithmetic Subarray

Given an input array, the output must be the length of the longest arithmetic subarray of the given array.
I am getting a different output other than the desired one. I don't understand where I went wrong, I'm still a beginner so please ignore the rookie mistakes and kindly help me out wherever I'm wrong. Thanks in advance.
Here's the code:
#include <iostream>
using namespace std;
int main () {
int n;
cin>>n;
int array[n];
for (int i=0;i<n;i++)
{
cin>>array[i];
}
int length = 2;
int cd = array[1] - array[0];
for(int i=2; i<n; i++){
if(array[i] - array[i-1] == cd){
length++;
}
else {
cd = array[i] - array[i-1];
length=2;
}
cout<<length<<" ";
}
return 0;
}
If you are looking for a subsequence then what you did would not accomplish that.
For example:
Input: nums = [9,4,7,2,10]
Output: 3
Explanation:
The longest arithmetic subsequence is [4,7,10].
You would require a nested loop structure (a for loop within the for loop you currently have) to accomplish that as you want to check a certain cd with the entire array and not just the next element.
If you require to find a subsequence/subarray given that the elements must be adjacent to one another then your program would work correctly.
Also a big error in your code is that you are printing the length inside the for loop. Unsure of whether that was for debugging purposes.
The problem here is you're resetting length after every update. You need a variable to store the maximum of every length.
#include <iostream>
using namespace std;
const int maxn = 1e6;
int arr[maxn];
int main ()
{
int n; cin>>n;
for (int i=0;i<n;i++) { cin >> arr[i]; }
int length = 2;
int maxLength = 2; //max variable
int cd = arr[1] - arr[0];
for(int i=2; i<n; i++){
if(arr[i] - arr[i-1] == cd) {length++;}
else {
cd = arr[i] - arr[i-1];
length=2;
}
//cout<<length<<" "; //remove this
maxLength = max(maxLength, length); //update maxLength
}
cout << maxLength;
}
A few more aesthetic notes:
array is a keyword in C++ used to declare std::array. Although the program may still run, it could create unnecessary confusion.
int array[n] is a VLAs (variable length array). It's not a C++ standard. It may or may not work depends on the compiler.
Why is "using namespace std;" considered bad practice?

Array doesn't print anything on executing code

I was creating a function that takes an integer number, finds the next multiple of 5 after the number and then if the difference between the multiple and the number is less than 3, then it prints out the multiple else the number itself, finally prints out an array of all the numbers.
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
vector<int> gradingStudents(vector<int> grades) {
int size=grades.size();
int c=0;
int d;
vector<int> array;
for(int i=0;i<size;i++){
while(grades[i]>(c*5)){
c++;
}
d=c*5;
if((d-grades[i])<3){
array[i]=d;
}else{
array[i]=grades[i];
}
d=0;
c=0;
}
return array ;
Now I tried running this function, and the compiler gives shows no error in the program in the code, however the code doesn't print anything.
Someone Please help.
First, I have to say that this code is extremely inefficient. Finding the difference between the closest muliplication of 5 and a number can be simply done by:
int difference = (n - (n + 4) / 5 * 5) - n;
Explanation: C++ is rounding down the division, so (n + 4) / 5 is n / 5 rounded up, and hence (n+4)/5*5 is the closest multiplication of 5.
Another thing, you declare an array but never resize it, so its size is 0. You need to resize it either by specifying the size in the constructor or using the std::vector::resize method.
code:
std::vector<int> gradingStudents(std::vector<int> grades) {
std::size_t size = grades.size();
std::vector<int> array(size);
for (int i = 0; i < size; i++) {
int closestMul = (grades[i] + 4) / 5 * 5;
if (closestMul - grades[i] < 3) {
array[i] = closestMul;
}
else {
array[i] = grades[i];
}
}
return array;
}
Proably your code is crashing, which is why it doesn't print anything. And one reason it might be crashing is your vector use is wrong.
It's very common to see beginners write code like this
vector<int> array;
for (int i=0;i<size;i++) {
array[i] = ...;
But your vector has zero size. So array[i] is an error, always.
Two possible solutions
1) Make the vector the correct size to begin with
vector<int> array(size);
for (int i=0;i<size;i++) {
array[i] = ...;
2) Use push_back to add items to the vector, every time you call push_back the vector increases in size by one.
vector<int> array(size);
for (int i=0;i<size;i++) {
array.push_back(...);
And please don't call your vector array, that's just taking the piss.
i feel nothing is wrong with your function but calling of this function is a bit tricky let me give you a quick main to try may be that will help you.
int main() {
vector <int> test ;
test.push_back(1);
test.push_back(2);
gradingStudents(test);
return 0;
}
Try initially the size of the vector is empty i hope you are sending something from the main . Your code is very inefficient whenever you find time must read how to write an efficient code.

Find the largest palindrome made from the product of two 3-digit numbers in c++

my program seems correct but I don't know why it has a logic problem
int main()
{
int r,s=0;
for(int i=10000;i<=998001;i++)
{
while (i>0)
{
r=i%10;
s=s*10+r;
i=i/10;
}
cout<<s<<endl;
}
Your question and code don't seem to match Ali. You have told that you need the largest possible palindrome, but you are printing each and every reversed number. And your code has glitches too. I will list the mistakes and corresponding changes to be made:
using i as both the for loop counter variable and as well as the number you're reversing. This causes i to become 0 after every reversal and hence the for loop never ends. The fix for this... use another variable, say num, and equate it to i at the start of the loop. This ensures that i remains unchanged and for goes unfazed.
use long int instead of int. This avoids any anomalies and chances of junk numbers.
s(the sum variable) is initialized only at the start. Hence every time you calculate a new reversed number, it is adding s to its previous value. The fix: Initialize s to 0 at the start of for loop so that you get a fresh reversed for every i value.
You are not checking for any palindrome condition. You are just printing the reversed number. The fix: Hence check if the the number is a palindrome, i.e, if the number ,i.e., i is equal to the reversed number, i.e., s
I have attached the code below. I am currently printing the greatest palindrome in the range in which you were checking. In case you need all the palindromes, just uncomment the commented cout line.
CODE:
#include <iostream>
using namespace std;
int main()
{
int r, s = 0;
long int num, max = 0;
for(long int i = 10000; i <= 998001; i++)
{
s = 0;
num = i;
while (num > 0)
{
r = num % 10;
s = s * 10 + r;
num = num / 10;
}
if(s == i) {
//cout<<s<<endl; //uncomment this line if you intend to display all palindromes
if(i > max)
max = i;
}
}
cout<<max<<endl;
}

why am I getting seg fault in this?

Problem Statement
Mark is an undergraduate student and he is interested in rotation. A conveyor belt competition is going on in the town which Mark wants to win. In the competition, there's A conveyor belt which can be represented as a strip of 1xN blocks. Each block has a number written on it. The belt keeps rotating in such a way that after each rotation, each block is shifted to left of it and the first block goes to last position.
There is a switch near the conveyer belt which can stop the belt. Each participant would be given a single chance to stop the belt and his PMEAN would be calculated.
PMEAN is calculated using the sequence which is there on the belt when it stops. The participant having highest PMEAN is the winner. There can be multiple winners.
Mark wants to be among the winners. What PMEAN he should try to get which guarantees him to be the winner.
Definitions
PMEAN = (Summation over i = 1 to n) (i * i th number in the list)
where i is the index of a block at the conveyor belt when it is stopped. Indexing starts from 1.
Input Format
First line contains N denoting the number of elements on the belt.
Second line contains N space separated integers.
Output Format
Output the required PMEAN
Constraints
1 ≤ N ≤ 10^6
-10^9 ≤ each number ≤ 10^9
Code
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main (void)
{
int n;
cin>>n;
vector <int> foo;
int i = 0,j = 0,k,temp,fal,garb=0;
while (i < n)
{
cin>>fal;
foo.push_back(fal);
i++;
}
vector<int> arr;
//arr.reserve(10000);
for ( i = 0; i < n; i++ )
{
garb = i+1;
arr.push_back(garb);
}
long long product = 0;
long long bar = 0;
while (j < n)
{
i = 0;
temp = foo[0];
while ( i < n-1 )
{
foo[i] = foo[i+1];
i++;
}
foo[i] = temp;
for ( k = 0; k < n; k++ )
bar = bar + arr[k]*foo[k];
if ( bar > product )
product = bar;
j++;
}
return 0;
}
My Question:
What I am doing is basically trying out different combinations of the original array and then multiplying it with the array containing the values 1 2 3 ...... and then returning the maximum value. However, I am getting a segmentation fault in this.
Why is that happening?
Here's some of your code:
vector <int> foo;
int i = 0;
while (i < n)
{
cin >> fal;
foo[i] = fal;
i++;
}
When you do foo[0] = fal, you cause undefined behavior. There's no room in foo for [0] yet. You probably want to use std::vector::push_back() instead.
This same issue also occurs when you work on vector<int> arr;
And just as an aside, people will normally write that loop using a for-loop:
for (int i=0; i<n; i++) {
int fal;
cin >> fal;
foo.push_back(fal);
}
With regards to the updated code:
You never increment i in the first loop.
garb is never initialized.

Solving sudoku puzzle with c++

I want to make a program for solving a 3*3 sudoku puzzle. I have made a program but it is only working for 50% problems and for the rest it gives 60% right solution. I do not know how to solve it in a finite number of steps for every possible problem. The technique I have used is that I am searching every individual element of array and check which no does not exist in the same row and column and then I put it in that unit and move to the next. But this is not the solution for every problem. The next thing that come to mind was that we should have to write each and every possible number for a unit and then proceed. But how will we decide that which number we should finally put in the unit. I just want that how to write a solution that will work for every problem. I hope you got the point.
The code I have written is
#include<iostream>
using namespace std;
int rowsearch(int l[9][9],int row,int num) // function to search a particular number from a row of array
{
int counter=0;
for (int c=0 ; c<9 ; c++)
{
if (l[row][c]==num)
counter=counter+1;
}
if (counter>0)
return 1;
else
return 0;
}
int colsearch(int l[9][9],int col,int num) // function to search a number from a column of an array
{
int counter=0;
for (int c=0 ; c<9 ; c++)
{
if (l[c][col]==num)
counter=counter+1;
}
if (counter>0)
return 1;
else
return 0;
}
int rowcolnotexist(int x[9][9],int row , int col) // to find a nuber which does not exists int a row and column
{
for (int c=1 ; c<=9 ; c++)
{
if ( rowsearch(x,row,c)!=1 && colsearch(x,col,c)!=1)
return c;
}
return 0;
}
int main()
{
int l[9][9]={};
// input of the list
for (int i=0 ; i<9 ; i++)
for (int j=0 ; j<9 ; j++)
{
cout<<"Enter "<<i+1<<"*"<<j+1<<"entry of the list(For not entering a number enter 0).";
cin>>l[i][j];
}
// operations
for (int i=0 ; i<9 ; i++)
{
for (int j=0 ; j<9 ; j++)
if (l[i][j]==0)
l[i][j]=rowcolnotexist(l,i,j);
}
// printing list
for (int i=0 ; i<9 ; i++)
{
for (int j=0 ; j<9 ; j++)
{
cout<<l[i][j];
if ((j+1)%3==0)
cout<<" ";
else
cout<<" ";
}
if ((i+1)%3==0)
cout<<"\n\n\n";
else
cout<<"\n\n";
}
return 0;
}
I'd recommend the same algorithm I use when solving them myself ;-)
Choose an arbitrary square and list all the valid values for it, based on what is present in all the other rows (there's probably a way to make a more efficient decision about which square to start with).
Then move on to a related empty square (there's probably a way to make a more efficient decision about which square to check next) and store all its possible values.
Rinse and repeat until you find a square that has only one valid value.
Then unzip.
This should sounds like a recursive problem, by now. (note: almost anything that can be done recursively can be done conventionally, but the idea is the same).
So, store up a list of partially solved squares, and when you get to a square that's been solved completely, go back through your list in reverse order re-evaluating your partial solutions with the new data (namely, the one you WERE able to solve).
Rinse and repeat for full body and volume.