Menerapkan pegolf spasi putih


15

Beberapa esolang dua dimensi, seperti Forked , dan beberapa non-esolangs, seperti Python , terkadang dapat membutuhkan spasi sebelum baris kode. Ini tidak terlalu golf. Juga, saya malas dan menulis lang 2d yang membutuhkan banyak ruang sebelum kode. Tugas Anda adalah menulis alat yang membuat bahasa ini menjadi lebih golf.

Tentu saja, ini tidak akan sempurna; itu tidak dapat digunakan, misalnya, ketika angka adalah karakter pertama pada satu baris sumber. Namun, ini umumnya akan bermanfaat.

Tantangan

Anda akan menulis sebuah program atau fungsi yang ...

  • ... mengambil satu argumen, nama file atau string, atau ...
  • ... membaca dari input standar.

Program Anda akan bertindak seperti cat, kecuali:

  • Jika karakter pertama pada baris apa pun adalah angka, kode Anda akan mencetak x spasi, di mana x adalah angka itu.
  • Kalau tidak, itu hanya akan dicetak.
  • Seperti halnya setiap karakter lain dalam input.

Uji kasus

Memasukkan:

foo bar foo bar
1foo bar foo bar foo bar
2foo bar foo bar foo bar foo bar

Keluaran:

foo bar foo bar
 foo bar foo bar foo bar
  foo bar foo bar foo bar foo bar

Memasukkan:

--------v
8|
8|
80
8,
7&

Keluaran:

--------v
        |
        |
        0
        ,
       &

Memasukkan:

foo bar
bar foo
foo bar

Keluaran:

foo bar
bar foo
foo bar

Memasukkan:

0123456789
1234567890
2345678901
3456789012
4567890123

Keluaran:

123456789
 234567890
  345678901
   456789012
    567890123

Aturan

  • Output harus persis seperti input, kecuali untuk baris di mana karakter pertama adalah angka.
  • Program Anda tidak dapat menambahkan / menambahkan apa pun ke file, kecuali satu baris baru jika Anda inginkan.
  • Program Anda mungkin tidak membuat asumsi tentang input. Ini mungkin berisi baris kosong, tidak ada angka, karakter Unicode, apa pun.
  • Jika angka dengan lebih dari satu digit memulai garis (mis. 523abcdefg), Hanya digit pertama (dalam contoh, 5) yang akan berubah menjadi spasi.

Pemenang

Kode terpendek di setiap bahasa menang. Selamat bersenang-senang dan semoga berhasil!



6
Of course, this will not be perfect; it cannot be used, for instance, when a number is the first character on a line of source.Tidak benar, buat saja karakter pertama 0 (ahem, test case terakhir Anda)
HyperNeutrino

Bisakah kita membaca daftar string dari stdin ( apakah ini valid )?
Riley

Jawaban:



10

Secara kubik , 69 byte

R1B1R3B1~(+50<7?6{+54>7?6{-002+7~?6{(@5*1-1/1)6}}}(-6>7?6&@7+70-4~)6)

Cobalah online!

Penjelasan:

Pertama kita lakukan inisialisasi ini:

R1B1R3B1

Untuk mengatur kubus ini:

   533
   004
   000
411223455441
311222331440
311222331440
   555
   555
   200

Yang paling penting tentang kubus ini adalah bahwa 5jumlah wajah menjadi 32, yang merupakan nilai yang diperlukan untuk mencetak spasi. Secara kebetulan, itu juga cukup pendek untuk semua perhitungan lainnya. Setelah itu selesai:

~( . . . )                                    Takes the first input, then loops indefinitely

  +50<7?6{+54>7?6{-002+7~?6{(@5*1-1/1)6}}}    Handle leading digit:
  +50<7?6{                               }    If input is greater than 47 ('0' is 48)
          +54>7?6{                      }     And input is less than 58 ('9' is 57)
                                              Then input is a digit
                  -002+7                      Set notepad equal to value of input digit
                        ~                     Take next input (only convenient place for it)
                         ?6{           }      If the notepad isn't 0
                            (        )6       While the notepad isn't 0:
                             @5                 Print a space
                               *1-1/1           Decrement the notepad by one
                                              Leading digit handled

     (-6>7?6&@7+70-4~)6                       Handle rest of line:
     (               )6                       While the notepad isn't 0:
      -6>7?6&                                   Exit if End of Input
             @7                                 Print the next character
               +70-4                            Set notepad to 0 if it was a newline
                    ~                           Take the next character

1
Wow, itu penggunaan sarang yang bagus ... semuanya. +1
MD XF

6

Sekam , 15 13 byte

-2 byte terima kasih kepada @Zgarb

mΓo+?oR' i;±¶

Cobalah online!

Menggunakan teknik yang sama dengan @Jonathan Allan

Penjelasan

             ¶  -- split input into a list of lines
m               -- apply the following function to each line
 Γ              --   deconstruct the string into a head and a tail
  o+            --   prepend to the tail of the string ...
    ?      ±    --     if the head is a digit (n)
     oR' i      --       the string of n spaces
                --     else
          ;     --       the head of the string
                -- implicitly print list of strings line-by-line

2
13 byte dengan penggunaan Γ.
Zgarb

5

JavaScript (ES8), 38 37 byte

a=>a.replace(/^\d/gm,a=>''.padEnd(a))

Saya pikir itu tidak bisa diperbaiki lagi.
Disimpan 1 byte berkat Shaggy - Gunakan fitur ES8.


" Saya tidak berpikir itu dapat ditingkatkan lebih banyak. " - Anda dapat menyimpan byte dengan menggunakan ES8 padEndseperti:s=>s.replace(/^\d/gm,m=>"".padEnd(m))
Shaggy

@ Shaggy. Saya tidak tahu ES8 sudah diizinkan. Terima kasih.

1
Jika ada penerjemah tunggal (mis., Peramban) di luar sana yang mendukung fitur maka fitur itu adalah permainan yang adil di sini :)
Shaggy

4

Python 2 , 98 74 67 65 byte

-24 byte terima kasih kepada Jonathan Allan. -7 byte terima kasih kepada Tn. Xcoder.

for i in open('f'):print' '*int(i[0])+i[1:]if'/'<i[:1]<':'else i,

Cobalah online!

Mengambil input dalam file yang bernama f.


Juga kesalahan ketika tidak ada digit dalam karakter pertama dari sebuah baris (saat menggunakan daftar sebagai cara untuk memilih item, semua elemen dievaluasi)
Jonathan Allan


87 byte - Header tautan TIO mengejek open; kode mengharapkan file bernama 'f'. Saya pikir tidak apa-apa?
Jonathan Allan

Ah, benar ' '*0itu palsu. Menggunakan [:1]masih menyimpan sekalipun. Tidak perlu untuk readsaya percaya (dan itu akan terjadi readlines) karena perilaku default openadalah untuk beralih melalui garis. Juga tidak perlu untuk mode karena 'r'ini adalah default. Jika saya benar itu 73 !
Jonathan Allan


4

Ruby , 24 21 + 1 = 25 22 byte

Menggunakan -pbendera. -3 byte dari GB.

sub(/^\d/){"%#$&s"%p}

Cobalah online!


{"% # $ & s"% ""} menyimpan 1 byte
GB

Dan byte lain jika Anda menggunakan sub bukannya gsub
GB

@ GB dan byte lain dengan meletakkan %pdi akhir, bukan %"". Terima kasih atas bantuan Anda!
Value Ink

3

05AB1E , 10 byte

v0y¬dićú},

Cobalah online!


1
Bagaimana cara satu input dengan baris kosong?
Jonathan Allan

Tidak tahu lol ... Saya akan memeriksanya
Oliver Ni

|vy¬dićú},bekerja selama 10 byte.
Riley

OK, itu bukan salah satu tidak dapat memasukkan baris kosong, itu bahwa kode tidak bekerja untuk baris kosong : jika seseorang menggunakan nol tunggal itu bekerja, jadi pasti ada sesuatu tentang kepala tidak ada (hal yang sama berlaku untuk @ Riley menyarankan 10 byter by the way).
Jonathan Allan

@ JonathanAllan Ada hubungannya dengan cara |kerjanya. Seharusnya push the rest of input as an array with strings, tetapi berhenti di baris kosong ( TIO ). Saya membawa ini di chatroom 05AB1E jika Anda ingin tahu lebih banyak.
Riley

2

Python 3 , 95 byte

lambda y:'\n'.join(re.sub('^\d',lambda x:' '*int(x.group()),z)for z in y.split('\n'))
import re

Cobalah online!

-4 byte dengan mencuri ide regex dari ThePirateBay


4
Anda mencuri dari ThePirateBay , bagaimana tabel telah berubah
joH1

@Moonstroke HAH lol I didn't even notice that :P
HyperNeutrino

2

Jelly, 19 bytes

V⁶ẋ
Ḣǹe?ØD;
ỴÇ€Yḟ0

A monadic link taking and returning lists of characters, or a full program printing the result.

Try it online!

How?

V⁶ẋ - Link 1, make spaces: character (a digit)
V   - evaluate as Jelly code (get the number the character represents)
 ⁶  - a space character
  ẋ - repeat

Ḣǹe?ØD; - Link 2, process a line: list of characters
Ḣ        - head (get the first character and modify the line)
         -   Note: yields zero for empty lines
     ØD  - digit characters = "0123456789"
    ?    - if:
   e     - ...condition: exists in? (is the head a digit?)
 Ç       - ...then: call the last link as a monad (with the head as an argument)
  ¹      - ...else: identity (do nothing; yields the head)
       ; - concatenate with the beheaded line

ỴÇ€Yḟ0 - Main link: list of characters
Ỵ      - split at newlines
 Ç€    - call the last link (1) as a monad for €ach
   Y   - join with newlines
    ḟ0 - filter out any zeros (the results of empty lines)

beheaded line Is that the actual term? xD
HyperNeutrino

1
Well, it is now :)
Jonathan Allan

Ahahaha I tried outgolfing you and ended up with a solution essentially identical to yours xD
HyperNeutrino


2

Haskell, 63 bytes

unlines.map g.lines
g(x:r)|x<';',x>'/'=(' '<$['1'..x])++r
g s=s

Try it online! The first line is an anonymous function which splits a given string into lines, applies the function g to each line and joins the resulting lines with newlines. In g it is checked whether the first character x of a line is a digit. If this is the case, then ['1'..x] yields a string with length equal to the value of the digit x and ' '<$ converts the string into as many spaces. Finally the rest of the line r is appended. If x is not a digit we are in the second equation g s=s and return the line unmodified.


2

Python 2, 76 72 68 bytes

-4 bytes thanks to @ovs!

@DeadPossum suggested switching to Python 2, which saved 4 bytes too.

Just thought it's nice to have a competitive full program in Python 2 that does not explicitly check if the first character is a digit. This reads the input from a file, f.

for i in open('f'):
 try:r=int(i[0])*" "+i[1:]
 except:r=i
 print r,

Try it online! (courtesy of @ovs)


@ovs Thanks for that
Mr. Xcoder

@ovs What did you change (I will do it by hand) ? It tells me that the permalink cannot be decoded
Mr. Xcoder

Instead of printing in every iteration I assigned the output to a variable and printed it all at the end.
ovs

@ovs I managed to get 72 bytes by printing every iteration, thanks for the variable idea!
Mr. Xcoder

Python 2 version of print will give you 68 bytes
Dead Possum

2

Java 8, 105 99 97 93 bytes

Saved few more bytes thanks to Nevay's suggestion,

s->{int i=s.charAt(0);if(i>47&i<58)s=s.substring(1);while(i-->48)s=" "+s;System.out.print(s);}

1
You have two bugs in your golfed version: The digit check has to use and instead of or; The brackets after the digit check are missing. Besides that you can save a few bytes by using s->{int i=s.charAt(0);if(i>47&i<58)for(s=s.substring(1);i-->48;s=" "+s);System.out.print(s);} (93 bytes).
Nevay

@Nevay You are right. Thanks. I'll update my answer.
CoderCroc

2

R, 138 128 bytes

-9 bytes thanks to CriminallyVulgar

