Sorting doesn't seem to work - c++

This code is written in C++. I've the following structure:
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
struct Data
{
int h, b, w;
Data(int _h, int _b, int _w) : h(_h), b(_b), w(_w)
{}
bool operator<(const Data& other) const
{
bool overlap = (other.b >= b && other.b <= w) ||
(other.w >= b && other.w <= w) ||
(other.b < b && other.w > w);
if (overlap)
{
return h < other.h;
}
return h > other.h;
}
};
The operator< will be used for sorting. The idea is to sort from highest-h to lowest-h, unless there is any overlapping between either b or w in comparing variables. Remaining code:
vector <int> getOrdering(vector <int> height, vector <int> bloom, vector <int> wilt)
{
vector<Data> vdata;
for (int i = 0; i < height.size(); i++)
{
vdata.push_back(Data(height[i], bloom[i], wilt[i]));
}
sort(vdata.begin(), vdata.end());
vector<int> ans;
for (Data data : vdata)
{
ans.push_back(data.h);
}
return ans;
}
int main()
{
vector <int> p0 = { 1, 2, 3, 4, 5, 6 };
vector <int> p1 = { 1, 3, 1, 3, 1, 3 };
vector <int> p2 = { 2, 4, 2, 4, 2, 4 };
vector<int> ans = getOrdering(p0, p1, p2);
for (int a : ans)
{
cout << a << ' ';
}
cout << endl;
return 0;
}
The way the I've written the operator< function, the code should output 2 4 6 1 3 5. But the output is 6 5 4 3 2 1. I'm using Visual Studio 2013 Ultimate.
After debugging the operator< function, I found out that it is being called for Data object as follows:
1st call: this->h = 2, other.h = 1
2nd call: this->h = 1, other.h = 2
3rd call: this->h = 3, other.h = 2
4th call: this->h = 2, other.h = 3
5th call: this->h = 4, other.h = 3
6th call: this->h = 3, other.h = 4
7th call: this->h = 5, other.h = 4
8th call: this->h = 4, other.h = 5
9th call: this->h = 6, other.h = 5
10th call: this->h = 5, other.h = 6
Note that when Data objects' h values are 1, 3 or 5, their b and w values are same. They will be sorted by ascending order of h. Same goes true for Data objects whose h values are 2, 4 and 6. But in the operator<() no two Data objects are ever compared whose h values are same! 1 compared to 2, 2 compared to 3, 3 compared to 4 and so on. So the overlap variable is always false. The outcome of sort() would be different if Data objects whose h values are same got compared - but that never happened!
Any explanation of this behavior of compiler?

It is because your operator< depends a lot of the data order. If we run you're algorithm with your data, it's the expected output.
The first comparaison is between Data(1,1,2) and Data(2,3,4). According to your operator<, Data(2,3,4) is the lower so the temp order is [Data(2,3,4), Data(1,1,2)]
Then, Data(3,1,2) comes and is compared against the lowest value of the current sorted list, so Data(2,3,4). Again, according to your operator<, Data(3,1,2) is lower so no need to compare against the other values in the list and the new temp ordered list is [Data(3,1,2),Data(2,3,4), Data(1,1,2)].
Then it's the same for each other value, they are each time only compared to the first value in the list since they are lower (according to operator<) and so put in front of the sorted list.
If you change your init list order with:
vector <int> p0 = { 6, 5, 4, 3, 2, 1};
vector <int> p1 = { 3, 1, 3, 1, 3, 1};
vector <int> p2 = { 4, 2, 4, 2, 4, 2};
you'll have the expected output since there will be more comparaison involved.
But the fact that the result depend on the init order show there is clearly a flaw in your operator< function.

Related

Find base period of sequence in C++

