Eu fiz uma nave espacial!

39

Introdução:

Inspirado por este comentário de @MagicOctopusUrn em @Emigna resposta 05AB1E 's para o meu ' Foi apenas um erro ' desafio :

8F9ÝÀNð×ý}».∊Eu fiz uma nave espacial! E fiquei empolgado ao sugerir uma edição de 12 bytes. # 1: Magic Octopus Urn Jul 17 '17 às 20:10

Que é um programa 05AB1E (legado), resultando neste:

1234567890
1 2 3 4 5 6 7 8 9 0
1  2  3  4  5  6  7  8  9  0
1   2   3   4   5   6   7   8   9   0
1    2    3    4    5    6    7    8    9    0
1     2     3     4     5     6     7     8     9     0
1      2      3      4      5      6      7      8      9      0
1       2       3       4       5       6       7       8       9       0
1      2      3      4      5      6      7      8      9      0
1     2     3     4     5     6     7     8     9     0
1    2    3    4    5    6    7    8    9    0
1   2   3   4   5   6   7   8   9   0
1  2  3  4  5  6  7  8  9  0
1 2 3 4 5 6 7 8 9 0
1234567890

Experimente online.

Desafio:

Entrada: uma sequência não vazia

Saída: de dentro para fora, adicione mais um espaço entre cada caractere a cada linha, semelhante ao feito na saída acima, igual a length - 1. Então, para uma entrada1234567890 a saída seria realmente essa:

1234567890
1 2 3 4 5 6 7 8 9 0
1  2  3  4  5  6  7  8  9  0
1   2   3   4   5   6   7   8   9   0
1    2    3    4    5    6    7    8    9    0
1     2     3     4     5     6     7     8     9     0
1      2      3      4      5      6      7      8      9      0
1       2       3       4       5       6       7       8       9       0
1        2        3        4        5        6        7        8        9        0
1         2         3         4         5         6         7         8         9         0
1        2        3        4        5        6        7        8        9        0 
1       2       3       4       5       6       7       8       9       0
1      2      3      4      5      6      7      8      9      0
1     2     3     4     5     6     7     8     9     0
1    2    3    4    5    6    7    8    9    0
1   2   3   4   5   6   7   8   9   0
1  2  3  4  5  6  7  8  9  0
1 2 3 4 5 6 7 8 9 0
1234567890

Por quê? O comprimento do1234567890 é 10. Então começamos produzindo 10 linhas: a primeira linha sem espaços; segundo com um delimitador de espaço; terceiro com dois; etc. E então (sem ter a linha do meio com length - 1espaços duplicados), voltamos à entrada inicial enquanto diminuímos.

Regras do desafio:

  • A entrada é garantida como não vazia (um comprimento >= 1 ). (Para entradas de caracteres simples, simplesmente produzimos esse caractere.)
  • Qualquer quantidade de espaços à direita / à esquerda / novas linhas é permitida, desde que a saída em si (onde quer que esteja na tela) esteja correta. (Linhas vazias entre as linhas de saída também não são permitidas.)
  • A entrada conterá apenas caracteres ASCII imprimíveis, excluindo espaços em branco (intervalo de ponto de código [33, 126] )
  • A E / S é flexível. A entrada pode ser tomada como STDIN, argumento ou parâmetro de função. Pode ser uma lista / matriz / fluxo de caracteres em vez de sequência. A saída também pode ser uma lista / matriz / fluxo de caracteres em vez de cadeias; pode ser impresso em STDOUT; retornado como string delimitada por nova linha; etc.

Regras gerais:

  • Isso é , então a resposta mais curta em bytes vence.
    Não permita que idiomas com código de golfe o desencorajem a postar respostas com idiomas que não sejam codegolf. Tente encontrar uma resposta o mais curta possível para 'qualquer' linguagem de programação.
  • Aplicam-se regras padrão à sua resposta, para que você possa usar STDIN / STDOUT, funções / método com os parâmetros adequados e programas completos do tipo retorno. Sua chamada.
  • Lacunas padrão são proibidas.
  • Se possível, adicione um link com um teste para o seu código.
  • Além disso, é altamente recomendável adicionar uma explicação para sua resposta.

Casos de teste:

Input: @
Output:
@

Input: test
Output:
test
t e s t
t  e  s  t
t   e   s   t
t  e  s  t
t e s t
test

Input: ?!
Output:
?!
? !
?!

