Ways to Create a Number with Sum of Ones and Twos - algorithm

I am wondering if there is a way to count the possible ways to sum a number using only ones and twos
For example:
We have the number 10. The number 10 can be summed by:
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 2
2 + 2 + 2 + 2 + 2
etc...
Thank you all in advance!

If the order of elements does not matter, as the comments explain (i.e. 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 2 is identical to 2 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1), this is simply choosing the number of elements in the summation, which can be anywhere between 5 to 10. Once the number of elements is chosen, you know exactly how many of them have to be 1s and how many of them have to be 2s: For x elements, there are 10-x 2s, and the rest are 1s.
Since there are 6 numbers to choose from, this is the number of ways to create 10.

Rather than going into complex mathematical formulas, I would recommend DP approach.
int arr[N+1]; // Represents no. of ways to produce a number at index 1
// Like arr[5] is no. of ways to produce number 5
for(int i=0;i<=N;i++) {
arr[i] = 1; // As all 1s
}
for(int i=2;i<=N;i++) {
// if we add 2 now, check for no. of ways i-2 can be made,
// add it to current arr[i] value.
arr[i] += arr[i-2];
}
cout<< (arr[N]); // print

Number of ways to create a number using only ones = 1
Number of ways to create a number using at least one two = floor(n/2)
Total = 1 + floor(n/2)
See javascript code snippet below:
let numWays = n => 1 + Math.floor(n/2);
for (let i=1; i<=20; i++)
console.log("Number of ways to create " + i + " is: " + numWays(i));

Related

It is possible to get the index of a combination without generating it?

I mean a function that accepts an array of elements and a combination as params, and returns a number that represents the index of a combination without generating every combination.
I have no preference, it can be in any programming language.
An example of code getCombinationIndex("114") and should return the index of combination 114.
[1,1,1]: 1
[2,1,1]: 2
[3,1,1]: 3
[4,1,1]: 4
[.....]
[1,1,4]: ?
Let's say you are considering combinations of k symbols from alphabet A = {a_0, a_1, ..., a_n} (i.e. with n symbols and a_i < a_j lexicographically if i < j). In your example, you have an alphabet of 4 symbols A = {1, 2, 3, 4} and combinations of k = 3 symbols.
Then, a combination c = [a_i1, a_i2, ..., a_ik] can be uniquely encoded as I(c) = i1 + n*i2 + (n^2)*i3 + ... + (n^(k-1))*ik. The indexing you're looking for is F(c) = I(c) + 1.
Let's see how it works for your example:
F([1,1,1]) = I([1,1,1]) + 1 = 0 + 4*0 + (4^2)*0 + 1 = 1
F([2,1,1]) = I([2,1,1]) + 1 = 1 + 4*0 + (4^2)*0 + 1 = 2
F([3,1,1]) = I([2,1,1]) + 1 = 2 + 4*0 + (4^2)*0 + 1 = 3
F([4,1,1]) = I([2,1,1]) + 1 = 3 + 4*0 + (4^2)*0 + 1 = 4
...
F([2,1,3]) = I([2,2,3]) + 1 = 1 + 4*1 + (4^2)*2 + 1 = 38
...
F([1,1,4]) = I([1,1,4]) + 1 = 0 + 4*0 + (4^2)*3 + 1 = 49
...
F([4,4,4]) = I([4,4,4]) + 1 = 3 + 4*3 + (4^2)*3 + 1 = 64
This problem can be seen as base conversion. You need two informations to start with and then it will be only a base conversion.
The base
In your case this is the highest number of all the items.
[4,1,1] -> 4
The desired combination
This only works for the premiss that all items can have the same maximum.
Algorithm
Reverse the order of items
Decrement every item by 1
Convert the number to base 10
Increment by 1
Example
Start: 114
Reverse: 411
Decrement: 300
Conversion:
Base 4: 300
Base 10: 3*4^2 + 0*4^1 + 0*4^0 = 24
Increment: 25

