I am given this problem:
We are going over recursion in my class and I do not quite understand it, I was wondering if someone can help me with this problem
let c(n) be the number of different group integers that can be chosen from the integers 1 through n-1, so that the integers in each group add up to n (for example, n=4=[1+1+1+1]=[1+1+2]=[2+2]). Write a recursive definition for c(n) under the following variations:
a) You count permutations. For example, 1,2,1 and 1,1,2 are two groups that each add up to 4
b)you ignore permutations
I know permutations is how many ways you can arrange a set of numbers, so is my code below correct? I get an answer of 7?
Here is my code for part a:
int recurse (int n);
int main(){
int a=4;
int sum_perm;
sum_perm=recurse(a);
cout<<sum_perm-1<<endl;
//Can I do -1 here because it should be from a group of integers from 1 to n-1?
return 0;
}
int recurse(int n)
{
int sum = 1;
if (n == 1){
return 1;
}
for(int i = 1; i < n; i++){
sum += recurse(n - i);
}
return sum;
}
For part B, if I am not counting permutations, what am I counting?
Here is my code for part b:
int without (int n, int max);
int main(){
int a=4, b =3;
int sum_without;
sum_without=without(a,b);
cout<<sum_without<<endl;
system("Pause");
return 0;
}
int without(int n, int max)
{
if(n == 1 || max == 1){
return 1;
}
else if (n == max){
return 1 + without(n, n-1);
}
else{
return without(n,max-1) + without(n-max, max);
}
}
You don't show any code to generate the combinations of numbers that produce a sum. Link to wiki article about partitions .
In this case, the goal is to count the number of combinations and/or permutations, which might be possible without actually generating a set of combinations. Not sure if recursion helps here, but you can convert any loop into recursion if you pass enough variables.
Example "partitions"
1 combination that sums to 1:
1
2 combinations that sum to 2:
1 1
2
3 combinations that sum to 3:
1 1 1
1 2
3
5 combinations that sum to 4:
1 1 1 1
1 1 2
1 3
2 2
4
7 combinations that sum to 5:
1 1 1 1 1
1 1 1 2
1 1 3
1 2 2
1 4
2 3
5
11 combinations of numbers that sum to 6:
1 1 1 1 1 1
1 1 1 1 2
1 1 1 3
1 1 2 2
1 1 4
1 2 3
2 2 2
1 5
2 4
3 3
6
I would recommend combinations directly being considered. While it seems like the more difficult case a simple rule makes it trivial.
Numbers calculated are in decreasing order
This requires you to track the last number, but ensures you don't calculate 1 5 and then 5 1, as the former is impossible.
Related
You have n coins with certain values. Your task is to find all the money sums you can create using these coins.
Input
The first input line has an integer n: the number of coins.
The next line has n integers x1,x2,…,xn: the values of the coins.
Output
First print an integer k: the number of distinct money sums. After this, print all possible sums in increasing order.
Constraints
1≤n≤100
1≤xi≤1000
Example
Input:
4
4 2 5 2
Output:
9
2 4 5 6 7 8 9 11 13
I have written a code which works perfectly for the small inputs but gives the wrong answer to the large inputs. Please help to find the mistake and how do I correct it.
my code is:
#include <bits/stdc++.h>
using namespace std;
set<long long> s;
// Prints sums of all subsets of array
void subsetSums(long long arr[], long long n)
{
// There are totoal 2^n subsets
long long total = 1 << n;
// Consider all numbers from 0 to 2^n - 1
for (long long i = 0; i < total; i++)
{
long long sum = 0;
// Consider binary reprsentation of
// current i to decide which elements
// to pick.
for (long long j = 0; j < n; j++)
if (i & (1 << j))
sum += arr[j];
// Print sum of picked elements.
if (sum)
s.insert(sum);
}
}
// Driver code
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
long long n;
cin >> n;
long long arr[n];
for (long long i = 0; i < n; i++)
{
cin >> arr[i];
}
subsetSums(arr, n);
cout << s.size() << "\n";
for (auto it = s.begin(); it != s.end(); ++it)
cout << *it << " ";
return 0;
}
for example, it gives the wrong answer for
50
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
as
18
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36
the correct output should be:
50
1 2 3 4 ... 50
your code is simply too slow 2^n subsets gives 1,267,650,600,228,229,401,496,703,205,376 subsets in the worst case (when n=100) while C++ does on average about 1000,000,000 operations per second.
This problem can be solved with dynamic programming, consider having an array dp of size 100001, so that dp[x] denotes if sum of x is possible to achieve.
Base case is easy - sum of 0 is possible without using any coins: dp[0]=1
Then for each coin we can try to increase existing sums by coins value to fill up our table:
for each coinValue:
for coinSum = 100000 - coinValue; coinSum >=0; coinSum--)
if(dp[coinSum])
dp[coinSum + coinValue]=1
Notice that we are looping backwards, this is done on purpose so that each coin gets used only once.
Complexity: O(n^2*maxCoinValue)
Your algorithm is poor, but the reason you're getting wrong results is because you're overflowing int. long long total = 1<<n; shifts an int left by n places, and the fact you're assigning the result to a long long is irrelevant.
You can find problems like this using ubsan. Here's a reproduction of your problem, including warning messages from ubsan:
$ clang++ -fsanitize=undefined a.cpp -o a && ./a
50
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
a.cpp:11:25: runtime error: shift exponent 50 is too large for 32-bit type 'int'
a.cpp:22:24: runtime error: shift exponent 32 is too large for 32-bit type 'int'
18
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36
Here is the link to the question. Essentially, it asks to find the kth number having digit sum as 10. I have tried multiple solutions and also looked upon solutions online. Specifically this one (also shared below). The one with constant time talks about outliers in Arithmetic Progression and uses it to find the nth number having sum as 10. Obviously, the code is incorrect as it fails for test cases when k=1000 etc.
#include <bits/stdc++.h>
using namespace std;
int findNth(int n)
{
int nthElement = 19 + (n - 1) * 9;
int outliersCount = (int)log10(nthElement) - 1;
// find the nth perfect number
nthElement += 9 * outliersCount;
return nthElement;
}
int main()
{
cout << findNth(5) << endl;
return 0;
}
Eventually, I ended up writing combination of Arithmetic Progression + brute force as below
#include <bits/stdc++.h>
using namespace std;
#define ll unsigned long long
int main() {
int n;
cin >> n;
int count = 0;
ll i = 19;
for (; ; i += 9) {
int curr = i;
int localSum = 0;
while (curr) {
localSum += curr%10;
curr /= 10;
}
if (localSum == 10) {
count += 1;
}
if (count == n) {
break;
}
}
cout << i << endl;
return 0;
}
I am wondering, if there is no constant time or better algorithm that does not require me to calculate the sum, but my algorithm always hops in a way that I have number whose digit sum is 10?
Here is a Python solution that you can translate into C++.
cached_count_ds_l = {}
def count_digit_sum_length (s, l):
k = (s, l)
if k not in cached_count_ds_l:
if l < 2:
if s == 0:
return 1
elif l == 1 and s < 10:
return 1
else:
return 0
else:
ans = 0
for i in range(min(10, s+1)):
ans += count_digit_sum_length(s-i, l-1)
cached_count_ds_l[k] = ans
return cached_count_ds_l[k]
def nth_of_sum (s, n):
l = 0
while count_digit_sum_length(s, l) < n:
l += 1
digits = []
while 0 < l:
for i in range(10):
if count_digit_sum_length(s-i, l-1) < n:
n -= count_digit_sum_length(s-i, l-1)
else:
digits.append(str(i))
s -= i
l -= 1
break
return int("".join(digits))
print(nth_of_sum(10, 1000))
The idea is to use dynamic programming to find how many numbers there are of a given maximum length with a given digit sum. And then to use that to cross off whole blocks of numbers on the way to finding the right one.
The main logic goes like this:
0 numbers of length 0 sum to 10
- need longer
0 numbers of length 1 sum to 10
- need longer
9 numbers of length 2 sum to 10
- need longer
63 numbers of length 3 sum to 10
- need longer
282 numbers of length 4 sum to 10
- need longer
996 numbers of length 5 sum to 10
- need longer
2997 numbers of length 6 sum to 10
- answer has length 6
Looking for 1000th number of length 6 that sums to 10
- 996 with a leading 0 sum to 10
- Need the 4th past 99999
- 715 with a leading 1 sum to 10
- Have a leading 1
Looking for 4th number of length 5 that sums to 9
- 495 with a leading 0 sum to 9
- Have a leading 10
Looking for 4th number of length 4 that sums to 9
- 220 with a leading 0 sum to 9
- Have a leading 100
Looking for 4th number of length 3 that sums to 9
- 55 with a leading 0 sum to 9
- Have a leading 1000
Looking for 4th number of length 2 that sums to 9
- 1 with a leading 0 sum to 9
- Need the 3rd past 9
- 1 with a leading 1 sum to 9
- Need the 2nd past 19
- 1 with a leading 2 sum to 9
- Need the 1st past 29
- 1 with a leading 3 sum to 9
- Have a leading 10003
Looking for 1st number of length 1 that sums to 6
- 0 with a leading 0 sum to 6
- Need the 1st past 0
- 0 with a leading 1 sum to 6
- Need the 1st past 1
- 0 with a leading 2 sum to 6
- Need the 1st past 2
- 0 with a leading 3 sum to 6
- Need the 1st past 3
- 0 with a leading 4 sum to 6
- Need the 1st past 4
- 0 with a leading 5 sum to 6
- Need the 1st past 5
- 1 with a leading 6 sum to 6
- Have a leading 100036
And it finishes in a fraction of a second.
Incidentally the million'th is 20111220000010, the billionth is 10111000000002000000010000002100, and the trillionth is 10000000100000100000100000000000001000000000000100000000010110001000.
Problem
I need to compute a function of an array of integers. For every three-element subset (or triplet) of the array, I need to compute the term floor((sum of triplet)/(product of triplet)). Then I need to return the sum of all such terms.
Example
Input (length; array):
5
1 2 1 7 3
Output:
6
Explanation
The following triplets exist in the given array:
1 2 1
1 2 7
1 2 3
1 1 7
1 1 3
1 7 3
2 1 7
2 1 3
2 7 3
1 7 3
Considering these triplets from the sample input:
1 2 1 contributes 2, because floor((1+2+1)/(1*2*1)) = floor(4/2) = 2
1 2 3 contributes 1
1 1 7 contributes 1
1 1 3 contributes 1
2 1 3 contributes 1
All other triplets contribute 0 to the sum.
Hence the answer is (2+1+1+1+1)=6.
My Solution
What I tried is complexity O(n^3). Code is given below:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long t,n[300005],sum=0,mul=1,i,j,k,res=0;
cin >> t;
for(i=0;i<t;i++)
cin >>n[i];
for(i=0;i<t-2;i++)
for(j=i+1;j<t-1;j++)
for(k=j+1;k<t;k++)
{
sum = n[i]+n[j]+n[k];
mul = n[i]*n[j]*n[k];
res += floor(sum/mul);
}
cout << res << endl;
return 0;
}
Is there any hint of better optimization?
While still O(n^3), you could save some operations by caching the redundant calculations between n[i] and n[j] as you iterate over n[k].
For example:
long sum_ij,mul_ij;
for(i=0;i<t-2;i++) {
for(j=i+1;j<t-1;j++) {
sum_ij = n[i]+n[j];
mul_ij = n[i]*n[j];
for(k=j+1;k<t;k++)
{
sum = sum_ij+n[k];
mul = mul_ij*n[k];
res += floor(sum/mul);
}
}
}
This question already exists:
Recursion all combinations of lower triangle C++
Closed 8 years ago.
I recently posted a poor question on how to use recursion to estimate all combinations of lower triangle in C++. I managed to find a recursive algorithm that given an array of size n, generates and prints all possible combinations of r elements in array. I've employed this function using Rcpp in R. I've then written a loop around this function to get all the subsets of combinations r to r + n.
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
int recursive(IntegerVector arr, IntegerVector data, int start, int end, int index, int r)
{
if (index == r)
{
for (int j=0; j<r; j++)
printf("%d ", data[j]);
printf("\n");
}
for (int i=start; i<=end && end-i+1 >= r-index; i++)
{
data[index] = arr[i];
recursive(arr, data, i+1, end, index+1, r);
}
}
R code with five groups:
Rcpp::sourceCpp('recursive2.cpp')
nComm <- 5
r <- c(2:nComm)
n <- nComm
arr <- c(1:nComm)
dat <- c(1:nComm)
for(i in 1:(n-1)){
recursive(arr, dat, 0, n-1, 0, r[i])
}
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5
1 2 3 4 5
Currently, this just prints the subsets of combinations I need to estimate my dissimilarities. I'd like to be able to remove the loop and use it as a single Rcpp function/script. With the end goal to be able to use the subsets (currently printed combinations) as way to subset rows in an array. Which will be used to calculate the intersect between vectors. So 1 2 will be used to compare rows 1 and 2 in an array. And so forth.
What I want to do is to find every permutation of a 1-d array with repetitions of its contents.
e.g.
int array[]={1,2,3};
for(i=0;i<3;i++){
next_permutation(array,array+3)
for(int j=0;j<=3;j++){
printf("%d ",array[j]);
}
printf("\n");
}
will return:
1 2 3
1 3 2
2 1 3
etc...
what I want the function to return:
1 1 1
1 1 2
1 2 1
2 1 1
1 2 2
2 2 1
2 1 2
1 1 3
1 3 1
3 1 1
etc...
Is there a function that can do that?
Thanks in advance,
Erik
You are not doing permutation but just counting.
Ex. if your enumerating set {0, 1} over 3 digits, you'll get:
000
001
010
011
100
101
110
111
See, that's just binary counting.
So map your element set into n-digits, then do n-based count will give you the right awnser
I had this written in Java.
Non optimized code, but you get the point:
String [] data = {"1","2","3"};
public void perm(int maxLength, StringBuffer crtComb){
if (crtComb.length() == maxLength){
System.out.println(crtComb.toString());
return;
}
for (int i=0; i<data.length; i++){
crtComb.append(data[i]);
perm(maxLength, crtComb);
crtComb.setLength(crtComb.length()-1);
}
}
In general when computing permutations of integers from 1 to k (with repetition):
Initially set first permutation as 1 1 1 .... (k times).
Find the rightmost index (say j) such that the element at that index is less than k.
Increment the value of the element at index j by one, and from position j + 1 to k reset all elements to 1.
Repeat steps 2 and 3.
Applying this logic, we now get:
1st permutation -> 1 1 1.
Then at position 2 (0 index counting), we have 1 < 3, so increment it and reset all elements after this to 1. 2nd permutation -> 1 1 2.
Then at position 1 (0 index counting), we have 1 < 3, so increment it and reset all elements after this to 1. 3rd permutation -> 1 2 1
And so on.