文字列に数字を掛けます!


34

少し前に、文字列の乗算に関する課題がありました。数値だけでなく文字列も乗算できる方法を示しました。ただし、数字に文字列を適切に掛けることはできません。そうする試みが1つありましたが、これは明らかに間違っています。修正する必要があります!

あなたのタスク:

文字列と整数の2つの入力を乗算する関数またはプログラムを作成します。文字列に整数を(適切に)乗算するには、文字列を文字に分割し、各文字を整数に等しい回数繰り返してから、文字を元に戻します。整数が負の場合、最初のステップでその絶対値を使用し、文字列を逆にします。入力が0の場合、何も出力しません(0を掛けたものは何も等しくありません)。

入力:

印刷可能なASCII文字と改行のみで構成される文字列、および整数(負の可能性あり)。

出力:

文字列に整数を掛けたもの。

例:

Hello World!, 3            --> HHHeeellllllooo   WWWooorrrlllddd!!!
foo, 12                    --> ffffffffffffoooooooooooooooooooooooo
String, -3                 --> gggnnniiirrrtttSSS
This is a fun challenge, 0 --> 
Hello
World!, 2                  --> HHeelllloo

                               WWoorrlldd!!

得点:

これは、最低バイト数が勝ちです!


4
文字列はASCIIのみで印刷可能であり、改行も可能であると想定できますか?
— mbomb007

文字列のリストを出力できますか?
— 完全に人間

Retinaの部分的なソリューション。整数の正の値に対してのみ機能します。誰かが望んでいるなら、私はおそらくそれを終える時間を作らないでしょう。tio.run/##K0otycxL/P8/...
— mbomb007

@ mbomb007、はい、それについて長い間ごめんなさい。
— グリフォン-モニカの復活

@totallyhuman、いいえ。
— グリフォン-モニカの復活

回答:


31

ゼリー、6 5 4バイト

²Ɠxm

オンラインでお試しください!

使い方

²Ɠxm  Main link. Argument: n (integer)

²     Yield n².
 Ɠ    Read and eval one line of input. This yields a string s.
  x   Repeat the characters of s in-place, each one n² times.
   m  Takes each |n|-th character of the result, starting with the first if n > 0, 
      the last if n < 0.

1
OK、今、私は本当に感銘を受けました。この特定の不思議をミニチュアで説明したいと思います。
— グリフォン-モニカの復活

確かに。テストスイートを作成し、ゴルフが終了するとすぐに。
— デニス

4
OK、これをもっと小さくできるなら、10バイト以上かかる質問をしようとするのをあきらめます。
— グリフォン-モニカの復活

13
OK、それだけです。私はゼリーを学んでいます。魔法もできるようになりたい。
— グリフォン-モニカの復活

2
我々ゼリーチェーンについての議論が混乱されて終わる方法をすべて知っている...
— エリックOutgolfer

9

JavaScript(ES6)、63バイト

カリー化構文で入力を受け取り(s)(n)。

s=>n=>[...s].reduce((s,c)=>n<0?c.repeat(-n)+s:s+c.repeat(n),'')

テストケース


3
+1のためのreduce!
— ニール



6

05AB1E、10バイト

S²Ä×J²0‹iR

オンラインでお試しください!

S          # Split the string into characters
 ²Ä×       # Repeat each character abs(integer) times
    J      # Join into a string
     ²0‹i  # If the integer is less than 0...
         R #   Reverse the string

TFW ²0‹iは、@ Riley に最良のルートではないことを証明し、文字通り0の代替案を考え出すために30分を費やします。
— 魔法のタコUr

@MagicOctopusUrn私は²0‹i以前のようなものを使用しましたが、もっと良いものが必要だといつも思っています。
— ライリー

私は今、約10倍の選択肢を見つけようとしていると思います。私の人生の累積3時間を無駄にしています。Ä.D)øJ¹0‹iRあなたをコピーせずにできることは最高です、あなたのものは最適化されていると思います。
— 魔法のタコUr

