Array Best Match [closed] - c++

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 8 years ago.
Improve this question
You have been called upon to write a Match-Making program for a marriage beaureau. The beaureau’s questionnaire has 8 statements, and the applicant indicates her or his degree of agreement on a scale of 1 to 5. The response of the applicant is entered through the keyboard. Each response contains the applicant’s code number, sex (F or M), & response to the questionnaire (8 integers).
You may assume that there are no more than 50 applicants. Your program should match each person with 3 most compatible person of opposite sex and should print the code no. of applicant along with code no. of prospective applicants.
i want to implement this through c++. Is there any matching algorithm for this ?. or there is some simple approach. It would be nice for me, if you write the whole function.
and sorry, if the question is very simple bcs i'm a learner.

Based on our comments above I'll post some comments to get you started. But remember the best thing is to try something on your own and then get help afterwards...
int questionnaire_answers[50][8]; // 2D array holding answers
int sex[50]; // 1D array holding sex of those who answered
int i, j;
int index = 0;
int best = 999999;
int distance;
// We look for the best match for the first person
for (i = 1; i < 50; i++)
{
if (sex[0] != sex[i])
{
// Calculate the distance from index 0 to index i
// See note below
distance = 0;
for (j=0 ; j < 8; j++)
{
distance = distance + abs(questionnaire_answers[0][j]-questionnaire_answers[i][j]);
}
}
else
{
distance = 999999;
}
if (distance < best)
{
best = distance;
index = i;
}
}
// Now index holds the index of the best match
I'll leave it to you to figure out how to find the second and third best match :)
IMPORTANT:
I have used a simple linear distance calculation. In the real world you will probably do better with something more complicated. The world of math has several good option, e.g. least/minimum-mean-square
Have fun!

You can use Cosine Correlation. First normalize the 50X8 matrix such that each column has mean=0 and standard deviation=1. Now for each record(row), calculate the cosine correlation with every other record. The record giving maximum cosine correlation will be a match for this record.

Related

What is the median value is decimal? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm writing a program to find the median of an array in CPP. I am not sure if I have a clear idea about what a median is. As far as I know, I've written my program to find median but when the array is even-numbered, I'm confused whether I should print the ceiling or ground value of division ofthe decimal output I get when I divide the middle two elements from the array.
using namespace std;
void findMedian(int sortedArray[], int N);
int main()
{
int ip[4] = {1, 2, 5, 8};
findMedian(ip, 4);
}
void findMedian(int sortedArray[], int N)
{
int size = N;
int median;
if ((size % 2) != 0)
{
median = sortedArray[(size / 2)];
}
else
{
median = (sortedArray[(size / 2) - 1] + sortedArray[size / 2]) / 2;
}
cout << median;
}
Thanks in advance, also if anyone can give the literal purpose of finding a median, I'd appreciate and it'd help me not ask this question again when I have to deal with Median.
Pardon my English.
on odd array the median is unique, but in a even array there are two medians: the lower median (the one in (n/2)th position) and the upper median (the one in (n/2+1) th position). I usually always see that the lower median is used as "median" for even arrays.
In this case you need only one formula for even and odd arrays:
medianPosition = n/2; // integer division
median = sortedArray[medianPosition];
Note that it is true only for array where indices starts with zero (like C/C++).

How to take n samples from vector? [duplicate]

