11
\$\begingroup\$

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

Your challenge

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.
\$\endgroup\$
10
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ Aug 1 at 2:47
  • 1
    \$\begingroup\$ "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 \$\endgroup\$ Aug 1 at 6:58
  • 1
    \$\begingroup\$ Is the input guaranteed to only contain letters (both lower- and uppercase) and spaces? \$\endgroup\$ Aug 1 at 6:59
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ Aug 1 at 19:27
  • 1
    \$\begingroup\$ In that case, if you want to know, it should contain printable ASCII characters. \$\endgroup\$ Aug 2 at 6:04

37 Answers 37

11
\$\begingroup\$

JavaScript, 45 35 bytes

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

Try it online!

−10 thanks to Arnauld.

\$\endgroup\$
1
  • 4
    \$\begingroup\$ padEnd() is probably the best option here (35 bytes) \$\endgroup\$
    – Arnauld
    Jul 31 at 8:19
7
\$\begingroup\$

Haskell, 30 bytes

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"
\$\endgroup\$
6
\$\begingroup\$

Python, 39 bytes

lambda s:('HelloWorld'*len(s))[:len(s)]

Attempt This Online!

\$\endgroup\$
6
\$\begingroup\$

sed, 111 55 51 44 bytes

s/./a/
:a
s/^/HelloWorld/
s/.\{10\}$//
/a/ba

Attempt This Online!

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

Charcoal, 13 bytes

…HelloWorldLS

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

 HelloWorld     Literal string `HelloWorld`
…               Reshaped to length
           L    Length of
            S   Input string
\$\endgroup\$
1
  • \$\begingroup\$ Best answer - no dictionary lookup tomfoolery! \$\endgroup\$
    – Rob Grant
    Aug 3 at 14:50
5
\$\begingroup\$

05AB1E, 9 bytes

”Ÿ™‚ï”áI∍

Input as a list of characters.

Try it online or verify all test cases.

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".

\$\endgroup\$
2
  • 1
    \$\begingroup\$ This is larger than 9 bytes with any Unicode encoding. More like 16. \$\endgroup\$ Aug 1 at 19:28
  • 4
    \$\begingroup\$ @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. \$\endgroup\$ Aug 1 at 21:22
5
\$\begingroup\$

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.

enter image description here

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

Pyth, 25 bytes

FNrZlwp@"HelloWorld"%N 10

Try it online!

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

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to Code Golf! \$\endgroup\$
    – Steffan
    Jul 31 at 19:30
4
\$\begingroup\$

C (gcc), 55 bytes

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

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ Is this a function or a full program? \$\endgroup\$ Aug 7 at 10:38
  • \$\begingroup\$ 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 \$\endgroup\$
    – c--
    Aug 7 at 15:58
  • \$\begingroup\$ @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 \$\endgroup\$
    – c--
    Aug 7 at 17:02
3
\$\begingroup\$

Retina, 27 bytes

T`p`~
Y`~`\He\l\l\oW\or\l\d

Try it online! Explanation:

T`p`~

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.

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

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ 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 \$\endgroup\$
    – Sisyphus
    Jul 31 at 23:38
  • \$\begingroup\$ @Sisyphus thanks! I didn't think to use the replacement in that position, but since it still executes before the rest, that makes sense! \$\endgroup\$ Aug 1 at 11:12
3
\$\begingroup\$

Vyxal s, 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.

Vyxal sr, 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
\$\endgroup\$
1
  • \$\begingroup\$ Steffan has a 2 bytes lesser answer. \$\endgroup\$ Aug 1 at 13:53
3
\$\begingroup\$

Knight, 23 bytes

O G*"HelloWorld"=cL P0c

Try it online!

\$\endgroup\$
0
2
+50
\$\begingroup\$

Vyxal, 5 bytes

LkhȧẎ

Try it Online!

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

Haskell, 33 bytes

($cycle "HelloWorld").take.length

Try it online!

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

Factor + sequences.repeating, 33 bytes

[ "HelloWorld"swap length cycle ]

Try it online!

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

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.

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

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
\$\endgroup\$
2
\$\begingroup\$

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!

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

PowerShell, 37 bytes

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

Try it online!

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

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!

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

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
\$\endgroup\$
2
\$\begingroup\$

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
\$\endgroup\$
1
\$\begingroup\$

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)
\$\endgroup\$
1
\$\begingroup\$

Kustom, 39 bytes

Basically just this Javascript answer.

The extra byte is for the global variable name.

$tc(rpad,"",tc(len,gv(i)),HelloWorld)$
\$\endgroup\$
1
\$\begingroup\$

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
\$\endgroup\$
7
  • \$\begingroup\$ It is a code snippet, not a full program (PS script) and not a function. Sorry. \$\endgroup\$
    – mazzy
    Aug 2 at 6:07
  • 2
    \$\begingroup\$ 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. \$\endgroup\$
    – user314159
    Aug 2 at 10:59
  • \$\begingroup\$ 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. \$\endgroup\$
    – mazzy
    Aug 2 at 12:17
  • \$\begingroup\$ 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". \$\endgroup\$
    – user314159
    Aug 2 at 14:40
1
\$\begingroup\$

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.

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

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!

\$\endgroup\$
4
  • 1
    \$\begingroup\$ 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... \$\endgroup\$ Aug 3 at 10:53
  • 2
    \$\begingroup\$ 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... \$\endgroup\$ Aug 3 at 11:00
  • 1
    \$\begingroup\$ BTW - you can easily convert to a full program using scan() instead of defining a function, although it costs a byte: Try it... \$\endgroup\$ Aug 3 at 11:11
  • \$\begingroup\$ @DominicvanEssen Thanks for the tips. I will correct this later today! \$\endgroup\$
    – qdread
    Aug 3 at 11:51
1
\$\begingroup\$

Ruby, 37, 35 bytes

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

Try it online!

-2 bytes thanks to @Steffan

\$\endgroup\$
2
  • 2
    \$\begingroup\$ 35: ->x{('HelloWorld'*l=x.size)[0...l]} \$\endgroup\$
    – Steffan
    Aug 3 at 14:35
  • \$\begingroup\$ @Steffan nice catch! thanks! \$\endgroup\$
    – game0ver
    Aug 3 at 14:55
1
\$\begingroup\$

J, 15 bytes

'HelloWorld'$~#

Try it online!

Very straightforward.

Explanation

'HelloWorld'$~#
            $~     reshape
'HelloWorld'       this string
              #    by the length of the input
\$\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.