Input file not being read from input.txt file - c++

#include <bits/stdc++.h>
#include <iostream>
#include <fstream>
using namespace std;
typedef long long int ll;
int main()
{
istream in("input.txt", "r", stdin);
ofstream out("output.txt", "w", stdout);
int t;
in >> t;
while (t--)
{
ll n;
in >> n;
ll arr[n];
for (int i = 0; i < n; i++)
{
in >> arr[i];
}
sort(arr, arr + n);
double sum = 0;
for (int i = 0; i < n - 1; i++)
{
sum += arr[i];
}
double ans = (sum / (n - 1)) + arr[n - 1];
out << setprecision(9) << ans << endl;
}
return 0;
}
Note that I also changed my tasks.json file.
I changed my code according to what #john and #PepjinKramer said, but my inputs are not being read from the input.txt file and so nothing is shown in output.txt.
How do I solve this problem?

Some feedback to show how to reduce the "cargo cult" content of much C++ code out there :
// #include <bits/stdc++.h> <== NO not standard C++
#include <algorithm> // for sort
#include <iostream>
#include <fstream>
#include <vector> // for resizable arrays
#include <numeric> // for accumulate
#include <iomanip> // for setprecission
// using namespace std; <== NO will become a problem in big projects (nameclashes0
// typedef long long int ll; <== NO just use standard types in code e.g. std::size_t or std::int64_t
int main()
{
//istream in("input.txt", "r", stdin); // reading from file doesn't need anything from stdin
//ofstream out("output.txt", "w", stdout); // writing to a file doesn't need anything from stdout
// std::ifstream input{ "input.txt" };
// std::ofstream output{ "output.txt" };
// for testing manual input
auto& input = std::cin;
auto& output = std::cout;
std::size_t number_of_averages; // give variables more meaningful names then just 't'
std::cout << "input number of averages to calculate = ";
input >> number_of_averages;
for(std::size_t n = 0; n < number_of_averages; ++n )
{
//ll n; NO sizes of containters should be std::size_t not long long
//ll n;
//in >> n;
std::size_t number_of_values;
std::cout << "input number of values = ";
input >> number_of_values;
// ll arr[n]; // NO C++ doesn NOT have variable length arrays, use std::vector
std::vector<double> values(number_of_values);
// for (int i = 0; i < n; i++) // Do NOT use index based loops if you don't have to (out of bound bugs)
//{
// use range based for loops and learn about (const) references
for(auto& value : values)
{
std::cout << "input number : ";
input >> value;
}
// sort(arr, arr + n); // No use iteraters
std::sort(values.begin(), values.end());
// NO for summing collections use <algorithm> accumulate
/*
double sum = 0;
for (int i = 0; i < n - 1; i++)
{
sum += arr[i];
}
*/
auto sum = std::accumulate(values.begin(), values.end(), 0.0);
auto average = sum / static_cast<double>(values.size());
std::cout << "average = ";
output << std::setprecision(9) << average << std::endl;
}
return 0;
}

Related

How to find missing number in array

#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.

Set of Pairs program in C++

