number of ways of distribution - algorithm

if we have n different things and we need to distribute them among m different people then how many ways can we do it such that for each of the m persons there is conditions that:
person 1 can have at least a things and at most b things
person 2 can have at least c things and at most d things
.. and so on ?
e.g if n = 5 and m =3 and the conditions are:
person 1 can receive at least 0 and at most 1 gift
person 2 can receive at least 1 and at most 3 gift
person 3 can receive at least 1 and at most 4 gift
then the number of ways of distributing these 5 gifts is 6((0 1 4), (0 2 3), (0 3 2), (1 1 3), (1 2 2), (1 3 1)).
One way i believe is to iterate through all possible combinations for each range and see which ones sum upto n , but can't think of an efficient algorithm.
Thanks

You probably want to use a generating function approach. Represent the number of objects that person i gets by the exponents of x. This means that if person i can have at least 3 and at most 7 things, this corresponds to the term
x^3 + x^4 + x^5 + x^6 + x^7
Remember to think of + as OR and * as AND. If we want to impose conditions and person 1 and person 2, then multiply their functions together. For example, with person 1 having between 3 and 7 things, and say person 2 has at least 5 things, and add a third person with at most 10 things. Then we get:
(x^3 + x^4 + x^5 + x^6 + x^7) * (x^5 + x^6 + ... ) * (1 + x + x^2 + ... + x^10)
which can also be written as
(x^3 + x^4 + x^5 + x^6 + x^7) * ( x^5/(1+x) ) * (1 + x + x^2 + ... + x^10)
The way to get information back from this is the following. The coefficient of x^M in the expansion of these terms gives the number of ways to distribute a total of M things among all the people subject to the given constraints.
You can work this out from the formulas, or write a program to extract the coefficient, but the idea is to use generating functions as a convenient and efficient way to encode the constraints along with the answer.

Related

Scoring results based on an ideal solution

I am searching through a large number of possible outcomes and, while I may not find the perfect outcome, I would like to score the various outcomes to see how close they come to ideal. (I think I'm talking about some kind of weighted scoring, but don't let that influence your answer in case I'm completely off base.)
For some context, I'm generating a variety of work schedules and would like to have each result scored such that I don't have to look at them individually (it's a brute force approach, and there are literally billions of solutions) to determine if one is better or worse than any other one.
Input-wise, for each generated schedule, I have a 3x14 array that holds the total number of people that are scheduled to work each shift on any given day (i.e. for each day in a two-week period, the number of people working days, swings, and mids on that day).
So far, I have tried:
A) summing the values in each row, then multiplying each sum (row) by a weight (e.g. row 0 sum * 1, row 1 sum * 2, row 2 sum * 3, etc.), and finally adding together the weighted sums
function calcScore(a)
dim iCol, iTotalD, iTotalM, iTotalS
for iCol = 0 to 13
iTotalD = iTotalD + a(0)(iCol)
iTotalS = iTotalS + a(1)(iCol)
iTotalM = iTotalM + a(2)(iCol)
next
calcScore = iTotalD + iTotalS * 2 + iTotalM * 3
end function
And
B) multiplying each value in each row by a weight (e.g. row 0(0) * 1, row 0(1) * 2, row 0(2) * 3, etc.), and then summing the weighted values of each row
function calcScore(a)
dim iCol, iTotalD, iTotalM, iTotalS
for iCol = 0 to 13
iTotalD = iTotalD + a(0)(iCol) * (iCol + 1)
iTotalS = iTotalS + a(1)(iCol) * (iCol + 1)
iTotalM = iTotalM + a(2)(iCol) * (iCol + 1)
next
calcScore = iTotalD + iTotalS + iTotalM
end function
Below are some sample inputs (schedules), both ideal and non-ideal. Note that in my ideal example, each row is the same all the way across (e.g. all 4's, or all 3's), but that will not necessarily be the case in real-world usage. My plan is to score my ideal schedule, and compare the score of other schedules to it.
Ideal:
Su Mo Tu We ...
Day: 4 4 4 4 ...
Swing: 3 3 3 3 ...
Mid: 2 2 2 2 ...
Not Ideal:
Su Mo Tu We ...
Day: 3 4 4 4 [D(0) is not 4]
Swing: 3 3 3 3
Mid: 2 2 2 2
Not Ideal:
Su Mo Tu We ...
Day: 4 4 4 4
Swing: 3 3 4 3 [S(2) is not 3]
Mid: 0 2 2 2 [M(0) is not 2]
Summarizing my comments into an answer.
So you have an optimal/ideal/perfect solution and want to compare other solutions to it. In this case you could for example compute the sum of (squared) errors. If you need a score you can invert the error.
Specifically, you would have to calculate the sum of (squared) differences between a solution and the optimal by looking at each entry of your matrix and calculating the difference. Sum these (squared) differences up and you get the error.
For the examples you gave the sum of errors are as follows:
E(Ideal, Not Ideal 1) = 1
E(Ideal, Not Ideal 2) = 3
The sum of squared errors would yield the following:
SQE(Ideal, Not Ideal 1) = 1
SQE(Ideal, Not Ideal 2) = 5
Usually, the sum of squared errors is used in order to penalize larger errors more than several small errors.