Input: Spaceship
Output:
Spaceship
S p a c e s h i p
S  p  a  c  e  s  h  i  p
S   p   a   c   e   s   h   i   p
S    p    a    c    e    s    h    i    p
S     p     a     c     e     s     h     i     p
S      p      a      c      e      s      h      i      p
S       p       a       c       e       s       h       i       p
S        p        a        c        e        s        h        i        p
S       p       a       c       e       s       h       i       p
S      p      a      c      e      s      h      i      p
S     p     a     c     e     s     h     i     p
S    p    a    c    e    s    h    i    p
S   p   a   c   e   s   h   i   p
S  p  a  c  e  s  h  i  p
S p a c e s h i p
Spaceship

Input: 05AB1E
Output:
05AB1E
0 5 A B 1 E
0  5  A  B  1  E
0   5   A   B   1   E
0    5    A    B    1    E
0     5     A     B     1     E
0    5    A    B    1    E
0   5   A   B   1   E
0  5  A  B  1  E
0 5 A B 1 E
05AB1E

Input: )}/\
Output:
)}/\
) } / \
)  }  /  \
)   }   /   \
)  }  /  \
) } / \
)}/\
Kevin Cruijssen
fonte
1
Fica toda nervosa !!! NAVE ESPACIAL !!!
WallyWest 5/09
1
Eu sabia que reconhecia essa saída. Eu amo que essa idéia ainda esteja acontecendo.
Carcigenicate
2
TFW, você reconhece vagamente um padrão em uma pergunta ಠ_ಠe percebe que é porque você o acidentalmente o fez há um ano ಠ⌣ಠ.
Magic Octopus Urn
1
@MagicOctopusUrn Obrigado pela inspiração. ; D
Kevin Cruijssen
3
@KevinCruijssen obrigado por manter a citação pateta haha!
Magic Octopus Urn

Respostas:

11

Japonês , 8 6 bytes

Recebe a entrada como uma matriz de caracteres, gera uma matriz de seqüências de caracteres.

£qYçÃê

Tente


Explicação

£          :Map each element at (0-based) index Y
 q         :  Join input with
  Yç       :   Space repeated Y times
    Ã      :End Map
     ê     :Palindromise

Original, 8 bytes

E / S é uma sequência. Usa a -Rbandeira. Inclui espaços à direita em cada linha.

¬£múYÄÃê

Tente

Explicação

             :Implicit input of string U
¬            :Split
 £           :Map each character at 0-based index Y
  m          :  Map original U
   ú         :    Right pad with spaces to length ...
    YÄ       :     Y+1
      Ã      :End map
       ê     :Palindromise
             :Implicitly join with newlines
Shaggy
fonte
S.ç()FTW mais uma vez :-)
ETHproductions
1
Pergunta séria: seria possível pesquisar iterativamente em todas as soluções de 1 a 6 bytes de comprimento para um quebra-cabeça como esse?
filip
2
@ Filip No: existem mais de 256 ** 6 = 281474976710656 (pelo menos ingênuas) combinações. É como adivinhar uma senha.
Kirill Bulygin
3
@KirillBulygin, existem mais de 37 trilhões (37.764.717.485.592) de maneiras possíveis de combinar os caracteres disponíveis no Japt em uma cadeia de caracteres entre 1 e 6 caracteres. Se você incluir todos os outros caracteres de 1 byte que podem ser usados ​​em literais de seqüência de caracteres ou seqüências de caracteres compactadas, esse número aumentará para mais de 276 trilhões (276.024.445.697.280). Portanto, não, escrever um bot para gerar todos, filtrar os programas Japt válidos e encontrar o (se houver algum) que funcione para o desafio em questão provavelmente não seria viável. Além do mais, onde está a diversão em deixar um bot jogar golfe por você ?!
Shaggy
6
@ Shaggy: "onde está a diversão em deixar um bot jogar golfe por você ?!" E se você tornasse o bot muito, muito curto?
Oddthinking
11

R , 105 99 85 84 79 bytes

-6 graças a @Kevin Cruissen e @Giuseppe

-14 de mudar para um método baseado em regex

-1 graças a @Giuseppe

-5 graças a @digEmALl

function(w,n=nchar(w)-1)write(trimws(Map(gsub,"",strrep(" ",n-abs(n:-n)),w)),1)

Experimente online!

J.Doe
fonte
Você pode jogar golfe com 1 byte removendo o espaço em in(r<-.
Kevin Cruijssen
1
e você só usa suma vez para poder usá-lo como argumento writediretamente; trazendo-lhe até 99 bytes
Giuseppe
1
que deveria ser um 1em vez de um ""em write? Estou gostando do seu uso Map!
Giuseppe
1
Impressionante ! 79 bytes usando matemática :)
digEmAll
1
Eu estava convencido de que eu poderia vencer isso com o collapseargumento paste, mas ele simplesmente não está acontecendo ...
JDL
6