気にするなら、エミグナはè ここで使用しましたが、このシナリオでそれを適用する方法を見つけることはできません。その場合、最大1バイトを保存します。
— 魔法のタコUr

SÂΛ@²Ä×J、Î順序を変更すると0をプッシュして入力が機能します。1バイト節約!(ifも置き換えるため、閉じる必要はありません)
— -kalsowerus

5

MATL、9バイト

y|Y"w0<?P

入力は、数値、次に文字列です。

改行を含む文字列は10、次のようにchar を使用して入力されます['first line' 10 'second line']。

オンラインでお試しください!または、すべてのテストケースを確認します。

説明

入力-3とを検討してください'String'。

y      % Implicitly take two inputs. Duplicate from below
       % STACK: -3, 'String', -3
|      % Absolute value
       % STACK: -3, 'String', 3
Y"     % Run-length decoding
       % STACK: -3, 'SSStttrrriiinnnggg'
w      % Swap
       % STACK: 'SSStttrrriiinnnggg', -3
0<     % Less than 0?
       % STACK: 'SSStttrrriiinnnggg', 1
?      % If so
  P    %   Flip
       %   STACK: 'gggnnniiirrrtttSSS'
       % End (implicit). Display (implicit)


5

V、29、23、18、17のバイト

æ_ñÀuñÓ./&ò
ÀäëÍî

オンラインでお試しください!

Hexdump:

00000000: e65f f1c0 75f1 d32e 2f26 f20a c0e4 ebcd  ._..u.../&......
00000010: ee                                       .

6バイトを保存してくれた@ nmjcman101に感謝します。

元の改訂版はかなりひどいものでしたが、負の数を驚くほどうまく処理できるので、この回答を本当に誇りに思います。(Vはほとんど数値的サポートも負数もサポートしていません)

説明:

æ_          " Reverse the input
  ñ  ñ      " In a macro:
   À        "   Run the arg input. If it's positive it'll give a count. If it's negative
            "   running the '-' will cause V to go up a line which will fail since we're
            "   on the first line, which will break out of this macro
    u       "   (if arg is positive) Undo the last command (un-reverse the line)
      Ó./&ò " Put every character on it's own line

この時点で、バッファーは次のようになります。

H
e
l
l
o

w
o
r
l
d
!
<cursor>

末尾の改行ではなく、カーソルがその上にあることが重要です。

À           " Run arg again. If it's negative, we will move up a line, and then give the 
            " absolute value of the count. If it's positive (or 0) it'll just give the
            " count directly (staying on the last line)
 ä          " Duplicate... (count times)
  ë         "   This column. 
   Íî       " Remove all newlines.

yaのための数バイトオンラインで試してみてください! 私はいつも「負の数は何か他のものを意味する!」が嫌いです。エッジケースも。これは、0Vの特別なケースが非常に便利なケースです。
— nmjcman101

特別な負の数については申し訳ありません。しかし、多くの回答がそれをメインの回答に組み込むことができました。ただし、このVには印象的です。
— グリフォン-モニカの復活

@ nmjcman101ああすごい、それはとても明白です、私はそれをどう考えなかったのかわかりません。ありがとうございました!
— DJMcMayhem

@グリフォンああ、わかった。挑戦は結構です。私は自分の言語が苦手だと思うので、自分の言語が嫌いです。:P
— DJMcMayhem

5

R、83 78 76バイト

function(s,i)cat('if'(i<0,rev,`(`)(rep(el(strsplit(s,'')),e=abs(i))),sep='')

匿名関数。

フレデリックは3バイトを節約し、ジュゼッペは2バイトを節約しました 4。

説明:

     el(strsplit(s,''))                      # split string into list characters
 rep(                  ,e=abs(i)))           # repeat each character abs(i) times


    'if'(i<0,rev,   ){...}                 # if i>0, reverse character list
                 `(`                       # otherwise leave it alone: `(` is the identity function
cat(                      ,sep='')         # print the result

テスト:

