21
\$\begingroup\$

Background

Hello is a language "written" by Anne Veling, which errors if the program does not contain only h, and will print Hello World for every h

Task

You are to write an interpreter/compiler for Hello.

Example in Python

import os
i = input("Program: ")
for a in i:
    if a != 'h':
        print("err")
        quit()
    else:
        print("Hello World")

Details

  • If the program is not only hs, it must print err or error (case-insensitive)
  • It's okay if you print "Hello World"s before your program discovers a non-h character and errors, however, the program must halt if a non-h
  • You may throw an error, as long as you print err/error before throwing, or by using a custom error builtin, like raise SyntaxError('err') in python. (basically, you have to purposefully error with err/error
  • Assume the program will not be empty
  • Output can have a trailing newline, space, or nothing to separate Hello Worlds
  • If a program has multiple lines, it should error (due to \n not being an h)
  • You can assume that input will always be ASCII 33-126 and 10 (decimal)
  • The hs are case sensitive (so H is not a valid program) instruction is found
  • This is , shortest answer wins

Test cases

Input:

h

Output:

Hello World

Input:

hhhhhh

Output:

Hello WorldHello WorldHello WorldHello WorldHello WorldHello World

(again, it doesn't matter whether it's spaces, newlines, or nothing to separate `Hello World`s

Input:

rubbish

Output:

err

Input:

huh

Output:

Hello Worlderr

Or

err

First challenge so please have mercy

\$\endgroup\$
  • 9
    \$\begingroup\$ Thank you for using the sandbox. I'd recommend leaving challenges there for at least a week, and even to advertise their imminent publishing in TNB, to lessen the risk of having to make changes after posting. \$\endgroup\$ – Adám Sep 3 at 4:46
  • 4
    \$\begingroup\$ Can we return a list of Hello Worlds? \$\endgroup\$ – Adám Sep 3 at 5:23
  • 4
    \$\begingroup\$ Currently there are 2 kind of solutions: those which reproduce the sample code (for hhxhh outputs “Hello WorldHello Worlderr”) and those which only implement the written rules (for hhxhh outputs “err”). This is not good. Please clarify and add a relevant test case. \$\endgroup\$ – manatwork Sep 3 at 12:48
  • 3
    \$\begingroup\$ @RossPresser "It's okay if you print "Hello World"s before your program discovers a non-h character and errors" \$\endgroup\$ – Adám Sep 3 at 13:25
  • 3
    \$\begingroup\$ I never said it should print err, I said it could print Hello Worlderr or err \$\endgroup\$ – the-cobalt Sep 3 at 13:26

47 Answers 47

25
\$\begingroup\$

Lenguage, \$1.42 \times 10^{122}\$ bytes

minus a lot of bytes thanks to Kevin Cruijssen and Bubbler

hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh...

This is 142099843608359281286315447494338058415442968773543757980908246691462388164856076679905341690709953072132211450166077106439 hs, which also makes it a valid Hello program, though not one you'd want to run. The original brainfuck code is 140 135 bytes:

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

Try it online!

This prints Hello World every time it sees a h through a modification of the shortest known Hello, World! program, stopping the loop and printing err if it sees anything other than a h.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ The output of Hello World is supposed to be without exclamation mark in this challenge. \$\endgroup\$ – Kevin Cruijssen Sep 3 at 8:59
  • 1
    \$\begingroup\$ I think this works, which should give 1/64 of the current score. \$\endgroup\$ – Bubbler Sep 3 at 9:14
  • 1
    \$\begingroup\$ Technically this would actually be a polyglot. \$\endgroup\$ – the-cobalt Sep 3 at 17:55
13
\$\begingroup\$

Python 3, 49 bytes

lambda s:{*s}-{'h'}and'err'or'Hello World'*len(s)

Try it online!

Python 2, 51 bytes

lambda s:s.strip('h')and'err'or'Hello World'*len(s)

Try it online!

Python 2, 51 bytes

lambda s:['err','Hello World'*len(s)]['h'+s==s+'h']

Try it online!

| improve this answer | |
\$\endgroup\$
11
\$\begingroup\$

APL (Dyalog Unicode), 32 bytes (SBCS)

Anonymous tacit prefix function.

{'h'=⍵:'Hello World'⋄-⎕←'err'}⍤0

Try it online!

{}⍤0 replace each character () with the result of applying the following lambda to it:

'h'=⍵: if the character is h:

  'Hello World' return the required phrase

 else:

  ⎕←'err' print err
  - negate it (causing an error and terminating)

| improve this answer | |
\$\endgroup\$
11
+50
\$\begingroup\$

R, 76 bytes

function(p,n=nchar(p))ifelse(p==strrep('h',n),strrep("Hello World",n),'err')

Try it online!

Should be a comment on https://codegolf.stackexchange.com/a/210520/98085 - I didn't realise you could do functions like that! Slight change to be more robust when n = 0 and to use direct comparison rather than regex. -1 byte thanks to https://codegolf.stackexchange.com/users/90265/zippymagician.

Bonus version with side-effects (like redefining subtraction) thanks to https://codegolf.stackexchange.com/users/92901/dingus.

R, 71 bytes

{`-`=strrep;function(p,n=nchar(p))`if`(p=='h'-n,'Hello world'-n,'err')}

Try it online!

| improve this answer | |
\$\endgroup\$
  • 2
    \$\begingroup\$ Welcome to the site! I see you left a space between the last comma and 'err', so you should most likely remove that. Other than that, great answer! \$\endgroup\$ – ZippyMagician Sep 3 at 12:19
  • 4
    \$\begingroup\$ This is a fantastic R golf, well done! Your 71-byter can be shortened by defining - inside the function, which also removes the 'bonus' side-effect: 69 bytes. \$\endgroup\$ – Dominic van Essen Sep 3 at 13:35
  • \$\begingroup\$ Good point @DominicvanEssen, thank you! \$\endgroup\$ – Cong Chen Sep 3 at 15:58
  • 2
    \$\begingroup\$ welcome to CCGC! You've come at the best time, R is the language of the month for September! Feel free to also join us in the chatroom, and happy golfing :-) \$\endgroup\$ – Giuseppe Sep 3 at 20:14
7
\$\begingroup\$

Gema, 23 characters

h=Hello World
?=err@end

Sample run:

bash-5.0$ echo -n 'hohoho' | gema 'h=Hello World;?=err@end'
Hello Worlderr

Gema (old version with err on empty code), 32 characters

\A\Z=err
h=Hello World
?=err@end

Try it online! / Try all test cases online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ The table generating code is better than the actual code (JK, but seriously, nice table) \$\endgroup\$ – the-cobalt Sep 3 at 4:41
  • \$\begingroup\$ Do you use Gema as an awk replacement in your daily work? \$\endgroup\$ – Jonah Sep 3 at 4:44
  • \$\begingroup\$ @Jonah, unfortunately the practical usefulness of Gema is limited by the fact that it processes a piece of input only once. For example in this code I didn't had to worry because “h” matches both templates, as immediately after the first matching template was processed, the result was written out and a new cycle started by reading fresh input. But the real life problems usually require processing a piece of input in multiple steps, which is much more suitable for sed. \$\endgroup\$ – manatwork Sep 3 at 5:13
7
\$\begingroup\$

x86-16 machine code, IBM PC DOS, 41 40 bytes

Binary:

00000000: be82 00ba 1801 b409 ac3c 0d74 0a3c 6874  .........<.t.<ht
00000010: 02b2 24cd 2174 f1c3 4865 6c6c 6f20 576f  ..$.!t..Hello Wo
00000020: 726c 6424 6572 7224                      rld$err$

Listing:

BE 0082         MOV  SI, 82H            ; SI to DOS PSP 
BA 0118         MOV  DX, OFFSET HW      ; point to 'Hello World' string 
B4 09           MOV  AH, 9              ; DOS write string function 
            CHAR_LOOP: 
AC              LODSB                   ; AL = next input byte 
3C 0D           CMP  AL, 0DH            ; is a CR (end of input string)? 
74 0A           JZ   DONE               ; if so, end 
3C 68           CMP  AL, 'h'            ; is an 'h'? 
74 02           JZ   WRITE_STR          ; if so, write Hello(s)
B2 24           MOV  DL, LOW OFFSET ER  ; otherwise, point to 'err' string 
            WRITE_STR: 
CD 21           INT  21H                ; write string to stdout 
74 F1           JZ   CHAR_LOOP          ; if 'h', keep looping 
            DONE:
C3              RET                     ; return to DOS 
            HW  DB  'Hello World$'
            ER  DB  'err$'

Standalone PC DOS executable COM program. Input via command line. This version prints Hello Worlderr if an error is in the input code.

enter image description here

And for fun (and since I did it first), this version will only print err if an error is in the code.

x86-16 machine code, IBM PC DOS, 47 45 44 bytes

Binary:

00000000: bf80 00ba 1c01 8a0d 4951 abb8 6809 f3ae  ........IQ..h...
00000010: 5974 04b2 28b1 01cd 21e2 fcc3 4865 6c6c  Yt..(...!...Hell
00000020: 6f20 576f 726c 6424 6572 7224            o World$err$

Listing:

BF 0080         MOV  DI, 80H            ; DI to DOS PSP 
BA 011C         MOV  DX, OFFSET HW      ; point to 'Hello World' string 
8A 0D           MOV  CL, BYTE PTR[DI]   ; CL = input length 
49              DEC  CX                 ; remove leading space from length 
51              PUSH CX                 ; save length for later 
AB              STOSW                   ; DI to start of command line input
B8 0968         MOV  AX, 0968H          ; AL = 'h', AH = 9 
F3/ AE          REPZ SCASB              ; search input for 'h': ZF if Hello, NZ if error
59              POP  CX                 ; restore input length 
74 04           JZ   HELLO_LOOP         ; if no error, write Hello(s) 
B2 28           MOV  DL, LOW OFFSET ER  ; otherwise, point to 'err' string 
B1 01           MOV  CL, 1              ; only show 'err' once 
            WRITE_LOOP: 
CD 21           INT  21H                ; write string to stdout 
E2 FC           LOOP WRITE_LOOP         ; loop until done 
C3              RET                     ; return to DOS 
            HW  DB  'Hello World$'
            ER  DB  'err$'

enter image description here

Props:

  • -1 byte for both thanks to @MatteoItalia for suggestion to change only the low byte on the error string pointer.
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ If you want to play dirty, you can shave 1 byte off from the second listing by changing MOV DX, OFFSET ER to MOV DL, 2AH. \$\endgroup\$ – Matteo Italia Sep 4 at 10:38
  • \$\begingroup\$ A similar trick can be done in the first one, maybe moving the first mov over dx inside the loop just for good measure (I don't remember if dx is affected by the DOS call). \$\endgroup\$ – Matteo Italia Sep 4 at 10:41
  • 1
    \$\begingroup\$ @MatteoItalia that is dirty! Though perhaps using a preprocessor operator like LOW would make it more clean. Don't see any reason it wouldn't work for the ER one. Great idea! \$\endgroup\$ – 640KB Sep 4 at 13:08
  • 1
    \$\begingroup\$ @MatteoItalia that's MASM syntax. Other assemblers may have their own similar way of doing the same I'd suspect. \$\endgroup\$ – 640KB Sep 4 at 13:59
  • 1
    \$\begingroup\$ @MatteoItalia I tried just a mov dl, offset ER with MASM but it gives as Value out of range error. Interestingly it will "correct" a mov ax, bl to mov ax, bx though, with a warning. \$\endgroup\$ – 640KB Sep 4 at 16:13
6
\$\begingroup\$

Ruby -0p, 42...35 33 bytes

The idea to use the -0p flags (instead of -n like I originally had) came from @DomHastings's Perl answer, saving 4 bytes.

$_=/[^h]/?:err:'Hello World'*~/$/

Try it online!

Reads the program from STDIN. A regex is used to check whether the program contains any character other than h. If so, print err; otherwise, print Hello World as many times as the number of characters in the program (given by ~/$/).

Using a bare regex literal as a boolean is a deprecated Perlism that (since Ruby 1.9) only works with the -n or -p flags.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Wow, that was fast! Good job! However, I noticed that an empty program does not print err \$\endgroup\$ – the-cobalt Sep 3 at 3:46
  • \$\begingroup\$ Sorry, was I unclear? By "empty", I mean a program that contains zero bytes. \$\endgroup\$ – the-cobalt Sep 3 at 4:03
  • \$\begingroup\$ @the-cobalt You're right. But your example Python code behaves the same way. \$\endgroup\$ – Dingus Sep 3 at 4:04
  • 2
    \$\begingroup\$ @the-cobalt The empty program does not contain a non-h instruction, therefore it only contains hs, whether it actually has a h in it or not \$\endgroup\$ – Jo King Sep 3 at 4:05
  • \$\begingroup\$ Whoops, you're right! Let me reclarify the specs. \$\endgroup\$ – the-cobalt Sep 3 at 4:06
5
\$\begingroup\$

05AB1E, 17 bytes

'hÃQig”Ÿ™‚ï”×ë'‰ë

Try it online!

Big thanks to @Kevin for your dictionary compression tool!

And once again, Kevin has struck and managed to shave 3 bytes from my answer! So the aforementioned thanks is to be multiplied by a massive magnitude.

Explained (old)

Ð'hÃQig”Ÿ™‚ï”и»ë"err
Ð                       # Triplicate the input. STACK = [input, input, input]
 'h                     # Push the letter 'h'. STACK = [input, input, input, 'h']
   Ã                    # Keep _only_ the letter h in the input. STACK = [input, input, input.keep('h')]
    Q                   # Compare this with the original input. STACK = [input, 1 OR 0]
     i                  # If the comparison is truthy (i.e. it's only h's):
      g                 #   Push the length of the input. STACK = [len(input)]
       ”Ÿ™‚ï”           #   Push the compressed string "Hello World". STACK = [len(input), "Hello World"]
             и»         #   Repeat that string length of input times and join upon newlines. STACK = ["\n".join("Hello World" * len(input))]
               ë        # Else:
                "err    #   Push the string "err" to the stack. STACK = [input, "err"]
                        # Implicitly output the top of the stack
   
         
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ 19 bytes by printing Error instead of err. But there's a bug with both versions: they're supposed to error when the program contains a newline. \$\endgroup\$ – Dingus Sep 3 at 5:43
  • 2
    \$\begingroup\$ @Dingus You can have multi-line input by wrapping the input in """...""". And 2 more bytes can be saved. One by removing Ð, since the input is used implicitly anyway. And the other is by changing и» to × since without separator is allowed as well. PS: I had Ù'hQ instead of 'hÃQ, but I like your approach more. :) 17 bytes \$\endgroup\$ – Kevin Cruijssen Sep 3 at 7:18
  • \$\begingroup\$ @KevinCruijssen Thanks - I didn't know about the quotes for multi-line input. All credit for the approach goes to Lyxal of course. \$\endgroup\$ – Dingus Sep 3 at 7:26
  • 1
    \$\begingroup\$ Ah, I see I screwed up the input in the 17-byter I've linked, lol.. Here the correct one. \$\endgroup\$ – Kevin Cruijssen Sep 3 at 7:26
  • 1
    \$\begingroup\$ Here also an alternative 17-byter by porting the Japt approach, which could be 15 bytes if outputting as a list of "Hello World" is allowed (which is an open question in the comments of the challenge). \$\endgroup\$ – Kevin Cruijssen Sep 3 at 7:37
5
\$\begingroup\$

Haskell (Hugs 2006), 31 bytes

mapM(\'h'->putStr"Hello World")

Pending a question to the OP r.e. "error" in a larger error message. The spec says "it must print err or error", which it does on Hugs 2006, specifically the Raskell 1.0.13 interpreter based on Hugs 2006:

> mapM(\'h'->putStr"Hello World") "huh"
Hello World
Program error: pattern match
failure: ww_v4136 'u'
| improve this answer | |
\$\endgroup\$
4
\$\begingroup\$

Arn, 24 bytes

ùÝ└ån<⁼aLw$■v&Z(#▄╗└·I╔║

Try it!

Explained

Unpacked: (${="h"})#=#&&'yt bs'^#||"err

And this is why I need to add an if else...

      (              Begin expression
        $            Filter
          {          Block with index of _
              _      Implicit
            =        Equals
              "h"    String
          }          End block
          _          Variable initialized to STDIN; implied
      )              End expression
    #                Length
  =                  Equals
      _              Implied
    #
&&                   Boolean AND
    'yt bs'        Compressed string equal to "Hello World"
  ^                  Repeated
      _              Implied
    #
||                   Boolean OR
  "err
| improve this answer | |
\$\endgroup\$
4
\$\begingroup\$

Excel, 63 bytes

=IF(SUBSTITUTE(A1,"h","")="",REPT("Hello World",LEN(A1)),"err")

SUBSTITUTE(A1,"h","")="" returns TRUE iff A1 contains nothing but h.

REPT("Hello World",LEN(A1)) repeats the string for however many characters are in A1.

=If(Substitute(~)="",REPT(~),"err") returns the repeated string if A1 contains only h and err if it contains anything else.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ I think the question spec calls for Hello World with an uppercase W \$\endgroup\$ – caird coinheringaahing Sep 3 at 13:02
  • \$\begingroup\$ @cairdcoinheringaahing So it does, thanks. Corrected. \$\endgroup\$ – Engineer Toast Sep 3 at 13:09
4
\$\begingroup\$

SNOBOL4 (CSNOBOL4), 94 bytes

	I =INPUT
	I NOTANY('h')	:S(E)
	OUTPUT =DUPL('Hello World',SIZE(I))	:(END)
E	OUTPUT ='err'
END

Try it online!

	I =INPUT					;* Read input
	I NOTANY('h')	:S(E)				;* If there is a character that's not 'h' in the input, goto E
	OUTPUT =DUPL('Hello World',SIZE(I))	:(END)	;* else print "Hello World" repeatedly and goto END
E	OUTPUT ='err'					;* print 'err'
END
| improve this answer | |
\$\endgroup\$
4
\$\begingroup\$

Jelly, 17 bytes

14 if we can print Err as a substring of the output (e.g. “½,⁾ẇṭ»€!fƑ?”h TIO).

“½,⁾ẇṭ»€“¹ṫ»fƑ?”h

Try it online!

How?

“½,⁾ẇṭ»€“¹ṫ»fƑ?”h - Main Link: program
               ”h - set right argument to 'h'
              ?   - if...
             Ƒ    - ...condition: is (program) invariant under?:
            f     -     keep only ('h's)
       €          - ...then: for each (c in program):
“½,⁾ẇṭ»           -     "Hello World"
        “¹ṫ»      - ...else: "error"
                  - implicit, smashing print
| improve this answer | |
\$\endgroup\$
4
\$\begingroup\$

flex, 76 \$\cdots\$ 55 52 bytes

%%
h puts("Hello World");
[^h] puts("err");exit(1);

Put the above code in a file called hello.l and make the interpreter with:

flex hello.l && gcc lex.yy.c -o hello -lfl

Trying it on my terminal:

> echo -n hhh|./hello.exe
Hello World
Hello World
Hello World

With newline:

> echo hhh|./hello.exe
Hello World
Hello World
Hello World
err

notice the err because of the trailing newline echo normally sends.

With non-h character:

> echo -n hhhehhh|./hello.exe
Hello World
Hello World
Hello World
err
| improve this answer | |
\$\endgroup\$
4
\$\begingroup\$

C (gcc), 71 65 bytes

f(char*p){p=*p-'h'?*p&&puts("err"):f(p+1)||!puts("Hello World");}

Try it online!

  • Thanks to @rtpax for saving 6!

f(char*p){p= - function tacking a program and returning with the eax trick, reusing p.
Calls itself recursively.
Recursion happens before program execution so if all steps are correct a false value is returned and the program is executed.
If there's an error a truthy value is returned and program is not executed at all, an error message is displayed.

*p-'h'? `...` :f(p+1)||!puts("Hello World");
 - check each character in program : if h  continue recursion and
   if result is false program do its job.
p is true  if there was an error, false instead.

 - if not h stop recursion and :
*p            - if end of program 
p  is false
&&puts("err") - if not end of program display error
p  is true.



61 58 bytes alternative less interesting solution which runs the program and stops when an error happens

f(char*p){*p&&puts(*p-'h'?"err":"Hello World")>4&&f(p+1);}
  • Saved 3 thanks to @rtpax !
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ I like it, but why is the 61-byte program less interesting? \$\endgroup\$ – Dominic van Essen Sep 3 at 19:37
  • 2
    \$\begingroup\$ @Dominic Van Essen thanks! In my opinion the 71 bytes exploits the combination of C's procedural with recursion(which feels more functional) to achieve a result where if there's any non h the program prints only an error. Nothing special.. just a recursion call before the function task and a global variable , but I like it! \$\endgroup\$ – AZTECCO Sep 3 at 19:52
  • 2
    \$\begingroup\$ Ah, I've got it: the 71-byter does extra work to only print 'err' for illegal input, but the 61-byter is lazy and prints some 'Hello World's if they come before the illegal letter. It wasn't obvious (to me) without the test case with hs before the illegal instruction. Thanks for the explanation! \$\endgroup\$ – Dominic van Essen Sep 4 at 8:15
  • 1
    \$\begingroup\$ 66 bytes for the more interesting one \$\endgroup\$ – rtpax Sep 4 at 13:44
  • \$\begingroup\$ @rtpax this is very interesting! \$\endgroup\$ – AZTECCO Sep 4 at 16:47
3
\$\begingroup\$

Python 3, 52 bytes

lambda x:(x=='h'*len(x))*len(x)*'Hello World'or'err'

Try it online!

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

Python 3, 58 bytes

lambda s:s and s=="h"*len(s)and"Hello World"*len(s)or"err"

Try it online!

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

JavaScript, 49 bytes

-4 bytes if we can throw an error instead of outputting a string.

f=([c,...a])=>c?c==`h`?`Hello World`+f(a):`err`:a

Try it online!

| improve this answer | |
\$\endgroup\$
3
\$\begingroup\$

JavaScript 72 66 bytes

-6 bytes thanks to @Ismael Miguel

alert(/^h*$/.test(a=prompt())?a.replace(/h/g,'Hello World'):'err')
| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ input is required, unless you're submitting as a function. Some rare questions allow input as variables, but that is not applicable here. Please do check codegolf.meta.stackexchange.com/questions/2447/… from more details. \$\endgroup\$ – Razetime Sep 3 at 9:39
  • 1
    \$\begingroup\$ If you want to save 1 byte, you can store /h/g into a variable. The final result would be like: a=prompt();alert(a.replace(r=/h/g,'')?'err':a.replace(r,'Hello World')). If you are willing to take a different approach, you can test if a matches /^h+$/ and then do the replacement as you have. It would look like this (66 bytes): alert(/^h+$/.test(a=prompt())?a.replace(/h/g,'Hello World'):'err'). I know it can be reduced, but I'm out of ideas. \$\endgroup\$ – Ismael Miguel Sep 3 at 15:03
  • 1
    \$\begingroup\$ 65 bytes or 52 bytes as a function. \$\endgroup\$ – Shaggy Sep 4 at 9:24
  • \$\begingroup\$ @Shaggy I've detected a possible bug on your version, and on the posted version. Your regex is /^h*$/, while the regex I've used is /^h+$/. The + is important if you want to make sure that there is at least an h, while /^h*$/ will move on even on an empty input, which may be an undesirable behaviour, as an empty program seems to be invalid. (However, the implementation provided by O.P. simply outputs nothing for an empty program) \$\endgroup\$ – Ismael Miguel Sep 4 at 14:19
  • \$\begingroup\$ @IsmaelMiguel, we don't need to handle the empty input. You could also use /[^h]/ for the same byte count and reverse the ternary. \$\endgroup\$ – Shaggy Sep 4 at 14:45
3
\$\begingroup\$

Pip, 28 27 bytes

aRM'h?"err""Hello World"X#a

-1 byte from DLosc.

If the string without h's is empty, print "Hello World" required number of times.

Otherwise, error.

This program errors on empty input as well.

Try it online!

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Yep, almost exactly my solution. One trick to save a byte: you can use M with a scalar lhs to do the equivalent of [scalar for i in iterable] in Python. Try it online! \$\endgroup\$ – DLosc Sep 4 at 2:50
  • \$\begingroup\$ Oh, actually, here's another byte: Test aRM'h and switch the true and false branches. \$\endgroup\$ – DLosc Sep 4 at 2:52
  • \$\begingroup\$ Just read the docs. Empty string is falsy, eh? \$\endgroup\$ – Razetime Sep 4 at 6:15
3
\$\begingroup\$

Python 3, 57 52 bytes

lambda a:a=='h'*len(a)and'Hello World'*len(a)or'err'

Try it online!

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

Japt, 23 19 bytes

-4 bytes thanks to @Shaggy

rh ?`r`:¡`HÁM Wld

Try it

Explanation

rh ?`...`:¡`...
   ?              // if
rh                //   input with 'h' removed
    `...`         // then "err"
         :        // else
          ¡       //   each char in input
           `...   //   replaced with "Hello World"
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

MathGolf, 23 20 bytes

'h-╛æ╖•p0{δ╕○ô 'W╕7ÿ

Try it online.

Explanation:

'h-                  '# Remove all "h" from the (implicit) input-string
   ╛                  # Pop, and if it's now truthy (thus non-empty):
    æ                 #  Use the following four characters as single code-block:
     ╖•p              #   Push compressed string "err"
        0             #   And push a 0
         {            # Either loop 0 times,
                      # or loop over each character of the (implicit) input-string:
          δ           #  Titlecase the implicitly pushed current character ("h"→"H")
           ╕○ô        #  Push compressed string "ello"
                      #  Push " "
               'W    '#  Push "W"
                 ╕7ÿ  #  Push compressed string "orld"
                      # (implicitly output the entire stack joined together as result)
| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

SimpleTemplate 0.84, 92 63 bytes

This challenge was simple, yet fun!

Simply checks if the input is just "hhh...." and outputs the text, or outputs "err" to STDOUT:

{@ifargv.0 matches"@^h+$@"M}{@eachM.0}Hello World{@/}{@else}err

The big byte saving was due to the-cobalt's comment:

Outputting to STDOUT is fine, so you could use your 63 byte version.


Ungolfed:

Below is a more readable version of the code:

{@if argv.0 matches "@^h+$@"}
    {@each argv.0 as h}
        {@echo "Hello World"}
    {@/}
{@else}
    {@echo "err"}
{@/}

You can try this on: http://sandbox.onlinephpfunctions.com/code/e35a07dfbf6b3b56c2608aa86028b395ef457129

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Outputting to STDOUT is fine, so you could use your 63 byte version. \$\endgroup\$ – the-cobalt Sep 3 at 13:38
  • \$\begingroup\$ @the-cobalt Thank you for confirming that, I've implemented it. \$\endgroup\$ – Ismael Miguel Sep 3 at 15:07
2
\$\begingroup\$

PowerShell, 44 bytes

$args|%{if($_-104){'err';exit}"Hello World"}

Try it online!

Takes input by splatting

| improve this answer | |
\$\endgroup\$
2
\$\begingroup\$

GFA Basic (Atari ST), 125 bytes

INPUT a$
FOR i=1 TO LEN(a$)
b$=MID$(a$,i,1)
IF b$="h"
PRINT "Hello World"
ELSE
PRINT "err"
EXIT IF 1
ENDIF
NEXT I
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Can the if statement be shortened to PRINT ... IF b$="h" ELSE PRINT ...? \$\endgroup\$ – Razetime Sep 5 at 15:49
  • \$\begingroup\$ @Razetime I don't know any version of GFA Basic that would allow this syntax. \$\endgroup\$ – Arnauld Sep 6 at 8:43
  • \$\begingroup\$ You can do IF b$<>"h" / PRINT "err" / EXIT IF 1 / ENDIF / PRINT "Hello World" to get rid of the ELSE. \$\endgroup\$ – Arnauld Sep 6 at 8:45
  • \$\begingroup\$ See for instance this answer of mine for some tricks to reduce the byte count (using abbreviated keywords and ending each line with CR instead of CRLF). \$\endgroup\$ – Arnauld Sep 6 at 8:48
2
\$\begingroup\$

Java 8, 65 53 bytes

s->s.matches("h+")?s.replace("h","Hello World"):"err"

-12 bytes thanks to @corvus_192.

Try it online.

Explanation:

s->                           // Method with String as both parameter and return-type
  s.matches("h+")?            //  If the input consists solely of 1 or more "h":
    s.replace("h",            //   Replace all "h" in the input
              "Hello World")  //   with "Hello World"
             :                //  Else:
              "err"           //   Return "err" instead
| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ There must be a fancy way to raise an exception here. \$\endgroup\$ – Razetime Sep 3 at 9:37
  • \$\begingroup\$ @Razetime Probably, but the challenge states to output "err" or "error", not to cause an error/exception. \$\endgroup\$ – Kevin Cruijssen Sep 3 at 9:48
  • 1
    \$\begingroup\$ I think you can use s.matches("h*") instead \$\endgroup\$ – corvus_192 Sep 8 at 10:57
1
\$\begingroup\$

Pyth, 25 bytes

?-Q\h"err"*"Hello World"l

Try it online!

Explanation

?-Q\h"err"*"Hello World"l
?                           // if
 -Q\h                       //    input with 'h' removed
     "err"                  // then "err"
          *"Hello World"l   // else "Hello World" repeated len(input) times
| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

R, 84 bytes

function(p,n=nchar(p))`if`(n-lengths(gregexpr("h",p)),"err",strrep("Hello World",n))

Try it online!

As R is the Language of the month for September 2020, let's get the ball rolling with an R answer to this challenge.
However, this is still not the shortest-possible answer in R, so I'd like to encourage other not-normally-R-golfers to have a go, too...

| improve this answer | |
\$\endgroup\$
1
\$\begingroup\$

Batch, 64 bytes

@set/ps=
@if "%s:h=%"=="" (echo %s:h=Hello World%)else echo err

Takes input on STDIN. If replacing the hs in the input results in an empty string, output the result of replacing the hs with Hello World otherwise output err.

| improve this answer | |
\$\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.