Напишіть програму для еластичності рядків


33

Гарний дієслово там, у заголовку.

Написати програму, яка дала рядок введення, "еластизує" цей рядок і виведе результат. Еластизація рядка виконується наступним чином:

Перший символ відображається один раз. Другий символ відображається двічі. Третій персонаж показаний тричі тощо.

Як бачимо, кількість дублювань певного символу пов'язана з індексом символу на відміну від його попередніх випадків у рядку.

Ви можете розраховувати на отримання лише друкованих символів ASCII. Виходячи з наступного посилання , ці символи мають десяткові значення 32-126.

Приклади:

Why: Whhyyy

SKype: SKKyyyppppeeeee

LobbY: LoobbbbbbbYYYYY (Зверніть увагу, як існує 7 b, оскільки перший b відображається 3 рази, а другий b відображається 4 рази, що становить 7 b).

A and B: A aaannnnddddd BBBBBBB

Найкоротший байт виграє :)


2
Це, здається, не погоджується з "жодна підтримка білого простору не потрібна, окрім символу пробілу". Якщо висновок повинен бути таким же, як вхід? (Два слова з однієї літери?) Також зауважте, у нас є приємне місце під назвою « Пісочниця», де ви можете поставити перед людьми завдання, щоб дати вам відгуки перед публікацією.
FryAmTheEggman

FryAmTheEggman ваше припущення справедливе. @TimmyD Я розумію, де мені було незрозуміло, ви можете в кінцевому підсумку з рядками розділити мої декілька пробілів, як це видно в прикладі, який розмістив FryAmTheEggman.
Маріо Ішак

Я припускаю, що найкоротший код виграє? ;)
Аднан

@Adnan Так, хоча я не впевнений, чи варто відзначити відповідь скороченою програмою як прийняту, оскільки певні мови створені для цілей гольфу на відміну від інших.
Mario Ishac

2
Пов’язано: 1 , 2
Sp3000

Відповіді:


34

Желе , 3 байти

Код:

ĖP€

Пояснення:

Ė     # Enumerate.
 P€   # Product of each.
      # Implicit joining of everything.

Використовує кодування Jelly . Спробуйте в Інтернеті! .


16
Приємно зловживати тим фактом, що Python's *робить множення рядків. Це насправді не задумано, але це працює.
Денніс

1
@Dennis: який *? У цілій відповіді такого немає.
Томас Веллер

10
@Thomas: Jelly написано в Python, і команда Jelly Pобчислює продукт за кадром, використовуючи *оператор Python . Ця публікація зловживає динамічною абстракцією базового коду, який фактично знаходиться в Python, тому виконання команди P(product) на рядку працює так, як очікувалося.
mellamokb

16

J, 4 байти

#~#\

Використання

   f =: #~#\
   f 'Why'
Whhyyy
   f 'SKype'
SKKyyyppppeeeee
   f 'LobbY'
LoobbbbbbbYYYYY
   f 'A and B'
A  aaannnnddddd      BBBBBBB

Пояснення

#~#\  Input: s
  #\  Computes the length of each prefix of s
      This forms the range [1, 2, ..., len(s)]
#~    For each value in the range, copy the character at the
      corresponding index that many times
      Return the created string

12

Brainfuck, 15 байт

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

Досить проста реалізація, зміщуючи простір пам’яті на 1 для кожного вхідного діаграма. Потрібен інтерпретатор, який дає 0 на EOF, і 32-бітні / довільні комірки точності для входів довше 255 знаків.

Спробуйте в Інтернеті! (Примітка: TIO використовує 8-бітні комірки)


1
Крім того, я думаю, що це не працює для рядків довше 255 символів.
Ісмаель Мігель