Analyzing a recursive algorithm

I'm trying to figure out this algorithm that accepts an input of an int and should return an output of the sum of each element in the int.
# Input -> 4321
# output -> 10 (4+3+2+1)
def sum_func(n):
# Base case
if len(str(n)) == 1:
return n
# Recursion
else:
return n%10 + sum_func(n/10)
When Trying to break apart this algorithm this is what I come up with
1st loop -> 1 + 432 = 433
2nd loop -> 2 + 43 = 45
3rd loop -> 3 + 4 = 7
4th loop -> 4 + 4 = 8
How was it able to come up with the result of 10?
Unwinding, it would look like this:
sum_func(4321)
= 1 + sum_func(432)
= 1 + 2 + sum_func(43)
= 1 + 2 + 3 + sum_func(4)
= 1 + 2 + 3 + 4
When trying to understand recursion you'll have to clearly understand what is returned.
In this case function sum_func(n) returns the sum of the digits in it's argument n.
For concrete n task is divided into last_digit_of_n + sum_func(n_without_last_digit).
For example,
sum_func(4321) =
sum_func(432) + 1 =
sum_func(43) + 2 + 1 =
sum_func(4) + 3 + 2 + 1 =
4 + 3 + 2 + 1
Hope this helps.
(As a side note, checking if n has more than one digit using str is a bad idea. Better just to check if n <= 9)
You must reach the base case before the summation occurs:
Iteration 1: 1 + sum_func(432)
Iteration 2: 1 + 2 + sum_func(43)
Iteration 3: 1 + 2 + 3 + sum_func(4) = 1 + 2 + 3 + 4 = 10

How to write a function f("123")=123+12+23+1+2+3 as a recurrence relationship

