How to find missing number in array - c++

#include <iostream>
#include <algorithm>
using std::cin;
using std::cout;
using std::endl;
using std::sort;
int main()
{
int x = 0;
int n; // Enter Size of 2 array
cin >> n; // enter 5
long long *ptr1 = new long long[n - 1]; // size of array must be less than 5 by one n-1
for (int x = 0; x < n - 1; x++)
{
cin >> ptr1[x];
}
sort(ptr1, ptr1 + (n - 1));
for (int z = 1; z < n; z++)
{
if (z != ptr1[x])
{
cout << z;
break;
}
x++;
}
return 0;
}
You're given all positive integers from 1,2,…,n except one integer. Find the missing integer.
Input
The first line of input contains an integer n (2≤n≤2×105).
The second line of input contains n−1 distinct integers from 1 to n (inclusive).
Output
Print the missing integer.
when i try to sumbit this code i get wrong in test 10 but i don't know why! and he didn't show the test so what is wrong?

I have a three-fold answer:
This program leaks memory
You included <algorithm> please use it. (Look on cppreference)
Spoilers vector, iota, mismatch
Also, you don't reset x before the second loop.
That's never going to work unless the missing integer is the last of the array, and not equal to 1
// for (... z)
if (z != ptr1[x] /* Here */) {
// print 1, end loop OR invoke undefined behavior
}
x++; // Now x is equal to (n - 1)

There are some problems with your code:
long long *ptr1 = new long long[n - 1];
You call new, without delete. This will create a memory leak.
You haven't reinitialized x, so any access to ptr1[x] is out-of-bounds.
Slove all of that, and your code will look like:
#include <iostream>
#include <algorithm>
#include <vector>
int main()
{
int n;
cin >> n;
std::vector<int> vec(n-1); // std::vector instead
for (int x = 0; x < n - 1; x++)
{
std::cin >> vec[x];
}
std::sort(vec.begin(), vec.end());
int x = 0; // use another variable instead of reused the old one.
for (int z = 1; z < n; z++)
{
if (z != vec[x])
{
std::cout << z;
break;
}
x++;
}
return 0;
}
But, this isn't the best approach anyway. As #molbdnilo suggest:
#include <iostream>
int main()
{
int n;
std::cin >> n;
int sum{};
for (int i = 0; i < n - 1; ++i)
{
int tmp;
std::cin >> tmp;
sum += tmp;
}
std::cout << (n + 1) * n / 2 - sum;
}

