CodeChef Problems: Minimum Maximum - c++

I can't seem to understand why this code isn't yielding the correct answer on CodeChef. When I run it on my machine. Seems to yield the correct cost
Problem Link: https://www.codechef.com/problems/MNMX
using namespace std;
int main()
{
unsigned int T, N, cost,element,del;
std::cout<<"Enter the Test Cases";
std::cin>>T;
for (unsigned int i=0;i<T;i++){
std::cout<<"Enter the size of the array";
std::cin>>N;
std::cout<<"Enter the values for "<<i+1<<" Test Case"<<endl;
vector<int> first;
std::cout<<"enter the values of the array"<<endl;
for (unsigned int i=0;i<N;i++){
std::cin>>element;
first.push_back(element);
}
if (N>1){
for (unsigned int i=0;i<N;i++){
element = 0;
element = min (first.front() , first[1]);
del = max (first.front() , first[1]);
first.erase(std::remove(first.begin(), first.end(), del), first.end());
first.push_back(element);
}
}
cost = first.front();
std::cout<<"Cost: "<<cost<<endl;
}
return 0;
}

Generally this kind of test cases will not allow your logs to be part of this so please remove all cout statement except last, which you can modify like
std::cout << cost << std::endl;
Try this on codechef.
Or just edit last main output line as above.

Try using different iterator variables in your for-loops, e.g. j and k for the inner loops.

Related

Partition of Array by Element given X

I Am Trying To Find Partition Of Array ,On Condition By Checking Variable x ,when less then x they will be on one side or else on another. but my code need some correction.
HERE am not able to find the error , i will be thankful to you if you help me.
Code is:-
#include<iostream>
using namespace std;
int partition(int arr[],int n,int x){
for(int i=0;i<n;){
if(arr[i]<x){
i++;
}
else if(arr[i]==x){
int temp=arr[i];
arr[i]=arr[n];
arr[n]=temp;
i--;
}
else if(arr[i]>x){
int temp=arr[i];
for(int j=i;j<n;j++){
arr[j]=arr[j+1];
}
arr[n]=temp;
i--;
}
}
return 0;
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
int x;
cin>>x;
partition(arr,n,x);
for(int i=0;i<n;i++){
cout<<arr[i]<<"\t";
}
return 0;
}
Input >> array={2,10,15,1,3,15} ,x=10
Expected << {2,1,3,10,15,15}
Output I get << nothing .
The code isn't giving any output because, first, the "cin" and "cout" are in upper case which is syntactically incorrect, secondly, the variable j is in different case in loop statement and body inside the second else-if clause in the partition function, same goes for the "I" in the first for loop in the main() function. Sort this out and you should be good to go.
First in C++ the size of an array must be a compile-time constant. So for example, consider the following examples:
int n = 10;
int arr[n]; //INCORRECT
The correct way to write the above would be:
const int n = 10;
int arr[n]; //CORRECT
Similarly, in your code,
int n;
cin>>n;
int arr[n]; //INCORRECT because n is not a constant expression
Second, in your code, when you wrote:
arr[n] = temp; Undefined behavior
you're going out of bounds and so you have undefined behavior.
Solution
You can use std::stable_partition and std::vector to solve your problem as shown below:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int n;
std::cout <<"Enter n:"<<std::endl;
std::cin >> n;
std::vector<int> arr(n); //create a vector of size n instead of an array
std::cout<<"Enter elements: "<<std::endl;
//iterate and take input from user
for(int &elem: arr){
std::cin >> elem ;
}
int x;
std::cout << "Enter x: "<<std::endl;
std::cin>>x;
//use std::partition
std::stable_partition(arr.begin(), arr.end(), [x](int i){return (i < x);});
std::cout<<"This is the partitioned vector: "<<std::endl;
for(int i=0;i<n;i++)
{
std::cout<<arr[i]<<"\t";
}
return 0;
}
Output
The output of the above program is as follows:
Enter n:
6
Enter elements:
2
10
15
1
3
15
Enter x:
10
This is the partitioned vector:
2 1 3 10 15 15
which can be seen here.

What is the problem with the logic of the code?

