Збільшити пробіжки літер


28

Враховуючи непорожній рядок з малих літер ASCII a-z, виведіть цей рядок із кожним послідовним “запуском” одного і того ж листа, подовженого ще однією копією цього листа.

Наприклад, dddogg( 3 d 's, 1 o , 2 g ' s) перетворюється на ddddooggg( 4 d 's, 2 o ' s, 3 g 's).

Це : виграє найкоротша відповідь у байтах.

Тестові справи

aabbcccc -> aaabbbccccc
дзвінок у двері -> ddooorrbbeelll
уууууууууз -> уууууууууузз
q -> qq
xyxyxy -> xxyyxxyyxxyy
xxxyyy -> xxxxyyyy

Пов’язані (додайте лише іншого символу, якщо тривалість пробігу непарна)
MildlyMilquetoast

Відповіді:


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"

Спробуйте його в Інтернеті або як тестовий набір .

Enclose - досить новий вбудований; це я вперше застосував. Дуже зручно;)

05AB1E , 4 байти (не конкуруючий)

γ€ĆJ

було замінено γна останнє оновлення.


Enclose - одна з найбожевільніших побудованих досі.
Ерік Аутгольфер

3
@EriktheOutgolfer Божевільний? Ні.
Okx

Я думаю, ви маєте ddddна увазі перший елемент масиву на стеку в поясненні після того, як буде виконано "enclose".
Esolanging Fruit

Вуха, почекай хвилинку, що за чорт Ć?
Чарівна урва восьминога

Також 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


6

Аліса , 17 байт

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

Спробуйте в Інтернеті!

Пояснення

/.../
@...\

Це рамка для програм, які працюють повністю в звичайному режимі і по суті є лінійними (можна записати прості петлі, і один використовується в цій програмі, але складніше працювати з інакше розгалуженим контрольним потоком тут). Вказівник вказівки відскакує по діагоналі вгору і вниз по коду зліва направо, потім переміщується на одну клітинку двома дзеркалами в кінці, і рухається назад праворуч ліворуч, виконуючи комірки, які вона пропустила на першій ітерації. Лінеаризована форма (ігнорування дзеркал) тоді в основному виглядає так:

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

Брахілог , 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
Дякую, що ви опублікували це рішення, оскільки це мотивувало мене придумати більш коротке рішення, яке ухиляється від другої програми. Отримано.
2501 р


3

Japt , 8 байт

7 байт коду, +1 для -Pпрапора.

ó¥ ®+Zg

Перевірте це в Інтернеті!

Пояснення

Для цього використовується óвбудований (розділ на фальшивий), який я щойно додав:

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

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?
Esolanging Fruit

@ Challenger5 Так. Довжина пробігу навіть не відслідковується, тому немає можливості переповнювати довжину пробігу.
Нітродон

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

Haskell, 36 байт

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

Приклад використання: f "aab"-> "aaabb". Спробуйте в Інтернеті!

Коли рядок має щонайменше дві символи, прив'яжіть aдо першого знака, bдо другого та cдо решти струни. Після виходу aслідує, aякщо 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

Желе , 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.

Добре зіграний, Деннісе.
Лина монашка

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

Математика, 34 21 байт

Дякуємо Мартіну Ендеру за те, що він знайшов правильний спосіб зробити це в Mathematica, заощадивши 13 байт!

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

Чиста функція, використовуючи масив символів як вхідних, так і вихідних форматів. Splitвідокремлює список на його ряди рівних символів. ##&[#,##]&це функція, яка повертає послідовність аргументів: перший аргумент, який він подається, потім всі аргументи (так повторюється перший, зокрема); це застосовано ( @@@) до кожного підпису Splitсписку.


1
Можливо ##&[#,##]&@@@Split@#&? (Неперевірено.)
Мартін Ендер

1
^ Зараз перевірено. Btw, Gatherнасправді не працює, якщо є кілька запусків одного персонажа (але, на щастя, Splitвсе-таки байт коротший)
Мартін Ендер

(о так, я мав 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, тому я видалив свою. Але чому Matcherі Pattern? Можна String f(String s){return s.replaceAll("((.)\\2*)","$1$2");}
пограти в

@KevinCruijssen виправлено зараз, thx.
Халед.К

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 байт

Два байти були в гольфі завдяки Мартину Ендеру ще до того, як ця відповідь була опублікована. Він могутніший, ніж ви могли собі уявити.

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.
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.