Escriba un programa o función que tome una matriz de enteros no negativos como entrada y genere un conjunto de vectores / matrices con los elementos de la matriz de entrada en orden, divídalos de modo que cada vector sume hasta 15. Si la suma de los primeros N elementos no "golpean 15", entonces el número que hizo pasar 15 debe cortarse, y el resto será el primer elemento del siguiente vector. Esto continúa hasta llegar al final de la matriz de entrada. Si la suma del vector final es menor que 15, entonces se debe agregar un número al final para que la suma suba.
Creo que las reglas se entienden más fácilmente mirando los ejemplos:
Input: 3 7 5 10
Output:
3 7 5 <- Sum is 15
10 5 <- 5 is added to make the sum 15
Input: 2 4 5 9 2 3 5 0 2 4 5 0 3
Output:
2 4 5 4 <- Sum 15. 9 is split in two.
5 2 3 5 <- The first 5 is the remainder of 9
0 2 4 5 0 3 1 <- The last number is added to make the sum 15
Input: 1 1 1
Output:
1 1 1 12 <- The number 12 is added to make the sum 15
Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Output:
1 2 3 4 5
6 7 2 <- 2 is the first part of 8
6 9 <- 6 is the remainder of 8
10 5 <- 5 is first part of 11
6 9 <- 6 is remainder of 11. 9 is first part of 12
3 12 <- 3 is remainder of 12. 12 is first part of 13
1 14 <- 1 is remainder of 13. 14 is 14
15
15 <- 15 is first part of 16
1 14 <- 1 is remainder of 16. 14 is first part of 17
3 12 <- 3 is remainder of 17. 12 is added to make the sum 15
Input: 20 20
Output:
15
5 10 <- 5 is remainder from the first 20
10 5 <- 10 is remainder from second 20. 5 is added to make the sum = 15.
Tanto el formato de entrada como el de salida son opcionales. Lo que sea mejor en tu idioma.
El código más corto en bytes gana.
Tabla de clasificación
El Fragmento de pila al final de esta publicación genera el catálogo a partir de las respuestas a) como una lista de la solución más corta por idioma yb) como una tabla de clasificación general.
Para asegurarse de que su respuesta se muestre, comience con un título, usando la siguiente plantilla de Markdown:
## Language Name, N bytes
¿Dónde N
está el tamaño de su envío? Si mejora su puntaje, puede mantener los puntajes antiguos en el título, tachándolos. Por ejemplo:
## Ruby, <s>104</s> <s>101</s> 96 bytes
Si desea incluir varios números en su encabezado (por ejemplo, porque su puntaje es la suma de dos archivos o desea enumerar las penalizaciones de la bandera del intérprete por separado), asegúrese de que el puntaje real sea el último número en el encabezado:
## Perl, 43 + 2 (-p flag) = 45 bytes
También puede hacer que el nombre del idioma sea un enlace que luego aparecerá en el fragmento:
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
fuente
[[3, 7, 5], [10, 5]]
que sería una salida válida para el primer caso de prueba?Input: 100 Output: 15; 15; 15; 15; 15; 15; 10 5
Respuestas:
Pyth, 37 bytes
Explicado
Este fue mi primer pitón, así que siéntase libre de sugerir mejoras.
Ejemplo:
Entrada
Salida
Nota: ¡ Muchas gracias a Isaacg por varios bytes de consejos de reducción de tamaño y por crear Pyth en primer lugar! Por favor vota sus comentarios a continuación :)
fuente
.?
lugar deE
, pero olvidé actualizar los documentos. Lo siento por eso.=Z+ZN
and=+ZN
are the same. It's a bit like Python's+=
. Likewiese,=Z-ZK
->=-ZK
. Also, you don't need the)
at the end - it's filled in automatically. Finally,FNQ
andVQ
are the same.I>Z0
withIZ
-Z
can't be negative, so you're really just checking ifZ
is not zero, and zero is falsy, while all other numbers are truthy.Java -
229200192181172170168 bytesHad already begun, not for the win but for the fun :)
Any suggestion is welcome.
Saved 8 bytes thanks to @ThomasKwa
Saved 20 bytes thanks to @corsiKa
Saved 2 bytes thanks to @Ypnypn
Saved 2 bytes thanks to @user902383
170 bytes
172 bytes
181 bytes
192 bytes
200 bytes
229 bytes
fuente
Python 3 - 1̶7̶7̶ 1̶3̶8̶ 1̶6̶6̶ 1̶3̶3̶ 113
Edit 5 Truly golfed thanks to @poke *removed line breaks etc
Edit 4 Aliased print, and replaced a = with a -= to save a byte. Thanks to @poke and @elzell. Also moved input eval into for loop to save 2 bytes from assignment
Edit 3 Found savings in different OO inside second if
Edit 2 Fixed bug
Edit 1 Changed the input to be in the form '[1,2,3,4,5...]', and implemented first two comments, big thanks to @Morgan Thrapp
First time poster here. Input is command line with entries separated by spaces, output is entry per line, with a newline between groupings.
fuente
print
so often, you should save it as a variable:p=print
. Saves you another 14 characters.if s>i:s-=i;p(e-s);p();e=s
for the second one. That saves you line breaks and indentation characters.Haskell,
126107102100 bytesUsage example:
(#[]).(++[14]) $ [1..17]
->[[1,2,3,4,5],[6,7,2],[6,9],[10,5],[6,9],[3,12],[1,14],[15],[15],[1,14],[3,12]]
Edit: @Stewie Griffin helped me saving 19 bytes. Thanks!
fuente
CJam, 39 bytes
Test it here.
This feels very suboptimal, but so far all my attempts at a shorter solution have been foiled by the presence of zeros in the input.
fuente
Python2powered by RegEx:
158155 bytesMade in python with love and almost no math.
Or Regex Math if you will, unary math.
'Real' math used only to 'fix' the last requirement:
Codegolfed:
The way this works is by converting each number N into a string of length N (x chosen as the char to fill up the string) and joining them all into a space separated
string
. Resulting string is split via RegEx BLACK MAGIC into something like:for an input like:
f([1, 2, 3, 4, 5, 6, 7, 8, 10])
That's then split again, and the length of consecutive
x
es is used to create the numbers again, everything packed nicely in a list comprehension.Ungolfed:
Output:
Note: there wasn't enough magic for the 0s so this entry disqualifies
fuente
Seriously, 88 bytes
Try it online
It's my first Seriously answer! Now I'm intimately familiar with all the language's shortcomings!
Hex Dump:
Explanation:
fuente
Javascript,
138128 bytesWith whitespace:
Example:
Assign the function to a variable
Then evaluate like so:
Revision history:
12/3/2015 00:02 - Thanks to user81655(+1 him in the comments) for 10 byte improvement
12/2/2015 21:44 - Switched to use functional style in-order to reduce size.
fuente
f=
is not needed according to site rules, remove the parentheses from(i)
, surround witheval
so you don't needreturn
or the brackets and replace theif
with a ternary so thato
is returned and change'\n'
to`\n`
, merget+=...
witht>=m
to remove for loop brackets. Here's your solution in 127 bytes with all these improvements:i=>eval("for(o=z=n='',m=15,t=q=0;q<i.length;q++)(t+=c=+i[q])>=m?(t-=m,z+=c-t,o+=z+`\n`,z=t>0?t+' ':n):z+=c+' ';t<m?o+z+(m-t):o")
o+
at the end of the line. Deleteo+=z
and write it again and it will work. :P\n
makes any difference`\n`
? It won't work without it because the code is inside"..."
because of theeval
.Python 3: 139 bytes
Slightly different approach than the other answer. Produces the actual output from the question because I initially assumed that was a requirement.
Example usage:
fuente
Perl, 86 bytes
Counting the shebang as three, input is taken from stdin, space separated.
Sample Usage
fuente
R, 155 bytes
With indents and linebreaks:
Usage:
fuente
Python 2, 117 bytes
Takes input as list:
fuente
Perl, 76 bytes
Includes +3 for
-p
(normally +1, but +3 to play fair with the other perl solution)Run with the input on STDIN (final newline on input is optional, but MUST be absent for the empty input)
sum15.pl
:Look ma, no calculations whatsoever...
fuente
0
s are rather tricky in this solution (represented by extra spaces) and I have to be very careful to properly handle spaces to keep the number of0
s correct. In particular consider inputs where a partial sum is exactly 15, like1 14 2 13
. Try them without the ` ?` and see what happensJava -
158155 bytesLambda version of https://codegolf.stackexchange.com/a/65590/46866 by yassin-hajaj, Not sure if a valid submission, but dont have enough rep to add a comment on the linked answer. Counted using http://meta.codegolf.stackexchange.com/questions/4944/byte-counter-snippet
158 Bytes
Ungolfed
can be used like
fuente