加长信纸


28

给定一个非空的小写ASCII字母a-z字符串,请输出该字符串,并且该字母的每个连续“游程”都要加长该字母的一个副本。

例如,dddogg3 d “S,1 o2 g “S)打开到ddddooggg4 d “S,2 o “S,3 g “S)。

这是:以字节为单位的最短答案将获胜。

测试用例

aabbcccc-> aaabbbccccc
门铃-> ddooorrbbeelll
uuuuuuuuuuz-> uuuuuuuuuuzz
q-> qq
xyxyxy-> xxyyxxyyxxyy
xxxyyy-> xxxxyyyy

相关(如果运行的长度是奇数,则仅添加另一个字符)
MildlyMilquetoast

Answers:


11

05AB1E,5个字节

.¡€ĆJ

说明:

Example input: "dddogg"
.¡       Split into chunks of consecutive equal elements
         stack: [['ddd', 'o', 'gg']]
  €      For each...
   Ć       Enclose; append the first character to the end of the string
         stack: [['dddd', 'oo', 'ggg']]
    J    Join array elements into one string
         stack: ['ddddooggg']
Implicitly output top element in stack: "ddddooggg"

在线或作为测试套件尝试

附件是一个非常新的内置函数。这是我第一次使用它。很方便 ;)

05AB1E,4个字节(非竞争)

γ€ĆJ

γ在最新更新中已被替换。


封闭是有史以来最疯狂的内置程序之一。
暴民埃里克(Erik the Outgolfer)'17年

3
@EriktheOutgolfer疯狂吗?没事
Okx

我认为您的意思dddd是执行“包围”之后的解释中的堆栈上数组的第一个元素。
硕果累累

哇,等等,这到底是Ć什么?
魔术章鱼缸

另外,xx -> xxxx什么时候应该xx -> xxx...?
魔术章鱼缸



8

Pyth,7个字节

r9hMMr8

测试套件

怎么运行的

r9hMMr8  example input: "xxyx"
     r8  run-length encoding
         [[2, "x"], [1, "y"], [1, "x"]]
  hMM    apply h to each item
         this takes advantage of the overloading
         of h, which adds 1 to numbers and
         takes the first element of arrays;
         since string is array of characters in
         Python, h is invariant on them
         [[3, "x"], [2, "y"], [2, "x"]]
r9       run-length decoding
         xxxyyxx

7

MATL,5个字节

Y'QY"

在线尝试!

说明

考虑输入'doorbell'

Y'    % Implicit input. Run-length encoding
      % STACK: 'dorbel', [1 2 1 1 1 2]
Q     % Increase by 1, element-wise
      % STACK: 'dorbel', [2 3 2 2 2 3]
Y"    % Run-length decoding. Implicit display
      % STACK: 'ddooorrbbeelll'

6

爱丽丝,17个字节

/kf.>o./
@i$QowD\

在线尝试!

说明

/.../
@...\

这是一个用于程序的框架,该程序完全在Ordinal模式下运行,并且基本上是线性的(可以编写简单的循环,并且在该程序中使用了一个循环,但是在这里使用其他分支控制流比较棘手)。指令指针在代码中从左到右沿对角线上下反弹,然后在最后由两个镜像移动一个单元格,然后从右向左移动,执行它在第一次迭代中跳过的单元格。线性化的形式(忽略镜子)基本上如下所示:

ifQ>w.Doo.$k@

让我们来看一下:

i     Read all input as a string and push it to the stack.
f     Split the string into runs of equal characters and push those
      onto the stack.
Q     Reverse the stack, so that the first run is on top.
>     Ensure that the horizontal component of the IP's movement is east.
      This doesn't do anything now, but we'll need it after each loop
      iteration.