Carvão , 10 bytes

Eθ⪫θ× κ‖O↓

Experimente online! Link é a versão detalhada do código. Explicação:

Eθ          Map over characters of input string
  ⪫θ        Join characters of input string using
    ×       a literal space repeated 
      κ     current index number of times
            Implicitly print each result on its own line
       ‖O↓  Reflect vertically with overlap
Neil
fonte
O carvão não refletir a coisas como [a ]- ou é que outro comando separado?
Magic Octopus Urn
@MagicOctopusUrn Existem comandos separados se você quiser transformar a reflexão. Veja codegolf.stackexchange.com/a/127164 para exemplo.
Neil
Eu pensei que já tinha visto isso refletir antes, mas não tinha certeza. Arrumado!
Magic Octopus Urn
6

Python 2 , 72 70 68 66 65 bytes

-2 bytes graças a Kevin Cruijssen
-3 bytes graças a ovs

w=input();c=s=-1
while c:print(' '*~c).join(w);s*=w[:c]>'';c+=s|1

Experimente online!

Cajado
fonte
c==len(w)-1pode ser jogado por 1 byte com c+2>len(w). EDIT: Na sua nova versão de 70 bytes, 0<cpode ser c.
Kevin Cruijssen
6

05AB1E , 10 9 bytes

Guardado 1 bytes graças a Adnan

εINð×ý}û»

Experimente online!

Explicação

ε            # apply to each in input
 I           # push the input
  Nð×        # push <index> spaces
     ý       # merge the input on the spaces
      }      # end loop
       û     # palendromize
        »    # join on newlines
Emigna
fonte
Você pode largar o S. A entrada é flexível, portanto, a entrada como lista é permitida.
Kevin Cruijssen
1
@KevinCruijssen: Sua primeira versão possui 9 bytes de legado, pois »pode ser omitida.
Emigna 04/09/19
1
Na verdade, o seu também funciona no legado em 9 bytes, se você remover »e alterar o loop vpara um mapa ε.
Kevin Cruijssen
1
Postou a resposta . E atualmente o Japt está nos batendo com 6 bytes, receio. Ou você quis dizer o menor em 05AB1E (reescrita do Elixir) e 05AB1E (legado do Python)? :)
Kevin Cruijssen
2
Será que εINð×ý}û»também funcionam?
Adnan
5

Ruby , 54 49 bytes

->a{(-(z=a.size-1)..z).map{|i|a*(?\s*(z-i.abs))}}

Experimente online!

Recebe entrada como uma matriz de caracteres, gera uma matriz de seqüências de caracteres.

Kirill L.
fonte
4

Japt, 9 8 bytes

-1 byte from @Shaggy

ÊƬqXîÃê

ÊƬqXîÃê        Full program, implicity input U
ÊÆ              Rage from 0 to U length and map
  ¬             split U at ""
   qXîà     join U using " " times range current value
        ê       horizontal mirror

Try it online!

Luis felipe De jesus Munoz
fonte
Dang; looks like you ninjaed me again! Lemme know if you'd like me to delete mine.
Shaggy
1
@Shaggy no, keep your answer, you are using array as input while I use a string so they are kind of different xD
Luis felipe De jesus Munoz
1
SpX -> for a 1 byte saving.
Shaggy
4

PowerShell, 66 54 bytes

-12 bytes thanks to mazzy

0..($x=($a=$args).count-1)+$x..0|gu|%{$a-join(' '*$_)}

Try it online!

Takes input via splatting, which on TIO manifests as separate command-line arguments for each character.

We first set $a=$args as the input argument. Then we set $x equal to the .count of that array -1. We then need to loop through the letters to construct the spaceship. That's done by constructing a range from 0 to $x, then $x back down to 0, then using Get-Unique to pull out just the appropriate range.

Each iteration, we take our input arguments and -join them together with the corresponding number of spaces. Each of those strings is left on the pipeline, and an implicit Write-Output gives us newlines for free when the program completes.

AdmBorkBork
fonte
Try this: 0..($x=($a=$args).count-1)+$x..0|gu|%{$a-join(' '*$_)}
mazzy
1
@mazzy What the ... how does Get-Unique work like that on the range? That's crazy! Thanks!
AdmBorkBork
4

05AB1E (legacy), 9 bytes

εINúíJ}û»

Input as list of characters.

Try it online or verify all test cases.

Explanation:

