Cyfry na swoich liniach


32

Wkład:

Lista liczb całkowitych

Wydajność:

Umieść każdą cyfrę (i znak minus) na swoim własnym torze, w kolejności -0123456789 , ignorując powielone cyfry.

Przykład:

Wkład: [1,729,4728510,-3832,748129321,89842,-938744,0,11111]

Wydajność:

-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        

Zasady konkursu:

  • Wszelkie zduplikowane cyfry w numerze są ignorowane.
  • I / O może mieć dowolny rozsądny format. Dane wejściowe mogą mieć postać listy / tablicy ciągów lub tablicy znaków. Dane wyjściowe mogą być listą ciągów, znaków, macierzy znaków itp.
  • Spacje końcowe są opcjonalne.
  • Dowolna liczba wiodących lub końcowych nowych wierszy jest opcjonalna (ale nie między wierszami).
  • Dane wejściowe zawsze będą zawierać co najmniej jedną liczbę całkowitą
  • Będziesz musiał obsługiwać zakres całkowitą przynajmniej -2,147,483,648choć2,147,483,647 (32-bit).
  • Wejście-lista nigdy nie będzie zawierać -0, 00(lub więcej niż dwa zera) lub całkowite z wiodącymi zerami (czyli012 ).
  • Jeśli twój język używa innego symbolu dla liczb ujemnych (jak górna ¯ ), możesz również użyć tego, o ile jest on spójny.
  • Dozwolony jest separator spacji między cyframi (więc - 0 1 2 3 4 6 7 9zamiast 5 lub 8 można wstawić wiersz -01234 67 9), o ile jest spójny (dlatego też powinna istnieć spacja między -i 0).

Główne zasady:

  • To jest , więc wygrywa najkrótsza odpowiedź w bajtach.
    Nie pozwól, aby języki gry w golfa zniechęcały Cię do publikowania odpowiedzi w językach niekodujących golfa. Spróbuj znaleźć możliwie najkrótszą odpowiedź na „dowolny” język programowania.
  • Do odpowiedzi mają zastosowanie standardowe reguły , więc możesz używać STDIN / STDOUT, funkcji / metody z odpowiednimi parametrami i zwracanymi typami, pełnych programów. Twoja decyzja.
  • Domyślne luki są zabronione.
  • Jeśli to możliwe, dodaj link z testem swojego kodu.
  • W razie potrzeby dodaj również wyjaśnienie.

Przypadki testowe:

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

Czy na wyjściu byłyby dozwolone spacje między cyframi?
Shaggy

Czy możemy użyć górnego minus ¯zamiast -?
Uriel

The missing digits would still be replaced with spaces so, in your example, there would be 3 spaces between 4 & 6 and 7 & 9: "-0 1 2 3 4 <space> 6 7 <space> 9" (Multiple spaces get collapsed in comments, for some reason)
Shaggy

1
I was hoping to sneak that one past you! :D Well-spotted!
Shaggy

Odpowiedzi:


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


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

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

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:` `))


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

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!


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!


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)

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.


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!


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

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!


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.


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.


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


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.


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

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

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.

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).


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!


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

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.


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.


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)

0

APL+WIN, 33 bytes

Prompts for screen input as a string

n←11⍴' '⋄n['-0123456789'⍳s]←s←⎕⋄n
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.