18
\$\begingroup\$

We haven't had a question for a while (5 days to be precise), so let's go for one.

Given a string s and a positive integer n, take every nth element of s, repeat it n times, and put it back into s.

For example, if n = 3 and s = "Hello, World!", every third character is Hl r!. You then repeat each character n times to produce HHHlll rrr!!!. You then replace the original letters with the repeated versions to produce the final product of HHHellllo, Worrrld!!!

You are to accomplish this task in the shortest code possible in your language!

Rules

  • This is a so the shortest code in bytes wins
  • n is guaranteed to be smaller than the length of s and greater than 0
  • The first character of s is where the nth characters are taken from, and is always repeated n times
  • s will only consist of printable ASCII (code points 0x20 (space) to 0x7E (~))

Test cases

s, n => output

"Hello, World!", 3 => "HHHellllo,   Worrrld!!!"
"Code golf", 1 => "Code golf"
"abcdefghijklm", 10 => "aaaaaaaaaabcdefghijkkkkkkkkkklm"
"tesTing", 6 => "ttttttesTingggggg"
"very very very long string for you to really make sure that your program works", 4 => "vvvvery    veryyyy verrrry loooong sssstrinnnng foooor yoooou toooo reaaaally    makeeee surrrre thhhhat yyyyour    proggggram    workkkks"
\$\endgroup\$
  • \$\begingroup\$ Can we take the input s as a character array? \$\endgroup\$ – Kevin Cruijssen Oct 12 '17 at 7:40
  • 2
    \$\begingroup\$ "and put it back into s" <- is this a strict requirement (overwriting the original string) or ist it ok to just output the final result? \$\endgroup\$ – Felix Palmen Oct 12 '17 at 9:15
  • \$\begingroup\$ @KevinCruijssen Yes you can \$\endgroup\$ – caird coinheringaahing Oct 12 '17 at 15:41
  • 1
    \$\begingroup\$ @FelixPalmen that was simply how I explained it. You can use any method you want \$\endgroup\$ – caird coinheringaahing Oct 12 '17 at 15:42
  • \$\begingroup\$ @cairdcoinheringaahing good, thanks, already did that. \$\endgroup\$ – Felix Palmen Oct 12 '17 at 16:46

29 Answers 29

10
\$\begingroup\$

Jelly, 3 bytes

Ḣs×

Input is taken as s, n.

Try it online!

How it works

Ḣs×  Main link. Argument: s, n

Ḣ    Head; yield s.
     This pops the list, leaving [n] as the main link's argument.
 s   Split s into chunks of length n.
  ×  Multiply each chunk by [n], repeating its first element n times.
\$\endgroup\$
  • \$\begingroup\$ Isn't it actually 6 bytes in UTF-8 encoding? E1 B8 A2 73 C3 97 \$\endgroup\$ – CoDEmanX Oct 12 '17 at 12:58
  • 5
    \$\begingroup\$ In UTF-8, yes. However, Jelly uses a custom code page, where each of the characters it understands takes up only a single byte. \$\endgroup\$ – Dennis Oct 12 '17 at 14:05
7
\$\begingroup\$

Jelly,  6  5 bytes

