title: Rolling Quine Dice

text:
# Question
Title: Rolling Quine Dice
Create a program that outputs itself.

However, if the source code is repeated n times *(meaning to concatenate a copy of the source code to the end n-1 times)*, then there should be 1/n probability outputting the original source code, a 1/n probability of outputting the source code repeated twice, a 1/n probability of outputting the source code repeated three times, ..., and a 1/n probability of outputting the source code n times.

For example, if your program is `foobar`, then it should always output exactly `foobar`. However, if you run `foobarfoobarfoobarfoobar`, then there should be a ¼ chance each of outputting `foobar`, `foobarfoobar`, `foobarfoobarfoobar` and `foobarfoobarfoobarfoobar`.

* The distribution of each possible output should be equal
* In addition to standard I/O methods applying and standard loopholes forbidden, standard quine rules apply (can't access its own source, etc.)
* This is code golf so shortest answer in bytes wins

# Answer
# Perl 5, ~~82~~ 80 bytes

```
$s=q($s=q(%s);printf"$s\n+1#",$s for 0..rand);printf"$s\n+1#",$s for 0..rand
+1#

```

Try it online! or Test suite
> 13 votes

# Answer
# Jelly, ~~24~~ 22 bytes

```
“Ṿ;ẋŻɼLX¤¤µ”Ṿ;ẋŻɼLX¤¤µ

```

Try it online!

Try it x4!

```
“Ṿ;ẋŻɼLX¤¤µ”Ṿ;ẋŻɼLX¤¤µ
“Ṿ;ẋŻɼLX¤¤µ”              String literal: Ṿ;ẋŻɼLX¤¤µ
            Ṿ             Uneval. Return “Ṿ;ẋŻɼLX¤¤µ” (with quotes)
             ;            Append the initial string. Yields the source code.
                ɼ         Apply the preceding link to the register and store the
                          result in the register.
               Ż          Prepend 0.
                          Each time Żɼ is used when the source code is repeated
                          the register's length increases by one.
                          We can't use ‘ because it closes string literals.
                 L        Length. Returns the number of times the source code has
                          been repeated up till now.
                  X       Random element. If ɼ results in n, X returns a random
                          integer between 1 and n.
                   ¤      Combines ŻɼLX as a nilad.
              ẋ           Repeat the source code a random number of times between
                          1 and n.
                    ¤     Close everything from the initial string literal as a
                          nilad.
                     µ    Start a new monadic chain. The register gets updated
                          once for time the code is repeated but only the final
                          repetition will result in output.

```
> 9 votes

# Answer
# 05AB1E, 32 bytes

```
"34çìDJ¼32ôн¾L×Ω"34çìDJ¼32ôн¾L×Ω

```

Try it online!

**Explanation**

```
"34çìDJ¼32ôн¾L×Ω"                   # push this string
                 34ç                # push a "-character
                    ì               # prepend it to the string
                     DJ             # duplicate and join the copy to the string
                       ¼            # increment the counter
                        32ô         # split the string into pieces of size 32
                           н        # take the first one
                            ¾L×     # repeat it for each in [1 ... counter]
                               Ω    # pick one at random

```
> 5 votes

# Answer
# Gol\>\<\>, 21 bytes

```
:QoaonC|P\Sx*F2ssS"
0

```

Try it online!

### Explanation:

```
:Q     |     If the top of stack is 0, skip to next |
             Top of stack is implicitly 0
        P    Increment top of stack
         \   Redirect pointer down]
0:QoaonC|P\Sx*F2ssS"  Increment for each copy of the source code
0:QoaonC|P\Sx*F2ssS"

         \   Redirect back to the right
          Sx*  Multiply the number of copies of the source code by a random number between 0 and 1
             F      Repeat that many times
              2ss   Push a double quote
                 S" Print the source code minus the quote, newline and 0
 :Q       If top of stack is not 0
   oaonC  Print the quote, a newline and a 0 to complete the source code and continue the loop
        \Sx*   Error on the * for some reason

```
> 2 votes

# Answer
# Alice, 35 bytes

```
"d3a*h-&;adddd12h&}Uh*t&w.odt,k@
 !

```

Try it online!

### Explanation

```
"

```

Like in many quines in 2D languages, this starts with a `"` that wraps around to itself and pushes the entire first line except the `"` itself.

```
d3a*h-&;

```

Adding one or more additional copies of the source code will place some implicit spaces at the end of the string literal. To make this actually a quine, we truncate the stack at 31 characters.

```
addd

```

Push a newline, then the stack height three times. The values pushed as the stack height are 32 (the space in the second line), 33 (the `!` in the second line), and 34 (the initial `"`).

```
d

```

Push the stack height again, this time as the length of the original source code (35).

```
1

```

Initialize a counter at 1. This will count the number of times the source code is repeated.

```
2h&}

```

Turn right three times in place (i.e., turn left). Each additional repetition of the source code will contribute an `h` in the same column as this `}`, thus incrementing the counter. When the IP returns to the `}`, turn right again to continue in the same direction.

```
Uh

```

Take a uniform random number from 0 to n-1, then add 1 to get the number of times to output the original source.

```
*t&w

```

Multiply by the previously pushed stack height (code length), then repeat the following that many times by pushing a return address that many times minus one.

```
.o

```

Output the top of the stack without destroying it.

```
dt,

```

Move the bottom stack entry to the top.

```
k@

```

Repeat, then terminate after the loop is finished.
> 1 votes

# Answer
# JavaScript (Node.js), 62 bytes

```
(f=a=>b=>b?f(a+.5):`(f=${f})(1)`.repeat(1+Math.random()*a))(1)

```

Try it online!
> 1 votes

# Answer
# Charcoal, 58 bytes

```
≔´θ´⎚´×´⊕´‽´Ｌ´⊞´Ｏ´υ´ω´⁺´⪫´⁺´´´≔´θ´´´´´θθ⎚×⊕‽Ｌ⊞Ｏυω⁺⪫⁺´≔θ´´θ

```

Try it online! No verbose version because the deverbosifier currently chokes on `"´"`. Mostly based on the Charcoal quine from Golf you a quine for great good!. Explanation:

```
≔´θ´⎚´×´⊕´‽´Ｌ´⊞´Ｏ´υ´ω´⁺´⪫´⁺´´´≔´θ´´´´´θθ

```

Assign the literal string `θ⎚×⊕‽Ｌ⊞Ｏυω⁺⪫⁺´≔θ´´θ` to `θ`.

Clear any previous output, so that only the last output takes effect.

```
×⊕‽Ｌ⊞Ｏυω

```

Push the empty string to the predefined array. This makes the array length equal to the number of repetitions processed so far, so take its length, take a random number the implicit exclusive range, add 1, and repeat the following string that many times.

```
⁺⪫⁺´≔θ´´θ

```

Prepend the literal string  to `θ`, then insert literal `´`s between each character, then suffix another copy of `θ`.
> 1 votes

# Answer
# Python 3.8 (pre-release), ~~118~~ 116 bytes

```
for i in(1,c:=0):
 exec(s:="from random import*;c+=i or print('for i in(1,c:=0):\\n exec(s:=%r)#'%s*randint(1,c))")#

```

Try it online!
> 0 votes

---
Tags: code-golf, random, quine
---


title: No one, please!

text:
# Question
Title: No one, please!
I absolutely hate the digit `1`. So, I need your help to convert numbers to their "proper forms".

Numbers in proper form never have two `1`s in a row. `101` is okay, but `110` is hideous.

To convert, simply skip all the improper numbers and count normally. For instance...

```
1 -> 1
2 -> 2
...
10 -> 10
11 -> 12
12 -> 13
...
108 -> 109
109 -> 120
110 -> 121
111 -> 122

```

and so on.

Your program should take an integer and output it in proper form. This is , so shortest code in bytes wins.

# Answer
> 9 votes
## Burlesque, 10 bytes

{11~\[n!}FO

Older versions:

```
ro{11~[n!}f[

ro{Sh"11"~=n!}f[

```

# Answer
> 11 votes
# Bash + GNU utils, 36

```
seq $1$1|grep -v 11|sed -n "$1{p;q}"

```

Try it Online

# Answer
> 9 votes
# Jelly, 8 bytes

```
1w11¬$#Ṫ

```

Try it online!

Almost entirely printable ASCII! Takes input from STDIN

## How it works

```
1w11¬$#Ṫ - Main link. No arguments
     $   - Group the previous 2 links into a monad f(k):
  11     -   Yield 11
 w       -   Yield 1 if 11 is a sublist of k's digit else 0
    ¬    -   Map 1 to 0 and 0 to 1
1     #  - Count up k = 1, 2, 3, ... until n integers return true under f(k)
       Ṫ - Return the last k

```

---

# Jelly, 8 bytes

```
²wÐḟ11ị@

```

Try it online!

An alternate approach, still only 8 bytes though. Relies on the assumption that the output is always less than the square of the input

## How it works

```
²wÐḟ11ị@ - Main link. Takes n on the left
²        - n²
  Ðḟ     - Filter-false the range [1, 2, ..., n²] on:
    11   -   11
 w       -   Is a sublist of the digits
      ị@ - Take the n'th value in this list

```

# Answer
> 8 votes
# JavaScript, 53 bytes

```
n=>[...Array(n*2).keys()].filter(a=>!/11/.test(a))[n]

```

Alternate (using comprehensions, same length):

```
n=>[for(i of Array(n*2).keys())if(!/11/.test(i))i][n]

```

# Answer
> 8 votes
# Perl 5, 34 Bytes

Looping a counter and changing the occasional double-one.

```
map{$i++;$i=~s/11/12/}1..pop;say$i

```

### Test

```
$ perl -M5.012 -e 'map{$i++;$i=~s/11/12/}1..pop;say$i' 111
$ 122

```

# Answer
> 7 votes
## Python 2, 50

```
lambda n:[i for i in range(n*2)if'11'not in`i`][n]

```

An anonymous function that lists the numbers not containing `11` in order, and takes the `n`th one. The off-by-one error of zero-indexing cancels with the inclusion of `0` in the list.

In theory, this will fail for sufficiently high numbers where `f(n)>2*n`, but this shouldn't happen until `n` is at least `10**50`.

---

51 bytes:

```
n=input();i=0
while n:i+=1;n-='11'not in`i`
print i

```

Counts up numbers `i` until the quota of `n` numbers without `11` is met.

A function is the same length because of the off-by-one corrections needed.

```
f=lambda n,i=0:n+1and f(n-('11'not in`i`),i+1)or~-i

```

# Answer
> 7 votes
# Pyth, ~~13~~ 11 bytes

```
e.f!}`hT`ZQ

```

Saved 2 bytes thanks to @FryAmTheEggman.

Live demo and test cases.

## 13-byte version

```
e.f!}"11"+ZkQ

```

# Answer
> 5 votes
# Python 3 74

Still need a bit of golfing.

```
n=int(input())
c=0
for x in ' '*n:
 c+=1
 while'11'in str(c):c+=1
print(c)

```

It's pretty brute force right now.

# Answer
> 5 votes
# JavaScript (ES6) 43 bytes

As an anonymous function

```
n=>eval('for(i=0;/11/.test(i)||n--;i++);i')

```

Note: the very simplest way would be 44:

```
n=>{for(i=0;/11/.test(i)||n--;i++);return i}

```

Test running the snippet below.

```
f=n=>eval('for(i=0;/11/.test(i)||n--;i++);i')

var o='',v=0,r,c;
for(r=0;r<30;r++)
{
  o += '<tr>';
  for(c=0;c<10;c++)
  {

    o += '<td>' +v + '⇨' + f(v) + '</td>';
    v++;
  }
  o += '</tr>'

}
O.innerHTML=o
```

```
<table id=O style='font-size:80%'></table>
```

# Answer
> 4 votes
# Haskell, 51 bytes

```
([x|x<-[0..],notElem('1','1')$zip=<<tail$show x]!!)

```

Usage example: `([x|x<-[0..],notElem('1','1')$zip=<<tail$show x]!!) 110` -\> `121`.

How it works:

```
[x|x<-[0..]                                   ]    -- take all x starting with 0
           ,                                       -- where
                   ('1','1')                       -- the pair of two chars '1'
            notElem                                -- is not part of
                             zip=<<tail            -- the list of pairs of neighbor elements of
                                        show x     -- the string representation of x
                                               !!  -- take nth element, where n is the parameter

```

# Answer
> 3 votes
# MUMPS, 37 bytes

```
t(i) f j=1:1 s:j'[11 k=k+1 q:k=i
    q j

```

Pretty straightforward. The only "interesting" thing here is the construct `j'[11` \- `'[` is the "does not contain" operator, so that `"abc"'["ab"` is false and `"abc"'["cd"` is true. Despite both operands of `j'[11` being numbers, MUMPS remains unperturbed. It will happily autocoerce both operands to strings and move on with its life. Hooray!

(Incidentally, if you're okay with the program never terminating, we can shorten this to 35 bytes: `t2(i) f j=1:1 s:j'[11 k=k+1 w:k=i j`)

# Answer
> 3 votes
# Brachylog, 15 bytes

```
∧{ℕ₁≜¬s11&}ᶠ↖?t

```

Try it online!

```
∧{ℕ₁≜¬s11&}ᶠ↖?t
∧{ …      }ᶠ↖?t get the N'th output from …
  ℕ₁≜             try a number, starting with 1
     ¬s11         doesn't contain 11
         &        output that number

```

# Answer
> 3 votes
# 05AB1E (legacy), ~~7~~ 6 bytes

```
µN11å≠

```

-1 byte switching to the legacy version of 05AB1E, where the index is output implicitly after a while-loop `µ`. In the new 05AB1E version we have to push the `N` explicitly, and it'll output the top of the stack after the while-loop instead (so the `N` would be `NN` or `ND`).

Try it online or verify all test cases.

**Explanation:**

```
µ       # Loop until the counter_variable is equal to the (implicit) input-integer:
        # (the counter_variable is 0 by default)
 N11å   #  Check if the 0-based loop-index `N` contains 11 as substring
     ≠  #  Invert this boolean (1→0; 0→1)
        #  (implicitly pop the top of the stack, and increase the counter_variable by
        #  1 if it's truthy)
        # (after which the index `N` is output implicitly as result)

```

# Answer
> 3 votes
# GolfScript, ~~29~~ ~~24~~ 18 bytes

```
~0\{{).`11`?)}do}*

```

Try it online!

This is my first code golf, so this is probably the least effecient way of doing things

-5 bytes by not being dumb and using the increment symbol as well as just keeping the input on the stack and decrementing instead of wasting space saving it as a variable and comparing it, probably more things I could save on

-6 bytes the loop is fixed size and I don't need the input after the loop so I can just use repeat

# Answer
> 2 votes
## Perl 5, 47 bytes

```
@_[$_]=++$i!~/11/?$i:redo for 1..<>;print$_[-1]

```

# Answer
> 2 votes
# PHP, 43 bytes

```
while(preg_match('/11/',$i)){$i++;}print$i;

```

# Answer
> 2 votes
# Perl 5 `-p`, 25 bytes

```
$\++while$\=~/11/||$_--}{

```

Try it online!

# Answer
> 2 votes
# Japt, ~~9~~ 8 bytes

```
È¥srB}iU

```

Try it

# Answer
> 2 votes
# Husk, ~~11~~ 10 bytes

*Edit: -1 byte thanks to Razetime*

```
!fö¬€ḋ3QdN

```

Try it online!

Finds index of input among natural numbers filtered to exclude those with digit-sublists that include `[1,1]`.

# Answer
> 2 votes
# Raku, 24 bytes

```
{grep(?1^/11/,^∞)[$_]}

```

Try it online!

`grep(..., ^∞)` filters the numbers from zero to infinity according to the given test object, and `[$_]` indexes into that sequence with the function argument, returning the number at that index.

`/11/` matches any number whose decimal representation contains two consecutive one digits. The sense of the match can be inverted by writing `True ^ /11/`, where `^` creates an exclusive-or junction matcher that succeeds only if exactly one of its operands succeeds. `True` will always succeed, so the overall junction can only succeed if the `/11/` fails. Finally, `True` can be expressed more concisely as `?1`, that is, `1` coerced to a Boolean.

`none(/11/)` also works as a matcher, but is longer.

# Answer
> 2 votes
# Julia 1.0, ~~44~~ 42 bytes

```
x->(r=1:9x)[.!occursin.("11",repr.(r))][x]

```

Try it online!

# Answer
> 2 votes
# AWK, 33 bytes

```
{for(;$1;)$1-=!index(++b,11)}$0=b

```

Try it online!

It works by running a loop that increments a counter blindly each iteration, but only decrements the control variable if the blind counter does NOT include the string 11. Once the loop exits, the blind counter is printed as the answer.

```
 {                            }     - code block run for each input line
  for(;$1;)                         - loop until $1 is 0
           $1-=!index(   ,11)       - decrement $1 if "b" doesn't include "11"
                      ++b           - blindly increment a counter
                               $0=b - set $0 to blind count, prints automatically

```

# Answer
> 2 votes
# Python 3, 64 bytes

```
[print(e) for e in map(str,range(int(input())+1))if not'11'in e]

```

Try it online!

# Answer
> 1 votes
# Java (JDK), 76 bytes

```
p->{int c=1,s=0;while((c+s+"").indexOf("11")>=0&&++s>0||c++<p);return p+s;};

```

Try it online!

How it works: Lambda function obviously, but mostly it uses short-circuit logic in the while loop boolean to increment the appropriate counter keeping track of the cumulative shift for each input and returning the input plus that shift.

# Answer
> 1 votes
# Excel, 64 bytes

```
=LET(x,SEQUENCE(2^20),INDEX(FILTER(x,ISERROR(FIND("11",x))),I7))

```

Works up to 1,000,579 -\> 1,048,576

# Answer
> 0 votes
# Pip, 11 bytes

```
LaW11N Ui_i

```

Attempt This Online!

### Explanation

```
             i is 0; a is first command-line argument (implicit)
La           Loop (a) times:
  W           Loop while
   11N        11 is a substring of
       Ui     i, incremented:
         _     No-op
          i  Once the loop completes, output i

```

---
Tags: code-golf, number
---


title: Implement true string addition

text:
# Question
Title: Implement true string addition
Many languages allow strings to be "added" with `+`. However this is really concatenation, a *true* addition would follow the group axioms:

* It is closed (the addition of any two strings is always a string)
* It is associative ( \\$\forall a b . (a + b) + c = a + (b + c)\\$)
* There is an identity (\\$\exists e . \forall a . a + e = a\\$)
* Every element has an inverse (\\$\forall a . ∃b . a + b = e\\$)

*(concatenation violates the 4th group axiom)*

So my task to you is to implement a true string addition, that is a function that takes two sequences of bytes representing strings and returns a third such that your function satisfies all the group axioms on sequences of bytes.

It must work on all sequence of bytes representing strings including those with null bytes.

This is so answers will be scored in bytes with less bytes being better.

# Answer
# Python 3, ~~177~~ ~~170~~ ~~163~~ 130 bytes

```
lambda a,b:s(d(a)^d(b))
def s(n,x=0,s=''):
 while n:n-=1;s+=chr(n%256);n>>=8
 return s
def d(n,c=0):
 while s(c)!=n:c+=1
 return c

```

Try it online!

-14 bytes thanks to notjagan

-33 bytes thanks to Leaky Nun (and switched endianness)

I have no business trying to golf anything in Python, but I didn't want to use Lua since this method needs large exact integers to work on reasonable length stings. (Note: the algorithm is still Really Slow when ramping up the string length.) This is mostly just to provide an answer ;)

Each string is self-inverse, and the empty string is the identity. This simply performs xor under a simple bijection between strings and non-negative integers. `s` is a helper function that computes the bijection (one way only), and `d` is the inverse.

Non-slow version (148 bytes, courtesy of Leaky Nun):

```
lambda a,b:s(d(a)^d(b))
def s(n,x=0,s=''):
 while n:n-=1;s=chr(n%256)+s;n>>=8
 return s
def d(n,c=0):
 while n:c=c*256+ord(n[0])+1;n=n[1:]
 return c

```

Try it online!

I'm going to hijack this for a group-theory primer as well.

Any right inverse is **a** left inverse: **inv(a) + a = (inv(a) + a) + e = (inv(a) + a) + (inv(a) + inv(inv(a))) = inv(a) + (a + inv(a)) + inv(inv(a)) = (inv(a) + e) + inv(inv(a)) = inv(a) + inv(inv(a)) = e**

This also means that **a** is an inverse of **inv(a)**.

Any right identity is a left identity: **e + a = (a + inv(a)) + a = a + (inv(a) + a) = a**

The identity is unique, given other identity **f**: **e = e + f = f**

If **a + x = a** then **x = e**: **x = e + x = (inv(a) + a) + x = inv(a) + (a + x) = inv(a) + a = e**

Inverses are unique, if **a + x = e** then: **x = e + x = (inv(a) + a) + x = inv(a) + (a + x) = inv(a) + e = inv(a)**

Following the proofs should make it fairly easy to construct counterexamples for proposed solutions that don't satisfy these propositions.

Here's a more natural algorithm I implemented (but didn't golf) in Lua. Maybe it will give someone an idea.

```
function string_to_list(s)
  local list_val = {}
  local pow2 = 2 ^ (math.log(#s, 2) // 1) -- // 1 to round down
  local offset = 0
  list_val.p = pow2
  while pow2 > 0 do
    list_val[pow2] = 0
    if pow2 & #s ~= 0 then
      for k = 1, pow2 do
        list_val[pow2] = 256 * list_val[pow2] + s:byte(offset + k)
      end
      list_val[pow2] = list_val[pow2] + 1
      offset = offset + pow2
    end
    pow2 = pow2 // 2
  end
  return list_val
end

function list_to_string(list_val)
  local s = ""
  local pow2 = list_val.p
  while pow2 > 0 do
    if list_val[pow2] then
      local x = list_val[pow2] % (256 ^ pow2 + 1)
      if x ~= 0 then
        x = x - 1
        local part = ""
        for k = 1, pow2 do
          part = string.char(x % 256) .. part
          x = x // 256
        end
        s = s .. part
      end
    end
    pow2 = pow2 // 2
  end
  return s
end

function list_add(list_val1, list_val2)
  local result = {}
  local pow2 = math.max(list_val1.p, list_val2.p)
  result.p = pow2
  while pow2 > 0 do
    result[pow2] = (list_val1[pow2] or 0) + (list_val2[pow2] or 0)
    pow2 = pow2 // 2
  end
  return result
end

function string_add(s1, s2)
  return list_to_string(list_add(string_to_list(s1), string_to_list(s2)))
end

```

The idea is basically to split the string based on the power-of-two components of its length, and then treat these as fields with a missing component representing zero, and each non-missing component representing numbers from 1 up to 256^n, so 256^n+1 values total. Then these representations can be added component-wise modulo 256^n+1.

Note: This Lua implementation will have numeric overflow problems for strings of sizes greater than 7. But the set of strings of length 7 or less is closed under this addition.

Try it online!
> 5 votes

# Answer
# Python 3.8, 93 bytes

```
f=lambda a,b,L=len:f(c:=a.rstrip(x:=a[-1]),x*(L(a)-L(c)^L(b)-L(d:=b.lstrip(x)))+d)if a else b

```

Try it online!

This doesn’t use base conversion or character codes at all. It works on strings over any alphabet \\$\mathcal A\\$.

We define addition by concatenation \\$a + b = ab\\$ except when \\$a\\$ ends with the same character \\$\mathtt x\\$ that starts \\$b\\$, in which case we use

$$\underbrace{\mathtt{xx\cdots x}}\_{\text{$i$ times}} + \underbrace{\mathtt{xx\cdots x}}\_{\text{$j$ times}} = \underbrace{\mathtt{xx\cdots x}}\_{\text{$i \oplus j$ times}},$$

where \\$\oplus\\$ is bitwise XOR, perhaps repeatedly if \\$i = j\\$. For example,

$$\mathtt{uuzzzzzyxx} + \mathtt{xxyzzzv} = \mathtt{uuzzzzzzv},$$

because \\$2 \oplus 2 = 0\\$, \\$1 \oplus 1 = 0\\$, and \\$5 \oplus 3 = 6\\$. The identity is the empty string, and the inverse of a string is its reversal.

This describes the free product of \\$|\mathcal A|\\$ copies of the group \\$(\mathbb N, \oplus)\\$.
> 5 votes

# Answer
# Jelly, 8 bytes

```
‘ḅ⁹^/ḃ⁹’

```

This uses a bijective mapping **φ** from byte arrays to the non-negative integers, XORs the result of applying **φ** to two input strings, then applies **φ-1** to the result.

The empty array is the neutral element and every byte arrays is its own inverse.

Try it online!

### How it works

```
‘ḅ⁹^/ḃ⁹’  Main link. Argument: [A, B] (pair of byte arrays)

‘         Increment all integers in A and B.
 ḅ⁹       Convert from base 256 to integer.
   ^/     XOR the resulting integers.
     ḃ⁹   Convert from integer to bijective base 256.
       ’  Subtract 1.

```
> 4 votes

# Answer
# Python 2, 114 bytes

```
lambda a,b:s(d(a)^d(b))
d=lambda s:s and d(s[1:])*256+ord(s[0])+1or 0
s=lambda d:d and chr(~-d%256)+s(~-d/256)or''

```

Try it online! Works by XORing the strings interpreted as little-endian bijective base 256.
> 3 votes

# Answer
# Python 2, 197 bytes

```
def n(s):
 n=s and ord(s[0])+1 or 0
 for c in s[1:]:n=n*256+ord(c)
 return(-1)**n*n/2
def f(l,r,s=""):
 i=n(l)+n(r)
 i=abs(i*2+(i<=0))
 while i>257:s=chr(i%256)+s;i/=256
 return["",chr(i-1)+s][i>0]

```

Try it online!

Turns the string into a number (reducing by charcode), negates if odd, then halves. Not as golfy as the other one, but faster :P
> 1 votes

# Answer
# JavaScript (Node.js), 119 bytes

```
a=>b=>q(p(a)^p(b));p=x=>Buffer(x,h=0).map(c=>h=h*256-~c)|h;q=(n,i=0)=>n<2**i?i?q(n>>8,i-8)+Buffer([n]):'':q(n-2**i,i+8)

```

Try it online!

xor of id of string
> 0 votes

---
Tags: code-golf, string, abstract-algebra, open-ended-function
---


# Question
Title: Find the shortest route on an ASCII road
You want to find the length shortest path between two points, on an 2d ASCII "map". The roads are made up of `+` characters, and the two endpoints are represented by `#`s (not counted in the length). This road can be arranged in any way, and any other characters can be ignored. You can assume the endpoints will always connect to each other through roads.

**Examples:**

Output: 1

```
#+#

```

Output: 5

```
   #+
+   +
++++++
   +
   #

```

Output: 8

```
++++#+++
+      +
+      +
++#+++++

```

Output: 4

```
#+++
++++
+++#

```

Output: 2

```
+++++
+   +
+#  +
+++#+
   +
 +++

```

**Undefined output:**

```
##

```

```
#   +++#
+    +

```

```
#+++#
    +
    +
    #

```

```
#++
  +

```

**Rules:**

* You can take input as a 2d array, matrix, string separated by newlines, etc.
* Output should be a number
* Can be a snippet, function, or full program
* You can represent one endpoint with a different character if necessary

# Answer
> 7 votes
# Python 3, 146 bytes

```
def f(k,*s):w=k.find('\n')+1;*p,x=k.find('#'),*s;return len(k*(x in p or'#'>(k+w*' ')[x])or('+'<k[x])*s[1:])or min(f(k,*s,x+a)for a in(-1,1,-w,w))

```

Try it online!

Uses `#` for start and `@` for end. Finds all paths along `+` and returns the shortest. Each path ends when either a space is encountered, the range is outside the box or a previous position is visited.

# Answer
> 5 votes
# Python 3 (+ numpy), 183 bytes

Assuming the input can be passed in as a numpy character array, here is a different approach. It works by calculating a distance matrix from the start point by repeatedly 'diffusing' distances along roads. Uses `'#'` for start and `'@'` for end.

```
from numpy import*
def f(A):
 B=(A!=" ")-1+(A=="#")
 for _ in nditer(A):B=pad(B,1);B+=(B==0)*stack(roll(B+(B>0),n%3-1,n%2)for n in[0,2,3,5]).max(0);B=B[1:-1,1:-1]
 print(*B[A=="@"]-2)

```

Try it online! (*11 bytes longer as the version of numpy on TIO requires an explicit mode parameter for pad, which is no longer the case*)

# Answer
> 3 votes
# JavaScript (ES7),  ~~131~~  130 bytes

Takes input as a matrix of characters. Expects `1` for the starting point and `2` for the arrival.

```
m=>(M=g=(X,Y,n)=>m.map((r,y)=>r.map((c,x)=>(X-x)**2+(Y-y)**2^1?c^1||g(x,y,r[x]=g):1/c?c^2|M>n?0:M=n:r[g(x,y,r[x]=~-n),x]=c)))()|-M

```

Try it online!

# Answer
> 2 votes
# Java 8, ~~421~~ ~~408~~ ~~403~~ ~~400~~ 351 bytes

```
int M[][],v[][],l,L;m->{int i=(l=m.length)*(L=m[0].length);for(M=m,v=new int[l][L];m[--i%l][i/l]!=65;);return f(i%l,i/l,-1>>>1,-1);}int z(int x,int y,int r,int d){return x<l&y<L&x>=0&y>=0&&M[x][y]>32&v[x][y]<1?f(x,y,r,d):r;}int f(int x,int y,int r,int d){return M[x][y]>65?r>d?d:r:z(x,y-1,z(x-1,y,z(x,y+1,z(x+1,y,r,d+=v[x][y]=1),d),d),d)+(v[x][y]=0);}

```

-57 bytes thanks to *@ceilingcat*.

Input as a matrix of bytes, with `A` as start and `B` as finish.

Try it online.

**Explanation:**

```
int M[][],                // Matrix on class-level, starting uninitialized
    v[][],                // Visited matrix on class-level, starting uninitialized
    l,L;                  // x and y dimensions on class-level, starting uninitialized

m->{                      // Method with integer-matrix as input and integer as return
 int i=(l=m.length)       //  Set `l` to the amount of rows
       *(L=m[0].length);  //  Set `L` to the amount of columns
                          //  And set `i` to the product of the two
 for(M=m,                 //  Set `M` to the input-matrix
     v=new int[l][L];     //  Create the visited-matrix filled with 0s
     m[--i%l][i/l]!=65;); //  Loop as long as the current cell doesn't contain an 'A'
 return f(                //  Start the recursive method `f` with:
   i%l,i/l,               //   The current cell as the starting x,y-coordinate
   -1>>>1,                //   Integer.MAX_VALUE as starting minimum-distance
   -1);}                  //   And -1 as amount of steps

int z(int x,int y,int r,int d){
                          // Method `z` to check whether we can travel to the given cell
  return x<l&y<L&x>=0&y>=0//  If the x,y-coordinate is within the matrix boundaries,
    &&M[x][y]>32          //  and that the current cell does NOT contain a space,
    &v[x][y]<1?           //  and we haven't visited this cell yet:
      f(x,y,r,d)          //   Return a call to the recursive method `f` with the same arguments
    :                     //  Else:
     r;}                  //   Return the row

int f(int x,int y,int r,int d){
                          // Create the recursive method `f`
  return M[x][y]>65?      //  If the current cell contains 'B':
     r>d?d:r              //   Return the minimum of the min-distance and amount of steps
    :                     //  Else:
     z(x,y-1,             //   Do a recursive `z`-call westward,
       z(x-1,y,           //   do a recursive `z`-call northward,
         z(x,y+1,         //   do a recursive `z`-call eastward,
           z(x+1,y,r,     //   do a recursive `z`-call southward,
             d+=v[x][y]=1),d),d),d)
                          //   after we've first marked the current cell as visited
     +(v[x][y]=0);}       //   And unmark the current cell as visited afterwards

```

# Answer
> 2 votes
# , 65 bytes

Takes the ASCII map with `#` and `*` for end goals.

```
1 i:~&,('*'i.~,){&,"2<@#@,((,-)#:i.3)&(*@]*[:>./|.!.0)3|' +# 'i.]

```

Try it online!

### How it works

```
3|' +# 'i.       converts streets/goal to 1, start to 2, space to 0
((,-)#:i.3)      the 4 offsets + identity
(         |.!.0) shift the matrix in the directions,
     [:>./       join them by taking the greatest number,
 *@]*            and setting spaces back to 0
<@#@,            call the above function NxM times,
                   building up the results
('*'i.~,){&,"2   flatten the results, taking the position of the goal
1 i:~&,          last place the goal was 1 (before being overwritten to 2)

```

# Answer
> 1 votes
# Jelly, ~~31~~ ~~28~~ 27 bytes

Takes input as a list of lines. Incredibly slow.

```
œẹⱮ⁾+#ŒP;€¥/Œ!ạƝ§ṀƊ€ṂƊÞḢL_2

```

Try it online!

**Comments** (slightly outdated):

```
ạƝ§=1Ạ   -- helper function: is this a connected path?
ạƝ       -- element-wise absolute differences of adjacent coordinates
  §=1Ạ   -- do all differences sum to 1?

  Ɱ⁾+#   -- call with right arguments '+' and '#'
œẹ       --   multidimensional indices of right argument in inputs
    ¥/   -- call next two functions with '+'-indices on the left and '#'-indices on the right
ŒP       --   all subsets of the '+'-indices
  ;€     --   append '#'-indices to each subset

     ƊƇ  -- filter; keep subsets where the following three functions yield a thruthy result
Œ!       --   all permutations of the subsets
  Ç€     --   call the helper function for each subset
    Ẹ    --   is any result truthy?
Ḣ        -- take first (shortest) subset
 L_2     -- length - 2

```

---
Tags: code-golf, ascii-art, path-finding
---


# Question
Title: Lean golf: List Game Lv2 (is_in_append, is_in_rev)
The title is an homage of the Natural Number Game, which is a nice interactive tutorial into proving certain properties of natural numbers in Lean.

---

The definitions used in Lv1 will be reused here. I've done some improvements:

* Now it starts with `import tactic`, which means you can freely use powerful mathlib tactics.
* I noticed that I can define the general list notation `[a, b, ..., z]` without problems.

```
import tactic
universe u
variables {A : Type u}
namespace mylist

inductive list (T : Type u) : Type u
| nil : list
| cons : T → list → list

infixr ` :: `:67 := list.cons
notation `[]` := list.nil
notation `[` l:(foldr `, ` (h t, list.cons h t) list.nil `]`) := l

def append : list A → list A → list A
| [] t := t
| (h :: s) t := h :: (append s t)
instance : has_append (list A) := ⟨@append A⟩

@[simp] lemma nil_append (s : list A) : [] ++ s = s := rfl
@[simp] lemma cons_append (x : A) (s t : list A) : (x :: s) ++ t = x :: (s ++ t) := rfl

@[simp] def rev : list A → list A
| [] := []
| (h :: t) := rev t ++ [h]

```

Now, here's a new definition we will use from now on: a membership relationship between an element and a list. It is defined recursively using two cases: A value `x` is in a list `l` if

* `x` is the head of `l`, or
* `x` is in the tail of `l`.

```
inductive is_in : A → list A → Prop
| in_hd {x : A} {l : list A} : is_in x (x :: l)
| in_tl {x y : A} {l : list A} : is_in x l → is_in x (y :: l)
open is_in

```

Now your task is to prove the following two statements: (think of these as parts of a chapter, sharing a few lemmas)

* `is_in_append`: `x` appears in `l1 ++ l2` if and only if `x` appears in `l1` or `x` appears in `l2`.
* `is_in_rev`: if `x` appears in `l`, `x` appears in `rev l`.

```
theorem is_in_append : ∀ (x : A) (l1 l2 : list A), is_in x (l1 ++ l2) ↔ is_in x l1 \/ is_in x l2 := sorry
theorem is_in_rev : ∀ (x : A) (l : list A), is_in x l → is_in x (rev l) := sorry

```

You can change the name of each statement and golf its definition, as long as its type is correct. Any kind of sidestepping is not allowed. Due to the nature of this challenge, adding imports is also not allowed (i.e. no mathlib, except for tactics).

The entire boilerplate is provided here. Your score is the length of the code between the two dashed lines, measured in bytes. The shortest code wins.

### Tips for beginners

The new beast called "inductive Prop" is a particularly hard concept to grasp. Simply put, a value of `is_in x l` contains a concrete proof that `x` appears in `l`. It is an unknown value, but we can still reason about it:

* Consider all the possible paths `is_in x l` could have been constructed (i.e. proven). This is done with `cases` tactic. When used on a hypothesis of `is_in x l`, it generates two subgoals, one assuming `in_hd` and the other assuming `in_tl`.
    + If you use `cases` on `is_in x []`, there is no way it could have been constructed (since both possibilities result in a cons), the goal is immediately closed by contradiction.
* Apply induction on the proof. It works just like induction on a nat or a list: to prove a theorem in the form of `∀ (x:A) (l:list A), is_in x l → some_prop`, you can prove it by induction on `is_in x l` and prove the "base case" `is_in x (x::l)` and "inductive case" `(is_in x l → some_prop) → is_in x (y::l) → some_prop`.

It takes some practice to see which argument (an inductive data or an inductive prop - in this challenge, `list` or `is_in`) works best with induction for a given statement. You can start by proving parts of the main statement separately as lemmas:

> ```
> lemma is_in_append_l : ∀ (x : A) (l l2 : list A), is_in x l → is_in x (l ++ l2) := sorry
> lemma is_in_append_r : ∀ (x : A) (l l2 : list A), is_in x l → is_in x (l2 ++ l) := sorry
> ```
>
> (Hint: One works best by induction on `l2`, and the other works best on `is_in x l`.)

# Answer
# Lean, 188 bytes

```
infix`~`:=is_in
def P(x:A)(l m):x~l++m↔x~l\/x~m:=by induction
l;split;repeat{safe[in_hd,in_tl];cases ᾰ<|>cases l_ih.1 ᾰ_ᾰ}def
R(x:A)(l)(i:x~l):x~rev l:=by induction i;safe[P,in_hd]

```

Try it on Lean Web Editor (warning: very slow )
> 9 votes

# Answer
# Lean, ~~254~~ ~~226~~ 221 bytes

```
infix`~`:=is_in
variables(x y:A)def D(a):x=y\/x~a↔x~y::a:=by
split;rintro(c|d);safe[in_hd,in_tl]def E:¬x~[].
def P(a b):x~a++b↔x~a\/x~b:=by
induction a;safe[<-D,E]def Q(a)(h:x~a):x~rev a:=by
induction h;safe[in_hd,P]

```

Try it on the Lean Web Editor

`P` and `Q` are the desired theorems. I reuse the `~` notation (which is normally for the `list.perm` relation) to mean the `is_in` relation, which lets us save a lot of spaces in lemma statements.

I was going for "readable" and fast-to-typecheck (Anders isn't kidding about their solution being slow!). `D` is a definition lemma for `is_in` (mathlib calls the reversed version of it `list.mem_cons_iff`; I had to reverse it to trick Lean into disambiguating `::` correctly). The `E` lemma uses the equation compiler to automatically construct a proof (mathlib calls it `list.not_mem_nil`).

Some of these tricks can shorten Anders's first solution to 217 bytes:

```
infix`~`:=is_in
attribute[simp]in_hd in_tl
def P(x:A)(l m):x~l++m↔x~l\/x~m:=by induction l;split;intro;repeat{finish<|>cases
ᾰ<|>cases l_ih.1 ᾰ_ᾰ}def R(x:A)(l)(i:x~l):x~rev l:=by induction i;simp[P];left;tauto

```

---

I want to mention that `is_in` might more conventionally be given as a recursive definition:

```
def is_in (x : A) : Π (l : list A), Prop
| [] := false
| (y::ys) := x = y ∨ is_in ys

```

Given this, there is a 150 byte solution:

```
infix`~`:=is_in
def P(x:A)(l m):x~l++m↔x~l\/x~m:=by
induction l;split;simp!;intro;safe
def Q(x:A)(l)(i:x~l):x~rev l:=by induction l;simp![P]at*;safe

```
> 2 votes

---
Tags: code-golf, lean
---


title: Hello World in Multiple Languages

text:
# Question
Title: Hello World in Multiple Languages
## Task

Create a program or a function that is valid in multiple programming languages, and when compiled/interpreted as a different language outputs "Hello, World!" in a different natural language.

For example, a valid solution might output `Hello World!` (English) when compiled and run as C, `Hallo Welt!` (German) when compiled and run as C++ and `你好世界！` (Chinese) when run as Python.

## Rules

To avoid ambiguity about the validity of an answer, below is a list of allowed versions of the phrase in several languages. The list consists of the phrase in languages for which Google Translate has a community-verified translation of the phrase (as of this writing).\*

The accuracy of these translations is debatable, but they are what this challenge will use. The printed strings must follow exactly the format below (with the exception of leading or trailing whitespace).

```
Afrikaans:    Hello Wêreld!
Albanian:     Përshendetje Botë!
Amharic:      ሰላም ልዑል!
Arabic:       مرحبا بالعالم!
Armenian:     Բարեւ աշխարհ!
Basque:       Kaixo Mundua!
Belarussian:  Прывітанне Сусвет!
Bengali:      ওহে বিশ্ব!
Bulgarian:    Здравей свят!
Catalan:      Hola món!
Chichewa:     Moni Dziko Lapansi!
Chinese:      你好世界！
Croatian:     Pozdrav svijete!
Czech:        Ahoj světe!
Danish:       Hej Verden!
Dutch:        Hallo Wereld!
English:      Hello World!
Estonian:     Tere maailm!
Finnish:      Hei maailma!
French:       Bonjour monde!
Frisian:      Hallo wrâld!
Georgian:     გამარჯობა მსოფლიო!
German:       Hallo Welt!
Greek:        Γειά σου Κόσμε!
Hausa:        Sannu Duniya!
Hebrew:       שלום עולם!
Hindi:        नमस्ते दुनिया!
Hungarian:    Helló Világ!
Icelandic:    Halló heimur!
Igbo:         Ndewo Ụwa!
Indonesian:   Halo Dunia!
Italian:      Ciao mondo!
Japanese:     こんにちは世界！
Kazakh:       Сәлем Әлем!
Khmer:        សួស្តីពិភពលោក!
Kyrgyz:       Салам дүйнө!
Lao:          ສະບາຍດີຊາວໂລກ!
Latvian:      Sveika pasaule!
Lithuanian:   Labas pasauli!
Luxemburgish: Moien Welt!
Macedonian:   Здраво свету!
Malay:        Hai dunia!
Malayalam:    ഹലോ വേൾഡ്!
Mongolian:    Сайн уу дэлхий!
Myanmar:      မင်္ဂလာပါကမ္ဘာလောက!
Nepali:       नमस्कार संसार!
Norwegian:    Hei Verden!
Pashto:       سلام نړی!
Persian:      سلام دنیا!
Polish:       Witaj świecie!
Portuguese:   Olá Mundo!
Punjabi:      ਸਤਿ ਸ੍ਰੀ ਅਕਾਲ ਦੁਨਿਆ!
Romanian:     Salut Lume!
Russian:      Привет мир!
Scots Gaelic: Hàlo a Shaoghail!
Serbian:      Здраво Свете!
Sesotho:      Lefatše Lumela!
Sinhala:      හෙලෝ වර්ල්ඩ්!
Slovenian:    Pozdravljen svet!
Spanish:      ¡Hola Mundo!         // Leading '¡' optional
Sundanese:    Halo Dunya!
Swahili:      Salamu Dunia!
Swedish:      Hej världen!
Tajik:        Салом Ҷаҳон!
Thai:         สวัสดีชาวโลก!
Turkish:      Selam Dünya!
Ukrainian:    Привіт Світ!
Uzbek:        Salom Dunyo!
Vietnamese:   Chào thế giới!
Welsh:        Helo Byd!
Xhosa:        Molo Lizwe!
Yiddish:      העלא וועלט!
Yoruba:       Mo ki O Ile Aiye!
Zulu:         Sawubona Mhlaba!

```

So there are 74 languages that can be used.

## Winning Criterion

The solution that can output the phrase in the greatest number of languages wins. In case of a tie, the shorter solution (in bytes) wins.

---

<sub>\*The translations for Malagasy and Maltese were marked community-verified, but were clearly incorrect (one was just "Hello World!" and the other "Hello dinja!", but "Hello!" alone translates to "Bongu!"). These were excluded. Also some languages (Arabic, Hebrew, Pashto, Persian and Yiddish) read from right to left on Google Translate, but when copied here they read from left to right. I hope that's okay.</sub>

# Answer
> 40 votes
## 23 Befunges, 713 bytes

The only language I really know is Befunge, so instead of multiple languages, I've just gone with multiple implementations of Befunge. I believe this is still valid under PPCG rules, which consider the language to be defined by its implementation.

```
8023/# !-1401p680p88+79*6+1p238*7+0pg90p$#v0';1';+>9%80p$$$$"ph~s"+3vv
vv_2#!>#-/\#21#:+#:>#\<0/-2*3`0:-/2g01g00p>#< 2#0 ^#1/4*:*9"9"p00***<<
>>$:2%3*-4/3g68*-70p1-0`02-3/-03-2%1+2/-70g+80g65+70g`7++3g68*-70g9`*v
0168:0>0133?45130120340200v00:<+8*+76%4p00+5/4:+-*86g3++98/2%+98g09+<<
                         @>gg#^:#+,#$"!"-#1_@
       !Helo Byd!!!!!Hai dunia!!!!Ciao mondo!!!Hallo Wereld!!!!
       !Hallo Welt!!!Halo Dunia!!!Halo Dunya!!!Bonjour monde!!!
       !Hei Verden!!!Hej Verden!!!Moien Welt!!!Labas pasauli!!!
       !Molo Lizwe!!!Salut Lume!!!Hei maailma!!Sveika pasaule!!
       !Hello World!!Salom Dunyo!!Tere maailm!!Sawubona Mhlaba!
       !Kaixo Mundua!Salamu Dunia!Sannu Duniya!!!!!!!!!!!!!!!!!

```

The frustrating thing about Befunge, is that although there is an open source reference implementation, and the language itself is dead simple, there isn't a single third-party interpreter (that I'm aware of) that exactly matches the reference behaviour. Every implementation fails in a different way.

On the plus side, this gives us the opportunity to develop a single piece of code that will produce a different result in almost every interpreter. And that's what I'm attempting in the program above.

If anyone is interested in verifying the results, I've tried to group the various implementations into categories based on how easy they are to get up and running (e.g. some people may not be able to run Windows binaries, or may not be willing to build from source, but everyone should be able to test the online interpreters).

### Online Interpreters

No installation required. It's usually just a matter of pasting in the code and clicking a button or two. But note that some of these are quite slow, so may need some time to finish executing.

**Alexios' Befunge Playground** \- *Salamu Dunia!*

Click the `Clear...` button and paste the code into the input field. Toggle the `Edit` switch to activate the interpreter, and then click the `Run` button to begin executing.
*Note that this site probably won't work in Browser's other than Chrome.*

**Befungius** \- *Molo Lizwe!*

Paste the code into the input field, making sure to overwrite the existing code. Then click the `Run` button to execute.

**David Klick's Befunge 93 Interpreter** \- *Sannu Duniya!*

Paste the code into the *Playfield* input field, and then click the `Run` button to begin executing.

**Ian Osgood's Befunge-93 Interpreter** \- *Salut Lume!*

Paste the code into the input field under the `Show` button, making sure to overwrite the `@` that is already there. Click the `Show` button to import the code, then click the `Run` button to begin executing.

**jsFunge IDE** \- *Hej Verden!*

First close the *Help* dialog, then click the *Open/Import* toolbar button (second from left), paste in the code, and click `OK`. To execute, click the *Run Mode* button (fourth from left), and then *Start* (fifth from left).

Also note that a few of the console-based interpreters are actually available on TIO, so while they aren't technically online interpreters, they can be tested online. For those that are supported (currently BEF, FBBI, MTFI and PyFunge), I've included a *Try It Online!* link next to their entry.

### Java IDEs

You'll need to have the Java run-time installed for these, but they should theoretically work on any platform. Only tested on Windows though.

**Ashley Mills' Visual Befunge Applet** \- *Moien Welt!*

This was initially an online applet which is unfortunately no longer available, but you can still download the jar and run it locally as a desktop application. You'll need to paste the code into the *Program Editor* window, then click the `Convert` button, followed by the `Run` button.

**WASABI: Wasabi's A Superbly Asinine Befunge Interpreter** \- *Hallo Welt!*

To paste in the code, right click in the top left corner of the editor window (it *must* be the very top left) and select the *Paste* menu item. Then enable the *Full Speed* check box (otherwise it'll take forever), and click the `Run!` button to begin executing.

**YABI93: Yet Another Befunge93 Interpreter** \- *Halo Dunia!*

Press `Ctrl`+`A`, `Ctrl`+`V` to paste the code into the editor window, being sure to overwrite the default source. Then click the `Start` button to begin executing.

### Windows IDEs

You'll typically need Windows for these, although in some cases there may be binaries available for other operating systems. I can't promise the code will work on other platforms though.

**BefunExec** \- *Hello World!*

You can't paste the code into the editor, so you'll first need to save it to disk somewhere. Then from the IDE, use the *File \> Open* menu to load the code from disk, and select the *Simulation \> Run/Pause* menu to run it.

**BeQunge** \- *Labas pasauli!*

Press `Ctrl`+`V` to paste in the code, and then click the *Debug* toolbar button (the blue cog) to begin executing. Once the *Debugger* panel appears, you'll want to set the *Speed* to maximum - the button to the right of the slider - otherwise it'll take forever to finish.

**Fungus** \- *Tere maailm!*

Press `Ctrl`+`V` to paste in the code, and then press `F5` to run it.

**Visbef: Visual Befunge '93 for Windows** \- *Hallo Wereld!*

You can't paste the code into the editor, so you'll first need to save it to disk somewhere. Then from the IDE, press `Ctrl`+`O` to open the file browser and load the code from disk, and press `F5` to run it.

### Windows Console Apps

Again these typically require Windows, although other platforms may be available, but not guaranteed to work.

In all cases the code will need to be saved to a file on disk and the filename passed to the interpreter as a command line parameter (*source.bf* in the example command lines given below). Also note that some of these are technically Befunge-98 interpreters, and must be run with a particular command-line option to force a Befunge-93 compatibility mode. If you don't do that, you won't get the correct results.

**BEFI: Rugxulo's Befunge-93 Interpreter** \- *Hei Verden!*

Command line: `bef93w32 -q source.bf`

**CCBI: Conforming Concurrent Befunge-98 Interpreter** \- *Sveika pasaule!*

Comand line: `ccbi --befunge93 source.bf`

**MTFI: Magus Technica Funge Interpreter** \- *Hai dunia!*

Command line: `mtfi -3 source.bf` (Try it online!)

### Python and PHP Console Apps

These require the appropriate scripting language installed - either Python or PHP.

**Befungee** \- *Helo Byd!*

Command line: `befungee.py source.bf`

**PyFunge** \- *Halo Dunya!*

Command line: `pyfunge -v 93 source.bf` (Try it online!)

**Bephunge** \- *Bonjour monde!*

Command line: `php bephunge.phps source.bf`

### Source-only Console Apps

These will need to be built from source, and that's usually easiest with a \*nix-like environment. On Windows I use the Windows Subsystem for Linux.

**BEF: Befunge-93 Reference Distribution** \- *Ciao mondo!*

Command line: `bef -q source.bf` (Try it online!)

**cfunge** \- *Sawubona Mhlaba!*

Command line: `cfunge -s 93 source.bf`

**FBBI: Flaming Bovine Befunge-98 Intepreter** \- *Hei maailma!*

Command line: `fbbi -93 source.bf` (Try it online!)

**Fungi** \- *Kaixo Mundua!*

Command line: `fungi source.bf`

**Rc/Funge-98** \- *Salom Dunyo!*

Command line: `rcfunge -93 source.bf`

### How it works

The challenge with this was finding the fewest number of tests that provided the most differentiation between interpreters. In the end it came down to four main test sequences:

1. The first is an out-of-bounds memory read from offset -1,1. In theory this should always return 32 (ASCII space), but there were actually 10 variations in practice. This test is complicated by the fact that two of the interpreters crash on an out-of-bounds read, so a couple of special-case tests (division rounding and space bridging) were required to force those two back into bounds.
2. The second sequence is a test of Befunge-98 functionality - specifically the instructions `;` and `'`. Almost all of the interpreters are Befunge-93, or are run in Befunge-93 compatibility mode, so they should just ignore those instructions. In practice there were 6 different ways in which this sequence was interpreted.
3. The third test checks the range of memory cells. In the reference interpreter, memory cells are signed 8-bit, but other implementations vary in range from 8-bit to unbounded, some signed and some unsigned. However, for the purposes of this test, we only had to distinguish between 5 of those variants.
4. The fourth and final sequence is a combination of underflow and negative division tests. There are a number of ways in which interpreters get underflow wrong, and there are at least 3 different ways in which the division and modulo instructions are implemented, but there were only 3 combinations we cared about here.

Each of these sequences returned a single number, and those four numbers were combined (via some basic arithmetic and translation tables) to produce a final value in the range 0 to 22. That value could then be used as an index to lookup the actual message to display.

# Answer
> 64 votes
# 16 languages, 1363 bytes

```
 #define ip"MemuL tulaS",,,,,,,,,,"!",@++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.@,kc"Kaixo Mundua!"v#!
#define print(A,B,C)main(){printf("Helo Byd!");}//ss                                                                          ;ooooooooooooooooooo"Moni Dziko Lapansi!"<[-
#ifdef __cplusplus//p                                                                                ;;];;
#include<cstdio>//ffffffffff?
#define print(A,B,C)int main(){printf("Halo Dunya!");}//ssp
#endif//;  [;;;;;;;;;     "!etejivs vardzoP"]
#ifdef __OBJC__//;;;;;
#define print(A,B,C)main(){printf("Hallo Welt!");}//ss
#endif//\
"""echo" "Salom Dunyo!";"exit";puts"Moien Welt!";\
__END__
#define B//\
"""#;;;;;
print(["Hai dunia!","Hej Verden!","Halo Dunia!"][(int(1>0)is 1)+~int(-1/2)*2])
#define s eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejiiiiiiiijeeeeeeeeeeeeeejiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejeejijiiiiiiiiiijeeeeeeeeeeejiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiij
#define U   !"!dlereW ollaH"<           ;
#define T@,kc"Sannu Duniya!?%?"

```

Try it online!

(use "switch languages" to change language)

* Python 3 = Halo Dunia! (Indonesian)
* Python 2 = Hej Verden! (Danish)
* Python 1 = Hai dunia! (Malay)
* C (gcc) = Helo Byd! (Welsh)
* C++ (gcc) = Halo Dunya! (Sundanese)
* Objective C (clang) = Hallo Welt! (German)
* Brainfuck = Hello World! (English, obviously)
* Befunge-93 = Salut Lume! (Romanian)
* Ruby = Moien Welt! (Luxemburgish)
* Bash = Salom Dunyo! (Uzbek)
* Befunge-98 (PyFunge) = Kaixo Mundua! (Basque)
* Unefunge-98 (PyFunge) = Sannu Duniya! (Hausa)
* Cardinal = Hallo Wereld! (Dutch)
* Alphuck = Ciao mondo! (Italian)
* \>\<\> = Moni Dziko Lapansi! (Chichewa)
* Fission = Pozdrav svijete! (Croatian)

Any golfing tips are welcome (especially on the Brainfuck)!!

Thanks to @JonathanFrech for -1 byte! Also, thanks to @ovs for -40 bytes!

## How (general ideas, I actually forgot specifics)??

The languages can be put into four groups:

* Macro: C, C++, Objective C
* Comment: Python3, Python2, Python1, Ruby, Bash
* Dimensional: Befunge-93, Befunge-98, Unefunge-98, Cardinal, \>\<\>, Fission
* Vulgar: Brainfuck, Alphuck

The Macro languages see `#` as the start of a preprocessor directive. These are used for three reasons: to house code for other groups, to distinguish among Macro languages, and to actually define a macro. All three use `//` as comment, so after that we store code for the other groups. Also, the backslash continues the comment in these languages.

The Comment languages see `#` as the start of a comment. The quirk here is the triple quotes, which distinguish the Pythons from Ruby from Bash. And to distinguish Python 1 from 2 from 3, we use a distinguishing feature in all three, along with an array of outputs. Oh yeah, there's also that `__END__`. This is used to end the code for some (can't remember exactly which ones) of the Comment languages.

The Dimensional languages are distinguished in a way that is hard to explain. One has to know the specifics of each language to figure it out. For example, `#` is only a skip in the fungeoids, while it does various different things in the other languages. The code is strewn about everywhere for these languages.

And finally, we arrive at the Vulgar languages. These two ignore everything that isn't in their set of valid characters. A balancing act has to be played with these languages and the others, as the code already contains characters in the character sets.

Edit: Wow... Somehow I only now realized Brainfuck did not seem to work, so that's fun!

# Answer
> 38 votes
# 15 languages, 532 bytes

```
# ;"!audnuM oxiaK">:#,_@R"Hej Verden!";;@,kb"Tere maailm!";# w"!amliaam ieH"ck,@oooooooooo"Hai dunia!"
`true #{puts'Hola món!'}` \
__END__
"Hola Mundo!" puts
case `ps -p$$ -oargs=` in \
b*)echo Hallo Welt!;;k*)echo Ndewo Ụwa!;;d*)echo Ciao mondo!;;z*)echo Moien Welt!;;a*)echo Hei Verden!;;esac
true;
#xx
#x%"Olá Mundo!"x
#xx+++[++[<+++>->+++<]>+++++++]<<<--.<.<--..<<---.<+++.<+.>>.>+.>.>-.<<<<+.

