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

46 Answers 46

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, 2022 at 8:19
8
\$\begingroup\$

sed, 111 55 51 44 bytes

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

Attempt This Online!

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

Python, 39 bytes

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

Attempt This Online!

Python, 39 bytes

Alternative version proposed by mazunki:

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

Attempt This Online!

\$\endgroup\$
2
  • \$\begingroup\$ If we could somehow l=len(s) there, that'd maybe strip some bytes? lambda s:("helloworld"*(l:=len(s)))[:l] has the same lenght, not sure if there's a better way. \$\endgroup\$
    – mazunki
    Oct 29, 2022 at 21:53
  • 1
    \$\begingroup\$ The other way would be Python, 41 bytes: lambda s,l=len:('HelloWorld'*l(s))[:l(s)] but it's longer. \$\endgroup\$
    – solid.py
    Oct 30, 2022 at 8:38
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, 2022 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, 2022 at 19:28
  • 5
    \$\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, 2022 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\$
5
\$\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, 2022 at 10:38
  • \$\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, 2022 at 17:02
  • \$\begingroup\$ It is a full program. It can be compiled with cc <program_name> using any c89 compiler on a little endian machine, if you intend to run it I recommend running it as printf '%s' '<test_input>' | ./a.out, to avoid confusion with '\n' in the input \$\endgroup\$
    – c--
    Mar 9 at 14:21
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\$
    – naffetS
    Jul 31, 2022 at 19:30
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, 2022 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, 2022 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, 2022 at 13:53
3
\$\begingroup\$

Knight, 23 bytes

O G*"HelloWorld"=cL P0c

Try it online!

\$\endgroup\$
0
3
\$\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\$
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, 2022 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, 2022 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, 2022 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\$

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\$
    – naffetS
    Aug 3, 2022 at 14:35
  • \$\begingroup\$ @Steffan nice catch! thanks! \$\endgroup\$
    – game0ver
    Aug 3, 2022 at 14:55
2
\$\begingroup\$

Zsh, 26 bytes