-1 byte thanks to leaky Nun (use Python's string multiplication.)

×Jm¥¦

A full program, accepting two command line arguments, the string and the number, and printing the result.

Try it online!

How?

×Jm¥¦ - Main link: list of characters, s; number, n   e.g. ['g','o','l','f','e','r'], 2
    ¦ - sparse application:
   ¥  - ...to indices: last two links as a dyad:
 J    -      range of length of s                          [1,2,3,4,5,6]
  m   -      modulo slicing by n (every nth entry)         [1,3,5]
×    - ...action: multiply  ["gg",'o',"ll",'f',"ee",'r']
      - implicit print                                 >>> ggollfeer
\$\endgroup\$
  • \$\begingroup\$ 5 bytes? \$\endgroup\$ – Leaky Nun Oct 12 '17 at 0:01
  • \$\begingroup\$ Yep tried x forgot ×; thanks. \$\endgroup\$ – Jonathan Allan Oct 12 '17 at 7:20
  • \$\begingroup\$ Isn't it actually 8 bytes in UTF-8 encoding? C3 97 4A 6D C2 A5 C2 A6 \$\endgroup\$ – CoDEmanX Oct 12 '17 at 13:00
  • 2
    \$\begingroup\$ @CoDEmanX Uses Jelly's custom code page \$\endgroup\$ – MD XF Oct 12 '17 at 15:43
  • \$\begingroup\$ @MDXF thanks for fielding! \$\endgroup\$ – Jonathan Allan Oct 12 '17 at 16:22
4
\$\begingroup\$

JavaScript (ES6), 46 bytes

Takes input in currying syntax (s)(n).

s=>n=>s.replace(/./g,(c,i)=>c.repeat(i%n?1:n))

Test cases

let f =

s=>n=>s.replace(/./g,(c,i)=>c.repeat(i%n?1:n))

console.log(f("Hello, World!")(3))
console.log(f("Code golf")(1))
console.log(f("abcdefghijklm")(10))
console.log(f("tesTing")(6))
console.log(f("very very very long string for you to really make sure that your program works")(4))

\$\endgroup\$
3
\$\begingroup\$

Proton, 44 bytes

s=>n=>"".join(s[i]*(i%n?1:n)for i:0..len(s))

Try it online!

\$\endgroup\$
3
\$\begingroup\$

C# (.NET Core), 84 82 bytes

n=>m=>{var s="";for(int i=0;i<n.Length;)s+=new string(n[i],i++%m<1?m:1);return s;}

Try it online!

\$\endgroup\$
  • \$\begingroup\$ You can save a byte by removing i++ and changing n[i],i%m<1?m:1 to n[i],i++%m<1?m:1. \$\endgroup\$ – Kevin Cruijssen Oct 12 '17 at 7:46
  • \$\begingroup\$ You can save another byte by currying the inputs: n=>m=>... \$\endgroup\$ – raznagul Oct 12 '17 at 9:37
3
\$\begingroup\$

05AB1E, 8 7 bytes

-1 byte thanks to @Emigna

ôʒć²×ì?

Try it online!

Explanation

ôʒć²×ì?    Arguments s, n  ("Hello, World!", 3)
ô          Split s into pieces of n  (["Hel", "lo,", ...])
 ʒ         Filter (used as foreach)
  ć          Extract head  ("Hel" -> "el", "H" ...)
   ²×ì       Repeat n times and prepend  ("el", "H" -> "HHHel" ...)
      ?      Print without newline
\$\endgroup\$
  • \$\begingroup\$ Save a byte with ôʒć²×ì? \$\endgroup\$ – Emigna Oct 12 '17 at 11:04
  • \$\begingroup\$ @Emigna thanks, I knew there must be a way to get rid of the closing } \$\endgroup\$ – kalsowerus Oct 12 '17 at 11:15
  • \$\begingroup\$ Weird use of filter when it isn't using the result but it actually makes a difference... \$\endgroup\$ – Magic Octopus Urn Oct 12 '17 at 20:05
  • \$\begingroup\$ @MagicOctopusUrn, yep filter is still the better foreach in 05AB1E \$\endgroup\$ – kalsowerus Oct 12 '17 at 20:19
  • \$\begingroup\$ @kalsowerus vy is one foreach, ε is another. Oddly enough, ε doesn't work. \$\endgroup\$ – Magic Octopus Urn Oct 12 '17 at 20:22
2
\$\begingroup\$

PowerShell, 51 bytes

param($a,$n)-join($a|%{($_,("$_"*$n))[!($i++%$n)]})

Try it online!

