# Repeat Hello World according to another string's length

This was related to a program I am writing. Although the title is simple, the challenge is a lot more complicated.

You must write a program that takes an input, and your answer must match the sample outputs in this question.

What the program should be is that you must output "HelloWorld" with the length of the input matching the length of what you output. If the input's length is not divisible with 10, you should cut off the last few letters until it matches the length of the last few letters of the input. More clarification in the examples.

Standard loopholes apply, except that answers should be full programs, and the input has to be printable ASCII.

## Example inputs

Input:how are you
Output:HelloWorldH

Note: In the above example, there is an extra H due to the
characters in the input being 11, so we add an extra letter

Input:hrienehwnv
Output:HelloWorld

Input:kill him at dawn
Output:HelloWorldHelloW


This is , so shortest answer wins!

Steffan won the first +50 bounty reputation award for 5 bytes. I know lyxal also had a 5 bytes with the same language, but previously he had his answer with 8 bytes, before he shortened it to 5 bytes, but after Steffan's answer had already been posted.
• BTW, the answers seem to be assuming Default for Code Golf: Input/Output methods , writing functions or lambdas that take 2 operands. Not whole programs, because in many languages that requires a lot of uninteresting boilerplate. Your phrasing requires a program. You could avoid that by rephrasing to "you must take 2 inputs ... and output a string with the same length, filled with repeats of the string HelloWorld". Then answers can write programs or functions, whatever they like. Aug 1 at 2:47
• "Filling a buffer" is just the terminology I'm using to describe the the interesting core part of the problem in terms of a C or assembly implementation, separate from actual I/O. i.e. generating a string in memory. Of course an implementation in a higher-level language wouldn't be in those terms, just manipulation of string variables (but still often not IO). If you did want to disallow functions and require answers to be whole programs, you should edit to explicitly say you're overriding Default for Code Golf: Input/Output methods Aug 1 at 6:58
• Is the input guaranteed to only contain letters (both lower- and uppercase) and spaces? Aug 1 at 6:59
• I assume Kevin is considering an implementation in some language using a search/replace function or something like that, in which case the contents could matter. Remember, this is code-golf, where any guarantee might potentially be useful for a hacky implementation, even if that would be irrelevant for a sane clean implementation. Aug 1 at 19:27
• In that case, if you want to know, it should contain printable ASCII characters. Aug 2 at 6:04

# JavaScript, 45 35 bytes

s=>"".padEnd(s.length,"HelloWorld")


Try it online!

−10 thanks to Arnauld.

• padEnd() is probably the best option here (35 bytes) Jul 31 at 8:19

map fst.zip(cycle"HelloWorld")


Try it online!

A cute way to truncate one string to the length of another is to zip them together, which truncates the longer string, then extract the desired string with map fst.

Longer alternatives:

fst.unzip.zip(cycle"HelloWorld")
zipWith const$cycle"HelloWorld"  # Python, 39 bytes lambda s:('HelloWorld'*len(s))[:len(s)]  Attempt This Online! # sed, 1115551 44 bytes s/./a/ :a s/^/HelloWorld/ s/.\{10\}$//
/a/ba

Attempt This Online!

# Charcoal, 13 bytes

…HelloWorldＬＳ


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

 HelloWorld     Literal string HelloWorld
…               Reshaped to length
Ｌ    Length of
Ｓ   Input string

• Best answer - no dictionary lookup tomfoolery! Aug 3 at 14:50

# 05AB1E, 9 bytes

”Ÿ™‚ï”áI∍


Input as a list of characters.

Explanation:

”Ÿ™‚ï”     # Push dictionary string "Hello World"
á    # Only keep letters to remove the space: "HelloWorld"
I   # Push the input-list
∍  # Shorten/extend the "HelloWorld" string to its length
# (after which the result is output implicitly)


See this 05AB1E tip of mine (section How to use the dictionary?) to understand why ”Ÿ™‚ï” is "Hello World".

• This is larger than 9 bytes with any Unicode encoding. More like 16. Aug 1 at 19:28
• @VioletGiraffe 05AB1E uses, just like some other golfing languages you'll see on CGCC like Jelly, Charcoal, Vyxal, etc. its own codepage for the 256 characters it knows. Each of these characters are 1 byte each in this encoding. I'm not sure how to run the new 05AB1E version (which compiles with Elixir) in Bash, but here is an example of running the raw bytes in this encoding for the legacy version of 05AB1E, which compiles in Python. Aug 1 at 21:22

