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

63 Answers 63

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
\$\endgroup\$
3
  • \$\begingroup\$ There must be a fancy way to raise an exception here. \$\endgroup\$
    – Razetime
    Commented Sep 3, 2020 at 9:37
  • \$\begingroup\$ @Razetime Probably, but the challenge states to output "err" or "error", not to cause an error/exception. \$\endgroup\$ Commented Sep 3, 2020 at 9:48
  • 1
    \$\begingroup\$ I think you can use s.matches("h*") instead \$\endgroup\$
    – corvus_192
    Commented Sep 8, 2020 at 10:57
2
\$\begingroup\$

K, 38 bytes

{$[&/"h"=x;,/{"Hello World"}'x;"err"]}
  • {..x..} defines a function with implicit arg x.
  • $[cond; a; b] corresponds to a "if (cond) {a} else {b}" sentence
  • The condition &/"h"=x can be read as "((string x).map(char is "h").reduce(and))"
  • ,/{..}'xdefines a function that applies to each char of x, and catenates results.
  • {"Hello World"} is a function without args that returns string "Hello World" `

Examples

  • {$[&/"h"=x;,/{"Hello World"}'x;"err"]}"hhhh"

"Hello WorldHello WorldHello WorldHello World

  • {$[&/"h"=x;,/{"Hello World"}'x;"err"]}"hhxh"

"err"

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

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

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

Charcoal, 21 bytes

¿⁻θh¦err⭆θHello World

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

¿⁻θh

Delete all hs from the implicit input.

err

If the result is empty then output err.

Fθ

Otherwise the input only contains hs. Loop over each h.

Hello World

Output Hello World for each one.

Other options for the same byte count:

¿⁻θh¦err⭆θHello World

Replaces each h with Hello World and prints the result.

¿⁻θh¦errEθHello World

Prints each Hello World on its own line.

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

Red, 65 bytes

func[s][either"h"= unique s[replace/all s"h""Hello World"]['err]]

Try it online!

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

><>, 44 bytes

i:0(?;"dlroW olleH"oooooooo!;ooo"errh"{=?!|]

Try it Online!

Always fun when one can golf by reusing some of the code by running it backwards.

i:0(?;"rre'oodlroW olleH"o83*0l9)?.{"h"=?!']

Alternatively, for the same byte count, one can exploit the fact that "dlroW", "World" backwards, can be used to print an additional character and terminate.

\$\endgroup\$
2
  • \$\begingroup\$ I don't think printing Hello World before checking the character is allowed. The input huh should print one Hello World before printing err, not two. Also, if you could include a link to TIO for testing, that would be nice \$\endgroup\$
    – Jo King
    Commented Sep 3, 2020 at 15:15
  • \$\begingroup\$ @JoKing I figured it was allowed since "It's okay if you print "Hello World"s before your program discovers a non-h character and errors" doesn't specify the number, and we are allowed to assume the input is not empty. \$\endgroup\$ Commented Sep 3, 2020 at 16:12
1
\$\begingroup\$

Lua, 80 bytes

(...):gsub('.',load'print(...=="h"and"Hello World"or print("err")or os.exit())')

Try it online!

Not really fun...

Or, if 'err' can be a part of error message, like python example from question:

Lua, 67 bytes

(...):gsub('.',load'print(...~="h"and ("err")() or "Hello World")')

Try it online!

By calling "err", it will appear in error message.

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

Wolfram Language (Mathematica), 57 bytes

""<>If[Union@#=={"h"},"Hello World"~Table~Tr[1^#],"err"]&

Try it online!

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

Forth (gforth), 66 bytes

: f bounds do i c@ 'h - if ." err"leave then ." Hello World"loop ;

Try it online!

Code Explanation

: f                 \ start a new word definition
  bounds            \ get starting and ending address for string
  do                \ loop from starting char address to ending char address
    i c@            \ get character at current address
    'h -            \ check if not equal to "h" (save a byte by using - instead of <>)
    if              \ if character is not h
      ." err"leave  \ print "err" and exit the loop
    then            \ end if
    ." Hello World" \ print "Hello World"
  loop              \ end the loop
;                   \ end the word definition   
\$\endgroup\$
1
\$\begingroup\$

Perl 5 + -0pF, 30 bytes

Thanks to Abigail for helping let me know about a bug and providing a solution.

$_=/[^h]/?err:"Hello World"x@F

Try it online!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ This one prints "Hello World" on an input of "h\n" -- it's not clear from the description whether that's allowed. You can fix that without loss of bytes by using /[^h]/ as the pattern, and swapping the cases in ?:. Try it online \$\endgroup\$
    – Abigail
    Commented Sep 4, 2020 at 16:55
  • \$\begingroup\$ Thank you @Abigail! \$\endgroup\$ Commented Sep 4, 2020 at 17:03
1
\$\begingroup\$

Whispers v2, 100 bytes

> InputAll
> "Hello World"
> "h"
> "err"
>> 1∖3
>> Output 4
>> #1
>> 2⋅7
>> Output 8
>> If 5 6 9

Try it online!

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

Husk, 20 bytes

?*¨H◄⁰ω]!¨L¹¨Ėr¨Λ='h

Try it online!

An if statement with compressed strings using This utility

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

Vyxal, 16 bytes, Courtesy of Lyxal

\hJ≈[\h↔Lkh*|«∧↳

Try it Online!

Vyxal, 32 bytes

\hṡ¤=≈['\h=;L`Hello World`*|`err

Try it Online!

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

C (gcc) - 99 bytes, input using stdin

i;main(){char x[99];gets(x);for(;x[i];++i){if(x[i]-'h'){puts("err");break;}puts("Hello World");}}

(Like I said in my last answer to some other question) This program can only handle 99 characters, and uses the unsafe gets() function.

An alternative, also 99 bytes:

i;main(){char x[99];gets(x);for(;x[i];++i){if(x[i]-104){puts("err");break;}puts("Hello World");}}
\$\endgroup\$
1
1
\$\begingroup\$

Vyxal j, 67 bitsv1, 8.375 bytes

ƛ\h=[kH|«½F

Try it Online!

ƛ           # map the following over the input
 \h=[       # if it is equal to `h`
     kH     # push `Hello World`
       |    # else
        «½F # push the compressed string `err`
\$\endgroup\$
1
\$\begingroup\$

C++, 192 121 bytes

#include <iostream>
int main() {
    char a;
    while (true) {
        std::cout << ">> ";
        std::cin >> a;
        if (a != 'h') {
            std::cout << "err";
        }
        else {
            std::cout << "hello world\n";
        }
    }
}

Edit: Shrunken to 121 bytes

#include <iostream>
int main(){char a;while(1){std::cin>>a;if(a!='h'){std::cout<<"err";}else{std::cout<<"hello world";}}}
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome to CG&CC! We require submissions to make some effort to be competitive; try removing unnecessary whitespace, then consider checking out our tips for golfing in C++. Also consider including a link to an online interpreter, like TIO. Happy golfing! \$\endgroup\$ Commented Jun 1, 2023 at 17:51
  • \$\begingroup\$ 94 bytes \$\endgroup\$
    – ceilingcat
    Commented Jun 4, 2023 at 4:47
0
\$\begingroup\$

PHP, 72 bytes

<?=trim($a=$argv[1],'h')!=''?'err':str_repeat('Hello World',strlen($a));
\$\endgroup\$
0
\$\begingroup\$

Javascript ES6, 51 chars

s=>s.replace(/h|.+/g,m=>m=='h'?"Hello World":"err")

Runnable example:

f=s=>s.replace(/(h)|.+/g,(m,h)=>h?"Hello World":"err") // 52 chars
f=s=>s.replace(/h|.+/g,m=>m=='h'?"Hello World":"err")  // 51 chars
inp.addEventListener('input',e=>out.textContent=f(inp.value))
input { width: 100%; box-sizing: border-box; }
<input id=inp autofocus>
<output id=out></output>

\$\endgroup\$
0
\$\begingroup\$

Dart, 83 bytes

void h(p)=>print(p.contains(RegExp("[^h]"))?"err":p.replaceAll("h","Hello World"));

My first try on Dart although I'm not completely familiar with it. Maybe the call of the method can be shortend.

Explanation: simply check with a Regular Expression if there is something else than h in the input. If so print err, else replace all the h with Hello World.

Try it online!

\$\endgroup\$
0
\$\begingroup\$

AWK, 69 bytes

a=b=length($0){for(;b--;)x=x"Hello World"}$0=NR*gsub("h",c)-a?"err":x

Try it online!

The command to get a string length is pretty long in AWK, so this

a=b=length($0)

saves the values in two variables for use later. Since we're guaranteed some input, the test is always truthy and the code will execute.

{for(;b--;)x=x"Hello World"}

The body just appends copies of Hello World to x, one for each letter in the input.

$0=NR*gsub("h",c)-a?"err":x

Sets the default output $0 to err or the string of concatenated Hello World strings. The gsub("h",c)-a is truthy if number of h characters in the input matches the length of the string. The NR* multiple will sabotage the comparison if this isn't the first input line.

Well then... After reading some other entries, and specifically the one from jmizv I realized a simpler (and shorter) approach like this works.

NR*length($0)!=gsub("h","Hello World"){$0="err"}1

But that's a completely different program, so I'm going to leave the original one in place.

\$\endgroup\$
0
\$\begingroup\$

AWK, 54 bytes

BEGIN{RS="^$"}/[^h]/{$0="err"}1gsub(/h/,"Hello World")

Try it online!

BEGIN{RS="^$"}

We begin setting the Record Separator as "^$", which makes AWK read the input as a whole.

/[^h]/{$0="err"}

If there is anything different from h, the whole input is substituted by the "err" string.

1gsub(/h/,"Hello World")

This is the number 1 and the result of gsub(/h/,"Hello World") concatenated, which will be evaluated as an AWK pattern. gsub tries to find every h, and substitutes each one for a Hello World. If $0 was changed for err, gsub returns 0, hence the concatenation. Thus, It will always result true, printing $0 (simply err or a bunch of Hello World).

\$\endgroup\$
0
\$\begingroup\$

ErrLess, 43 bytes

SSQl0=2+].0g'h=1-[{SHello WorldS?c]}SerrS?.

Try it online!

SSQ        { Get one line of input }
l0=        { Is the program empty? }
2+].       { If so, halt (-1 -- True -> 1, move IP to `.`; 0 -- False -> 2, move IP past `.`) }
0g         { Pop first element from program, pushing to the stack }
'h=        { Is equal to 'h'? }

1-[{ ... } { If so, }
    SHello, WorldS? { Print "Hello World" }
    c]              { Skip 12 chars forward (loops back to start of program, skipping `SSQ`) }
            { Else }
    SerrS?          { Print "err" }
    .               { Halt }
\$\endgroup\$
0
\$\begingroup\$

Rust, 85 78 bytes

|n:&str|for c in n.chars(){if c=='h'{print!("Hello World")}else{todo!("err")}}

Try it on Rust Playground!

I tried to get clever with rust iterators and map_while, but it ended up being much more golfy to just do a boring for loop :(

Even pattern matching is longer...

todo!(err) is a macro that always panics with the message not yet implemented: err, the key difference being that todo! is 1 byte shorter than panic!, the standard panic macro.

\$\endgroup\$
0
\$\begingroup\$

Julia 0.6, 43 bytes

~=length
!x=x!="h"^~x?:err:"Hello World"^~x

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Rockstar, 84 65 bytes

listen to S
cut S
while S
say roll S's "h" and "Hello World" or e

Try it here (Code will need to be pasted in)

\$\endgroup\$
0
\$\begingroup\$

Thunno 2, 14 bytes

U'h=?{kh£}:`~Ɱ

Attempt This Online!

Explanation

U'h=?{kh£}:`~Ɱ  '# Implicit input
U                # Uniquify the input
 'h=?           '# If it equals "h":
     {   }       #   Length of input times:
      kh£        #     Print "Hello World"
                 #   No implicit output
          :      # Otherwise:
           `~Ɱ   #   Push compressed string "Error"
                 #   Implicit output
\$\endgroup\$
0
\$\begingroup\$

Here are some different approaches I tried.

Python 3.8 (pre-release), 57 bytes

lambda s:"Hello World"*(x:=s.count("h"))+"err"*(len(s)-x)

Try it online!

Python 3.8 (pre-release), 60 bytes

lambda s:"err"if(x:=s.count("h"))!=len(s)else"Hello World"*x

Try it online!

Python 3.8 (pre-release), 63 bytes

lambda s:"Hello World"*x if len(s)-(x:=s.count("h"))<1else"err"

Try it online!

Python 3.8 (pre-release), 66 bytes

lambda s:eval("'err''Hello World'*x"[(x:=len(s)-s.count("h"))+5:])

Try it online!

(Disclaimer: Does not work.)

I'm not sure if 1/0 is okay (it outputs a ZeroDivisionError) but if it is of course that would be bytes saved.

\$\endgroup\$
0
\$\begingroup\$

Uiua, 35 bytes

&p("err"|▽:"Hello World")≍⊙:↯:@h.⧻.

Test pad

Outputs to stdout for compliance with the challenge.

\$\endgroup\$

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.