Takes input as a char-array $a and the number $n. Loops through $a and each iteration either outputs the current letter $_ or the current letter multiplied by $n, based on an index into a pseudo-ternary. The index chooses between the two based off of incrementing $i and then modulo $n. Those letters are then -joined back together and the string is left on the pipeline; output is implicit.

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

Python 2, 54 53 bytes

Edit: Saved 1 byte thanks to @Rod

f=lambda x,n,i=0:x[i:]and[1,n][i%n<1]*x[i]+f(x,n,i+1)

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ you can swap x[i] and [1,n][i%n<1] to save a space \$\endgroup\$ – Rod Oct 11 '17 at 19:48
2
\$\begingroup\$

Alice, 25 bytes

/
KI /!Iw?&.?t&O?&wWOI.h%

Try it online!

Explanation

/         Switch to Ordinal.
I         Read first line of input (i.e. n).
/         Switch to Cardinal.
!         Convert input to its integer value and store it on the tape.
I         Read first character from input string.
w         Push current IP address onto the return address stack. This
          effectively marks the beginning of the main loop.

  ?         Retrieve n.
  &.        Duplicate current character n times (once more than we need,
            but who cares about a clean stack...).
  ?t        Retrieve n and decrement.
  &O        Output n-1 copies of the current character.
  ?         Retrieve n.
  &w        Push the current IP address onto the return address stack n
            times. This marks the beginning of a loop that is executed n 
            times.

    W         Discard one copy of the return address from the stack,
              effectively decrementing the loop counter.
    O         Output the last character. On the first iteration, this is
              the final copy of the repeated character, otherwise it's just
              the single character we read on the last iteration.
    I         Read a character for the next iteration.
    .h%       Compute c % (c+1) on that character, which is a no-op for
              for valid characters, but terminates the program at EOF when
              c becomes -1.

K         Jump to the address on top of the return address stack. As long
          as there are still copies of the address from the inner loop, we
          perform another iteration of that, otherwise we jump back to the
          beginning of the outer loop.
\$\endgroup\$
2
\$\begingroup\$

R, 82 76 75 bytes

function(s,n)cat(rep(S<-el(strsplit(s,'')),c(n,rep(1,n-1))+!seq(S)),sep='')

Try it online!

A function; takes a string s and an integer n, and prints the repeated version to stdout.

Explanation:

function(s,n){
 S <- el(strsplit(s,""))                  # characters
 r     <- c(n,rep(1,n-1))                 # [n, 1, 1,...,1], length n
 repeats <- r+!seq(S)                     # extends R to length of S
 cat(rep(S, repeats), sep="")             # print out
}

R, 55 bytes

function(S,n)cat(rep(S,c(n,rep(1,n-1))+!seq(S)),sep="")

Try it online!

Same algorithm as above, but with S taken as a list of individual characters.

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

Python 2, 57 bytes

lambda s,n:''.join(c*[1,n][i%n<1]for i,c in enumerate(s))

Try it online!

\$\endgroup\$
  • \$\begingroup\$ Would indexing into the string rather than using enumerate be shorter? \$\endgroup\$ – caird coinheringaahing Oct 11 '17 at 19:46
  • \$\begingroup\$ @cairdcoinheringaahing i would have to use range(len()) in the end would be longer \$\endgroup\$ – Rod Oct 11 '17 at 19:49
  • \$\begingroup\$ 56 bytes \$\endgroup\$ – ovs Oct 11 '17 at 20:25
1
\$\begingroup\$

Python 2, 53 bytes

f=lambda x,n,i=0:x[i:]and n**0**(i%n)*x[i]+f(x,n,i+1)

Try it online!

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

Japt, 8 bytes

ËùDV*EvV

Test it online!

Explanation

 Ë    ùDV*EvV
UmDE{DùDV*EvV}   Ungolfed
                 Implicit: U = s, V = n
