distributing apples and oranges into boxes. Confused about solution - probability

How many ways are there to discribute 4 identical oranges and 6 distinct apples into 5 distinct boxes
I know you find number of ways for apples which is 5^6.
The solution tells me that the ways for oranges is 8 choose 4.
You then multiply both of them together to get solution, which is 1,093,750
My question is....where does 8 come from, for 8 choose 4???

The number of ways you can stick the 4 identical oranges into 5 distinct boxes is the same as the number of nonnegative integer solutions to the problem:
x1 + x2 + x3 + x4 + x5 = 4
Suppose I take 4 1's and 4 separating +'s. Then there is a one-to-one correspondence between orderings of 1's and +'s and solutions of the equation.
For example, "1++11+1+" corresponds to "1 + 0 + 2 + 1 + 0".
There are 8! ways to order these 8 symbols, and because there are 4 identical 1's and 4 identical +'s we need to divide by 4! twice.
8! / (4! × 4!) = 8 choose 4
In general, the number of ways to put n identical objects into r distinct bins is [(n + r - 1) choose (r - 1)]. (r - 1 is referring to the number of "separating '+' symbols.")

Although there is a easy mathematical solution I give you the programming solution because other answer would be of topic:
consider every possible arrangement of oranges in boxes, and do it with recursion:
1.no orange in the last box: it is similar to you have 4 similar oranges and 4 distinct boxes.
2.one orange in the last box: it is similar to you have 3 similar oranges and 4 distinct boxes.
and so on ...
now for making it to program use a function like this:
int orangeRecursion(int numOfOranges,int numOfBoxes){
if(numOfOranges == 0)
return 1;
if(numOfBoxes == 0)
return 0;
int num = 0;
for(int i = 0 ; i<=numOfOranges ; i++){
num += orangeRecursion(numOfOranges - i,numOfBoxes - 1)
}
return num;
}

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.

Strategy with regard to how to approach this algorithm?

