28
\$\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\$
27
  • 11
    \$\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
    Commented Sep 3, 2020 at 4:46
  • 4
    \$\begingroup\$ Can we return a list of Hello Worlds? \$\endgroup\$
    – Adám
    Commented Sep 3, 2020 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
    Commented Sep 3, 2020 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
    Commented Sep 3, 2020 at 13:25
  • 3
    \$\begingroup\$ I never said it should print err, I said it could print Hello Worlderr or err \$\endgroup\$
    – the-cobalt
    Commented Sep 3, 2020 at 13:26

65 Answers 65

26
\$\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.

\$\endgroup\$
3
  • \$\begingroup\$ The output of Hello World is supposed to be without exclamation mark in this challenge. \$\endgroup\$ Commented Sep 3, 2020 at 8:59
  • 1
    \$\begingroup\$ I think this works, which should give 1/64 of the current score. \$\endgroup\$
    – Bubbler
    Commented Sep 3, 2020 at 9:14
  • 3
    \$\begingroup\$ Technically this would actually be a polyglot. \$\endgroup\$
    – the-cobalt
    Commented Sep 3, 2020 at 17:55
14
\$\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!

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

\$\endgroup\$
10
+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!

\$\endgroup\$
4
  • 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\$ Commented Sep 3, 2020 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\$ Commented Sep 3, 2020 at 13:35
  • \$\begingroup\$ Good point @DominicvanEssen, thank you! \$\endgroup\$
    – Cong Chen
    Commented Sep 3, 2020 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
    Commented Sep 3, 2020 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!

\$\endgroup\$
3
  • \$\begingroup\$ The table generating code is better than the actual code (JK, but seriously, nice table) \$\endgroup\$
    – the-cobalt
    Commented Sep 3, 2020 at 4:41
  • 1
    \$\begingroup\$ Do you use Gema as an awk replacement in your daily work? \$\endgroup\$
    – Jonah
    Commented Sep 3, 2020 at 4:44
  • 1
    \$\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
    Commented Sep 3, 2020 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.
\$\endgroup\$
7
  • 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\$ Commented Sep 4, 2020 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\$ Commented Sep 4, 2020 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
    Commented Sep 4, 2020 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
    Commented Sep 4, 2020 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
    Commented Sep 4, 2020 at 16:13
6
\$\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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I think the question spec calls for Hello World with an uppercase W \$\endgroup\$ Commented Sep 3, 2020 at 13:02
  • \$\begingroup\$ @cairdcoinheringaahing So it does, thanks. Corrected. \$\endgroup\$ Commented Sep 3, 2020 at 13:09
6
\$\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
\$\endgroup\$
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.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Wow, that was fast! Good job! However, I noticed that an empty program does not print err \$\endgroup\$
    – the-cobalt
    Commented Sep 3, 2020 at 3:46
  • \$\begingroup\$ Sorry, was I unclear? By "empty", I mean a program that contains zero bytes. \$\endgroup\$
    – the-cobalt
    Commented Sep 3, 2020 at 4:03
  • \$\begingroup\$ @the-cobalt You're right. But your example Python code behaves the same way. \$\endgroup\$
    – Dingus
    Commented Sep 3, 2020 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
    Commented Sep 3, 2020 at 4:05
  • \$\begingroup\$ Whoops, you're right! Let me reclarify the specs. \$\endgroup\$
    – the-cobalt
    Commented Sep 3, 2020 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
   
         
\$\endgroup\$
5
  • 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
    Commented Sep 3, 2020 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\$ Commented Sep 3, 2020 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
    Commented Sep 3, 2020 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\$ Commented Sep 3, 2020 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\$ Commented Sep 3, 2020 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'
\$\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
\$\endgroup\$
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
\$\endgroup\$
4
\$\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!

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

JavaScript 72 66 bytes

-6 bytes thanks to @Ismael Miguel

alert(/^h*$/.test(a=prompt())?a.replace(/h/g,'Hello World'):'err')
\$\endgroup\$
6
  • 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
    Commented Sep 3, 2020 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\$ Commented Sep 3, 2020 at 15:03
  • 1
    \$\begingroup\$ 65 bytes or 52 bytes as a function. \$\endgroup\$
    – Shaggy
    Commented Sep 4, 2020 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\$ Commented Sep 4, 2020 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
    Commented Sep 4, 2020 at 14:45
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
\$\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 !
\$\endgroup\$
6
  • 1
    \$\begingroup\$ I like it, but why is the 61-byte program less interesting? \$\endgroup\$ Commented Sep 3, 2020 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
    Commented Sep 3, 2020 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\$ Commented Sep 4, 2020 at 8:15
  • 1
    \$\begingroup\$ 66 bytes for the more interesting one \$\endgroup\$
    – rtpax
    Commented Sep 4, 2020 at 13:44
  • \$\begingroup\$ @rtpax this is very interesting! \$\endgroup\$
    – AZTECCO
    Commented Sep 4, 2020 at 16:47