UmDE{        }   Replace each char D and (0-)index E in U by this function:
          EvV      Take 1 if the index is divisible by V; 0 otherwise.
        V*         Multiply this by V. This gives V for every Vth index; 0 for others.
     DùD           Pad D with itself to this length. This gives V copies of D for every
                   Vth index; 1 copy of D for others.
                 Implicit: output last expression

I have to credit the idea to use ù to @Shaggy's answer here. I don't know that I ever would have thought of it myself...

\$\endgroup\$
  • \$\begingroup\$ You see now why was so keen to see string padding added :) Nice solution. I was trying to get something to work with ë, for poops & giggles, but failed miserably! \$\endgroup\$ – Shaggy Oct 11 '17 at 21:26
1
\$\begingroup\$

J, 17 bytes

(#@]$[,1#~<:@[)#]
  • (...) # ] everything in parens creates the string for J's built in "copy" verb. So, eg, if the left argument is 3, it creates the string 3 1 1 repeated as needed to equal the number of characters in the right arg ], which contains the string. Which is to say, # solves the problem directly, assuming we can give it the correct left argument: 4 should be 4 1 1 1 repeated, and so on.
  • Examining #@]$[,1#~<:@[, we see it uses J's shape verb $ in the middle -- that's the main verb of this phrase...
  • To the left of $ is #@], meaning the length # of the right arg ].
  • To the right of $ is [,1#~<:@[, a 5 verb train. The first train executed is...
  • 1#~<:@[, which means 1 copied #~ (passive form of copy) one less than <: the left arg [. This result is passed to the final fork:
  • [, ... meaning take the left arg, and append the result we just calculated, which is a string of 1s.

Try it online!

\$\endgroup\$
  • \$\begingroup\$ ]#~[^0=(|i.@#) for 14 bytes \$\endgroup\$ – miles Oct 13 '17 at 11:55
  • \$\begingroup\$ That's quite clever. Your improvements to my posts are the best part of this site for me. \$\endgroup\$ – Jonah Oct 13 '17 at 14:16
1
\$\begingroup\$

C# (.NET Core), 61 + 18 = 79 bytes

using System.Linq;
n=>m=>string.Concat(n.Select((c,i)=>new string(c,i%m<1?m:1)))

Try it online!

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

Perl 5, 37, 29 +1 (-p) bytes

-8 bytes thanks to Tom's comment.

$n=<>;s/./"@-"%$n?$&:$&x$n/ge

Try It Online

\$\endgroup\$
  • \$\begingroup\$ Can't think of a better approach right now, but I came up with a few ideas: $n=<>; instead of the BEGIN block and have n on the next line of input and replace $-[0] with "@-" since only the first number is evaluated in comparison. Also, if you take input of n via -i you can just use $^I instead of declaring and using $n, but since this is non-standard it might not fly... :) \$\endgroup\$ – Dom Hastings Oct 12 '17 at 11:33
1
\$\begingroup\$

6502 machine code routine, 50 bytes

A0 01 84 97 88 84 9E 84 9F B1 FB F0 20 A4 9F 91 FD C6 97 D0 10 A6 FF CA F0
05 C8 91 FD D0 F8 84 9F A5 FF 85 97 E6 9E A4 9E E6 9F D0 DC A4 9F 91 FD 60

This is a position-independent subroutine expecting a pointer to the input string (0-terminated aka C-string) in $fb/$fc, a pointer to the output buffer in $fd/$fe and the count (n) in $ff. It uses simple indexing, so it's limited to a maximum output length of 255 characters (+ 0 byte) due to the 8bit architecture.

Explanation (commented disassembly):

 .rep:
A0 01       LDY #$01            ; init counter to next repetition sequence
84 97       STY $97
88          DEY                 ; init read and write index
84 9E       STY $9E             ; (read)
84 9F       STY $9F             ; (write)
 .rep_loop:
B1 FB       LDA ($FB),Y         ; read next character
F0 20       BEQ .rep_done       ; 0 -> finished
A4 9F       LDY $9F             ; load write index
91 FD       STA ($FD),Y         ; write next character
C6 97       DEC $97             ; decrement counter to nex rep. seq.
D0 10       BNE .rep_next       ; not reached yet -> next iteration
A6 FF       LDX $FF             ; load repetition counter
 .rep_seqloop:
CA          DEX                 ; and decrement
F0 05       BEQ .rep_seqdone    ; if 0, no more repetitions
C8          INY                 ; increment write index
91 FD       STA ($FD),Y         ; write character
D0 F8       BNE .rep_seqloop    ; and repeat for this sequence
 .rep_seqdone:
84 9F       STY $9F             ; store back write index
A5 FF       LDA $FF             ; re-init counter to next ...
85 97       STA $97             ; ... repetition sequence
 .rep_next:
E6 9E       INC $9E             ; increment read index
A4 9E       LDY $9E             ; load read index
E6 9F       INC $9F             ; increment write index
D0 DC       BNE .rep_loop       ; jump back (main loop)
 .rep_done:
A4 9F       LDY $9F             ; load write index
91 FD       STA ($FD),Y         ; and write terminating0-byte there
60          RTS                 ; done.

Example C64 machine code program using it:

This is a program in ca65-style assembler for the C64 using this routine (imported as rep):

REP_IN          = $fb
REP_IN_L        = $fb
REP_IN_H        = $fc

REP_OUT         = $fd
REP_OUT_L       = $fd
REP_OUT_H       = $fe

REP_N           = $ff

.import         rep


.segment "LDADDR"
                .word   $c000

.code
                jsr     $aefd           ; consume comma
                jsr     $ad9e           ; evaluate expression
                sta     REP_IN_L        ; store string length
                jsr     $b6a3           ; free string
                ldy     #$00            ; loop over string
readloop:       cpy     REP_IN_L        ; end of string?
                beq     termstr         ; then jump to 0-terminate string
                lda     ($22),y         ; read next character
                sta     in,y            ; store in input buffer
                iny                     ; next
                bne     readloop
termstr:        lda     #$00            ; load 0 byte
                sta     in,y            ; store in input buffer

                jsr     $b79b           ; read 8bit unsigned int
                stx     REP_N           ; store in `n`
                lda     #<in            ; (
                sta     REP_IN_L        ;   store pointer to
                lda     #>in            ;   to input string
                sta     REP_IN_H        ; )
                lda     #<out           ; (
                sta     REP_OUT_L       ;   store pointer to
                lda     #>out           ;   output buffer
                sta     REP_OUT_H       ; )
                jsr     rep             ; call function

                ldy     #$00            ; output result