I have been trying to solve this simple problem in C++ but every time I submit, it says wrong answer. I am pretty sure I have got the logic right. Any help is appreciated.
Question: Find the sum of distances between the inputted numbers.
Ex. Input: 2 5 8 2 1
Distance=2+2+5+0
=9, (1 < n < 1000000)
PS: Input can't have the same number consecutively.
PSS: Subtask two is giving Wrong Answer
Code:
#include <iostream>
using namespace std;
int main() {
// your code goes here
int t,a[100000],n,sum=0;
cin>>t;
for(int i=0;i<t;i++)
{
cin>>n;
for(int j=0;j<n;j++)
{
cin>>a[j];
}
for(int j=0;j<n-1;j++)
{
if(a[j]!=a[j+1])
{
sum = sum + abs(a[j]-a[j+1])-1;
}
}
cout<<sum<<endl;
sum=0;
}
}
The problem with your code is that you are using int type for sum whose maximum value (1E11) can exceed the upper limit of int(if it's 32-bit or less). Use long long(atleast 64-bit) instead to store your sum.
Well, you can also optimize the code because you don't exactly need an array of 100000 integers and store the values in it. You can do so using only two variables.
Here is a modified implementation of your logic:
#include <iostream>
int main() {
int t, n, first, second;
long long sum; // or better use std::int_fast64_t sum;
std::cin >> t;
while (t--) {
sum = 0;
std::cin >> n >> first;
for (int i = 0; i < n - 1; ++i) {
std::cin >> second;
sum += std::abs(first - second) - 1;
first = second;
}
std::cout << sum << std::endl;
}
}
PS: In competitive coding checking the provided constraints like if(a[j]!=a[j+1]) is useless. The problem statement simply guarantees it that it will never be false.

Reverse of an array Hackerrank

This is a syntax of a program that I made of hackerrank to reverse an array. The location of the question is Practice < Data Structures < Arrays < Arrays - DS
the program seems to work fine on an online compiler but is showing error over hackerrank.
can anyone guide me where I went wrong?
#include<iostream>
using namespace std;
int main(){
int n,i;
int arr[n];
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=n-1;i>=0;i--)
{
cout<<arr[i];
}
}
You are creating an array with n elements before you read n, i.e n is having garbage value. Here is correct working code.
#include <iostream>
using namespace std;
int main(){
int n,i;
cout<<"Enter number of elements"<<endl; // Comment it if you don't want debug console outut
cin>>n;
int arr[n];
cout<<"Enter "<<n<<" elements"<<endl; // Comment it if you don't want debug console outut
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
for(int i=n-1;i>=0;i--)
{
cout<<arr[i];
}
}
I changed your solution and it work fine now , i will tell you some notes for your future:
1 - You have to read size of array first before declare array as mentioned in comments by #HolyBlackCat , otherwise it will give garbage value.
2 - this command int arr[n]; won't work on all Compilers and may give you an Error. Is there a solution to declare array without specific size ? Yes , you can use Vector like that vector<int> arr(n);but you have to include library of vector first #include<vector>
3 - In C and C++ programs the main function is of type int and therefore it should return an integer value. The return value of the main function is considered the "Exit Status" of the application. On most operating systems returning 0 is a success status like saying "The program worked fine". So you have to write return 0; in the end of your program.
#include<iostream>
#include<vector> // must include to use Vectors
using namespace std;
int main(){
int n;
cin >> n; // Must read size of array first , otherwise it will give it garbude value
vector<int> arr(n); // instead of int arr[n]
for(int i = 0 ; i < n ; i++)
cin >> arr[i];
for(int i = n-1 ; i >= 0 ; i--)
cout << arr[i] << " ";
cout << endl; // to print new line as mentioned in the problem statement
return 0; // Prefer to use it always
}
Hope that helps you and Good Luck.
The exercise of Hacker Rank needs that you reverse an array of integers, might you have a problem with the variable size array, cause some compilers support this characteristic but others not.
And Hacker Rank do not support some properties in other languages like JS , Hacker Rank do not support prompt() for take an input.
In any case for fix this error you can use vector class.
#include<iostream>
#include<vector>//Include library vector for dynamic size of array
using namespace std;
int main(){
int n;
cin>>n;
vector<int> arr(n);//Declare the vector with a max size n
for(int i=0;i<n;i++){
cin>>arr[i];
}
for(int i = n-1 ;i>=0;i--){
cout<<arr[i]<<" ";
}
return 0;
}
This code has passed al test cases of hackerRank
All the test on hackerRank had passed

