实施空白高尔夫球手


15

某些二维esolang(例如Forked)和某些非eolang(例如Python)有时可能在代码行之前需要空格。这不是高尔夫运动。另外,我很懒,在编写2d lang之前需要很多空格。您的任务是编写一个使这些语言更具特色的工具。

当然,这不是完美的。例如,当数字是源代码行中的第一个字符时,就不能使用它。但是,它通常是有用的。

挑战

您将编写一个程序或函数,该程序或函数可以...

  • ...采用一个参数,文件名或字符串,或者...
  • ...从标准输入中读取。

您的程序的行为类似于cat,除了:

  • 如果任一行的第一个字符是数字,则您的代码将打印x个空格,其中x是该数字。
  • 否则,将仅打印它。
  • 输入中的所有其他字符也一样。

测试用例

输入:

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

输出:

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

输入:

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

输出:

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

输入:

foo bar
bar foo
foo bar

输出:

foo bar
bar foo
foo bar

输入:

0123456789
1234567890
2345678901
3456789012
4567890123

输出:

123456789
 234567890
  345678901
   456789012
    567890123

规则

  • 输出必须与输入完全相同,但第一个字符是数字的行除外。
  • 您的程序无法在文件中追加/添加任何内容,但如果需要,可以在结尾加上换行符。
  • 您的程序可能不假设输入内容。它可能包含空行,无数字,Unicode字符等。
  • 如果一个数字多于一个数字开始一行(例如523abcdefg),则只有第一个数字(在本例中为5)应该变成空格。

优胜者

每种语言中最短的代码将获胜。玩得开心,祝你好运!



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.不正确,只需将第一个字符
— 设为

我们可以从stdin中读取字符串列表吗(这是有效的)吗?
— 莱利

Answers:



10

大概是69个字节

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

在线尝试!

说明:

首先我们进行以下初始化:

R1B1R3B1

要设置此多维数据集:

   533
   004
   000
411223455441
311222331440
311222331440
   555
   555
   200

这个立方体最重要的是那张脸 5总和为32,这是打印空格所需的值。巧合的是,对于所有其他计算,它也很短。完成之后:

~( . . . )                                    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
哇,这是嵌套...一切的好用法。+1
— MD XF

6

稻壳,15 13字节

-2个字节,感谢@Zgarb

mΓo+?oR' i;±¶

在线尝试!

使用与@Jonathan Allan相同的技术

说明

             ¶  -- 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个字节Γ。
— Zgarb

5

的JavaScript(ES8),38 37个字节

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

我认为无法进一步改善。
感谢Shaggy-使用ES8功能,节省了1个字节。


“ 我认为它无法进一步改善。 ”-您可以padEnd像这样使用ES8来节省一个字节:s=>s.replace(/^\d/gm,m=>"".padEnd(m))
— Shaggy

@毛茸茸。我不知道已经允许使用ES8。谢谢。

1
如果那里有支持该功能的单个解释器(即浏览器),则该功能在这里很公平:)
— Shaggy

4

Python 2中,98 74 67 65字节

-24字节感谢Jonathan Allan。-7个字节感谢Xcoder先生。

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

在线尝试!

在名为的文件中输入f。


当一行的第一个字符中没有数字时也会出错(使用列表作为选择所有元素的方法时)
— Jonathan Allan


87个字节 -TIO链接的标头是模拟的open;代码需要一个名为“ f”的文件。我认为可以吗?
— 乔纳森·艾伦

啊,真是' '*0假。使用[:1]仍然是一个节省。无需read我相信(这将是readlines)因为默认行为open是迭代通过线。由于'r'默认设置,因此也不需要此模式。如果我是对的,那就是73岁!
— 乔纳森·艾伦


4

红宝石,24 21 + 1 = 25 22字节

使用-p标志。GB的-3个字节。

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

在线尝试!


{“%#$&s”%“”}保存1个字节
— GB

还有一个字节,如果您使用sub而不是gsub
— GB

@GB和另一个字节,方法是放在%p末尾而不是%""。谢谢你的帮助!
— 价值墨水

3

05AB1E,10个字节

v0y¬dićú},

在线尝试!


1
空行如何输入?
— 乔纳森·艾伦,

不知道大声笑...我会调查一下
— 奥利弗·尼

|vy¬dićú},适用于10个字节。
— 莱利

好的,不是一个人不能输入空行,而是代码对空行不起作用:如果一个人使用单个零,它就可以工作,所以它一定是关于头部不存在的(@Riley建议的10也是如此)顺便说一句)。
— 乔纳森·艾伦

@JonathanAllan它与|工作方式有关。它应该是push the rest of input as an array with strings,但是停在空行(TIO)。如果您想了解更多,我在05AB1E聊天室中提出了这一点。
— 莱利

2

Python 3,95字节

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

在线尝试!

通过从ThePirateBay窃取正则表达式的想法获得-4个字节


4
您从ThePirateBay偷了,桌子如何转动
— joH1

