Dígitos en sus carriles

32

Entrada:

Una lista de enteros

Salida:

Coloque cada dígito (y el signo menos) en su propio carril, en el orden -0123456789, ignorando los dígitos duplicados.

Ejemplo:

Entrada: [1,729,4728510,-3832,748129321,89842,-938744,0,11111]

Salida:

-0123456789  <- Added as clarification only, it's not part of the output

  1         
   2    7 9
 012 45 78 
-  23    8 
  1234  789
   2 4   89
-   34  789
 0         
  1        

Reglas de desafío:

  • Cualquier dígito duplicado en el número se ignora.
  • Las E / S pueden estar en cualquier formato razonable. La entrada puede ser como una lista / matriz de cadenas o una matriz de caracteres. La salida puede ser como una lista de cadenas, caracteres, matriz de caracteres, etc.
  • Los espacios finales son opcionales.
  • Cualquier cantidad de nuevas líneas iniciales o finales son opcionales (pero no entre líneas).
  • La entrada siempre contendrá al menos un número entero
  • Sin -2,147,483,648embargo , deberá admitir un rango entero de al menos 2,147,483,647(32 bits).
  • La entrada de lista no contendrá -0, 00(o más de dos ceros), o enteros con ceros a la izquierda (es decir 012).
  • Si su idioma usa un símbolo diferente para los números negativos (como un superior ¯), también se le permite usarlo, siempre que sea coherente.
  • Se le permite tener un delimitador de espacio entre dígitos (por lo que puede ser una línea sin 5 u 8 en - 0 1 2 3 4 6 7 9lugar de -01234 67 9), siempre que sea coherente (y, por lo tanto, también debe haber un espacio entre -y 0).

Reglas generales:

  • Este es el , por lo que la respuesta más corta en bytes gana.
    No permita que los lenguajes de code-golf lo desanimen a publicar respuestas con lenguajes que no sean codegolf. Trate de encontrar una respuesta lo más breve posible para 'cualquier' lenguaje de programación.
  • Se aplican reglas estándar para su respuesta, por lo que puede usar STDIN / STDOUT, funciones / método con los parámetros adecuados y programas completos de tipo retorno. Tu llamada.
  • Las lagunas predeterminadas están prohibidas.
  • Si es posible, agregue un enlace con una prueba para su código.
  • Además, agregue una explicación si es necesario.

Casos de prueba:

Input: [1,729,4728510,-3832,748129321,89842,-938744,0,11111]
Output:
  1         
   2    7 9
 012 45 78 
-  23    8 
  1234  789
   2 4   89
-   34  789
 0         
  1        

Input: [4,534,4,4,53,26,71,835044,-3559534,-1027849356,-9,-99,-3459,-3459,-94593,-10234567859]
Output:
      4     
     345    
      4     
      4     
     3 5    
    2   6   
   1     7  
  0  345  8 
 -   345   9
 -0123456789
 -         9
 -         9
 -   345   9
 -   345   9
 -   345   9
 -0123456789

Input: [112,379,-3,409817,239087123,-96,0,895127308,-97140,923,-748]
Output:
  12       
   3    7 9
-  3       
 01 4   789
 0123   789
-      6  9
 0         
  123 5 789
-01  4  7 9
   23     9
-    4  78 

Input: [-15,-14,-13,-12,-11,10,-9,-8,-7,-5,-4,-3,-1,0,9,100,101,102,1103,104,105,106,116,-12345690]
Output:
- 1   5    
- 1  4     
- 1 3      
- 12       
- 1        
-01        
-         9
-        8 
-       7  
-     5    
-    4     
-   3      
- 1        
 0         
          9
 01        
 01        
 012       
 01 3      
 01  4     
 01   5    
 01    6   
  1    6   
-0123456  9

Input: [99,88,77,66,55,44,33,22,11,10,0,0,0,-941]
Output:
          9
         8 
        7  
       6   
      5    
     4     
    3      
   2       
  1        
 01        
 0         
 0         
 0         