LeetCode TwoSum solution not working

#include<stdio.h>
#include<conio.h>
#include<iostream.h>
int bins(int* p,int lo,int hi,int t)
{//BinarySearch
int mid=0;
int c=0;
if(lo<hi)
{
mid=(lo+hi)/2;
if(p[mid]==t) c=1;
else if(t>p[mid])
bins(p,mid+1,hi,t);
else if(t<p[mid])
bins(p,0,mid,t);
}
return c;
}
int main()
{
clrscr();
int target;
int k;
int count=0;
cout<<"Enter the number of elements:";
cin>>k;
int* numbers=new int(k);
cout<<"Enter the target element"<<endl;
cin>>target;
cout<<"Enter the elements:"<<endl;
for(int i=0;i<k;i++)
cin>>numbers[i];
int* nu=new int(k);
memset(nu,0,sizeof(int));
/*for(i=0;i<k;i++){
cout<<numbers[i]<<endl;
}*/
for(i=0;i<k;i++)
{
int bool=bins(nu,0,k,numbers[i]);
//printf("%d\n",bool);
if(bool)
{
count++;
}
else
{
int tg=target-numbers[i];
cout<<"targetval:"<<tg<<endl;
nu[i]=tg;
}
//bool?count++:(nu[i]=target-numbers[i]);
}
cout<<"Count is:"<<count<<endl;
getch();
return 0;
}
this is the code i have written for TwoSum problem in leetcode,instead of using HashMap whose time complexity is O(n) i used binary search whose complexity is O(logn)
The problem i'm facing is the input i give to the array numbers[i] takes only 3 values and from then it stores junk values even after assigining proper inputs from console
this program has been compiled succesfully on Turbocompiler on system
int* numbers=new int[k];////allocates an array of k adjacent integers. (undefined values)
You are allocating for an array. Check the notations.
Also you are using a keyword as a variable.(bool).
What have you done?
int *numbers=new int(k);////allocates an integer, set to k. (same syntax as constructors)
Leetcode doesn't give exact code. It will have syntax errors or compilation erros. You have to fix them to make it work. In this case, following are the issues,
int* numbers=new int[k]; //not int* numbers=new int(k);
Another thing is that bool is a keyword, that is used to give true or false for variables. You have to use another variable.

how to count in recurrsive function?

Here is my code for printing the divisors and then number of divisors of a given number.
Now suppose I take 2 test cases: 5 and 8; this code gives count of 5 as 2 and 8 as 6 (i.e it adds the previous count).
Even if I declare it as int count = 0; it returns the same output.
The other problem arises when I declare int count = 0 inside function factors.
The code gives count as 0 for all cases.
#include<iostream>
using namespace std;
int count;
long long factors(long n, long f=1)
{
if(n%f==0) {
cout << f << endl;
count++;
}
if(f==n) {
return 0;
}
factors(n,f+1);
return count;
}
int main()
{
int n;
int t;
cin >> t;
while(t--)
{
cin >> n;
cout << factors(n) << endl;
}
return 0;
}
Using globals is not usually a good idea. It is especially bad in recursive functions, which should preferably be re-entrant. Of course you can fix your function by resetting the count in the loop, like this:
while(t--)
{
cin>>n;
count = 0; // Reset count before the recursive call
cout << factors(n) << endl;
}
You could also make factors "wrapper" that resets the count to free the callers from the need to reset count before calling factors, like this:
long long factors(long n) {
count = 0;
return factors(n, 1);
}
long long factors(long n,long f /* Remove the default */) {
... // the rest of your code
}
you can achieve this by passing count as reference -
#include<iostream>
using namespace std;
long long factors(long n, int& count, long f=1)
{
if(n%f==0)
{
cout<<f<<endl;
count = count + 1;
}
if(f==n)
return 0;
factors(n, count, f+1);
return 0;
}
int main()
{
int n,t;
cin>>t;
while(t--)
{
cin>>n;
int count = 0;
factors(n, count);
cout << count << endl;
}
return 0;
}
-Gaurav
First, why are you declaring the count variable in the global space?
Second, you can not perform arithmetic operations to an undeclared variable (the int "count" in this case is never declared).
Third, why do you create an infinite loop by doing while(t--)?
You said the function gives you count as 0 for all input,
Can this be due to count never being declared?