I was asked this question in a test and I need help with regards to how I should approach the solution, not the actual answer. The question is
You have been given a 7 digit number(with each digit being distinct and 0-9). The number has this property
product of first 3 digits = product of last 3 digits = product of central 3 digits
Identify the middle digit.
Now, I can do this on paper by brute force(trial and error), the product is 72 and digits being
8,1,9,2,4,3,6
Now how do I approach the problem in a no brute force way?
Let the number is: a b c d e f g
So as per the rule(1):
axbxc = cxdxe = exfxg
more over we have(2):
axb = dxe and
cxd = fxg
This question can be solved with factorization and little bit of hit/trial.
Out of the digits from 1 to 9, 5 and 7 can rejected straight-away since these are prime numbers and would not fit in the above two equations.
The digits 1 to 9 can be factored as:
1 = 1, 2 = 2, 3 = 3, 4 = 2X2, 6 = 2X3, 8 = 2X2X2, 9 = 3X3
After factorization we are now left with total 7 - 2's, 4 - 3's and the number 1.
As for rule 2 we are left with only 4 possibilities, these 4 equations can be computed by factorization logic since we know we have overall 7 2's and 4 3's with us.
1: 1X8(2x2x2) = 2X4(2x2)
2: 1X6(3x2) = 3X2
3: 4(2x2)X3 = 6(3x2)X2
4: 9(3x3)X2 = 6(3x2)X3
Skipping 5 and 7 we are left with 7 digits.
With above equations we have 4 digits with us and are left with remaining 3 digits which can be tested through hit and trial. For example, if we consider the first case we have:
1X8 = 2X4 and are left with 3,6,9.
we have axbxc = cxdxe we can opt c with these 3 options in that case the products would be 24, 48 and 72.
24 cant be correct since for last three digits we are left with are 6,9,4(=216)
48 cant be correct since for last three digits we are left with 3,9,4(=108)
72 could be a valid option since the last three digits in that case would be 3,6,4 (=72)
This question is good to solve with Relational Programming. I think it very clearly lets the programmer see what's going on and how the problem is solved. While it may not be the most efficient way to solve problems, it can still bring desired clarity and handle problems up to a certain size. Consider this small example from Oz:
fun {FindDigits}
D1 = {Digit}
D2 = {Digit}
D3 = {Digit}
D4 = {Digit}
D5 = {Digit}
D6 = {Digit}
D7 = {Digit}
L = [D1 D2 D3] M = [D3 D4 D5] E= [D5 D6 D7] TotL in
TotL = [D1 D2 D3 D4 D5 D6 D7]
{Unique TotL} = true
{ProductList L} = {ProductList M} = {ProductList E}
TotL
end
(Now this would be possible to parameterize furthermore, but non-optimized to illustrate the point).
Here you first pick 7 digits with a function Digit/0. Then you create three lists, L, M and E consisting of the segments, as well as a total list to return (you could also return the concatenation, but I found this better for illustration).
Then comes the point, you specify relations that have to be intact. First, that the TotL is unique (distinct in your tasks wording). Then the next one, that the segment products have to be equal.
What now happens is that a search is conducted for your answers. This is a depth-first search strategy, but could also be breadth-first, and a solver is called to bring out all solutions. The search strategy is found inside the SolveAll/1 function.
{Browse {SolveAll FindDigits}}
Which in turns returns this list of answers:
[[1 8 9 2 4 3 6] [1 8 9 2 4 6 3] [3 6 4 2 9 1 8]
[3 6 4 2 9 8 1] [6 3 4 2 9 1 8] [6 3 4 2 9 8 1]
[8 1 9 2 4 3 6] [8 1 9 2 4 6 3]]
At least this way forward is not using brute force. Essentially you are searching for answers here. There might be heuristics that let you find the correct answer sooner (some mathematical magic, perhaps), or you can use genetic algorithms to search the space or other well-known strategies.
Prime factor of distinct digit (if possible)
0 = 0
1 = 1
2 = 2
3 = 3
4 = 2 x 2
5 = 5
6 = 2 x 3
7 = 7
8 = 2 x 2 x 2
9 = 3 x 3
In total:
7 2's + 4 3's + 1 5's + 1 7's
With the fact that When A=B=C, composition of prime factor of A must be same as composition of prime factor of B and that of C, 0 , 5 and 7 are excluded since they have unique prime factor that can never match with the fact.
Hence, 7 2's + 4 3's are left and we have 7 digit (1,2,3,4,6,8,9). As there are 7 digits only, the number is formed by these digits only.
Recall the fact, A, B and C must have same composition of prime factors. This implies that A, B and C have same number of 2's and 3's in their composition. So, we should try to achieve (in total for A and B and C):
9 OR 12 2's AND
6 3's
(Must be product of 3, lower bound is total number of prime factor of all digits, upper bound is lower bound * 2)
Consider point 2 (as it has one possibility), A has 2 3's and same for B and C. To have more number of prime factor in total, we need to put digit in connection digit between two product (third or fifth digit). Extract digits with prime factor 3 into two groups {3,6} and {9} and put digit into connection digit. The only possible way is to put 9 in connection digit and 3,6 on unconnected product. That mean xx9xx36 or 36xx9xx (order of 3,6 is not important)
With this result, we get 9 x middle x connection digit = connection digit x 3 x 6. Thus, middle = (3 x 6) / 9 = 2
My answer actually extends #Ansh's answer.
Let abcdefg be the digits of the number. Then
ab=de
cd=fg
From these relations we can exclude 0, 5 and 7 because there are no other multipliers of these numbers between 0 and 9. So we are left with seven numbers and each number is included once in each answer. We are going to examine how we can pair the numbers (ab, de, cd, fg).
What happens with 9? It can't be combined with 3 or 6 since then their product will have three times the factor 3 and we have at total 4 factors of 3. Similarly, 3 and 6 must be combined at least one time together in response to the two factors of 9. This gives a product of 18 and so 9 must be combined at least once with 2.
Now if 9x2 is in a corner then 3x6 must be in the middle. Meaning in the other corner there must be another multiplier of 3. So 9 and 2 are in the middle.
Let's suppose ab=3x6 (The other case is symmetric). Then d must be 9 or 2. But if d is 9 then f or g must be multiplier of 3. So d is 2 and e is 9. We can stop here and answer the middle digit is
2
Now we have 2c = fg and the remaining choices are 1, 4, 8. We see that the only solutions are c = 4, f = 1, g = 8 and c = 4, f = 8, g = 1.
So if is 3x6 is in the left corner we have the following solutions:
3642918, 3642981, 6342918, 6342981
If 3x6 is in the right corner we have the following solutions which are the reverse of the above:
8192463, 1892463, 8192436, 1892436
Here is how you can consider the problem:
Let's note the final solution N1 N2 N3 N4 N5 N6 N7 for the 3 numbers N1N2N3, N3N4N5 and N5N6N7
0, 5 and 7 are to exclude because they are prime and no other ciphers is a multiple of them. So if they had divided one of the 3 numbers, no other number could have divided the others.
So we get the 7 remaining ciphers : 1234689
where the product of the ciphers is 2^7*3^4
(N1*N2*N3) and (N5*N6*N7) are equals so their product is a square number. We can then remove, one of the number (N4) from the product of the previous point to find a square number (i.e. even exponents on both numbers)
N4 can't be 1, 3, 4, 6, 9.
We conclude N4 is 2 or 8
If N4 is 8 and it divides (N3*N4*N5), we can't use the remaining even numbers (2, 4, 6) to divides
both (N1*N2*N3) and (N6*N7*N8) by 8. So N4 is 2 and 8 does not belong to the second group (let's put it in N1).
Now, we have: 1st grp: 8XX, 2nd group: X2X 3rd group: XXX
Note: at this point we know that the product is 72 because it is 2^3*3^2 (the square root of 2^6*3^4) but the result is not really important. We have made the difficult part knowing the 7 numbers and the middle position.
Then, we know that we have to distribute 2^3 on (N1*N2*N3), (N3*N4*N5), (N5*N6*N7) because 2^3*2*2^3=2^7
We already gave 8 to N1, 2 to N4 and we place 6 to N6, and 4 to N5 position, resulting in each of the 3 numbers being a multiple of 8.
Now, we have: 1st grp: 8XX, 2nd group: X24 3rd group: 46X
We have the same way of thinking considering the odd number, we distribute 3^2, on each part knowing that we already have a 6 in the last group.
Last group will then get the 3. And first and second ones the 9.
Now, we have: 1st grp: 8X9, 2nd group: 924 3rd group: 463
And, then 1 at N2, which is the remaining position.
This problem is pretty easy if you look at the number 72 more carefully.
We have our number with this form abcdefg
and abc = cde = efg, with those digits 8,1,9,2,4,3,6
So, first, we can conclude that 8,1,9 must be one of the triple, because, there is no way 1 can go with other two numbers to form 72.
We can also conclude that 1 must be in the start/end of the whole number or middle of the triple.
So now we have 819defg or 918defg ...
Using some calculations with the rest of those digits, we can see that only 819defg is possible, because, we need 72/9 = 8,so only 2,4 is valid, while we cannot create 72/8 = 9 from those 2,4,3,6 digits, so -> 81924fg or 81942fg and 819 must be the triple that start or end our number.
So the rest of the job is easy, we need either 72/4 = 18 or 72/2 = 36, now, we can have our answers: 8192436 or 8192463.
7 digits: 8,1,9,2,4,3,6
say XxYxZ = 72
1) pick any two from above 7 digits. say X,Y
2) divide 72 by X and then Y.. you will get the 3rd number i.e Z.
we found XYZ set of 3-digits which gives result 72.
now repeat 1) and 2) with remaining 4 digits.
this time we found ABC which multiplies to 72.
lets say, 7th digit left out is I.
3) divide 72 by I. result R
4) divide R by one of XYZ. check if result is in ABC.
if No, repeat the step 3)
if yes, found the third pair.(assume you divided R by Y and the result is B)
YIB is the third pair.
so... solution will be.
XZYIBAC
You have your 7 numbers - instead of looking at it in groups of 3 divide up the number as such:
AB | C | D | E | FG
Get the value of AB and use it to get the value of C like so: C = ABC/AB
Next you want to do the same thing with the trailing 2 digits to find E using FG. E = EFG/FG
Now that you have C & E you can solve for D
Since CDE = ABC then D = ABC/CE
Remember your formulas - instead of looking at numbers create a formula aka an algorithm that you know will work every time.
ABC = CDE = EFG However, you have to remember that your = signs have to balance. You can see that D = ABC/CE = EFG/CE Once you know that, you can figure out what you need in order to solve the problem.
Made a quick example in a fiddle of the code:
http://jsfiddle.net/4ykxx9ve/1/
var findMidNum = function() {
var num = [8, 1, 9, 2, 4, 3, 6];
var ab = num[0] * num[1];
var fg = num[5] * num[6];
var abc = num[0] * num[1] * num[2];
var cde = num[2] * num[3] * num[4];
var efg = num[4] * num[5] * num[6];
var c = abc/ab;
var e = efg/fg;
var ce = c * e
var d = abc/ce;
console.log(d); //2
}();
You have been given a 7 digit number(with each digit being distinct and 0-9). The number has this property
product of first 3 digits = product of last 3 digits = product of central 3 digits
Identify the middle digit.
Now, I can do this on paper by brute force(trial and error), the product is 72 and digits being
8,1,9,2,4,3,6
Now how do I approach the problem in a no brute force way?
use linq and substring functions
example var item = array.Skip(3).Take(3) in such a way that you have a loop
for(f =0;f<charlen.length;f++){
var xItemSum = charlen[f].Skip(f).Take(f).Sum(f => f.Value);
}
// untested code