3
\$\begingroup\$

Python 3, 52 bytes

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

Try it online!

\$\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!

\$\endgroup\$
0
3
\$\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"
\$\endgroup\$
1
  • \$\begingroup\$ 19 bytes \$\endgroup\$
    – Shaggy
    Commented Sep 3, 2020 at 7:22
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!

\$\endgroup\$
3
  • \$\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
    Commented Sep 4, 2020 at 2:50
  • \$\begingroup\$ Oh, actually, here's another byte: Test aRM'h and switch the true and false branches. \$\endgroup\$
    – DLosc
    Commented Sep 4, 2020 at 2:52
  • \$\begingroup\$ Just read the docs. Empty string is falsy, eh? \$\endgroup\$
    – Razetime
    Commented Sep 4, 2020 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!

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

Vim, 48 47 bytes

Thanks to @DLosc for -1 bytes

:g/\_$\_^\|[^h]/norm HcGerr
:s/h/Hello World/g

Try it online!

The :g command is a bit convoluted, but there's a reason for that. The [^h] part will match all non-h characters, but it won't match newlines. $ or \n will match end-of-line, which means they will match a single line without a newline. To make it match only when there are multiple lines, I used \_$\_^. This will only match newlines (\_$) that are followed by another line (\_^).

For some reason, this doesn't work properly in TIO, so programs where the only non-h characters are newlines won't error. However, this does work properly in Vim.

Explanation:

:g/    (x)     /     (y)     # If x exists, execute y:
   \_$\_^                    #  x -> An end-of-line followed by a start-of-line;
         \|[^h]              #   OR any character that isn't 'h'
                norm HcGerr  #  y -> Delete all lines, then print 'err'

:s/h/Hello World/g           # Replace every 'h' with 'Hello World'
\$\endgroup\$
1
  • \$\begingroup\$ I think HdGi can become HcG for -1 byte. \$\endgroup\$
    – DLosc
    Commented Apr 28, 2021 at 3:56
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)
\$\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

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

PowerShell, 44 bytes

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

Try it online!

Takes input by splatting

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

Befunge-93, 58 56 bytes

~:1+!#v_"h"-#v_"dlroW olleH",,,,,,,,,,,  
  @,,,@#"err"<

Try it online!

How does it work?

~                         # Read a character.

:1+!                      # Check whether we read -1 (end of input);
                          # this leaves 1 on the stack if we are at 
                          # the end of the input, else 0.

#v_                       # Exit the program if we're at the end
 @                        # end of the input.

"h"-                      # Compare the read character with the
                          # character "h", if equal, we leave 0 on
                          # the stack, otherwise, non-zero.

          #v_             # If we read anything but "h", print "err"
@,,,@#"err"<              # and exit the program.

"dlroW olleH",,,,,,,,,,,  # Print "Hello World"
\$\endgroup\$
1
  • \$\begingroup\$ You can print it all out at the end for 51 bytes \$\endgroup\$
    – Jo King
    Commented Sep 5, 2020 at 9:56
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
\$\endgroup\$
4
  • \$\begingroup\$ Can the if statement be shortened to PRINT ... IF b$="h" ELSE PRINT ...? \$\endgroup\$
    – Razetime
    Commented Sep 5, 2020 at 15:49
  • \$\begingroup\$ @Razetime I don't know any version of GFA Basic that would allow this syntax. \$\endgroup\$
    – Arnauld
    Commented Sep 6, 2020 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
    Commented Sep 6, 2020 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
    Commented Sep 6, 2020 at 8:48
2
\$\begingroup\$

Io, 63 bytes

method(:,:foreach(X,if(X!=104,"err"print-,"Hello World"print)))

Try it online!

Explanation

method(i,                         // Take input
    i foreach(X,                  // For every item:
        if(X!=104,                //     If the codepoint isn't 104:
             "err"print           //         print "err" (w/o nl)
                       -          //         Subtract "err" by the "Object" class (causes error)
             ,"Hello World"print  //     Otherwise, print "Hello World" (w/o nl)
)))
\$\endgroup\$
2
\$\begingroup\$

C (gcc), 84 80 bytes

-4 bytes thanks to ceilingcat. It's beautiful!

main(c,v)char**v;{*v[1]++-'h'?*--v[1]&&puts("err"):main(puts("Hello World"),v);}

Try it online!

Not so fancy, but I like that it's a complete program :)

"Normal" version:

#include <stdio.h>

int main(int argc, char** argv)
{
    if (*argv[1]++ - 'h')
        return *--argv[1] && puts("err");
    else
        return main(puts("Hello World"), argv);
}
\$\endgroup\$
0

Your Answer

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

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