ε     }    # Map each character in the input to:
 I         #  Take the input
  Nú       #  Prepend each with the 0-indexed amount of spaces
           #   i.e. ["t","e","s","t"] & 3 → ["   t","   e","   s","   t"]
    í      #  Reverse each item
           #   i.e. ["   t","   e","   s","   t"] → ["t   ","e   ","s   ","t   "]
     J     #  Join them together to a single string
           #   i.e. ["t   ","e   ","s   ","t   "] → "t   e   s   t   "
       û»  # Palindromize the list, and join by newlines
           #  i.e. ["test","t e s t ","t  e  s  t  ","t   e   s   t   "]
           #   → "test\nt e s t \nt  e  s  t  \nt   e   s   t   \nt  e  s  t  \nt e s t \ntest"
Kevin Cruijssen
fonte
1
Oooooo, also this isn't valid because mirror changes the orientation of / to \ when mirrored, same with [, ] and (, ). May want to add those cases to catch charcoal too. (Moved the other comments to Emigna's answer, because he was the answer I originally commented on)
Magic Octopus Urn
@MagicOctopusUrn Thanks for letting me know. Fixed it by using û» instead of .∊.
Kevin Cruijssen
4

Haskell, 60 59 bytes

(init<>reverse).(scanl(?)<*>tail)
a?_=do u<-a;u:[' '|' '<u]

Try it online!

Explanation

For a string (eg. "abc") we apply first

scanl (?) <*> tail

which is the same as

\str -> scanl (?) str (tail str)

This repeatedly applies (?) (appends a space to each character in the range [33..]) to the str until there are that many strings as str has characters: ["abc","a b c ", "a b c "]

Now we only need to concatenate the result (minus the last element) with its reversed counter part:

init<>reverse
ბიმო
fonte
4

MATL, 25 22 13 bytes

zZv"Gtz@he!1e

Try it online!

Thanks to Luis Mendo for suggesting a 5 byte golf, which then inspired me to shave off 4 more bytes!

Explanation, with example input 'abc':

         # Implicit input, 'abc'
z        # find number of nonzero elements (length of string)
         # stack: [3]
Zv       # symmetric range
         # stack: [[1 2 3 2 1]]
"        # begin for loop, iterating over [1 2 3 2 1] as the loop indices
G        # push input
         # stack: ['abc']
tz       # dup and push length
         # stack: ['abc', 3]
@        # push loop index, i (for example, 2)
         # stack: ['abc', 3, 2]
h        # horizontally concatenate
         # stack: ['abc', [3, 2]]
e!       # reshape to matrix of 3 rows and i columns, padding with spaces, and transpose
         # stack: [['abc';'   ';'   ']]
1e       # reshape to matrix of 1 row, leaving last value on stack
         # stack: ['a  b  c  ']
         # implicit end of for loop
         # implicit end of program, display stack contents
Giuseppe
fonte
3

Jelly, 9 bytes

jⱮLḶ⁶ẋƲŒḄ

Try it online!

Returns a list of lines; output prettified over TIO.

Erik the Outgolfer
fonte
A somewhat different 9: ,€⁶$LСŒḄ. Other, more similar, 9's: J’⁶ẋŒḄɓjⱮ and J’⁶ẋŒḄjⱮ@ (I was looking for shorter but no joy yet)
Jonathan Allan
@JonathanAllan I'm pretty sure this is optimal, I don't think there's any shorter way to write LḶ⁶ẋ or ŒḄ. However, if you manage to find a save, do ping me. :-)
Erik the Outgolfer
Thinking about it a bit my ,€⁶$LСŒḄ may not be valid since it has crazy nesting so might need a Y and be a full program.
Jonathan Allan
@JonathanAllan Yeah, of course it's not. ['I', 'f', [[' '], 't', 'h', [['i']], 's'], ' ', 'i', ['s', ' '], 'a', [[' ', 's', 't'], 'r', ['i', 'n', 'g'], ' '], 'w', ['e', ' ', 'a', 'r', 'e'], ' ', 'd', 'o', ['o'], 'm', [[[[['e']]]]], [[[['d']]]], '!'] At least I've outgolfed 05AB1E...
Erik the Outgolfer
I said I outgolfed 05AB1E, eh? Bah, not anymore. :/
Erik the Outgolfer
3

Pyth, 12 bytes

Just my mandatory Pyth submission. I am quite proud of this so an explanation will likely come soon.

+P_=jRQ*L;_U

Try it here!

+P_=jRQ_.e*d

Try it here!

Mr. Xcoder
fonte
3

Stax, 10 bytes

Ç·9ƒù▌╘Ä┘e

Run and debug it

Outputs with trailing whitespace on each line.