@IsmaelMiguel Це залежатиме від того, чи має відповідний перекладач цілі довільні точності чи ні (але дійсно для більшості реалізацій це
обмежує значення

Конвенція полягає у використанні 8-біт. Який 1 символ. Але деякі дійсно можуть реалізовуватися з 32-бітовими номерами. Оскільки ви вказуєте, що вам потрібно, щоб EOF дорівнював 0 (це поведінка, що відповідає компілятору / інтерпретатору), слід зазначити, що для рядків довжиною більше 255 символів вам потрібен компілятор / інтерпретатор з 32-бітовими комірками. Я просто хочу, що це слід додати до відповіді, оскільки це також поведінка, що стосується компілятора / перекладача.
Ісмаїл Мігель

1
@IsmaelMiguel Впевнений, зазначав.
Sp3000

8

Java, 158 121 байт

Збережено колосальних 37 байт завдяки Кевіну Крейсейну !

interface a{static void main(String[]A){int b=0,B;for(char c:A[0].toCharArray())for(B=b+++2;--B>0;)System.out.print(c);}}

У якості бонусу ця програма може обробляти всі наявні символи Unicode, включаючи контрольні символи, розташовані в самому кінці базової багатомовної площини .


3
Так, це дуже короткий код Java.
пр.

1
Ви можете скоротити його на 1 байт, замінивши його for(int C=c+1;C>0;C--)наfor(int C=c+2;--C>0;)
Кевін Круїйсен

2
Або навіть коротше ( 121 байт ):interface a{static void main(String[]A){int x=0,i;for(char c:A[0].toCharArray())for(i=x+++2;--i>0;)System.out.print(c);}}
Кевін Круїйсен

Ну просто зробіть це лямбда чи метод
Leaky Nun

2
Нічого собі, використовуючи методи interfaceза замовчуванням public. Це розумно.
Джастін

7

Perl, 16 байт

s/./$&x$+[0]/ge

+1 байт для -pпрапора.

s/./        /    find every character
             g   globally
              e  and replace with the eval'd result of
    $&           the matched string
      x          repeated
       $+[0]     by the index of the character after the match

7

Хаскелл, 29 байт

concat.zipWith replicate[1..]

Приклад використання: concat.zipWith replicate[1..] $ "SKype"-> "SKKyyyppppeeeee".

replicate n cробить n копій c і concatскладає єдиний список із усіх підспісок.


id=<<приємний штрих. :)
sudee

Я просто хотів спробувати це, але призначення f = id=<<zipWith replicate[1..](у файлі) призвело до некрасивої помилки, чи можете ви сказати, що я роблю неправильно?
недолік

Чи не можна було б призначити цю (без назви, правда?) Функцію імені, щоб ми могли використовувати її як функцію? Я маю на увазі, якщо це функція, то (id=<<zipWith replicate[1..] ) "SKype"все-таки має працювати? Інакше я вважав би це фрагментом . Повна програма ви надали дійсно є «SKYPE» жорстко.
flawr

Я б сказав, якщо ви не можете використовувати його як будь-яку іншу функцію, це не функція. Напр. :t, Не розглядають id=<<zipWith replicate[1..]як функцію (вона просто видає помилку), однак (id=<<).zipWith replicate[1..]розглядається як функція. Я б сказав, що перший - це просто фрагмент, який просто працює, якщо ви жорстко кодуєте вхід, а другий, який ви тільки що розміщуєте, - це функція (і :tпогоджується), чи погоджуєтесь ви це?
недолік

ОК здорово! Якщо ви не погоджуєтесь з моїм "визначенням", я думаю, що ми повинні почати мета-повідомлення для очищення цього питання. Тим часом я намагаюсь знайти інших хаскеллійців для їхньої думки з цього приводу, оскільки це лише мій погляд.
недолік

7

CJam, 9 8 7 байт

Завдяки jimmy23013 за збереження 1 байта.

Sl+eee~

Тестуйте це тут.

Пояснення

Використовуючи LobbYприклад:

                                      Stack:
S    e# Push space.                   [" "]
l    e# Read input.                   [" " "LobbY"]
+    e# Append.                       [" LobbY"]
ee   e# Enumerate.                    [[[0 ' ] [1 'L] [2 'o] [3 'b] [4 'b] [5 'Y]]]
e~   e# Run-length decode.            ["LoobbbbbbbYYYYY"]


5

Javascript ES6, 39 байт

x=>x.replace(/./g,(y,i)=>y+y.repeat(i))

Та ж довжина, але веселіше:

x=>x.replace(i=/./g,y=>y.repeat(i=-~i))

Демонстраційний фрагмент:

f= x=>x.replace(/./g,(y,i)=>y+y.repeat(i))
run.onclick=_=>output.textContent=f(input.value)
<input id="input" value="SKype">
<button id="run">Go</button>
<pre id="output"></pre>


Small error, the program does not support spaces, which is required as a submission (check the OP).
Mario Ishac

@MarDev I changed the snippet to use <pre> instead of <div>, that should help.
Neil

1
@Neil Ah, so the result was correctly computed, but the output was rendered incorrectly by the HTML. Forgot that <div> does that.
Mario Ishac