```

Try it online!

1. `Kaixo Mundua!` in Befunge-93
2. `Hej Verden!` in Fission
3. `Tere maailm!` in Unefunge-98
4. `Hei maailma!!` in Befunge-98
5. `Hai dunia!` in \>\<\>
6. `Hola món!` in Ruby
7. `Hola Mundo!` in GolfScript
8. `Hallo Welt!` in bash
9. `Ndewo Ụwa!` in ksh
10. `Ciao mondo!` in dash
11. `Moien Welt!` in zsh
12. `Hei Verden!` in ash
13. `Olá Mundo!` in Cardinal
14. `Hello World!` in brainfuck, courtesy of primo.
15. `Helo Byd!` in Whitespace

# Explanation

Line 1 distinguishes between five 2D esolangs:

1. `><>` reads `#` as a mirror, wraps around to the left, prints `"Hai dunia!"` and crashes (`@`). All the Funges read it as a trampoline and go right.
2. Befunge-93 ignores `;`, prints `Kaixo Mundua!` and exits (`@`).
3. The ’98 Funges jump from the first `;` to the second, then from the third `;` to the fourth. `w` is a NOP for Befunge-98, printing `Hei maailma!`.
4. But `w` reflects the instruction pointer in Unefunge-98, printing `Tere maailm!`.
5. Fission doesn’t start in the top-left corner at all. `R"Hej Verden!";` is executed. (Another instruction pointer starts from the `D` in `__END__`, but it does nothing then dies to the `;` in `true;`.)

