c++ output increasing numbers - c++

Hi I have an array of share prices but I only want to output them as they increase.
For example if I have 1,1,1,2,2,2,3,3,3,4,4,4,5,5,5, etc. I only want to print 1,2,3,4.
I have tried setting a temporary max and min but still can't get it.
Now I only have this:
for(int h = 0; h < max; h++)
{
if(v3[h].getPrice() > 0)
{
ofile << v[h].getPrice() << ", ";
}
}

What you want is this
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
// Assign your vector
int a[] = {1,1,1,2,2,3,3,3,4,4,5,5,5,1,3};
vector<int> vec(a, a+15);
// Sort before calling unique
sort(vec.begin(), vec.end());
// Impose only one of each
vector<int>::iterator it;
it = unique(vec.begin(), vec.end());
vec.resize( distance(vec.begin(),it) );
// Output your vector
for( vector<int>::iterator i = vec.begin(); i!= vec.end(); ++i)
cout << (*i) << endl;
return 0;
}
Live example
The sort is necessary for unique to work.

#include <iostream>
using namespace std;
int main()
{
int a[15] = {1,1,1,2,2,2,3,3,3,4,4,4,5,5,5};
for (int i=0; i<15; i+=3)
{
cout << a[i] <<",";
}
return 0;
}
Increment the counter 3 times in the loop " for(int h=0;h < max; h+=3){} ".

Related

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;
}

Complexity Reduction to O(n) Over Multiple Simultaeneous Vector Iteration

So I have 2 string vectors with the following content:
tokens: name name place thing thing
u_tokens: name place thing
Now my task is to simultaneously loop through both these vectors and find the occurrence of each word and store it in a third vector. Here's a minimal working implementation that I did (my task doesn't mention about duplicates so I did not consider removing it) :
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int> counts;
vector<string> tokens;
vector<string> u_tokens;
tokens.push_back("name");
tokens.push_back("name");
tokens.push_back("place");
tokens.push_back("thing");
tokens.push_back("thing");
u_tokens.push_back("name");
u_tokens.push_back("place");
u_tokens.push_back("thing");
string temp;
int temp_count = 0;
for (int i = 0; i < tokens.size(); i++)
{
temp = tokens[i];
for (int j = 0; j < u_tokens.size(); j++)
{
if(temp == u_tokens[j])
{
temp_count++;
}
}
temp = tokens[i];
for (int k = 0; k < tokens.size(); k++)
{
if (temp == tokens[k])
{
temp_count++;
}
}
counts.push_back(temp_count);
temp_count = 0;
}
for (vector<int>::const_iterator i = counts.begin(); i != counts.end(); ++i)
cout << *i << " ";
return 0;
}
However, I noticed, this obviously has a O(n^2) complexity. How can I reduce it to O(n)? Is it possible?
Regards.
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
using namespace std;
void CountOccurences(const vector<string>& input, unordered_map<string, size_t>& occurences)
{
for (int i = 0; i < input.size(); i++)
{
occurences[input[i]]++;
}
}
int main()
{
vector<string> tokens;
vector<string> u_tokens;
unordered_map<string, size_t> occurences;
tokens.push_back("name");
tokens.push_back("name");
tokens.push_back("place");
tokens.push_back("thing");
tokens.push_back("thing");
u_tokens.push_back("name");
u_tokens.push_back("place");
u_tokens.push_back("thing");
CountOccurences(tokens, occurences);
CountOccurences(u_tokens, occurences);
for (auto i : occurences)
cout << i.first << "=" << i.second << " ";
return 0;
}
Use std::unordered_map as O(1) access container to create O(N) solution. In cost of memory of course.
Link to online compiled program

Size of a vector of pairs

I am filling up an adjacency list of vector with pairs given by :
vector<pair<int, int>> adj[1000];
I am doing a depth first search on the list but experiencing some weird behaviour. The first print statement prints some value which means I have some items in adj[s][0], adj[s][1], adj[s][2] and so on. However when I calculate the size of adj[s] in the next line it prints out to be zero. Am I missing something here?. Is my definition for vector of pairs correct?. The adjacency list is correctly filled because when I ran cout << adj[s][0].first << endl; in dfs, it was correctly showing me the neighbors of each and every node.
Complete code
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <utility>
#include <climits>
#include <algorithm>
using namespace std;
vector<pair<int, int>> adj[1000];
bool visited[1000];
int nodeweight[1000];
void initialize()
{
for(int i = 0; i < 1000; i++)
visited[i] = false;
for(int i=0; i < 1000; i++)
adj[i].clear();
for(int i = 0; i <1000; i++)
nodeweight[i] = INT_MAX;
}
void dfs(int s)
{
visited[s] = true;
cout << adj[s][1].first << endl;
int minimum = INT_MAX, tovisit = 0;
for(int i = 0; i < adj[s].size(); i++)
{
cout << adj[s][i].second;
if(!visited[adj[s][i].first] && adj[s][i].second < minimum)
{
minimum = adj[s][i].second;
tovisit = adj[s][i].first;
}
}
nodeweight[tovisit] = minimum;
//dfs(tovisit);
}
int main() {
int N, E;
cin >> N >> E;
while(E--)
{
int i, j, w;
cin >> i >> j >> w;
adj[i].push_back(make_pair(j,w));
adj[j].push_back(make_pair(i,w));
}
initialize();
for(int i = 1; i <= N; i++)
{
dfs(i);
}
return 0;
}
You are clearing adj again after filling in initialize().
First you fill adj in the while loop in main. Then you call initialize() which includes this loop clearing all vectors in it:
for(int i=0; i < 1000; i++)
adj[i].clear();
Then you have cout << adj[s][1].first << endl; in dfs which is undefined behavior because there are no elements in adj[s]. The fact that you seem to get the correct results is just coincidental undefined behavior (although practical it is because the memory holding the vector data was not cleared.)
adj[s].size() is correctly reported as 0.

Max In a C++ Array

I am trying to find the 'biggest' element in a user made array ,by using the max function from the algorithm library/header.
I have done some research on the cplusplus reference site but there I only saw how to compare two elements using the max function. Instead I am trying to display the maximum number using a function 'max' ,without having to make a 'for' loop to find it.
For example:
Array: array[]={0,1,2,3,5000,5,6,7,8,9}
Highest value: 5000
I have made this code but it gives me a bunch of errors, which can be the issue?
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 10;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
max(array , array + n);
for (int i = 0; i < n; i++)
cout << array[i] << " ";
return 0;
}
max_element is the function you need. It returns an iterator to the max element in given range. You can use it like this:
cout << " max element is: " << *max_element(array , array + n) << endl;
Here you can find more information about this function: http://en.cppreference.com/w/cpp/algorithm/max_element
Here is a modification of your program that does what you want:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int array[11];
int n = 11;
for (int i = 0; i < n; i++) {
array[i] = i;
}
array[5] = 5000;
cout << *std::max_element(array, array + n) << "\n";
return 0;
}
Note that you had a bug in your program, you did not initialize the last element in your array. This would cause your array to contain junk value in the last element. I've fixed that by increasing n to 11. Note that this is OK because the condition in the for loop is i < n, which means that i can be at most 10, which is what you want.
You can also use std::array by #include<array>
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
array<int,10> arr;
int n = 10;
for (int i = 0; i < n; i++) {
arr[i] = i;
}
arr[5] = 5000;
cout<<"Max: "<< *max_element(arr.begin(),arr.end())<<endl;
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
More info on std::array

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?