..."and output the result"
spender

1
@spender returning is a valid form of output for functions
cat

4

APL (8)

{⍵/⍨⍳⍴⍵}

I.e.:

      {⍵/⍨⍳⍴⍵} ¨  'Why' 'SKype' 'LobbY'
┌──────┬───────────────┬───────────────┐
│Whhyyy│SKKyyyppppeeeee│LoobbbbbbbYYYYY│
└──────┴───────────────┴───────────────┘

Explanation:

  • ⍴⍵: length of given vector
  • : numbers 1..N
  • ⍵/⍨: replicate each element in N times.

4

MATLAB, 45 bytes

g=@(m)sort(m(m>0));@(s)s(g(hankel(1:nnz(s))))

Explanation: The key is hankel, which produces a Hankel matrix of a given vector. From this matrix, we can extract a vector of indices, which defines which character of the string is at which position in the output. E.g. hankel(1:4) produces following matrix:

 1  2  3  4
 2  3  4  0
 3  4  0  0
 4  0  0  0

From this matrix we can extrac the vector 1,2,2,3,3,3,4,4,4,4,4. This vector allows us to output the first character of the string once, the second one twice e.t.c.


4

NARS2000, 6 chars = 12 bytes

⍳∘⍴/⊙⊢

⍳∘⍴ enumeration of the argument... (indices of its length)
/⊙ replicates the elements of...
the unmodified argument


link to interpreter?
cat

@cat See edit (in header).
Adám

@cat What was your edit?
Adám

Identical to yours down to the character, because I googled it myself and my edit took 10 minutes to submit
cat

Also, in which codepage is this 6 bytes?
cat

3

PowerShell v2+, 36 bytes

-join([char[]]$args[0]|%{"$_"*++$i})

Takes input $args[0], explicitly casts it as a char array, sends that into a loop |%{...}. Each iteration we take the current letter/character "$_" and use the * overloaded operator to concatenate the string pre-incremented $i times. The result of each loop iteration is encapsulated in parens to form an array and then -joined together to form a string. That string is left on the pipeline and output is implicit.

Examples

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 Why
Whhyyy

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 SKype
SKKyyyppppeeeee

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 LobbY
LoobbbbbbbYYYYY

PS C:\Tools\Scripts\golfing> .\elasticize-a-word.ps1 'a b'
a  bbb

3

Brachylog, 13 bytes

:ImC,0:Ie,Cw\

This prints the result to STDOUT.

Explanation

This is a good example of exploiting backtracking to loop.

:ImC            C is the Ith character of the Input
    ,
     0:Ie       Unify an implicit variable with an integer between 0 and I
         ,
          Cw    Write C to STDOUT
            \   False, trigger backtracking. It will go back to 0:Ie and unify the implicit
                variable with another integer, until all integers were used. After that, it
                will backtrack to :ImC and unify I and C with the next character.

3

MATLAB, 23 bytes

@(x)repelem(x,1:nnz(x))

Creates an anonymous function ans that can be called using ans('stringtoelacticize')


What version are you using? Cannot find repelem in my (relatively old) version =(
flawr

1
@flawr repelem was introduced in R2015a
Luis Mendo


3

Perl 6,  22 20  19 bytes

{S:g/(.)/{$0 x$/.to}/}
{S:g[(.)]=$0 x$/.to}
{[~] .comb Zx 1..*}

Explanation:

{          # implicit parameter $_
  [~]      # string concatenate the following list
    .comb  # the NFG characters from $_
    Z[x]   # zip combined using the string repetition operator
    1 .. * # 1 to infinity
}

3

VBA, 75 bytes

Function e(s):For a=1 To Len(s):e=e &String(a,Mid(s,a,1)):Next:End Function

Call as e.g. a user function in a spreadsheet.

=e(A1)

┌─────────┬───────────────┐
│   SKype │SKKyyyppppeeeee│
└─────────┴───────────────┘

It truncates if you feed it its own output a few times :-).


2
Welcome to the site! =)
DJMcMayhem

3

PHP, 68 bytes

<?php foreach(str_split($argv[1])as$i=>$a)echo str_repeat($a,$i+1);

Hi, and welcome to PPCG! Nice first post!
Rɪᴋᴇʀ

You can get it down to 47 bytes: for(;$a=$argv[1][$i++];)echo str_repeat($a,$i);.
insertusernamehere

3

Javascript ES6, 42 41 bytes

s=>[,...s].map((e,i)=>e.repeat(i)).join``