I am making a set of pairs of Max and Min elements of Every Subset in an Array.But its giving me these errors. And at last I need Size of set.
(Edited with some suggestions)
In function 'int main()':
27:12: error: 'max_element' was not declared in this scope
27:12: note: suggested alternative: 'max_align_t'
28:12: error: 'min_element' was not declared in this scopeIn function 'int main()':
Code:
#include <iostream>
#include <set>
#include <vector>
#include <utility>
typedef std::pair<int,int> pairs;
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n, max, min;
set<pairs> s;
cin >> n;
int a[n];
for(int i=0;i<n;i++) {
cin >> a[i];
}
for(int i=0;i<n;i++) {
for(int j=i;j<n;j++) {
vector<int> v;
v.push_back(a[j]);
if(v.size() > 1) {
max = *max_element(v.begin(),v.end());
min = *min_element(v.begin(),v.end());
pairs p1 = make_pair(max, min);
s.insert(p1);
max = 0;
min = 0;
}
}
}
cout << s.size() << endl;
}
typedef pair<int,int> pairs;
should be
typedef std::pair<int,int> pairs;
(Or you could move using namespace std; so that it is before your typedef).
Plus typedefing a single pair as the plural pairs is a really really bad idea, that is going to confuse you and anyone else reading your code for the rest of this programs existence. If you want a typedef for a pair of ints, then call it that
typedef std::pair<int,int> pair_of_ints;
To make your last programme works, it was needed to move the declaration of std::vector<int> v;
Moreover, your code has a complexity O(n^3). In practice, it is possible to get a complexity O(n^2), by calculating
iteratively the max and min values.
This code compares your code and the new one. The results are identical. However, I cannot be sure
that your original code does what you intended to do.
#include <iostream>
#include <set>
#include <vector>
#include <utility>
#include <algorithm>
typedef std::pair<int,int> pairs;
//using namespace std;
void print (const std::set<pairs> &s) {
for (auto& p: s) {
std::cout << "(" << p.first << ", " << p.second << ") ";
}
std::cout << "\n";
}
int count_pairs_op (const std::vector<int>& a) {
int max, min;
int n = a.size();
std::set<pairs> s;
for(int i = 0; i < n; i++) {
std::vector<int> v;
for(int j = i; j < n; j++) {
v.push_back(a[j]);
if(v.size() > 1) {
max = *std::max_element(v.begin(), v.end());
min = *std::min_element(v.begin(), v.end());
pairs p1 = std::make_pair(max, min);
s.insert(p1);
}
}
}
print (s);
return s.size();
}
int count_pairs_new (const std::vector<int>& a) {
int max, min;
int n = a.size();
std::set<pairs> s;
for(int i = 0; i < n; i++) {
min = a[i];
max = a[i];
for(int j = i+1; j < n; j++) {
max = std::max (max, a[j]);
min = std::min (min, a[j]);
pairs p1 = std::make_pair(max, min);
s.insert(p1);
}
}
print (s);
return s.size();
}
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
int n;
std::cin >> n;
std::vector<int> a(n);
for(int i = 0; i < n; i++) {
std::cin >> a[i];
}
std::cout << count_pairs_op(a) << std::endl;
std::cout << count_pairs_new(a) << std::endl;
}
It appears that there was a mistake in the understanding of the problem.
For each subarray, we have to consider the maximum and the second maximum.
Moreover, we know that all elements are distinct.
As the size can be up to 10^5, we have to look for a complexity smaller than O(n^2).
In practice, each element can be the second element of two subarrays,
if there exist a greater element before and after it.
We just have to check it.
This can be perfomed by calculating, for each index i, the maximum value before and after it.
Total complexity: O(n)
#include <iostream>
#include <set>
#include <vector>
#include <utility>
#include <algorithm>
int count_pairs_2nd_max (const std::vector<int>& a) {
int n = a.size();
int count = 0;
std::vector<int> max_up(n), max_down(n);
max_up[0] = -1;
for (int i = 1; i < n; ++i) {
max_up[i] = std::max(max_up[i-1], a[i-1]);
}
max_down[n-1] = -1;
for (int i = n-2; i >= 0; --i) {
max_down[i] = std::max(max_down[i+1], a[i+1]);
}
for(int i = 0; i < n; ++i) {
if (max_up[i] > a[i]) count++;
if (max_down[i] > a[i]) count++;
}
return count;
}
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
int n;
std::cin >> n;
std::vector<int> a(n);
for(int i = 0; i < n; i++) {
std::cin >> a[i];
}
std::cout << count_pairs_2nd_max(a) << std::endl;
}

I want to print out the last result done by the loop C++