Ruby sees ``true #{puts'Hola món!'}``, then `__END__`.

GolfScript sees ```, then `true` (NOP), then a comment; then `__END__` (NOP); then `"Hola Mundo!" puts` (this is executed); then `case` (NOP), then ``` (crashes on empty stack).

The shells see a comment, then an invocation to `true` (NOP), then invocations to unknown commands `__END__` and `"Hola Mundo!"` (which error to STDERR but execution continues), then the `case` statement which distinguishes based on the first letter of the name of the current process.

Cardinal is another 2D esolang which starts at the `%`, sending 4 IPs up, down, left, and right. They're all killed by the surrounding `x` commands, but one prints `"Olá Mundo!"` before dying.

The brainfuck code is primo’s, prefixed with `++` to counteract the dashes in `ps -p$$ -oargs=`.

The whitespace in my code is executed as the Whitespace program

```
 push 0
 push 0
label_0:
 push 0
 push 0
 drop
 drop
 push 72; printc
 push 101; printc
 push 108; printc
 push 111; printc
 push 32; printc
 push 66; printc
 push 121; printc
 push 100; printc
 push 33; printc

```

which prints `Helo Byd!`

**EDIT**: I forgot that adding `UDLR` characters breaks the Fission program, so I’ve changed the strings up to avoid these.