# Excel, 38 bytes

=LEFT(REPT("HelloWorld",3276),LEN(A1))


Input is in the cell A1. Output is wherever the formula is.

Repeats the string as many times as allowed based on the limitations of inputs to LEFT() and the truncates all but the left-most characters based on the length of the input.

# Pyth, 25 bytes

FNrZlwp@"HelloWorld"%N 10


Try it online!

PS: first time using Pyth & this platform is awesome!

• Welcome to Code Golf! Jul 31 at 19:30

# C (gcc), 55 bytes

main(c){for(;~getchar();)printf(L"dHelloWorl"+c++%10);}


Try it online!

• Is this a function or a full program? Aug 7 at 10:38
• it is a full program. It can be compiled as cc <program_name> with any c89 compiler on a little endian machine, if you intend to run it I reccomend running it as printf '%s' '<test_input>' | ./a.out, to avoid confusion with '\n' in the input
– c--
Aug 7 at 15:58
• @py3programmer here is a C11 compliant and cross platform (the printf trick only works on a little-endian architecture) implementation of the same program for clarity
– c--
Aug 7 at 17:02

# Retina, 27 bytes

Tp~
Y~\He\l\l\oW\or\l\d


Try it online! Explanation:

Tp~


Translate all the characters to ~s.

Y~\He\l\l\oW\or\l\d


Cyclically translate all the ~s to the characters HelloWorld. Note that unfortunately most of them have special meanings to translate so that they have to be quoted.

# Perl 5 + -pl, 23 bytes

Inspiration taken from @Neil's Retina answer. 3 bytes saved thanks to @Sisyphus!

$_&=HelloWorld x y//./c Try it online! ## Explanation Sets $_ (which will be implicitly output via -p) to the result of stringwise ANDing a string of HelloWorlds repeated once for the count of each char in the input (implicitly stored in $_ via the implicit -n from -p) when tr///ansliterated (y///) from any char to \xFFs. This operation results in a string the length of the original input with the content HelloWorld truncated accordingly. • You should be able to use the return value of s by doing HelloWorld x s/./\x7f/g. Save an additional byte by using y//\x7f/c instead Jul 31 at 23:38 • @Sisyphus thanks! I didn't think to use the replacement in that position, but since it still executes before the rest, that makes sense! Aug 1 at 11:12 # Vyxals, 5 bytes ẏkhȧİ  Try it Online! Can't believe I had to find a new 5 byter because someone got my answer by 2 bytes shorter :p. ## Explained ẏkhȧİ ẏ # The range [0, len(input)] khȧ # The string "HelloWorld" İ # The range indexed into the characters of the string.  ## Vyxalsr, 5 bytes khȧf•  Try it Online! More flags and more ways that I won't be outgolfed again. Takes input as a list of characters ### Explained khȧf• khȧf # The string "HelloWorld" as a list of chars • # Molded to the shape of the input  • Steffan has a 2 bytes lesser answer. Aug 1 at 13:53 # Knight, 23 bytes O G*"HelloWorld"=cL P0c  Try it online! # Vyxal, 5 bytes LkhȧẎ  Try it Online! # Haskell, 33 bytes ($cycle "HelloWorld").take.length


Try it online!

• xnor has written a 3 bytes lesser answer, check it out. Aug 1 at 5:50

# Factor + sequences.repeating, 33 bytes

[ "HelloWorld"swap length cycle ]


Try it online!

# lin, 25 bytes

"HelloWorld"cyc.~ len t


Try it here! Returns an iterator.

For testing purposes:

"how are you" ; _ outln
"HelloWorld"cyc.~ len t


## Explanation

Cycle and take (input length) items.

# Jelly, 8 bytes

“ ⁷ỴNt»ṁ


A monadic Link that accepts a list of characters and yields a list of characters.

Try it online!

### How?

Pretty simple...

“ ⁷ỴNt»ṁ - Link: list of characters, S
“ ⁷ỴNt»  - dictionary lookup -> "HelloWorld"
ṁ - mould like S


# vim, 46 bytes

$mma<C-R>=col('$')
aHelloWorld<C-V><ESC><ESC>mlDo<ESC>@"khjllDkdd


## Annotated

$mm # Go to the end of input and mark our position a # Append... <C-R>=col('$')         #   The column offset/line length
aHelloWorld<C-V><ESC>  #   This exact string
<ESC>                    # ...which yields a command that prints "HelloWorld"
# once per char in the original input. (All that matters
# is that this string is at least as long as the output
# needs to be.)