<<<${(r:$#1::HelloWorld:)}

Attempt This Online!

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

x86‑64 machine code on Linux, 97 B

input

  • /dev/stdin connected to a pipe or terminal in cooked mode
  • possibly empty input
  • Linux zeros processor registers upon process initialization (with the obvious exception of rsp).

source code

Uses NASM – the Netwide Assembler. Overview of algorithm:

  1. Infinitely wait until data become available. (select)
  2. Query total number of Bytes immediately available for reading. (FIONREAD)
  3. Discard input. (TCIFLUSH)
  4. Integer division: Bytes that were available for reading count divided by 10.
  5. Loop: Whole 10 Byte writes of 'HelloWorld'.
  6. Write remainder of integer division Bytes.
global _start

bits 64
default rel

; These two constants rather serve as documentation:
STDIN_FILENO         equ   0
STDOUT_FILENO        equ   1
; Linux (`syscall`) system call numbers used in this program:
sys_exit             equ   60
sys_ioctl            equ   16
sys_select           equ   23
sys_write            equ   1
; `ioctl(2)` requests used:
FIONREAD             equ   0x0000541B
TCFLSH               equ   0x0000540B
; Argument to `TCFLSH` request:
TCIFLUSH             equ   0


; ==============================================================
section .text
hello_world:
    db 'Hello'
    db 'World'
; 'HelloWorld'’s length is `10`, but this is cleaner style:
hello_world_length   equ   $ - hello_world

_start:
    ; rax    rdi  rsi    rdx   r10   r8
    ; select(  1, [rsp], NULL, NULL, NULL)
    push 1                      ; bitfield with LSB set
    mov rsi, rsp                ; *readfds
    pop rdi                     ; nfds
    push rdi                    ; rsp for get_iteration_count
    mov al, sys_select
    syscall
    
get_input_length:
    ; rax   rdi           rsi       rdx
    ; ioctl(STDIN_FILENO, FIONREAD, [rsp])
    
    xor edi, edi                ; fd := 0 (STDIN_FILENO)
    xchg rsi, rdx               ; bytes available buffer
    mov si, FIONREAD            ; ioctl(2) request number
    mov al, sys_ioctl
    syscall
    
discard_input:
    ; rax   rdi           rsi     rdx
    ; ioctl(STDIN_FILENO, TCFLSH, TCIFLUSH)
    
    mov edx, edi                ; TCIFLUSH = 0 → copy zero
    mov sil, TCFLSH & 0xFF      ; TCFLSH − 0x10 = FIONREAD
    mov al, sys_ioctl
    syscall
    ; `rax` may be non-zero now, in particular −ENOTTY.
    test eax, eax               ; for dumb last char = "\n" test
    setns dil                   ; subtrahend = 0 for ENOTTY
    
get_iteration_count:
    ; Retrieve number of Bytes that were available for reading.
    pop rax
    sub eax, edi                ; subtract 1 if this is terminal
    jc exit                     ; user typed ^D (detach input)
    
    ; Load divisor.
    push hello_world_length
    pop rcx
    ; eax := number of whole writes; edx := Bytes in partial write
    div ecx
    
    ; Save Bytes in partial write for `finish_write` below.
    ; The `push rdx`/`pop rdx` pattern is just two 2 Bytes.
    push rdx
    
    ; Use `ebx` as loop counter, because `syscall` clobbers `rcx`
    ; and this does not require a REX prefix like r8 – r15 do.
    xchg eax, ebx
write:  
    ; rax   rdi            rsi          rdx
    ; write(STDOUT_FILENO, hello_world, 10)
    xchg edx, ecx
    lea rsi, [hello_world]
    mov dil, STDOUT_FILENO
    
    test ebx, ebx               ; zero _whole_ writes test
    jz finish_write             ; zero entire 10B writes
keep_writing:
    mov al, sys_write
    syscall
    dec ebx
    jnz keep_writing
    
    ; Write the remainining ≤ 9 Bytes.
finish_write:
    pop rdx
    mov al, sys_write
    syscall

exit:
    xchg ebx, edi               ; rdi := 0 (= “successful”)
    push sys_exit               ; need to wipe entire register
    pop rax                     ; because we may have jumped
    syscall                     ; here from get_iteration_count

; vim: ft=nasm:

disassembly

helloWorld.o:     file format ELF64-x86-64


Disassembly of section .text:

0000000000000000 <hello_world>:
   0:   48                      rex.W
   1:   65 6C                   gs ins byte ptr es:[rdi], dx
   3:   6C                      ins    byte ptr es:[rdi], dx
   4:   6F                      outs   dx, dword ptr ds:[rsi]
   5:   57                      push   rdi
   6:   6F                      outs   dx, dword ptr ds:[rsi]
   7:   72 6C                   jb     75 <exit + 0x1B>
   9:   64                      fs

000000000000000A <_start>:
   A:   6A 01                   push   0x1
   C:   48 89 E6                mov    rsi, rsp
   F:   5F                      pop    rdi
  10:   57                      push   rdi
  11:   B0 17                   mov    al, 0x17
  13:   0F 05                   syscall 

0000000000000015 <get_input_length>:
  15:   31 FF                   xor    edi, edi
  17:   48 87 F2                xchg   rdx, rsi
  1A:   66 BE 1B 54             mov    si, 0x541B
  1E:   B0 10                   mov    al, 0x10
  20:   0F 05                   syscall 

0000000000000022 <discard_input>:
  22:   89 FA                   mov    edx, edi
  24:   40 B6 0B                mov    sil, 0xB
  27:   B0 10                   mov    al, 0x10
  29:   0F 05                   syscall 
  2B:   85 C0                   test   eax, eax
  2D:   40 0F 99 C7             setns  dil

0000000000000031 <get_iteration_count>:
  31:   58                      pop    rax
  32:   29 F8                   sub    eax, edi
  34:   72 24                   jb     5A <exit>
  36:   6A 0A                   push   0xA
  38:   59                      pop    rcx
  39:   F7 F1                   div    ecx
  3B:   52                      push   rdx
  3C:   93                      xchg   ebx, eax

000000000000003D <write>:
  3D:   87 D1                   xchg   ecx, edx
  3F:   48 8D 35 BA FF FF FF    lea    rsi, [rip + 0XFFFFFFFFFFFFFFBA]
  46:   40 B7 01                mov    dil, 0x1
  49:   85 DB                   test   ebx, ebx
  4B:   74 08                   je     55 <finish_write>

000000000000004D <keep_writing>:
  4D:   B0 01                   mov    al, 0x1
  4F:   0F 05                   syscall 
  51:   FF CB                   dec    ebx
  53:   75 F8                   jne    4D <keep_writing>

0000000000000055 <finish_write>:
  55:   5A                      pop    rdx
  56:   B0 01                   mov    al, 0x1
  58:   0F 05                   syscall 

000000000000005A <exit>:
  5A:   87 DF                   xchg   edi, ebx
  5C:   6A 3C                   push   0x3C
  5E:   58                      pop    rax
  5F:   0F 05                   syscall 

Having the 'HelloWorld' string in the .text section is weird, but putting (read-only) data into an already/definitely existing section, i. e. .text, makes the executable file smaller. The stripped ELF64 executable file has a size of merely 440 B, not that that really mattered for code golfing.

output

  • output lacks of a trailing newline
  • HelloWorld repeating until the input’s length is reached
  • on a terminal input length − 1 accounting for a presumed terminating "\n" [even if the user actually detached from input Ctrl‑D]

limitations

  • I am not sure, but maybe the FIONREAD ioctl(2) I am utilizing is capped at 0x7FFFF000 because one read(2) can transfer at most this many Bytes? Therefore this program’s output will be limited to 2,147,479,552 Bytes accordingly.
  • At any rate, there’s a 32-bit div ecx, so a string length ≥ 232 is not handled correctly.
  • If we’re reading from a pipe, the pipe’s capacity may be the limiting factor. In pipe(7), § pipe capacity, it says the default value is 65536 B (so it can be changed). Similarly, a terminal’s input buffer may have comparable “low” dimensions. Yet these are implementation details outside of this program.
\$\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, 2022 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, 2022 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, 2022 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, 2022 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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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