highschool text problem: " In how many ways can 10 numbered balls be distributed in four numbered compartments so that the first compartment contains 4, the second 3, the third 2 and the fourth 1 balls each (4+3+2+1=10)? The sequence of balls within the compartments be irrelevant."
Well, the answer is simple, 210×20×3×1=12600. A valid 4-tuple would be, for example:
( {1, 6, 9, 10}, {2, 3, 8}, {5, 7}, {4} )
Today i tried to build the list with 12600 such entries, and it involved a lot of MapThread, Thread, so i revisted this thread to check how we did things. I managed to produce the list but my coding feels awkward because i always worked with 2 lists at a time. The question is, is there a more elegant way of producing the output, maybe by feeding all four lists (sub4, sub3, sub2, rest2) at the same time in a single MapThread[Thread[]] statement?
del[from_List, this_List] := DeleteCases[from, Alternatives @@ this] ;
nUrne = Range[10] ;
sub4 = Subsets[nUrne, {4}] ; (*210 elements e.g. {1,2,3,4}*)
rest4 = del[nUrne, #] & /@ sub4 ; (* 210 elements e.g. {5,6,7,8,9,10}*)
sub3 = Subsets[#, {3}] & /@ rest4 ;
rest3 = MapThread[Function[{u, v}, del[u, #] & /@ v], {rest4, sub3}] ;
sub2 = MapAt[Subsets[#, {2}] &, rest3, {All, All}] ;
rest2 = MapThread[Function[{u, v}, del[u, #] & /@ v], {rest3, sub2}, 2] ;
sub2rest2 = MapThread[List, {sub2, rest2}, 3] ;
sub3sub2rest2 = MapThread[Thread[{##}, List, -1] &, {sub3, sub2rest2}, 2] ;
rest6 = MapAt[Sequence @@ # &, sub3sub2rest2, {All, All, All, 2}] ;
rest6neu = Flatten[#, 1] & /@ rest6 ;
almost = Flatten[MapThread[Thread[{##}, List, -1] &, {sub4, rest6neu}], 1] ;
finally = MapAt[Sequence @@ # &, almost, {All, 2}]
Heavily shorted output:
{{{1, 2, 3, 4}, {5, 6, 7}, {8, 9}, {10}}, {{1, 2, 3, 4}, {5, 6, 7}, {8, 10}, {9}},
{{1, 2, 3, 4}, {5, 6, 7}, {9, 10}, {8}}, <···12593···> ,
{{7, 8, 9, 10}, {3, 5, 6}, {2, 4}, {1}}, {{7, 8, 9, 10}, {4, 5, 6}, {1, 2}, {3}},
{{7, 8, 9, 10}, {4, 5, 6}, {1, 3}, {2}}, {{7, 8, 9, 10}, {4, 5, 6}, {2, 3}, {1}}}
Thanks for your attention. In any case, this problem was a good beginner's exercise in juggling with Map, MapAt, Thread, MapThread and their combinations.