I'm wondering if someone can help me try to figure this out.
I want f(str) to take a string str of digits and return the sum of all substrings as numbers, and I want to write f as a function of itself so that I can try to solve this with memoization.
It's not jumping out at me as I stare at
Solve("1") = 1
Solve("2") = 2
Solve("12") = 12 + 1 + 2
Solve("29") = 29 + 2 + 9
Solve("129") = 129 + 12 + 29 + 1 + 2 + 9
Solve("293") = 293 + 29 + 93 + 2 + 9 + 3
Solve("1293") = 1293 + 129 + 293 + 12 + 29 + 93 + 1 + 2 + 9 + 3
Solve("2395") = 2395 + 239 + 395 + 23 + 39 + 95 + 2 + 3 + 9 + 5
Solve("12395") = 12395 + 1239 + 2395 + 123 + 239 + 395 + 12 + 23 + 39 + 95 + 1 + 2 + 3 + 9 + 5
You have to break f down into two functions.
Let N[i] be the ith digit of the input. Let T[i] be the sum of substrings of the first i-1 characters of the input. Let B[i] be the sum of suffixes of the first i characters of the input.
So if the input is "12395", then B[3] = 9+39+239+1239, and T[3] = 123+12+23+1+2+3.
The recurrence relations are:
T[0] = B[0] = 0
T[i+1] = T[i] + B[i]
B[i+1] = B[i]*10 + (i+1)*N[i]
The last line needs some explanation: the suffixes of the first i+2 characters are the suffixes of the first i+1 characters with the N[i] appended on the end, as well as the single-character string N[i]. The sum of these is (B[i]*10+N[i]*i) + N[i] which is the same as B[i]*10+N[i]*(i+1).
Also f(N) = T[len(N)] + B[len(N)].
This gives a short, linear-time, iterative solution, which you could consider to be a dynamic program:
def solve(n):
rt, rb = 0, 0
for i in xrange(len(n)):
rt, rb = rt+rb, rb*10+(i+1)*int(n[i])
return rt+rb
print solve("12395")
One way to look at this problem is to consider the contribution of each digit to the final sum.
For example, consider the digit Di at position i (from the end) in the number xn-1…xi+1Diyi-1…y0. (I used x, D, and y just to be able to talk about the digit positions.) If we look at all the substrings which contain D and sort them by the position of D from the end of the number, we'll see the following:
D
xD
xxD
…
xx…xD
Dy
xDy
xxDy
…
xx…xDy
Dyy
xDyy
xxDyy
…
xx…xDyy
and so on.
In other words, D appears in every position from 0 to i once for each prefix length from 0 to n-i-1 (inclusive), or a total of n-i times in each digit position. That means that its total contribution to the sum is D*(n-i) times the sum of the powers of 10 from 100 to 10i. (As it happens, that sum is exactly (10i+1−1)⁄9.)
That leads to a slightly simpler version of the iteration proposed by Paul Hankin:
def solve(n):
ones = 0
accum = 0
for m in range(len(n),0,-1):
ones = 10 * ones + 1
accum += m * ones * int(n[m-1])
return accum
By rearranging the sums in a different way, you can come up with this simple recursion, if you really really want a recursive solution:
# Find the sum of the digits in a number represented as a string
digitSum = lambda n: sum(map(int, n))
# Recursive solution by summing suffixes:
solve2 = lambda n: solve2(n[1:]) + (10 * int(n) - digitSum(n))/9 if n else 0
In case it's not obvious, 10*n-digitSum(n) is always divisible by 9, because:
10*n == n + 9*n == (mod 9) n mod 9 + 0
digitSum(n) mod 9 == n mod 9. (Because 10k == 1 mod n for any k.)
Therefore (10*n - digitSum(n)) mod 9 == (n - n) mod 9 == 0.
Looking at this pattern:
Solve("1") = f("1") = 1
Solve("12") = f("12") = 1 + 2 + 12 = f("1") + 2 + 12
Solve("123") = f("123") = 1 + 2 + 12 + 3 + 23 + 123 = f("12") + 3 + 23 + 123
Solve("1239") = f("1239") = 1 + 2 + 12 + 3 + 23 + 123 + 9 + 39 + 239 + 1239 = f("123") + 9 + 39 + 239 + 1239
Solve("12395") = f("12395") = 1 + 2 + 12 + 3 + 23 + 123 + 9 + 39 + 239 + 1239 + 5 + 95 + 395 + 2395 + 12395 = f("1239") + 5 + 95 + 395 + 2395 + 12395
To get the new terms, with n being the length of str, you are including the substrings made up of the 0-based index ranges of characters in str: (n-1,n-1), (n-2,n-1), (n-3,n-1), ... (n-n, n-1).
You can write a function to get the sum of the integers formed from the substring index ranges. Calling that function g(str), you can write the function recursively as f(str) = f(str.substring(0, str.length - 1)) + g(str) when str.length > 1, and the base case with str.length == 1 would just return the integer value of str. (The parameters of substring are the start index of a character in str and the length of the resulting substring.)
For the example Solve("12395"), the recursive equation f(str) = f(str.substring(0, str.length - 1)) + g(str) yields:
f("12395") =
f("1239") + g("12395") =
(f("123") + g("1239")) + g("12395") =
((f("12") + g("123")) + g("1239")) + g("12395") =
(((f("1") + g("12")) + g("123")) + g("1239")) + g("12395") =
1 + (2 + 12) + (3 + 23 + 123) + (9 + 39 + 239 + 1239) + (5 + 95 + 395 + 2395 + 12395)

Number of ways to divide a number

