Wydłuż bieg listów


28

Biorąc pod uwagę niepusty ciąg małych liter ASCII a-z, wypisuj ten ciąg z każdym kolejnym „uruchomieniem” tej samej litery, przedłużonym o jeszcze jedną kopię tej litery.

Na przykład dddogg( 3 d , 1 o , 2 g ) zmienia się w ddddooggg( 4 d , 2 o , 3 g ).

To jest : wygrywa najkrótsza odpowiedź w bajtach.

Przypadki testowe

aabbcccc -> aaabbbccccc
dzwonek do drzwi -> ddooorrbbeelll
uuuuuuuuuz -> uuuuuuuuuuzz
q -> qq
xyxyxy -> xxyyxxyyxxyy
xxxyyy -> xxxxyyyy

Powiązane (dodaj inny znak, jeśli długość biegu jest nieparzysta)
MildlyMilquetoast

Odpowiedzi:


11

05AB1E , 5 bajtów

.¡€ĆJ

Wyjaśnienie:

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"

Wypróbuj online lub jako pakiet testowy .

Enclose jest całkiem nowym wbudowanym; to pierwszy raz, kiedy go użyłem. Bardzo wygodne;)

05AB1E , 4 bajty (niekonkurujące)

γ€ĆJ

został zastąpiony przez γw najnowszej aktualizacji.


Enclose to jedno z najbardziej zwariowanych wbudowań w historii.
Erik the Outgolfer,

3
@EriktheOutgolfer Crazy? Nie
Okx,

Myślę, że masz na myśli ddddpierwszy element tablicy na stosie w wyjaśnieniu po wykonaniu polecenia „załącz”.
Esolanging Fruit

Woah, poczekaj chwilkę, co to do cholery jest Ć?
Magic Octopus Urn

Ponadto, xx -> xxxxkiedy powinno być xx -> xxx...?
Magic Octopus Urn



8

Pyth , 7 bajtów

r9hMMr8

Zestaw testowy .

Jak to działa

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 bajtów

Y'QY"

Wypróbuj online!

Wyjaśnienie

Rozważ wejście '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

Alice , 17 bajtów

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

Wypróbuj online!

Wyjaśnienie

/.../
@...\

Jest to struktura dla programów, które działają w całości w trybie porządkowym i są zasadniczo liniowe (można napisać proste pętle, a jedna jest używana w tym programie, ale trudniej jest tu pracować z inaczej rozgałęzionym przepływem sterowania). Wskaźnik instrukcji odbija się po przekątnej w górę i w dół przez kod od lewej do prawej, a następnie zostaje przesunięty o jedną komórkę o dwa lustra na końcu, a następnie przesuwa się z prawej do lewej, wykonując komórki, które pominął przy pierwszej iteracji. Zlinearyzowana forma (ignorowanie kopii lustrzanych) w zasadzie wygląda następująco:

ifQ>w.Doo.$k@

Przejdźmy przez to:

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 bajtów

ḅ{t,?}ᵐc

Wypróbuj online!

Wyjaśnienie

             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 Znalazłem to też zaraz po opublikowaniu tego
Fatalize

Naprawdę musisz ~mieć pierwszeństwo przed metapredykatami (lub zmienić na operację postfiksową); jeśli tak, możesz to zrobić w siedem.



3

C, 53 bajty

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

Wypróbuj online!


1
Dziękujemy za opublikowanie tego rozwiązania, ponieważ zmotywowało mnie to do opracowania krótszego rozwiązania, które pomija drugi putchar. Pozytywne.
2501


3

Japt , 8 bajtów

7 bajtów kodu, +1 dla -Pflagi.

ó¥ ®+Zg

Przetestuj online!

Wyjaśnienie

Korzysta z ówbudowanego (partycja na falsy), który właśnie dodałem wczoraj:

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

Sześciokąt , 33 bajty

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

Rozszerzony:

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

Wypróbuj online!

Pseudo-kod to mniej więcej:

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

3

JavaScript (ES6), 33 30 bajtów

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

Spróbuj

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

pieprzenie mózgu , 23 bajty

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

Wypróbuj online!

Wyjaśnienie

,            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
Czy to zadziała z listem działa> 256?
Esolanging Fruit

@ Challenger5 Tak. Długość przebiegu nie jest nawet śledzona, więc nie ma możliwości przepełnienia długości przebiegu.
Nitrodon,

2

Perl 6 , 18 bajtów

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

Spróbuj

Rozszerzony:

{   # 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 bajtów

.¡DÔ‚ø˜J

Wypróbuj online!

Wyjaśnienie:

.¡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 bajtów

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

Przykład użycia: f "aab"-> "aaabb". Wypróbuj online!

Gdy łańcuch ma co najmniej dwa znaki, powiąż az pierwszym znakiem, bz drugim i cresztą łańcucha. Po wyjściu anastępuje aif, jeśli anie jest równe, ba następnie wywołanie rekurencyjne z b:c. Jeśli jest tylko jeden znak, wynik jest dwa razy większy niż ten znak.


2

CJam, 10 bajtów

le`1af.+e~

Wypróbuj online!

Wyjaśnienie:

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

Galaretka , 5 bajtów

n2\׿

Wypróbuj online!

Jak to działa

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.

Dobra gra, Dennis.
Leaky Nun

1

Partia, 140 bajtów

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

Pobiera dane wejściowe na STDIN.





1

Mathematica, 34 21 bajtów

Podziękowania dla Martina Endera za znalezienie odpowiedniego sposobu na zrobienie tego w Mathematica, oszczędzając 13 bajtów!

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

Czysta funkcja wykorzystująca tablicę znaków jako formaty wejściowe i wyjściowe. Splitdzieli listę na sekwencje równych znaków. ##&[#,##]&jest funkcją, która zwraca sekwencję argumentów: pierwszy argument jest podawany, a następnie wszystkie argumenty (więc w szczególności powtarzanie pierwszego); jest to stosowane ( @@@) do każdej podlisty Splitlisty.


1
Może ##&[#,##]&@@@Split@#&? (Nietestowane.)
Martin Ender

1
^ Teraz przetestowane. Btw, Gathertak naprawdę nie działa, jeśli istnieje wiele przebiegów tej samej postaci (ale na szczęście Spliti tak jest bajt krótszy)
Martin Ender

(och tak, miałem na myśli Splitw sercu) Cudowna konstrukcja w twoim pierwszym komentarzu!
Greg Martin

1

Java, 151 146 60 bajtów

String f(String s){return s.replaceAll("((.)\\2*)","$1$2");}
  • -5 bajtów, dzięki @FryAmTheEggman
  • -86 bajtów, dzięki @KevinCruijssen

Regex

(         )     group

 (.)            a character

     \\2*       optional repetition

Szczegółowy

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");
    }
}

Nie zauważyłem, że jest już odpowiedź Java, więc usunąłem moją. Ale dlaczego Matcheri Pattern? Możesz String f(String s){return s.replaceAll("((.)\\2*)","$1$2");}
zagrać w

@KevinCruijssen naprawione teraz, dzięki.
Khaled.K

1

pieprzenie mózgu , 38 bajtów

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

Wypróbuj 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
]

1

Alice , 12 bajtów

Dwa bajty zostały rozegrane dzięki Martinowi Enderowi jeszcze przed opublikowaniem tej odpowiedzi. Jest potężniejszy niż można sobie wyobrazić.

I4&.h%?-$OO!

Wypróbuj online!

Wyjaśnienie

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.
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.