# Answer
> 18 votes
# 4 languages, 75 bytes

```
#"Hej Verden!"o|
print ([]and(0and"Hola món!"or"Helo Byd!")or"Hai dunia!")

```

**Python \- `Hai dunia!`**

**Perl \- `Helo Byd!`**

**Ruby \- `Hola món!`**

**Haystack \- `Hej Verden!`**

# Answer
> 14 votes
# 7 languages, 221 bytes

```
<?php echo'مرحبا بالعالم!';die?>h+#;"!dlereW ollaH"ck,@;
;echo Kaixo Mundua!;                        <@,k+4f"ሰላም ልዑል!"

Բարեւ աշխարհ!
@,k+4f"Përshendetje Botë!";XXXX;"Hello Wêreld!"

```

Since this program contains some nasty characters, here's an xxd:

```
00000000: 3c3f 7068 7020 6563 686f 27d9 85d8 b1d8  <?php echo'.....
00000010: add8 a8d8 a720 d8a8 d8a7 d984 d8b9 d8a7  ..... ..........
00000020: d984 d985 2127 3b64 6965 3f3e 682b 233b  ....!';die?>h+#;
00000030: 2221 646c 6572 6557 206f 6c6c 6148 2263  "!dlereW ollaH"c
00000040: 6b2c 403b 0a0c 3b65 6368 6f20 4b61 6978  k,@;..;echo Kaix
00000050: 6f20 4d75 6e64 7561 213b 2020 2020 2020  o Mundua !;
00000060: 2020 2020 2020 2020 2020 2020 2020 2020
00000070: 2020 3c40 2c6b 2b34 6622 e188 b0e1 888b    <@,k+4f"......
00000080: e188 9d20 e188 8de1 8b91 e188 8d21 220a  ... .........!".
00000090: 0ad4 b2d5 a1d6 80d5 a5d6 8220 d5a1 d5b7  ........... ....
000000a0: d5ad d5a1 d680 d5b0 210a 402c 6b2b 3466  ........!.@,k+4f
000000b0: 2250 c3ab 7273 6865 6e64 6574 6a65 2042  "P..rshendetje B
000000c0: 6f74 c3ab 2122 3b58 5858 583b 2248 656c  ot..!";XXXX;"Hel
000000d0: 6c6f 2057 c3aa 7265 6c64 2122 0a         lo W..reld!".

```

