Square from Digits with Largest Sum

Pyth, 15 bytes

s*VSsM^^LTUQ2SQ

Demonstration. Test harness.

Note: Input in any python sequence format, such as a,b,c, or [a, b, c]. Fails on a.

This will be an explanation for the example input 5,8,6,8.

^LTUQ: This is a list of powers of 10, out to the length of Q. [1, 10, 100, 1000].

^ ... 2: Then, we take pairs of powers of 10. [[1, 1], [1, 10], ....

sM: Then, we sum those pairs. [2, 11, 101, ... Each number repesents the value of a grid location. The value of the bottom right corner is 2, because the digit placed there is in the ones place of the two numbers it is in. Note that 16 values were generated, even though we only need 4. This will be handled shortly.

S: Sort the value in increasing order. [2, 11, 11, 20, 101, .... Note that the only values which are relevant for this input are the first 4, because this square will not have hundreds or thousands places.

SQ: Sort the input in ascending order. [5, 6, 8, 8]

*V: Vectorized multiplication over the two lists. Pyth's vectorized multiplication truncates the longer input, so this performs [5*2, 6*11, 8*11, 8*20], equivalent to filling in the grid, smallest to largest, bottom right to top left.

s: Sum the results, 324. Printing is implicit.


CJam, 23 bytes

q~$_,mQ,A\f#2m*::+$.*:+

Try it online. Generates the weights for each cell and assigns the highest digits to the highest weights.

An alternative 23:

q~$_,mQ_,A\f#*_$.+$.*:+

CJam, 25 bytes

q~_e!\,mqf/{_z+Afb:+}%$W=

Pretty straight forward approach. Generate all combinations, get the sum, print largest.

Try it online here