El reto
Dada una entrada entera xdonde 1 <= x <= 255, devuelve los resultados de potencias de dos que, cuando se suman, dan x.
Ejemplos
Dada la entrada:
86
Su programa debería generar:
64 16 4 2
Entrada:
240
Salida:
128 64 32 16
Entrada:
1
Salida:
1
Entrada:
64
Salida:
64
La salida puede contener ceros si la cierta potencia de dos no está presente en la suma.
Por ejemplo, la entrada 65puede salir 0 64 0 0 0 0 0 1.
Tanteo
Este es el código de golf , por lo que gana la respuesta más corta en cada idioma.
                    
                        code-golf
                                binary
                                code-golf
                                sequence
                                integer
                                chess
                                code-golf
                                number
                                arithmetic
                                matrix
                                code-golf
                                code-golf
                                combinatorics
                                grid
                                set-partitions
                                code-golf
                                array-manipulation
                                graph-theory
                                code-golf
                                number
                                code-golf
                                string
                                decision-problem
                                code-golf
                                matrix
                                cellular-automata
                                3d
                                code-challenge
                                restricted-source
                                printable-ascii
                                code-golf
                                board-game
                                code-golf
                                geometry
                                grid
                                code-golf
                                word-puzzle
                                code-golf
                                matrix
                                sorting
                                code-golf
                                code-golf
                                string
                                decision-problem
                                code-golf
                                matrix
                                cellular-automata
                                code-golf
                                decision-problem
                                code-golf
                                math
                                number
                                arithmetic
                                restricted-source
                                code-golf
                                code-golf
                                number
                                integer
                                matrix
                                code-golf
                                date
                                code-golf
                                matrix
                                code-golf
                                sequence
                                combinatorics
                                chemistry
                                code-golf
                                array-manipulation
                                popularity-contest
                                code-golf
                                code-golf
                                natural-language
                                code-golf
                                number
                                integer
                                sorting
                                substitution
                                code-golf
                                string
                                number
                                date
                                encode
                                code-golf
                                decision-problem
                                code-golf
                                string
                                subsequence
                                code-golf
                                string
                                alphabet
                                code-golf
                                
                    
                    
                        SpookyGengar
fuente
                
                fuente