# Answer
> 10 votes
# 5 languages, 168 bytes

```
  //"!nedreV jeH",,,,,,,,,,,@R"Hello World!"*#x
///"!mliaam ereT">:?v; x"!dyB oleH"           %x
//               ^ o<                         x
// >`Sawubona Mhlaba!`;

```

I think 2-dimensional languages are interesting.

\>\<\> prints `Tere maailm!`
Befunge-98 prints `Hej Verden!`
Beeswax prints `Sawubona Mhlaba!`
Cardinal prints `Helo Byd!`
Fission prints `Hello World!`

Try it online! (Cardinal)

# Answer
> 8 votes
# 2 languages, 16 characters, 24 bytes

*Well, at least that's shorter than both strings.*

```
L"שלום עולם"33ç«

```

**05AB1E \- `שלום עולם!`**

**Help, WarDoq! \- `Hello World!`**

<sub>Help, WarDoq! can add two numbers and test for primes, so it is considered as a valid programming language per this meta post.</sub>

# Answer
> 7 votes
## 3 languages, ~~67~~ 62 bytes

To qualify for this bounty (100 rep).

```
x:Helo Byd!
O
y:"Hai dunia!"
u?`h;`4$'5^5D+Asi:^:E+IvIvAB*vhm,

```

**Add++:** Try it online!

**Foo:** Try it online!

**Somme:** Try it online!

## Explanation

### Add++

Add++ sees:

```
x:Helo Byd!
O

```

"Output `x`'s string"

```
y:"Hai dunia!"

```

"Set y to a different string"

```
u?`h;`4$'5^5D+Asi:^:E+IvIvAB*vhm,

```

"idk something weird, I'll error out"

### Foo

Foo sees:

```
x:Helo Byd!
O
y:"Hai dunia!"

```

"Oo, quotes, I'll output those."

```
u?`h;`4$'5^5D+Asi:^:E+IvIvAB*vhm,

```

"Uh... something about a mode? Idk, I'll error out."

### Somme

Somme sees, well, this:

```
8s+vi:4+vhIvE-Asi:^:E+IvIvAB*vhm,

```