Given a number N, print in how many ways it can be represented as
N = a + b + c + d
with
1 <= a <= b <= c <= d; 1 <= N <= M
My observation:
For N = 4: Only 1 way - 1 + 1 + 1 + 1
For N = 5: Only 1 way - 1 + 1 + 1 + 2
For N = 6: 2 ways - 1 + 1 + 1 + 3
1 + 1 + 2 + 2
For N = 7: 3 ways - 1 + 1 + 1 + 4
1 + 1 + 2 + 3
1 + 2 + 2 + 2
For N = 8: 5 ways - 1 + 1 + 1 + 5
1 + 1 + 2 + 4
1 + 1 + 3 + 3
1 + 2 + 2 + 3
2 + 2 + 2 + 2
So I have reduced it to a DP solution as follows:
DP[4] = 1, DP[5] = 1;
for(int i = 6; i <= M; i++)
DP[i] = DP[i-1] + DP[i-2];
Is my observation correct or am I missing any thing. I don't have any test cases to run on. So please let me know if the approach is correct or wrong.
It's not correct. Here is the correct one:
Lets DP[n,k] be the number of ways to represent n as sum of k numbers.
Then you are looking for DP[n,4].
DP[n,1] = 1
DP[n,2] = DP[n-2, 2] + DP[n-1,1] = n / 2
DP[n,3] = DP[n-3, 3] + DP[n-1,2]
DP[n,4] = DP[n-4, 4] + DP[n-1,3]
I will only explain the last line and you can see right away, why others are true.
Let's take one case of n=a+b+c+d.
If a > 1, then n-4 = (a-1)+(b-1)+(c-1)+(d-1) is a valid sum for DP[n-4,4].
If a = 1, then n-1 = b+c+d is a valid sum for DP[n-1,3].
Also in reverse:
For each valid n-4 = x+y+z+t we have a valid n=(x+1)+(y+1)+(z+1)+(t+1).
For each valid n-1 = x+y+z we have a valid n=1+x+y+z.
Unfortunately, your recurrence is wrong, because for n = 9, the solution is 6, not 8.
If p(n,k) is the number of ways to partition n into k non-zero integer parts, then we have
p(0,0) = 1
p(n,k) = 0 if k > n or (n > 0 and k = 0)
p(n,k) = p(n-k, k) + p(n-1, k-1)
Because there is either a partition of value 1 (in which case taking this part away yields a partition of n-1 into k-1 parts) or you can subtract 1 from each partition, yielding a partition of n - k. It's easy to show that this process is a bijection, hence the recurrence.
UPDATE:
For the specific case k = 4, OEIS tells us that there is another linear recurrence that depends only on n:
a(n) = 1 + a(n-2) + a(n-3) + a(n-4) - a(n-5) - a(n-6) - a(n-7) + a(n-9)
This recurrence can be solved via standard methods to get an explicit formula. I wrote a small SAGE script to solve it and got the following formula:
a(n) = 1/144*n^3 + 1/32*(-1)^n*n + 1/48*n^2 - 1/54*(1/2*I*sqrt(3) - 1/2)^n*(I*sqrt(3) + 3) - 1/54*(-1/2*I*sqrt(3) - 1/2)^n*(-I*sqrt(3) + 3) + 1/16*I^n + 1/16*(-I)^n + 1/32*(-1)^n - 1/32*n - 13/288
OEIS also gives the following simplification:
a(n) = round((n^3 + 3*n^2 -9*n*(n % 2))/144)
Which I have not verified.
#include <iostream>
using namespace std;
int func_count( int n, int m )
{
if(n==m)
return 1;
if(n<m)
return 0;
if ( m == 1 )
return 1;
if ( m==2 )
return (func_count(n-2,2) + func_count(n - 1, 1));
if ( m==3 )
return (func_count(n-3,3) + func_count(n - 1, 2));
return (func_count(n-1, 3) + func_count(n - 4, 4));
}
int main()
{
int t;
cin>>t;
cout<<func_count(t,4);
return 0;
}
I think that the definition of a function f(N,m,n) where N is the sum we want to produce, m is the maximum value for each term in the sum and n is the number of terms in the sum should work.
f(N,m,n) is defined for n=1 to be 0 if N > m, or N otherwise.
for n > 1, f(N,m,n) = the sum, for all t from 1 to N of f(S-t, t, n-1)
This represents setting each term, right to left.
You can then solve the problem using this relationship, probably using memoization.
For maximum n=4, and N=5000, (and implementing cleverly to quickly work out when there are 0 possibilities), I think that this is probably computable quickly enough for most purposes.