Converting a number into a special base system

I want to convert a number in base 10 into a special base form like this:
A*2^2 + B*3^1 + C*2^0
A can take on values of [0,1]
B can take on values of [0,1,2]
C can take on values of [0,1]
For example, the number 8 would be
1*2^2 + 1*3 + 1.
It is guaranteed that the given number can be converted to this specialized base system.
I know how to convert from this base system back to base-10, but I do not know how to convert from base-10 to this specialized base system.
In short words, treat every base number (2^2, 3^1, 2^0 in your example) as weight of an item, and the whole number as the capacity of a bag. This problem wants us to find a combination of these items which they fill the bag exactly.
In the first place this problem is NP-complete. It is identical to the subset sum problem, which can also be seen as a derivative problem of the knapsack problem.
Despite this fact, this problem can however be solved by a pseudo-polynomial time algorithm using dynamic programming in O(nW) time, which n is the number of bases, and W is the number to decompose. The details can be find in this wikipedia page: http://en.wikipedia.org/wiki/Knapsack_problem#Dynamic_programming and this SO page: What's it called when I want to choose items to fill container as full as possible - and what algorithm should I use?.
Simplifying your "special base":
X = A * 4 + B * 3 + C
A E {0,1}
B E {0,1,2}
C E {0,1}
Obviously the largest number that can be represented is 4 + 2 * 3 + 1 = 11
To figure out how to get the values of A, B, C you can do one of two things:
There are only 12 possible inputs: create a lookup table. Ugly, but quick.
Use some algorithm. A bit trickier.
Let's look at (1) first:
A B C X
0 0 0 0
0 0 1 1
0 1 0 3
0 1 1 4
0 2 0 6
0 2 1 7
1 0 0 4
1 0 1 5
1 1 0 7
1 1 1 8
1 2 0 10
1 2 1 11
Notice that 2 and 9 cannot be expressed in this system, while 4 and 7 occur twice. The fact that you have multiple possible solutions for a given input is a hint that there isn't a really robust algorithm (other than a look up table) to achieve what you want. So your table might look like this:
int A[] = {0,0,-1,0,0,1,0,1,1,-1,1,1};
int B[] = {0,0,-1,1,1,0,2,1,1,-1,2,2};
int C[] = {0,1,-1,0,2,1,0,1,1,-1,0,1};
Then look up A, B, C. If A < 0, there is no solution.

