title: Is it a fibonacci-like sequence?

text:
# Question
Title: Is it a fibonacci-like sequence?
The Fibonacci Sequence is a sequence of positive integers where the first two elements are 1 and the rest are the sum of the previous two. It begins \\$1, 1, 2, 3, 5, 8, 13\\$ and continues forever.

But what if you started with numbers other than \\$1, 1\\$? You could start with \\$3, 4\\$ and have the sequence go \\$3, 4, 7, 11, 18, 29\cdots\\$. Or you could start with \\$2, 9\\$ and have it go \\$2, 9, 11, 20, 31, 51 \cdots\\$.

Your challenge is to take a list of positive integers and determine if it could be part of some Fibonacci-like sequence. Essentially, determine if for each element but the first two, it's equal to the sum of the previous two.

## Testcases

Truthy:

```
[1, 1, 2, 3, 5]
[6, 9, 15, 24]
[49, 71, 120, 191, 311, 502]
[3, 4, 7, 11]

```

Falsy:

```
[1, 2, 4]
[1, 1, 2, 3, 4]
[3, 4, 6, 8, 9]
[3, 9, 12, 15, 31]
[3, 4, 6, 10, 16]
[1, 1, 1, 2]

```

You can assume the input will be (non-strictly) increasing and have a length ≥ 3.

# Answer
> 11 votes
# Shue, 149 bytes

```
=R
1,R=<,R
1<=<1
,<=*,
,*=*,
1*=i
i*=*i
,,R=t,R
it=t1
,t=T,
iT=T1
1,T=1,
T=L
L1=L
L,=L
LR
*=Xe
1t=e
1T=e
i,T=e
1e=e
ie=e
ei=e
e1=e
e,=e
,e=e
e=Xe
XeR

```

Try it online!

Returns "LR" for yes and "XeR" for no. Previous version didn't work for inputs like `1,1,111,` so a few bytes went into fixing that.

# Explanation

```
=R       - Right edge
1,R=<,R  - Spawn a triangle and decrement the last number
1<=<1    - Triangle passes trough the last element
,<=*,    - Triangle turns into star after last element
,*=*,    - Star passes trough commas
1*=i     - Reversibly "Decrement" the  element (i=0)
i*=*i    - Star passes trough zeros
,,R=t,R  - When done, send a test probe (t)
it=t1    - Test probe passes trough zeros, turning them to ones
,t=T,    - Upgrade test probe
iT=T1    - Still passes trough zeros
1,T=1,   - And when done, delete itself
T=L      - Or, if the left edge was reached, turn into L
L1=L     - L deletes everything to it's right
L,=L     - --||--
LR       - And finally, success
*=Xe     - Or, if the star reached the end, create error
1t=e     - Or if there weren't enough elements to delete last time, create error (b>c)
1T=e     - Same as before (a+b>c)
i,T=e    - Too many elements to delete (a+b<c)
1e=e     - Errors propagate
ie=e     - --||--
ei=e     - --||--
e1=e     - --||--
e,=e     - --||--
,e=e     - --||--
e=Xe     - Unify error types
XeR      - Final error state

```

# Example run:

```
1,1,11,
1,1,11,R
1,1,1<,R
1,1,<1,R
1,1*,1,R
1,i,1,R
1,i,<,R
1,i*,,R
1,*i,,R
1*,i,,R
i,i,,R
i,it,R
i,t1,R
iT,1,R
T1,1,R
L1,1,R
L,1,R
L1,R
L,R
LR

```

# Example run 2

```
1,1,111,
1,1,111,R
1,1,11<,R
1,1,1<1,R
1,1,<11,R
1,1*,11,R
1,i,11,R
1,i,1<,R
1,i,<1,R
1,i*,1,R
1,*i,1,R
1*,i,1,R
i,i,1,R
i,i,<,R
i,i*,R
i,*i,R
i*,i,R
*i,i,R
Xe,i,R
Xei,R
Xe,R
XeR

```

# Answer
> 8 votes
# , ~~46~~ ~~41~~ ~~42~~ 38 bytes

*Edit: Bug-fix for +1 byte thanks to pajonk, but then -4 bytes by adopting Giuseppe's use of `head` with a negative `n`...*

```
function(x)any(diff(x)[-1]-head(x,-2))

```

Try it online!

Function `not_fiblike` outputs `TRUE` if the input `x` is *not* a fibonacci-like sequence, `FALSE` if it is one.

# Answer
> 8 votes
# Wolfram Mathematica ~~34~~ 29 bytes

```
 2#~Drop~2==MovingMap[Tr,#,2]&

```

–5 bytes from @att

Try it online!

\[Included the `[3,4,6,10,16]` and `[1,1,1,2]` falsey test cases from Noodle9 and DLosc, respectively.\]

# Answer
> 7 votes
# Python, 31 bytes

```
def f(a,*d):a+d[0]-d[1]or f(*d)
```

Attempt This Online!

-3 bytes thanks to @emanresuA.

Outputs via presence of an exception or not.

# Answer
> 7 votes
# Wolfram Language (Mathematica), ~~43~~ ~~38~~ 31 bytes

```
#[[;;-3]]+#[[2;;-2]]==#[[3;;]]&

```

Try it online!

Previously I had a 43-byte version using Partition, which simplifies to a 39-byte solution with BlockMap:

```
And@@BlockMap[Plus@@#==2#[[3]]&,#,3,1]&

```

In case it gives anyone ideas, there is a 44-byte solution using a function specifically for generating linear recurrences:

```
#==LinearRecurrence[{1,1},#[[;;2]],Tr[1^#]]&

```

# Answer
> 6 votes
# Jelly, 4 bytes

```
IḊw@
```

Attempt This Online!

```
I      differences between consecutive elements
 Ḋ     remove the first item
  w@   find the sublist index of this in the input

```

`1` is truthy and all other values are falsey.

# Answer
> 6 votes
# , 40 bytes

```
function(l)any(diff(l,2)-head(l,-1)[-1])

```

Try it online!

Returns `FALSE` for Fibonacci-like sequences, and `TRUE` otherwise.

Slightly different approach than Dominic van Essen's, takes the lag-2 differences of `l` and compares to the list with the first and last elements removed, relying on the following idea:

\\$F\_{n+1}=F\_{n}+F\_{n-1}\Rightarrow F\_n=F\_{n+1}-F\_{n-1}\\$

# Answer
> 5 votes
# JavaScript (Node.js), 32 bytes

```
a=>!a.some(n=>n+a[i]-a[++i],i=1)

```

Try it online!

# Answer
> 5 votes
# Pari/GP, 27 bytes

```
a->#Pol(Ser(a)*(1-x-x^2))<3

```

A sequence is Fibonacci-like if and only if its generating function is of the form \\$\frac{a+b\ x}{1-x-x^2}\\$.

Try it online!

# Answer
> 5 votes
# Julia, ~~48~~ ~~44~~ 43 bytes

```
~f=0∉3:length(f).|>i->f[i]==f[i-2]+f[i-1]

```

Try it online!

# Answer
> 5 votes
# Haskell, 34 bytes

```
g(a:l@(b:c:_))=a+b==c&&g l;g _=0<1

```

Try it online!

* Thanks to @Laikoni for suggesting a recursive approach 1 Byte shorter
* Original solution 35 bytes

```
g l@(a:b:c)=zipWith(-)c l==b:init c

```

Try it online!

# Answer
> 5 votes
# Dyalog APL, ~~11~~ 10 bytes

```
⊃2∘↓⍷2+/⊢

```

-1 thanks to @DLosc.

Try it online!

Taking the array `1 1 2 3 5` as an example:

```
 2∘↓      Is the array with the first two elements removed         (2 3 5)
    ⍷     a subarray of
     2+/⊢ the sum of each consecutive pair of numbers in the array (2 3 5 8)
⊃         at the first position?

```

# Answer
> 5 votes
# Curry (PAKCS), 22 bytes

-3 bytes thanks to Wheat Wizard.

```
f(_++a:b:c:_)|a+b/=c=0

```

Try it online!

This returns nothing if the input is Fibonacci-like, and `0` otherwise.

# Answer
> 4 votes
# Python 2, 39 bytes

```
lambda a:map(sum,zip(a[1:-1],a))==a[2:]

```

Try it online!

---

# Python 3 \+ NumPy, 35 bytes

```
lambda a:all(a[1:-1]+a[:-2]==a[2:])

```

Try it online!

# Answer
> 4 votes
# 05AB1E, 4 bytes

```
¥¦Å?

```

Port of *@pxeger*'s Jelly answer.

Try it online or verify all test cases.

An inversed version is also possible, but would be a byte longer:

```
ü+¨Å¿

```

Try it online or verify all test cases.

**Explanation:**

```
       #  e.g. input = [49,71,120,191,311,502]

¥      # Get the deltas/forward-differences of the (implicit) input-list
       #  STACK: [22,49,71,120,191]
 ¦     # Remove the first item
       #  STACK: [49,71,120,191]
  Å?   # Check if the (implicit) input-list starts with this sublist
       #  STACK: 1
       # (after which the result is output implicitly)

ü      # For each overlapping pair of the (implicit) input-list:
 +     #  Add them together
       #   STACK: [120,191,311,502,813]
  ¨    # Remove the last item
       #   STACK: [120,191,311,502]
   Å¿  # Check if the (implicit) input-list ends with this sublist
       #   STACK: 1
       # (after which the result is output implicitly)

```

# Answer
> 4 votes
# 80386 machine code, ~~19~~ 16 bytes

```
\x49\x49\x8b\x44\x8a\x04\x2b\x04\x8a\x2b\x44\x8a\xfc\xe1\xf3\xc3

```

Try it online!

Applying @PeterCordes's suggestion to remove `setz` saved 3 bytes. I first considered simply returning `al` as a boolean value, but then the problem is that a non-zero value will represent `false` and zero will represent `true`. I felt it's not clear-cut whether this is okay.

Now, the function works as returning the zero flag. Thus, it is not possible to be directly called from C as before. If you follow the TIO link, there is a wrapper function to interface with this assembly function returning a flag value. Since I'll usually have to write such wrapper when calling functions from other languages, I think this approach is okay.

Thanks to @Deadcode for letting me know a nice way to translate the flag to a value in the wrapper function.

**assembly (nasm)**

```
testfib: ; fastcall, ecx = length of array, edx = pointer to array
    dec ecx
    dec ecx
.loop:
    mov eax, [edx + ecx * 4 + 4]
    sub eax, [edx + ecx * 4]
    sub eax, [edx + ecx * 4 - 4]
    loopz .loop
    ret

```

# Answer
> 4 votes
# Husk, ~~5~~ ~~6~~ 5 bytes

```
€¹tẊ-

```

Try it online!

Outputs `1` for truthy (it's a fibonacci-like sequence), any other non-negative integer for falsy (it isn't a fibonacci-like sequence).

Get the pairwise differences (`Ẋ-`), remove the first one (`t`), and ~~check if this is an ordered sublist of the input~~ find the index of this sublist in the input (`€ḣ¹`), or `0` if not present.

~~Of course, it needs to be a *prefix* of the input (rather than a sublist at any other position), but I think this should be ensured since the input is increasing.~~ *Edit:* the fact that the input is increasing does *not* ensure that sublists must be prefixes (consider `1 2 4` with difference sublist `2`), so we check this by requiring that the index of the sublist must be `1`.

# Answer
> 4 votes
# MATL, 10 bytes

```
d4L)tfGw)=

```

Try it online!

Just the usual: take the pairwise difference, discard the first, chop off the last two elements of input, compare.

---

*Alternate*:

### MATL, ~~17~~ 16 bytes

```
tnwTTZ+2YSG=s-I<

```

Try it online!