Example runs:

f=s=>[,...s].map((e,i)=>e.repeat(i)).join``

f("Why")   => "Whhyyy"
f("SKype") => "SKKyyyppppeeeee"
f("LobbY") => "LoobbbbbbbYYYYY"

Same length: s=>[...s].reduce((a,b,i)=>a+b.repeat(i+1))
Bassdrop Cumberwubwubwub

2
-1 byte: s=>[,...s].map((e,i)=>e.repeat(i)).join``
nderscore

@nderscore Aha, thats clever, thanks!
Dendrobium

3

Retina, 22 bytes

Byte count assumes ISO 8859-1 encoding.

.
$&$.`$*·
+`(.)·
$1$1

Try it online!

Basically, we insert the right amount of · as placeholders between the characters (since these extended ASCII characters can't appear in the input), then fill them up with the adjacent character in the second stage.


3

R, 83 50 bytes

-23 Thanks to Giuseppe, though he used essentially an entire new method altogether

function(s)intToUtf8(rep(utf8ToInt(s),1:nchar(s)))

My original post:

function(s){r="";for(i in 1:nchar(s))r=paste0(r,strrep(el(strsplit(s,""))[i],i));r}

Try it online!

I feel like there's definitely a better way to do this, but with my new knowledge of a few functions in R, this is my approach.


1
Not a golfing tip, but your code link output was messed up. Here
Robert S.

Ah, I see. I'm new to TIO, so I didn't quite understand the header/footer portions. Thank You!
Sumner18


1
Very nice! However, using rep and the argument collapse="" to paste is shorter, and utf8ToInt is shorter still! TIO
Giuseppe

2

Actually, 7 bytes

' +ñ♂πΣ

Try it online!

Explanation:

' +ñ♂πΣ
' +      prepend a space
   ñ     enumerate ("abc" -> [[0, 'a'], [1, 'b'], [2, 'c']])
    ♂π   map: for each character, repeat it n times
      Σ  concatenate


2

Python 3, 48 47 bytes

Thanks to mego for saving a byte with the -~i trick.

lambda s:''.join(c*-~i for i,c in enumerate(s))

This is mostly self-explanatory. One thing for those not versed in Python: The * operator is overloaded to act like Perl's x operator, repeating its string argument the number of times specified by its numeric argument. E.g. 'foo' * 3 == 'foofoofoo'


c*-~i is shorter than c*(i+1).
Mego

2

C#, 81 Bytes

void f(string s){for(int i=0;i<s.Length;i++)Console.Write(new String(s[i],i+1));}

you can save 1 byte by changing to a foreach loop, e.g. foreach(var a in s)Console.Write(new C(a,1*i++));
Abbath

but if its a foreach we don't have the i variable so you'd need to declare it.
ScifiDeath

It seems you're missing a using System or a System. in front of the Console.
Martin Ender

@ScifiDeath That's true - but the end result is still one byte shorter. Sorry for omitting it and causing confusion int i=1;
Abbath

Also one byte shorter using Linq: void f(string s){s.Select((c,i)=>{Console.Write(new string(c,i+1));return c;});}. The need for a (unused) return value is ugly though. Edit: just found similar snippets in other answers further back.
linac

2

MATL, 5 bytes

tn:Y"

Try it Online

Explanation

    % Implictly grab input as a string
tn  % Duplicate and compute the length (N)
:   % Create an array from [1...N]
Y"  % Perform run-length decoding to elacticize the string
    % Implicitly display the result


2

Julia, 34 bytes

!s=s>""?!s[1:(e=end)-1]*s[e:e]^e:s

Try it online!


Your solution was good. But I managed to beat it.
Glen O

I saw. I had c%n="$c"^n;~s=join([s[r=1:end]...].%r), but that's actually longer. split was the missing piece of the puzzle.
Dennis

2

TSQL, 97 bytes

Golfed:

DECLARE @x varchar(max)='Lobby'
DECLARE @ int=LEN(@x)WHILE @>0SELECT
@x=STUFF(@x,@,1,REPLICATE(SUBSTRING(@x,@,1),@)),@-=1PRINT @x

Ungolfed:

DECLARE @x varchar(max)='Lobby'

DECLARE @ int=LEN(@x)
WHILE @>0
  SELECT 
    @x=STUFF(@x,@,1,REPLICATE(SUBSTRING(@x,@,1),@)),
    @-=1

PRINT @x

Try it online

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