mlD                     # Delete the string we just appended, copying into register "
o<ESC>@"                 # Run the command, putting a bunch of "HelloWorld"s on next line
khjllD                   # Make the new line the same length as the input
kdd                      # delete the input


<C-R> is 0x12, <ESC> is 0x1b, <C-V> is 0x16.

Try it online!

# PowerShell, 37 bytes

-join($args|%{'HelloWorld'[$i++%10]})


Try it online!

# Rust (full program), 145 bytes

The full program rule doubles the length.

fn main(){for l in std::io::stdin().lines(){print!("{}",(0..).zip(l.unwrap().chars()).map(|i|b"HelloWorld"[i.0%10]as char).collect::<String>())}}

Attempt This Online!

# Rust (function), 85 bytes

|l:&str|(0..).zip(l.chars()).map(|i|b"HelloWorld"[i.0%10]as char).collect::<String>()

Attempt This Online!

• Using Iterator::cycle, you can save 6 bytes: |l:&[_]|b"HelloWorld".iter().copied().cycle().take(l.len()).collect::<Vec<_>>() Aug 7 at 8:46
• @corvus_192 Nice find, since it has basically nothing in common with my answer feel free to post it seperately Aug 7 at 10:33

# Alice, 54 bytes

/ H l o o l " \w>?hn$vihn$@?]oK
" e l W r d !  ^(H' <


Try it online!

# Flattened