outloop:        lda     out,y
                beq     done
                jsr     $ffd2
                iny
                bne     outloop
done:           rts


.bss
in:             .res    $100
out:            .res    $100

Online demo

Usage: sys49152,"[s]",[n], e.g. sys49152,"Hello, World!",3

Important: If the program was load from disk (like in the online demo), issue a new command first! This is necessary because loading a machine program trashes some C64 BASIC pointers.

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

Java 8, 100 76 bytes

s->n->{int i,k=0;for(char c:s)for(i=k++%n<1?n:1;i-->0;)System.out.print(c);}

-24 bytes thanks to @OliverGrégoire.

Explanation:

Try it here.

s->n->{                    // Method with char-array and int parameters and no return-type
  int i,k=0;               //  Index-integers
  for(char c:s)            //  Loop (1) over the characters of the input array
    for(i=k++%n<1?         //   If `k` is divisible by the input `n`:
         n                 //    Change `i` to `n`
        :                  //   Else:
         1;                //    Change `i` to 1
        i-->0;)            //   Inner loop (2) from `i` down to 0
      System.out.print(c); //    And print the current character that many times
                           //   End of inner loop (2) (implicit / single-line body)
                           //  End of loop (1) (implicit / single-line body)
}                          // End of method
\$\endgroup\$
  • \$\begingroup\$ Oops, I didn't see there was already a submission so I deleted mine. Here's it, shortened to 76 bytes: n->s->{int i,k=0;for(char c:s)for(i=k++%n<1?n:1;i-->0;)System.out.print(c);} (with a char[], instead of String.) \$\endgroup\$ – Olivier Grégoire Oct 12 '17 at 10:29
  • \$\begingroup\$ Rule of the thumb, if you have to declare exactly one String that will be returned, it's shorter to just print it out. \$\endgroup\$ – Olivier Grégoire Oct 12 '17 at 10:41
  • \$\begingroup\$ @OlivierGrégoire Oops.. Yes, I know that rule of thumb, just forgot to apply it this time.. And thanks for the saved bytes! \$\endgroup\$ – Kevin Cruijssen Oct 13 '17 at 7:17