- 1  4    9
Kevin Cruijssen
fuente
¿Se permitirían espacios entre los dígitos en la salida?
Shaggy
¿Podemos usar menos superior en ¯lugar de -?
Uriel
Los dígitos que faltan todavía se reemplazarían con espacios, por lo que, en su ejemplo, habría 3 espacios entre 4 y 6 y 7 y 9: "-0 1 2 3 4 <space> 6 7 <space> 9"(Los espacios se colapsan en los comentarios, por alguna razón)
Shaggy
1
¡Esperaba escabullirme de ti! : D Bien visto!
Shaggy
1
relacionado
callejero

Respuestas:

4

Stax, 8 bytes

║V≡u╝─é╢

Run and debug it

It takes one number per line on standard input. It works by finding the target index of each character and assigning it into that index of the result. If the index is out of bounds, the array is expanded with zeroes until it fits. During output, 0 becomes a space. The rest are character codes.

Unpacked, ungolfed, and commented, this is what it looks like.

m       for each line of input, execute the rest of the program and print the result
 zs     put an empty array under the line of input
 F      for each character code in the line of input, run the rest of the program
  Vd    "0123456789"
  I^    get the index of the character in this string and increment
  _&    assign this character to that index in the original string

Run this one

recursive
fuente
How is one meant to input a list of length one? (If it is just the value or the value and a new line it does not work.)
Jonathan Allan
1
Oh yes, good point. An alternate form of input that also works for single values is ["7"]. This format can also handle multiple values such as ["34", "43"].
recursive
6

05AB1E, 13 bytes

Code:

v'-žh«DyмSð:,

Uses the 05AB1E encoding. Try it online!

Explanation:

v               # For each element in the input..
 '-žh«          #   Push -0123456789
      D         #   Duplicate this string
       yм       #   String subtraction with the current element
                    e.g. "-0123456789" "456" м  →  "-0123789"
         Sð:    #   Replace all remaining elements with spaces
                    e.g. "-0123456789" "-0123789" Sð:  →  "     456   "
            ,   #   Pop and print with a newline
Adnan
fuente
1
Nice! Going the replace-route was shorter than the insert-route I see :)
Emigna
2
@Emigna The insert-route is also a very interesting approach. In fact, I think you can save 4 bytes with vðTúyvyÐd+ǝ}, ;).
Adnan
1
Brilliant! I didn't know ǝ would function like that on -0. But now that I tihnk of it, that's actually a number and not a string as I first read it as :P
Emigna
Ooooof... I was at 23bytes. The 05AB1E (pun on the humanity).
Magic Octopus Urn
4

Haskell, 51 bytes

-1 byte thanks to Laikoni.

f l=[[last$' ':[n|n`elem`i]|n<-"-0123456789"]|i<-l]

Try it online!

This challenge is digitist. D:

totallyhuman
fuente
"-0123456789" is a byte shorter than '-':['0'..'9'].
Laikoni
4

JavaScript, 59 58 bytes

Input & output as an array of strings.

a=>a.map(x=>`-0123456789`.replace(eval(`/[^${x}]/g`),` `))

Try it

o.innerText=(g=s=>(f=
a=>a.map(x=>`-0123456789`.replace(eval(`/[^${x}]/g`),` `))
)(s.split`,`).join`\n`)(i.value="1,729,4728510,-3832,748129321,89842,-938744,0,11111");oninput=_=>o.innerText=g(i.value)
input{width:100%;}
<input id=i><pre id=o></pre>


Original

Takes input as an array of strings and outputs an array of character arrays

a=>a.map(x=>[...`-0123456789`].map(y=>-~x.search(y)?y:` `))

Shaggy
fuente
1
such an elegant solution, i really like it.
Brian H.
3

05AB1E, 17 13 bytes

Saved 4 bytes thanks to Adnan

vðTúyvyÐd+ǝ},

Try it online!

Explanation

v               # loop over elements y in input
 ðTú            # push a space prepended by 10 spaces
    yv          # for each element y in the outer y
      y         # push y
       Ðd+      # push y+isdigit(y)
          ǝ     # insert y at this position in the space-string
           }    # end inner loop
            ,   # print
Emigna
fuente
3

Ruby, 42 bytes

Anonymous lambda processing the array of numbers:

