How to get numbers into array after point "." [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 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

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

Reduce subsequence problem complexity from exponential to polynomial?

I am working on the following problem:
Given a set of non-negative distinct integers, and a value m, determine if there is a subset of the given set with sum divisible by m.
Input: The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case contains an integer N and M where N denotes the size of the array and M is the number for which we have to check the divisibility. The second line of each test case contains N space separated integers denoting elements of the array A[ ].
Output: If there is a subset which is divisible by M print '1' else print '0'.
I have tried a recursive solution:
#include <iostream>
#include<unordered_map>
using namespace std;
bool find_it(int a[],int &m,int n,int sum) {
if ((sum%m)==0 && sum>0)
return true;
if (n==0)
return false;
return find_it(a,m,n-1,sum) || find_it(a,m,n-1,sum-a[n-1]);
}
int main() {
int tc;
cin >> tc;
while (tc--) {
int n,m;
cin >> n >> m;
int a[n];
int sum = 0;
for (int i=0;i<n;i++) {
cin >> a[i];
sum += a[i];
}
bool answer = find_it(a,m,n,sum);
cout << answer << "\n";
}
return 0;
}
Which works fine and get accepted, but then I tried top-down approach, and am getting TLE ("Time Limit Exceeded"). What am I doing wrong in this memoization?
#include <iostream>
#include<unordered_map>
using namespace std;
bool find_it(
int a[], int &m, int n, int sum,
unordered_map<int,unordered_map<int,bool>> &value,
unordered_map<int,unordered_map<int,bool>> &visited){
if ((sum%m)==0 && sum>0)
return true;
if(n==0)
return false;
if(visited[n][sum]==true)
return value[n][sum];
bool first = false,second = false;
first = find_it(a,m,n-1,su1m,value,visited);
if(sum<a[n-1])
{
second=false;
}
else
second = find_it(a,m,n-1,sum-a[n-1],value,visited);
visited[n][sum] = true;
value[n][sum] = first || second;
return value[n][sum];
}
int main() {
int tc;
cin >> tc;
while (tc--) {
int n,m;
cin >> n >> m;
int a[n];
int sum = 0;
for (int i=0;i<n;i++) {
cin >> a[i];
sum+=a[i];
}
unordered_map<int,unordered_map<int,bool>> value;
unordered_map<int,unordered_map<int,bool>> visited;
cout << find_it(a,m,n,sum,value,visited) << "\n";
}
return 0;
}
Well, at first, you can reduce the problem to a modulo m problem, as properties of integers don't change when switching to modulo m field. It's easy to demonstrate that being divisible by m is the same as being identical to 0 mod m.
I would first convert all those numbers to their counterparts modulo m and eliminate repetitions by considering a_i, 2*a_i, 3*a_i,... until rep_a_i * a_i, all of them mod m. Finally you get a reduced set that has at most m elements. Then eliminate all the zeros there, as they don't contribute to the sum. This is important for two reasons:
It converts your problem from a Knapsack problem (NP-complete) on which complexity is O(a^n) into a O(K) problem, as its complexity doesn't depend on the number of elements of the set, but the number m.
You can still have a large set of numbers to compute. You can consider the reduced set a Knapsack problem and try to check (and further reduce it) for an easy-knapsack problem (the one in which the different values a_i follow a geometric sequence with K > 2)
The rest of the problem is a Knapsack problem (which is NP-complete) or one of it's P variants.
In case you don't get so far (cannot reduce it to an easy-knapsack problem) then you have to reduce the number of a_i's so the exponential time gets a minimum exponent :)
edit
(#mss asks for elaboration in a comment) Assume you have m = 8 and the list is 1 2 4 6 12 14 22. After reduction mod m the list remains as: 1 2 4 6 4 6 6 in which 6 is repeated three times. we must consider the three possible repetitions of 6, as they can contribute to get a sum, but not more (for the moment), let's consider 6*1 = 6, 6*2 = 12 and 6*3 = 18, the first is the original 6, the second makes a third repetition of 4 (so we'll need to consider 3 4s in the list), and the third converts into a 2. So now, we have 1 2 4 6 4 4 2 in the list. We make the same for the 4 repetitions (two 4 run into 8 which is 0mod m and don't contribute to sums, but we have to keep one such 0 because this means you got by repeated numbers the target m) getting into 1 2 4 6 0 4 2 => 1 2 4 6 0 0 2 =(reorder)=> 0 1 2 2 4 6 => 0 1 2 4 6. This should be the final list to consider. As it has a 0, you know a priori that there's one such sum (in this case you got is as including the two 4, for the original list's 4 and 12 numbers.
There is no need for value. Once you find a valid combination, i.e. if find_it ever returns true, you can just immediately return true in all recursive calls.
Some additional remarks:
You should use consistent indentation.
Variable sized arrays as in int a[n] are not standard C++ and will not work on all compilers.
There is no reason to pass m as int& instead of int.
A map taking boolean values is the same as a set where the element is assumed to map to true if it is in the set and false if it is not. Consider using unordered_set instead of unordered_map.
Composing two unordered_maps like this is expensive. You can just as easily put both keys into a std::pair and use that as key. This would avoid the overhead of maintaining the map.
bits/stdc++.h is also non-standard and you should specify the correct header files instead, e.g. #include <unordered_map> and #include <iostream>.
You should put spaces between the variable type and its name, even if the > from the template parameter allows it to parse correctly without. It makes code hard to read.

Generate random values with fixed sum in C++ [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 8 years ago.
Improve this question
I saw tons of answers to this question on the web but, can you believe me? I still don't get the solution of this problem. I have an array of values. The size of this array is "n". I have also the defined value "sum". What I want is to generate "n" random values in such a way that their sum is equals to "sum", preferably uniformly distributed, otherwise (for example) having the first random number equals to "sum" and the rest equals to zero is not that nice. I need two algorithms which accomplish this task. One with positive Integers and one with positive Floats. Thanks a lot in advance!
First generate n random variables. Then sum them up: randomSum. Calculate coefficient sum/randomSum. Then multiply all random variables with that coefficient.
Integers would pose a problem... Rounding too (probably)
You can generate n numbers with a normal distribution then normalize them to your sum
You can generate n values defined by this : ((Sum - sumOfGeneratedValues) / n - (numberOfGeneatedValue)) -+X (With X maximal deviance)
Example :
SUM = 100 N = 5
+- 10
Rand between 100 - 0 / 5 - 0 --> 20 +-10 (So bewteen 10 and 30)
Value1 = 17;
Rand between 100 - 17 / 5 - 1 ---> 21 +-10 (So between 11 and 31)
... etc
Deviance would make your random uniform :)
you have a loop, where the number of iterations is equal to the number of random numbers you want minus 1. for the first iteration, you find a random number between 0 and the sum. you then subtract that random number from the sum, and on the next iteration you get another random number and subtract that from the sub sum minus the last iteration
its probably more easy in psuedocode
int sum = 10;
int n = 5; // 5 random numbers summed to equal sum
int subSum = sum;
int[] randomNumbers = new int[n];
for(int i = 0; i < n - 2; i++)
{
randomNumbers[i] = rand(0, subSum); // get random number between 0 and subSum
subSum -= randomNumbers[i];
}
randomNumbers[n - 1] = subSum; // leftovers go to the last random number
My C++ is very (very very) rusty. So let's assume you already know how to get a random number between x and y with the function random(x,y). Then here is some psuedocode in some other c derived language:
int n = ....; // your input
int sum = ....; // your input
int[] answer = new int[n];
int tmpsum = 0;
for (int i=0; i < n; i++) {
int exactpart = sum/n;
int random = (exactpart/2) + random(0,exactpart);
int[i] = tmpsum + random > sum ? sum - tmpsum : random;
tmpsum += int[i];
}
int[n-1] += sum - tmpsum;

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.

How to find uncoupled integer in an array? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Find integer not occurring twice in an array
Accenture interview question - find the only unpaired element in the array
Given an array of integers of odd size. All the integers in the array appear twice except for a single integer. How to find this uncoupled integer in most efficient (both memory and complexity-wise) way?
If you XOR all of them together, you'll end up with the lone (uncoupled) value.
That's because x XOR x is zero for all x values, and 0 XOR x is x.
By way of example, the following program outputs 99:
#include <stdio.h>
int main (void) {
int num[] = { 1, 2, 3, 4, 5, 99, 1, 2, 3, 4, 5};
unsigned int i;
int accum;
for (accum = 0, i = 0; i < sizeof(num)/sizeof(*num); i++)
accum ^= num[i];
printf ("%d\n", accum);
return 0;
}
In terms of efficiency, it's basically O(1) space and O(n) time complexity, minimal, average and worst case.
As pax suggests, XOR'ing all the elements together will give you your lone value.
int getUncoupled(int *values, int len)
{
int uncoupled = 0;
for(int i = 0; i < len; i++)
uncoupled ^= values[i];
return uncoupled;
}
However there is a slight caveat here: What's the difference between no uncoupled values and a set whose uncoupled value is zero? x^x^y^y = 0 but doesn't x^x^0^y^y also equal zero? Food for thought :)