12
\$\begingroup\$

Help! My device malfunctions and whenever I try to repeat a String, I get a messy results. Instead of repeating the same string N times, it fills an NxN square with each of its characters, and stacks the squares up.

For example, given the String "Test" and the number 2, instead of "TestTest", I get:

TT
TT
ee
ee
ss
ss
tt
tt

After I have seen this for a while, I started to like it. Your task today is to reproduce this strange behaviour. Given a non-empty string that consists of printable ASCII only, and a positive integer, output the String my malfunctioning device returns.

  • All standard rules apply.

  • The input and output may be handled through any reasonable mean.

  • This is , so the shortest code in bytes in each language wins.


Test Cases

Input 
Output

----------

"Test", 2

TT
TT
ee
ee
ss
ss
tt
tt

----------

"UuU", 3

UUU
UUU
UUU
uuu
uuu
uuu
UUU
UUU
UUU

----------

"A", 5

AAAAA
AAAAA
AAAAA
AAAAA
AAAAA

----------

You can find a larger test case here. Good luck and have fun golfing!

\$\endgroup\$
  • \$\begingroup\$ Borderline duplicate of Enlarge ASCII art \$\endgroup\$ – Digital Trauma Sep 5 '17 at 19:52
  • 1
    \$\begingroup\$ Is a "list of lines" instead of a string separated by newlines valid? \$\endgroup\$ – geokavel Sep 5 '17 at 20:04
  • 21
    \$\begingroup\$ Hmm, I don't see how the "abuse its undefined behavior" from the title actually shows in the task. There is no undefined behavior, the task is to reproduce a quite specifically defined behavior. \$\endgroup\$ – Paŭlo Ebermann Sep 5 '17 at 21:24
  • 3
    \$\begingroup\$ it fills an NxN square - Not a correct statement. \$\endgroup\$ – Magic Octopus Urn Sep 6 '17 at 19:30

34 Answers 34

9
\$\begingroup\$

Jelly, 4 bytes

Inspired by Mr. Xcoder's Jelly abuse

x⁹×Y

A full program taking the string and the number as command line arguments and printing the result (since as a dyadic link it returns a list of strings and newline characters, which may not really be acceptable).

Try it online!

How?

The naive (non-abusive) five byter is:

x⁹x€Y - Main link: list of characters, s; number, n  e.g. "xyz", 2
 ⁹    - chain's right argument, n                         2
x     - times (repeat each element)                       ['x','x','y','y','z','z']
  x€  - times for €ach                                   [['x','x'],['x','x'],['y','y'],['y','y'],['z','z'],['z','z']]
    Y - join with newlines                                ['x','x','\n','x','x','\n','y','y','\n','y','y','\n','z','z','\n','z','z']
      - as a full program: implicit print
      -   note: this could be submitted as a dyadic link (AKA unnamed function)