This question already has answers here:
Copy every other element using standard algorithms (downsampling)
(5 answers)
Closed 4 years ago.
My question is how to choose n element from vec.begin() to vec.end() such that we almost cover all the vector elements?
vector<double> take_100_samples(vector<double>& in)
{
vector<double> vec(100);
double step = (in.size() - 1) / (100 - 1);
// sampling process
return vec;
}
for example if in vector has size of 200, we choose every two element of it (i.e. in[0], in[2] , in[4], ... ,in[199]) but what if the size is not dividable by 100?
Is there efficient way for doing that?
Regards
The usual way to do so is to get the floating point fraction and then rounding it to an integer:
double step = in.size() / 100.;
for(int i = 0; i < 100; ++i)
{
auto index = std::lround(i * step);
// use index
}
Of course, adapt the step computation as you did as well as the loop if you want to get the first and last elements all the time.
My interpretation is that you want to downsample a signal with an asynchronous frequency.
One way to do this is to implement a kind of Digital PLL (Phase Lock Loop).
Let us assume that you have N = 1030 elements at input and that you want to get K = 100 elements.
The average rate is equal to rate = 10.3.
In practice, you will have to use a step equal to 10 or 11 depending of the current position of the indices.
If you are in "advance" : step = 10 (slow down)
If you are "late" : step = 11 (speed up)
Test to know if you late or in advance:
The current "read" index i is equal to the sum of the former steps.
k is the output index
if i < rate*k : you are late
else you are in advance
This is the basic idea. Some small adaptations are possible, for example to insure getting the last element.
EDIT: I just 'rediscovered' Mathieu Brucher's solution. In my first too fast reading of it, I was misled by the original error (corrected) on step calculation in his answer. It is clear that results will be equivalent, except that Mathieu Brucher's implementation is simpler. In this situation, the only interest (?) of my answer is to provide another interpretation of the process