Explanation:

%R|pmx{]n(m Full program, unpacked, implicit input
%           Length of input
 R          1-based range
  |p        Palindromize
    m       Map:
     x{   m   Map over characters of input:
       ]        Character -> string
        n(      Right-pad to length given by outer map value
              Implicit flatten and output
wastl
fonte
3

Java (JDK 10), 115 bytes

s->{for(int l=s.length(),i=-l;++i<l;)System.out.printf(s.replaceAll(".","%-"+(i<0?l+i:l-i)+"s")+"%n",s.split(""));}

Try it online!

Olivier Grégoire
fonte
1
l-Math.abs(i) can be golfed to i<0?l+i:l-i for -2 bytes.
Kevin Cruijssen
@KevinCruijssen Thanks! :)
Olivier Grégoire
could it be l-i<0?-i:i?
Quintec
@thecoder16 You would need parentheses: l-(i<0?-i:i) (12 bytes).
Jonathan Frech
3

K (oK), 25 24 bytes

Solution:

,/'(1+a,1_|a:!#x)$\:+,x:

Try it online!

Explanation:

Port of my K4 solution:

,/'(1+a,1_|a:!#x)$\:+,x: / the solution
                      x: / save input as x
                     ,   / enlist
                    +    / flip
                 $\:     / pad ($) right by each-left (\:)
   (            )        / do this together
              #x         / count length of input,           e.g. 3
             !           / range 0..length,                 e.g. 0 1 2
           a:            / save as a
          |              / reverse it,                      e.g. 2 1 0
        1_               / drop first,                      e.g. 1 0
      a,                 / join to a,                       e.g. 0 1 2 1 0
    1+                   / add 1,                           e.g. 1 2 3 2 1
,/'                      / flatten (,/) each (')

Notes:

  • -1 byte thanks to ngn
streetster
fonte
1
,:' -> +,­­
ngn
2

Pascal (FPC), 143 135 bytes

var s:string;i,j,l:word;begin read(s);l:=length(s);repeat i:=i+1;for j:=1to l do write(s[j],'':l-abs(l-i)-1);writeln until i=l*2-1 end.

Try it online!

I will probably win only against Lenguage...

AlexRacer
fonte
2

PHP, 88 89 bytes

for(;++$i<2*$e=count($a=str_split($argn));)echo join(str_pad("",~-$e-abs($i-$e)),$a),"\n";

requires PHP 5 or later for str_split. Run as pipe with -nR or try it online.

Titus
fonte
Your try-it-online link gives the wrong output I'm afraid. In your output all lines also have leading spaces, instead of only between characters (or optionally trailing). The first character should all be in the same column in the output.
Kevin Cruijssen
1
@KevinCruijssen Didn´t look at the output close enough. Fixed. (Though imo my previous output looked more like a rocket) ;-)
Titus
It kinda looked like the head of an arrow to me. :D But +1 now that it's fixed.
Kevin Cruijssen
If you place an actual newline instead of the \n, you save a byte :)
Martijn
@Martijn I actually did only count one byte for it ... forgot to replace it when I pasted the code here.
Titus
2

K4, 23 bytes

Solution:

,/'(1+a,1_|a:!#x)$\:$x:

Example:

q)k),/'(1+a,1_|a:!#x)$\:$x:"Spaceship"
"Spaceship"
"S p a c e s h i p "
"S  p  a  c  e  s  h  i  p  "
"S   p   a   c   e   s   h   i   p   "
"S    p    a    c    e    s    h    i    p    "
"S     p     a     c     e     s     h     i     p     "
"S      p      a      c      e      s      h      i      p      "
"S       p       a       c       e       s       h       i       p       "
"S        p        a        c        e        s        h        i        p        "
"S       p       a       c       e       s       h       i       p       "
"S      p      a      c      e      s      h      i      p      "
"S     p     a     c     e     s     h     i     p     "
"S    p    a    c    e    s    h    i    p    "
"S   p   a   c   e   s   h   i   p   "
"S  p  a  c  e  s  h  i  p  "
"S p a c e s h i p "
"Spaceship"

Explanation:

Has trailing whitespace on each line.

,/'(1+a,1_|a:!#x)$\:$x: / the solution
                     x: / save input as x,                 e.g. "abc"
                    $   / string,                          e.g. (,"a";,"b";,"c")
                 $\:    / pad ($) right by each-left (\:)
   (            )       / do this together
              #x        / count length of input,           e.g. 3
             !          / range 0..length,                 e.g. 0 1 2
           a:           / save as a
          |             / reverse it,                      e.g. 2 1 0
        1_              / drop first,                      e.g. 1 0
      a,                / join to a,                       e.g. 0 1 2 1 0
    1+                  / add 1,                           e.g. 1 2 3 2 1