The abuse used by Mr. Xcoder (Python's operator.mul may act on a str and an int to repeat the str - here single characters - and the atom which uses it, ×, vectorises w.r.t. its left argument) can be used here too to replace x€ with × - yielding the full program:

x⁹×Y - Main link: list of characters, s; number, n  e.g. "xyz", 2
 ⁹   - chain's right argument, n                         2
x    - times (repeat each element)                       ['x','x','y','y','z','z']
  ×  - multiply (vectorises)                             ["xx","xx","yy","yy","zz","zz"]
     -     (note, these "..." are actually strings, something not usually seen in Jelly) 
    Y - join with newlines                                ["xx",'\n',"xx",'\n',"yy",'\n',"yy",'\n',"zz",'\n',"zz"]
      - implicit print
\$\endgroup\$
  • \$\begingroup\$ heh abuse on challenge about abuse \$\endgroup\$ – Erik the Outgolfer Sep 6 '17 at 7:54
9
\$\begingroup\$

Jelly, 5 bytes

This is exactly what we are asked to do... Abuse undefined behaviour!*

×+⁷×⁴

Try it online!

* By undefined behaviour I am talking about using × for repeating strings. Sometimes it's shorter than usual behaviour, so why not?

\$\endgroup\$
5
\$\begingroup\$

Haskell, 26 bytes

The function (!) returns a list of lines.

n!s=map(<$[1..n])s<*[1..n]

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Bash + GNU Sed, 58

Using a very similar technique to this answer to illustrate how close to being a dup to this that this question is:

printf -vr %$1s
sed "s/./${r// /&}\n/g;s/\S*./${r// /&}/g"

Try it online.

\$\endgroup\$
4
\$\begingroup\$

Husk, 5 4 bytes

-1 byte thanks to @Zgarb

SṀRṘ

Try it online!

\$\endgroup\$
  • \$\begingroup\$ ṠMRṘ works if you swap the inputs. \$\endgroup\$ – Zgarb Sep 5 '17 at 19:17
3
\$\begingroup\$

PowerShell, 31 bytes

param($a,$b)$a|%{,("$_"*$b)*$b}

Try it online!

Explanation:

param($a,$b)                    # Takes input $a (char-array) and $b (integer)
            $a|%{             } # Loop through every character in $a
                   "$_"*$b      # Construct a string of $b length of that character
                 ,(       )*$b  # Repeat that $b times
                                # Implicit Write-Output inserts a newline between elements
\$\endgroup\$
3
\$\begingroup\$

05AB1E, 7 5 bytes

-2 bytes thanks to scottinet

εײF=

Try it online!

ε     # For each character:
 ×    #   Repeat this character N times
  ²F  #   For 0 .. N:
    = #     Print without popping 
\$\endgroup\$
  • \$\begingroup\$ -2 bytes by taking advantage of implicit inputs, printing without popping (=) and by replacing vywith ε : Try it online! \$\endgroup\$ – scottinet Sep 5 '17 at 19:30
2
\$\begingroup\$

Python 3, 42 bytes

lambda x,y:"".join(y*(r*y+"\n")for r in x)

Try it online!

\$\endgroup\$
2
\$\begingroup\$

MATL, 5 bytes

t&Y"!

Try it online!

Explanation

t     % Implicitly input a number, n. Duplicate
&Y"   % Implicitly input a string. Three-input repelem function. Repeats
      % each entry in the first input (s) the specified numbers of times 
      % vertically (n) and horizontally (n). Gives a char matrix
!     % Transpose. Implicit display
\$\endgroup\$
2
\$\begingroup\$

C++, 125 123 bytes

-2 bytes thanks to aschepler

#include<string>
using s=std::string;s u(s a,int b){s r;for(auto&c:a)for(int i=0;i<b*b;){if(!(i++%b))r+=10;r+=c;}return r;}

Make sure that the overload of the += operator called takes a char data type in this instruction if(!(i++%b))r+=10

\$\endgroup\$
  • 2
    \$\begingroup\$ using s=std::string; is shorter than typedef std::string s; by two bytes. \$\endgroup\$ – aschepler Sep 5 '17 at 23:02
2
\$\begingroup\$

Japt, 7 bytes

Outputs an array of strings.

VÆmpVÃy

Try it (-R flag for visualisation purposes only)


Explanation

Implicit input of string U and integer V.

VÆ    Ã

Generate an array of integers from 0 to V-1 and pass each through a function.

mpV

Map (m) over U and repeat (r) each character V times.

y

Transpose and implicitly output resulting array.

\$\endgroup\$
1
\$\begingroup\$

R, 59 bytes

function(S,n)write(rep(strsplit(S,"")[[1]],e=n*n),"",n,,"")

Writes to stdout.

Splits the string into characters, repeats each n^2 times, and then prints with width n and with no separator.

Try it online!

\$\endgroup\$
1
\$\begingroup\$

J, 15 14 bytes

[:,/]$"1 0~[,[

Sub-optimal for sure. Returns a 2D array of chars. Takes n as the left argument and the string as the right.

On mobile, so the usual amenities are missing.

Explanation

(For old answer)

[:,/(2#[)$"1 0]

$"1 0 reshape each character to

(2#[) an n * n matrix.

,/ join matrices together to yield the output.

\$\endgroup\$
  • 2
    \$\begingroup\$ 5 bytes \$\endgroup\$ – miles Sep 6 '17 at 4:06
  • \$\begingroup\$ @miles brilliant! I'd say that deserves its own answer personally. \$\endgroup\$ – cole Sep 6 '17 at 5:53
  • \$\begingroup\$ @miles post yours :) \$\endgroup\$ – Ven Sep 6 '17 at 15:51
1
\$\begingroup\$

Perl 5, 26 + 1 (-p) = 27 bytes

$"=<>;s|.|($&x$".$/)x$"|ge

Try it online!

\$\endgroup\$
  • \$\begingroup\$ This seems to replace each character with a horizontal row of characters, not with a square of characters. \$\endgroup\$ – aschepler Sep 5 '17 at 23:05
  • \$\begingroup\$ I guess I didn't understand it properly at first. Fixed it with an extra 5 bytes. \$\endgroup\$ – Xcali Sep 6 '17 at 1:47
1
\$\begingroup\$

Pyth, 9 bytes

VEp*+*NQb

Try it here!

Pyth, 11 10 bytes

sm*Q+*QdbE

Try it here!

Or, 10 bytes:

jsm*Q]*QdE

Or, 11 bytes:

js*RQm]*dQE
jsm*vzm*dvz
sm*vz+*dvzb
\$\endgroup\$
1
\$\begingroup\$