n=readLines();for(d in grep("^[0-9]",n))n[d]=gsub('^.?',paste0(rep(' ',eval(substr(n[d],1,1))),collapse=''),n[d]);cat(n,sep='
')

This is pretty bad, but it's a bit better now... R is, once again, terrible at strings.

Try it online!


2
I am commenting on behalf of CriminallyVulgar, who suggests a 129-byte version, but does not have enough reputation to comment.
Mr. Xcoder

@Mr.Xcoder Thank you and @CriminallyVulgar!
Giuseppe

123 Bytes Apparently rep can take a string of an int for the second argument???
CriminallyVulgar

@CriminallyVulgar huh. it's right there in the docs for rep, now that I check them again: "other inputs being coerced to an integer or double vector".
Giuseppe

2

Japt (v2.0a0), 11 10 bytes

Japt beating Jelly and 05AB1E? That doesn't seem right!

r/^\d/m_°ç

Test it


Explanation

Implicit input of string U

r/^\d/m

Use Regex replace (r) all occurrences of a digit at the beginning of a line (m is the multiline flag - the g flag is enabled by default in Japt).

_

Pass each match through a function, where Z is the current element.

°

The postfix increment operator (++). This converts Z to an integer without increasing it for the following operation.

ç

Repeat a space character Z times.

Implicitly output the resulting string.


Can m@ be shortened?
Oliver

Not in this case, @Oliver; the m here is the multi-line flag for the regex, not the map method.
Shaggy

1
@Oliver: r/^\d/m_î (or r/^\d/m_ç) would be 2 bytes shorter but Z is a string so, unfortunately, it wouldn't work. r/^\d/m_°ç, for a 1 byte saving, does work, though :)
Shaggy

°ç is an amazing trick :-) I'd have suggested just \d for the regex, but that leaves out the flag... perhaps I should add support for flags on single-class regexes, like \dm (oh yeah, and that leaves out the ^ too...)
ETHproductions

@ETHproductions, would it be feasible/possible to make the opening / optional in RegExes?
Shaggy

1

Jelly, 19 bytes

Ḣ⁶ẋ;µ¹µḣ1ẇØDµ?
ỴÇ€Y

Try it online!

-5 bytes total thanks to Jonathan Allan's comments and by looking at his post

Explanation

Ḣ⁶ẋ;µ¹µḣ1ẇØDµ?  Main link
             ?  Ternary if
                if:
       ḣ1       the first 1 element(s) (`Head` would modify the list which is not wanted)
         ẇ      is a sublist of (essentially "is an element of")
          ØD    "0123456789"
                then:
  ẋ             repeat
 ⁶              ' '
Ḣ               n times where n is the first character of the line (head)
   ;            concatenate the "beheaded" string (wording choice credited to Jonathan Allan)
                else:
     ¹          Identity (do nothing)
    µ µ     µ   Link separators
ỴÇ€Y            Executed Link
Ỵ               Split by newlines
  €             For each element,
 Ç              call the last link on it
   Y            Join by newlines

no need to swap arguments: Ḣ⁶ẋ;
Jonathan Allan

The pop then head trick wont work if there is a line containing only a single digit character :( -- ;0Ḣ would work for one byte, maybe there is a single atom, I also tried ¹, no joy there
Jonathan Allan

1
@JonathanAllan Ah right. Thanks. ḣ1ẇØD works for the same bytecount \o/
HyperNeutrino

ṚṪ will work :)
Jonathan Allan

@JonathanAllan That works too :) But I made an explanation already for my method so I'm too lazy to change it :P But thanks anyway :)
HyperNeutrino

1

Pyth,  16  15 bytes

jm.x+*;shdtdd.z

Try it online!


Explanation

jm.x+*;shdtdd.z   - Full program that works by reading everything from STDIN.

             .z  - Read all STDIN and split it by linefeeds.
 m               - Map with a variable d.
  .x             - Try:
     *;shd           - To convert the first character to an Integer and multiply it by a space.
    +     td         - And add everything except for the first character
            d        - If the above fails, just add the whole String.
j                 - Join by newlines.

Let's take an example that should be easier to process. Say our input is:

foo bar foo bar
1foo bar foo bar foo bar
2foo bar foo bar foo bar foo bar

The program above will do the following:

  • .z - Reads it all and splits it by newlines, so we get ['foo bar foo bar', '1foo bar foo bar foo bar', '2foo bar foo bar foo bar foo bar'].

  • We get the first character of each: ['f', '1', '2'].

  • If it is convertible to an integer, we repeat a space that integer times and add the rest of the String. Else, we just place the whole String. Hence, we have ['foo bar foo bar', ' foo bar foo bar foo bar', ' foo bar foo bar foo bar foo bar'].

  • Finally, we join by newlines, so our result is:

    foo bar foo bar
     foo bar foo bar foo bar
      foo bar foo bar foo bar foo bar
    

