Briefläufe verlängern

28

Bei einer nicht leeren Zeichenfolge aus ASCII-Kleinbuchstaben a-zgeben Sie diese Zeichenfolge mit jedem aufeinanderfolgenden „Durchlauf“ desselben Buchstabens aus, der um eine weitere Kopie dieses Buchstabens verlängert wird.

Zum Beispiel wird dddogg( 3 d , 1 o , 2 g ) zu ddddooggg( 4 d , 2 o , 3 g ).

Das ist : Die kürzeste Antwort in Bytes gewinnt.

Testfälle

aabbcccc -> aaabbbccccc
türklingel -> ddooorrbbeelll
uuuuuuuuuz -> uuuuuuuuuzz
q -> qq
xyxyxy -> xxyyxxyyxxyy
xxxyyy -> xxxxyyyy
Lynn
quelle
Verwandte (nur ein weiteres Zeichen hinzufügen, wenn die Länge des Laufs ungerade ist)
MildlyMilquetoast

Antworten:

11

05AB1E , 5 Bytes

.¡€ĆJ

Erläuterung:

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"

Probieren Sie es online oder als Testsuite aus .

Enclose ist ein ziemlich neues Produkt. Es ist das erste Mal, dass ich es benutzt habe. Sehr angenehm ;)

05AB1E , 4 Bytes (nicht konkurrierend)

γ€ĆJ

wurde durch γdas neueste Update ersetzt.

Okx
quelle
Enclose ist eines der verrücktesten Bauwerke überhaupt.
Erik der Outgolfer
3
@EriktheOutgolfer Verrückt? Nein.
Ok
Ich denke, Sie meinen ddddfür das erste Element des Arrays auf dem Stapel in der Erklärung, nachdem "einschließen" ausgeführt wird.
Esolanging Fruit
Woah, warte mal, was zur Hölle ist das Ć?
Magic Octopus Urn
Auch xx -> xxxxwann sollte es sein xx -> xxx...?
Magic Octopus Urn
8

Pyth , 7 Bytes

r9hMMr8

Testsuite .

Wie es funktioniert

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
Undichte Nonne
quelle
7

MATL , 5 Bytes

Y'QY"

Probieren Sie es online!

Erläuterung

Betrachten Sie die Eingabe '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'
Luis Mendo
quelle
6

Alice , 17 Bytes

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

Probieren Sie es online!

Erläuterung

/.../
@...\

Dies ist ein Framework für Programme, die vollständig im Ordinal-Modus arbeiten und im Wesentlichen linear sind (einfache Schleifen können geschrieben werden, und eine wird in diesem Programm verwendet, aber es ist schwieriger, hier mit einem ansonsten verzweigten Steuerungsfluss zu arbeiten). Der Befehlszeiger springt diagonal von links nach rechts auf und ab, wird dann von den beiden Spiegeln am Ende um eine Zelle verschoben und von rechts nach links zurückgeschoben, wobei die Zellen ausgeführt werden, die er bei der ersten Iteration übersprungen hat. Die linearisierte Form (ohne Berücksichtigung der Spiegel) sieht dann im Wesentlichen so aus:

ifQ>w.Doo.$k@

Lass uns das durchgehen:

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.
Martin Ender
quelle
4

Brachylog , 8 Bytes

ḅ{t,?}ᵐc

Probieren Sie es online!

Erläuterung

             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"
Tödlich
quelle
@LeakyNun Ich habe das tatsächlich auch gleich nach dem Posten gefunden
Fatalize
Sie müssen wirklich ~sicherstellen , dass Metapredicates Vorrang haben (oder es in eine Postfix-Operation ändern). Wenn du das tust, könntest du das in sieben machen.
3

C 53 Bytes

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

Probieren Sie es online!

betseg
quelle
1
Vielen Dank, dass Sie diese Lösung veröffentlicht haben, da sie mich dazu motiviert hat, eine kürzere Lösung zu entwickeln, bei der der zweite Putchar weggelassen wurde. Upvoted.
2501
3

PHP, 40 Bytes

<?=preg_filter('#(.)\1*#',"$1$0",$argn);

Online Version

PHP <7.1, 44 Bytes

Version ohne Regex

for(;a&$c=$argn[$i++];)echo$c[$c==$l].$l=$c;

Online Version

Jörg Hülsermann
quelle
3

Japt , 8 Bytes

7 Byte Code, +1 für das -PFlag.

ó¥ ®+Zg

Online testen!

Erläuterung

Dies verwendet die ó(Partition auf falsch) eingebaute, die ich gestern hinzugefügt habe:

ó¥  ®   +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
ETHproductions
quelle
3

Hexagony , 33 Bytes

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

Erweitert:

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