Classical Round Table algorithm?

Coins with different value are spread in circle around a round table . We can choose any coin such that for any two adjacent pair of coins , atleast one must be selected (both maybe selected too) . In such condition we have to find minimum possible value of coins selected .
I have to respect time complexity so instead of using naive recursive bruteforce , i tried doing it using dynamic programming . But i get Wrong Answer - my algorithm is incorrect .
If someone could suggest an algorithm to do it dynamically , i could code myself in c++ . Also maximum number of coins is 10^6 , so i think O(n) solution exists .
EDIT : Okay , i also add an example .
If coins value around table is 1,2,1,2,2 (in circle) , then minimum value of coin would be 4 by selecting 1st,3rd & 4th(or 5th) .
Having everything in a circle hampers dynamic programming, because there is no stable start point.
If you knew that a particular coin would be included in the best answer, you could use that as your start point. Renumber it coin 1 and use dynamic programming to work out the best cost of 1..N, with and without the Nth coin selected. Given this you can work out the best cost of 1..N+1 and so on.
Actually you can also use this method if somebody tells you that a particular coin would not be selected - you just have slightly different starting conditions. Or you could use that fact that if you know that a particular coin is not selected, the two on either side of it must be selected.
Any coin is either selected or not, so you can look at the costs both ways, produced by solving two dynamic programming problems, and pick whichever cost is cheapest.
I think the following algorithm will get you the best solution. I have not gone through your code (sorry):
We will select a random point in the circle to start. Say it's 1. We will look at what happens if it would be selected.
So we select 1. Move up in the circle and you get the choice of selecting 2 or not. This can be shown in a tree where the top branch represents selecting the coin and the lower one not selecting the coin. The numbers represent the total sum of the selected coins.
3 = 1 and 2 both selected
/
1
\
1 = 1 selected, 2 not
Now we continue in the circle and get the choice of selecting 3 or not. This gives a tree like
6 = 1, 2 and 3 selected
/
3
/ \
/ 3= 1 and 2 selected, 3 not
/
1
\
\ 4 = 1 and 3 selected, 2 not
\ /
1
\
1 = 1 selected, 2 and 3 not
Now in that tree, we can prune! Given your problem statement, you have to keep track of which coins are taken to make sure every coin is 'covered'. Say the last 2 coins were not selected. Then you know the the next has to be selected in order not to violate your constraints. More importantly, the possibilities in the rest of your algorithm only depend on the choice of the last 2 coins.
Now look at all branches that have selected the last coin (3). You only need to keep the one with the lowest weight. Both those branches are free to choose what they want in the rest of the algorithm. In this case, we can safely remove the top branch. We then have 3 possible paths left.
Now take a look at what happens if we enumerate the choices for coin 4
3 7= 1, 2 and 4 selected, 3 not
/ \ /
/ 3
/ \
3 = 1 and 2 selected, 3 and 4 not
1 8 = 1, 3 and 4 selected, 2 not
\ /
\ 4
\ / \
1 4 = 1 and 3 selected, 2 and 4 not
5 = 1 and 4 selected, 2 and 3 not
\ /
1
\
1 = only 1 selected
Now you have 6 choices. However, the lowest branch (only 1 is selected) is invalid because 3 is not adjacent to anything. You can prune that to have 5 branches left. Of those 5 there are 3 that selected 4 (=the last coin so far) and we can do the same thing as before: only keep the cheapest branch. This reduces the number of branches to 3 again.
You can keep doing this for your whole circle until you reach the start again. Then you should have 3 paths of which you can choose the cheapest. This gives you the best solution if you start of by selecting coin 1.
Now we have the best solution for when 1 is selected. However, It could be that 1 should not be selected. It could be that it is adjacent to another coin that is selected: coin 2 or coin 6. If we now do the above algorithm once for coin 2 instead of coin 1 and once for coin 6 we should have the best solution.
This approach relies on the fact that either coin 1, 2 or 6 is selected.
I hope I made my approach comprehensible. It's rather long and you could do it fasterr by using some state transition diagram in which you only maintain the possible states (which depends on the last 2 coins) and work on that. The methods are the same as above, only more compact)
O(n) suggestion, by induction. Hmm, I read the wiki now and I found out it counts as dynamic programming. Really a broad term. I had a different understanding of dynamic programming before.
Glossary
We have N coins in N places. Coin values are a[i], where 0 <= i < N. Each coin may be selected or deselected which we express as the sequence of 0 and 1.
Algorithm description
00 is invalid sequence in any place, because it would violate the problem constraints. 111 is also invalid because it is not optimal, 101 is always better.
Sequentially for every place i we calculate 3 best sums, for 3 codes: 01, 10, 11. The code comes from the setting of last 2 coins, that is i-1 and i. So we have best (minimum) sums in variables b01, b02, b11.
We have to start from something sure, so we will apply the algorithm 2 times. One for coin at place 0 set, and one for unset.
At the beginning we try places 0 and 1 and initiate bs directly. b01 = a[1], b10 = a[0], b11 = a[0] + a[1]. However if this is the round in which we choose the first coin to be unset, we can accept only b01 solution. So we assign a big number to b10 and b11. These solutions will be quickly dropped by next algorithm steps. On the second round we will do the opposite: assign big nuber to b01, because first bit must be set.
At step i we have best sums for place i-1 in bs. We compute cs which are the best sums for place i.
c01 = b10 + a[i] // 101 (10 -> 01)
c10 = min(b01, b11) // 010 (01 -> 10) or 110 (11 -> 10)
c11 = b01 + a[i] // 011 (01 -> 11)
That comes from following possibilities:
010 - b01 -> c10
011 - b01 -> c11
100 - invalid
101 - b10 -> c01
110 - b11 -> c10
111 - invalid
Of course we finish each step with assigning best sums back to bs.
When we processed all the coins we must drop the solutions that are incompatible with the initial assumption. Bits i-2, i-1 and 0 must produce valid sequences.
This is example run for 123456 sequence.
A. assume first bit 0
1 a[1] = 2: b01 = 2, b10 = 999, b11 = 999
2 a[2] = 3: b01 = 1002, b10 = 2, b11 = 5
3 a[3] = 4: b01 = 6, b10 = 9, b11 = 1006
4 a[4] = 5: b01 = 13, b10 = 6, b11 = 11
5 a[5] = 6: b01 = 12, b10 = 13, b11 = 19
b10 is unacceptable, we choose better from b01 and b11, which is 12.
B. assume first bit 1
1 a[1] = 2: b01 = 999, b10 = 1, b11 = 3
2 a[2] = 3: b01 = 4, b10 = 3, b11 = 1002
3 a[3] = 4: b01 = 7, b10 = 4, b11 = 8
4 a[4] = 5: b01 = 9, b10 = 12, b11 = 12
5 a[5] = 6: b01 = 18, b10 = 9, b11 = 15
Now b11 is invalid as it would produce 111. So we choose best of b01 and b10, which is 9. Step A gave 12, step B gave 9. 9 is better. This is the result.
I made the above calculations manually, so sorry if there is a mistake in them. However for the first coin unset I computed 2+4+6 and for first coin set the result was 1+3+5. Seems to be right.