1
Haha, we beat Jelly :)
Mr. Xcoder

1

Cubically, 82 bytes

R3D1R1D1+0(?6{?7@7~:1+2<7?6{+35>7?6{:7-120?6{(B3@5B1-0)6}:0}}}?6!@7~-60=7&6+4-3=7)

Note: This will not work on TIO. To test this, use the Lua interpreter with the experimental flag set to true (to enable conditionals). There's currently a bug with conditional blocks on the TIO interpreter. When using the TIO interpreter, you should replace ?6! with !6 and &6 with ?6&, which keeps the byte count the same.

R3D1R1D1          Set the cube so that face 0 has value 1 and the rest of the values are easy to calculate

+0                Set the notepad to 1 so that it enters the conditional below
(                 Do
  ?6{               If the notepad is 1 (last character was \n or start of input)
    ?7@7              Output the current character if it's \n
    ~                 Get the next character
    :1+2<7?6{         If the input is >= '0'
      +35>7?6{          If the input is <= '9'
        :7-120            Set the notepad to the input - '0'
        ?6{               If the notepad isn't 0
          (                 Do
            B3@5              Output a space
            B1-0              Subtract 1 from notepad
          )6                While notepad > 0
        }                 End if
        :0              Set notepad to 1
      }                 End if
    }                 End if
  }                 End if

  ?6!@7             If the notepad is 0 (did not attempt to print spaces), print current character

  ~                 Get next character
  -60=7&6           If there is no more input, exit the program
  +4-3=7            Check if current character is \n, setting notepad to result
)                 Repeat forever

This isn't as short as the other Cubically answer, but I thought I'd give this a try anyway :D


What's going on with loops in the TIO interpreter?
MD XF

@MDXF ) jumps to the most recent ( rather than the matching one I believe. EDIT: I'm in the chat.
TehPers

@MDXF Maybe it was the conditional blocks, actually. I forgot, I'll update the answer. Regardless, they weren't matching up.
TehPers

1
All right, I'll look at that later. I'm currently finishing Cubically 2.
MD XF

@MDXF That's... really exciting to hear actually o_O
TehPers

1

><>, 60 bytes

!^i:0(?;::"/")$":"(*0$.
v"0"-
>:?!v1-" "o
;>:o>a=&10&?.i:0(?

Try it online!

How It Works:

..i:0(?;... Gets input and ends if it is EOF
...
...
...

.^......::"/")$":"(*0$. If the inputted character is a digit go to the second line
...                     Else go to the fourth
...
...

....        If it was a digit
v"0"-       Subtract the character "0" from it to turn it into the corresponding integer
>:?!v1-" "o And print that many spaces before rejoining the fourth line
...

.^..               On the fourth line,
....               Copy and print the input (skip this if it was a digit)
....v              If the input is a newline, go back to the first line.
;>:o>a=&10&?.i:0(? Else get the input, ending on EOF

0

V, 9 bytes

ç^ä/x@"é 

Try it online!

Explanation

ç  /      ' On lines matching
 ^ä       ' (Start)(digit)
    x     ' Delete the first character
     @"   ' (Copy Register) number of times
       é  ' Insert a space

0

Gema, 21 characters

\N<D1>=@repeat{$1;\ }

Sample run:

bash-4.4$ gema '\N<D1>=@repeat{$1;\ }' <<< 'foo bar foo bar
> 1foo bar foo bar foo bar
> 2foo bar foo bar foo bar foo bar
> 
> --------v
> 8|
> 8|
> 80
> 8,
> 7&'
foo bar foo bar
 foo bar foo bar foo bar
  foo bar foo bar foo bar foo bar

--------v
        |
        |
        0
        ,
       &

0

PHP, 83 chars

preg_replace_callback('/^\d/m',function($m){return str_repeat(' ',$m[0]);},$argv);

I think your code is not compliant with the input rules of this challenge, you should enclose this in a function with a $s arg or populate it with the input. And it doesn't print anything
LP154

@LP154 is using argv acceptable?
Petah

@Petah If I'm correct in assuming argv is the command line args, then yes.
totallyhuman
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.