You can solve this in a more straightforward way if you subtract the numbers that were entered from the expected sum of all numbers 1, 2, ..., n (see comments by #molbdnilo, #Aconcagua and #marcus-müller):
#include <iostream>
int main() {
std::size_t n;
std::cin >> n;
std::size_t sum{ n*(n + 1)/2 };
for (std::size_t idx = 1; idx != n; ++idx) {
std::size_t thisNumber;
std::cin >> thisNumber;
sum -= thisNumber;
}
std::cout << "Missing number: " << sum << std::endl;
}

Building blocks:
The expected sum: int expected_sum = n * (n + 1) / 2;
The sum of all integers fed to the test after you've read n:
#include <iterator> // istream_iterator
#include <numeric> // accumulate
int sum = std::accumulate(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>{}, 0);
Now, expected_sum - sum should give you the missing value.

Related

What's wrong in this code , it's doing nothing other than taking inputs of n and m

Here in this question the function call is not executing also tell me abut can't I use array instead of vectors here.
if Possible to use array please provide me with code that how to pass arrays to a function in c++
Here in this question the function call is not executing also tell me abut can't I use array instead of vectors here.
if Possible to use array please provide me with code that how to pass arrays to a function in c++
#include <iostream>
#include <vector>
using namespace std;
int recursion(vector<vector<int>> &v, int n, int m)
{
if (n == 0 && m == 0)
{
return v[n][m];
}
int left = v[n][m] + recursion(v, n - 1, m);
int right = v[n][m] + recursion(v, n, m - 1);
return min(left, right);
}
int main()
{
int n, m;
cout << "enter the value of n and m" << endl;
cin >> n >> m;
cout << n << m;
//it's doing nothing after this point.
vector<vector<int>> vec(n, vector<int>(m));
for (int i = 0; i <= n; i++)
{
for (int j = 0; j <= m; j++)
{
vec[i][j] = (i)*m + (j + 1);
}
}
int result = recursion(vec, n, m);
cout << result;
return 0;
}
vec[i][j] = (i)*m + (j + 1);
is out-of-bounds for i = n and j = m. Same problem with calling recursion(vec, n, m);

Pointer refer different values

I got a problem while solving a beginner c++ challenge in hackerrank.
https://www.hackerrank.com/challenges/variable-sized-arrays/problem
The challenge require me to create an array of int array which simply is a 2d array, but the order of input constraints is so bad that I cannot make it. Suddenly, it pops up to me an idea of creating an array of pointers *arrA that each element refers &arrB[0] of its sub-array arrB.
Note: It is similar to vector<vector<int>> but I would not use vector here.
int main() {
int n, q, k, i, j;
cin >> n >> q;
int *arr[n];
for (int l = 0; l < n; l++) {
cin >> k;
int arr_i[k];
for (int m = 0; m < k; m++) {
cin >> arr_i[m];
}
arr[l] = &arr_i[0];
cout << *arr[l] << " " << arr[l] << endl;
}
// after 2 loop, it prints
// 1 0x7fff17940030
// 2 0x7fff17940020
for (int l = 0; l < q; l++) {
cin >> i >> j;
cout << *arr[l] << " " << arr[l] << endl;
}
// after 2 loop, it prints
// random integer(eg: 395575472) 0x7fff17940030
// random integer(eg: 922493088 ) 0x7fff17940020
return 0;
}
The constraints are:
2 2 // n q
3 1 5 4 // k k[0] k[1] k[2]
5 2 2 8 9 3 // k k[0] k[1] k[2] k[3] k[4]
0 1 // i j
1 3 // i j
Back to the problem, the first loop prints exactly what i need. But in the second loop, the values are missing though the address are the same. I have search many stackoverflow question but none of them meets my needs.
Can someone explain this to me. Many thanks !!!
The scope for int arr_i[k]; is the first loop, and while it's fine to take it's address with arr[l] = &arr_i[0]; those addresses are out of scope when you dereference them in the 2nd loop.
The C++ way to have variable sized arrays is std::vector. And you can have a vector-of-vectors.
Example:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
int main() {
int nrOfVectors, q /* what is q?*/;
std::cin >> nrOfVectors >> q;
std::vector<std::vector<int>> vecvec(nrOfVectors);
for(auto& vec : vecvec) {
int nrOfElements;
std::cin >> nrOfElements;
vec.reserve(nrOfElements);
std::copy_n(std::istream_iterator<int>(std::cin), nrOfElements, back_inserter(vec));
}
}
edit:
An array solution has no added value (actually makes thing unnecessarily complex and error-prone), but whatever
#include <iostream>
#include <memory>
int main() {
int nrOfVectors, q /* what is q?*/;
std::cin >> nrOfVectors >> q;
std::unique_ptr<std::unique_ptr<int[]>[]> vecvec(new std::unique_ptr<int[]>[nrOfVectors]);
for (int i = 0; i < nrOfVectors; ++i) {
int nrOfElements;
std::cin >> nrOfElements;
auto vec = new int[nrOfElements];
for (int j = 0; j < nrOfElements; ++j) {
std::cin >> vec[j];
}
vecvec[i].reset(vec);
}
}

Bad Access on Sieve

My block of code runs, but whenever I type in input, it returns Thread 1: EXC_BAD_ACCESS (code=1, address=0x4). I'm fairly new to coding, and was wondering what's wrong.
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int x, count = 1;
cin >> x;
vector<int> sieve;
fill(sieve.begin(), sieve.begin()+x-1, 1);
while (count <= x) {
for (int i = count+1; i <= x; i++) {
if (sieve[i-1] == 1) {
count = i;
break;
}
}
for (int i = count*count; i < x; i+=count) {
sieve[i-1] = 0;
}
}
for (int i = 0; i < x-1; i++) {
if (sieve[i] == 1) {
cout << i+1 << endl;
}
}
}
You need to allocate space for your sieve. So you might want vector<int> sieve(x). Or, you can even do vector<int> sieve(x, 1), which will allocate space for x ints and fill them all with 1s already, so you won't need the fill afterwards.

Can't increase range of numbers in a program in C++