->a{a.map{|n|"-0123456789".tr"^#{n}",?\s}}

Try it online!

Alternatively, a completely Perl-like full program is much shorter. I'd say -pl switches look quite funny in this context:

Ruby -pl, 29 bytes

$_="-0123456789".tr"^#$_"," "

Try it online!

Finally, the following is possible if it is acceptable for the output strings to be quoted:

Ruby -n, 27 bytes

p"-0123456789".tr ?^+$_,?\s

Try it online!

Kirill L.
fuente
3

JavaScript (Node.js), 60 bytes

  • Thank to @Andrew Taylor for reducing the join (8 chars)
  • Thank to @Yair Rand for X.match (8 chars)
a=>a.map(X=>"-0123456789".replace(/./g,x=>X.match(x)?x:" "))

Try it online!

DanielIndie
fuente
Oh, that join trick is lovely — but the question reads like an array of strings is OK output so maybe you can shave 8 bytes by removing it?
Andrew Taylor
Pretty sure you can save another by replacing (X+"").includes(x) with RegExp(x).test(X)
Andrew Taylor
(X+"").match(x) would be even shorter. The question also allows input to be an array of strings, so it could even be X.match(x) .
Yair Rand
2

Japt, 16 bytes

Input & output as an array of strings.

£Ao ¬i- ®iS gXøZ

Try it


Explanation

£                    :Map over each element X
 Ao                  :  Range [0,10)
    ¬                :  Join to a string
     i-              :  Prepend "-"
        ®            :  Map over each character Z
         iS          :    Prepend a space
            g        :    Get the character at index
             XøZ     :      X contains Z? (true=1, false=0)
Shaggy
fuente
2

Python 3, 77 64 bytes

-12 bytes thanks to @Rod

lambda x:[[[" ",z][z in str(y)]for z in"-0123456789"]for y in x]

Try it online!

My first proper attempt at golfing in Python. Advice welcome!

Returns a 2D array of characters.

Jo King
fuente
1
You can use '-0123456789' instead range(10) and drop the first block and swap str(z) with z, you can also switch to python2 and use `y` instead str(y) (`` is +- equivalent to repr)
Rod
Superfluous space in in "-.
Jonathan Frech
2

Haskell, 47 bytes

map(\s->do d<-"-0123456789";max" "[d|elem d s])

Try it online!

Uses max to insert a space where no element exist, since a space is smaller than any digit or minus sign.

If an ungodly number of trailing spaces is OK, two bytes can be saved:

45 bytes

map(\s->do d<-'-':['0'..];max" "[d|elem d s])

Try it online!

xnor
fuente
2

MATL, 13 bytes

"45KY2ht@gm*c

Input is a cell array of strings. Try it online! Or verify all test cases.

Explanation

         % Implicit input: cell array of strings, for example {'1','729',...,'11111'}
"        % For each cell
  45     %   Push 45 (ASCII code of '-')
  KY2    %   Push predefined literal '0123456789'
  h      %   Concatenate horizontally: gives '-0123456789'
  t      %   Duplicate
  @      %   Push current cell, for example {'729'}
  g      %   Convert cell to matrix. This effectively gives the cell's contents, '729'
  m      %   Ismember: gives an array of zeros and ones indicating membership of each
         %   char from '-0123456789' in '729'. The result in the example is
         %   [0 0 0 1 0 0 0 0 1 0 1]
  *      %   Multiply, element-wise. Chars are implicity converted to ASCII 
         %   Gives the array [0 0 0 50 0 0 0 0 55 0 57] 
  c      %   Convert ASCII codes to chars. 0 is displayed as space. Gives the string
         %   '   2    7 9'
         % Implicit end
         % Implicilly display each string on a different line
Luis Mendo
fuente
2

J, 32 27 bytes

-5 bytes thanks to FrownyFrog!

10|.":(10<."."0@[)}11$' '"0

Try it online!

Original solution:

J, 32 bytes

(('_0123456789'i.[)}11$' '"0)@":

Explanation:

@": convert to characters and

}11$' '"0 change the content of an array of 11 spaces to these characters