w     Push the current IP address to the return address stack. This marks
      the beginning of the main loop.

  .     Duplicate the current run.
  D     Deduplicate the characters in that run so we just get the character
        the run is made up of.
  o     Output the character.
  o     Output the run.
  .     Duplicate the next run. When we've processed all runs, this will
        duplicate an implicit empty string at the bottom of the stack instead.
  $     If the string is non-empty (i.e. there's another run to process),
        execute the next command otherwise skip it.

k     Pop an address from the return address stack and jump there. Note that
      the return address stack stores no information about the IP's direction,
      so after this, the IP will move northwest from the w. That's the wrong
      direction though, but the > sets the horizontal component of the IP's
      direction to east now, so that the IP passes over the w again and can
      now execute the next iteration in the correct direction.
@     Terminate the program.


4

Brachylog,8个字节

ḅ{t,?}ᵐc

在线尝试!

说明

             Example input: "doorbell"
ḅ            Blocks: ["d","oo","r","b","e","ll"]
 {   }ᵐ      Map: ["dd","ooo","rr","bb","ee","lll"]
  t            Tail: "d" | "o" | "r" | "b" | "e" | "l"
   ,?          Prepend to input: "dd" | "ooo" | "rr" | "bb" | "ee" | "lll"
       c     Concatenate: "ddooorrbbeelll"


@LeakyNun我实际上在发布此文章后也发现了一个
-Fatalize

您确实需要~优先于元谓词(或将其更改为后缀操作);如果您这样做了,则可以在七分钟内完成。



3

C,53字节

i;f(char*s){for(;i=*s++;)putchar(i^*s?putchar(i):i);}

在线尝试!


1
感谢您发布此解决方案,因为它激励了我提出一个较短的解决方案,该方案省略了第二个putchar。已投票。
2501年


3

Japt,8字节

7个字节的代码,-P标志+1 。

ó¥ ®+Zg

在线测试!

说明

这使用了ó我昨天刚刚添加的(falsy分区)内置函数:

ó¥  ®   +Zg
ó== mZ{Z+Zg}

ó==           // Split the input into runs of equal chars.
    mZ{    }  // Replace each item Z in this array with
       Z+Zg   //   Z, concatenated with the first char of Z.
-P            // Join the resulting array back into a string.
              // Implicit: output result of last expression

3

六角形,33字节

\~..,}/',\<.-/.<@;$>.${;/${/"$.>$

展开:

   \ ~ . .
  , } / ' ,
 \ < . - / .