@Moonstroke HAH大声笑我什至没有注意到:P
— HyperNeutrino

2

果冻,19 字节

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

用于获取和返回字符列表的单子链接,或打印结果的完整程序。

在线尝试!

怎么样?

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那是实际用语吗?xD
— HyperNeutrino

1
好吧,现在是:)
— 乔纳森·艾伦

啊哈哈哈,我尝试使您失望,并最终获得了与您的xD基本相同的解决方案
— HyperNeutrino


2

哈斯克尔,63个字节

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

在线尝试!第一行是一个匿名函数,它将给定的字符串分成几行,将函数g应用于每一行,并将结果行与换行符连接起来。在g其中检查x行的第一个字符是否是数字。如果是这种情况,那么将['1'..x]产生一个长度等于数字值的字符串x,' '<$并将该字符串转换为尽可能多的空格。最后,该行的其余部分r被附加。如果x不是数字,我们在第二个方程式中,g s=s并返回未修改的行。


2

Python 2中,76 72 68字节

-4个字节,感谢@ovs!

@DeadPossum建议切换到Python 2,它也节省了4个字节。

只是觉得在Python 2中有一个竞争性的完整程序会很不错,而该程序不会显式检查第一个字符是否为数字。这将从文件读取输入f。

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

在线尝试!(由@ovs提供)


@ovs感谢您的
— Xcoder先生

@ovs您做了什么更改(我会手工完成)?它告诉我永久链接无法解码
— Xcoder先生,2017年

我没有在每次迭代中打印,而是将输出分配给变量,并在最后全部打印。
— ovs '17

@ovs通过打印每次迭代,我设法获得了72个字节,这要归功于可变的想法!
— Xcoder先生17年

的Python 2版本print将为您提供68个字节
— 死负鼠(

2

爪哇8,105 99 97 93字节

多亏了Nevay的建议,节省了几个字节,

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
您的高尔夫版本中有两个错误:数字校验必须使用和代替or;数字检查后的括号丢失。除此之外,您还可以使用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个字节)节省一些字节。
— 涅瓦

@Nevay你是对的。谢谢。我将更新我的答案。
— CoderCroc

2

R,138128字节

-9个字节归功于CrimealVulgar

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='
')

这是很糟糕的,但是现在好一点了……R再次在字符串方面很糟糕。

在线尝试!


2
我评论代表CriminallyVulgar,谁提出一个129字节的版本,但没有足够的信誉评论。
— Xcoder先生17年

@ Mr.Xcoder谢谢您和@CriminallyVulgar!
— 朱塞佩

123字节显然rep可以为第二个参数采用int字符串。
— 刑事

@CriminallyVulgar呵呵。就在rep的文档中,现在我再次检查它们:“其他输入被强制转换为整数或双精度向量”。
— 朱塞佩

2

Japt(v2.0a0), 11 10字节

Japt击败Jelly 和 05AB1E?这似乎不对!

r/^\d/m_°ç

测试一下


说明

字符串的隐式输入 U

r/^\d/m

使用Regex replace(r)在行首出现的所有数字(m是多行标志-该g标志在Japt中是默认启用的)。

_

通过功能传递每个匹配项,Z当前元素在哪里。

°

后缀增量运算符(++)。Z在不进行后续操作的情况下,它将转换为整数而不增加它。

ç

重复空格字符 Z时间。

隐式输出结果字符串。


可以m@缩短吗?
— 奥利弗·

在这种情况下不是@Oliver;在m这里是正则表达式,而不是地图方法多行标记。
— 毛茸茸的

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

°ç是一个了不起的伎俩:-)我建议只\d对正则表达式,但省去了标志......也许我应该补充支持单级正则表达式,如标志\dm(噢,而且省去了^过...)
— ETHproductions'Aug 9'9

@ETHproductions,/在RegExes 中将开放设置为可选是否可行/可行?
— 毛茸茸的

1

果冻,19字节

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

在线尝试!

感谢乔纳森·艾伦(Jonathan Allan)的评论以及他的帖子,共-5字节

说明

Ḣ⁶ẋ;µ¹µḣ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

无需交换参数:Ḣ⁶ẋ;
— 乔纳森·艾伦

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也是可行的:)但是我已经为我的方法做了一个解释,所以我懒得更改它:P但还是要感谢:)
— HyperNeutrino

1

Pyth, 16  15字节

jm.x+*;shdtdd.z

在线尝试!


说明

jm.x + *; shdtdd.z-通过从STDIN中读取所有内容的完整程序。

             .z-读取所有STDIN并将其按换行分隔。
 m-具有变量d的映射。
  .x-尝试:
     *; shd-将第一个字符转换为Integer并将其乘以空格。
    + td-并添加除第一个字符外的所有内容
            d-如果以上操作失败,则只需添加整个String。
j-通过换行符加入。

让我们举一个应该更容易处理的示例。说我们的输入是:

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

上面的程序将执行以下操作:

  • .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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.