Perform a convolution of the input with `[1 1]`, circularly shift the result twice to align the sums, compare with input, and see that the last `n - 2` values match. (The last two bytes might as well be `2=` I think, but it's the same byte count anyway.)

Previous solution: `TT2&Y+3L)G&m2-tf=`
Perform a convolution of the input with `[1 1]`, and check that the 1:n-1 values of the result (excluding the last sum) are present in the input at right index.

---

Output is all 1s (in both solutions) for truthy.

# Answer
> 3 votes
# Desmos, 37 bytes

```
f(l)=min(1-sign(l[3...]-l[2...]-l)^2)

```

Try It On Desmos!

Try It On Desmos! - Prettified

Tell me if there is anything wrong. I made this answer faster than usual :D

# Answer
> 3 votes
# Python 3.8 (pre-release), 46 bytes

```
f=lambda n:n[2:]and(n[0]+n[1]-n[2]or f(n[1:]))

```

Try it online!

Recursion is shorter than doing `all(... for i,e in enumerate(n))`.

-2 by @emanresuA, -4 by @pxeger. What am I doing today...

# Answer
> 3 votes
# Factor, 30 bytes

```
[ dup differences rest head? ]

```

Try it online!

## Explanation

Does the input start with its differences sans the first?

```
              ! { 1 1 2 3 5 }
dup           ! { 1 1 2 3 5 } { 1 1 2 3 5 }
differences   ! { 1 1 2 3 5 } { 0 1 1 2 }
rest          ! { 1 1 2 3 5 } { 1 1 2 }
head?         ! t

```

# Answer
> 3 votes
# C (gcc), ~~58~~ ~~57~~ 51 bytes

```
r;f(a,n)int*a;{for(r=0;n-->2;)r|=*a+*++a-a[1];n=r;}

```

Try it online!

*Saved 6 bytes thanks to pxeger!!!*

Inputs a pointer to an array on integers and its length (because pointers in C carry no length info).
Returns \\$0\\$ if its a Fibonacci-like sequence or a truthy value otherwise.

# Answer
> 3 votes
# C (GCC), 44 bytes

```
f(a,n)int*a;{n=*a+*++a-a[1]||--n>2&&f(a,n);}
```

Attempt This Online!

-1 byte by inverting output, thanks to @AZTECCO

Recursive.

# Answer
> 3 votes
# Standard ML (MLton), ~~51~~ ~~48~~ 45 bytes

```
fun$(x::y::z::L)=x+y=z andalso$(tl L)| $_=1=1

```

Try it online!

-3 bytes thanks to Laikoni.

-3 bytes using `tl` to recurse instead of pattern matching.

# Answer
> 3 votes
# , ~~38~~ 12 bytes

```
2{]E.~2+/\}:

```

Or

```
2&}.-:2+/\}:

```

-26 bytes, thanks @Jonah

Try it online!

# Answer
> 3 votes
# BQN, ~~14~~ 13 bytes

```
+´↑∊·2⊸↓⊸⋈⊢-»

```

Try it at BQN online REPL

```
              »     # shift the input array right,
             -      # and subtract this from
            ⊢       # the input;
     ·2⊸↓           # now drop the first two elements,
          ⊸⋈       # and make a list of this list,
    ∊               # and check whether this equals
   ↑                # any prefix of the input;
×´                  # finally get the product to check if all are true.

```

# Answer
> 2 votes
# Retina 0.8.2, ~~38~~ 37 bytes

```
\d+
$*
^((1+),(?=(1+),\2\3\b))+1+,1+$

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
^((1+),(?=(1+),\2\3\b))+

```

Repeatedly match a number, each time checking that the number two ahead is the sum of it and the next number.

```
1+,1+$

```

Match the final two numbers.

Previous 38-byte version used .NET's ability to recapture an existing named or numbered group:

```
\d+
$*
^(1+),(1+)(,(?<2>\1(?<1>\2)))+$

```

Try it online! Link includes test cases. Explanation:

```
\d+
$*

```

Convert to unary.

```
^(1+),(1+)

```

Match two numbers `\1` and `\2`...

```
(,(?<2>\1(?<1>\2)))+$

```

... then repeatedly match numbers that are the sum of `\1` and `\2`, but recapture `\1` as `\2` and `\2` as the sum, so that each number has to be the sum of the previous two.

# Answer
> 2 votes
# APL+WIN, 26 bytes

Prompts for input

```
(¯2+⍴v)=+/(¯2↓v)=1↓-2-/v←⎕

```

Try it online! Thanks to Dyalog Classic

# Answer
> 2 votes
# PowerShell Core, 53 bytes

```
!(3..($a=$args).length|?{$a[--$_-2]+$a[$_-1]-$a[$_]})

```

Try it online!

Takes a list of numbers as parameter and returns a boolean

# Answer
> 2 votes
# C#, ~~114~~ 113 bytes

```
var a=args;int i=0,r=0;for(;i<a.Length-2;)if(int.Parse(a[i])+int.Parse(a[i+1])!=int.Parse(a[i+++2]))r=1;return r;

```

Program expects the list to be passed as a list of command line arguments, e.g.:

```
./program 1 2 3 5 8

```

Program uses C# v9 top-level statements feature, this is a full C# program. Unwrapped:

```
var a = args;
int i = 0, r = 0;
for (; i < a.Length - 2;)
    if (int.Parse(a[i]) + int.Parse(a[i + 1]) != int.Parse(a[i++ + 2]))
        r = 1;
return r;

```

# Answer
> 2 votes
# k (ngn/k), 41 bytes

```
c:{~#{x}_*,x{(x@y)=+/x@y-2 1}/:2+!(#x)-2}

```

try it in the ngn/k repl

# Answer
> 2 votes
# PowerShell Core, 44 bytes

inspired by Julian

```
$a,$b,$c=$args
!($c|?{$_-$a-$b;$a,$b=$b,$_})

```

Try it online!

# Answer
> 2 votes
# Vyxal, ~~7~~ 6 bytes

```
¯Ḣ₅⁰Ẏ⁼

```

Try it Online!

*-1 byte thanks to emanresu A*

## How?

```
¯Ḣ₅⁰Ẏ⁼
¯         # Deltas (consecutive differences) of (implicit) input
 Ḣ        # Remove the first item
  ₅       # Push length without popping
   ⁰      # Push the input
    Ẏ     # Slice the input until the length
     ⁼    # Exactly equal to the deltas with first item removed? (non-vectorizing)

```

# Answer
> 1 votes
# Charcoal, 18 bytes

```
⬤θ∨‹κ²⁼ι⁺§θ⊖κ§θ⁻κ²

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for Fibonacci-like, nothing if not. Explanation:

```
 θ                  Input array
⬤                   All elements satisfy
    κ               Current index
   ‹                Is less than
     ²              Literal integer `2`
  ∨                 Logical Or
       ι            Current value
      ⁼             Equals
          θ         Input array
         §          Indexed by
            κ       Current index
           ⊖        Decremented
        ⁺           Plus
              θ     Input array
             §      Indexed by
                κ   Current index
               ⁻    Minus
                 ²  Literal integer `2`
                    Implicitly print

```

# Answer
> 1 votes
# Perl 5, 35 bytes

```
sub{@_-2?$_[1]+shift==$_[1]&&&$f:1}

```

Try it online!

---
Tags: code-golf, decision-problem, integer, fibonacci, subsequence
---


title: Fifty Shades of Grey

text:
# Question
Title: Fifty Shades of Grey
Boys and girls are excited to see *Fifty Shades of Grey* on the silver screen, we just want to code without being bothered, so here's a challenge to pick our brain.

You have to:

* Print on the screen fifty squares filled **each with a different shade of grey**
* If your language of choice **lacks image processing capabilities**, you could output an **image file**
* Squares must be visible, **at least 20 x 20 pixels**
* You cannot use random numbers **unless you make sure each shade is unique.**
* You **cannot connect to any service over any network**
* You **cannot read any files in your program.**
* You cannot use any libraries out of the standard libraries of your language of choice.

**This is code golf so shortest code wins.**

# Answer
> 25 votes
# MATLAB, 24 bytes

Second attempt, now actually conforming to the rules.

```
imshow(0:1/49:1,'I',2e3)

```

The 'I' stands for 'InitialMagnification', but apparently Matlab will autocomplete names in name/value pairs. Sure is a good golfing trick!

# Answer
> 58 votes
# Mathematica, 30 bytes

Here is another Mathematica approach:

```
ArrayPlot[#+5#2&~Array~{5,10}]

```

or

```
ArrayPlot[5#+#2&~Array~{10,5}]

```

The first one simply creates an array

```
{{6, 11, 16, 21, 26, 31, 36, 41, 46, 51},
 {7, 12, 17, 22, 27, 32, 37, 42, 47, 52},
 {8, 13, 18, 23, 28, 33, 38, 43, 48, 53},
 {9, 14, 19, 24, 29, 34, 39, 44, 49, 54},
 {10, 15, 20, 25, 30, 35, 40, 45, 50, 55}}

```

and the second one

```
{{6, 7, 8, 9, 10},
 {11, 12, 13, 14, 15},
 {16, 17, 18, 19, 20},
 {21, 22, 23, 24, 25},
 {26, 27, 28, 29, 30},
 {31, 32, 33, 34, 35},
 {36, 37, 38, 39, 40},
 {41, 42, 43, 44, 45},
 {46, 47, 48, 49, 50},
 {51, 52, 53, 54, 55}}

```

Then, `ArrayPlot` plots them as a grid and, by default, uses greyscale to visualise the values.

# Answer
> 36 votes
# CJam - 23 (no actual graphical output)

Since CJam can't draw on the screen (yet?), I wrote a program that outputs an image in plain pgm format.
Save the output to a file called 50.pgm and open with an image viewer/editor.

```
"P2"1e3K51_,1>K*$K*~]N*

```

Try it online

The result looks like this:

**Explanation:**

```
"P2"     push "P2" (netpbm magic number)
1e3K     push 1000 and K=20 (image size)
51       push 51 (value of white)
_,       duplicate 51 and convert to an array [0 1 2 ... 50]
1>       remove 0 (slice from 1)
K*       repeat the array 20 times
$        sort, to get [(20 1's) (20 2's) ... (20 50's)]
K*       repeat the array 20 times
~        dump the elements on the stack
]        put everything from the stack in an array
N*       join with newlines

```

# Answer
> 30 votes
# Mathematica ~~72 61 59 43 35~~ 34 bytes

**Current version** (34 bytes)

```
GrayLevel[#/50]~Style~50 &~Array~50

```

---

**Earlier version** (59 bytes), thanks to Martin Büttner.

```
Graphics[{GrayLevel[#/50],Cuboid@{#~Mod~9,#/9}}&/@Range@50]

```

Blue borders added to highlight position of squares.

```
Graphics[{EdgeForm[Blue], GrayLevel[#/50], Cuboid@{#~Mod~9, #/9}} & /@Range@50]

```

Number of squares:

```
    Length[%[[1]]]

```

> 50

---

**First attempt (72 bytes)**

If the squares can overlap. As Zgarb notes, there is a remote possibility that one square would hide another.

```
  Graphics@Table[{GrayLevel@k,Cuboid[{0,15}~RandomReal~2]},{k,.4,.89,.01}]

```

# Answer
> 29 votes
# Sage - ~~26~~ ~~24~~ ~~35~~ 29 characters

```
matrix(5,10,range(50)).plot()

```

It looks like this:

##

*Previous attempts*: First I had `Matrix([range(50)]).plot()`, then `matrix_plot([range(50)])`. These looked like this:

User @flawr pointed out that the squares produced with default settings are too small. Adding a `figsize` options fixes it, but it is 6 characters longer than the 5x10 version at the top of this answer:

```
matrix_plot([range(50)],figsize=20)

```

# Answer
> 22 votes
## R, ~~47 42 39 38 37 36~~ 35 bytes

Assuming they're allowed to overlap, this works. `Symbols` requires a vector that holds the size for each square, and I'm saving space by reusing the same vector for all function parameters. The largest square is always 1 inch wide. With 50:99 as the range of integers, the smallest square will be around half an inch wide, so 36 pixels at 72 dpi.

```
symbols(x,,,x<-50:99,bg=gray(x/99))

```

Thanks to everyone for the comments and suggestions, I'm pretty new to R so this is all very educational.

Previous versions:

```
symbols(x,sq=x<-50:99,bg=gray(x/99))            #36
x=50:99;symbols(x,sq=x,bg=gray(x/99))           #37
x<-50:99;symbols(x,sq=x,bg=gray(x/99))          #38
x<-1:50;symbols(x,sq=x/x,bg=gray(x/50))         #39
x<-1:50/50;symbols(x,sq=x/x,bg=rgb(x,x,x))      #42
x<-1:50/50;symbols(x,squares=x/x,bg=rgb(x,x,x)) #47

```

Previous image:

# Answer
> 21 votes
# Java - 180

Pretty straightforward, just drawing boxes.

```
import java.awt.*;void f(){new Frame(){public void paint(Graphics g){for(int i=1;i<51;g.setColor(new Color(328965*i)),g.fillRect(i%8*20,i++/8*20,20,20))setSize(600,600);}}.show();}

```

With line breaks:

```
import java.awt.*;
    void f(){
        new Frame(){
            public void paint(Graphics g){
                for(int i=1;
                    i<51;
                    g.setColor(new Color(328965*i)),
                    g.fillRect(i%8*20,i++/8*20,20,20))
                    setSize(600,600);
            }
        }.show();
    }

```

# Answer
> 17 votes
# ipython 2, 54 bytes

The best I could do was with an ipython program. Starting ipython with `ipython -pylab` and executing this program will show a graph with 50 shades of grey in 50 squares:

```
t=arange(50);c=t/50.;scatter(t%5,t,500,zip(c,c,c),'s')

```

Output:

### Solution 2:

Here is another program (61 bytes):

```
imshow(arange(50).reshape(5,10)*.02,'Greys',None,1,'nearest')

```

that displays the following window:

# Answer
> 17 votes
# BBC BASIC, 57

```
FORn=51TO2STEP-1VDU19;-1,n,n,n:RECTANGLEFILL0,0,n*20NEXT

```

The squares have to be *at least* 20 pixels but there's nothing to say they have to be the same size, so I guess this qualifies.

It may be possible to shorten this by using more low-level VDU codes. But changing from this pattern to a less interesting one is unlikely to make it shorter.

# Answer
> 15 votes
# JavaScript (72, 70, 67 bytes)

72: original (borrowing the clever `■` usage from Sphinxxx's answer):

```
for(i=90;i>40;)document.write('<font color=#'+i+i+i--+' size=7>■')
```

70: stealing shamelessly from Ismael Miguel (who deserves the votes), a shorter for loop and allowing the browser to correct for a lack of # proceeding the colour code...

```
for(i=60;--i>9;)document.write('<font color='+i+i+i+' size=7>■')
```

67 bytes (65 chars): swapping the entity for the unicode character:

```
for(i=60;--i>9;)document.write('<font color='+i+i+i+' size=7>■')
```

# Answer
> 13 votes
## C++, ~~98~~ 83 characters

Okay so, you are going to need a terminal emulator that supports true colors. For mac os there are the nightly builds of iTerm2, for example. For unix I believe konsole supports it. Here's a list, just in case: https://gist.github.com/XVilka/8346728#now-supporting-truecolor

Compile with g++ (\e is compiler dependent).

For the squares to have enough area, you will have to change your terminal font size.

```
#include <cstdio>
int main(){for(int i=51;i--;)printf("\e[48;2;%i;%i;%im ",i,i,i);}

```

Using C libraries instead of C++ allows for shaving some characters.

## C, ~~61~~ 58 characters

This is the same program but in C, which assumes untyped function declarations to return int, and which doesn't need includes for some of the standard library functions, like in this case, printf. Suggested by @cartographer. Three characters less thanks to @user3601420

```
main(i){for(i=51;i--;)printf("\e[48;2;%i;%i;%im ",i,i,i);}

```

Compiles with a couple of warnings (for assuming main's return type to be int and for implicitly including the declaration of printf).

# Answer
> 11 votes
## J (~~43~~ ~~41~~ ~~40~~ ~~38~~ ~~33~~ 29 characters)

After suggestions from randomra.

```
1!:2&4'P2 ',":(,*:,],*:#?~)50

```

This solution does not display anything as the standard library of J does not contain GUI routines. Instead, I generate an image and write it to standard output. The output is randomized, it ensured that all shades are distinct. Here is a some sample output and the image converted to png and rotated by 90° for easier viewing:

# Answer
> 11 votes
# Piet- 2\*103 = 206

This is unique in that the source code and the output fulfill the challenge:

Most of it is decorative, so I only counted the top two rows, which stand alone just fine. Outputs a grayscale ppm like some others have done.

# Answer
> 10 votes
# Python 2, ~~125~~ ~~115~~ 104 bytes

```
from turtle import*
shape("square")
bk(500)
ht()
pu()
exec'color((xcor()/2e3+.5,)*3);stamp();fd(21);'*50

```

**Sample output:**

Good old turtle. This was the only method I could think of in Python which prints images to a screen using only the standard libraries.

The square turtle shape just happens to be 21 by 21, which is very convenient. This can be seen by digging through `turtle.py`:

```
"square" : Shape("polygon", ((10,-10), (10,10), (-10,10), (-10,-10)))

```

If you have a high res monitor or don't mind a few squares being off-screen, then this is **93 bytes:**

```
from turtle import*
shape("square")
ht()
pu()
exec'color((xcor()/2e3,)*3);stamp();fd(21);'*50

```

---

## Demo

*(This demo uses Skulpt by adapting the snippet found here. It is only included to give an idea as to what the code does — I had to modify a few bits to get it working.)*

```
function out(a){var b=document.getElementById("output");b.innerHTML+=a}function builtinRead(a){if(void 0===Sk.builtinFiles||void 0===Sk.builtinFiles.files[a])throw"File not found: '"+a+"'";return Sk.builtinFiles.files[a]}
$(document).ready(function run(){Sk.canvas="canvas";Sk.configure({output:out,read:builtinRead});try{Sk.importMainWithBody("<stdin>",!1,'import turtle\nt=turtle.Turtle()\nt.speed(9)\nt.shape("square")\n\nt.bk(500)\nt.ht()\nt.pu()\nfor i in range(50):t.color(64+2*i,64+2*i,64+2*i);t.stamp();t.fd(21)')}catch(a){throw Error(a.toString());}})
```

```
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script><script src="http://www.skulpt.org/static/skulpt.min.js" type="text/javascript"></script><script src="http://www.skulpt.org/static/skulpt-stdlib.js" type="text/javascript"></script>
<canvas height="100" width="1200" id="canvas" style="border:1px solid gray">Your browser does not support HTML5 Canvas!</canvas>
```

# Answer
> 10 votes
# Excel vba, 81

In the immediate window:

```
for i=1 to 9:for j=1 to 9:k=i+j*10:cells(i,j).interior.color=rgb(k,k,k):next:next

```

on the active sheet:

{81 shades is just as much code as 50}

# Answer
> 8 votes
**Matlab 35 thanks to sanchises**

```
imshow(int8(ones(20,1)*(0:.05:51)))

```

**Matlab 36**

```
imshow(uint8(ones(20,1)*(0:.05:51)))

```

Displays 50 squares filled with gray values 1 to 50 and 2 additional rectangles filled with gray value 0 and 51:

**Matlab, 45**

```
imshow(uint8(ones(20,1)*floor(1:0.05:50.95)))

```

# Answer
> 8 votes
# **R**, ~~37~~ 32 characters1:

```
image(t(1:50),c=gray.colors(50))

```

However, the display for this looks … meh (image rotated 90° to fit better into text; compressed, original square side length \> 20px):

Here’s a nicer version which plots the squares in random order inside a matrix (50 characters):

```
image(matrix(sample(1:50),10),c=gray.colors(50))

```

(And yes, the three adjacent squares of seemingly identical colours are actually three different shades of grey.)

1 Yes, another R answer, ~~and not even the shortest~~ (now the shortest for R) – apologies. I was missing a *pretty* rendering in R.

# Answer
> 7 votes
# JavaScript, 87 90 bytes

```
for(i=90;i>40;)document.write('<p style=background:#'+i+i+i--+';height:9ex;width:9ex>')
```

This outputs squares to the HTML, because it is really JavaScript's only method of graphical output. Thanks to edc65 for shaving off 3 bytes.

# Answer
> 7 votes
# PHP, ~~96~~ ~~88~~ 74 bytes

Thanks to Ismael Miguel for saving 22 bytes!

```
for($i=60;--$i>9;)echo"<p style=background:#$i$i$i;height:9mm;width:9mm>";

```

Writes 50 `<p>`s with 9mm as height and width (which should be bigger than 20px on the majority of screens), stacked on each other, all with a minor difference in shade.

Generated result (the image is zoomed out and 90° rotated):

# Answer
> 7 votes
# Javascript (~~77~~ 71 bytes):

This answer is no longer IE11 based. It works because the browser converts the bad color codes into usable ones (by adding `#` to the number).

Here is the code:

```
for(i=59;i-->9;)document.write("<hr color="+i+i+i+" size=20 width=20>")
```

Firefox still has the quirk of making circles.

(Small edit: Changed `for(i=61;i-->9;)` to `for(i=59;i-->9;)` because it was producing 52 squares)

---

**Old answer:**

This is based on my PHP answer, and uses almost the same ways to make the squares:

```
for(i=51;i--;)document.write("<hr color=rgb("+[i,i,i]+") size=20 width=20>");
```

Not the shortest answer, but it's worth adding here.

---

This solution **isn't compatible** with Chrome (produces multiple green colors) and Firefox (same result, but produces circles? o.O WTH?)

Since this is code-golf, a solution working with a specific version or a specific software is acceptable.

# Answer
> 7 votes
# Matlab - 33 bytes

```
surf(meshgrid(1:7)),colormap gray

```

Despite the verbose commands, the result is still quite compact. It looks a bit better if you replace `surf` with `surface` but that costs 3 chars.

If you don't notice the 50th gray square that is because it is a bit bigger than the others!

# Answer
> 6 votes
# JavaScript - 70 bytes

```
for(i=51;i-=1;)document.write('<a style=opacity:'+i/50+'>■</a>')
```

# Answer
> 6 votes
# PHP (~~62~~ ~~60~~ ~~63~~ ~~72~~ ~~71~~ ~~62~~ 59 bytes):

I've made the shortest I could find:

```
for($i=59;$i-->9;)echo"<hr color=$i$i$i size=20 width=20>";

```

This is **exactly** the same code as my Javascript answer (with 71 bytes).

But **SO MUCH** shorter!

This have a quirk in Firefox: instead of squares, Firefox makes **circles**! (Go insanity!)
Othen than that, all the browsers produce the right color (even with the missing `#` on the `color` attribute).

---

**Invalid submits and changelog**:

Old answer, with 62 bytes.

```
while($i++<51)echo"<hr color=rgb($i,$i,$i) size=20 width=20>";

```

All shades are perfectly aligned.

This solution won't work for Chrome (will produce squares with multiple colors) and Firefox (which makes circles o.O Yes, **circles** with `<hr>`! Horizontal ruler is a circle on Firefox!).
You can test it on IE11 and it should be fine.

---

(simply removed from above)

I've noticed something awful: It was outputting `#111` instead of `#010101` for some colors.

This meant that some colors were repeating.

Therefore, I had to sacrifice a few bytes:

```
<?while(f>$c=dechex(65-$i++))echo"<hr color=#$c$c$c size=20 width=20>";

```

Outputs the 50 shades in perfect order, from lighter to darker.

Due to a correct point made by @edc65, I had to add `width=20`, to produce **perfect squares**.

Reduced one more byte by replacing `f!=$c` with `f>$c`, which works perfectly.

---

Final version, without `width=20`:

```
<?while(f!=$c=dechex(65-$i++))echo"<hr color=#$c$c$c size=20>";

```

This is invalid because it is required to output squares.
This outputs the shades from lighter to darker.

---

Reduced 1 byte by switching to a `while` loop, like this:

```
<?while($c=dechex(50-$i++))echo"<hr color=#$c$c$c size=20>";

```

First solution:

```
<?for($i=50;$c=dechex($i--);)echo"<hr color=#$c$c$c size=20>";

```

This doesn't have the shades neatly ordered, but there are 50 different ones.

There is nothing stating that they must be ordered, but there is a requirement on size.

I hope I can reduce it a lot more.

You can test it on http://writecodeonline.com/php/ (click on "Display as HTML").

# Answer
> 6 votes
**Processing, 66 characters:**

```
size(1000,20);for(int i=0;i<981;i+=20){fill(i/4);rect(i,0,20,20);}

```

# Answer
> 5 votes
# PostScript, 34 bytes

In ISO-Latin-1 encoding:

```
20’›‡üˆì0{’81e3’6’–10’k0ˆ                   (note, this is a Line Feed)
’c’§}’H

```

This is the binary equivalent to:

```
20 setlinewidth 1020 -20 0 { dup 1e3 div setgray 10 moveto 0 10 lineto stroke } for

```

(This assumes that you are using it on a device that is at least 1000 points \[= 10 inches = 25.4 cm\] wide.)

# Answer
> 5 votes
# CSS (87 chars)

Uses animation ;)

```
:after{content:'\25A0';font:9em z;animation:g 8s steps(50)}@keyframes g{to{color:#fff}}

```

The runnable version is longer since Webkit still needs the vendor prefix. :(

```
:after{content:'\25A0';font:9em z;-webkit-animation:g 8s steps(50);animation:g 8s steps(50)}@-webkit-keyframes g{to{color:#fff}}@keyframes g{to{color:#fff}}
```

If we're allowed a random, empty `<a>` element, we can get it down to just 72 characters:

```
a{padding:3em;animation:g 8s steps(50)}@keyframes g{to{background:#000}}

```

See? CSS is a legit programming language!

# Answer
> 4 votes
# R, 36 bytes

I can make freekvd's answer shorter trivially.

```
x=9:59/59;symbols(x,sq=x,bg=gray(x))

```

(Sorry for not making a comment under his solution. Stackexchange does not allow me to make comments, vote etc yet).

# Answer
> 4 votes
# C# - 173

**Using LINQPAD**

```
var b=new Bitmap(1000,20);var g=Graphics.FromImage(b);for(int i=0;i<50;i++)g.FillRectangle(new SolidBrush(Color.FromArgb(i*5,i*5,i*5)),new Rectangle(i*20,0,20,20));b.Dump();

```

**Expanded**:

```
var b = new Bitmap(1000, 20);
var g = Graphics.FromImage(b);
for (int i = 0; i < 50; i++)
    g.FillRectangle(new SolidBrush(Color.FromArgb(i * 5, i * 5, i * 5)), new Rectangle(i * 20, 0, 20, 20));
b.Dump();

```

**Output**:

# Answer
> 4 votes
# DrRacket - 83

Just for the sake of firing up DrRacket 1 year after "Introduction to Systematic Program Design".

**EDIT**:

```
(require htdp/image)(map(λ(i)(rectangle 50 50'solid(make-color i i i)))(range 50))

```

# Answer
> 4 votes
# JavaScript, 152 bytes.

Okay, so maybe this isn't the best solution but here is mine.

```
function b(a){c=document
e=c.createElement('p')
with(e.style){background="rgb("+[a,a,a]+")"
width=height="20px"}c.body.appendChild(e)
a<245&&b(a+5)}b(0)

```

Here is the output with css float left (just so it is easier to count the squares) and without:

# Answer
> 3 votes
# **R 45 42 characters**

New version, after some comments (thanks!):

```
plot(1:50%%5,col=gray(1:50/60),ce=5,pc=15)

```

## Old version

It generates an error, but works fine :)

```
plot(x<-1:50,x%%5,col=gray(x/60),lw=30,pc=22)

```

# Answer
> 3 votes
**C++ Win32: 141 chars and 171 chars**

**C++ 171 chars**

```
#include"stdafx.h"#include<windows.h>int _tmain(){HDC h=GetDC(0);for(int i=0;i<50;i++){SelectObject(h,CreatePen(0,9,RGB(64+i,64+i,64)));Rectangle(h,i*9,i*9,i*9+9,i*9+9);}}

```

This draws 50 grey boxes to your desktop.

Which is super long, but pretty good for actually drawing squares in C++. I doesn't think I was ever going to win/not-come-last but I'm pretty satisfied with this. I can't guarantee the whole pixel thing as I use coordinates, but IWOMM :D.

I don't know if win32 counts as a standard library of c++, but I was more interested in the win32 than the c++ tbh. I had a crack at GDI, which look prettier but is super verbose. I was hoping I could get a win32 `ColorChooser` and turn them all grey for instant victory, but alas no.

Here's the idea (I've removed the resource leak from this extended version):

```
#include "stdafx.h"
#include <windows.h>
int _tmain(int a, _TCHAR* b[])
{
   HDC h=GetWindowDC(GetDesktopWindow()); //Zero works for GetDesktopWindow() as  Konrad Rudolph points out. GetDC is a good as GetWindowDC.
   for (int i = 0; i < 50; i++){
       HPEN p = CreatePen(PS_COSMETIC, 9, RGB(64 + i, 64 + i, 64)); //PS_COSMETIC is 0
       SelectObject(h, p); MoveToEx(h, 0, 0, NULL); //We can get away with removing MoveToEx and assuming it starts in the top left
       Rectangle(h, i * 9, i * 9, i * 9 + 9, i * 9 + 9); DeleteObject(p);
   }
   DeleteDC(h); //Or was it releaseDC? Who cares. The golf'd code leaks it anyway.
}

```

Also this can happen. When you want to get rid of it you just 'wipe' it away with another window. You would also not believe how slow this is to execute.

**Konrad Rudolph's comment: C++ 141**

```
// stdafx.h isn’t needed.
// However, we DO need the line break after the include,
// even in the golf version.
#include <windows.h>
// _tmain => main; VC++ accepts both.
int main()
{
   HDC h = GetDC(0);
  // Remove i++ here …
  for (int i = 0; i < 50;){
  // 65793 == 0x010101; multiplying with 1…50 generates
  // grey tones and is much shorter than RGB macro use
  SelectObject(h, CreatePen(0, 9, i*65793));
  // i * 9 + 9 == i * 10
  // … add i++ here.
  Rectangle(h, i * 9, i * 9, i * 10, i++ * 10);
  }
}

```

short.cpp

```
#include <windows.h>
int main(){HDC h=GetDC(0);for(int i=0;i<50;){SelectObject(h,CreatePen(0,9,i*65793));Rectangle(h,i*9,i*9,i*10,i++*10);}}
//141 with the line break

```

# Answer
> 3 votes
# Pyth \- 23 21 bytes

Is similar to CJam solution. Outputs is PGM format, save output as foo.pgm and view here. Edited it to make it conform to PGM specs so that lines are less than 70 chars long, in fact they are only one pixel long.

```
K50"P2"*KKKKVKjbS*UKK

```

Generates: Is fifty fifty by fifty squares. Goes from black to 49/50 of the way to white.

```
K50             K=50
"P2"            Prints P2 or pgm header magic #
*KK             Prints the length: 50*50
K               Prints width: 50
K               Prints value of white: 50
V         K     Do 50 times to make height of square 50
 j              joins by
  b             linebreaks
   S            Sort to bring out make each shade consecutive
    *  K        Times 50 to make length 50
     UK         Unary range 50 (0-49)

```

# Answer
> 3 votes
## R - 35 characters

Barplot uses `gray.colors` by default, helpful to save some bytes. To make sure the size is sufficient regardless of the screen size, the window size has to be defined beforehand, with x and y size picked as to generate a 1:1 aspect ratio.

```
x11(,1.7,23);barplot(matrix(1,50))

```

Output, rotated 90° and sized down:

As per comments below, the `x11()` results vary between machines. Hence, a safer option - also forcing aspect ratio of 1 - is `dev.new`. Run from terminal:

```
dev.new(height=20);barplot(matrix(1,50),as=1)

```

That's 46 characters. If manual resizing is allowed, `barplot(matrix(1,50),as=1)` is enough - only 27 characters.

# Answer
> 3 votes
# HTML/CSS - 81 characters

This is a very borderline solution because the shades aren't displayed very accurately (Chrome and Firefox both just use dithering), but in theory it "should" display 50 distinct shades. Also, the code is probably not very W3C compliant, but it compiles on any browser that knows CSS3.

```
<div style="height:1000px;width:20px;background:linear-gradient(#000,#303030);"/>

```

Note that 0x30 is 50 and 1000 is 50\*20.

# Answer
> 3 votes
# C (~~73~~ 65 characters)

Outputs a binary PGM to `stdout`, 20x20 squares.

```
s;main(){puts("P5 1000 20 50");while(s<2e4)putchar(s++%1000/20);}

```

Moar tricks would have been possible with 2^n instead of 50 shades, but nevermind.

# Answer
> 2 votes
## CoffeeScript, 86 bytes

As per edc56's comment on the JavaScript solution:

```
i=90;document.write '<p style=background:#'+i+i+i--+';height:1em;width:1em>'while i>40

```

# Answer
> 2 votes
# Python 2, 78 characters

This prints an image in PGM format to standard output (I took the idea from aditsu's CJam answer):

```
print"P2 2500 50 51"
r=range(50)
for x in r:
 for y in r:
  for z in r:print y

```

I wish Python would let me put all 3 `for`s on the same line. At least it lets me use a single space (or single tab) for each indentation level. I tried using variants of `for t in itertools.product(r,r,r)` instead, but the import is long and kills the benefit.

# Answer
> 1 votes
**Mathematica, 20 characters**

```
ArrayPlot@{Range@50}

```

gives the following output:

# Answer
> 1 votes
# Haskell 133

```
import Data.List
r=replicate 20
f 0=""
f i=(f(i-1))++(concat$r$'\n':(intercalate " "$r$show i))
main=putStr $"P2\n20 1000\n50"++f 50

```

outputs in Netpbm Format to stdout

# Answer
> 1 votes
## FFmpeg, 61 bytes

```
ffplay -f lavfi color=s=1000x20,format=y8,geq=8+4*trunc(X/20)

```

# Answer
> 0 votes
**Javascript (60 char)**

```
for(i=51;i--;)document.write("<hr color="+i+i+i+" size=20>")
```

# Answer
> 0 votes
# Python, 72 bytes

```
print'P2 1000 20 50 '+20*(''.join([20*(str(x)+' ')for x in range(50)]))

```

Another PPM answer, usage:

```
python golf_grey.py > grey.ppm

```

# Answer
> 0 votes
# Excel VBA, 60 Bytes

Anonymous VBE immediate window function that takes no input and outputs to the range `[A1:A50]` on the `ActiveSheet` object

```
For i=1To 50:j=5*i:Cells(i,1).Interior.Color=RGB(j,j,j):Next

```

# Answer
> 0 votes
# Perl 5 \+ `-M5.10.0`, 39 bytes

Outputs PGM format.

```
say"P5 20 1000 50 ",map chr()x400,0..49
```

Try it online!

---
Tags: code-golf, graphical-output
---


title: Convert between graph representations

text:
# Question
Title: Convert between graph representations
## What?

Let's say I have this graph:

```
   1
    \
     \
2     3
 \   /
  \ /
   4

```

I can represent it in 2 ways:

1. A list of connected vertices. `[[1,3],[2,4],[3,4]]`
2. A boolean matrix which shows where edges are:

```
c |1 2 3 4
--|-------
1 |0 0 1 0
2 |0 0 0 1
3 |1 0 0 1
4 |0 1 1 0
----- or -----
[[0,0,1,0],[0,0,0,1],[1,0,0,1],[0,1,1,0]]

```

## Task

* Your code should take input in the form of 1 (as a vertex list) and output it as 2 (as an adjacency matrix)
* The graph is not directed (aka it is an undirected graph).
* You can also accept input which is 0-indexed. For example: `[[0,2],[1,3],[2,3]]`
* This is code golf, shortest answer wins.
* You can also output 2 different values instead of 1 and 0.

## Test cases

```
[[1,2],[3,4]] -> [[0,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,0]]
[[1,3],[2,4],[3,4]] -> [[0,0,1,0],[0,0,0,1],[1,0,0,1],[0,1,1,0]]
[[1,2],[2,3],[5,6]] -> [[0,1,0,0,0,0],[1,0,1,0,0,0],[0,1,0,0,0,0],[0,0,0,0,0,0],[0,0,0,0,0,1],[0,0,0,0,1,0]]
[[1,2]] -> [[0,1],[1,0]]
[[1,2],[4,5]] -> [[0,1,0,0,0],[1,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1],[0,0,0,1,0]]
[[4,5]] -> [[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1],[0,0,0,1,0]]
[[4,5],[2,1]] -> [[0,1,0,0,0],[1,0,0,0,0],[0,0,0,0,0],[0,0,0,0,1],[0,0,0,1,0]]

```

# Answer
# APL (Dyalog Extended), 6 bytes

```
¯⍸⊢,⌽¨

```

Try it online!

When given an adjacency matrix,  gives the edge list (indices of 1's). Therefore the inverse `¯⍸` solves this challenge when we add the reverse edges to the input list.

I used Extended here for the short syntax for inverse functions and because the inverse of  doesn't require its input to be sorted.
> 10 votes

# Answer
# , ~~46~~ 43 bytes

*Edit: -3 bytes thanks to pajonk*

```
function(x,m=0*diag(max(x))){m[x]=1;m|t(m)}

```

Try it online!

Input is 2-column matrix with each row representing 2 connected vertices; output is matrix of `TRUE` and `FALSE` to indicate pairwise connections.

We could save 2 more bytes for 41 bytes by returning a matrix of falsy (zero) and truthy (either `1` or `-1`) to indicate connections.
> 7 votes

# Answer
# Jelly, 4 bytes

```
;UŒṬ

```

A monadic Link that accepts a list of pairs of positive integers (the vertex list) and yields a list of lists of `1`s and `0`s (the adjacency matrix).

**Try it online!** Or see the test-suite.

### How?

```
;UŒṬ - Link: list of pairs of positive integers, V
 U   - reverse each pair in V
;    - V concatenate that
  ŒṬ - multi-dimensional array with 1s at those coordinates and 0s elsewhere

```
> 5 votes

# Answer
# BQN, ~~38~~ 16 bytes

*Edit: -22 bytes thanks to a change-of-approach provoked by ~~goading~~ clever hint from ovs.*

*Edit2: changed `+` to  (logical OR) so that if there are any vertices connected to themselves, which would appear on the output matrix diagonal, they are still represented as `1` and not `2`; thanks to Neil for spotting this*

```
+⟜⍉⊢∊˜·↕2⥊1+⌈´∘∾

```

Try it at BQN online REPL

Uses zero-indexed input.

The BQN `Range` () function has the behaviour: "if its argument is list of numbers, then it returns an array of list indices" (here).
So we just use  to construct an array filled with indices, check whether each index is present in the input, and then combine the result with its transpose (to fill-in the elements corresponding to the same connections the other-way-around).

```
∨⟜⍉⊢∊˜·↕2⥊1+⌈´∘∾    # full train:
                ∾   # flatten the input connections,
             ⌈´∘    # get the maximum,
           1+       # add 1 (since 0-based indexing),
         2⥊         # duplicate it,
       ·↕           # and construct an array of 0-based 2d-coordinates;
      ˜             # now, for each 2d-coordinate,
    ⊢∊              # check if it's in the input (1) or not (0);
∨                   # finally, logical-OR the result
 ⟜⍉                 # with the transpose of itself

```
> 4 votes

# Answer
# 05AB1E, 14 bytes

```
Z©LãδQ.«~®ôDø~

```

The lack of builtins to check if a list is inside another list in 05AB1E is as always pretty dang annoying.. :/

Try it online or verify all test cases.

**Explanation:**

```
Z              # Push the flattened maximum of the (implicit) input
 ©             # Store it in variable `®` (without popping)
  L            # Pop and push a list in the range [1,®]
   ã           # Cartesian product to get all pairs of this list
    δ          # Apply double-vectorized with the input-pairs:
     Q         #  Check which pairs are equal
      .«       # Then reduce this list of lists by:
        ~      #  Bitwise-OR on the bits at the same positions
         ®ô    # Split this list into parts of size `®`
           D   # Duplicate this matrix of bits
            ø  # Zip/transpose; swapping rows/columns
             ~ # Bitwise-OR the bits at the same positions again
               # (after which the result is output implicitly)

```
> 3 votes

# Answer
# Python 3, ~~90~~ ~~88~~ ~~87~~ 86 bytes

*thanks to @Kevin Cruijssen for pointing out my mistake*

*thanks to @ophact for saving 2 bytes*

*thanks to @loopy walt for saving 1 byte*

*thanks to @Jonathan Allan for saving 1 byte*

```
lambda a:(r:=range(max(sum(a,[]))+1)and[[[i,j]in a or[j,i]in a for j in r]for i in r]

```

The input is a list of lists (as in the example).

# ~~85~~ ~~84~~ 83 bytes

*thanks to @loopy walt for saving 1 byte*

*thanks to @Jonathan Allan for saving 1 byte*

```
lambda a:(r:=range(max(sum(a,()))+1))and[[not{(i,j),(j,i)}&a for j in r]for i in r]

```

The input is a set of tuples.
> 3 votes

# Answer
# Mathematica 12, 15 bytes

```
AdjacencyMatrix

```

lol.

Mathematica can accept lists of tuples as edges in a graph, so

```
AdjacencyMatrix@{{1, 2}, {2, 3}, {3, 4}, {4, 1}}

```

produces

```
{{0, 1, 0, 1},
 {1, 0, 1, 0},
 {0, 1, 0, 1},
 {1, 0, 1, 0}}

```
> 3 votes

# Answer
# Charcoal, 24 bytes

```
≔⊕⌈Ｅθ⌈ιηＥη⭆η∨№θ⟦ιλ⟧№θ⟦λι

```

Try it online! Link is to verbose version of code. 0-indexed. Outputs the boolean matrix as a string array of `0` and `1`s for convenience. Explanation:

```
≔⊕⌈Ｅθ⌈ιηＥη

```

Calculate the size of the array.

```
⭆η∨№θ⟦ιλ⟧№θ⟦λι

```

For each cell of the array, check whether it or its transpose exists within the input list.
> 2 votes

# Answer
# Factor \+ `math.matrices`, 75 bytes

```
[ 1 swap dup mmax 1 + dup 0 <matrix> [ matrix-set-nths ] keep dup flip m+ ]

```

## Explanation

* Create a square zero-matrix large enough to accommodate the maximum value in the input.
* Set the (zero-indexed) input coordinates in the matrix to one.
* Add the resulting matrix to its transpose.

```
                         ! { { 0 1 } }
1                        ! { { 0 1 } } 1
swap                     ! 1 { { 0 1 } }
dup                      ! 1 { { 0 1 } } { { 0 1 } }
mmax                     ! 1 { { 0 1 } } 1
1                        ! 1 { { 0 1 } } 1 1
+                        ! 1 { { 0 1 } } 2
dup                      ! 1 { { 0 1 } } 2 2
0                        ! 1 { { 0 1 } } 2 2 0
<matrix>                 ! 1 { { 0 1 } } { { 0 0 } { 0 0 } }
[ matrix-set-nths ] keep ! { { 0 1 } { 0 0 } }
dup                      ! { { 0 1 } { 0 0 } } { { 0 1 } { 0 0 } }
flip                     ! { { 0 1 } { 0 0 } } { { 0 0 } { 1 0 } }
m+                       ! { { 0 1 } { 1 0 } }

```
> 2 votes

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

```
x=>[...Array(eval(`1+Math.max(${x})`))].map((_,i,t)=>t.map((_,j)=>x.some(v=>v==i+[,j]|v==j+[,i])))

```

Try it online!

:(
> 1 votes

# Answer
# Haskell, ~~66~~ 63 bytes

```
f x|r<-[1..maximum$id=<<x]=[[elem[i,j]x||elem[j,i]x|j<-r]|i<-r]

```

Try it online! Uses `True` and `False` for the output.
> 1 votes

# Answer
# PDL (Perl Data Language) 81 chars (the second paragraph)

```
use PDL;
use PDL::NiceSlice;
$_ = [[1,3],[2,4],[3,4]];

$i=pdl($_)-1;
$m=zeroes("$_",$_)for$i->max+1;
$m->indexND($i->glue(1,$i(-1:0))).=1;

print $m;

```

Explanation per line:

* construct indices ndarray, turn 1-based to 0-based
* find highest index+1; make square matrix that size; `""` is to coerce to Perl scalar not ndarray as `zeroes` with ndarray first arg copies its dimensions
* `$i(-1:0)` reverses order of indices in 0th dimension, i.e. symmetrises; `glue(1,...)` adds rows; `indexND` selects the given elements; set them to 1
> 0 votes

---
Tags: code-golf, matrix, graph-theory
---


title: Write an interpreter generator

text:
# Question
Title: Write an interpreter generator
There are quite a few accumulator-based programming languages featured in challenges across the site, but it's a little tiring to have to write almost identical code for each one. So in this challenge you will write a program which can generate interpreters from an input.

How does this work? Let us take this example:

```
[a ** 3, b * 2, c + 15, d = 0, e / 8]

```

This is not the only input format allowed. You are allowed to take input as an array of directives, an array of strings or even an entire string composed of these directives. Each directive looks similar to this:

```
[a, *, 3]

```

In this case, the `a` command multiplies (`+` means add, `-` means subtract, `*` means multiply, `/` means divide, `**` means exponentiate and `=` means assignment) the accumulator by `3` (the third element). So with the aforementioned input, we end up with this schema:

```
the command `a` cubes the accumulator
the command `b` doubles the accumulator
the command `c` adds 15 to the accumulator
the command `d` assigns the accumulator to 0
the command `e` divides the accumulator by 8

```

This means that typing the command `cabdcbbe` will output 7.5, because: (these rules apply to all generated "languages")

* the accumulator is automatically initialized to 0 at the beginning of a program
* the accumulator is implicitly outputted at the end of a command
* `(0 + 15)**3*2` is disregarded because d reassigns the accumulator to zero
* `(0 + 15)*2*2/8 = 7.5` When given an array of directives, your program should output a complete program in your favorite language (might be the one you write your answer in, but not necessarily) which takes a valid program in the newly generated language and outputs the accumulator at the end of it. If I were using JavaScript and were passed the array we discussed, my program might output

```
const program = prompt();
let acc = 0;
for (const command of program) {
  if (command === 'a') {
    acc = acc ** 3;
  } else if (command === 'b') {
    acc = acc * 2;
  } else if (command === 'c') {
    acc = acc + 15;
  } else if (command === 'd') {
    acc = 0;
  } else if (command === 'e') {
    acc = acc / 8;
  }
}
alert(acc);
```

now, for some more rules:

* the input will always be valid. No destructive operators will be entered (such as a / 0 which divides the accumulator by zero.
* each command will perform only one operation on the accumulator, so there will be no command which multiplies the accumulator by 3, squares it and adds 5 to it all in one go.
* each command is one letter long.
* the shortest answer in bytes wins. \[code-golf rules\]
* the interpreter should read the program from STDIN or from a file.
* on TIO, you may pre-define the input array in the header section, but your program should obviously be able to handle any valid input.
* you only need to support the six operators mentioned previously.
* commands can involve floating point numbers and not only integers
* you may replace the operators but you must then state which ones you changed
* you may output a float even if all operators yield integers. You may not truncate outputs however

# Answer
> 5 votes
# , 61 56 53 52 bytes

```
1 :0
('0'".@,~,@,.&' ')[u".@;@}:@,@,."1;:@'=: & &'
)

```

Try it online!

Note: -3 bytes off TIO for `f=:`

Operator changes used to match J's built-ins:

* `**` -\> `^`
* `/` -\> `%`
* `=` -\> `]`

Additional notes:

* This is adverb that modifies the program to interpret, which is given as a list of 3-element directives. The resulting verb then takes the input as an argument, and returns the result.
* Assumes the program string to execute will be read from right-to-left -- again, this is in keeping with J's normal convention.

# Answer
> 4 votes
# PowerShell 7, 133 ... 101 100 bytes

-5 bytes thanks to Wasif! Then +1 byte to fix an issue with `--` always being read as the decrement operator, regardless of context.
-2 bytes thanks to mazzy!

Takes input as an array of directives in the form `@('command','operation',number)`; the output is a TIO-Compatible PowerShell program.

```
'switch("$args"|% T*y){'
$args|%{$1,$2,$3=$_
"$1{`$a="
$2[1]?"""`$a*""*$3+1|iex}":"`$a$2 $3}"}
'}$a'

```

Link is to a 116-byte TIO-Friendly (PowerShell 6 and below) version of the code. Try it online!

### Explanation

```
'switch("$args"|% T*y){'        # The first part of the interpreter switches
                                # on the input program's characters. Switching
                                # on an array in powershell processes the
                                # switch statement for each element.

$args|%{$1,$2,$3=$_             # For each array in the input array, set $1,
                                # $2, $3 to the first, second, and third
                                # element, respectively.

"$1{`$a="                       # output the case for the letter of the command
                                # start the case with setting the accumulator
                                # equal to whatever else is in this case

$2[1]                           # If the second character of the command exists
                                # In other words, the command is '**'

    ?"""`$a*""*$3+1|iex}"       # Make the body of the case a special way to
                                # calculate powers in PowerShell which is
                                # shorter than [Math]::Pow - effectively
                                # builds a string representation of the
                                # calculation, then evaluates that string.

    :"`$a$2$3}"}                # If the command isn't '**', we just make the
                                # command '{accumulator}{command}{number}'
                                # for example: '$a/3', making the whole case
                                # '{$a=$a/3}'

'}$a'                          # Close the switch block, output the accumulator

```

### Output

Outputs a very ugly interpreter; for the example input provided in the challenge, the interpreter looks like this:

```
switch("$args"|% T*y){
a{$a=
"$a*"*3+1|iex}
b{$a=
$a*2}
c{$a=
$a+15}
d{$a=
$a=0}
e{$a=
$a/8}
}$a

```

And, of course, Try The Output Interpreter!

# Answer
> 4 votes
# Python 3.8, ~~120~~ ~~106~~ 93 bytes

*Saved 27 bytes thanks to @kaya3*

```
lambda f:lambda i,a=0:[a:={n:eval({'=':v}.get(o,str(a)+o+v))for n,o,v in f}[k]for k in i][-1]

```

Try it online!

Hey, my first golf! This golf utilizes Python 3.8's walrus operator. You can insert the interpreter's commands as a list tuples into a function that returns a function which accepts commands as a string/list of strings (and, optionally, an initial value for the accumulator).

If this `lambda` is assigned to `f` and run as:

```
f([('a','**','3'),('b','*','2'),('c','+','15'),('d','=','0'),('e','/','8')])

```

will give you:

```
<function __main__.<lambda>.<locals>.<lambda>(i, a=0)>

```

which if assigned to f2 can be run as:

```
f2('cabdcbbe')

```

which outputs:

```
7.5

```

Ungolfed version:

```
def interpreter_generator(commands):
    def interpreter(instructions, accum=0):
        for i in instructions:
            accum = {n: eval({'=': v}.get(o, str(accum) + o + v)) for n, o, v in commands}[i]

        return accum

    return interpreter

commands = [('a','**','3'), ('b','*','2'), ('c','+','15'), ('d','=','0'), ('e','/','8')]
instructions = 'cabdcbbe'
my_interpreter = interpreter_generator(commands)
print(my_interpreter(instructions))

```

# Answer
> 3 votes
# Python 3, ~~202~~ \\$\cdots\\$ ~~136~~ 134 bytes

```
lambda s:'%{\nfloat p;\n%}\n%%\n'+''.join(a+' p=p'+b+('(','w(p,')[b>'=']+c+');\n'for a,b,c in s)+'%%\nmain(){yylex();printf("%f",p);}'

```

Try it online!

Inputs the target language as a list of 3-tuples of strings. Uses `o` as the power operator.
Generates the Flex code that will generate a C program that will parse the input language.

If this `lambda` is assigned to `f` and run as:

```
print(f([["a","o","3"],["b","*","2"],["c","+","15"],["d","=","0"],["e","/","8"]]))

```

then that will output:

```
%{
float p;
%}
%%
a p=pow(p,3);
b p=p*(2);
c p=p+(15);
d p=p=(0);
e p=p/(8);
%%
main(){yylex();printf("%f",p);}

```

which if stored in file `write_an_interpreter_generator.l` and then run through flex and then compiled:

```
flex write_an_interpreter_generator.l
gcc lex.yy.c -o write_an_interpreter_generator -lfl -lm

```

will produce lexer `write_an_interpreter_generator`, which if run as:

```
echo 'cabdcbbe' | ./write_an_interpreter_generator

```

outputs:

```
7.500000

```

# Answer
> 3 votes
# JavaScript (ES6), 73 bytes

Expects an array of `[letter, operation, value]` triplets. Returns a function that expects an array of letters.

```
a=>`a=>a.reduce((A,c)=>eval({${a.map(([c,o,v])=>c+`:'A${o+v}'`)}}[c]),0)`

```

Try it online!

# Answer
> 2 votes
# Jelly, 7 bytes

```
ZyW€}FV

```

Try it online!

The example language would be represented like this: `[['a', '*3'], ['b', '×2'], ['c', '+15'], ['d', 'ṛ0'], ['e', '÷8']]` Operators:  = assignment, `+` = addition, `_` = subtraction, `×` = multiplication, `÷` = division, `*` = power. The program is given as the second argument.

# Answer
> 2 votes
# Haskell, 121 bytes

```
f d="($0).foldr(\\(Just g)->(.g))id.map(`lookup`["++(init$d>>=(\(c,o,p)->["('",c,"',(",o,"(",p,"))),"]>>=id))++"]);x!y=y"

```

Try it online!

Uses the default operators except for `=` which is replaced by `!`.

The function `f` accepts a list of directives such as `[("a","**","3"),("b","*","2"),("c","+","15"),("d","!","0"),("e","/","8")]` and returns a Haskell function such as

```
($0).foldr(\(Just g)->(.g))id.map(`lookup`[('a',(**(3))),('b',(*(2))),('c',(+(15))),('d',(!(0))),('e',(/(8)))]);x!y=y

```

(Try it online!). This function is the interpreter; in the above example, when called with input `"cabdcbbe"`, it returns `7.5`.

## How?

The idea is to use the list of directives to embed a lookup table in the interpreter. In the above example, the lookup table is `[('a',(**3)),('b',(*2)),('c',(+15)),('d',(!0)),('e',(/8))]` (some brackets removed for clarity). This table maps each character to the corresponding function. Using the lookup table, the interpreter is able to convert the list of characters (e.g. `"cabdcbbe"`) to a list of functions (e.g. `[(+15),(**3),(*2),(!0),(+15),(*2),(*2),(/8)]`), which is then `foldr`ed with the composition operator `(.)` to yield the full (interpreted) program. Finally, the program (which, like everything in Haskell, is a function) is applied to the value `0`, returning the desired result.

# Haskell, 113 bytes

Assuming the list of instructions can be read right-to-left.

```
f d="g i=foldr(.)id[f|c<-i,(a,f)<-["++(init$d>>=(\(c,o,p)->["('",c,"',(",o,"(",p,"))),"]>>=id))++"],a==c]0;x!y=y"

```

Same idea as above, but without the need to reverse the string.

# Answer
> 2 votes
# Ruby, 55 bytes

```
->x{"a=0;$<.chars{|c|a=eval(?a+#{x.to_h}[c])*1.0};p a"}

```

Try it online!

Outputs a full Ruby program which reads characters from the input. As it turns out, returning a function seems to be longer, by my attempt.

Takes input as an array like:

```
[
    ["a", "**3"],
    ["b", "*2"],
    ["c", "+15"],
    ["d", "=0"],
    ["e", "/8"],
]

```

The function simply converts this to a hash and indexes each character in the input by this. Unfortunately I can't use `$.` as the accumulator since it cannot store floats, apparently. The `a=0;...;p a` bit annoys me, but I couldn't quite squeeze it out.

## Alternative Attempts

```
->x{"a=0;$<.chars{|c|a=eval ?a+#{x.to_h}[c]+'.0'};p a"}
->x{"p$<.chars.inject(0){|a,c|eval(?a+#{x.to_h}[c])*1.0}"}
->x{"p$<.chars.inject(0){|a,c|eval ?a+#{x.to_h}[c]+'.0'}"}

```

Similar variants for returning functions, but I couldn't find a neat way to abuse the function nature.

# Answer
> 2 votes
# Haskell, 89 bytes

```
f c="a!c"++concat["|c=='"++a++"'=a"++o++x|(a,o,x)<-c,o/="="]++"|1>0=0\ne=print.foldl(!)0"

```

Try it online!

* generates this Haskell program:

```
a!c|c=='a'=a**3|c=='b'=a*2|c=='c'=a+15|c=='e'=a/8|1>0=0
e=print.foldl(!)0

```

Try it online!

* uses 1\>0 guard to handle operator `=`

# Answer
> 2 votes
# Charcoal, 35 bytes

```
”y≔⁰θＦ⁺Ｓψ≡ι”ＦＡ⭆⪪”y≔,θＩ,θ”,⁺§ιλκ”yＩθ

```

Try it online! Generates this Charcoal program:

```
≔⁰θＦ⁺Ｓψ≡ιa≔ＸθＩ3θb≔×θＩ2θc≔⁺θＩ15θd≔⎇⁰θＩ0θe≔∕θＩ8θＩθ

```

Try it online! Explanation:

```
”y≔⁰θＦ⁺Ｓψ≡ι”

```

Print code that initialises the accumulator and switches over the input's characters, plus a null terminator, in a loop.

```
ＦＡ

```

Loop over each directive.

```
⭆⪪”y≔,θＩ,θ”,⁺§ιλκ

```

Interleave the directive with the characters needed to turn it into a case clause.

```
”yＩθ

```

Print code to output the final value of the accumulator.

The commands can be any ASCII string of the user's choice, not just a single letter.

The required operators are as follows:

* : Exponentiation
* `×`: Multiplication
* : Division
* : Addition
* : Subtraction
* `⎇⁰`: Assignment

Two other operators are also supported, these are:

* `÷`: Integer division
* : Modulo

# Answer
> 2 votes
# Python 3.8 (pre-release), 68 bytes

```
lambda c:(f:=lambda p,a=0:f(p[1:],eval(f'(a{c[p[0]]})'))if p else a)

```

Try it online!

replaces the '=' operator with ':=' in order to utilize python 3.8+ walrus expressions

# Answer
> 1 votes
# Excel outputs VBA, 167 bytes

```
="Function f(s)
for i =1 to len(s)
j=mid(s,i,1)
select case j
"&TEXTJOIN("
",,IF(A:A="","","CASE """&A:A&"""
a"&IF(B:B="=","","=a")&B:B&C:C))&"
End Select
Next
f=a
End Function"

```

Input is in columns A, B, C. Oddly enough output must be pasted somewhere else before it can be copied into VBA. Otherwise it adds quotes in weird places. Excel is a quirky one.

# Answer
> 1 votes
# Python 2, 153 bytes

```
print"0  v\n<vi<"
for c,p in input():n=int(p[1:],16);p=[n/10*"a+"+`n%10`+p[0],":"*n+"*"*n][p[0]=="^"];print"^>:'"+c+"'=?!v~"+p+"\n^v       <"
print" >~n"

```

Try it online!

Example output:

# \>\<\>, 146 bytes

```
0  v
<vi<
^>:'a'=?!v~:::***
^v       <
^>:'b'=?!v~2*
^v       <
^>:'c'=?!v~5a++
^v       <
^>:'d'=?!v~~0
^v       <
^>:'e'=?!v~8,
^v       <
 >~n

```

Try it online!

Currently this only handles positive integers; Negative integers could probably be handled with some more bytes but float arguments would be a huge pain. Division is floating point by default, however. Commands must be one character, but that character can be totally arbitrary.

The \>\<\> program works by keeping only the accumulator on the stack in between commands.

`/` is denoted by `,`, its \>\<\> equivalent. `^` doesn't exist in \>\<\>, so it's done by multiplying the accumulator by itself `n` times: e.g. `::::****` for `n=4`. `=` is implemented by dropping the accumulator with `~` and pushing the new value `n`.

Example \>\<\> program, commented:

```
    0  v                  | push 0 onto the stack; proceed down
    <vi<                  | read a command from input
    ^>:'a'=?!v~:::***     | The following pairs of lines:
    ^v       <            | :'c'=     | non-destructively compare to command character
    ^>:'b'=?!v~2*         |      ?!v  | proceed downwards if not equal
    ^v       <            |           | otherwise
    ^>:'c'=?!v~5a++       |      ~    | destroy the command
    ^v       <            |       n   | push the operand
    ^>:'d'=?!v~~0         |        op | do  acc <op> n
    ^v       <            |           | implicitly wrap around, hit ^, proceed back up
    ^>:'e'=?!v~8,         |
    ^v       <            | if no match is found we must be done
     >~n                  | destroy the terminating character and output
                          |   the last line will repeat and crash due to empty stack

```

# Answer
> 1 votes
# Wolfram Language (Mathematica), 55 bytes

```
lD/*##@0&@@ToExpression[#/.(#->"#"<>##2<>"&"&@@@l)]&

```

Try it online!

Input `^` for exponentiation and `-`  for subtraction.

---

### 42 bytes

```
lD/*##@0&@@<|#->Curry[#2]@#3&@@@l|>/@#&

```

Try it online!

This one's probably a bit too cheaty with the operator symbols - input the appropriate Mathematica function's name instead of the corresponding symbol.

# Answer
> 1 votes
# Emotion, 74 bytes

```
☕⛷⛷

```

Try it online!

Try the sample interpreter!

The input is a string of space-separated directives. Each directive is a comma-separated list of the instruction name, the operation, and the value.

The operation names have been changed for efficiency:

`+` -\> `add`

`-` -\> `subtract`

`*` -\> `multiply`

`/` -\> `divide`

`**` -\> `math.pow`

Explanation

```
 Store the first stack value in the a register.
 Push literal load 0
☕ Push literal swp
 Push literal iterate
 Push the value contained in the a register.
 Push a list of the first stack values split by spaces.
 Enter an iteration block over the first stack value.
 Push literal ldr o
 Push the value contained in the iteration element register.
 Push literal ,
 Push a list of strings obtained by splitting the second stack value with the first stack value.
 Store the first stack value in the b register.
 Push literal load
 Push the value contained in the b register.
 Push literal 0
 Push the value in the list of the second stack value at the index of the first stack value.
 Push the sum of the second and first stack values.
 Push literal if equal
 Push literal load
 Push the value contained in the b register.
 Push literal 2
 Push the value in the list of the second stack value at the index of the first stack value.
 Push the sum of the second and first stack values.
 Push the value contained in the b register.
 Push literal 1
 Push the value in the list of the second stack value at the index of the first stack value.
 Push a copy of the first stack value.
 Push literal set
 Enter a conditional block if the top two stack values are equal.
 Remove the first stack values from the stack.
 End a control flow structure.
⛷ Push literal end
 End a control flow structure.
⛷ Push literal end
 Collapse all stack values into a list, then push that list.
 Compile a list of Emotion instructions on the top of the stack and print the compiler output.

```

# Answer
> 0 votes
# CSASM v2.3.0.1, 985 bytes

Looks like we've come full circle. CSASM is a language written with a C# backer and is parsed by a C# interpreter and this code generates C# code that's an interpreter for another language...

---

Generates a C# file named `a` in the same directory the CSASM executable is executed from.

Expects a space-separated string for the commands and no spaces within the commands themselves.

**Example (input: `a+1 b*3 c**2 d/4 e=0`):**

Output:

```
using System;class A{static void Main(){var a=0.0;var s=Console.ReadLine();for(int i=0;i<s.Length;i++){if(s[i]=='a')a=a+1;else if(s[i]=='b')a=a*3;else if(s[i]=='c')a=Math.Pow(a,2);else if(s[i]=='d')a=a/4;else if(s[i]=='e')a=a=0;}Console.Write(a);}}

```

Formatted:

```
using System;
class Program{
    static void Main(){
        var a = 0.0;
        var s = Console.ReadLine();
        for(int i = 0; i < s.Length; i++){
            if(s[i] == 'a')
                a = a + 1;
            else if(s[i] == 'b')
                a = a * 3;
            else if(s[i] == 'c')
                a = Math.Pow(a, 2);
            else if(s[i] == 'd')
                a = a / 4;
            else if(s[i] == 'e')
                a = a = 0;
        }
        Console.Write(a);
    }
}

```

### Code

```
func main:
.local a : i32
.local b : str
.local c : f64
lda 0
sta $1
in ""
push " "
div
pop $a
push 1
pop $io.f0
push 2
pop $io.m0
push 1
pop $io.s0
push "a"
pop $io.p0
io.w0 "using System;class A{static void Main(){var a=0.0;var s=Console.ReadLine();for(int i=0;i<s.Length;i++){"
.lbl a
push $a
dup
ldelem $1
dup
pop b
push "**"
index
push 1
add
pop a
push b
len
pop $5
push 0
pop $2
.lbl b
push b
conv ~arr:char
ldelem $2
pop $3
clf.o
push $2
push 2
comp.gte
push $f.o
brfalse m
clf.o
push $3
push '+'
comp
push $f.o
brtrue g
push $3
push '-'
comp
push $f.o
brtrue g
.lbl m
clf.n
push $3
conv str
pop $3
clf.n
push b
push $2
push $5
substr
conv f64
pop c
push $f.n
brtrue h
push $2
brtrue f
push $1
brfalse e
io.w0 "else "
.lbl e
push "if(s[i]=='"
push $3
add
push "')a="
add
pop $4
io.w0 $4
br i
.lbl f
push a
brfalse g
io.w0 "Math.Pow(a,"
inc $2
br i
.lbl g
push "a"
push $3
add
pop $3
io.w0 $3
br i
.lbl h
io.w0 c
push $5
push 1
sub
pop $2
push a
brfalse k
io.w0 ")"
.lbl k
io.w0 ";"
.lbl i
inc $2
push $2
push $5
sub
brtrue b
inc $1
push $a
len
push $1
sub
brtrue a
io.w0 "}Console.Write(a);}}"
push null
pop $io.p0
ret
end

```

**Commented and ungolfed:**

```
func main:
    ; these locals are needed since CSASM only has 6 value registers
    .local hasExponent : i32
    .local curCommand : str
    .local commandValue : f64

    ; Initialize the outer loop counter to zero
    lda 0
    sta $1

    ; Get the input, split it along space chars and put it in $a
    in ""
    push " "
    div
    pop $a

    ; Initialize a file handle as writing, FileMode.Create and Stream
    push 1
    pop $io.f0
    push 2
    pop $io.m0
    push 1
    pop $io.s0

    ; Start the handle by setting the file path
    push "a"
    pop $io.p0

    ; The first chunk of the generated program
    io.w0 "using System;class A{static void Main(){var a=0.0;var s=Console.ReadLine();for(int i=0;i<s.Length;i++){"

    .lbl outerLoop
        ; Get the value in $a at index $1
        push $a
        dup
        ldelem $1

        ; Then set the variable "hasExponent" to if said value contains "**"
        dup
        pop curCommand
        push "**"
        index
        push 1
        add
        pop hasExponent

        ; Store the length into "$5"
        push curCommand
        len
        pop $5

        ; Initialize the inner loop counter to zero
        push 0
        pop $2

        .lbl innerLoop
            ; Get the char in "curCommand" at index $2 and put it in $3
            push curCommand
            conv ~arr:char
            ldelem $2
            pop $3

            ; Clear the Comparison flag
            clf.o

            ; if $2 >= 2, ignore the check below
            push $2
            push 2
            comp.gte
            push $f.o
            brfalse checkCommandValue
            clf.o
            ; if $3 == '+' or $3 == '-', don't try to parse the rest of the string
            ;   as an <f64> yet
            push $3
            push '+'
            comp
            push $f.o
            brtrue printCommandStart
            push $3
            push '-'
            comp
            push $f.o
            brtrue printCompoundStart

        .lbl checkCommandValue
            ; Clear the Conversion flag
            clf.n

            ; Convert the current char into a string and put it back into $3
            push $3
            conv str
            pop $3

            clf.n
            ; Get the rest of the substring
            push curCommand
            push $2
            push $5
            substr
            conv f64
            pop commandValue
            push $f.n
            brtrue printStatementEnd

            ; If $2 is > 0, the stuff after the "a=" part needs to be checked
            push $2
            brtrue checkPowStart

            ; If this is the first command being parsed, don't print the "else" part
            push $1
            brfalse printStatementStart
            io.w0 "else "

        .lbl printStatementStart
            ; Begin the if block
            push "if(s[i]=='"
            push $3
            add
            push "')a="
            add
            pop $4
            io.w0 $4
            br getNextChar

        .lbl checkPowStart
            ; If a is non-zero, this command used "**".  Thus, it needs to be converted
            ;   to Math.Pow()
            push hasExponent
            brfalse printCompoundStart
            io.w0 "Math.Pow(a,"
            inc $2
            br getNextChar

        .lbl printCompoundStart
            ; The other commands follow the pattern of "a = a <operator> <value>;"
            push "a"
            push $3
            add
            pop $3
            io.w0 $3
            br getNextChar

        .lbl printStatementEnd
            ; Print the value at the end of the command, then close the statement
            io.w0 commandValue
            push $5
            push 1
            sub
            pop $2
            push hasExponent
            brfalse notPowStatementClose
            io.w0 ")"
        .lbl notPowStatementClose
            io.w0 ";"

        .lbl getNextChar
            ; Increment $2 and see if there's still more chars to parse
            inc $2
            push $2
            push $5
            sub
            brtrue innerLoop

        ; Increment $1 and see if there's more commands to parse
        inc $1
        push $a
        len
        push $1
        sub
        brtrue outerLoop

    ; The last chunk of the generated program
    io.w0 "}Console.Write(a);}}"

    ; Close the file handle by setting the path to null
    push null
    pop $io.p0

    ret
end

```

# Answer
> 0 votes
# PowerShell, ~~102~~ 100 bytes

Inspired by @Zaelin Goodman

```
'switch("$args"|% t*y){'
$args-replace'^.','$0{$a=$a$''}#'-replace'.a.(\*\d+)','"$a*"$1+1|iex'
'}$a'

```

Try it online!

With arguments `a**3 b*2 c+15 d=0 e/8` the script generates:

```
switch("$args"|% t*y){
a{$a="$a*"*3+1|iex}#**3
b{$a=$a*2}#*2
c{$a=$a+15}#+15
d{$a=$a=0}#=0
e{$a=$a/8}#/8
}$a

```

Try it online!

---
Tags: code-golf, interpreter
---


title: Hello... eh, who?

text:
# Question
Title: Hello... eh, who?
# Introduction

You started to write a "Hello, World!" program, but after you wrote the part to print the hello, you forgot what your program should actually print. So now, you somehow managed it to write a program which can check if the entered word is what you search.

# The task

Your task is to write a program or function, which first prints `Hello... eh, whom should I greet?`, then asks for input, and if the input equals `world` ignoring capitalization, the program should print `Ah, yes. World.`, else it should print `No. That isn't what I meant.`.

**But** you are not allowed to use any of the bytes equivalent to the ASCII values of:
`worldWORLD`
\- that is, for those using code-pages not aligned with ASCII, bytes:
`0x...:` `77, 6f, 72, 6c, 64, 57, 4f, 52, 4c, 44`.

# Compact rules

* No substring of the byte-string `worldWORLD` may appear in your program or in the file name of the program on any way
* `print "Hello... eh, whom should I greet?"; if input.lower == "world" print "Ah, yes. World."; else print "No. That isn't what I meant.";`
* Leading or trailing spaces are ignored.
* This is a challenge, so the program with the lowest amount of chars wins!

# Answer
# SOGL, 67 bytes

```
P5√~!9!j┌⁰‚V{7Χ←½χķ²‘q"A6‘,u=?"ΤΞ¦▲ξ⌠²ō⅞Σ↔─╚‘p}"⁽∙šžøp⅔…ļ4∑Ν…ZH]└»‘

```

Explanation:

```
...‘                        push "Hello... eh, whom should I greet?"
    q                       output, without disabling implicit output
     "A6‘                   push "world"
         ,u=?       }       if equal to lowercased input
             "....‘           push "Ah, yes. World."
                   p          output, disabling implicit output
                     "...‘  push "No. That isn't what I meant."
                            implicitly output that if that hasn't been disabled by the if.

```
> 3 votes

# Answer
# Jelly, 70 bytes

```
“¡Kịy<⁷ẊṘṘsṁñAỵḋẇ,ẇʂI»Ṅø“¢ƈṫ(Ɲ¬÷Ø“¡ṣƓ»µɠŒteḊȧKȯ“TḲj/Ẇi¤cecṡĿt⁺ƘNƁ⁻»;”.

```

Jelly's code-page is equal to ASCII in the range `' '`, `0x20`, through to `'~'`, `0x7e`, inclusive so the lack of any of `worldWORLD` in the code above suffices (note: `ẇȯṘĿḊ` are not `woRLD` or equivalent bytes.)

**Try it online!**

This took a little fiddling to avoid the forbidden bytes:
all the naive string compressions contained illegal characters;
finding the first index of a sublist within another is performed with the `w` atom;
finding the length of a list (for chopping and measuring to replace `w`) uses `L` \- something I considered was summing the indices with `JS` (triangle(9)=45), I ended up using a list of strings and a separate trailing period to kill three birds with one stone <sup>\[sic\]</sup>, allowing a dequeue-flatten-dequeue chain, `ḊFḊ`, to pick out the word `World`, this can be further shortened by post-joining the list with the space using , allowing for a simple dequeue,  to be used instead saving another byte.

Adding the trailing period to whichever response is output as a single action also allowed compression without illegal bytes.

For some reason, the word `yes` is not in Jelly's dictionary, yet even though compressing `Ah, yes.` is the same length as the raw string, having the compression as a list of strings `['Ah, yes.',' World']` (`“¢ƈṫ(Ɲ¬÷Ø“¥ḄḞ»`) is shorter by two bytes than concatenating (`“Ah, yes.”;“¥ḄḞ»`), the *third bird*.

For the first message I compressed `Hell` as a word and prepended the string '...' with an 'o' to avoid the forbidden bytes.

Commented code:

```
W: “¡Kịy<⁷ẊṘṘsṁñAỵḋẇ,ẇʂI» - compressed string "Hello... eh, whom should I greet?"

R: “¢ƈṫ(Ɲ¬÷Ø“¡ṣƓ» - compressed list of strings ["Ah, yes.","World"]

D: “TḲj/Ẇi¤cecṡĿt⁺ƘNƁ⁻» - compressed string "No. That isn't what I meant"

WṄøRµɠŒteḊȧKȯD;”. - Main link: no arguments
W                 - "Hello... eh, whom should I greet?"
 Ṅ                - print and yield
  ø               - niladic chain separation, no input to the following
   R              - ["Ah, yes.","World"]
    µ             - monadic chain separation, call that L
     ɠ            - read a line from STDIN
      Œt          - title-case it (e.g. "wOrLd" -> "World")
         Ḋ        - dequeue L: ["World"]
        e         - exists in?       (0 or 1)
          ȧ       - and L            (0 or ["Ah, yes.","World"])
           K      - join with spaces (0 or "Ah, yes. World")
             D    - "No. That isn't what I meant"
            ȯ     - or               ("No. That isn't what I meant" or "Ah, yes. World")
               ”. - literal '.'
              ;   - concatenate      ("No. That isn't what I meant." or "Ah, yes. World.")

```
> 4 votes

# Answer
# Java 8, ~~376~~ 361 bytes

```
v->{System.\u006Fut.p\u0072int\u006Cn("He\u006C\u006C\u006F... eh, \u0077h\u006Fm sh\u006Fu\u006C\u0064 I g\u0072eet?");System.\u006Fut.p\u0072int\u006Cn(ne\u0077 java.uti\u006C.Scanne\u0072(System.in).next().equa\u006CsIgn\u006F\u0072eCase("\u0077\u006F\u0072\u006C\u0064")?"Ah, yes. \u0057\u006F\u0072\u006C\u0064.":"N\u006F. That isn't \u0077hat I meant.");}

```

-15 bytes switching from Java 7 to 8.

Try it online.

**Explanation:**

In Java you can use unicode escapes in the form of `\u####`. Fortunately, `u` wasn't one of the disallowed characters, so I've used these unicode escapes for the characters that are disallowed.

The method above, without unicode escapes:

```
v->{                            // Method with empty unused parameter & no return
  System.out.println("Hello... eh, whom should I greet?");
                                //  Print the greetings line
  System.out.println(new java.util.Scanner(System.in).next()
                                //  Get the user input from STDIN
    .equalsIgnoreCase("world")? //  If it's equal to (case-insensitive) "world":
      "Ah, yes. World."         //   Print the World-response line
    :                           //  Else:
      "No. That isn't what I meant.");}
                                //   Print the No-response line

```

Taking the input as parameter and returning a String instead of using STDIN/STDOUT (which I think is allowed reading the challenge again, so not sure why I hadn't done that four years ago when I posted my answer), it would be **239 bytes** instead:

```
s->"He\u006C\u006C\u006F... eh, \u0077h\u006Fm sh\u006Fu\u006C\u0064 I g\u0072eet?\n"+(s.equa\u006CsIgn\u006F\u0072eCase("\u0077\u006F\u0072\u006C\u0064")?"Ah, yes. \u0057\u006F\u0072\u006C\u0064.":"N\u006F. That isn't \u0077hat I meant.")

```

Try it online.
> 4 votes

# Answer
# JavaScript, ~~484~~ 347 bytes

This is horrible and could most likely be golfed more. Just seeing if I could answer in JavaScript with the restrictions.

```
z=({}+[]+{})[-~[]]
y=(!![]+[])[+!+[]]
x=([][[]]+[])[!+[]+!+[]]
v=this
c=n=>v[`St${y}ing`][`f${y}${z}mCha${y}C${z}${x}e`](n*9)
u=c(12)
t=c(13.3)
v[s=`a${u}e${y}t`](`He${u+u+z}... eh, ${t}h${z}m sh${z}u${u+x} I g${y}eet?`)
v[s](v[`p${y+z}mpt`]()[`t${z+c(8.5)+z+t}e${y+c(7.5)}ase`]()==t+(s=z+y+u+x)?`Ah, yes. ${c(9.7)+s}.`:`N${z}. That isn't ${t}hat I meant.`)

```

### Try it online!

```
z=({}+[]+{})[-~[]]
y=(!![]+[])[+!+[]]
x=([][[]]+[])[!+[]+!+[]]
v=this
c=n=>v[`St${y}ing`][`f${y}${z}mCha${y}C${z}${x}e`](n*9)
u=c(12)
t=c(13.3)
v[s=`a${u}e${y}t`](`He${u+u+z}... eh, ${t}h${z}m sh${z}u${u+x} I g${y}eet?`)
v[s](v[`p${y+z}mpt`]()[`t${z+c(8.5)+z+t}e${y+c(7.5)}ase`]()==t+(s=z+y+u+x)?`Ah, yes. ${c(9.7)+s}.`:`N${z}. That isn't ${t}hat I meant.`)
```
> 2 votes

# Answer
# JavaScript (ES6), ~~215~~ 247 bytes

If I've understood correctly, the challenge is to not use any of the following chracters: `0, 2, 4, 5, 6, 7, c, d, f, l, o, r, w, x, D, L, O, R, W`.

```
(t=this,T=""+t,A=T[8],a=T[13],b=T[1],e=(""+!!1)[1],g=(""+!1)[3-1],h=T[11])=>t[`p${e+b}mpt`](`He${g+g+b}... eh, ${a}h${b}m sh${b}u${g+h} I g${e}eet?`)[`t${b}L${b+a}e${e}Case`]()==a+(z=b+e+g+h)?`Ah, yes. ${A+z}.`:`N${b}. That isn't ${a}hat I meant.`

```

---

## Try It

```
y=
(t=this,T=""+t,A=T[8],a=T[13],b=T[1],e=(""+!!1)[1],g=(""+!1)[3-1],h=T[11])=>t[`p${e+b}mpt`](`He${g+g+b}... eh, ${a}h${b}m sh${b}u${g+h} I g${e}eet?`)[`t${b}L${b+a}e${e}Case`]()==a+(z=b+e+g+h)?`Ah, yes. ${A+z}.`:`N${b}. That isn't ${a}hat I meant.`
alert(y())
```

## Explanation

```
t=this         // assigns the window object to variable t
T=""+t         // converts t to a string ("[object Window]") and assigns it to variable T
A=T[8]         // assigns the 9th character of T ("W") to variable A
a=T[13]        // assigns the 14th character of T ("w") to variable a
b=T[1]         // assigns the 2nd character of T ("o") to variable b
e=(""+!!1)[1]  // converts true to a string and assigns the 2nd character ("r") to variable e
g=(""+!1)[3-1] // converts false to a string and assigns the 3rd character ("l") to variable g
               // (1 is a truthy value in JS, so !1=false and !!1=true)
h=T[11]        // assigns the 12th character of T ("d") to variable h

// The rest then uses template literals and the above variables to construct the following:

window["prompt"]("Hello... eh, whom should I greet?")["toLowerCase"]()=="w"+(z="orld")?
"Ah, yes. W"+z:
"No. That isn't what I meant."

```
> 2 votes

# Answer
# 05AB1E, 71 bytes

```
.•ǝ·Þ•“Ÿ™...Ûß,£Ô‚© I ÿ?“ćuì,u‘‚ï‘Qi“ºÆ,…Ü.‚ï.“ë“€¸.€Š€ˆn't€À I±….“}.ª,

```

05AB1E uses a custom code-page, but the lower- and uppercase characters are on the same hexadecimal positions on the code-page, so as long as I don't use `worldWORLD` it's fine.

Try it online.

**Explanation:**

```
.•ǝ·Þ•               # Push compressed string "greet" (which unfortunately isn't part of
                     # the dictionary, AND contains an 'r'..)
 “Ÿ™...Ûß,£Ô‚© I ÿ?“ # Push dictionary string "hello... eh, whom should I ÿ?",
                     # where the `ÿ` is filled with the "greet" we pushed earlier
  ć                  # Extract head; pop and push remainder and first character separately
   u                 # Uppercase this first character
    ì                # Prepend it back to the remainder-string
     ,               # And output it to STDOUT with trailing newline
u                    # Convert the (implicit) input-string to uppercase
 ‘‚ï‘                # Push dictionary string "WORLD"
     Qi              # If they are equal:
       “ºÆ,…Ü.‚ï.“   #  Push dictionary string "ah, yes. world."
      ë              # Else:
       “€¸.€Š€ˆn't€À I±….“
                    '#  Push dictionary string "no. that isn't what I meant."
      }.ª            # After the if-else: sentence capitalize the string
         ,           # And also output it to STDOUT

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand why `.•ǝ·Þ•` is `"greet"`; `“Ÿ™...Ûß,£Ô‚© I ÿ?“` is `"hello... eh, whom should I ÿ?"`; `‘‚ï‘` is `"WORLD"`; `“ºÆ,…Ü.‚ï.“` is `"ah, yes. world."`; and `“€¸.€Š€ˆn't€À I±….“` is `"no. that isn't what I meant."`.

If all characters would be allowed, there are only two minor differences:

* The `greet` would have been placed literally inside the dictionary sentence
* The input would have been changed to lowercase with `l` instead, so `'‚ï` could be used for `"world"`

So it would be **68 bytes** instead:

```
“Ÿ™...Ûß,£Ô‚© I greet?“ćuì,l'‚ïQi“ºÆ,…Ü.‚ï.“ë“€¸.€Š€ˆn't€À I±….“}.ª,

```

Try it online.
> 2 votes

# Answer
# Vyxal, 75 bytes

```
`ƈṡ... eh, ↓Ṅ ƛ¤ I £Ẋet?`,⇩`ƛ†`=[`Ah, ∨ȯ. ƛ€.`,|«ƛτ«ǐ`. λ÷ ⋏°'t λ⟨ I ḋ↓.`J,

```

Try it Online!
> 2 votes

# Answer
# APL (Dyalog), 171 bytes

No compression here!

Requires `⎕IO←0` which is default on many systems. All characters are in the character set.

```
c←{⎕AV[¯25+⎕AV⍳⍵]}
c'Á.558GGGm.1´m∆186m¥18£5¯mÂm0⊢..$⍒'
c'Ë8GmÒ1z$m2¥7v$m∆1z$mÂm6.z7$G' 'Z1mB.¥GmÕ8⊢5¯G'⊃⍨(c'∆8⊢5¯')≡819⌶⍞

```

Try it online!

Works by first defining a custom decoding function `c` which decodes from a simple shifted encoding which was carefully chosen to be able to represent all the required strings while avoiding the ten forbidden characters.

`c←{``}` a function:
`⎕AV[``]` the **A**tomic **V**ector indexed by
`¯25+` the downshifted-by-25
`⎕AV⍳` indices into the **A**tomic **V**ector for
the argument

`c'Á.558GGGm.1´m∆186m¥18£5¯mÂm0⊢..$⍒'` implicitly print the decoded *Hello... eh, whom should I greet?*

get character input
`819⌶` lowercase it
`(``)≡` compare it to
`c'∆8⊢5¯'` the decoded *world*
`'Ë8GmÒ1z$m2¥7v$m∆1z$mÂm6.z7$G' 'Z1mB.¥GmÕ8⊢5¯G'⊃⍨` use that Boolean to pick from the encoded *No. That isn't what I meant.* (if false) and *Ah yes. World.* (if true)
`c` decode that
> 1 votes

# Answer
# Python 3, 186 bytes

```
t=a,b,c,e,f=5*'%c'%(87,111,114,108,100)
exec(f'exit(["N{b}. That isn\'t \u0077hat I meant.","Ah, yes. {t}."][input("He{e+e+b}... eh, \u0077h{b}m sh{b}u{e+f} I g{c}eet?").tit{e}e()==t])')

```

Try it online!

Outputs to `STDERR`.
> 1 votes

# Answer
# 05AB1E, ~~76~~ 73 bytes

```
u”Ÿ™... ”“Ûß,£Ô‚© I g“«’‚™ˆÆ?’«,‘‚ï‘Qi“ºÆ,…Ü.‚ï.“ë“€¸.€Š€ˆn't€À I±….“}.ª,

```

Try it online!

*-3 bytes thanks to @ovs.*

```
                                # (implicit) push STDIN to stack
u                               # convert top of stack to uppercase
”Ÿ™... ”“Ûß,£Ô‚© I g“«’‚™ˆÆ?’«  # push "Hello... eh, whom do I greet?"
,                               # output top of stack to STDOUT
‘‚ï‘                            # push "WORLD"
  Qi                            # if top two stack values are equal...
    “ºÆ,…Ü.‚ï.“                 # push "ah, yes. world."
  ë                             # else...
    “€¸.€Š€ˆn't€À I±….“         # push "no. that isn't what I meant."
}                               # exit if statement
.ª                              # push top of stack in sentence case
,                               # output top of stack to STDOUT

```
> 1 votes

# Answer
# brainfuck, 1445 bytes

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

```

Try it online!

Requires an 8-bit wrapping implementation where EOF=0.
> 1 votes

# Answer
# Retina, ~~211~~ 194 bytes

```
T`a-z`A-Z
T`A-Z`A-C\E-KMNPQS-VX-Z(%[]{
^(?!%SVNE$).*
Qs. Yiay jxq'y =iay J pfaqy.
%SVNE
Ai, *fx. %svne.
^
Ifnns... fi, =isp xiszne J hvffy?¶
T`A-C\E-KMNPQS-VX-Z(%[]{a-ce-kmn\pqs-vx-z}=+*&`A-Za-z

```

Explanation:

```
T`a-z`A-Z - Stage one (uppercasing input)
T`     Configuration - Transliterate;
a-z    Lowercase letters of the alphabet
`      ...into...
A-Z    Uppercase letters of the alphabet

T`A-Z`A-C\E-KMNPQS-VX-Z(%[]{ - Stage two (encoding input)
T`                             Configuration - Transliterate:
A-Z                            Uppercase letters of the alphabet
`                              ...into...
A-C\E-KMNPQS-VX-Z              All uppercase characters, excluding "WORLD"
                 (%[]{         And these characters to make up for the missing 5 characters

^(?!%SVNE$).*
Qs. Yiay jxq'y =iay J pfaqy. - Stage three (check whether input is not "world")
                               Implicit Configuration - Replace:
^(?!%SVNE$).*                  Anything except "%SVNE" (the encoded version of "WORLD") with
Qs. Yiay jxq'y =iay J pfaqy.   This line (encoded version of "No. That isn't what I meant.").

%SVNE
Ai, *fx. %svne.    - Stage four (check whether input is "world")
                     Implicit Configuration - Replace:
%SVNE                %SVNE with
Ai, *fx. %svne.      This line (the encoded version of "Ah, yes. World.")

^
Ifnns... fi, =isp xiszne J hvffy?¶ - Stage five (append message to start)
                                     Implicit Configuration - Replace:
^                                    The start with
Ifnns... fi, =isp xiszne J hvffy?¶   This line (the encoded version of ("Hello... eh, whom should I greet?"). The ¶ represents a newline

T`A-C\E-KMNPQS-VX-Z(%[]{a-ce-kmn\pqs-vx-z}=+*&`A-Za-z - Stage six (decode)
T`                                                      Configuration - Transliterate:
A-C\E-KMNPQS-VX-Z                                       All uppercase characters, excluding "WORLD"
                 (%[]{                                  And these characters to make up for the missing 5 characters
A-C\E-KMNPQS-VX-Z                                       All lowercase characters, excluding "world"
                 }=+*&                                  And these characters to make up for the missing 5 characters
`                                                       ...with...
A-Za-z                                                  All the uppercase characters followed by the lowercase characters.

```

Try it online!

I used this program to encode the strings, and this one to decode them.
> 0 votes

# Answer
## Python 3.7, ~~239~~ ~~267~~ ~~260~~ 258 bytes

```
a,b,c,e,f,g='\u0057','\u0077','\u006f','\u0072','\u006c','\u0064'
exec(f'p=p{e}int;p("He{f}{f}{c}... eh, {b}h{c}m sh{c}u{f}{g} I g{e}eet?");p("Ah, yes. {a}{c}{e}{f}{g}."if input().{f}{c}{b}e{e}()=="{b}{c}{e}{f}{g}"e{f}se"N{c}. That isn\'t {b}hat I meant.")')

```

Try it online!

I had to write `exec` because I had to write `p\u0072int` instead of `print`, `e\u006Cse` instead of `else` and `\u006C\u006F\u0077e\u0072` instead of `lower`.
> 0 votes

# Answer
# C (gcc), ~~208~~ ~~205~~ 202 bytes

```
a[];main(){puts("He\x6c\x6c\x6f... eh, \x77h\x6fm sh\x6fu\x6c\x64 I g\162eet?");gets(a);puts((*a|'    ')^1819438967|(a[1]|32)^100?"N\x6f. That isn't \x77hat I meant.":"Ah, yes. \x57\x6f\x72\x6c\x64.");}

```

Try it online!

Apparently you don't even have to specify an array length. Ungolfed:

```
int a[];                  // Array of ints. Hint: ints are 4 characters wide.

main(){
    puts("Hello... eh, whom should I greet?");
    gets(a);              // Read input line.
    puts(
        (*a | '    ')     // Tolower() the first four characters
            ^ 1819438967  // Compare to "worl", non-zero if not the same
        | (a[1] | 32)     // Tolower() the fifth character
            ^ 100         // Compare to "d\0\0\0", non-zero if not the same
        ?                 // If non-zero bits present, it wasn't "world".
            "No. That isn't what I meant."
        :                 // Otherwise, we have a match.
            "Ah, yes. World.");
}

```

Thanks to @ceilingcat for shaving off 3 bytes.
> 0 votes

---
Tags: code-golf, string, restricted-source, hello-world
---


title: Is it 1089-able?

text:
# Question
Title: Is it 1089-able?
\\$ 1089 \\$ is a very special number. To prove why, select any 3-digit number whose first and last digits differ by at least 2. Then, reverse the digits, and take the *difference* of these two numbers. Reverse the digits once more, and *add* these two numbers together. You will get \\$ 1089 \\$. The magic is left as an exercise to the reader.

Taking this a step further, let's define an algorithm for all possible integers:

* Choose any positive integer \\$ n \\$
* Reverse the digits of \\$ n \\$, and call it \\$ x \\$
* Set \\$ n \\$ equal to \\$ n - x \\$ if \\$ x \< n \\$, and \\$ n + x \\$ otherwise
* Repeat the above step until \\$ n \\$ reaches a number it has already visited

In turns out that this algorithm gets stuck in an infinite loop, for certain numbers. Let's call a number *1089-able™*, if it does in fact terminate (in other words, a duplicate is reached at some point). For example, everyone's favorite number, `2022`, is *1089-able™*:

```
2022 + 2202 ->
4224 + 4224 ->
8448 + 8448 ->
16896 + 69861 ->
86757 - 75768 ->
10989 + 98901 ->
109890 - 98901 ->
10989 (*)

```

In this challenge, you are given a positive integer, and are required to determine whether it is *1089-able™*. This is , so the shortest solution in bytes wins.

The first 50 *non-1089-able™* numbers are as follows:

```
[10057, 10118, 10168, 10254, 10458, 10598, 10698, 10798, 10898, 11047, 11108, 11158, 11244, 11448, 11499, 11588, 11688, 11788, 11888, 11998, 11999, 12037, 12148, 12234, 12438, 12489, 12578, 12678, 12778, 12878, 12988, 12989, 13027, 13138, 13224, 13428, 13479, 13568, 13668, 13768, 13868, 13978, 13979, 14017, 14128, 14198, 14214, 14418, 14469, 14558]

```

# Answer
> 7 votes
# Python, 117 bytes

```
def f(n):
    v={n}
    while 1:
        x=int(str(n)[::-1]);n-=[-x,x][x<n]
        if n in v:return 1
        if n/100in v:return 0
        v|={n}
```

Attempt This Online!

It works for all positive integers less or equal to the 50th *non-1089-able™* number.

Haven't proven that it works for numbers greater than `14558`.

# Answer
> 5 votes
# Python, ~~162~~ ~~136~~ 128 bytes

```
def h(n,e=0):e=(e or[])+[n];n+=(x:=int(str(n)[::-1]),-x)[x<n];return f"1089{(len(z:=str(n))-7)*'9'}099"!=z and(n in e or h(n,e))
```

Attempt This Online!

Haven't proven that it works for *non-1089-able™* numbers past the first 50.

-26 bytes thanks to benrg and ovs (and for pointing out the rules with reusable functions)

-8 bytes thanks to Jo King

# Answer
> 3 votes
# Retina, 70 bytes

```
^
$($^$%')*_;$%'*_¶
^(_+);\1\B|;

_+
$.&
D^`
/^./}s`^1099+8900+¶.+

^¶

```

Try it online! Link only includes two test cases as it's too slow otherwise. Explanation:

```
^
$($^$%')*_;$%'*_¶

```

Take the first number and its reverse and convert them both to unary with the reversed number first.

```
^(_+);\1\B|;

```

Subtract the two numbers of the second is larger otherwise add them.

```
_+
$.&

```

Convert back to decimal.

```
D^`

```

Delete the total if it's been seen before.

```
s`^1099+8900+¶.+

```

But delete the entire buffer if the value will increase infinitely.

```
/^./}`

```

Repeat until at least the current total was deleted.

Check to see whether an infinite loop was detected.

# Answer
> 3 votes
## Javascript, 149 145 137 128 bytes

```
c=n=>{a=[n];while(n){x=+[...''+n].reverse().join``;n=x<n?n-x:n+x;if(a[i='includes'](n))return 1;if(a[i](n/100))break;a.push(n)}}

```
* Thanks to @Radvylf Programs for saving 4 bytes!
* Saved 8 bytes replacing `return false` with `break` now that the loop is wrapped
* Thanks to @Steffan for saving 9 bytes!

Try me online.

## Javascript, 171 bytes (readable)

```
c=n=>{
    a = [n]
    while(n){
        x=+n.toString().split('').reverse().join('')
        n=x<n?n-x:n+x
        if(a.includes(n)) return true
        if(a.includes(n/100)) break
        a.push(n)
    }
}

```

Try me online.

A good chunk of the bytes in this are coming from included functions `.reverse()`, `.includes()`, etc. Have not tested past the 50 provided.

# Answer
> 3 votes
# Ruby, 84 bytes

```
->n,*r{q=0;1while(r!=r|=[n+=(w=n.digits.join.to_i)*(w<n ?-1:1)])&&q=[]!=[n/100]-r;q}

```

Try it online!

# Answer
> 2 votes
# Javascript, ~~94~~ 87 bytes

```
f=(n,s={},x=+[...``+n].reverse().join``,m=x<n?n-x:n+x)=>s[m]?!!(m-11e12+11):f(s[m]=m,s)

```

## How it works!

If the function does get stuck in a forever loop it will max out at the magic number `11e12+11` and this function returns the result minus that number casted to a boolean.

Try it online!

---
Tags: code-golf, decision-problem, integer
---