Here is the question:
Comparing two numbers written in index form like 2^11 and 3^7 is not difficult, as any calculator would confirm that 2^11=2048<3^7=2187.
However, confirming that 632382^518061>519432^525806 would be much more difficult, as both numbers contain over three million digits.
You are given N base exponent pairs, each forming a large number you have to find the Kth smallest number of them. K is 1−indexed.
Input Format
First line containts an integer N, number of base exponent pairs. Followed by N lines each have two space separated integers B and E, representing base and exponent.
Last line contains an integer K, where K<=N
Constraints
1≤N≤105
1≤K≤N
1≤B≤109
1≤E≤109
No two numbers are equal.
Here is my code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N,i = 0,k,j=0,x,m;
long long int *arr,*arr2,*arr3;
cin >> N;
arr = (long long int *)malloc(sizeof(long long int)*2*N);
arr2 = (long long int *)calloc(N,sizeof(long long int));
arr3 = (long long int *)calloc(N,sizeof(long long int));
x = 2*N;
while(x>0)
{
cin >> arr[i];
i++;
x--;
}
cin >> k;
for(i=0;i<2*N;i+=2)
{
arr2[j] = pow(arr[i],arr[i+1]);
j++;
}
arr3 = arr2;
sort(arr2,arr2+N);
for(i=0;i<N;i++)
{
if(arr3[i] == arr2[k-1])
{
m = i;
break;
}
}
cout << arr[2*m] << " " << arr[2*m + 1];
return 0;
}
The program works for small numbers only, can't make it work for large numbers. what to do?
Maybe you are generating an overflow on the big numbers. You could consider using a multiprecision arithmetic library such as https://gmplib.org/. I haven't used this library myself.
Have a look at this post How to detect integer overflow? on how to detect integer overflow.
From your choosing of long long int type I guess you calculated the a^b of the numbers in order to sort them, which leads to very big numbers and may lead to overflow.
Note that in order to sort the numbers there is no need for this calculation, for knowing if a^b > d^c it is sufficient to check log(a^b) > log(c^d) and therefore b*log(a) > d*log(c).
And it's better to use a struct or class to create a data structure for this big numbers.
This is the code for it:
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
struct BigNumber{
int base;
int exponent;
};
int Compare(BigNumber x, BigNumber y);
void Sort(BigNumber* arr, int N);
int main() {
int N,i = 0,k;
BigNumber *numbers;
cout<<"\nEnter N:";
cin >> N;
numbers = (BigNumber *)calloc(N,sizeof(BigNumber));
for(i=0; i<N; i++)
{
cout<<"\nEnter base and exponent for number "<<i<<":";
cin >> numbers[i].base>>numbers[i].exponent;
}
cout<<"\nEnter K:";
cin >> k;
Sort(numbers,N);
cout << "Kth number is :" << numbers[k].base << "^" << numbers[k].exponent;
return 0;
}
void Sort(BigNumber* arr, int N){
for(int i=0; i< N; i++ ){
for(int j=0; j< N; j++){
if(Compare(arr[i], arr[j])<0){
BigNumber temp = arr[j];
arr[j] = arr[i];
arr[i] = arr[j];
}
}
}
}
int Compare(BigNumber x, BigNumber y){
double X = x.exponent * log10(x.base);
double Y = y.exponent * log10(x.base);
return X == Y? 0: X > Y ? 1: -1;
}
I changed the code a little. Only problem I was having was I was calculating the exponent rather than comparing log of exponent.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N,i = 0,k,j=0,x,m;
int *arr;
double *arr2,*arr3;
cin >> N;
arr = (int *)malloc(sizeof(int)*2*N);
arr2 = (double *)calloc(N,sizeof(double));
arr3 = (double *)calloc(N,sizeof(double));
x = 2*N;
while(x>0)
{
cin >> arr[i];
i++;
x--;
}
cin >> k;
for(i=0;i<2*N;i+=2)
{
arr2[j] = arr[i+1]*log10(arr[i]);
j++;
}
for (i = 0; i < N; i++) {
arr3[i] = arr2[i];
}
sort(arr2,arr2+N);
for(i=0;i<N;i++)
{
if(arr3[i] == arr2[k-1])
{
m = i;
break;
}
}
cout << arr[2*m] << " " << arr[2*m + 1];
return 0;
}

Neumann's Random Generator

Please read the task first: http://codeabbey.com/index/task_view/neumanns-random-generator
I have to keep track of the number of iterations, but I get very strange results. In the example after the task we have the numbers 0001 and 4100 and they should come to loop after 2 and 4 iterations. But my results are 1, 4 or if I change the place of the counter 2 or 5 but never 2 and 4. Here is my code:
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
int value;
int counter;
int result;
int setvalue = 1; // use to exit the loop if setvalue == 0;
cin >> n;
vector<int> new_results(0); // use to store all the results from iterations
vector<int> results_vec(0); // use to store the number of iterations for each number
for (int i = 0; i < n ; i++)
{
cin >> value;
while(setvalue == 1)
{
value = value*value;
value = (value % 1000000) / 100;
if(find(results_vec.begin(), results_vec.end(), value) == results_vec.end())
{
results_vec.push_back(value);
}
else
{
counter = results_vec.size();
new_results.push_back(counter);
setvalue = 0;
}
}
results_vec.clear();
}
for (int i = 0; i < new_results.size() ; i++)
{
cout << new_results[i] << " ";
}
}
Going in and out of a string the way you have is really very ugly and extremely expensive computationally.
Use
(value % 1000000) / 100;
instead to extract the middle four digits. This works by (1) taking the modulus to remove the leading two digits then (2) removing the last two with integer division.
As it's so much simpler, I suspect that will fix your bugs too.
Here is the correct code, thank you for all your help.
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n;
int value;
int counter;
int result;
cin >> n;
vector<int> new_results(0); // use to store all the results from iterations
vector<int> results_vec(0); // use to store the number of iterations for each number
for (int i = 0; i < n ; i++)
{
cin >> value;
results_vec.push_back(value);
while(true)
{
value = value*value;
value = (value % 1000000) / 100;
if(find(results_vec.begin(), results_vec.end(), value) == results_vec.end())
{
results_vec.push_back(value);
}
else
{
counter = results_vec.size();
new_results.push_back(counter);
break;
}
}
results_vec.clear();
}
for (int i = 0; i < new_results.size() ; i++)
{
cout << new_results[i] << " ";
}
}