Every column is converted to code points, then 32 is subtracted from them, then each is taken modulo 95. This corresponds to these characters, which print, "Hei Verden!"

# Answer
> 6 votes
# 4 languages, 138 bytes

```
''' '/*' '''
print(["Bonjour monde!","Hei maailma!","Hallo Wereld!"][((int(not 0)is 1)+2*int(1/2==0))-1])
''' '*/print("Hallo Welt!")' '''

```

Try it online!

Py1, Py2, Py3, Proton; thanks to Mr. Xcoder; translated from Zacharý's answer

# Answer
> 5 votes
# 4 languages, 115 bytes

```
print ((("b" + "0" == 0)and eval('"Hallo Wereld!"'))or(0 and"Hello World!"or(1/2and"Hei Verden!"or"Hej Verden!")));

```

Perl 5 gives `Hallo Wereld!` \- TIO

Ruby gives `Hello World!` \- TIO

Python 2 gives `Hej Verden!` \- TIO

Python 3 gives `Hei Verden!` \- TIO

# Answer
> 5 votes
# Four Languages, a whopping 650 bytes

```
//iiciccepepceaiiiaiaiaicccsascciijceeeeeejccijjccjceaajaajcccjeeejaajaaijcccej
//[
/*
GOTO end
*/
//pis
//p
//p
//\u000Apublic class Main{public static void main(String[]a){System.out.print("Salut Lume!");}}
/*
lblend
print Hola Mundo!
//s
*/
//]
//s
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++++++++++++++++++++++++++++++++++++++.--------.++++++++++++++.-------------------------------------------------------------------------------.+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.++.-.----------.+++++++++++.------------------------------------------------------------------------------.

```

Java gives "Salut Lume!" Try it!

S.I.L.O.S gives "Hola Mundo" Try it!

Brainfuck gives "Ciao mondo!" Try it!

(The alphuck code is modified from the Esolangs page on Alphuck)

Alphuck gives "Hello World!" Try it!

