I'm tackling with a problem where I have to find the minimum number as well as the points such that all the given line segments would have atleast one point in their span.
Input is of the format - number of line segments followed by start,finish of each.
Output required is of the form - number of points along with its value
My approach: I am sorting the line segments in ascending order of finish values, iterating over them, adding them to the output list: and then comparing line segment start points with that end point. If the given start point is <=, we remove that start,end pair.
My code:
#include <algorithm>
#include <iostream>
#include <climits>
#include <vector>
using std::vector;
struct Segment {
int start, end;
};
struct less_than_key
{
inline bool operator() (const Segment& struct1, const Segment& struct2)
{
return (struct1.end < struct2.end);
}
};
vector<int> optimal_points(vector<Segment> &segments) {
vector<int> points;
sort(segments.begin(),segments.end(),less_than_key());
vector<Segment> ss = segments;
vector<int> output;
int p=0;
int t=0;
while(segments.size()!=0)
{
int m = segments[p].end;
int q=0;
output.push_back(m);
while(t==0)
{
if(q>=segments.size())
{
t=t+1;
continue;
}
if(segments[q].start<=m)
{
segments.erase(segments.begin()+q);
q=q-1;
}
q=q+1;
}
}
return output;
}
int main() {
int n;
std::cin >> n;
vector<Segment> segments(n);
for (size_t i = 0; i < segments.size(); ++i) {
std::cin >> segments[i].start >> segments[i].end;
}
vector<int> points = optimal_points(segments);
std::cout << points.size() << "\n";
for (size_t i = 0; i < points.size(); ++i) {
std::cout << points[i] << " ";
}
}
This code is working for very particular inputs and resulting in infinite loops in some. The logic should work perfectly on paper but my code is bugging out somewhere.
Running data -
Input -
3
1 3
2 5
3 6
Output -
1
3
Works correctly as the point 3 will result in each segment having a point.
Related
So I need to combine a specific number (not string) of digits from a vector of possible ones (all 0-9, not characters) in an N-digit number (not binary, then). However, I cannot have any extra permutations appear: for example 1234, 4321, 3124... are now the same and cannot be all outputed. Only one can be. This is hard because other questions cover these permutions by using std::next_permutation, but I still need the different combinations. My attempts at trying to remove permutations have failed, so how do you do this? Here is my current code with comments:
#include <iostream>
#include <vector>
using namespace std;
#define ll long long
int n = 0, m = 0, temp; //n is number of available digits
//m is the length of the desired numbers
//temp is used to cin
vector <int> given;
//vector of digits that can be used
vector <int> num;
//the vector to contain a created valid number
void generate(vector <int> vec, int m) {
//recursive function to generate all numbers
if (m == 0) {
for (int x : num) {
cout << x;
}
cout << '\n';
return;
}
for (int i = 0; i < given.size(); i++) {
num.push_back(given[i]); //add digit to number
int save = given[i];
given.erase(given.begin() + i);
//no repeating digits, save the used one and delete
//however, permutations can still pass, which is undesirable
generate(vec, m - 1);
//recursive
num.pop_back();
//undo move
given.insert(given.begin() + i, save);
//redo insert deleted digit
}
}
int main () {
cin >> n;
//input number of available digits
for (int i = 0; i < n; i++) {
cin >> temp;
given.push_back(temp); //input digits
}
cin >> m;
//input length of valid numbers
generate(given, m); //start recursive generation function
return 0;
}
I tried deleting permutations before printing them and erasing more digits to stop generating permutations, but they all failed. Lots of other questions still used std::next_permutation, which was not helpful.
Unlike some people who suggested binary strings in some comments, you can begin by having a recursive function that can go two ways as an on/off switch to decide whether or not to include a given digit. I personally like using a recursive function to do this and a check for length at the end to actually print the number of the desired len, demonstrated in the code below:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int givencount = 0, temp = 0, len = 0;
vector <int> given;
string creatednum;
void generate(int m) {
if (m == givencount) {
if (creatednum.length() == len) {
cout << creatednum << '\n';
}
return;
}
for (int i = 0; i < 2; i++) {
if (i == 1) {
generate(m + 1);
continue;
}
creatednum = creatednum + ((char) ('0' + given[m]));
generate(m + 1);
creatednum.erase(creatednum.begin() + creatednum.length() - 1);
}
}
int main () {
cin >> givencount;
for (int i = 0; i < givencount; i++) {
cin >> temp;
given.push_back(temp);
}
cin >> len;
generate(0);
return 0;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I have ant task, to search most frequent odd number in vector array. I cant figure it out.
this is, how i am writing data, to array
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
class oddNum {
private:
vector <int> numbers;
int number, n;
public:
void getData() {
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> number;
if(number % 2 != 0) {
numbers.push_back(number);
}
}
}
};
int main() {
oddNum n;
n.getData();
return 0;
}
my numbers
8 5 5 1 3
There are several ways to do it, I show you two. The first one is not intuitive and requires quite the bookmarking. However, the last solution uses the modern containers and their nature to do this in an elegant style.
First you sort the vector. This way all equal elements are next to each other. Than you iterate through this vector to look for the largest pack of elements while skipping all even numbers. Create a variable counter which resets if the elements change (this can be done by comparing the current element to the next element of the array) and a max variable that holds the largest value of said counter. Whenever this counter exceeds the value of max you have found the most common element so far which can be saved in a variable result. When you're done iterating, the variable result will contain the most frequent odd element of the vector. This implementation, in addition to <vector>, also needs the <algorithm> and <cassert> headers.
int get_most_frequent_odd(const std::vector<int>& vec) {
assert(!vec.empty());
std::vector<int> sorted = vec;
std::sort(sorted.begin(), sorted.end());
unsigned counter = 0u;
unsigned max = 0u;
int result;
for (unsigned i = 0u; i < sorted.size() - 1; ++i) {
if (sorted[i] % 2 != 0) {
if (sorted[i] == sorted[i + 1]) {
++counter;
if (max < counter) {
max = counter;
counter = 0u;
result = sorted[i];
}
}
else {
counter = 0u;
}
}
}
return result;
}
The function is quite specific (only for int's and odd elements). Also your getData() function already sorts out all even numbers. So here's a more generic function get_most_frequent<T>:
template<typename T>
T get_most_frequent(const std::vector<T>& vec) {
assert(!vec.empty());
std::vector<T> sorted = vec;
std::sort(sorted.begin(), sorted.end());
unsigned counter = 0u;
unsigned max = 0u;
T result;
for (unsigned i = 0u; i < sorted.size() - 1; ++i){
if (sorted[i] == sorted[i + 1]) {
++counter;
if (max < counter) {
max = counter;
counter = 0u;
result = sorted[i];
}
}
else {
counter = 0u;
}
}
return result;
}
Now a std::unordered_map or std::map will be superior over a std::vector for this task as they are build in a way that allows you to skip this ugly bookmarking. It's way more readable, too. But given you said you are a beginner I didn't put this at first place. The idea is to count the frequency by using a std::unordered_map. The elements are set to be the keys of the map and incrementing the values behind the keys will give you the occurrency of the elements. (Thanks #YSC) You can now use std::max_element which will return the pair with the highest saved occurrence. This implementation requires the <unordered_map>, <utility>, <algorithm> and <cassert> headers.
template<typename T>
T get_most_frequent(const std::vector<T>& vec) {
std::unordered_map<T, int> frequency_map;
for (auto i : vec) {
++frequency_map[i];
}
return std::max_element(frequency_map.begin(), frequency_map.end())->first;
}
example run using either of these 3 functions:
how many numbers?: 8
input number 1: 5
input number 2: 5
input number 3: 4
input number 4: 9
input number 5: 9
input number 6: 9
input number 7: 11
input number 8: 0
most common element is: 9
full code:
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <cassert>
template<typename T>
T get_most_frequent(const std::vector<T>& vec) {
std::unordered_map<T, int> frequency_map;
for (auto i : vec) {
++frequency_map[i];
}
return std::max_element(frequency_map.begin(), frequency_map.end())->first;
}
class oddNum {
private:
std::vector<int> numbers;
public:
void getData() {
std::size_t size;
std::cout << "how many numbers?: ";
std::cin >> size;
int number;
for (int i = 0; i < size; ++i) {
std::cout << "input number " << i + 1 << ": ";
std::cin >> number;
if (number % 2 != 0) {
numbers.push_back(number);
}
}
std::cout << "most common element is: " << get_most_frequent(numbers) << '\n';
}
};
int main() {
oddNum n;
n.getData();
}
I am a new in C++ and have difficulties in importing specific data (numbers) from the file.
My input looks like:
Open High Low Close
1.11476 1.11709 1.10426 1.10533
1.10532 1.11212 1.10321 1.10836
1.10834 1.11177 1.10649 1.11139
1.09946 1.10955 1.09691 1.10556
1.10757 1.11254 1.09914 1.10361
1.10359 1.12162 1.10301 1.11595
1.09995 1.10851 1.09652 1.10097
I use the following code which works fine for me to read the second column entirely, however I need to read specific data only. For example the third row/ third column which is 1.10649How can I read specific data? Do I need to use the string to get the row/column and then convert it to int in order to read it in a vector? I am open for any suggestions and would be greatly appreciated if any could help me with this issue.
// Data import 2nd Column
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <vector>
using namespace std;
int main()
{
const int columns = 4;
vector< vector <double> > data;
ifstream market_data("market_data.txt");
if (market_data.is_open()) {
double num;
vector <double> line;
while (market_data >> num) {
line.push_back(num);
if (line.size() == columns) {
data.push_back(line);
line.clear();
}
}
}
vector <double> column;
double col = 2;
for (double i = 0; i < data.size(); ++i) {
column.push_back(data[i][col - 1]);
cout << column[i] << endl;
}
system ("pause");
return 0;
}
You need to use a integer value for indexing (size_t to be precise), change
for (double i = 0; i < data.size(); ++i) {
to
for( size_t i = 0; i < data.size(); ++i) {
// ^^^^^^
Otherwise everything seems fine from your code sample.
If your numbers will always contain 7 characters (i assume it's not binary file), then you could make this simple.
Use seekg() method of ifstream.
Each number fills 10 characters (7 of number, 3 spaces). So, if you have table ROWS x COLUMNS, then to get specific number, you can do this:
const int ROW_LEN = 4
const int DATA_LEN = 10
...
int row,column;
double num;
std::cin >> row; //assume first row is 0
std::cin >> column //assume first column is 0
marked_data.seekg((column*ROW_LEN + row)*DATA_LEN);
marked_data >> num // here is your number
Thank you for replies.. I have solved the issue. So instead of:
vector <double> column;
double col = 2;
for (double i = 0; i < data.size(); ++i) {
column.push_back(data[i][col - 1]);
cout << column[i] << endl;
}
enough to write:
cout << data[2][2] << endl;
My problem looks like this:
At the beginning u have to insert an amount of numbers.
Next program counts the sum of digits of the number that u inserted in step one.
All scores are inserted in vector called vec
The problem is this: At the end of the program all numbers that You inserted in steps 1, must be sorted depends of theirs sums of digits(Sorting in increasing order).
And ATTENTION please! For example if two of numbers(e.g. 123 and 12300) have the same sum of digits you have to sort them by the lexicographic order.
I don't want to create function build by myself but I would like to use “sort” function from library but I have problem with that..Is it possible to use sort function also to sorting by the lexicographic order? Can someone can help me?
Example input:
6
13
36
27
12
4
123
Expected output:
12
13
4
123
27
36
My code:
#include<iostream>
#include<cmath>
#include<string>
#include<vector>
#include<sstream>
#include<algorithm>
using namespace std;
int main()
{
vector<vector<int> > vec;
int num;
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> num;
vector<int> row;
row.push_back(num);
//conversion int to string:
ostringstream ss;
ss << num;
string str = ss.str();
int sum = 0;
for (int g = 0; g < str.length(); g++){
int pom = str[g] - '0';
sum += pom;
}
row.push_back(sum);
vec.push_back(row);
row.clear();
}
//sort(vec[0][0], vec[vec.size()][0]);
for (int i = 0; i < vec.size(); i++){
for (int j = 0; j < 2; j++){
//cout << vec[i][j] << " ";
}
cout << vec[i][0] << endl;
}
system("pause");
return 0;
}
You could store each number as a string, but also pre-compute its digit-sum and keep both in a pair<int,string>, then put them into a vector<pair<int,string> and sort it. No need for a custom comparator, the one for std::pair does exactly what you want.
// note: std::pair<std::string,int> would not work
typedef std::pair<int,std::string> number;
std::vector<number> numbers;
// fill numbers such that number::first holds the digit sum
// and number::second the number as string.
// this is similar to your code
std::sort(numbers.begin(), numbers.end());
// now numbers are ordered as you want them
Just pass a suitable comparison function (or functor, e.g. a lambda would be natural) to std::sort.
Since you want to compare on sum of digits first and then lexicographically to break ties, it will be convenient to convert your input numbers to strings.
From there you can define a custom comparator to achieve the desired behavior:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int sumDigits(string s)
{
int sum = 0;
for (unsigned int i=0; i<s.length(); ++i)
{
sum += s[i] - '0';
}
return sum;
}
bool digitSumComparator(int i, int j)
{
int iSum = sumDigits(to_string(i));
int jSum = sumDigits(to_string(j));
if (iSum == jSum)
{
return iStr < jStr;
}
else
{
return iSum < jSum;
}
}
int main()
{
vector<int> v {6,13,36,27,12,4,123};
sort(v.begin(), v.end(), digitSumComparator);
for (vector<int>::iterator it=v.begin(); it!=v.end(); ++it)
{
cout << *it << ' ';
}
cout << '\n';
return 0;
}
Output:
$ g++ -std=c++11 digitsumsort.cpp
$ ./a.out
12 13 4 123 6 27 36
So I wanted to clean the rust off my C++ skills and thought I'd start with something fairly simple. An equilibrium point in a vector A of size N is a point K, such that: A[0] + A[1] + ... + A[K−1] = A[K+1] + ... + A[N−2] + A[N−1]. The rationale behind the function algorithm is simple: Check each consecutive element of the vector and compare the sum of the elements before said element with the sum of the elements after it and if they are equal, output the index of that element. While it sounds simple (and I imagine that it is) it turned out to be harder to implement in reality. Here's what the code looks like:
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
void EquilibriumPoint(std::vector<int> &A);
void VectorPrint(std::vector<int> &V);
void main()
{
int input;
std::vector<int> Vect1;
cout << "Input the vector elements" << endl;
while (cin >> input)
Vect1.push_back(input);
VectorPrint(Vect1);
EquilibriumPoint(Vect1);
}
void EquilibriumPoint(std::vector<int> &A)
{
for (int it = 0; it != A.size(); ++it)
{
int lowersum = 0;
int uppersum = 0;
for (int beg = 0; beg != it; ++beg) lowersum += A[beg];
for (int end = it + 1; end != A.size(); ++end) uppersum += A[end];
if (uppersum == lowersum) cout << it;
}
}
void VectorPrint(std::vector<int> &V)
{
for (int i = 0; i != V.size(); ++i)
cout << V[i] << endl;
}
As you can see I threw in a print function also for good measure. The problem is that the program doesn't seem to execute the EquilibriumPoint function. There must be a problem with the logic of the implementation but I can't find it. Do you guys have any suggestions?
cin >> input
always returns true for you - so IMHO you have an endless loop. You need to stop collecting elements at some point, for instance
int input = 1
while (input)
{
cin >> input;
Vect1.push_back(input);
}
Will accept all elements that are not zero, when zero arrives, it will end the vector and run your function.
Or you can first input the number of elements (if you want to include zeros), example:
int count;
cin >> count
for (int i = 0; i < count; ++i)
{
cin >> input;
Vect1.push_back(input);
}
I didn't check the rest of the code, though. One problem at a time.