Charcoal, 9 bytes

FS«GTIηι↓

Try it online!

Explanation

FS         For each character (i) in the next input as a string
   «
    G    ι  Polygon using i as fill
      T      Right, down, then left
       Iη   The second input (h) casted (to a number)
           ↓ Move down
\$\endgroup\$
1
\$\begingroup\$

Brainfuck, 103 Bytes

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

Try it online (Make sure to turn on dynamic memory or it won't run)

Note: The input is slightly different. This code takes in a string where the last character is a digit for number of repeats. So input might look like Test5.

This code requires an unbounded tape, and relies on byte wrapping behavior.

Ungolfed:

,[>,]< Take Input
>-[>+<-----]>--- ASCII 0, to use in next step
[-<<->>]<< Convert ASCII number to raw number by subtracting ASCII 0
[->+<]> Move the number over one to separate it from the phrase
[
  [->+>+<<]>>[-<<+>>]< Copy the number
  [
    <<<[<]> Back to Letter
    . Print Letter
    [>]>>- Back to Counter
  ]
  ++++++++++.[-]< Print the newline
  <<[<]>[-]> Clear Letter
  [>]> Back to Counter
]
\$\endgroup\$
1
\$\begingroup\$

SOGLOnline commit 2940dbe, 4 bytes

∙ι*I

This was made for a specific commit, namely the one before I changed from, when used on an array of strings, repeating each letter x times to repeat each item x times. Here is the online interpreter without that version, which, as can be seen, doesn't work.

To try the commit, download this, open the index.html file, in the program paste ∙ι*I and in the input write something like

Test
2

Explanation:

∙ι*I
∙     get an array with 2nd input amount of items of the 1st input
 ι    pop one implicit input to cycle back to the number
  *   multiply horizontally each separate character
   I  rotate clockwise
\$\endgroup\$
  • \$\begingroup\$ If it doesn't work, why the link? \$\endgroup\$ – isaacg Sep 6 '17 at 4:40
  • \$\begingroup\$ @isaacg good question. First I intended it to write what changed, but forgot \$\endgroup\$ – dzaima Sep 6 '17 at 18:50
1
\$\begingroup\$

Java 8, 152 128 118 100 bytes

s->n->{for(char c:s)for(int j=0;j++<n;System.out.println("".valueOf(new char[n]).replace('\0',c)));}

Try it online!

\$\endgroup\$
  • 2
    \$\begingroup\$ 100 bytes: s->n->{for(char c:s)for(int j=0;j++<n;System.out.println("".valueOf(new char[n]).replace('\0',c)));} \$\endgroup\$ – Nevay Sep 6 '17 at 20:13
1
\$\begingroup\$

APL (Dyalog), 8 bytes

Takes repetition as left argument and text as right argument.

{⍺⌿⍺/⍪⍵}

Try it online!

{} an unnamed lambda where represents the left argument and the right argument

⍪⍵ make the text into a one-column table

⍺/ replicate times horizontally

⍺⌿ replicate times vertically

\$\endgroup\$
1
\$\begingroup\$

Japt, 7 bytes

mpV² òV

Returns an array of strings.

Try it online! with the -R flag to join the array with newlines.

Explanation

mpV² òV     Implicit input of U=string, V=number
m           Map each char in the input string to...
 pV²        Itself repeated V² times
     òV     Cut the resulting string into partitions of length V
\$\endgroup\$
1
\$\begingroup\$

D, 86 bytes

S u(S,I)(S a,I b){S r;foreach(c;a)for(I i;i<b*b;){if(!(i++%b))r~='\n';r~=c;}return r;}

Try it online!

Takes the string as the left argument, and the integer as the right argument. This is a port of HatsuPointerKun's C++ answer into D.

\$\endgroup\$
0
\$\begingroup\$

C (gcc), 83 79 bytes

i,j;f(p,n)char*p,n;{for(;*p;p++)for(i=n;i--;puts(""))for(j=n;j--;putchar(*p));}

Try it online!

\$\endgroup\$
0
\$\begingroup\$

CJam, 11 Bytes

{__*@e*/N*}

Function that takes string followed by int.

Try it Online

\$\endgroup\$
0
\$\begingroup\$

Kotlin 1.1 - 99 bytes

fun s(s:String,c:Int)=s.flatMap{p->List(c,{p})}.joinToString("\n"){p->List(c,{p}).joinToString("")}

Returns the whole output as a string.

Can't use TryItOnline as 1.1 is not supported

Test

fun s(s:String,c:Int)=s.flatMap{p->List(c,{p})}.joinToString("\n"){p->List(c,{p}).joinToString("")}

fun main(args: Array<String>) {
    println(s("Hello World", 5))
}

It would be 84 if a list of strings was acceptable as output:

fun s(s:String,c:Int)=s.flatMap{p->List(c,{p})}.map{p->List(c,{p}).joinToString("")}
\$\endgroup\$
0
\$\begingroup\$

PHP, 97 bytes

for($i=0;$i<strlen($s=$argv[1]);$i++)for($j=0;$j<$r=$argv[2];$j++)echo str_repeat($s[$i],$r)."
";
\$\endgroup\$
0
\$\begingroup\$

Mathematica, 49 bytes

(z=#2;Grid[Column/@Table[#,z,z]&/@Characters@#])&

input

["Test",4]

\$\endgroup\$
0
\$\begingroup\$

Pyth, 12 bytes

Small minded, but I haven't gotten there just yet.

VQp*+*Nszbsz

Explanation:

VQ          For every letter in the first input...
  p         Print without newline...
   *+*Nszsz (The index * int(second input) + newline) * int(the second input)

Test Suite

\$\endgroup\$
0
\$\begingroup\$

Clojure, 82 75 bytes

#(dotimes[x(count %1)](dotimes[y %2](prn(apply str(repeat %2(get %1 x))))))

Try it online!

Uncompressed:

#(dotimes [x (count %1)]
  (dotimes [y %2]
    (prn
      (apply str
        (repeat %2 (get %1 x))))))

Edit: Shaved a few chars off the end by replacing a for loop with the stdlib repeat function.

\$\endgroup\$
0
\$\begingroup\$

C# (.NET Core), 68 + 18 bytes

a=>n=>new int[a.Length*n].Select((x,i)=>Enumerable.Repeat(a[i/n],n))

Also included in byte count:

using System.Linq;

Try it online!

Output is a collection of collections of characters (one collection for each line).

Explanation:

a => n =>                                // Take a string and a number
    new int[a.Length * n]                // Create new collection, 'n' times larger than 'a'
    .Select((x, i) =>                    // Replace every member with
        Enumerable.Repeat(a[i / n], n)   //     a collection of repeated character from 'a', based on index
    )
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy