What is the median value is decimal? [closed] - c++

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++).

Related

How to optimise this code of sorting,this is not exeuting within the time limits.This question is from hackerrank [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 2 years ago.
Improve this question
How to reduce the time compexity of this code,this is not exeuting within the time
exact ques from hackerrank--
Complete the circularArrayRotation function in the editor below. It should return an array of integers representing the values at the specified indices.
circularArrayRotation has the following parameter(s):
a: an array of integers to rotate
k: an integer, the rotation count
queries: an array of integers, the indices to report
vector<int> circularArrayRotation(vector<int> a, int k, vector<int> queries) {
int i,temp;
vector<int> ans;
//to perform number of queries k
while(k--)
{ //shift last element to first pos and then move rest of elements to 1 postion forward
temp=a[a.size()-1]; //last element
for(i=a.size()-1;i>0;i--)
{
a[i]=a[i-1];
}
a[0]=temp;
}
for(i=0;i<queries.size();i++)
{
ans.push_back(a[queries[i]]);
}
return ans;
}
The vector a is being rotated by k in the while loop. The whole loop can be removed by adding k and using modulo when accessing elements in a:
ans.push_back(a[(queries[i]+k)%a.size()]);
Note: you might need handling of negative values of k.
Note: Maybe it should be minus instead of plus.
An alternative could be to use std::rotate.
Furthermore, the ans vector should be pre-allocated to reduce the number of allocations to one:
ans.reserve(queries.size());

Code complexity [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
Can anybody explain to me the time complexity of the following code:
cin >> n;
while(n>9)
{
int num = n;
int s = 0;
while(num!=0)
{
s = s + num%10;
num = num/10;
}
n = s;
}
cout<<n<<endl;
The above code calculates the sum of the digits of the number until the sum becomes a single digit number.
Example: 45859 = 4+5+8+5+9 = 31 = 3+1 = 4
Edit: I think that the inner loop calculating the sum of digits has O(log_base_10(n)) complexity, but the outer loop continues till the sum obtained so far is less than 10. So the total complexity depends on how many times the outer loop is going to run.. I am not able to figure that out... Some kind of mathematical gimmicks to calculate the complexity of the outer loop would help!!!
You are calculating the sum of the digits. The number of digits in n scales with log(n).

Array Best Match [closed]

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.

How to get numbers into array after point "." [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 8 years ago.
Improve this question
How i can put the numbers into array like 11*11 = 121 how i can put 121 as 1,2,1 into array , so that it should like int arr[] = [1,2,1]; , the one logic to me is divide it by 10 , the code i am trying is
long mul , cube;
mul = num*num;
cube = num*num*num;
float unt = mul/10.0;
But how to save the number after period . into array , like if i have the number 2.3 so i want to save 3 into array
I think you want to get the individual digits into an array.
You can get the digits into an array in reverse order by following the algorithm (let n be the number you want to split):
while (n > 0):
push (n mod 10) into the array --- this is one digit from 0..9
divide n by 10, ignoring the decimal part (ignoring remainder, that is)
For example, with n=97 you get:
(n mod 10) = 7, push that into array
divide 97 by 10 to get 9 (ignoring .7)
(n mod 10) = 9, push that into array
divide 9 by 10 to get 0
end algorithm
now you have [7, 9] in the array, then reverse the array to get the left-to-right ordering.
Follow on from the OP requesting a code sample, and my understanding of the question. This implements the algorithm from another answer (Antti Huima);
#include <iostream>
#include <vector>
#include <algorithm>
std::vector<int> convert(int number)
{
std::vector<int> result;
if (number == 0) {
result.push_back(0);
}
while (number) {
int temp = number % 10;
number /= 10;
result.push_back(temp);
//result.insert(result.begin(), temp); // alternative... inserts in "forward" order
}
// push_back inserts the elements in reverse order, so we reverse them again
std::reverse(result.begin(), result.end());
return result;
}
int main()
{
int i = 123;
auto result = convert(i);
std::cout << i << std::endl;
for (auto& j : result) {
std::cout << j << ',';
}
std::cout << std::endl;
}
It's been implemented assuming certain basics (that can be altered or templated);
int base type and int as the array member
Variable array size is catered for (in the vector)
convert is a very arbitrary name
The main is just a demonstration of its use (so I was a little more liberal in C++11 language use).
Live code

Single number as xy coordinates [closed]

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
I'm using a very specific random number generator to produce numbers between 0 and 2^20. I am trying to access elements of a two dimensional array using this number.
Because myArray[x][y] can be represented as myArray[x*a + y] (where 'a' is the number of elements in the second dimension), shouldn't I be able to turn my single random number into 2-dimensional coordinates? The array in question is 2^10 by 2^10 exactly, so I thought it would be:
int random = randomize(); //assigned a random value up to 2^20
int x = floor(random / pow(2, 10));
int y = random % pow(2, 10);
myArray[x][y] = something(); //working with the array
The arrays elements are not being accessed as predicted and some are not being accessed at all. I suspect a bug in my logic, I've checked my program's syntax.
No I can't use two random numbers to access the array.
No I can't use a one dimensional array.
Just checking this would be the correct math. Thank you.
In C++ ^ is a binary bitwise XOR operator, not a power operator.
An idiomatic expression for obtaining powers of 2 in C++ is 1 << n, so you can rewrite your expression like this:
int x = floor(random / (1<<10));
int y = random % (1<<10);
The reason the left shift by n works like raising 2 to the power of n is the same that adding n zeros to one in a base-ten system multiplies the number by n-th power of ten.
2^10 isn't 1024 in C++.
Because in c++ ^ is XOR (a bitwise operator ) c++ operators
include <math.h> /* pow */
int main ()
{
int random = randomize(); //assigned a random value up to 2^20
int x = floor(random / pow(2,10));
int y = random % pow(2,10);
myArray[x][y] = something(); //working with the array
return 0;
}
Hope this helps.