Golfscript (3128 31 37)
~):$\.($\?:@;?,{@+}%{$base$,\-[0]=},,
Modification to gnibbler
's GolfScript solution. I think this is a working solution - tested with [3,2], [4,2], [6,3], and [9,2] with correct answers. (I used $
and @
for variables to tighten up space around the base
keyword).
There are two problems with gnibbler
's current solution.
- Checking length after removing [0] does not guarantee a solution, because [1,1,1,1] would be valid for input [4,2], even though all 4 balls are in the same cell (1). So I've modified to check also that all digits are used, i.e., the array contains 1-2, so each cell contains at least one ball.
- In the case of input [4,2], the base-3 format of numbers 0-27 are less than 4 digits, and the left-most 0's are not included. That means [1,1] is included as a valid solution, even though it is technically actually [0,0,1,1], which means the first two balls are not placed anywhere. I fix by adding 3^3 to every entry (generically k^n-1 to the array of k^n entries) so that the first entries are shifted upward to having at least n-digits in base-k format, and the last entries will automatically be invalid anyway and won't affect the solution (because the second digit will always be 0).
Edit
~:@\?:$,{$+}%{@base(;@,\-,0=},,
~`~:@\?:$,{$+}%{@base$+@base(;@,\-,0=},,`
Better solution yet! No need to increment, just add to all of the numbers so they start with [1], and no digits will be missing (including the left-padding of 0's) once you decon that first digit. This solution should work and has been tested with same entries above. It's also a lot faster because we aren't incrementing before taking exponent to generate the array (but still suffers from same performance / memory problem for larger input).
Edit: Use gnibbler
's idea of moving the addition of $
inside of the filter instead of as an extra step. (save 3 chars).