Total probability of a given answer of a given number of additions [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
I'm doing C++, and I want to find out the simplest way to find the total probability of a given answer of a given number of additions.
For example, the given answer is 5, and the given number of additions is 4 (x+x+x+x). The total probability that I want to find is 4:
1) 1 + 1 + 1 + 2 = 5
2) 1 + 1 + 2 + 1 = 5
3) 1 + 2 + 1 + 1 = 5
4) 2 + 1 + 1 + 1 = 5
Another example, the given answer is 6, and the given number of additions is 4 (x+x+x+x). The total probability is 10:
1) 1 + 1 + 1 + 3 = 6
2) 1 + 1 + 3 + 1 = 6
3) 1 + 3 + 1 + 1 = 6
4) 3 + 1 + 1 + 1 = 6
5) 1 + 1 + 2 + 2 = 6
6) 1 + 2 + 2 + 1 = 6
7) 2 + 2 + 1 + 1 = 6
8) 2 + 1 + 1 + 2 = 6
9) 2 + 1 + 2 + 1 = 6
10) 1 + 2 + 1 + 2 = 6
I have absolutely no idea where to start
Here's a start for you.
Have a look at this table
1 2 3 4 5
+------------------
1 | 1 0 0 0 0
2 | 1 1 0 0 0
3 | 1 2 1 0 0
4 | 1 3 3 1 0
5 | 1 4 6 4 1
The number of summands is increasing from left to right, the total increases in rows, so e.g. there are 3 ways to sum 3 integers (greater than 0) for a total of 4 (namely 1+1+2, 1+2+1, 2+1+1).
With 4 additions and a result Y, if all numbers will be positive and nonzero and small enough (<100) you can easily at least bruteforce this... just cycle trough all numbers with 4x for cycles and if they sum up to Y increment number of permutations. Disadvantage is the complexity O(N^4) which will be very slow.
#include <iostream>
using namespace std;
int main()
{
int y = 6;
int perm = 0;
for(int a = 1; a < y; a++)
for(int b = 1; b < y; b++)
for(int c = 1; c < y; c++)
for(int d = 1; d < y; d++)
{
if((a+b+c+d)==y)
{
cout << a << " + " << b << " + " << c << " + " << d << " = " << y << endl;
perm++;
}
}
cout << "number of permutations: " << perm << endl;
}
This is not probability what you are trying to find, it's number of comibnations.
Looking at your examples, I assume that the number of numbers you are adding is fixed (i.e. 4), so every number is greater or equal to 1. We can do simple math here then - let's substract this number from both sides of the equation:
Original: 1) 1 + 1 + 1 + 2 = 5
Result of substracting: 1) 0 + 0 + 0 + 1 = 1
When the substraction is done, your problem is the combination with repetition problem.
The formulas you can find in the link I provided are quite simple. The problem can be solved using following code:
#include <iostream>
unsigned factorial(int n)
{
if (n == 1) return 1;
return n * factorial(n-1);
}
unsigned combinationsWithRepetition(int n, int k)
{
return factorial(n + k - 1) / (factorial(k) * factorial(n - 1));
}
unsigned yourProblem(unsigned numberOfNumbers, unsigned result)
{
return combinationsWithRepetition(numberOfNumbers, result - numberOfNumbers);
}
int main()
{
std::cout << yourProblem(4, 5) << std::endl;
std::cout << yourProblem(4, 6) << std::endl;
return 0;
}
Also, you can check this code out in online compiler.
Note that this code covers only the problem solving and could be improved if you choose to use it (i.e. it is not protected against invalid values).

Resources