1
\$\begingroup\$

MATL, 10 7 bytes

-3 bytes thanks to Luis Mendo!

tq:ghY"

Try it online!

Takes input as n and then S as a string/char array.

    % (implicit input)
    % stack: n
t   % duplicate
    % stack: n n
q   % decrement
    % stack: n n-1
:   % range
    % stack: n [1 2 ... n-1]
g   % convert to logical (nonzero->1, zero->0)
    % stack: n [1 1 ... 1]
h   % horizontal concatenate
    % stack: [n 1 1 ... 1]
Y"  % run-length decoding, taking the string as first input and recycling 
    % the lengths [n 1 1 ... 1] as needed
    % (implicit output as string)

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

Haskell, 51 46 bytes

Thanks @Laikoni for saving me 5 bytes!

n&s=do(m,c)<-zip[0..]s;c<$[0..(n-1)*0^mod m n]

Try it online!

Explanation/Ungolfed

The operator c <$ [a..b] replaces each element of the list [a,a+1...b] by c - so it's just a golfed replicate:

do(m,c)<-zip[0..]s;                                  -- with all (m,c) in the enumerated ([(0,a),(1,b)..]) input string, replace with
                   replicate (1 + (n-1)*0^mod m n) c -- either n or 1 times the character c (note that the list begins with 0, that's where the 1+ comes from)
\$\endgroup\$
0
\$\begingroup\$

Charcoal, 14 bytes

Nθ⪫ES⎇﹪κθι×ιθω

Try it online! Link is to verbose version of code. Takes input in the order n, s.

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

V, 13 bytes

"aDJòylÀpÀll

Try it online!

This is a really dumb workaround. òlhÀälÀlÀ<M-->l should work, but I can't for the life of me understand why, especially since manually doing lhÀälÀlÀ<M-->l repeated a bunch of times does work.

Hexdump:

00000000: 1822 6144 4af2 796c c070 c06c 6c         ."aDJ.yl.p.ll

Explanation:

<C-x>               " Decrement the number
       D            " Delete that number...
     "a             "   Into register 'a'
        J           " Remove the blank line
         ò          " Recursively...
          yl        "   Yank the letter under the cursor
            Àp      "   And paste it 'a' times
              Àl    "   Move 'a' times to the right ('l' for right)
                l   "   Move to the right one more time
                    " (implicit) end the loop
\$\endgroup\$
  • \$\begingroup\$ 'l' for right ... I'm guessing that's a holdover Vim thing? Otherwise ... why? \$\endgroup\$ – AdmBorkBork Oct 11 '17 at 19:51
  • 2
    \$\begingroup\$ @AdmBorkBork yeah l is right in vim. it might be orthographically backwards, but it's geometrically correct: l is the rightmost letter key of the middle row. \$\endgroup\$ – Jonah Oct 12 '17 at 7:05
  • \$\begingroup\$ @DJMcMayhem Right. I made it right. \$\endgroup\$ – Jonah Oct 12 '17 at 7:08
0
\$\begingroup\$

Pyth, 12 bytes

s*Vzm^Q!d%Uz

Try it here.

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

Python 3, 58 bytes

Working on golfing it down.

I know there are already other Python answers, but I thought I'd post this one too seeing as it scores pretty well compared to the others, despite being a full function and not a lambda.

Takes input as function parameters, and prints to STDOUT.

def f(s,n,i=0):
 for c in s:print(end=[c,c*n][i%n<1]);i+=1

Try it online!

For one byte less (57), I coded a lambda, however similar answers have already been posted by other users:

lambda s,n:''.join([c,c*n][i%n<1]for i,c in enumerate(s))
\$\endgroup\$
0
\$\begingroup\$

Brain-Flak (BrainHack), 122 + 3 (-A) = 125 bytes

I am sure this is too long, but I spent quite a while looking and couldn't find any improvements.

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

Try it online!

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

05AB1E, 12 11 bytes

vX‚RNIÖèy×?

Try it online!

Explanation

v             # for each letter in the input string
       è      # index into
 X‚           # the list [input_int,1]
   R          # reversed
    NIÖ       # with letter_index % input_int == 0
        y×    # repeat the current letter this many times
          ?   # print
\$\endgroup\$
0
\$\begingroup\$

Mathematica, 71 bytes

""<>s[[i]]~t~If[i~Mod~#2==1,#2,1]~(t=Table)~{i,Tr[1^(s=Characters@#)]}&

Try it online!

saved -2 bytes by listening to user202729

\$\endgroup\$
  • \$\begingroup\$ I think Map over Characters may be shorter. \$\endgroup\$ – user202729 Oct 12 '17 at 10:03
  • \$\begingroup\$ @user202729 ok! -2 bytes \$\endgroup\$ – J42161217 Oct 12 '17 at 10:23
0
\$\begingroup\$

K (oK), 23 19 bytes

Solution:

{,/(1|y*~y!!#x)#'x}

Try it online!

Examples:

> {,/(1|y*~y!!#x)#'x}["Hello, World!";3]
"HHHellllo,   Worrrld!!!"
> {,/(1|y*~y!!#x)#'x}["Code golf";1]
"Code golf"
> {,/(1|y*~y!!#x)#'x}["abcdefghijklm";10]
"aaaaaaaaaabcdefghijkkkkkkkkkklm"

Explanation:

{,/(1|y*~y!!#x)#'x} / the solution
{                 } / lambda function with x and y as implicit parameters
   (          )     / do everything in brackets together
            #x      / count x, #"Hello, World!" -> 13
           !        / til, !13 -> 0 1 2 3 4 5 6 7 8 9 10 11 12
         y!         / y modulo, 3!0 1 2 3 4 5 6 7 8 9 10 11 12 -> 0 1 2 0 1 2 0 1 2 0 1 2 0
        ~           / not, ~0 1 2 0 1 2 0 1 2 0 1 2 0 -> 1 0 0 1 0 0 1 0 0 1 0 0 1
      y*            / multiply by y, 3*1 0 0 1 0 0 1 0 0 1 0 0 1 -> 3 0 0 3 0 0 3 0 0 3 0 0 3
    1|              / min of 1 and, 1|3 0 0 3 0 0 3 0 0 3 0 0 3 -> 3 1 1 3 1 1 3 1 1 3 1 1 3
                #'x / take each parallel, 1 2 3#'"abc" -> "a", "bb", "ccc"
 ,/                 / flatten the list, "a", "bb", "ccc" -> "abbccc"

Notes:

  • -4 bytes with different approach
\$\endgroup\$
0
\$\begingroup\$

Excel VBA, 71 Bytes

Anonymous VBE immediate window function that take input from range [A1:B1] and outputs to the VBE immediate window.

For i=1To[Len(A1)]:[C1]=i:?[Rept(Mid(A1,C1,1),B1^(Mod(C1,B1)=1))];:Next
\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.