#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
int i;
int n=0;
int F[10];
F[0]=0;
F[1]=1;
cin>>n;
for(i=2; i<n+1; ++i)
{
F[i]=(F[i-1])+F[i-2];
cout <<F[i]<<endl;
}
getch();
return 0;
}
now this is a sort of a fibonacci number generator, but it outputs all previous numbers in the fibonacci series. I want it to print the last one. For example, if the input is 8, i want it to output "21" instead of 1 2 3 5 8 13 21.
#include <iostream>
#include <conio.h>
int main()
{
int F[10];
F[0] = 0;
F[1] = 1;
int n = 0;
cin >> n;
for (int i = 2; i <= n; ++i)
{
F[i] = F[i-1] + F[i-2];
}
std::cout << F[n] << std::endl;
getch();
}
Since you already know the index of the last element (n), you can just print that after the loop. I also did some other cleanup that didn't change the functionality of the program.
Note that the program originally and still assumes that n is less than 10.
Just store only 2 last values:
#include <iostream>
using namespace std;
int main()
{
int F[2] = { 1, 1 };
int n = 0;
cin>>n;
for(int i=2; i<n; ++i)
{
swap( F[0], F[1] );
F[1] += F[0];
}
std::cout << F[1] << std::endl;
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] << " ";
}
}

Counting Sort infinite loop

I am writing a counting sort function and when I run it, a window pops up saying "filename.exe has stopped working". After debugging it looks like it is getting stuck in the second for loop. What really confuses me, is if I set maxInt to any number greater than 130000 it works, but if its 130000 or lower than I get that error message. The file I'm using to sort only has about 20 numbers.
#include <iterator>
#include <algorithm>
#include <vector>
#include <fstream>
#include <iostream>
using namespace std;
std::string file = "";
std::vector<int> numbers;
void CountingSort(vector<int> &numbers);
int main()
{
std::cout << "Which file would you like to sort?\n";
std::cin >> file;
std::ifstream in(file.c_str());
// Read all the ints from in:
std::copy(std::istream_iterator<int>(in), std::istream_iterator<int>(),
std::back_inserter(numbers));
CountingSort(numbers);
// Print the vector with tab separators:
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\t"));
std::cout << std::endl;
return 0;
}
struct CalcMaxInt
{
int maxInt;
CalcMaxInt () : maxInt(0) {}
void operator () (int i) { if (i > maxInt) maxInt = i; }
};
void CountingSort(vector<int>& numbers)
{
CalcMaxInt cmi = std::for_each(numbers.begin(), numbers.end(), CalcMaxInt());
//int maxInt = cmi.maxInt + 1;
int maxInt = 130001;
vector <int> temp1(maxInt);
vector <int> temp2(maxInt);
for (int i = 0; i < numbers.size(); i++)
{
temp2[numbers[i]] = temp2[numbers[i]] + 1;
}
for (int i = 1; i <= maxInt; i++)
{
temp2[i] = temp2[i] + temp2[i - 1];
}
for (int i = numbers.size() - 1; i >= 0; i--)
{
temp1[temp2[numbers[i]] - 1] = numbers[i];
temp2[numbers[i]] = temp2[numbers[i]] -1;
}
for (int i =0;i<numbers.size();i++)
{
numbers[i]=temp1[i];
}
return;
}
You are trying to access an element out of proper range.
temp2 has range [0...maxInt-1] but the following code uses temp2[maxInt] which is out of range.
for (int i = 1; i <= maxInt; i++)
{
temp2[i] = temp2[i] + temp2[i - 1];
}
You'll have to fix temp2 to have maxInt+1 elements or i < maxInt to not to see the error.
Isn't the whole point of you doing this:
CalcMaxInt cmi = std::for_each(numbers.begin(), numbers.end(), CalcMaxInt());
To get the max element?
I'd change your code to the following.
void CountingSort(vector<int>& numbers)
{
CalcMaxInt cmi;
std::for_each(numbers.begin(), numbers.end(), cmi);
int maxInt = cmi.maxInt;
vector <int> temp1(maxInt);
vector <int> temp2(maxInt);
// then the rest the same starting with the for loops
// but with the fix that #kcm1700 mentioned to the for loop
}
Shouldn't temp1 be dimensioned numbers.size()+1?