'_0123456789'i.[ at the places, indicated by the indices of the characters in this list

Try it online!

Galen Ivanov
fuente
1
10|.":(10<."."0@[)}11$' '"0
FrownyFrog
@FrownyFrog Nice solution, thanks!
Galen Ivanov
2

Google Sheets, 124 bytes

=Transpose(ArrayFormula(If(IsError(Find(Mid("-0123456789",Row($1:$11),1),Split(A1,",")))," ",Mid("-0123456789",Row($1:$11),1

Input is a comma-separated list in cell A1. Output is in the range B1:L? where ? is however many entries were input. (You can put the formula wherever you want, I just chose B1 for convenience.) Note that Sheets will automatically add four closing parentheses to the end of the formula, saving us those four bytes.

Screenshot

Another test case and another test case

Explanation:

  • Mid("-0123456789",Row($1:$11),1) picks out each of the 11 characters in turn.
  • Find(Mid(~),Split(A1,",")) looks for those characters in each of the input elements. This either returns a numeric value or, if it's not found, an error.
  • If(IsError(Find(~)," ",Mid(~)) will return a space if the character wasn't found or the character if it was. (I wish there was a way to avoid duplicating the Mid(~) portion but I don't know of one.)
  • ArrayFormula(If(~)) is what makes the multi-cell references in Mid(~) and Find(~) work. It's also what makes a formula in one cell return values in multiple cells.
  • Transpose(ArrayFormula(~)) transpose the returned array because it starts off sideways.
Engineer Toast
fuente
2

Jelly, 12 bytes

ØD”-;¹⁶e?€Ʋ€

Try it online!

-2 thanks to Jonathan Allan reading a rule I didn't.

Note that the I/O format used in the TIO link is not the actual one, which is input as a list of string representations and output as a list of lines.

Erik the Outgolfer
fuente
1

Perl 6, 35 bytes

{.map:{map {m/$^a/||' '},'-',|^10}}

Try it online!

Output is a character matrix containing either regex matches or space characters.

nwellnhof
fuente
If 'input can be in any reasonable format' could be stdin, then presumably -pe would let you dispense with the initial .map, braces and swap $^a for $_
Phil H
@PhilH -p and -n somehow seem buggy, at least on TIO. For some reason $_ isn't passed to blocks. See example 1, example 2.
nwellnhof
1

Java 8, 53 bytes

a->a.map(i->"-0123456789".replaceAll("[^"+i+"]"," "))

My own challenge is easier than I thought it would be when I made it..

Input and output both as a java.util.stream.Stream<String>.

Explanation:

Try it online.

a->                              // Method with String-Stream as both input and return-type
  a.map(i->                      //  For every String in the input:
    "-0123456789"                //   Replace it with "-0123456789",
    .replaceAll("[^"+i+"]"," ")) //   with every character not in `i` replaced with a space
Kevin Cruijssen
fuente
1

C (gcc), 159 bytes

f(A,l,j,k,b)long*A,k;{char*s,S[99];for(j=~0;++j<l;puts(""))for(sprintf(S,"%ld",k=A[j]),putchar(k<0?45:32),k=47;++k<58;putchar(b?32:k))for(b=s=S;*s;b*=*s++-k);}

Try it online!

Jonathan Frech
fuente
1

R, 96 75 bytes

for(i in scan())cat(paste(gsub(paste0("[^",i,"]")," ","-0123456789"),"\n"))

Try it online!

Thanks to Kevin Cruijssen for suggesting this regex approach!

Takes input from stdin as whitespace separated integers, and prints the ascii-art to stdout.

Giuseppe
fuente
I don't know R too well, so I'm sure it can be golfed further, but this different approach is 12 bytes shorter: function(N)for(i in N)cat(paste(gsub(paste("[^","]",sep=i)," ","-0123456789"),"\n")). (Input as string-array instead of integer-array.) Try it online.
Kevin Cruijssen
@KevinCruijssen ah, nice, yeah, I can golf that down as well.
Giuseppe
1

SOGL V0.12, 14 13 bytes

{ø,{²²⁴WI1ž}P

Try it Here!

Explanation:

{ø,{²²⁴WI1ž}P

{            repeat input times
 ø,            push an empty string and the next input above that
   {       }   for each character in the input
    ²²           push "0123456789"
      ⁴          copy the character on top
       W         and get it's index in that string (1-indexed, 0 for the non-existent "-")
        I        increment that (SOGL is 1-indexed, so this is required)
         1ž      at coordinates (index; 1) in the string pushed earlier, insert that original copy of the character
            P  print the current line
dzaima
fuente
1

SNOBOL4 (CSNOBOL4), 85 bytes

I	X =INPUT	:F(END)
	S ='-0123456789'
R	S NOTANY(X ' ') =' '	:S(R)
	OUTPUT =S	:(I)
END

Try it online!

I	X =INPUT	:F(END)		;* read input, if none, goto end
	S ='-0123456789'		;* set the string
R	S NOTANY(X ' ') =' '	:S(R)	;* replace characters of S not in X + space with space
	OUTPUT =S	:(I)		;* print S, goto I
END
Giuseppe
fuente
1

Pyth, 14 bytes

VQm*d}dNs+\-UT

Takes input as list of strings and outputs a list of strings for each line.
Try it here

Explanation

VQm*d}dNs+\-UT
VQ                For each string in the input...
  m     s+\-UT    ... and each character in "-0123456789"...
     }dN          ... check if the character is in the string...
   *d             ... and get that character or an empty string.

fuente
1

Retina, 26 bytes

%"-0123456789"~`.+
[^$&]¶ 

Try it online! Note: Trailing space. Explanation: % executes its child stage ~ once for each line of input. ~ first executes its child stage, which wraps the line in [^ and ]<CR><SP>, producing a program that replaces characters not in the line with spaces. The "-0123456789" specifies that the input to that program is the given string ($ substitutions are allowed but I don't need them).

Neil
fuente
1

Perl 5 -n, 30 bytes

Wouldn't work if - could appear anywhere else than in the first position

#!/usr/bin/perl -n
say"-0123456789"=~s/[^$_]/ /gr

Try it online!

Ton Hospel
fuente
Wouldn't work if - could appear anywhere else than in the first position if that can be true then you are not answering this challenge, since they wouldn't be integers anymore. :P
Erik the Outgolfer
1

Red, 94 bytes

func[b][foreach a b[s: copy"           "foreach c a[s/(index? find"-0123456789"c): c]print s]]

Takes input as a block of strings

Try it online!

Galen Ivanov
fuente
1

CJam, 20 bytes

qS%{'-10,+s_@-SerN}/

Try it online!

Accepts input as space separated list of integers. Pretty much the same approach as @adnans answer.

Marcos
fuente
1

C (gcc), 95 94 bytes

c,d;f(l,n)char**l;{for(;n--;l++)for(c=0;c<12;)putchar(strchr(*l,d=c++?c+46:45)?d:d^58?32:10);}

Try it online!

Input in the form of a list of strings. Output to STDOUT.

gastropner
fuente
You can golf a byte by removing the c++, and changing d=c?c+47: to d=c++?c+46:.
Kevin Cruijssen
1

K4, 30 27 bytes

Solution:

{?[a in$x;a:"-",.Q.n;" "]}'

Example:

q)k){?[a in$x;a:"-",.Q.n;" "]}'1 729 4728510 -3832 748129321 89842 -938744 0 11111
"  1        "
"   2    7 9"
" 012 45 78 "
"-  23    8 "
"  1234  789"
"   2 4   89"
"-   34  789"
" 0         "
"  1        "

Explanation:

Return "-0123..." or " " based on the input. Interpreted right-to-left. No competition for the APL answer :(

{?[a in$x;a:"-",.Q.n;" "]}' / the solution
{                        }' / lambda for each
 ?[      ;          ;   ]   / if[cond;true;false]
                .Q.n        / string "0123456789"
            "-",            / join with "-"
          a:                / save as a
       $x                   / convert input to string
   a in                     / return boolean list where each a in x
                     " "    / whitespace (return when false)
streetster
fuente
0

APL+WIN, 33 bytes

Prompts for screen input as a string

n←11⍴' '⋄n['-0123456789'⍳s]←s←⎕⋄n
Graham
fuente