,/'                     / flatten each
streetster
fonte
2

C#, 113 105 98 bytes

s=>{for(int l=s.Length,i=-l;++i<l;)WriteLine(Join("",s.Select(c=>$"{c}".PadRight(i<0?l+i:l-i))));}

Try it online!

RobIII
fonte
Hi there. Currently your answer is a snippet instead of a function or full program. This can cheaply be fixed by adding s=>{ before and } after to make it a lambda-function. In addition, one thing to golf is removing the brackets around the for-loop. Try it online.
Kevin Cruijssen
@KevinCruijssen Thanks! Forgot to fix that before posting...
RobIII
2

Scala, 82 bytes

for(i<-(0 to a.size)union(-a.size to 0))println(a.map(_+" "*Math.abs(i)).mkString)

Try it online

Scala has lot of shortcuts that are helping me here and that is quite readable! Try Scala

Andrew Kuleshov
fonte
Hi there, welcome to PPCG! Although it's a nice answer, I'm afraid two things are slightly incorrect. The line with the most spaces should only be output once in the middle instead of twice. And currently you print from 0 to length amount of spaces, instead of 0 to length-1 amount of spaces. I don't know Scala too well, but it seem you can fix both issues with +4 bytes (86 bytes in total) like this: for(i<-(0 to a.size-1)union(-a.size+2 to 0))println(a.map(_+" "*Math.abs(i)).mkString) Again welcome, and enjoy your stay! :)
Kevin Cruijssen
2

Oracle SQL, 115 bytes

Not a golfing language but...

SELECT TRIM(REGEXP_REPLACE(v,'(.)',LPAD('\1',1+LENGTH(v)-ABS(LEVEL-LENGTH(v)))))FROM t CONNECT BY LEVEL<2*LENGTH(v)

Assuming that the value is in column v of table t:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE t ( v ) AS
  SELECT 'test' FROM DUAL;

Query 1:

SELECT TRIM(REGEXP_REPLACE(v,'(.)',LPAD('\1',1+LENGTH(v)-ABS(LEVEL-LENGTH(v)))))
FROM   t
CONNECT BY LEVEL<2*LENGTH(v)

Results:

(SQLFiddle prints the values right-aligned in the column for some reason... there are no leading spaces)

| TRIM(REGEXP_REPLACE(V,'(.)',LPAD('\1',1+LENGTH(V)-ABS(LEVEL-LENGTH(V))))) |
|---------------------------------------------------------------------------|
|                                                                      test |
|                                                                   t e s t |
|                                                                t  e  s  t |
|                                                             t   e   s   t |
|                                                                t  e  s  t |
|                                                                   t e s t |
|                                                                      test |
MT0
fonte
Your SQL Fiddle results seems to only have single spaces in between characters? See this screenshot. I assume this is due to SQL Fiddle and it works locally? Btw, not sure if SQL uses standard regex rules, but can (.) be golfed to . by using \0 instead of \1 like you could in Java for example? EDIT: Never mind, that is for $0, not \0.. (Java example of what I meant).
Kevin Cruijssen
1
@KevinCruijssen Click on the down arrow next the the "Run SQL" button and change the output to "Plaintext Output" or "Markdown Output" and you will see the spaces.
MT0
Thanks. It indeed looks good in that case!
Kevin Cruijssen
2

8086 machine code, 56 53 bytes

00000000  bf 35 01 57 ba 01 00 52  be 82 00 b3 ff ac 59 51  |.5.W...R......YQ|
00000010  aa 3c 0d 74 07 b0 20 e2  f7 43 eb f1 b0 0a aa 59  |.<.t.. ..C.....Y|
00000020  00 d1 e3 08 38 cb d6 08  c2 51 eb dc c6 05 24 5a  |....8....Q....$Z|
00000030  b4 09 cd 21 c3                                    |...!.|
00000035

Assembled from:

org 0x100
use16
        mov di, buffer
        push di
        mov dx, 1
        push dx
nextl:  mov si, 0x82
        mov bl, -1
nextc:  lodsb
        pop cx
        push cx
stor:   stosb
        cmp al, 0x0d
        je cr
        mov al, ' '
        loop stor
        inc bx
        jmp nextc
cr:     mov al, 0x0a
        stosb
        pop cx
        add cl, dl
        jcxz done
        cmp bl, cl
        salc
        or dl, al
        push cx
        jmp nextl