Probieren Sie es online!

Der Pseudocode ist mehr oder weniger:

char = readchar()
while (char > 0)
    print(char)
    run_char = char
    do
        print(char)
        char = readchar()
    while (run_char == char)
FryAmTheEggman
quelle
3

JavaScript (ES6), 33-30 Bytes

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

Versuch es

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>

Zottelig
quelle
3

Brainfuck , 23 Bytes

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

Probieren Sie es online!

Erläuterung

,            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
]
Nitrodon
quelle
1
Funktioniert das mit Briefen> 256?
Esolanging Fruit
@ Challenger5 Ja. Die Lauflänge wird nicht einmal nachverfolgt, daher kann die Lauflänge nicht überlaufen.
Nitrodon
2

Perl 6 , 18 Bytes

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

Versuch es

Erweitert:

{   # 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)
}
Brad Gilbert b2gills
quelle
2

05AB1E , 8 Bytes

.¡DÔ‚ø˜J

Probieren Sie es online!

Erläuterung:

.¡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
Erik der Outgolfer
quelle
2

Haskell, 36 Bytes

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

Anwendungsbeispiel: f "aab"-> "aaabb". Probieren Sie es online!

Wenn die Zeichenfolge mindestens zwei Zeichen enthält, binden Sie sie aan das erste Zeichen, an das bzweite Zeichen und can den Rest der Zeichenfolge. Auf die Ausgabe afolgt, awenn anicht gleich, bein rekursiver Aufruf mit b:c. Wenn es nur ein Zeichen gibt, ist das Ergebnis das Zweifache dieses Zeichens.

nimi
quelle
2

CJam, 10 Bytes

le`1af.+e~

Probieren Sie es online!

Erläuterung:

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
Esolanging Fruit
quelle
2

Ruby, 30 Bytes

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

Gelee , 5 Bytes

n2\׿

Probieren Sie es online!

Wie es funktioniert

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.
Dennis
quelle
Gut gespielt, Dennis.
Undichte Nonne
1

Batch, 140 Bytes

@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%

Übernimmt die Eingabe für STDIN.

Neil
quelle
1

sed, 18-15 Bytes (+1 für -r)

s/(.)\1*/\1&/g

Originelle Lösung

s/((.)\2*)/\1\2/g
Ryan McCleary
quelle
1

R, 36 Bytes

gsub("((.)\\1*)","\\2\\1",scan(,""))
Flodel
quelle
1

Mathematica, 34 21 Bytes

Vielen Dank an Martin Ender, der in Mathematica den richtigen Weg gefunden hat, um 13 Byte zu sparen!

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

Reine Funktion mit einer Reihe von Zeichen als Eingabe- und Ausgabeformat. Splittrennt eine Liste in gleiche Zeichenfolgen. ##&[#,##]&ist eine Funktion, die eine Folge von Argumenten zurückgibt: das erste Argument, das eingegeben wird, dann alle Argumente (also insbesondere das erste wiederholen); Dies wird @@@auf jede Unterliste der SplitListe angewendet ( ) .

Greg Martin
quelle
1
Vielleicht ##&[#,##]&@@@Split@#&? (Ungetestet.)
Martin Ender
1
^ Jetzt getestet. Übrigens, Gatherfunktioniert nicht wirklich, wenn es mehrere Läufe desselben Charakters gibt (aber zum Glück Splitist das ein Byte kürzer)
Martin Ender
(oh ja, ich meinte Splitin meinem Herzen) Wunderbare Konstruktion in Ihrem ersten Kommentar!
Greg Martin
1

Java, 151 146 60 Bytes

String f(String s){return s.replaceAll("((.)\\2*)","$1$2");}
  • -5 Bytes, danke an @FryAmTheEggman
  • -86 Bytes dank @KevinCruijssen

Regex

(         )     group

 (.)            a character

     \\2*       optional repetition

Detailliert

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");
    }
}
Khaled.K
quelle
Hatte nicht bemerkt, dass es bereits eine Java-Antwort gab, also habe ich meine gelöscht. Aber warum das Matcherund Pattern? Sie können es auf 60 Bytes wie String f(String s){return s.replaceAll("((.)\\2*)","$1$2");}
folgt golfen
@ KevinCruijssen jetzt behoben, thx.
Khaled.K
1

Brainfuck , 38 Bytes

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

Probieren Sie es online!

,.               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
]
Türknauf
quelle
1

Alice , 12 Bytes

Zwei Bytes wurden dank Martin Ender golfen, noch bevor diese Antwort veröffentlicht wurde. Er ist mächtiger, als Sie sich jemals vorstellen können.

I4&.h%?-$OO!

Probieren Sie es online!

Erläuterung

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.
Löwe
quelle