Looking for a generic, fast, low-memory algorithm to output N-out-of-M combinations of an array without repetitions

I have an array with players
$players = array('A','B','C','D','E','F');
and i want to get every possible 3 way finishing.
1st 2nd 3rd
A B C
A B D
...
C A B
C B A
...
F D E
F E D
I have some permutation algorithm but it must be something else since in permutation there is 6 * 5 * 4 * 3 * 2 * 1 combination and here is only 6 * 5 * 4
Here's some pseudo-code to print your 3 out of 6 combinations without repetition:
for i = 1 to 6
for j = 1 to 6
if (j != i)
for k = 1 to 6
if (k != i && k != j)
print(A[i], A[j], A[k])
end if
next k
end if
next j
next i
For the general k-of-n case see: Algorithm to return all combinations of k elements from n
Given your permutation algorithm, you can use it in two steps to get the desired permutations.
First, let's consider the following mapping. Given input as A1 A2 A3 A4 A5 ... An, a value b1 b2 b3 b4 b5 ... bn means select Ai if bi is 1 and not if it is 0.
With your input, for example:
0 0 1 1 0 1 -> C D F
0 1 0 0 1 1 -> B E F
Now your algorithm can go as follows:
Take n as the number of elements (in your case 6) and m as the number you want to choose from.
Construct the following sequence:
0 0 0 ... 0 1 1 1 ... 1
\____ ____/ \____ ____/
V V
n - m m
Get all permutations of the above sequence and for each:
Find the m elements that are marked in the sequence
Get all permutations of those m elements and for each:
do whatever you want!
Your problem is not finding all permutations of 6 elements.
Your problem is to choose 3 elements, and than check its permutations.
The number of combinations = C(6,3)*3! = 6! / 3! = 6*5*4.
C(6,3) - for choosing 3 elements out of 6. (No matter the order)
3! - for ordering the 3 chosen elements.
This is the exactly number of combinations you should get. (and you do)
However, you can use your permutation algorithm to get all permutations of the 6 elements.
Than, just ignore the last 3 elements, and remove duplicates from the result.
I may be wrong but I think you have the correct amount of possible permutations here. You choose only 3 players among the 6 players array. So for the first player, you have 6 possibilities, for the second player you have 5 possibilities, and for the third player, you have 4 possibilities.
If you decide to have 4 players at the end instead of having 3, the possible amount of permutations would be 6*5*4*3, and so on.
I hope my math is not too old!

Resources