done:   mov [di], byte '$'
        pop dx
        mov ah, 0x09
        int 0x21
        ret
buffer:

Test case:

screenshot

user5434231
fonte
Hi there. I guess there isn't any online compiled for 8086 machine code, but could you perhaps add a screenshot of the output for one of the test cases? Then I can check if everything is correct. :)
Kevin Cruijssen
Done. Also shaved off one more byte :)
user5434231
Thanks for the screenshot! Unfortunately there is one small mistake in the output. The middle line now has length amount of spaces and there are 9 lines in total, but the middle line should have length-1 amount of spaces and there should be a total of 7 lines instead (for the 4-letter word 'test'`).. :( I hope it's not to expensive in terms of bytes to fix?
Kevin Cruijssen
1
Ohh I see. That's fixed now, I even reduced it by one more byte.
user5434231
2

Haskell, 64 60 59 bytes

(""#)
a#s|l<-(:a)=<<s,w<-' ':a=l:[x|w<(' '<$s),x<-w#s++[l]]

Try it online!

a#s                         -- take a string of spaces 'a' and the input string 's'
 |l<-(:a)=<<s               -- let 'l' be the current line, i.e. the spaces in 'a'
                            -- appended to each char in 's'
  w<-' ':a                  -- let 'w' be 'a' with an additional space   
 =l                         -- return that 'l'
   :[   |w<(' '<$s)   ]     -- and, if 'w' is shorter than 's',
     x  ,x<-w#s++[l]        -- followed by a recursive call with 'w' 
                            -- and by another copy of 'l'

(""#)                       -- start with an empty 'a'
nimi
fonte
2

Bash, 115, 109, 105, 100, 97, 96, 92, 91, 90 bytes

-5 & -3 thanks to Kevin Cruissen

read s;for((c=f=1;f;c-=2*(f>=${#s}),f+=c))
{ printf '%-'${f}'.c' `grep -o .<<<"$s"`
echo
}

Try it online!


Note that since the \ is a shell escape char, the test case )}/\ should be entered with an extra \ like this: )}/\\.

agc
fonte
Hi there. Is it possible to add a TIO-link with test case(s)? Also, I don't know Bash very well, but is it possible to remove the spaces after in and printf like in Python?
Kevin Cruijssen
1
@KevinCruijssen, Thanks, see revised answer. I'm new to TIO-link however, and am not sure how to use multiple test cases, since this bash code only inputs a string, (i.e. just one line). The test cases all work however, though )}/\ must be single quoted like this <<< ')}/\' read s; ...etc. . The spaces after in and printf are needed.
agc
Thanks. And a single test case for TIO is fine. It's mainly to verify if everything is working as expected, which indeed seems the case. +1 from me. :)
Kevin Cruijssen
1
In your new version you can golf 5 more bytes like this. Spaces after for and do can be removed. f=1 can be changed to c=f=1. And f=f+c can be f+=c.
Kevin Cruijssen
1
Oh, one more small thing to golf. Wasn't sure if it's possible in Bash, but apparently it is (one more reason why a TIO-link is handy ;) ), is by changing f!=0 to f in the for-loop. Just like in JavaScript and Python, 0 is falsey and every other positive/negative integer is apparently truthy in Bash.
Kevin Cruijssen
2

Perl 6, 43 bytes

{(0....comb-1...0)>>.&{join ' 'x$^a,.comb}}

Try it online!

Returns a list of lines.

Explanation:

 {                                         }  # Anonymous code block
  (0....comb-1...0) # A list from
   0                  # 0
    ...               # to
       .comb-1        # the length of the input string -1
              ...     # back to
                 0    # 0
                   >>.&{                  }  # Map each number to
                        join        ,.comb   # Join the list of characters
                             ' 'x$^a         # With the number of spaces
Jo King
fonte
2

C (gcc), 131 129 111 bytes

i;x;f(k,j)char*k,*j;{x=strlen(k)-1;for(i=0;i<x-~x;i+=puts(""))for(j=k;*j;)printf("%c%*s",*j++,i<x?i:2*x-i,"");}

Try it online!

-20 bytes thanks to ceilingcat!

#import<string.h>
i;x;f(k,j)char*k,*j;{x=strlen(k)-1;for(i=0;i<x-~x;i+=puts(""))for(j=k;*j;)printf("%c%*s",*j++,i<x?i:2*x-i,"");}

Try it online!

Or, if length can be accepted as a parameter:

C (gcc), 105 102 bytes

-1 byte thanks to ceilingcat!

i;x;f(k,x,j)char*k,*j;{for(i=!x--;i<x-~x;i+=puts(""))for(j=k;*j;)printf("%c%*s",*j++,i<x?i:2*x-i,"");}

Try it online!

Conor O'Brien
fonte
@ceilingcat huh!
Conor O'Brien
1
In your 102 bytes long golf, I think the global x is shadowed and thus redundantly declared.
Jonathan Frech
2

PHP, 148 146 143 141 Bytes

function s($s){for(;$i<strlen($s);++$i)f($i,$s);for(--$i;--$i>=0;)f($i,$s);}function f($i,$s){echo chunk_split($s,1,str_repeat(' ',$i))."
";}

You can test it like this:

<?php
error_reporting(0);

$s = 1234567890;
function s($s){for(;$i<strlen($s);++$i)f($i,$s);for(--$i;--$i>=0;)f($i,$s);}function f($i,$s){echo chunk_split($s,1,str_repeat(' ',$i))."
";}

Output

1234567890
1 2 3 4 5 6 7 8 9 0 
1  2  3  4  5  6  7  8  9  0  
1   2   3   4   5   6   7   8   9   0   
1    2    3    4    5    6    7    8    9    0    
1     2     3     4     5     6     7     8     9     0     
1      2      3      4      5      6      7      8      9      0      
1       2       3       4       5       6       7       8       9       0       
1        2        3        4        5        6        7        8        9        0        
1         2         3         4         5         6         7         8         9         0         
1        2        3        4        5        6        7        8        9        0        
1       2       3       4       5       6       7       8       9       0       
1      2      3      4      5      6      7      8      9      0      
1     2     3     4     5     6     7     8     9     0     
1    2    3    4    5    6    7    8    9    0    
1   2   3   4   5   6   7   8   9   0   
1  2  3  4  5  6  7  8  9  0  
1 2 3 4 5 6 7 8 9 0 
1234567890

Sandbox

Expanded version

 function s($s){
    //loop upwards 0-10
    for(;$i<strlen($s);++$i) f($i,$s);
     //decrement so it's odd, from 9 loop downwards to 0
    for(--$i;--$i>=0;)f($i,$s);
 }
 //2nd function to save space
 function f($i,$s){
     //chunk it, split 1 char, insert $i number of spaces
     echo chunk_split($s,1,str_repeat(' ',$i))."
";}

Attempt 2, 92 bytes

after seeing @Titus answer I reduced mine to this:

for(;++$i<2*$e=strlen($s=$argn);)echo chunk_split($s,1,str_repeat(' ',~-$e-abs($i-$e)))."
";

I was trying to think of a way to use 1 loop, instead of 2... Believe it or not, I almost never use the for loop in "real" code. It was the ~ bitwise Not, that I was missing...

It's sill a tiny bit longer at 92 so I don't feel so bad. But I will put it in as a second attempt anyway.

$argn is the input from the command line

Run as pipe with -nR or try it online.

Sandbox

ArtisticPhoenix
fonte
It seems to me that your first version would be 4 bytes shorter if you used a named function f instead of assigning an anonymous one to $f - function f( saves 2 bytes over $f=function(, and you save another byte every time you call f(...) instead of $f(...). Alternatively, you could capture the $s, saving 2 bytes - ($i)use($s) is 4 bytes longer than ($i,$s), but you save 3 bytes for each call to $f($i) instead of $f($s,$i); in languages with automatic capture, like JS, this is more often a viable saving, because you don't pay the penalty of the use statement.
IMSoP
I do appreciate the help, I'm pretty new to code golf and don't really do it that much, one does get bored on the regular SO pages, though. I did think about using use but it feels longer, to do that sense $i is dynamic, it would have to be passed in by reference. So it has to be use(&$i) and the $i has to be defined before passing it by reference to $f. Which means setting it in the parent function, or before any other. For the function it could be function s($s,$i) and just know it has to be called with s($s,0) but it seems ugly, and that is around 11 bytes, use(&$i),$i
ArtisticPhoenix
We could use $s though and change the \n to a real line return. That gets it to 143 2 from the line ending and 1 from use
ArtisticPhoenix
Yes, I hadn't even considered putting $i into the use, because $s felt the "natural" capture, but it's always worth calculating the net saving. However, you can still save 2 bytes by just declaring a named function f instead of a closure: function s($s){for(;$i<strlen($s);++$i)f($i,$s);for(--$i;--$i>=0;)f($i,$s);}function f($i,$s){echo chunk_split($s,1,str_repeat(' ',$i))." ";} Extra functions like this are allowed according to this meta post: codegolf.meta.stackexchange.com/questions/7614/…
IMSoP
Updated, saved a couple
ArtisticPhoenix