/"HelloWorld"!\w>?hn$vihn$@?]oK
^(H' <
/"HelloWorld"!\                  Pushes the hello world string on the tape
w      ihn$@ K While where are characters to read on the input >?hn$v           If the tape is outside of "HelloWorld"
^(H' <           Rewind the tape
?]o   Print one character from the tape and move to the next one


# brainfuck, 180 bytes

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


Try it online!

Can likely be golfed quite a bit more, as the majority of the code is setting up the string "HdlroWolle" on the tape.

Explanation:

>+[++[++>]<<+]>+                          108 = 'l'
[->>+>+>+>+>+>+>+>+>+<<<<<<<<<<]          ptr before '\0lllllllll'

-[>+<-------]>-                           ptr on 'H'

>--------                                 'd'
>                                         'l'
>++++++                                   'r'
>+++                                      'o'
>---------------------                    'W'
>+++                                      'o'
>                                         'l'
>                                         'l'
>-------                                  'e'    ("HdlroWolle")

> ,[>+<,]         [Read all input, counting the length of it 2 cells after the string.]

>[-<                                      Do len(input) times:

<[                                        Shift the string right by 1
[->+<]
<
]
[see https://www.codingame.com/playgrounds/50443/brainfuck-part-2---working-with-arrays]

[Print the first character of the string and move the far
right cell back to the beginning, rotating the string.]
>>.>>>>>>>>>[-<<<<<<<<<<+>>>>>>>>>>]

>]                                        End loop


# BQN, 15 bytes

"HelloWorld"⥊˜≢


Try it at BQN REPL

"HelloWorld"⥊˜≢
≢    # get the shape (length) of the input
⥊˜      # and use this to reshape
"HelloWorld"        # the string "HelloWorld"
# (recycling elements if required)


## Kustom, 39 bytes

The extra byte is for the global variable name.

$tc(rpad,"",tc(len,gv(i)),HelloWorld)$


# PowerShell Core, 35 bytes

% L*h|%{'HelloWorld'*$_|% S*g 0,$_}


Try it online!

# Windows PowerShell, 38 bytes

% L*h|%{'HelloWorld'*$_|% S*g -a 0,$_}


Same as above, but PS 5.1 requires actually naming the parameter "-ArgumentList" (shortened to "-a") for the Substring() method call.

Input comes from the pipeline.

Nothing fancy; this is basically
ForEach-Object {$l =$_.Length; ('HelloWorld' * $l).Substring(0,$l)}
The expensive method calls can be golfed by using the cmdlet ForEach-Object (that is, its alias "%"), and its possibility to call a method of the input object by name, accepting wildcards.

% L*h|%{'HelloWorld'*$_|% S*g 0,$_}
% L*h                                  # "ForEach-Object -MemberName Length": invoke the method "Length" for the string passed in the pipeline
|                                 # Pipe the length of the input string to the next cmdlet
%{                               # "ForEach-Object -ScriptBlock {"
'HelloWorld'*$_ # repeat the string 'HelloWorld' <Length> times | # and pipe the 'HelloWorldHelloWorld...' to the next cmdlet % S*g 0,$_     #     "ForEach-Object -MemberName Substring -ArgumentList 0, <Length>": invoke the method "Substring" for the string passed in the pipeline, get <Length> chars starting at 0
}                               # }: end of the scriptblock; Output is implicit

• It is a code snippet, not a full program (PS script) and not a function. Sorry. Aug 2 at 6:07
• You repeating it is a snippet doesn't make it so. ForEach-Object is a regular command in PowerShell, like grep in bash, so it may be used. This bash uses the same method, and nobody was complaining about the byte count; instead, the comments were actually constructive. You have yet to provide one single argument to back up your claim that this is a snippet, or why pipeline input should be counted. So, please, either finally back up your claim with something other than repeating because I say so, or pass it on to moderation. Aug 2 at 10:59
• Aug 2 at 10:59
• if you use a bash pipe then you can't to use ForEach simple. Your code 'how are you', 'hrienehwnv', 'kill him at dawn' | is a Powershell code, that placed outside counted bytes. Please, use bash pipe correcly or place | into counted bytes. Aug 2 at 12:17
• That pipe is the initial invocation, and I'm using it quite correctly; pipeline input is explicitly allowed, see above, and that's how you do it in a Shell. You don't count the function invocation &$f in your script at PS, either. The bash I linked above uses exactly the same invocation of a header echo "$REPLY" | \  followed by the counted code grep ..., and nobody, including you, complained. Where's the difference, pray tell? This is just another iteration of "because I say so". Aug 2 at 14:40

# simply, 111 106 bytes

This is (yet another) language I'm just working on, for fun.

It is a very verbose language, and still in progress, which is why the algorithm is ... less conventional and very convoluted...

def&f($v){$C=&str_chunk("HelloWorld"&len($v));send$C[0];}echo&join(&array_map(&str_chunk($argv[0]10)&f)'')  Due to oversights in the parser, the values don't have to have to be separated by commas. ## Ungolfed: Create a function called &handle_chunk with arguments ($value).
Begin
Assign $len the value of executing the function &len with argument$value.

Set the variable $chunks with the value of calling the function &str_chunk with the arguments "HelloWorld",$len.

Return the value $chunks[0]. End. Display the result of calling &join( Call the function &array_map with the arguments ( Run &str_chunk($argv[0], 10),
&handle_chunk
),
""
).


Should be self-explanatory.

## How to run:

Download the repository and open índex.html.

## Unintended method:

This is simply a re-implementation of m90's answer:

%c="";def&f($s)call%c->padEnd(&len($s)"HelloWorld");


Works the same way as the intended way.

# R (function), 41 bytes

substr<-(a,1,90,strrep("HelloWorld",9))


I assume this can be improved...

This takes advantage of a feature of substr() I learned when I was today years old: substr() has a replacement function, and if the string replacing the substring is longer than the substring, it is cut off at the appropriate place, which works perfectly for this challenge. We can replace the entire input string a with a string of concatenated "HelloWorld"s with the last one truncated. This will not work for any string longer than 90 characters but no test cases in the input are that long. To make it work for longer strings, you can replace both of the 90 and 9 with nchar(a).

Try it online!

• Nice answer! To compete fairly with everyone else, you'll need to include all the essential code required for the function definition in the byte-count: this includes the function(a) bit like this, which makes this 52 bytes in total... Aug 3 at 10:53
• Also, although none of the examples given include >90 character strings, it isn't really valid to assume that this will always be the case, so you'll need to include the nchar(a) (or something equivalent) to fully comply with the spec. Luckily you can re-arrange a bit to avoid doing this twice... Aug 3 at 11:00
• BTW - you can easily convert to a full program using scan() instead of defining a function, although it costs a byte: Try it... Aug 3 at 11:11
• @DominicvanEssen Thanks for the tips. I will correct this later today! Aug 3 at 11:51

# Ruby, 37, 35 bytes

->x{('HelloWorld'*l=x.size)[0...l]}


Try it online!

-2 bytes thanks to @Steffan

• 35: ->x{('HelloWorld'*l=x.size)[0...l]} Aug 3 at 14:35
• @Steffan nice catch! thanks! Aug 3 at 14:55

# J, 15 bytes

'HelloWorld'$~#  Try it online! Very straightforward. ## Explanation 'HelloWorld'$~#
\$~     reshape
'HelloWorld'       this string
#    by the length of the input