Finding number representation in different bases

I was recently solving a problem when I encountered this one: APAC Round E Q2
Basically the question asks to find the smallest base (>1) in which if the number (input) is written then the number would only consist of 1s. Like 3 if represented in base 2 would become 1 (consisting of only 1s).
Now, I tried to solve this the brute force way trying out all bases from 2 till the number to find such a base. But the constraints required a more efficient one.
Can anyone provide some help on how to approach this?
Here is one suggestion: A number x that can be represented as all 1s in a base b can be written as x = b^n + b^(n-1) + b^(n-2) + ... + b^1 + 1
If you subtract 1 from this number you end up with a number divisble by b:
b^n + b^(n-1) + b^(n-2) + ... + b^1 which has the representation 111...110. Dividing by b means shifting it right once so the resulting number is now b^(n-1) + b^(n-2) + ... + b^1 or 111...111 with one digit less than before. Now you can repeat the process until you reach 0.
For example 13 which is 111 in base 3:
13 - 1 = 12 --> 110
12 / 3 = 4 --> 11
4 - 1 = 3 --> 10
3 / 3 = 1 --> 1
1 - 1 = 0 --> 0
Done => 13 can be represented as all 1s in base 3
So in order to check if a given number can be written with all 1s in a base b you can check if that number is divisble by b after subtracting 1. If not you can immediately start with the next base.
This is also pretty brute-forcey but it doesn't do any base conversions, only one subtraction, one divisions and one mod operation per iteration.
We can solve this in O( (log2 n)^2 ) complexity by recognizing that the highest power attainable in the sequence would correspond with the smallest base, 2, and using the formula for geometric sum:
1 + r + r^2 + r^3 ... + r^(n-1) = (1 - r^n) / (1 - r)
Renaming the variables, we get:
n = (1 - base^power) / (1 - base)
Now we only need to check power's from (floor(log2 n) + 1) down to 2, and for each given power, use a binary search for the base. For example:
n = 13:
p = floor(log2 13) + 1 = 4:
Binary search for base:
(1 - 13^4) / (1 - 13) = 2380
...
No match for power = 4.
Try power = 3:
(1 - 13^3) / (1 - 13) = 183
(1 - 6^3) / (1 - 6) = 43
(1 - 3^3) / (1 - 3) = 13 # match
For n around 10^18 we may need up to (floor(log2 (10^18)) + 1)^2 = 3600 iterations.

Unique combinations of numbers that add up to a sum

I was asked this in an interview recently and got completely stumped. I know there are questions like this asked on here before but none handled the little twist thrown onto this one.
Given a number, find all possible ways you can add up to it using only the numbers 1,2,3. So for an input of 3, the output would be 4 because the combinations would be 1,1,1 and 1,2 and 2,1 and 3. I know about the coin change algorithm but it doesn't give me that permutation of 1,2 and 2,1. So I just ended up implementing the coin change algorithm and couldn't get the permutation part. Does anybody have any ideas?
It's a recursive problem:
take for example the possible options for 5
X X X X X
1 X X X X
2 X X X
3 X X
So
f(5)=f(4) + f(3) + f(2)
So the generic solution is
f(1)=1
f(2)=2
f(3)=4
f(N)= f(N-1) + f(N-2) + f(N-3) for N > 3
To answer your question about classification of the problem it looks like dynamic programming problem to me. See following question taken from stanford.edu
1-dimensional DP Example
◮ Problem: given n, find the number of different ways to write
n as the sum of 1, 3, 4
◮ Example: for n = 5, the answer is 6
5 = 1 + 1 + 1 + 1 + 1
= 1 + 1 + 3
= 1 + 3 + 1
= 3 + 1 + 1
= 1 + 4
= 4 + 1
And here is the solution to similar problem

