Suma matricial no superpuesta
Dadas k matrices de longitud n , genere la suma máxima posible utilizando un elemento de cada matriz, de modo que no haya dos elementos del mismo índice. Se garantiza que k <= n.
Entrada
Una lista no vacía de matrices no enteras de enteros.
Salida
Un entero que representa la suma máxima.
Ejemplos
Input -> Output
[[1]] -> 1
[[1, 3], [1, 3]] -> 4
[[1, 4, 2], [5, 6, 1]] -> 9
[[-2, -21],[18, 2]] -> 0
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> 15
[[1, 2, 3, 4], [5, 4, 3, 2], [6, 2, 7, 1]] -> 16
[[-2, -1], [-1, -2]] -> -2
code-golf
array-manipulation
Quintec
fuente
fuente

Respuestas:
Jalea ,
106 bytesPruébalo en línea!
(4 bytes salvados por @Dennis, quien señaló que la jalea tenía una "suma de diagonal principal" incorporado que estaba. No esperaba que tuviera uno de esos; la solución anterior implementa la operación sin necesidad de utilizar la orden interna La operación en cuestión,.
Æṭ, se define como "traza", pero la traza solo se define para matrices cuadradas; Jelly implementa una generalización a matrices rectangulares también.)La mejora con respecto a las otras respuestas se debe principalmente a un algoritmo más simple (por lo tanto, más difícil de expresar); Este programa se escribió originalmente en Brachylog v2 (
{\p\iᶠ∋₎ᵐ+}ᶠot), but Jelly has some builtins for parts of the program that have to be spelled out in Brachylog, so this came out shorter.Explicación
Debe quedar claro que para cualquier solución al problema, podemos permutar las columnas de la matriz original para colocar esa solución en la diagonal principal. Entonces, esta solución simplemente revierte eso, encontrando todas las diagonales principales posibles de permutaciones.
Note that the "permute the columns" operation is done as "transpose, permute the rows" without bothering to transpose back; the rest of the algorithm happens to be symmetrical about the main diagonal, so we don't need to undo the transpose and thus can save a byte.
fuente
ZŒ!ÆṭṀsaves four bytes. Try it online!ZŒ!ŒD§ṀḢbefore remembering thatÆṭwas a thing.J, 28 bytes
Try it online!
Here the recursive call is done by
$:which represents the largest anonymous function containing it. We are lucky in J to have the primitivex u\. y, which appliesuto successive "outfixes" ofyobtained by suppressing successive infixes of lengthxof the items iny; here we want to surpress successive columns to get "minors", so we transpose|:the lower rows (or tail}.) ofy, and then recurse on the transpose of their outfixes.fuente
Python 3,
94 90 89 8480 bytes-4 bytes thanks to xnor (using sets instead of lists)!
Try it online!
fuente
ya set to shorten the membership check:f=lambda x,y={-1}:x>[]and max(e+f(x[1:],y|{i})for(i,e)in enumerate(x[0])if{i}-y).-1trick is really clever :) Thanks a lot!Husk,
12 119 bytesTry it online!
Thanks to BMO for suggesting a port of ais523's answer and a 2-byte save, which I managed to improve on further, and in turn BMO shaved off 2 more bytes.
Previous solution (14 bytes)
Try it online!
I wasn't able to make a test suite because this answer uses the first command line argument command explicitly. But Husk doesn't use STDIN at all so I included all the test cases there, so you can just copy paste in the argument field to check it out. Also note that arrays in Husk may not contain spaces between elements while being inputted.
How it works?
Code breakdown
Example
Let's pick an example:(154621)
One must pick exactly one index from each such that no two indices correspond. So, we generate the length ranges of the rows and only keep those without duplicates, yielding the following combinations (each combination is a column instead of a row to save space):
Then, the program indexes in the input lists with each element of the combination, returning:
Summing all those results (here, each column, for the aforementioned reason), one obtains all possible valid sums according to the criteria, in this case9 .
fuente
JavaScript (ES6),
7471 bytesThanks to @tsh for identifying 2 useless bytes that were used to fix a bug
Saved 3 bytes thanks to @tsh
Try it online!
fuente
0from input array,-1+(-1)is-2and it is correct answer.f=([a,...r],k,i=1)=>a?Math.max(...a.map(c=>k&(i+=i)?-1/0:c+f(r,k|i))):0It's strange, butMath.maxsaves bytes...Jelly,
1312 bytesTry it online!
Alternate version, 11 bytes
This uses the newly added
œ!built-in, which generates all permutations of a given length.Try it online!
How it works
fuente
XLṗLinstead ofJ€Œp.Haskell, 65 bytes
Try it online!
Explanation & Ungolfed
The function
take i<>drop(i+1)takes a list and removes the element at positioni.The function
fgets each possible elementeat positioni, removes the elements at positionifrom the remaining elements and addseto the recursively computed optimum:And the base case for the empty list is just
0:fuente
Brachylog, 18 bytes
Try it online!
Explanation
fuente
Perl 6,
5049 bytesTry it online!
Decently short, even despite the long
permutationscall. This is an anonymous code block that takes a list of lists and returns a number.Explanation:
fuente
K (oK),
40, 32, 28,19 bytes-13 bytes thanks to ngn!
Try it online!
Initial solution:
Try it online!
Note: Doesn't work for the first test case [[1]]
Explanation:
{ }- function with argumentxfuente
prmcan be applied directly to a list to generate its permutations=, but the result was longer. Is thereflattenin oK?flattenin what sense?(1 2 3; 4 5 6; 7 8 9) -> (1 2 3 4 5 6 7 8 9),/or if you want it to go into deeper structures:,//Haskell, 65 bytes
Try it online!
71 bytes
Try it online!
The
[x|x<-a,y<-a,x==y]==achecks that the elements ofaare distinct. This uses up a surprising number of characters, but I didn't see a shorter way.fuente
Pyth,
1512 bytesTry it online here.
Edit: saved 3 bytes courtesy of issacg
fuente
.PUlhQlcan be replaced by.plh.Vimplicitly ignores any extra entries.05AB1E,
1813 bytesI have the feeling it's overly long, but I'm not sure how to do vectorized indexing byte-efficiently in 05AB1E..And I was indeed right that it was too long.. -5 bytes thanks to @Emigna.Try it online or verify all test cases.
Explanation:
Example run:
[[1,4,2],[5,6,1]]нgL):[1,2,3]œ):[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]ε‚):[[[[1,4,2],[5,6,1]],[1,2,3]],[[[1,4,2],[5,6,1]],[1,3,2]],[[[1,4,2],[5,6,1]],[2,1,3]],[[[1,4,2],[5,6,1]],[2,3,1]],[[[1,4,2],[5,6,1]],[3,1,2]],[[[1,4,2],[5,6,1]],[3,2,1]]]ø):[[[[1,4,2],1],[[5,6,1],2]],[[[1,4,2],1],[[5,6,1],3]],[[[1,4,2],2],[[5,6,1],1]],[[[1,4,2],2],[[5,6,1],3]],[[[1,4,2],3],[[5,6,1],1]],[[[1,4,2],3],[[5,6,1],2]]]ε`è]):[[4,1],[4,5],[2,6],[2,5],[1,6],[1,1]](NOTE: 05AB1E is 0-indexed (with automatic wraparound), so indexing3into[5,6,1]results in5.)O):[5,9,8,7,7,2]à):9fuente
нgLœε‚øεè]OZ` for 13.Haskell, 84 bytes
Try it online!
fuente
Ruby,
747269 bytesTry it online!
fuente
05AB1E, 7 bytes
Port of @ais523's Jelly CW answer, so make sure to upvote it as well!
Try it online or verify all test cases.
Explanation:
fuente