Respuestas:
JavaScript (ES6), 28 bytes
Pruébalo en línea!
fuente
f=n=>n&&f(n&~-n)+[,n&-n].Pure Bash , 20
Pruébalo en línea!
Explicación
fuente
Jalea , 4 bytes
-2 ya que podemos generar ceros en lugar de potencias no utilizadas de 2 :)
Pruébalo en línea!
¿Cómo?
fuente
Jalea , 6 bytes
Pruébalo en línea!
Explicación
PERO aquí hay una explicación (nota: asumí que solo podemos generar los poderes de 2 y nada más):
"Prueba" de que funciona correctamente. La representación estándar de un enteroX  en la base 2 es una lista {x1,x2,x3,⋯,xn}  , donde xi∈{0,1},∀i∈1,n¯¯¯¯¯¯¯¯  , tal que:
X=∑i=1nxi⋅2n−i   
Los índicesi  tal quexi=0  obviamente no tienen contribución, por lo que solo estamos interesados en encontrar aquellos quexi=1  . Desde restari  den  no es conveniente (las potencias de dos tienen exponentes de la forman−i  , dondei  es cualquier índice de un1  ), en lugar de encontrar los índices de verdad en esta lista, lo invertimos y luego los encontramos "al revés"2  a esos poderes.
UT. Ahora que hemos encontrado los índices correctos, todo lo que tenemos que hacer es elevarfuente
’there ...BUT2*Hque funcionaría.Python , 35 bytes
Little-endian con ceros en potencias no utilizadas de 2.
Pruébalo en línea!
fuente
APL (Dyalog Extended) , SBCS de 7 bytes
Función de prefijo tácito anónimo. Requiere indexación basada en 0 (
⎕IO←0).Pruébalo en línea!
2dos*elevado a la potencia de⍸los Ɩ ndices donde la verdadera⍢mientras que⌽invierte⍤de⊤la representación binariafuente
Almádena 0.2, 3 bytes
Se descomprime en
{intLiteral[2],call[NumberExpand,2]}.Sledgehammer es un compresor para el código Wolfram Language que utiliza Braille como página de códigos. El tamaño real de lo anterior es 2.75 bytes, pero debido a las reglas actuales en meta, el relleno al byte más cercano se cuenta en el tamaño del código.
fuente
05AB1E , 3 bytes
Puerto de la respuesta Jelly @JonathanAllan , ¡así que asegúrate de votarlo!
Contiene ceros (incluidas las cargas de ceros finales).
Pruébalo en línea o verifique todos los casos de prueba .
Explicación:
fuente
bitwise andusado en osabie. Buena esa.&. XD He usado Bitwise-XOR un par de veces, como aquí o aquí, y Bitwise-NO una vez aquí (que luego eliminé nuevamente después de jugar más golf ...). Utilizo Bitwise-AND, XOR, OR, NOT, SHIFT, etc. con bastante frecuencia en Java, pero en 05AB1E no tanto. :)Catholicon , 3 bytes
Pruébalo en línea!
Explicación:
fuente
Wolfram Language (Mathematica) , 17 bytes
Pruébalo en línea!
Mathematica ataca de nuevo.
fuente
R ,
2723 bytesPruébalo en línea!
Código desenrollado y explicación:
fuente
C # (compilador interactivo de Visual C #) , 29 bytes
Contiene 5 caracteres no imprimibles.
Explicación
Pruébalo en línea!
fuente
n=>new int[8].Select((j,i)=>1<<i&n).Where(i=>i!=0)La parte anteriorWherees cinco bytes más corta por ciertoThe output may contain zerosn=>new int[8].Select((j,i)=>1<<i&n)tiene 35 bytes de longitud y no necesitaremos marcas adicionales ni codificaciones de texto.n=>"INSERT ASCII HERE".Select(a=>1<<a&n)pero estoy en un dispositivo móvil que no puede mostrar o escribir no imprimibles, así que tendré que esperar hasta llegar a casa para actualizar la respuestaC # (compilador interactivo de Visual C #) , 38 bytes
Pruébalo en línea!
fuente
1,2,4,8,16, etc. (thex>yshould bex>=yinstead)./u:System.Linq.Enumerableand try this for 31 bytes/u:System.Linq.Enumerable" :PC (gcc), 39 bytes
Try it online!
fuente
05AB1E, 7 bytes
explanation:
Try it online!
fuente
Haskell, 29 bytes
Try it online!
fuente
Ruby, 25 bytes
Try it online!
fuente
C (clang),
1331106358 bytes58-byte solution thanks to @ceilingcat.
Try it online!
fuente
main(){}and the return type defaults to int. Same for variables at global scope. Also, at least on normal implementations like clang, printf and scanf work without prototypes. You get warnings of course, but it's still valid C89 (maybe) or at least K&R C for them to be implicitly declared. The types of the C objects you pass as args defines how they're passed, so achar*andint*will Just Work without truncating pointers to 32-bit on x86-64 or anything. (Default argument promotions happen, same as for variadic functions which they are anyway.)&to check if a bit is set. Likey&(1<<x)&&printf("%d ",1<<x);. Or to not skip zeros, justprintf("%d ", y&(1<<x)). Or instead of counting bit positions, usex=256andx>>=1to shift the mask.main(y){int x=256;for(scanf("%d",&y);x>>=1;)printf("%d ",y&x);}63 bytes Try it online! clang will even compile that with-std=c11MATL, 5 bytes
Try it online!
Explanation
Consider input
86as an example.fuente
Perl 6,
1612 bytes-4 bytes thanks to Jonathan Allan
Try it online!
Returns an All Junction with 8 elements. This is a rather non-standard way of returning, but generally, Junctions can act as ordered (at least until autothreading is implemented) lists and it is possible to extract the values from one.
Explanation:
fuente
Japt,
85 bytesTry it
Alternative
Suggested by Oliver to avoid the
0s in the output using the-mfflag.Try it
fuente
N&2pUwith-mfto avoid the0s05AB1E, 9 bytes
Try it online!
This is also correct for 6-bytes, but it doesn't complete in time on TIO for 86:
05AB1E, 6 bytes
Try it online!
fuente
15, instead of[1,2,4,8]2**0, nice catch.ÝoverL.Linstead ofÝat first in my answer.Julia 0.6, 13 bytes
Try it online!
fuente
CJam, 12 bytes
Try it online!
fuente
K (oK),
1916 bytes-3 bytes thanks to ngn!
Try it online!
oK does not have
poweroperator, that's why I need a helper function{*/x#2}(copy 2xtimes and reduce the resulting list by multiplication)fuente
{x}Alchemist, 125 bytes
Try it online! or Test every input!
Explanation
fuente
PHP,
4139 bytesTry it online!
Or 38 with no fun
>>=operator and PHP 5.6+:Or 36 with little-endian ("0 2 4 0 16 0 64 0") output:
Really I just wanted to use the
>>=operator, so I'm sticking with the 39.Tests:
fuente
TSQL,
4339 bytesCan't find a shorter fancy solution, so here is a standard loop. -4 bytes thanks to MickyT and KirillL
Try it out
fuente
,@ int=128s:print @y&@ set @/=2IF @>0GOTO s. This is hinted by @KirillL for the R answerPython 2,
4340 bytesTry it online!
fuente
C# (Visual C# Interactive Compiler), 33 bytes
Port of @Arnauld's JavaScript (ES6) answer, so make sure to upvote him!
Try it online.
Explanation:
fuente