> f('Hello World!', 3 )
HHHeeellllllooo   WWWooorrrlllddd!!!
> f('foo', 12)
ffffffffffffoooooooooooooooooooooooo
> f('String', -3)
gggnnniiirrrtttSSS
> f('This is a fun challenge', 0)
> f('Hello
+ World!', 2)
HHeelllloo

WWoorrlldd!!

2
よくやった !書くrep(foo,,,3)かrep(foo,e=3)(同じ長さ)で数バイト節約できます;-)
— フレデリック

@Frédéricあなたは私にそれを打ち負かした、私は同じことを言うつもりだった!
— ジュゼッペ

1
ええ、問題ありません!基本的に、ブレースを削除したかったので、削除する必要がありましたa=。したがって、条件付きで関数を返すことによりa、逆関数ifの引数としての値を使用しましたi<0(これが逆引用符を必要とした理由です)。しかし、私はi>=0ケースに恒等関数も適用する必要があったので、(どちらを使用するかは十分に近いものでした。(実際には関数です。Rは変です。
— ジュゼッペ

1
ところで、ParenのRドキュメント(は、意味的にアイデンティティと同等であると言いますfunction(x)x
— ジュゼッペ




4

Brain-Flak(BrainHack)、154 152バイト

([(({})(<()>))]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<>({}<([][()]){{}({<({}<(({}<>)<>)>())>[()]}<{}{}>)([][()])}{}{}<>>){{}{({}<>)<>}(<>)}{}

オンラインでお試しください!

DJMcMayhemにいくつかの競争を与えるためだけにここに。;)

説明

DJMcMayhemの説明の修正版を以下に示します

#Compute the sign and negative absolute value 
([(({})<(())>)]<>)<>{({}()<([{}]()<([{}])>)<>({}<>)<>>)<>}{}<>{}<>

#Keep track of the sign
({}<

    #For each char in the input string:
    ([][()])
    {
        {}

        #Push n copies to the alternate stack
        ({<({}<(({}<>)<>)>())>[()]}<{}{}>)

        #Endwhile
        ([][()])
    }{}{}<>

#Push the sign back on
>)

#If so...
{{}

    #Reverse the whole stack
    {({}<>)<>}

    #And toggle over, ending the loop
    (<>)
}

#Pop the counter off
{}

4

J、19 15 13バイト

(#~|)A.~0-@>]

オンラインでお試しください!

説明

        0-@>]      NB. first or last index depending on sign of right arg
     A.~           NB. get first or last Anagram of left arg
(#~|)              NB. copy left arg, absolute-value-of-right-arg times

2
(#~|)A.~0-@>]13バイト
— マイル

とてもいい@miles!
— -Tikkanz

問題ない。また、動詞の呼び出しに使用される括弧を数える必要もありません。
— マイル

1
また13バイト:#~ ::(|.@#~|)
— FrownyFrog

3

Dyalog APL、15バイト

{⌽⍣(⍵<0)⊢⍺/⍨|⍵}

左引数としての文字列、右引数としての数値。

オンラインでお試しください!

どうやって?

⍺/⍨ -文字列を繰り返します

|⍵ -abs(number)回

⌽⍣ -逆の場合

(⍵<0) -数値は0未満です


ええと、TIOがうまくいったらいいですね。
— グリフォン-モニカの復活

@Gryphonそしてここにバイト
— Uriel

うん、私はちょうどそれに気づいたとあなたに伝えるために私のコメントを入力していた。
— グリフォン-モニカの復活

3

MATLAB、37バイト

@(s,n)flip(repelem(s,abs(n)),(n<0)+1)

これは、入力s:stringおよびn:numberを持つ無名関数を定義します。

実行例:

>> @(s,n)flip(repelem(s,abs(n)),(n<0)+1)
ans = 
    @(s,n)flip(repelem(s,abs(n)),(n<0)+1)

>> f = ans;

>> f('String', 3)
ans =
SSStttrrriiinnnggg

>> f('String', -3)
ans =
gggnnniiirrrtttSSS

>> f('String', 0)
ans =
   Empty matrix: 1-by-0

反転させる次元を選択することは、私が😛+1を書いた混乱よりもはるかに優れていました。そして、私は常にrepelem存在することを忘れます。
— スティーヴィーグリフィン

@StewieGriffinまあ、あなたもあなたの答えにそれを取り入れることができます:-)(すでに+1)。repelem今のところオクターブにはないだろうと思う
— ルイス・メンドー

3

Brain-Flak(Haskell)、202 192バイト

(({})<(([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>)([][()]){{}({<({}<(({}<>)<>)>[()])>()}<{}{}>)([][()])}{}{}<>>)([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}{{}{({}<>)<>}(<>)}{}

オンラインでお試しください!

これはおそらくそれを実行するのに最悪の可能性のある言語ですが、完了しています。混合入力形式を許可するHaskellインタープリターを提供してくれた@Wheatwizardに感謝します。これがないと、約150バイト長くなります。

説明:

#Keep track of the first input (n)
(({})<

    #Push abs(n) (thanks WheatWizard!)
    (([({})]<>)){({}()<([{}])<>({}<>)<>>)<>}{}([{}]<><{}>)

    #For each char in the input string:
    ([][()])
    {
        {}

        #Push n copies to the alternate stack
        ({<({}<(({}<>)<>)>[()])>()}<{}{}>)

        #Endwhile
        ([][()])
    }{}{}<>

#Push the original n back on
>)

#Push n >= 0
([({}<(())>)](<>)){({}())<>}{}{((<{}>))<>{}}{}<>{}

#If so...
{{}

    #Reverse the whole stack
    {({}<>)<>}

    #And toggle over, ending the loop
    (<>)
}

#Pop the counter off
{}

52バイトのabsを使用して2バイトを節約できます。また、50バイトの-absを使用して、6バイトを節約するために減分する代わりに増分することもできます。
— 小麦ウィザード


3

Java(OpenJDK 8)、99 98 89 87 85 bytes

s->n->{for(int i=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);}

Try it online!

  • -2 bytes thanks to @Xanderhall
  • @Nevayのおかげで-2バイト

Ideas that don't work (way longer): reverse the string before, use a stream,
— Olivier Grégoire

1
Save 2 bytes with s[(n<0?-l-~i:i)/n]
— Xanderhall

@Xanderhall Thanks! I've been looking for that one for so long my eyes bleed. I knew it was possible, I just messed everything up when implementing it.
— Olivier Grégoire

1
@user902383 Yes, it's mandatory. If they were optional, a lot of things would be unreadable. Also, my function is not a "single statement", but a for-loop, which encompass several statements.
— Olivier Grégoire

1
You can save 1 byte by incrementing i in the condition s->n->{for(int l=s.length*(n<0?-n:n),i=0;i++<l;)System.out.print(s[(n<0?i-l:i-1)/n]);}. Another byte can be saved by iterating from -l to 0 instead (s->n->{for(int i=s.length*(n<0?n:-n),r=n<0?0:~i;i++<0;)System.out.print(s[(i+r)/n]);}).
— Nevay



2

Charcoal, 16 bytes

Fθ¿‹η0F±Iη←ιFIηι

Try it online! Link is to verbose version of code. Explanation:

Fθ              For each character in the input string
  ¿‹η0          If the input number is less than zero
      F±Iη      Repeat the negation of the input number times
          ←ι    Print the character leftwards (i.e. reversed)
      FIη       Otherwise repeat the input number times
         ι      Print the character


2

Japt, 12 bytes

®pVaìr!+sVg

Try it online!

Explanation

Implicit input of string U and integer V.

®pVaÃ

Map (®) each letter of U (implicitly) to itself repeated (p) abs(V) (Va) times.

¬r

Turn the string into an array of chars (¬) and reduce (r) that with...

!+sVg

"!+".slice(sign(V)) - this either reduces with + → a + b, or with !+ → b + a.
Thanks @Arnauld for the backwards-reduce idea!


I feel like £gY*Vg)pVa should lead to a shorter solution but my brain has shut down for the holidays so I can't quite figure it out. You may be able to do something with it, though.
— Shaggy

2

WendyScript, 46 bytes

<<f=>(s,x){<<n=""#i:s#j:0->x?x>0n+=i:n=i+n/>n}

f("Hello World", -2) // returns ddllrrooWW  oolllleeHH

Try it online!

Explanation (Ungolfed):

let f => (s, x) {
  let n = ""
  for i : s
    for j : 0->x
      if x > 0 n += i
      else n = i + n
  ret n
}

2

C89 bytes

main(int c,char**v){for(;*v[1];v[1]++)for(c=atoi(v[2]+(*v[2]=='-'));c--;)putchar(*v[1]);}

I saw Ben Perlin's version and wondered if you couldn't be shorter still and also have a full program; surely, atoi() and putchar() aren't that expensive in terms of bytes? Seems I was right!


2

Pyth, 13 11 bytes

*sm*.aQdz._

Try it!

-2 bytes thanks to @jacoblaw

explanation

*sm*.aQdz._   
  m     z     # map onto the input string (lambda var: d)
   *.aQd      # repeat the char d as often as the absolute value of the input number 
 s            # sum the list of strings into a single string
*        ._Q   # Multiply with the sign of the implicit input value: reverse for negative Q 

old approach, 13 bytes

_W<Q0sm*.aQdz

Try it!


you can save two bytes with this reversal logic
— jacoblaw

2

Python 3, 68 bytes

h=lambda s,n:h(s[::-1],-n)if n<0 else s[0]*n+h(s[1:],n)if s else s*n

Try it online!


Hello, and welcome to the site! Unfortunately, this answer is invalid right now, since it doesn't support Negative numbers. The challenge says: If the integer is negative, we use its absolute value in the first step, and then reverse the string.
— DJMcMayhem

Thanks for fixing it! BTW, you could take two bytes off by removing the spaces after parenthesis )
— DJMcMayhem

Edited, thanks for the contribution
— Kavi

n<0 else => n<0else
— Zacharý

1

QBIC, 32 bytes

g=sgn(c)[_l;||[:*g|?_sA,b*g,1|';

Explanation

            Takes inputs A$ ('Hello'), and c (-3) from the cmd line
g=sgn(c)    Save the sign of c          -1
[_l;||      FOR each char in A$
[:*g|       FOR the number of repetitions wanted    (ie: -3 * -1)
            Note that : reads a number from the cmd line, and c is the first 
            available variable to save it in after a and b got used as FOR counters.
            Also note that a negative value times the sign becomes positive.
?_s         PRINT a substring
  A         of A$
 ,b*g       startng at char n, where n is the first FOR loop counter times the sign
                That means that when c is negative, so is this. A negative starting index
                on Substring instructs QBIC to take from the right.
 ,1|        taking 1 char.
';          This bit injects a literal ; in the output QBasic, to suppress newlines om PRINT

1

Mathematica, 89 bytes

(T=Table;t=""<>T[s[[i]]~T~Abs@#2,{i,Length[s=Characters@#]}];If[#2>0,t,StringReverse@t])&


input

["Hello World!", 3]



1

C, 109 bytes

char *f(int n, char *s){char *o=calloc(n,strlen(s)+1),*t=o;while(*s){for(int i=n;i--;)*t++=*s;s++;}return o;}

Starting with a function declaration that takes an int and a string and produces a string (it seems implied that memory is not preallocated and must be created) it seems that the straight-forward approach is shorter than any attempts at being cleaver that I had tried.

char *f(int n, char *s){
  char *o=calloc(n, strlen(s)+1),
    *t=o;

  while (*s) {
    for(int i=n; i--; )
      *t++=*s;
    s++;
  }

 return o;

}


This does not seem to work for negative n.
— gastropner
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.