Summarize different category rankings

I determine the rankings of i.e. 1000 participants in multiple categories.
The results are something like that:
Participant/Category/Place (lower is better):
A|1|1.
A|2|1.
A|3|1.
A|4|7.
B|1|2.
B|2|2.
B|3|2.
B|4|4.
[...]
Now I want to summarize the rankings. The standard method would be to sum up all places and divide it by the number of categories:
Participant A: (1+1+1+7) / 4 = 2,5
Participant B: (2+2+2+4) / 4 = 2,5
But I want to prefer participant A, because he's won 3 of 4 categories.
I could define fixed points for all places, i.e:
Place|Points
1|1000
2|500
3|250
4|125
5|62.5
6|31.25
7|15.625
[...]
Participant A: 1000+1000+1000+15.625 = 3015.625
Participant B: 500+500+500+125 = 1625
The problem is now, that I want to give every place some points, so it's still possible to sort low places. And when I continue to divide the available points by 2, the maximum number of decimal places are insufficient (Available points /2^Number of places).
What can I do?
How about using harmonic mean?
4 / (1/1 + 1/1 + 1/1 + 1/7) = 1.272727
4 / (1/2 + 1/2 + 1/2 + 1/4) = 2.285714

How many total gifts in the twelve days of christmas if we extend 12 to any number?

I got this question today in an interview: write a function to calculate the total number of gifts received for any day in the 12 days of christmas song. I wrote a simple function using a for() loop in c#'ish code that worked. Then the interviewer asked me to extend it to any number of days. The conversation then turned to how to optimize the loop. Apparently there's a cool math trick that will do this within the limits of whatever your integer is. Anyone know what it is and what it's called? Any language is ok and a reference to the algorithm would be fabuloso.
Answers that use recursion are NOT what I'm looking for.
EDIT: Answer for day 2 is 4 gifts total, not 3 since I will have 2 Trees (1 from today, 1 from yesterday) and 2 partridges. On day 12 I'll have received a total of 364. I want the formula that lets me input 12 and get 364.
On the first day, you get 1.
On the second day, you get 1 + 2.
On the third day, you get 1 + 2 + 3.
...
On nth day, you get 1 + 2 + 3 + ... + n.
The sum 1 + 2 + ... + n is n(n+1)/2. So the total number, T(N) is the sum of n(n+1)/2 for n in 1..N, where N is the number of days.
Now, n(n+1)/2 = n^2 / 2 + n / 2, and sum of n^2 for n in 1..N is N(N+1)(2N+1)/6, so you get:
T(N) = N(N+1)(2N+1)/12 + N(N+1)/4
= N(N^2 + 3N + 2) / 6
No loops. No recursion.
The $P$-th type of present (where the $1$st is partridges, the $2$nd is turtle doves, etc.) comes in quantities of $P = \sum_{X = 1}^{P} 1$.
On day $D$, you receive presents of type $1$ through $D$, for a total of $\sum_{P = 1}^{D} \sum_{X = 1}^{P} 1$ many presents on that day.
And so, if the days run from $1$ through $N$ (canonically, $N$ is 12, but our interest now is in allowing it to vary), you receive overall $\sum_{D = 1}^{N} \sum_{P = 1}^{D} \sum_{X = 1}^{P} 1$.
This counts the number of non-decreasing triples $1 \leq X \leq P \leq D \leq N$.
This is the same as the number of increasing triples $1 \leq X < P + 1 < D + 2 \leq N + 2$.
So the answer is $\binom{N + 2}{3} = \frac{(N + 2)(N + 1)N}{6}$.
On the n th day, we get 1 + 2 + 3 + ... + n gifts.
Or ... (1 + n) + (2 + n-1) + ...
In other words, (n + 1) * n/2.
You receive 364 gifts.
1
2+1=3
3+2+1=6
4+3+2+1=10
5+4+3+2+1=15
6+5+4+3+2+1=21
7+6+5+4+3=2+1=28
8+7+6+5+4+3+2+=36
9+8+7+6+5+4+3+2+1=45
10+9+8+7+6+5+4+3+2+1=55
11+10+9+8+7+6+5+4+3+2+1=66
12+11+10+9+8+7+6+5+4+3+2+1=78
If you add all of them up you’ll get 364.

Resources