The line beginning \u000A is the Java code. The code on line one is the Alphuck code, which will ignore the rest of the code (as long as "p" and "s" are balanced. The relevant line for SIL/S.I.L.O.S is "print Hola Mundo", and the brainfuck code is at the end and will ignore the rest of the code.

# Answer
> 5 votes
# 5 languages, 213 bytes

I decided to try and write a small answer myself.

```
#include<stdio.h>
#define hint(x)int main(){auto i=.5;puts(i?"Hallo Welt!":"Hei maailma!");}
#define R "Pozdrav svijete!";
#if 0
hint=print
goto=len
s="Tere maailm!"
goto("endif")
s="Hallo Wereld!";
#endif
hint(s)

```

**Languages:**

```
C:                                       Hei maailma!      (Finnish)
C++:                                     Hallo Welt!       (German)
Python 3:                                Hallo Wereld!     (Dutch)
Operation Flashpoint scripting language: Tere maailm!      (Estonian)
Fission:                                 Pozdrav svijete!  (Croatian)

```

**C and C++ see the code as:**

```
#include<stdio.h>
#define hint(x)int main(){auto i=.5;puts(i?"Hallo Welt!":"Hei maailma!");}
#define R "Pozdrav svijete!"; // Unused macro
hint(s)

```

`auto i=.5;` is (in effect) equal to `int i=0;` in C, but equal to `double i=0.5;` in C++.

Try it online! (as C)

Try it online! (as C++)

**Python 3 sees the code as:**

```
hint=print
goto=len
s="Tere maailm!"
goto("endif")         # Calculate string length and discard the result.
s="Hallo Wereld!"
hint(s)

```

Try it online!

**OFP scripting language sees:**

```
; (A semicolon at the beginning of a line comments the line in a script.)

; Four labels with strange names.
#include<stdio.h>
#define hint(x)int main(){auto i=.5;puts(i?"Hallo Welt!":"Hei maailma!");}
#define R "Pozdrav svijete!";
#if 0

; Assign a null value to "hint", no practical effect. Same for "goto".
hint=print
goto=len

; Assign the string to variable "s".
; I would like to have used the Czech phrase for OFP (because it's a Czech game),
; but it didn't recognize the 'ě' and printed a '?' instead.
s="Tere maailm!"

; Jump to label "endif".
goto("endif")

; This reassignment of "s" gets skipped.
s="Hallo Wereld!";

; Declare a label called "endif".
#endif

; Print the string "s".
hint(s)

```

**Fission sees:**

```
R "Pozdrav svijete!";

```

Try it online!

# Answer
> 4 votes
## 3 languages, ~~184~~ 181 bytes

Only works once - you have to clear the list to run it again.

```
when gf clicked
add<[]=[]>to[c v
if<(join(item(1 v)of[c v])[d])=[1d
say[Helo Byd!
else
repeat(300000
add[]to[c v
end
if<(length of[c v])>[250000
say[Hello world!
else
say[Hai dunia!

```

Scratch 1.4: `Helo Byd!`

Scratch 2.0: `Hello world!`

Scratch 3.0 beta as of the time of this answer: `Hai dunia!`

## Explanation

In Scratch 1.4, adding a boolean to a list adds `1` or `0`, but in 2.0 and up it adds `true` or `false`, but when checking if the item is equal to `1` with \<\[\]=\[\]\>, it will return true if the item is either `1` or `true`, so we add another letter to it and check that.

In Scratch 3.0, lists have a maximum size of 200,000 items, so we just add a bunch of items and see if the list is that long.

# Answer
> 3 votes
# 17 languages, 1043 bytes

```
'abddef'*((1<2)//2);''';;;;`Hai dunia!`,#d((A{[                                      ;"!odnom oaiC"S<       v<    v\
*'');typeof Buffer<'g'?console.log(`Sveika pasaule!`):print(`Tere maailm!`)+`//#@,,,,,,,,,,,<     v       v'<|-8y2< @@@@@@@
$ 'main'                                  //       @,,,,,,,,,,,,,"Kaixo Mundua!"<v          ^"Molo Lizwe!"<         """""""
 \-[Labas pasauli!]o-#`//%"Hei maailma!"x;                                      |<+1$Y            <                 Hlowrl!
// #                                             @,,,,,,,,,,,,,,"Bonjour monde!"< @,,,,,,,,,,,"Hei Verden!"^'<      al eed"
//#                                                                              >o<'Salom Dunyo!'~~^?@001~~~~~~~~~\""""""
//#''';print(1/2 and 'Moien Welt!' or 'Salamu Dunia!')#){{i                                      }ddd}iic{iii}dc{i}dddciiic{{d}ii}ic{iii}iiiic{iiiii}iiiiic{dd}dc{{d}iii}iiic}ddddddddddddddddddddddddddddddddd\M(\o)\i\e\n\ \W\e\l\t\!]+[+[<<<+>>>>]+<-<-<<<+<++]<<.<++.<++..+++.<<++<---.>>.>.+++.------.>-.>>--.

```

Four Befung(i/es/en), two Pythons, two Javascripts, two \>\<\>es and a bunch of other random esolangs. This is a horribly ungolfed mess, but I'm proud of it.

Gol\>\<\> prints `Ciao mondo!`

\>\<\> prints `Salom Dunyo!`

Python 2 prints `Salamu Dunia!`

Python 3 prints `Sawubona Mhlaba!`

Javascript (V8) prints `Tere maailm!`

Vyxal prints `Hai dunia!`

Deadfish~ prints `Helo Byd!`

Befunge-93 prints `Molo Lizwe!`

Befunge-96 prints `Kaixo Mundua!`

Befunge-97 prints `Bonjour monde!`

Befunge-98 prints `Hei Verden!`

Splinter prints `Moien Welt!`

Rail prints `Labas pasauli!`

Javascript (Node.js) prints `Sveika pasaule!`

Brainfuck prints `Hello World!`

Cascade prints `Hallo wereld!`

Cardinal prints `Hei maailma!`

# Answer
> 2 votes
# 3 languages, 61 bytes

```
;“,ḷṅḳȦ»Ḋḷ“
x:Hai dunia!
O
y:"Helo Byd!"
;”

```

Add++ outputs `Hai dunia!`

Jelly outputs `Hello World!`

Foo outputs `Helo Byd!`

Just because I set the bounty doesn't mean I can't take part :D (ab)uses the brilliant string setting trick that Conor found for Add++

## How it works

### Add++

```
;“,ḷṅḳȦ»Ḋḷ“     ; A comment. This does nothing
x:Hai dunia!    ; Set the x accumulator to the string "Hai dunia!"
O               ; Output x
y:"Helo Byd!"   ; Set the y accumulator to the string "Helo Byd!"
;”              ; Another comment

```

### Jelly

Comments in Jelly can be formed with the syntax `ḷ“comment”`, which is how the Add++ and Foo code is ignored. The code that is actually executed by Jelly is

```
;“,ḷṅḳȦ»Ḋ - Main link. Arguments: None
 “,ḷṅḳȦ»  - Yield the string "Hello World!"
;         - Append 0, yielding "0Hello World!"
        Ḋ - Remove the first character, yielding "Hello World!"

```

### Foo

Foo ignores all characters here aside from `"Helo Byd!"`, which, as it's in quotes, is outputted.

# Answer
> 2 votes
**3 Languages, 274 Bytes**

```
#define b++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+>
#include<stdio.h>
#define p(x)int main(){printf("नमस्ते दुनिया!");}
#if 0
p=print
goto=len
goto("endif")
s="Helo Byd!";
#endif
p(s)

```

C:`नमस्ते दुनिया!`

Python: `Helo Byd!`

Brainfuck: `Hello World!`

Try it online!

---
Tags: code-challenge, polyglot, hello-world, unicode, rosetta-stone
---


title: Write a C / C++ Polyglot

text:
# Question
Title: Write a C / C++ Polyglot
This challenge's concept is pretty simple. All you have to do is write a program that will compile as both valid C and valid C++! Well, there are some catches. **The program must behave differently when compiled in each language.** The program must have different output for each language in order to be considered "behaving differently".

## Rules

* The program must be both valid C and C++
* The program must have different outputs based on the language it was compiled in.
* `#ifdef __cplusplus` or other "easy" preprocessor tricks are discouraged! (Other preprocessor operations are perfectly fine, though.)
* Try not to make it look completely obvious that the program does something different.

This is a , so whoever has the most interesting and surprising solution wins. Have fun!

## Example:

I created my own program to see if this was even possible to do with out `#ifdef` tricks:

```
#include <stdio.h>
#include <string.h>

char *m="C++ rules!";

int t[11]={0,0,0,0,1,-1,-3,9,-8,82,0};

char tr(char c,int i)
{
    return c+((sizeof('!')+1)&1)*t[i];
}

int main()
{
    int i = 0;
    for(;i<strlen(m);i++)
    {
        printf("%c",tr(m[i],i));
    }
    printf("\n");
    return 0;
}

```

This program outputs `C++ rules!` when compiled in C++ and `C++ stinks` when compiled in C.

**Explanation:**

> What causes the difference between languages is the `tr()` function. It takes advantage of one of the differences between C and C++, specifically, how char literals are treated. In C, they are treated as integers, so `sizeof('!')` returns 4, as opposed to 1 in C++. The `((...+1)&1)` part is just part of a simple bitwise operation that will return 1 if `sizeof('!')` returns 4, and 0 if it returns 1. That resulting number is multiplied by the ints in array `t` and then that product is finally added to the specific character being transformed. In C++ the product will always be zero, so the string `C++ rules!` remains unchanged. In C, the product will always be the value in `t`, and so the string changes to `C++ stinks`.

# Answer
# Is the cake a lie?

As there has been much debate over whether the cake is or is not a lie, I wrote this program to answer this contentious question.

```
#include <stdio.h>

// checks if two things are equal
#define EQUALS(a,b) (sizeof(a)==sizeof(b))

struct Cake{int Pie;}; // the cake is a pie!
typedef struct Cake Lie;
main(){
    struct CakeBox{
        struct Cake{ // the cake contains lies!
            Lie Lies[2];
        };
    };
    typedef struct Cake Cake;

    printf("The cake is ");
    if(EQUALS(Cake, Lie)){
        printf("a LIE!\n");
    }else{
        printf("..not a lie?\n");
    }
    return 0;
}

```

What will the outcome be?

C:

> `The cake is ..not a lie?`

C++:

> `The cake is a LIE!`
> 20 votes

# Answer
## Just some bools

```
#include <stdio.h>

int test(bool)
  {
  return sizeof(bool) == sizeof(int);
  }

int main(void)
  {
  puts(test(0) ? "C" : "C++");
  return 0;
  }
```

http://codepad.org/dPFou20W
http://codepad.org/Ko6K2JBH
> 10 votes

# Answer
I could have done this with a 3 line program but then it would be obvious why it produces different results for C and C++. So instead I started writing a bigger program with some stegonography which gets different results in C and C++...

```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct product
{
    int quantity;
    char name[20];
    char desc[80];
};

struct _customer
{
    char name[80];
    struct product *products;
} customer;

int main(int argc, char *argv[])
{

struct shipment
{
    char tracking_number[40];
    int quantity;
    struct product { int model; int serial; } sku;
};

struct _supplier
{
    char name[80];
    struct shipment *shipments;
} supplier;

/* now read the command line and allocate all the space we need */

if(argc<5)
{
    printf("Usage: %s <supplier name> <# of shipments> <customer name> <# of products> ",argv[0]);
    exit(1);
}

strcpy(supplier.name,argv[1]);
int shipments_size = atoi(argv[2])*sizeof(struct shipment);
printf("Allocating %d bytes for %s shipments\n", shipments_size,supplier.name);
supplier.shipments=(struct shipment *)malloc(shipments_size);

strcpy(customer.name,argv[3]);
int products_size = atoi(argv[4])*sizeof(struct product);
printf("Allocating %d bytes for %s products\n", products_size,customer.name);

/* ... TODO ... finish the rest of this program later */

free(customer.products);
free(supplier.shipments);

return 0;
}

```

You need to specify a command line. When I run it on my copy of gcc I get this output:

```
>g++ x.cpp

>a.exe "Bob Supplier" 1 "Jane Customer" 1
Allocating 52 bytes for Bob Supplier shipments
Allocating 104 bytes for Jane Customer products

>gcc x.c

>a.exe "Bob Supplier" 1 "Jane Customer" 1
Allocating 52 bytes for Bob Supplier shipments
Allocating 8 bytes for Jane Customer products

```

How can things go so horribly wrong?
> 7 votes

# Answer
```
#include <stdio.h>

int c[1];
int main() {
   struct c { int cpp[2]; };
   printf("%d\n", (int)sizeof(c)/4);
}

```
> 6 votes

# Answer
This one works with C++11 and newer and any C so far (before C11).

```
#include <stdio.h>

int main()
{
    auto a = 'a';
    printf(sizeof(a) == sizeof(int) ? "C\n" : "C++\n");
    return 0;
}

```

See here: C++: http://ideone.com/9Gkg75 and C: http://ideone.com/eECSmr

It exploits the fact that in C++11 the auto keyword got a new meaning. So while a in C is of type int stored in an AUTOmatic location it is of type char in C++11.

EDIT: As FUZxxl said the implicit int was removed in C11.
> 5 votes

# Answer
# Self-describing program

This will print "This program is written in C!" if compiled using a C compiler; otherwise, it'll print "This program is written in C++!". It needs a C99 compiler.

```
#include <stdbool.h>
#include <stdio.h>
char str[] = "This program is written in C++ ";
#define S (sizeof(str)-sizeof(true)-sizeof(true)%4)
int main(){for(int i=S;i<=S+1;++i)str[i]=i==S?'!':'\0';puts(str);return 0;}

```

> Most other posts take advantage of the difference of the size of a char in C vs C++; this one uses the fact that, in C99, `true` is defined to be a number. This inserts the exclamation point and null terminator based on the size of `true`.
> 1 votes

# Answer
```
#include <stdio.h>

int main() {
  char arr[100];
  printf("%zu",sizeof(0, arr)); // prints 8 in C and 100 in C++
}

```

In C the comma operator forces an array-to-pointer conversion while in C++ the result of the comma operator:

> The type and value of the result are the type and value of the right operand; the result is of the same value category as its right operand,
> 1 votes

---
Tags: popularity-contest, c, c++, polyglot
---


# Question
Title: We had a question once which only failed on Sundays
Inspired by We had a unit test once which only failed on Sundays, write a program or function that does nothing but throw an error when it is Sunday, and exit gracefully on any other day.

### Rules:

* No using input or showing output through the usual IO methods, except to print to STDERR or your language's equivalent. You are allowed to print to STDOUT if it's a by-product of your error.
* A function may return a value on non-Sundays as long as it doesn't print anything
* Your program may use a Sunday from any timezone, or the local timezone, as long as it is consistent.
* An error is a something that makes the program **terminate abnormally**, such as a divide by zero error or using an uninitialised variable. This means that if any code were to be added after the part that errors, it would not be executed on Sunday.
* You can also use statements that manually create an error, equivalent to Python’s `raise`.
* This includes runtime errors, syntax errors and errors while compiling (good luck with that!)
* On an error there must be some sign that distinguishes it from having no error
* This is , so the shortest bytecount in each language wins!

I'll have to wait til Sunday to check the answers ;)

# Answer
# Bash \+ coreutils, ~~15~~ 14 bytes

```
`date|grep Su`

```

Try it online!
> 27 votes

# Answer
# PHP 7, 12 bytes

```
1%date("w");

```

On PHP 7 it throws an exception of type `DivisionByZero` on Sundays. The same happens if it is interpreted using HHVM.

On PHP 5 it displays a warning (on `stderr`) on Sundays:

```
PHP Warning:  Division by zero in Command line code on line 1

```

On any PHP version, it doesn't display anything on the other days of the week.

Run using the CLI:

```
php -r '1%date("w");'

```

or try it online!

Two more bytes can be squeezed by stripping the quotes (`1%date(w);`) but this triggers a notice (that can be suppressed by properly set `error_reporting = E_ALL & ~E_NOTICE` in `php.ini`).
> 18 votes

# Answer
# Java 8, ~~69~~ ~~43~~ 34 bytes

```
v->1/new java.util.Date().getDay()

```

-26 bytes thanks to *@OlivierGrégoire*.
-9 bytes thanks to *@Neil*.

**Explanation:**

Try it here.

* `v->{...}` (unused `Void` `null` parameter) is one byte shorter than `()->{...}` (no parameter).
* `new java.util.Date().getDay()` will return 0-6 for Sunday-Saturday, so `1/...` will give an `java.lang.ArithmeticException: / by zero` error if the value is 0, which only happens on Sundays.
> 11 votes

# Answer
# PHP, 15 bytes

```
<?@date(w)?:\n;

```

Assumes default settings.

**Output on Sundays**

```
Fatal error: Undefined constant 'n' on line 1

```

Try it online!
> 9 votes

# Answer
# Python 3, 33 bytes

```
import time
"Su"in time.ctime()>q

```

Try it online!

# Python 3, 50 bytes

```
from datetime import*
datetime.now().weekday()>5>q

```

Try it online!

Saved ~3 bytes thanks to Rod.
> 8 votes

# Answer
# JavaScript, 23 Bytes

```
Date().slice(1)>'um'&&k

```

Full program.

The variable `k` must not be defined.

# JavaScript, 20 bytes by Rick Hitchcock

```
/Su/.test(Date())&&k

```

# JavaScript, 19 bytes by apsillers

```
Date().match`Su`&&k

```
> 7 votes

# Answer
# Pyth, ~~8~~ 7 bytes

```
 l-6.d9

```

Try it online!

Explanation

```
    .d9 # Get the current day of week (0 = Monday, 6 = Sunday)
  -6    # Subtract 6 from the day
 l      # Try to calculate the log base 2 of the result of the previous operation raising a "ValueError: math domain error" on sundays
        # there is an extra space at the start, to supress the output on the other days

```
> 7 votes

# Answer
# 05AB1E, ~~45~~ 44 bytes

As 05AB1E doesn't have a built in for getting the day of the week, I've used Zeller's Rule to calculate it.

Prints a newline to stderr in case of a Sunday (observable in the debug view on TIO)

```
žežf11+14%Ì13*5÷žgžf3‹-т%D4÷žgт÷©4÷®·(O7%i.ǝ

```

Try it online!

**Explanation**

The general formula used is
`DoW = d + [(13*(m+1))/5] + y + [y/4] + [c/4] - 2*c`
Where `DoW=day of week`, `d=day`, `m=month`, `y=last 2 digits of year`, `c=century` and and expression in brackets (`[]`) is rounded down.

Each month used in the formula correspond to a number, where `Jan=13,Feb=14,Mar=3,...,Dec=12`
As we have the current month in the more common format `Jan=1,...,Dec=12` we convert the month using the formula
`m = (m0 + 11) % 14 + 1`

As a biproduct of March being the first month, **January** and **February** belong to the previous year, so the calculation for determining `y` becomes
`y = (year - (m0 < 3)) % 100`

The final value for `DoW` we get is an int where `0=Sat,1=Sun,...,6=Fri`.
Now we can explicitly throw an error if the result is true.
> 7 votes

# Answer
# Haskell \+ Data.Dates, 55 bytes

```
import Data.Dates
succ.dateWeekDay<$>getCurrentDateTime

```

Try it online!

This uses the fact that Sunday is the last day of the week. `dateWeekDay` returns the day of the week as a `WeekDay` type, which is simply defined as

```
data WeekDay = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday

```

`WeekDay` is an instance of `Enum`, thus we can use `succ` and `pred` to get the successor or predecessor of a weekday, e.g. `succ Monday` yields `Tuesday`.

However, `Sunday` is the last enum entry, so calling `succ Sunday` results in the following error:

```
fail_on_sunday.hs: succ{WeekDay}: tried to take `succ' of last tag in enumeration
CallStack (from HasCallStack):
  error, called at .\Data\Dates.hs:56:34 in dates-0.2.2.1-6YwCvjmBci55IfacFLnAPe:Data.Dates

```

*Edit 1: Thanks to nimi for -3 bytes!*
*Edit 2: -11 bytes now that functions are allowed.*

---

### Full program: ~~88~~ ~~81~~ ~~74~~ ~~69~~ 66 bytes

```
import Data.Dates
main=pure$!succ.dateWeekDay<$>getCurrentDateTime

```

Try it online!

`pure` is needed to lift the resulting `WeekDay` back into the IO Monad. However, Haskell sees that the value is not output in any way by the program, so lazy as it is, the expression is not evaluated, so even on Sundays the program would not fail. This is why `$!` is needed, which forces the evaluation even if Haskell would normally not evaluate the expression.

---

### Previous approach with `Data.Time`: ~~127~~ 124 bytes

```
import Data.Time.Clock
import Data.Time.Calendar.WeekDate
c(_,_,d)|d<7=d
main=getCurrentTime>>=(pure$!).c.toWeekDate.utctDay

```

Try it online! These are some impressive imports. Change `d<7` to e.g. `d/=5` to test failure on a Friday. Fails with the following exception: `Non-exhaustive patterns in function c`.
> 6 votes

# Answer
## Ruby, 15 bytes

```
1/Time.now.wday

```

`wday` will return 0 on Sunday causing a ZeroDivisionError: divided by 0 error. For example: `1/Time.new(2018,1,7).wday`.
> 6 votes

# Answer
# VBA / VBScript, ~~22~~ 20 bytes

Saved 2 bytes thanks to Taylor Scott.

```
a=1/(Weekday(Now)-1)

```

This should be run in the Immediate Window. `Weekday()` returns 1 (Sunday) through 7 (Saturday) so this creates a divide by zero error on Sunday. Otherwise, no output.
> 6 votes

# Answer
# Perl 5, 13 bytes

```
1/(gmtime)[6]

```

Try it online!

Ported @biketire's answerj

*removed 3 bytes with @mik's reminder*
> 6 votes

# Answer
# TI-Basic 84+, 23 bytes

```
getDate
0/(1-dayOfWk(Ans(1),Ans(2),Ans(3

```

Needs date & time commands, which are 84+ and higher only.
> 5 votes

# Answer
## C, 35, 34 27 bytes

```
f(n){n/=time(0)/86400%7^3;}

```

-7 bytes with thanks to @MartinEnder and @Dennis

Try it online!
> 5 votes

# Answer
# Vyxal `O`, 25 bytes

```
kðtD4/‟₀/N‟:400/kτṠ7%2<[←

```

Try it Online!

Vyxal doesn't have a weekday function, so I made one myself.
> 5 votes

# Answer
# , ~~31 bytes~~ 30 bytes

```
if(format(Sys.Date(),'%u')>6)a

```

Try it online!

No output on non-Sundays, `Error: object 'a' not found` on Sundays.

`format(Sys.Date(),'%u')` was the shortest way I could find to get weekday, it outputs a character-class number for day of week, with 7 for Sundays. We can compare to a numeric 7, and if true attempt to use an undefined object.

Saved a byte thanks to Giuseppe!
> 4 votes

# Answer
# Zsh `-G`, 14 bytes

```
>`date`
dd Su*
```

Attempt This Online!

* `date`: get the date in the format `Sun 28 Mar 07:55:54 BST 2021`
* `>`: create a file named according to each of the words in the output
* `dd`: "copy and convert" - here it basically does nothing
    + this command expects no arguments
* `Su*`: search for a file starting with `Su`
    + if a file matching that exists (which happens when it is Sunday), then it is passed to `dd`
        - since `dd` expects no arguments, this produces an error
    + with the `-G` option: if no file matches (i.e. it is not Sunday), don't error as usual

This produces a bit of extra junk output to STDERR (not an error though) which may or may not be allowed; the question isn't really clear. Here's an alternative answer which doesn't:

## Zsh `-G`, 18 bytes

```
>`date`
mv <-> Su*
```

Attempt This Online!

`<->` matches any file whose name is a number, of which there are two: the day of the month, and the year.

When there is no `Su*` file, this is renames the day of the month to the year (overwriting the year), which works fine.

When `Sun` exists, it tries to move the day of the month and the year into the directory `Sun`, which fails because `Sun` is a file, not a directory.
> 4 votes

# Answer
# C,  ~~68~~  55 bytes

*Thanks to @Ken Y-N for saving 13 bytes!*

```
#import<time.h>
f(n){time(&n);n/=gmtime(&n)->tm_wday;;}

```

Try it online!
> 3 votes

# Answer
# jq, 42 characters

(39 characters code + 3 characters command line option)

```
now|strftime("%w")|strptime("%d")|empty

```

Just trying a different approach here: parse week day number (0..6) as month day number (1..31).

Sample run:

```
bash-4.4$ TZ=UTC faketime 2018-01-06 jq -n 'now|strftime("%w")|strptime("%d")|empty'

bash-4.4$ TZ=UTC faketime 2018-01-07 jq -n 'now|strftime("%w")|strptime("%d")|empty'
jq: error (at <unknown>): date "0" does not match format "%d"

```

Note that jq only handles UTC dates.

Try it online!
> 3 votes

# Answer
# MATL, 12 bytes

```
vZ'8XOs309>)

```

The error produced on Sundays is:

* Interpreter running on Octave:

```
MATL run-time error: The following Octave error refers to statement number 9:  )
---
array(1): out of bound 0

```
* Interpreter running on Matlab:

```
MATL run-time error: The following MATLAB error refers to statement number 9:  )
---
Index exceeds matrix dimensions

```

To invert behaviour (error on any day except on Sundays), add `~` after `>`.

**Try it Online!**

### Explanation

This exploits the fact that

* indexing into an empty array with the logical index `false` is valid (and the result is an empty array, which produces no output); whereas
* indexing with `true` causes an error because the array lacks a first entry.

Commented code:

```
v       % Concatenate stack. Gives empty array
Z'      % Push current date and time as a number
8XO     % Convert to date string with format 8: gives 'Mon', 'Tue' etc
s       % Sum of ASCII codes. Gives 310 for 'Sun', and less for others
309>    % Greater than 309? Gives true for 'Sun', false for others
)       % Index into the empty array
        % Implicit display. Empty arrays are not displayed (not even newline)

```
> 3 votes

# Answer
# ***Q, 20 Bytes***

```
if[1=.z.d mod 7;'e]

```

.z.d returns the current date. mod does the modulo of the current date, which returns an int. If the date is a sunday, .z.d mod 7 returns 1. If 1=1, (on sunday), and error is raised using the ' operator For brevity the error is just the e character.
> 3 votes

# Answer
# Julia 0.6, 32 bytes

Thanks to @Dennis for pointing out `<` saves a byte over `!=`.

```
@assert Dates.dayofweek(now())<7

```

Try it online!
> 3 votes

# Answer
## VBA 18 bytes

This relies on the inbuilt function `date()` returning a day number that remainders 1 if divided by 7, so may be OS and/or CPU specific.

```
a=1/(date mod 7-1)

```

It runs in the VBA project Immediate window.
> 3 votes

# Answer
# Excel, 24

Closing quote and paren not counted toward final score, as Excel will autocorrect both of those. Tested in Excel 2016.

```
=IF(MOD(TODAY()-1,7)^0,"")

```

I think this is different from the other submission enough to warrant another answer.

### How it works:

* I've rolled the error into the conditional check. As it turns out, `TODAY()` mod 7 also gives the weekday. If it's a Sunday, this means that `MOD(TODAY()-1,7)` is `0`, and `0^0` is an error in Excel.
    + Of course, I could also have divided `1` by the `MOD()` value or used `+6` instead of `-1`.
* If it's not Sunday, the `MOD(...,7)` will be non-zero, which when raised to `0`, returns `1`, a truthy value. This makes the `IF` return an empty string (our "nothing").
* The if statement, therefore, cannot evaluate to `FALSE`, because it errors or returns nothing.

### Alternative

Here's one that works just as well, but uses a Name error instead:

```
=IF(MOD(TODAY(),7)=1,A,"")

```
> 3 votes

# Answer
# TI-Basic, ~~22~~ 21 bytes

```
getDate
log(log(dayOfWk(Ans(1),Ans(2),Ans(3

```

-1 byte by using MarcMush's method but replacing `ln(` with `log(`.

Only works on TI-84+/SE. Assumes that the date is set correctly before the program is run. There is a newline at the end.
> 3 votes

# Answer
# C# (.NET Core), 55 54 48 bytes

Try it online!

*Saved 1 byte thanks to Shaggy*

*Saved 5 byte thanks to Emigna*

*Saved 1 byte thanks to Kevin Cruijssen*

```
_=>{var k=1/(int)System.DateTime.Now.DayOfWeek;}

```

Lucky that Sunday is indexed 0 in enum or else it would've needed to be `(System.DayOfWeek)7`
> 2 votes

# Answer
# APL (Dyalog), 23 bytes

```
⎕CY'dfns'
o←÷7|⌊days⎕TS

```

Try it online!
> 2 votes

# Answer
## Ocaml, 46 bytes

```
open Unix
let()=1/(gmtime(time())).tm_wday;()

```

and in the ocaml REPL, we can achieve better by removing the `let` and the final `:()`:

```
$ open Unix;;1/(gmtime(time())).tm_wday;;<CR>

```

which is 41 bytes (incuding 1 byte for the carriage return).
> 2 votes

# Answer
## SAS, 36 bytes

```
%put %eval(1/(1-%index(&sysday,Su)))

```
> 2 votes

# Answer
# Julia 0.5, 28 bytes

```
Dates.dayofweek(now())<7||~-

```

Try it online!

This does *not* work with 0.6, but it does with 0.4.
> 2 votes

# Answer
# Groovy, 16 bytes

```
1/new Date().day

```

Try it online!
> 2 votes

# Answer
# Zsh, 15 bytes

```
${(%):-%(w._.)}

```

Try it online!

Prompt sequences can be really crazy sometimes...

```
${(%):-%(w._.)}
${(%)         }   # expand as prompt sequence
     :-           # ${var:-fallback}, but without the var
       %( . .)    # Prompt ternary
         w        # If DoW matches given number (implied 0, which is Sunday)
          ._      # Then substitute _
            .     # Else substitute nothing

```

Since `_` is not a command, it fails on Sunday.
> 2 votes

# Answer
# , 40 bytes

```
stopifnot(weekdays(Sys.Date(),T)!="Sun")

```

Try it online!

`weekdays` returns the weekday of the date, with an optional argument `abbreviate`, which shortens `Sunday` to `Sun`, saving a single byte.

`stopifnot` throws an error if, for each argument, not `all` are `TRUE`, and throws an error with a message indicating the first element of which isn't `TRUE`, so the error is `Error: "Sun" is not TRUE`
> 1 votes

# Answer
# Gema, 40 characters

```
\A=@subst{Su=\@err\{S\}\;*=;@datime}@end

```

Had to specify an error message, so choose a short one: “S”.

Sample run:

```
bash-4.4$ faketime 2018-01-06 gema '\A=@subst{Su=\@err\{S\}\;*=;@datime}@end'

bash-4.4$ faketime 2018-01-07 gema '\A=@subst{Su=\@err\{S\}\;*=;@datime}@end'
S

```
> 1 votes

# Answer
# Funky, 21 bytes

```
if!os.date"%w"error()

```

`os.date"%w"` returns the current day of the week in 0-6 format, where 0 is sunday. Getting the logical not of that is only true when the weekday is 0, so Sunday. Then just a basic `if(a){error()}` will assure that this program only errors on sunday

Try it online!
> 1 votes

# Answer
# Perl 6,  ~~29~~  21 bytes

```
die if now.Date.day-of-week>6

```

Try it

```
die if now/86400%7+^3

```

Try it
> 1 votes

# Answer
# Pure bash BASH (interactive mode + *no* coreutils required), 17 20 19 bytes

```
PS1='`((1/\D{%w}))&&:`'

```

# Now only 19 bytes thanks to manatwork's comment below.

Bonus, if you put it in your bashrc it fails *every sunday* you log in :-) not just when you run it on sundays!
> 1 votes

# Answer
# Excel, ~~77~~ 30 bytes

Yes, vastly more golfable.

```
=IF(WEEKDAY(TODAY())=1,1/0,"")

```

Simply checks if it's Sunday, and if so, finds the quickest way I know of to error. If not Sunday, returns "",the closest Excel has to not returning anything
> 1 votes

# Answer
# C# (.NET Core), 39 43 41 bytes

```
_=>{if(1/(int)DateTime.Now.DayOfWeek<0);}

```

Try it online!

Thanks to @caird coinheringaahing and @Jo King
> 1 votes

# Answer
**Postgresql, 32**

Not sure if you need to add ; at the end for valid answer

```
SELECT 1/EXTRACT(DOW FROM now())

```
> 1 votes

# Answer
# SmileBASIC, 20 bytes

```
DTREAD OUT,,,W
W=W/W

```

`DTREAD` outputs the current year, month, day, and day of the week. Sunday is 0.
> 1 votes

# Answer
# Java 8, 34 bytes

Returns 1 on Mondays, 0 on other days, and throws an ArithmeticException on Sundays

```
v->1/new java.util.Date().getDay()

```

Try it online!
> 1 votes

# Answer
# 05AB1E, ~~54~~ 52 bytes

```
žg¦¦D4÷že+•YFóåι•žf<è+žg4Öžf3‹&-ŽPjžg2£4%è++7%iõEëõ}

```

Try it online!

## Explanation

Formula from here.

```
žg¦¦                                                 # Take the last two digits of the year.
    D                                                # Save for later.
     4÷                                              # Divide by 4, discarding any fraction.
       že+                                           # Add the day of the month.
          •YFóåι•                                    # Push the month's key values.
                 žf                                  # Take the month.
                   <è                                # Find the month's key value.
                     +                               # Add the month's key value.
                      žg4Ö                           # Is this year a leap year?
                          žf3‹                       # Is it January or Feburary?
                              &                      # And the results of both questions.
                               -                     # Subtract 1 for January or February of a leap year.
                                ŽPj                  # Push 6420.
                                   žg2£              # Take the first two digits of the year.
                                       4%è           # Index the thing into the list.
                                          +          # Do step 6.
                                           +         # Add the last two digits of the year.
                                            7%       # Divide by 7 and take the remainder.
                                              i  ë } # Sunday is 1, so it goes in the if.
                                              iõ ë } # Push empty string.
                                              i Eë } # For loop.
                                              i  ëõ} # If not sunday, push empty string and implicit output.

```
> 1 votes

# Answer
# Pyth, 7 bytes

```
/1-6.d9

```

Try it online!

```
/1-6.d9
    .d9  // Current day of the week, 0 indexed on monday.
  -6     // 6 - day of week (0 if Sunday)
/1       // 1 ÷ ^

```
> 1 votes

# Answer
# Japt, 7 bytes

```
çKe ªUí

```

Test it

```
çKe ªUí
ç           :U=0 times repeat
 K          :  Current date
  e         :  0-based day of the week
    ª       :  Logical OR with
     Uí     :  The result of running the í method on U, which doesn't exist for numbers

```
> 1 votes

# Answer
# Python 3, 50 bytes

```
from datetime import*
1/(date.today().weekday()-6)

```

Try it online!
> 1 votes

# Answer
## Batch, 88 bytes

```
@for /f "skip=1" %%d in ('wmic path win32_localtime get dayofweek')do @set/a1/%%d&exit/b

```

Tries to divide by zero on Sunday.

Unfortunately neither `date` nor `powershell date` work on my PC to give me the day of the week.
> 0 votes

# Answer
## PowerShell, ~~24~~ 20 Bytes

```
1/(date).DayOfWeek>1

```

Sunday triggers divide by zero same as most of the other solution here. Problem is that on other days that a double gets returned so redirect to nowhere useful trumps that output.
> 0 votes

# Answer
# AWK, ~~27~~ ~~25~~ ~~23~~ 21 bytes

```
END{1/strftime("%w")}

```

Try it online!

Saved 4 bytes thanks to manatwork

Saved 2 bytes thanks to mik
> 0 votes

# Answer
# Swift 4, 78 bytes

```
import Foundation;if(Calendar.current.component(.day,from:Date()))==7{exit(1)}

```

Try it online!
> 0 votes

# Answer
# Octave, ~~23~~ 22 bytes

```
(1:6)(weekday(now)-1);

```

Try it online!

This will try to access an element in 1:6. When the day is Sunday it will try to access the element `(1-1)=(0)` which will result in an error as MATLAB is 1-indexed.

---

Original for 23.

```
assert(weekday(now)~=1)

```

Try it online!

`assert(...)` will throw an error when the condition is false. `weekday(now)` returns the current day of the week where 1 = Sunday. Put the two together, the code will throw an error only on sundays when the condition becomes `1~=1`.
> 0 votes

# Answer
# Clojure, 43 bytes

```
#(and(=(.getDay(java.util.Date.))7)(/ 1 0))

```

Try it online!

Uses the fact that `and` doesn't evaluate the second argument unless necessary. I originally thought I could get away with using the Ratio literal `1/0` to save two bytes, but that unfortunately causes exceptions immediately. It must try to reduce the Ratio right away or something.

```
(defn sunday-fail []
  (and (= (.getDay (Date.)) 7)
       (/ 1 0)))

```
> 0 votes

---
Tags: code-golf, date, error-message
---