maxi and min times to calculate the Fibonacci numbers for six seperate runs at n [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
The wording for this problem has me completely confused. I know how to get "timing" using GetTickCount() but I have to repeat the calculation 6 times for each N and I have to have 6 different N and the results have to be reported in one table as max an min times. It seams to me as though this is not feasible because the run time for one N is not going to be the run time for another N. Any help is greatly appreciated. Ill post the original question below.
EDIT*: My own Frazzled brain was over complicating the problem! I got it figured out now Thanks to everyone who took time to try and help out!
'Your task is to find the maximum and minimum execution times of the Fibonacci number computation routines for six separate, unique runs at each value of n. NOTE: do not use the tail recursion implementation.'
I was thinking of perhaps storing the average run time values in arrays and then sorting those arrays to get the min and max and doing that 6 different times for both the min and max for iterative and recursive but that takes something like 24 arrays which just seems pointless.
For each input N, you need to calculate Fibb(N) six times, and display the minimum and maximum of those times. You display one minimum per N, and one maximum per N. Does it help to imagine that there are 100 N, and each one is calculated 6 times? You'd expect to see 100 minimums and 100 maximums.
For many simple competitions or homework, it looks vaguely like this:
while(std::cin >> N) {
int duration[6] = {};
int result = 0;
for(int i=0; i<6; ++i) {
auto start = GetTickCount();
int result = Fib(N);
auto end = GetTickCount();
duration[i] = end-start;
}
int max = std::max_element(std::begin(duration), std::end(duration));
int min = std::min_element(std::begin(duration), std::end(duration));
std::cout<<"Fib("<<N<<")="<<result<<" max="<<max<<" min="<<min<<'\n';
}

How to check if two n-sized vectors are linearly dependant on C++? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
A program should be made which finds if the two vectors a = (a0, a1, ..., an-1) and b = (b0, b1, ..., bn-1) (1 ≤ n ≤ 20) are linearly dependant. The input should be n, and the coordinates of the two vectors and the output should be 1 if the vectors are linearly dependant, else - 0.
I've been struggling for hours over this now and I've got absolutely nothing. I know only basic C++ stuff and my geometry sucks way too much. I'd be really thankful if someone would write me a solution or at least give me some hint. Thanks in advance !
#include <iostream>
using namespace std;
int main()
{
int n;
double a[20], b[20];
cin >> n;
int counter = n;
bool flag = false;
for (int i = 0; i < n; i++)
{
cin >> a[i];
cin >> b[i];
}
double k;
for (int i = 0; i < n; i++)
{
for (k = 0; k < 1000; k = k + 0.01)
{
if (a[i] == b[i])
{
counter--;
}
}
}
if (counter == 0 && k != 0)
flag = true;
cout << flag;
return 0;
}
Apparently that was all I could possibly come up with. The "for" cycle is wrong on so many levels but I don't know how to fix it. I'm open to suggestions.
There are 4 parts to the problem:
1. Math and algorithms
Vectors a and b are linearly depndent if ∃k. a = k b. That is expanded to ∃k. ∑i=1..n ai = k ai and that is a set of equations any of which can be solved for k.
So you calculate k as b0 / a0 and check that the same k works for the other dimensions.
Don't forget to handle a0 = 0 (or small, see below). I'd probably swap the vectors so the larger absolute value is denominator.
2. Limited precision numeric calculations
Since the precision is limited, calculations involve rounding error. You need to check for approximate equality, not exact, because most likely you won't get exact results even when you expect them.
Approximate equality comes in two forms, absolute (|x - y| < ε) and relative (1 - ε < |x / y| < 1 + ε). Obviously the relative makes more sense here (you want to ignore the last significant digit only), but again you have to handle the case where the values are too small.
3. C++
Don't use plain arrays, use std::vector. That way you won't have arbitrary limits.
Iterate with iterator, not indices. Iterators work for all container types, indices only work for the few with continuous integral indices and random access. Which is basically just vector and plain array. And note that iterators are designed so that pointer is iterator, so you can iterate with iterator over plain arrays too.
4. Plain old bugs
You have the loop over k, but you don't use the value inside the loop.
The logic with counter does not seem to make any sense. I don't even see what you wanted to achieve with that.
You're right, that code bears no reationship to the problem at all.
It's easier than you think (at least conceptually). Divide each element in the vector by the corressponding element in the other vector. If all those division result in the same number then the vectors are linearly dependendent. So { 1, 2, 4 } and { 3, 6, 12 } are linear because 1/3 == 2/6 == 4/12.
However there are two technical problems. First you have to consider what happens when your elements are zero, you don't want to divide by zero.
Secondly because you are dealing with floating point numbers it's not sufficient to test if two numbers are equal. Because of rounding errors they often won't be. So you have to come up with some test to see if two numbers are nearly equal.
I'll leave you to think about both those problems.

How to compute center of an arbitrary shape in 3D? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I want to know the accurate method to find the center of an arbitrary shape in 3D.
In the figure, I have explained 3 cases.
In first case how can we compute the center of arbitrary points ? One idea is summation of all points divided by total number of points. Is it the only method and Is it accurate ?
2nd is how to compute the approximate center of irregular arbitrary shape in 3D? Is this the same case of 1 ?
How can we compute the center line of the bended/curved tube that composed of arbitrary vertices ? For this problem we have to solve first two cases I think so ?
The solution really depends on what you are actually looking for.
If you seek the average position of all points in a shape, then averaging them does indeed give you that. But it can be far off from the point which you'd intuitively say is "in the middle". For example, consider a box where one side has twice as many vertices as the opposite side. The average position would be on the half of that side, not in the middle of the box.
More likely, I'd say you are looking for the point defined by calculating the max and min bounds in each dimension and then averaging the two. Because you tagged this with C++, here's some example code:
// Define max and min
double max[DIMENSIONALITY];
double min[DIMENSIONALITY];
// Init max and min to max and min acceptable values here. (see numeric_limits)
// Find max and min bounds
for(size_t v_i = 0; v_i < num_vertices; ++v_i)
{
for(int dim = 0; dim < DIMENSIONALITY; ++dim)
{
if(shape[v_i][dim] < min[dim]) min[dim] = shape[v_i][dim];
if(shape[v_i][dim] > max[dim]) max[dim] = shape[v_i][dim];
}
}
// Calculate middle
double middle[DIMENSIONALITY];
for(int dim = 0; dim < DIMENSIONALITY; ++dim)
middle[dim] = 0.5 * (max[dim] + min[dim]);
For either solution, the dimensionality of the problem doesn't matter.
Edit:
As pointed out in the comment below, this may result in a middle point which lies outside of the shape itself. If you need a point which lies inside the shape, an alternative approach must be used. A simple solution could be to use ray-marching across each axis.