For a sequence of numbers a1, a2,...,an, we say that there is a period if 1≤p<n and if it holds that it is ai=ai+p for all values for which this equality makes sense.
For example, the sequence of numbers 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 has period 5, because ai=ai+5 for all values such that both indices i and i+5 are within the allowable range (i.e. for 1 to 7 inclusive). The same sequence also has a period of 10. Next, we say that the sequence of numbers is periodic if it exists at least one number that is the period of that sequence, with the smallest such number being called the base sequence period. If such a number does not exist, the sequence is not periodic. For example, the above the sequence of numbers is periodic with the base period 5, while the sequence of numbers 4, 5, 1, 7, 1, 5 is not periodic.
#include <iostream>
#include <vector>
int period(std::vector<double> vektor) {
int p;
for (int i : vektor) {
for (int j : vektor) {
if (vektor[i] == vektor[j])
p = j;
}
}
return p;
}
int main() {
std::vector<double> vektor{1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3};
std::cout << period(vektor);
return 0;
}
This should be solved using vector.
Could you help me fix this code? This returns 3 as base period of sequence.
For starters it is unclear why you are using a vector with the value type double instead of the type int when all initializers have the type int.
The function period should accept a vector by constant reference.
The variable p is not initialized. As a result the function can return an indeterminate value.
The range based for loop does not return indices in a container as you think
for (int i : vektor) {
It returns stored in the vector objects of the type double.
So the condition in the if statement
if (vektor[i] == vektor[j])
makes no sense.
The function can look the following way as it is shown in the demonstration program below.
#include <iostream>
#include <vector>
size_t period( const std::vector<double> &v )
{
size_t p = 0;
for (size_t i = 1; !p && i < v.size(); i++)
{
size_t j = 0;
while (j < v.size() - i && v[j] == v[j + i]) ++j;
if ( j + i == v.size() ) p = i;
}
return p;
}
int main()
{
std::vector<double> v = { 1, 3, 1, 4, 2, 1, 3, 1, 4, 2, 1, 3 };
std::cout << period( v ) << '\n';
}
The program output is
5

Time complexity of the travelling salesman problem (Recursive formulation)

According to this recursion formula for dynamic programming (Held–Karp algorithm), the minimum cost can be found. I entered this code in C ++ and this was achieved (neighbor vector is the same set and v is cost matrix):
recursion formula :
C(i,S) = min { d(i,j) + C(j,S-{j}) }
my code :
#include <iostream>
#include <vector>
#define INF 99999
using namespace std;
vector<vector<int>> v{ { 0, 4, 1, 3 },{ 4, 0, 2, 1 },{ 1, 2, 0, 5 },{ 3, 1, 5, 0 } };
vector<int> erase(vector<int> v, int j)
{
v.erase(v.begin() + j);
vector<int> vv = v;
return vv;
}
int TSP(vector<int> neighbor, int index)
{
if (neighbor.size() == 0)
return v[index][0];
int min = INF;
for (int j = 0; j < neighbor.size(); j++)
{
int cost = v[index][neighbor[j]] + TSP(erase(neighbor, j), neighbor[j]);
if (cost < min)
min = cost;
}
return min;
}
int main()
{
vector<int> neighbor{ 1, 2, 3 };
cout << TSP(neighbor, 0) << endl;
return 0;
}
In fact, the erase function removes the element j from the set (which is the neighbor vector)
I know about dynamic programming that prevents duplicate calculations (like the Fibonacci function) but it does not have duplicate calculations because if we draw the tree of this function we see that the arguments of function (i.e. S and i in formula and like the picture below) are never the same and there is no duplicate calculation.
My question is, is this time O(n!)?
picture :
If yes,why? This function is exactly the same as the formula and it does exactly the same thing. Where is the problem? Is it doing duplicate calculations?
Your algorithm time complexity is O(n!). It's easy to understand that your code is guessing the next node of the path. And there're exactly n! different paths. Your code actually counts the same value several times. For example if you run TSP({1, 2, 3, 4}, 0) and it tries order {1, 2, 3} and {2, 1, 3}. It is clear that code will run TSP({4}, 3) two times. To get rid of this store already calculated answers for masks and start node.

Product modulo random numbers

A prime p is fixed. A sequence of n numbers is given, each from 1 to p - 1. It is known that the numbers in the sequence are chosen randomly, equally likely and independently from each other. Choose some numbers from the sequence so that their product, taken modulo p, is equal to the given number x. If no numbers are selected, the product is considered equal to one.
Input:
The first line contains three integers separated by spaces: the length of the sequence n, the prime number p and the desired value x
(n=100, 2<=p<=10^9, 0<x<p)
Next, n integers are written, separated by spaces or line breaks: the sequence a1, a2,. . ., an
(0 <ai <p)
Output:
Print the numbers from the sequence whose product modulo p is equal to x. The order in which numbers are displayed is not important. If there are several possible answers, print any of them
Example:
INPUT:
100 11 4
9 6 1 1 10 4 9 10 3 1 10 1 6 8 3 3 9 8
10 3 7 7 1 3 3 1 5 2 10 4 1 5 6 7 2 6
2 8 3 3 6 7 6 3 1 5 10 2 2 10 9 6 8 6
2 10 3 2 7 4 3 2 8 6 4 1 7 2 10 8 4 9
7 9 8 7 4 7 3 2 8 2 3 7 1 5 2 10 7 1 8
6 4 10 10 3 6 10 2 1
OUTPUT:
4 6 10 9
My solution:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int n,p,x,y,m,k,tmp;
vector<int> v;
cin >> n >> p >> x;
for (int i = 0; i<n; i++){
cin >> tmp;
v.push_back(tmp);
}
sort(v.begin(), v.end());
v.erase(v.begin(), upper_bound(v.begin(), v.end(), 1));
k=-1;
while(1){
k++;
m = 1;
y = x+p*k;;
vector<int> res;
for (int i = 0; i<n; i++){
if (y == 1) break;
if ( y%v[i] == 0){
res.push_back(v[i]);
m*=v[i];
m%=p;
y = y/v[i];
}
}
if (m==x) {
for (int i = 0; i<res.size(); i++){
cout << res[i] << " ";
}
break;
}
}
return 0;
}
In my solution, I used condition (y=x+k*p, where y is the product of numbers in the answer, and k is some kind of natural number). And also iterated over the value k.
This solution sometimes goes beyond the allotted time. Please tell me a more correct algorithm.
I would consider a backtracking routine over the hashed multiset of the input list. Since p is a prime, at any point we can consider if the current multiple, m, has (multiplicative_inverse(m, p) * x) % p in our multiset (https://en.wikipedia.org/wiki/Multiplicative_inverse). If it exists, we're done. Otherwise, try multiplying either by the same number we are currently visiting in the multiset, or by the next one (keep the result of the multiplication modulo p).
Please see comment below for a link to example code in Python. The example you gave has trivial solutions so it would be helpful to have some non-trivial, as well as challenging examples to test and refine on. Please also clarify if more than one number is expected in the output.
You can use dynamic programming approach. It requires O(p) memory cells and O(p*n) loop iterations. There is possible several optimization (to exclude processing input duplicates, or print longest/shortest selection chain). Following is simplest and basic DP-program, demonstrating this approach.
#include <stdio.h>
#include <stdlib.h>
int data[] = {
9, 6, 1, 1, 10, 4, 9, 10, 3, 1, 10, 1, 6, 8, 3, 3, 9, 8,
10, 3, 7, 7, 1, 3, 3, 1, 5, 2, 10, 4, 1, 5, 6, 7, 2, 6,
2, 8, 3, 3, 6, 7, 6, 3, 1, 5, 10, 2, 2, 10, 9, 6, 8, 6,
2, 10, 3, 2, 7, 4, 3, 2, 8, 6, 4, 1, 7, 2, 10, 8, 4, 9,
7, 9, 8, 7, 4, 7, 3, 2, 8, 2, 3, 7, 1, 5, 2, 10, 7, 1, 8,
6, 4, 10, 10, 3, 6, 10, 2, 1
};
struct elm {
int val; // Value
int prev; // from which elemet we come to this
int n; // add loop cound for prevent multiple use same val
};
void printsol(int n, int p, int x, const int *in) {
struct elm *dp = (struct elm *)calloc(p, sizeof(struct elm));
int i, j;
for(i = 0; i < n; i++) // add initial elements into DP array
dp[in[i]].val = in[i];
for(i = 0; i < n; i++) { // add elements, one by one, to DP array
if(dp[in[i]].val <= 1) // skip secondary "1" multipliers
continue;
for(j = 1; j < p; j++)
if(dp[j].val != 0 && dp[j].n < i) {
int y = ((long)j * in[i]) % p;
dp[y].val = in[i]; // current value, for printout
dp[y].prev = j; // reference to prev element
dp[y].n = n; // loop num, for prevent double reuse
if(x == y && dp[x].n > 0) {
// targed reached - print result, by iterate linklist
int mul = 1;
while(x != 0) {
printf(" %d ", dp[x].val);
mul *= dp[x].val; mul %= p;
x = dp[x].prev;
}
printf("; mul=%d\n", mul);
free(dp);
return;
}
} // for+if
} // for i
free(dp);
}
int main(int argc, char **argv) {
printsol(100, 11, 4, data);
return 0;
}

Count reduction using Thrust

Given some input keys and values, I am trying to count how many consecutive values with the same key exist. I will give an example to make this more clear.
Input keys: { 1, 4, 4, 4, 2, 2, 1 }
Input values: { 9, 8, 7, 6, 5, 4, 3 }
Expected output keys: { 1, 4, 2, 1 }
Expected output values: { 1, 3, 2, 1 }
I am trying to solve this problem on a GPU using CUDA. The reduction capabilities of the Thrust library seemed like a good solution for this and I got to the following:
#include <thrust/reduce.h>
#include <thrust/functional.h>
struct count_functor : public thrust::binary_function<int, int, int>
{
__host__ __device__
int operator()(int input, int counter)
{
return counter + 1;
}
};
const int N = 7;
int A[N] = { 1, 4, 4, 4, 2, 2, 1 }; // input keys
int B[N] = { 9, 8, 7, 6, 5, 4, 3 }; // input values
int C[N]; // output keys
int D[N]; // output values
thrust::pair<int*, int*> new_end;
thrust::equal_to<int> binary_pred;
count_functor binary_op;
new_end = thrust::reduce_by_key(A, A + N, B, C, D, binary_pred, binary_op);
for (int i = 0; i < new_end.first - C; i++) {
std::cout << C[i] << " - " << D[i] << "\n";
}
This code is pretty similar to an example from the Thrust documentation. However, instead of the plus operation, I am trying to count. The output from this code is the following:
1 - 9
4 - 7
2 - 5
1 - 3
However, I would expected the second column to contain the values 1, 3, 2, 1. I think the counts are off because the reduction starts with the first value it finds and does not apply the operator until it has a second value, but I am not sure this is the case.
Am I overlooking something about the reduce_by_key function that could solve this problem or should I use a completely different function to achieve what I want?
For your use case you don't need the values of B, the values of D are only dependent on the values of A.
In order to count how many consecutive values are in A you can supply a thrust::constant_iterator as the input values and apply thrust::reduce_by_key:
#include <thrust/reduce.h>
#include <thrust/functional.h>
#include <iostream>
#include <thrust/iterator/constant_iterator.h>
int main()
{
const int N = 7;
int A[N] = { 1, 4, 4, 4, 2, 2, 1 };
int C[N];
int D[N];
thrust::pair<int*, int*> new_end;
thrust::equal_to<int> binary_pred;
thrust::plus<int> binary_op;
new_end = thrust::reduce_by_key(A, A + N, thrust::make_constant_iterator(1), C, D, binary_pred, binary_op);
for (int i = 0; i < new_end.first - C; i++) {
std::cout << C[i] << " - " << D[i] << "\n";
}
return 0;
}
output
1 - 1
4 - 3
2 - 2
1 - 1

set constructor with custom compare function

How is the y.size() = 4 in the following? The values in y are {11, 2, 4, 7} How does one arrive at this? What are a and b in the operator() function for each iteration of the set. I don't understand the construction of y and I can't find anything online that explains this situation. Thank You
#include <iostream>
#include <set>
struct C
{
bool operator()(const int &a, const int &b) const
{
return a % 10 < b % 10;
}
};
int main()
{
std::set<int> x({ 4, 2, 7, 11, 12, 14, 17, 2 });
std::cout << x.size() << std::endl;
std::set<int, C> y(x.begin(), x.end());
std::cout << y.size() << std::endl;
std::set<int>::iterator iter;
for (iter = y.begin(); iter != y.end(); ++iter)
{
std::cout << *iter << std::endl;
}
return 0;
}
Second template argument of set is comparator type — type of functor that implements less operation.
struct C
{
bool operator()(const int &a, const int &b) const
{
return a % 10 < b % 10;
}
};
This comparator will compare a and b as a < b only if a % 10 < b % 10, so practically all numbers will be compared by modulo 10.
UPDATE:
After pushing into x set numbers { 4, 2, 7, 11, 12, 14, 17, 2 }, set will contain seven elements { 2, 4, 7, 11, 12, 14, 17 }. These elements will be sorted in that way, because set stores objects in sorted way.
Then numbers from x set are being sequentially inserted into y set. Before inserting of each element, set will find proper place in sorted order of currently inserted numbers. If set will see, that there is already some number on it's place, set will not insert it.
After inserting {2, 4, 7} from x to y, y will be {2, 4, 7}.
Then, to insert 11 into y set will do comparisons of 11 with {2, 4, 7} to find proper place using provided C functor.
To check is 11 less than 2 set will call C()(11, 2), which will result in 11 % 10 < 2 % 10 comparison, which will result in true, so 11 will be inserted before 2.
Other numbers from x (12, 14, 17) will not be inserted, because set will find, that 12 should be on place of 2 (because 2 % 10 < 12 % 10 or 12 % 10 < 2 % 10 expression is false, so 2 == 12), and in same way 14 and 17.