< @ ; $ > . $
 { ; / $ { /
  " $ . > $
   . . . .

在线尝试!

伪代码或多或少:

char = readchar()
while (char > 0)
    print(char)
    run_char = char
    do
        print(char)
        char = readchar()
    while (run_char == char)

3

JavaScript(ES6),33个 30字节

s=>s.replace(/(.)\1*/g,"$1$&")

试试吧

f=
s=>s.replace(/(.)\1*/g,"$1$&")
i.addEventListener("input",_=>o.innerText=f(i.value))
console.log(f("aabbcccc")) // aaabbbccccc
console.log(f("doorbell")) // ddooorrbbeelll
console.log(f("uuuuuuuuuz")) // uuuuuuuuuuzz
console.log(f("q")) // qq
console.log(f("xyxyxy")) // xxyyxxyyxxyy
console.log(f("xxxyyy")) // xxxxyyyy
<input id=i><pre id=o>


3

疯子,23字节

,[.[->->+<<]>[[-]>.<],]

在线尝试!

说明

,            read the first input character
 [           main loop to be run for each input character
 .           output the character once
 [->->+<<]   subtract from previous character (initially 0), and create a copy of this character
 >[          if different from previous character:
   [-]       zero out cell used for difference (so this doesn't loop)
   >.<       output character again from copy
 ]
 ,           read another input character
]

1
可以使用大于256的字母运行吗?
硕果累累

@ Challenger5是的。甚至没有跟踪行程,因此没有办法使行程溢出。
Nitrodon

2

Perl 6、18个字节

{S:g/)>(.)$0*/$0/}

试试吧

展开:

{   # bare block lambda with implicit parameter 「$_」

  S        # replace and return
  :global  # all occurrences
  /

    )>     # don't actually remove anything after this

    (.)    # match a character

    $0*    # followed by any number of the same character

  /$0/     # replace with the character (before the match)
}

2

05AB1E,8个字节

.¡DÔ‚ø˜J

在线尝试!

说明:

.¡DÔ‚ø˜J
.¡       Split equal runs of input
  D      Duplicate
   Ô     Take connected-uniquified
    ‚    Pair connected-uniquified equal runs with original equal runs
     ø   Zip
      ˜  Deep-flatten (i.e. normal flattening)
       J Join elements together

2

Haskell,36个字节

f(a:b:c)=a:[a|a/=b]++f(b:c)
f x=x++x

用法示例:f "aab"-> "aaabb"在线尝试!

当字符串中至少有两个字符时,请绑定a到第一个字符,b第二个字符和c其余字符串。输出a之后是aif a不等于,b然后使用进行递归调用b:c。如果只有一个字符,则结果是此字符的两倍。


2

CJam,10个字节

le`1af.+e~

在线尝试!

说明:

e# Input: doorbell
l   e# Read line:              | "doorbell"
e`  e# Run-length encode:      | [[1 'd] [2 'o] [1 'r] [1 'b] [1 'e] [2 'l]]
1a  e# Push [1]:               | [[1 'd] [2 'o] [1 'r] [1 'b] [1 'e] [2 'l]] [1]
f.+ e# Vectorized add to each: | [[2 'd] [3 'o] [2 'r] [2 'b] [2 'e] [3 'l]]
e~  e# Run-length decode:      | "ddooorrbbeelll"
e# Implicit output: ddooorrbbeelll

2

Ruby,30个字节

->s{s.gsub(/((.)\2*)/){$1+$2}}

2

果冻,5个字节

n2\׿

在线尝试!

怎么运行的

n2\׿  Main link. Argument: s (string)

n2\    Reduce all overlapping slices of length two by non-equal.
       For input "doorbell", this returns [1, 0, 1, 1, 1, 1, 0].
   ×   Multiply the characters of s by the Booleans in the resulting array. This is
       essentially a bug, but integer-by-string multiplication works as in Python.
       For input "doorbell", this returns ['d', '', 'o', 'r', 'b', 'e', '', 'l'].
       Note that the last character is always left unchanged, as the Boolean array
       has one fewer element than s.
    ż  Zip the result with s, yielding an array of pairs.
       For input "doorbell", this returns [['d', 'd'], [[], 'o'], ['o', 'o'],
           ['r', 'r'], ['b', 'b'], ['e', 'e'], [[], 'l'], ['l', 'l']].
       (implicit) Print the flattened result.

丹尼斯,打得好。
Leaky Nun

1

批量140字节

@set/ps=
@set r=
:g
@if not "%s:~,1%"=="%s:~1,1%" set r=%r%%s:~,1%
@set r=%r%%s:~,1%
@set s=%s:~1%
@if not "%s%"=="" goto g
@echo %r%

在STDIN上输入。





1

Mathematica,34岁 21字节

感谢Martin Ender 在Mathematica中找到了正确的方法来节省13个字节!

##&[#,##]&@@@Split@#&

使用字符数组作为输入和输出格式的纯函数。Split将列表分成相等的字符。##&[#,##]&是一个返回一系列参数的函数:第一个参数被输入,然后是所有参数(因此特别重复第一个);@@@它将()应用于列表的每个子Split列表。


1
也许##&[#,##]&@@@Split@#&吧?(未经测试。)
Martin Ender's

1
^现在测试。顺便说一句,Gather如果有多个相同字符的运行实际上是行不通的(但幸运的Split是反正短了一个字节)
Martin Ender

(哦,是的,我的意思是我的意思Split)您的第一个评论的构想很棒!
格雷格·马丁

1

Java中,151个 146 60字节

String f(String s){return s.replaceAll("((.)\\2*)","$1$2");}
  • -5个字节,感谢@FryAmTheEggman
  • -86字节,感谢@KevinCruijssen

正则表达式

(         )     group

 (.)            a character

     \\2*       optional repetition

详细

import java.util.*;
import java.lang.*;
import java.io.*;

class H
{
    public static String f(String s)
    {
        return s.replaceAll("((.)\\2*)","$1$2");
    }

    public static void main(String[] args)
    {
        f("dddogg");
    }
}

没有注意到已经有Java答案,所以我删除了我的。但是为什么MatcherPattern?您可以像这样将其打高尔夫球至60个字节String f(String s){return s.replaceAll("((.)\\2*)","$1$2");}
Kevin Cruijssen

@KevinCruijssen现在修复,谢谢。
Khaled.K

1

疯子,38个字节

,.[.>,[[->+>+<<]<[->>-<<]>>[[-]>.<]]>]

在线尝试!

,.               print the "doubling" of the first char of input
[                this main loop runs on every char
  .              print it "normally" (the not-doubling)
  >,             read the next char
  [              judiciously placed "loop" to prevent printing NULs
    [->+>+<<]    copy new char at position p to p+1 and p+2
    <[->>-<<]>>  subtract old char from p+1 - zero if same, nonzero otherwise
    [            if it *is* different (nonzero)...
      [-]        clear it
      >.<        print the char (at p+2 now) again
    ]
  ]
  >              the new char is now the old char
]

1

爱丽丝,12字节

甚至在发布此答案之前,都要感谢马丁·恩德(Martin Ender)打了两个字节。他比您想像的还要强大。

I4&.h%?-$OO!

在线尝试!

说明

I                 Input a character and push its unicode value
 4&.              Push 4 more copies of this value to the stack
                  (they will be needed for the following operations)
    h%            Try to compute n%(n+1), exits with an error if n==-1
                  which happens on EOF
      ?           Push a copy of what's currently on the tape.
                  In the first iteration this will push -1, in following
                  iterations it will push the previous character.
       -$O        If the two topmost values on the stack are different
                  output the third one. This will output one more copy of
                  any new character encountered.
          O       Output this character.
           !      Store this character on the tape.

                  Execution loops back to the beginning of the line.
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.