title: A quine of sorts

text:
# Question
Title: A quine of sorts
Given a string `x`, output the characters in `x` sorted according to the order of appearance in your source code.

## Examples

```
Source: ThisIs A Test
 Input: Is it a Test?
Output: TissI   etta?

Source: Harry - yer a wizard.
 Input: I'm a what?
Output: aa  wh'?Imt

Source: Mr. H. Potter, The Floor, Hut-on-the-Rock, The Sea
 Input:
Output:

```

## Rules

* Standard loopholes & i/o rules apply
* Input & output can be either a string, a list of characters, or a list of bytes.
* If a character is used multiple times in the source, use the first occurrence.
* If one or more characters does not appear in the source, they should be at the end; their order does not matter, nor does it have to be consistent.
* **Source must be non-empty**
* Newlines are treated the same as other characters.
* The order in which the code is executed doesn't matter; just the raw string.
* The input is in the same encoding as the code.
* The input is sorted by characters, not by bytes.
* Sorting is case sensitive
* This is , so shortest answer in bytes for each language wins!

```
let f = (s, i, o) => o.split("").map(x => [x, s.indexOf(x) == -1 ? s.length + 100 : s.indexOf(x)]).sort(([, a], [, b]) => a - b).map(([x]) => x).join("") === o && i.split("").sort().join("") === o.split("").sort().join("");let g = (s, i) => i.split("").map(x => [x, s.indexOf(x) == -1 ? s.length + 100 + Math.random() : s.indexOf(x)]).sort(([, a], [, b]) => a - b).map(([a]) => a).join("");$(() => $("button").click(() => $("#result").text(f($("#source").val(), $("#input").val(), $("#output").val()) ? "Valid" : `Invalid; example output: \`${g($("#source").val(), $("#input").val())}\``)));
```

```
body,label{display: flex;flex-direction: column;}*{white-space: pre;font-family: Inconsolata, Consolas, mono-space;font-size: 14px;}
```

```
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><label>Source: <textarea id="source">ThisIs A Test</textarea></label><label>Input: <textarea id="input">Is it a Test?</textarea></label><label>Output: <textarea id="output">TissI   etta?</textarea></label><div><button>Validate</button> <span id="result"></span></div>
```

# Answer
# Python 3.8 (pre-release), ~~102~~ ~~100~~ ~~96~~ ~~85~~ ~~79~~ ~~76~~ ~~68~~ ~~61~~ ~~59~~ 60 bytes

```
c="print(sorted(x:=input(),key=('c=%r;'%c+x).find))";exec(c)

```

Try it online!

*-2 bytes by using this*

*-4 bytes by realizing that `<0` == `==-1` and removing the unnecessary `+1`*

*-11 bytes thanks to Neil*

*-6 bytes thanks to dzaima*

*-3 bytes thanks to rod*

*-8 bytes thanks to negative seven pointing out that the program can output a list of chars*

*-7 bytes due to Embodiment of Ignorance switching back to Python 3.8 and using `:=`*

*-2 bytes due to Jo King switching out the variable name s for c, so we could leave out the `;c`*

*+1 bytes because negative seven pointed out that it wasn't filtering `;` correctly*
> 13 votes

# Answer
# APL (Dyalog Unicode), 14 bytesSBCS

Anonymous tacit prefix function.

```
'''∘⍋⊃¨⊂'∘⍋⊃¨⊂

```

enclose argument (to act on it as a whole)

`⊃¨` from that, pick one character for each of the following indices:

`∘⍋` the indices that would sort the argument in the the order given by the following string (all non-members go in order of appearance at the end):

`'''∘⍋⊃¨⊂'` the characters `'∘⍋⊃¨⊂`

Try it online!
> 7 votes

# Answer
# C# (Visual C# Interactive Compiler), 48 bytes

```
n=>n.OrderBy((@"n=>.OrdeBy(@""+)Ixf"+n).IndexOf)

```

Try it online!
> 6 votes

# Answer
# JavaScript (Node.js), ~~60 58~~ 56 bytes

*-2 bytes from Jo King*

```
f=_=>_.sort((a,b)=>(p=g=>`f=${f+g}`.indexOf(g))(a)-p(b))

```

Try it online!
> 5 votes

# Answer
# Jelly, 14 bytes

```
“;fɓḟṾⱮ”ṾɓfⱮ;ḟ

```

A full program accepting a (Python formatted) string (of Jelly code-page characters) which prints the output.
(as a monadic link it yields a list of lists of characters)

**Try it online!**

### How?

```
“;fɓḟṾⱮ”ṾɓfⱮ;ḟ - Main Link: list of characters, S
“;fɓḟṾⱮ”       - list of characters = [';', 'f', 'ɓ', 'ḟ', 'Ṿ', 'Ɱ']
        Ṿ      - un-evaluate = ['“', ';', 'f', 'ɓ', 'ḟ', 'Ṿ', 'Ɱ', '”']
         ɓ     - start a new dyadic chain, F(S, T=that):
           Ɱ   - for each character, t, in T:
          f    -   (S) filter keep any of (the single character, t)
             ḟ - (S) filter discard any of (the characters in T)
            ;  - concatenate

```
> 5 votes

# Answer
# Jelly, ~~16~~ 14 bytes (Jelly Code page), 25 bytes (UTF8)

```
“Ṿv`Ṿ;³³i@Þ”v`

```

Try it online!

A full program that takes a single argument, the string to be sorted.

Thanks to @JonathanAllan for pointing out a bug!

As per @EriktheOutgolfer, although the code can be input using the Jelly code page, the characters sorted are the equivalent UTF-8 ones rather than the bytes of the source. As such, I’ve included the score in UTF-8 bytes as well. Note the same probably applies to all languages with custom code pages.

### Explanation

```
“Ṿv`Ṿ;³³i@Þ”   | The string "Ṿv`Ṿ;³³i@Þ", referred to below as S
            v` | Evaluate this string as Jelly code using the string itself as the argument

```

The string above evaluates as:

```
Ṿ          | Uneval the string S (effectively wraps it in “”)
 v`        | Eval it (effectively removes the “”)
   Ṿ       | Uneval it again, adding back in the “”
    ;³     | Concatenate the input to this
      ³i@Þ | Sort the input with respect to the first occurence of each character in the “”-wrapped string S concatenated to the input

```

`Ṿv`` is a no-op effectively here, but exists to ensure all characters are represented.
> 4 votes

# Answer
# Perl 6, 56 bytes

```
<slurp.comb.sort({"<$_>~EVAL$^a".index($a)}).say>~~.EVAL

```

Try it online!
> 4 votes

# Answer
# 05AB1E, ~~31~~ ~~26~~ 19 bytes

```
Σ'"'ÿs"Σ'ÿÿsìyk"ìyk

```

-7 bytes by taking inspiration of @EmbodimentOfIgnorance's approach in his C# answer of appending the current character before indexing.

Try it online or try it with added debug-line to see the strings that's being indexed into.

**Explanation:**

```
Σ                 # Sort the (implicit) input-string by:
 '"              '#  Push string '"'
   'ÿ            '#  Push string "ÿ"
     s            #  Swap the order of these two strings on the stack
      "Σ'ÿÿsìyk"  #  Push string "Σ'ÿÿsìyk", where the `ÿ` are automatically filled with
                  #  the previous strings we created: `Σ'"ÿsìyk`
                  #  (top to bottom from stack; left to right in string)
       ì          #  Prepend this string in front of the character we're sorting
        yk        #  And then get the index of the character we're sorting in this string
                  # (after the sorting the resulting string is output implicitly)

```
> 3 votes

# Answer
# 05AB1E, ~~24~~ ~~22~~ 21 bytes

```
Σ"Σ"'"«"'«Rrk}"«Rrk}R

```

Try it online!

**Explanation:**

```
Σ                    }               # Sort
 "Σ"                                 # Σ string literal
    '"                               # " string literal
       «                             # Concatenate last two literals
        "'«Rrk}"                     # '«Rrk} another literal
                «                    # Concat again
                 R                   # Reverse literal (so: }krR'«'"Σ)
                  r                  # reverse stack
                   k                 # find the current sorting index in our code string
                     R               # reverse our sorted string

```

First time trying stuff in 05AB1E so probably lots to be saved
> 3 votes

# Answer
# Ruby, 57 bytes

```
->s{s.sort_by{|o|%{->s{.ort_by|%}index()9}.index(o)||99}}

```

Try it online!

Fairly straightforward, assuming I haven't missed a golfing trick. Take in a list of characters and sort by their index in a string consisting of all the uniq characters in the code in order of their appearance. Often their first appearance is in that very string, but that doesn't change the order.
> 3 votes

# Answer
# , 14 bytes

Anonymous tacit prefix function.

```
]/:']/:''i'i:]

```

Try it online!

`]` the argument

`i:` last occurrence (non-members get the index beyond end of lookup string) of each character in:

`']/:''i'` the characters `]/:'i`

`/:` use that to sort:

`]` the argument
> 2 votes

# Answer
# Charcoal, 37 bytes

```
≔´≔´´´η´Ｆ´Φ´θ´⁼´ι´κ´¬´№ηＦηΦθ⁼ικΦθ¬№ηι

```

Try it online! Explanation:

```
≔´≔´´´η´Ｆ´Φ´θ´⁼´ι´κ´¬´№η

```

There are two ways of quoting characters in Charcoal; `´` quotes any single character while `”y`... quotes any character except  and also counts as a separate string. It turns out that the overhead in having to deal with  means that it doesn't end up any golfier.

```
ＦηΦθ⁼ικ

```

Loop over the characters in turn, outputting any matching characters from the input. This sorts the input.

```
Φθ¬№ηι

```

Output any unmatched characters in the input.
> 2 votes

# Answer
# Python 2, 62 bytes

```
lambda a:sorted(a,key=('lambd :sorted(,ky=\'\\+).fin'+a).find)

```

Same concept as my C# answer.

Try it online!
> 2 votes

# Answer
# PowerShell, 68 bytes

```
$p=$args
&($t={$p|sort-object{"`$p=`$args
&(`$t={$t})$_"|% i*f $_}})

```

Try it online!
> 2 votes

# Answer
# Java 10, ~~129~~ 100 bytes

```
s->{s.sort(java.util.Comparator.comparing(c->("s->{.ort(javuilCmpcng\"\\+)dexOf;}"+c).indexOf(c)));}

```

-29 bytes by porting the `+c` from *@EmbodimentOfIgnorance*'s C# answer.

Try it online.

**Explanation:**

```
s->{                 // Method with char-List parameter and no return-type
  s.sort(java.util.Comparator.comparing(c->
    ("s->{.ort(javuilCmpcng\"\\+)dexOf;}"
                     //  Push a String containing the characters in the code
     +c)             //  Append the current character
        .indexOf(c)  //  And get the first index of the current character in the String

```

NOTE: Usually it's cheaper to use `s.sort((a,b)->Long.compare(a,b))` instead of `s.sort(java.util.Comparator.comparing(c->c)`, but in this case it would be 11 bytes longer:

```
s->{var v="s->{var =\"\\;.ot(,)Lngcmpe+idxOf}";s.sort((a,r)->Long.compare((v+a).indexOf(a),(v+r).indexOf(r)));}

```

Try it online.
> 2 votes

# Answer
# Japt, ~~18~~ 7 bytes

Takes input as an array of characters

```
nQi"nQi

```

Try it
> 2 votes

# Answer
# Jelly, 26 bytes (UTF-8\*)

```
“®³nÞṾ©V”Ṿ©VV

```

Try it online!

Takes input as a Python-formatted string in the 1st command-line argument.

Unique characters:

```
“®³nÞṾ©V”

```

\*Note: I discovered that this doesn't work when encoded in JELLY, since it sorts the UTF-8 characters instead of its own bytes.
> 1 votes

# Answer
# ReRegex, 335 bytes

```
([^(])\(/($1/([^(])\[/[$1/([^(\[])\^/^$1/([^(\[^])]/]$1/([^(\[^\]])\)/)$1/([^(\[^\])])\\/\\$1/([^(\[^\])\\])\//\/$1/([^(\[^\])\\\/])\$/\$$1/([^(\[^\])\\\/$])1/1$1/([^(\[^\])\\\/$1])\#/\#$1/([^(\[^\])\\\/$1\#])i/i$1/([^(\[^\])\\\/$1\#i])n/n$1/([^(\[^\])\\\/$1\#in])p/p$1/([^(\[^\])\\\/$1\#inp])u/u$1/([^(\[^\])\\\/$1\#inpu])t/t$1/#input

```

A Naïve solution, bubble sorts characters to the left based on their occurance in the source code, which only consists of the characters `([^])\/$1#input` (in order). Unfortunately, it requires a separate regex for each character, which gets progressively longer per index. Seperating the regexes for readability gives:

```
([^(])\(/($1/
([^(])\[/[$1/
([^(\[])\^/^$1/
([^(\[^])]/]$1/
([^(\[^\]])\)/)$1/
([^(\[^\])])\\/\\$1/
([^(\[^\])\\])\//\/$1/
([^(\[^\])\\\/])\$/\$$1/
([^(\[^\])\\\/$])1/1$1/
([^(\[^\])\\\/$1])\#/\#$1/
([^(\[^\])\\\/$1\#])i/i$1/
([^(\[^\])\\\/$1\#i])n/n$1/
([^(\[^\])\\\/$1\#in])p/p$1/
([^(\[^\])\\\/$1\#inp])u/u$1/
([^(\[^\])\\\/$1\#inpu])t/t$1/
#input

```

Try it online!
> 1 votes

# Answer
# brainfuck, 647 bytes

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

```

This was a mouthful. For each of Brainfuck's 8 command characters (In order of source appearance), compares them to each character of the input and outputs it when they occur. After each character is done, it outputs whatever wasn't found.

## Ungolfed

```
,[>>>+>,]             Load each character of input with some memory padding
<<<<[<<<<]>>>>         Navigate to the start

[                   For each COMMA
    [->+>+<<]           Copy over the next two
    --[>-<++++++]>-     Subtract 44
    <+>[<->[-]]<[       If NOT Zero
        >>.                 Write it
        >-                  Unset the remember flag
        <<<-                And unset the test flag
    ]
    >>[-<<+>>]          Copy Back
    >>                  Next Char
]<<<<[<<<<]>>>>     And Reset

[                   For each LEFT BRACKET
    [->+>+<<]           Copy over the next two
    -[>-<---]>------    Subtract 91
    <+>[<->[-]]<[       If NOT Zero
        >>.                 Write it
        >-                  Unset the remember flag
        <<<-                And unset the test flag
    ]
    >>[-<<+>>]          Copy Back
    >>                  Next Char
]<<<<[<<<<]>>>>     And Reset

[                   For each RIGHT ANGLE BRACKET
    [->+>+<<]           Copy over the next two
    ----[>-<----]>+     Subtract 62
    <+>[<->[-]]<[       If NOT Zero
        >>.                 Write it
        >-                  Unset the remember flag
        <<<-                And unset the test flag
    ]
    >>[-<<+>>]          Copy Back
    >>                  Next Char
]<<<<[<<<<]>>>>     And Reset

[                   For each PLUS
    [->+>+<<]           Copy over the next two
    --[>-<++++++]>      Subtract 43
    <+>[<->[-]]<[       If NOT Zero
        >>.                 Write it
        >-                  Unset the remember flag
        <<<-                And unset the test flag
    ]
    >>[-<<+>>]          Copy Back
    >>                  Next Char
]<<<<[<<<<]>>>>     And Reset

[                   For each RIGHT BRACKET
    [->+>+<<]           Copy over the next two
    -[>-<---]>--------  Subtract 93
    <+>[<->[-]]<[       If NOT Zero
        >>.                 Write it
        >-                  Unset the remember flag
        <<<-                And unset the test flag
    ]
    >>[-<<+>>]          Copy Back
    >>                  Next Char
]<<<<[<<<<]>>>>     And Reset

[                   For each LEFT ANGLE BRACKET
    [->+>+<<]           Copy over the next two
    ----[>-<----]>+++   Subtract 60
    <+>[<->[-]]<[       If NOT Zero
        >>.                 Write it
        >-                  Unset the remember flag
        <<<-                And unset the test flag
    ]
    >>[-<<+>>]          Copy Back
    >>                  Next Char
]<<<<[<<<<]>>>>     And Reset

[                   For each MINUS
    [->+>+<<]           Copy over the next two
    --[>-<++++++]>--    Subtract 45
    <+>[<->[-]]<[       If NOT Zero
        >>.                 Write it
        >-                  Unset the remember flag
        <<<-                And unset the test flag
    ]
    >>[-<<+>>]          Copy Back
    >>                  Next Char
]<<<<[<<<<]>>>>     And Reset

[                   For each DOT
    [->+>+<<]           Copy over the next two
    --[>-<++++++]>---   Subtract 46
    <+>[<->[-]]<[       If NOT Zero
        >>.                 Write it
        >-                  Unset the remember flag
        <<<-                And unset the test flag
    ]
    >>[-<<+>>]          Copy Back
    >>                  Next Char
]<<<<[<<<<]>>>>     And Reset

[       For each remaining character
    >>>[    If the remember flag is still set
        <<<.    Write it
        >>>-    Unset the flag
    ]>      Next character
]       Until it is done

```

Try it online!
> 0 votes

# Answer
# Thunno 2 `J`, 18 bytes

```
"XÞxṘs+nȮ"XÞxṘs+nȮ

```

#### Explanation

```
"XÞxṘs+nȮ"XÞxṘs+nȮ  # Implicit input
"XÞxṘs+nȮ"          # Push the string "XÞxṘs+nȮ"
          X         # Pop and store in the variable x
           Þ        # Sort the input by the following:
            x       #  Push x, "XÞxṘs+nȮ"
             Ṙ      #  Get its representation (surround by quotes)
              s+    #  Append the current character
                nȮ  #  And get its index in this string
                    # Implicit output, joined by the J flag

```

#### Screenshot
> 0 votes

---
Tags: code-golf, quine, sorting
---


title: Am I being run backwards?

text:
# Question
Title: Am I being run backwards?
Your task is to write a program, function, or snippet that will output one value if run forward, and another if run backward. The program must run without errors.

The output can be any two distinct values, of the same data type. For example, `1` and `3`, `true` and `false`, or `'t'` and `'f'`. In languages without a concept of data types, such as brainf\*** or text, any distinct values are allowed.

This is a code golf challenge, shortest answer per language wins. Note that snippets *are* allowed (so something like `1-2` is valid, but don't expect any upvotes).

# Answer
# Python 3, no comments or string literals, 106 bytes

```
x=quit
y=x.__class__
y.__add__=print
y.__pos__=x
x+x++x+x
x=__sop__.y
tnirp=__dda__.y
__ssalc__.x=y
tixe=x

```

I've never liked how comments and string literals let you "turn off" most of your language's syntax in challenges like this, so I wanted to see how far I could golf things without using either comments or string literals. This is what I came up with.

Since I don't have any way to disable the syntactical significance of parentheses, I cannot use the function call operator. Any attempt to do so would result in the reversed code having a closing parenthesis before the first opening parenthesis, which is invalid outside a comment or string literal. I also can't use `def` or container literals (aside from unparenthesized tuples), and my access to language features is in general extremely restricted.

One thing I *can* do is take advantage of Python's operator overloading to call functions implicitly. My ability to define any classes or functions is extremely limited, but fortunately, there are enough tools lying around in the built-in namespace for me to use. Most built-ins don't let me perform the attribute assignment I need to redefine their operator overloads, but (unless Python is run with one of the flags that disables `site` importing) the auto-imported `site` module adds `quit` and `exit` objects to the built-ins. These objects are instances of non-C classes, so I can reassign their operator overloads.

Setting `__add__` to `print` lets me use addition to print things, and setting `__pos__` to `quit` or `exit` lets me use the unary `+` operator to abort the program before the rest of the code runs. Without setting `__pos__`, I would need a bunch of additional code to make sure the "backwards" part of the code can find all the variables and attributes it needs to not fail. With `__pos__`, I only need to make sure the "backwards" code is still syntactically valid.

Forward, the code prints

```
Use quit() or Ctrl-D (i.e. EOF) to exit

```

Backward, the code prints

```
Use exit() or Ctrl-D (i.e. EOF) to exit

```

(The messages are slightly different on Windows. For platform-independent output at the expense of 3 extra bytes, you can replace the middle line with `x+1++x++2+x`, printing `1` when run forwards and `2` when run backwards.)

---

I also tried to figure out a way to do this by defining my own class instead of messing with `quit.__class__`. I got as far as the following:

```
if.1j:adbmal=1j
class ton:adbmal
a=lambda:j1.fi
j1=a
a.__dict__=a.__globals__

```

`class ton:adbmal` is one of the very few combinations of class name and class body such that the class statement is syntactically valid backward. `tressa`, `led`, `labolg`, `tropmi`, and `esiar` would also have been valid class names (with a different class body, such as `not fi`), but `ton` is the only one where the reversed name can be part of an expression, giving the most flexibility.

`if.1j:adbmal=1j` assigns a value to `adbmal` to make the class body succeed, while still being syntactically valid backward.

The stuff with `a` and `j1` lets me use `j1.ton` to refer to my `ton` class, which is still a valid expression backward.

At this point, I got stuck. I couldn't figure out how to get my class out of `j1.ton` and into a more useful variable. I can't assign attributes on `j1.ton` and still have valid syntax backward, so I can't set operator overloads. I also wanted to set `builtins.__build_class__` to my class so I could abuse the `class` statement to construct instances without the function call operator, but trying to put `j1.ton` on the right side of an assignment produces invalid syntax backward.

If I had been able to name my class something like `fi` or `tpecxe`, I could have used tricks like `b:j1.fi` to get the class into an annotation and then `a.__dict__=__annotations__` to get it into `a.b`, but I couldn't find any way to get the class statement and the annotation tricks to hook up. Anything that was compatible with the class statement was incompatible with the annotation tricks.

(You might wonder why I didn't abuse `builtins.__build_class__` to call an existing function directly, like `print`. I couldn't figure out a way to do that and have the output be deterministic, and I wanted deterministic output.)
> 73 votes

# Answer
# JavaScript, 19 bytes

Returns `true` because of the assignment at the end, since JS treats that as defining a global variable. The first part is an arrow function, which is ignored. When run backwards, `eurt` is set to `NaN` (not a number), and since `NaN` is not greater than `true` (or equal), it returns `false`.

```
eurt=>true;NaN=true

```

Try it online!

```
eurt=NaN;eurt>=true

```

Try it online!

# JavaScript, 3 bytes

A snippet which outputs `1`, or `-1` in reverse. Very simple.

```
2-1

```

Try it online!

```
1-2

```

Try it online!

# JavaScript, 7 bytes

Abuses the not equal to operator and the not operator, will output `false`, or `true` in reverse. JavaScript uses `NaN` as not-a-number.

```
5==!NaN

```

Try it online!

```
NaN!==5

```

Try it online!

# JavaScript, 18 bytes

Another boring solution, with comments instead of subtraction. Returns `1`, or `2` in reverse. I included the `print` statements in these.

```
print(1)//)2(tnirp

```

Try it online!

```
print(2)//)1(tnirp

```

Try it online!

# JavaScript, 7 bytes

Similar to the previous answer, but with assignment instead of equal-to. Uses the `atob` variable, which is a builtin in browser Javascript (decodes base64). Since TIO doesn't include browser builtins, I defined it just to keep it from erroring. Works as expected in console. Return `true`, or `false` in reverse.

```
2!=atob

```

Try it online!

```
bota=!2

```

Try it online!
> 15 votes

# Answer
# , 3 bytes

```
1"_

```

Try it online!

### one or infinity...

* `1"_` is the constant 1, turned into a verb of rank `"` infinity `_`. Hence always returns 1.
* `_"1` is the constant infinity `_`, turned into a verb of rank `1`. Hence always returns infinity.
> 8 votes

# Answer
# Jelly, 2 bytes

```
+1

```

Try it online!

Prints 1.

# Jelly, 2 bytes

```
1+

```

Try it online!

Prints 2.

The reason for this is that Jelly's dyad-nilad structure chains differently on either side. `+1` becomes a monad meaning "plus one", which is applied to the Left Argument, which defaults to zero. `1+` does not become a monadic chain here (if I remember correctly - correct me if my Jelly theory is off; I'm a bit rusty on the structural component), but rather is seen as `1` set as the Left Argument, and then `+` is applied as a dyad to `(left, left)` in the default case of no Right Argument, giving `1 + 1`.

Great challenge; I almost feel like this is a cheese. I don't know if I should be happy with this solution or feel bad for having such a short and trivial solution \>\_\<.

This uses Jelly's structure to be fancy. A more boring answer would just be `01` (prints 1) and `10` (prints 10), or any other two-digit number and its reverse (that isn't a palindrome).
> 6 votes

# Answer
# **bash, 12 bytes (no comments or string literals)**

```
echo 0$ ohce

```

Prints "0$ ohce"

```
echo $0 ohce

```

Prints "bash ohce"

# **bash, 11 bytes (no comments or string literals)**

```
echo ftnirp

```

Prints "ftnirp"

```
printf ohce

```

Prints "ohce"
> 6 votes

# Answer
# brainf\*** 2 bytes

```
+.

```

Try it online!

Outputs 1 forwards, 0 backwards. Really randomdude999's answer
> 4 votes

# Answer
# Wolfram Language (Mathematica), 10 bytes

```
Print@ohcE

```

Try it online!

Prints `ohcE`.

```
Echo@tnirP

```

Try it online!

Prints `>> tnirP`.
> 4 votes

# Answer
# , 2 bytes

```
.1

```

Prints `0.1`.

```
1.

```

Prints `1`.

Both numeric (double).

tio

Less trivial? and for an explicit true/false

```
2>1
# TRUE

1>2
# FALSE

```

tio
> 4 votes

# Answer
# POSIX sh (Dash, Bash, Zsh, ...), 3 bytes

```
: !

```

Try it online!

The builtin `:` discards its arguments and exits `0` (true). Reversed, `!` negates the exit code of `:` and exits `1` (false).
> 4 votes

# Answer
# , 2 characters, 1 byte in 7's encoding

```
31

```

Try it online! (forwards)

Try it online! (reversed)

This should be the first valid 1-byte solution (because the existing 1-byte solution in BCT requires a particular value on its input to work, and isn't counting it in the byte count – that could only be assumed in a full program, and BCT full programs can't do I/O and must wipe all their working memory to be able to halt, thus have no way to halt with a value). 7's encoding packs multiple characters into a single byte: here are `xxd` hexdumps for the forward and reverse programs:

```
00000000: 67                                       g

```

```
00000000: 2f                                       /

```

This conceptually outputs a string: `31` for the forwards program, and an empty string for the backwards program. The output encoding is set to be the same as the input encoding; so if you encode the program in 7's encoding, you'll get a single byte of output which encodes the string `31` (and if you use ASCII instead, you'll get two bytes that encode the string `31` in ASCII).

## Explanation

On the first pass through the program, the `3` appends a "print and pop" command to the stack, and the `1` appends a "push empty stack element" command to the stack. So, we end up forming a program on top of the stack. At the end of the first pass through the program, 7 will run the resulting program, but without popping it from the stack.

With the forward version of the program, the "print and pop" command will attempt to print the program consisting of a "print" command and a "pop" command. That isn't a valid literal, so the 7 interpreter will construct code that's capable of constructing that stack element and print that instead; in this case, the code it finds for for "push a stack element that generates a 'print and pop' command then a 'push empty stack element command'" is `**7**31` (i.e. basically the program we wrote, although our program appends to an implicit empty stack element, whereas the reconstructed program makes a new one). The print routine interprets the `**7**` as a command to set the output encoding to the same encoding that was used for the source code, and then the `31` is interpreted as a literal and gets printed. The command in question pops two things in total (the thing it's printing and the element below), so the stack now contains no data and thus there are no more passes through the program; it just exits (even though we push an empty stack element after this point, those don't affect the end-of-program behaviour).

With the reverse program, we're pushing the empty stack element before the print attempt, rather than the other way round, so it's now an empty string that gets printed, and the remnants of the program (which are below it) get popped without printing them. Everything is now the same as in the forward program, so the reverse program also exits naturally and without error.
> 4 votes

# Answer
# Keg, 2 bytes

```
10

```

Try it online!

# Keg, 2 bytes

```
01

```

Try it online!

When run forwards, it prints `10`. When run backwards, it prints `01`.

I might try to create a non-trivial answer soon, as this seems like a really great challenge!
> 3 votes

# Answer
# Actually, 2 bytes

Decrement empty value & push 1.

```
D1

```

Reversed program decrements 1, outputting 0.

```
1D

```

Try it online!

# 05AB1E, 2 bytes

The exact same answer ported to a different language.

```
<1

```

Try it online!
> 3 votes

# Answer
# Perl 5, 11 bytes

```
say$-,$$yas

```

Try it online!

Outputs `0` when run forward. Outputs the current process number followed by 0 when run backwards.
> 3 votes

# Answer
# MathGolf, 2 bytes

This one does not have any nilads or dyads inside the program. Just monads.

```
±(

```

Try it online!

## Explanation

```
±  Find absolute value of the implicit 0
 ( Decrement 0, resulting -1.

```

Reversed:

```
(  Decrement 0, resulting -1.
 ± Find absolute value of -1, which results in 1.

```
> 3 votes

# Answer
# HolyC, 12 bytes

Like the C version, except using the implicit print in HolyC

```
"0"; // ;"1"

```

Prints 0

```
"1"; // ;"0"

```

Prints 1

Spaces required by the compiler :)
> 3 votes

# Answer
# MarioLANG, 3 bytes

```
:
+

```

Try it online!

Prints 0

```
+
:

```

Try it online!

Prints 1

---

# MarioLANG, 10 bytes

```
 ==
:+
==

```

Try it online!

Prints 0

```
 ==
+:
==

```

Try it online!

Prints 1
> 3 votes

# Answer
# Poetic, ~~15~~ 13 bytes

```
tis,A NAMETAG

```

Try it online!

Prints ASCII character 1 (SOH).

```
GATEMAN A,sit

```

Try it online!

Prints ASCII character 0 (NUL).

*The previous answer ends with an "Unexpected EOF" error forwards because the END command (any ten-letter word) is omitted, and a "Mismatched IF/EIF" error backwards because EOF is encountered before an IF/EIF loop can end. The following answer terminates properly.*

# Poetic, 51 bytes

```
the difference between I and certain ridiculous men

```

Try it online!

Prints a newline.

```
nem suolucidir niatrec dna I neewteb ecnereffid eht

```

Try it online!

Prints a newline and a "vertical tab" character.

(I really wanted to be able to make the programs make sense both backwards and forwards, but I'm not sure that's possible in English, and I don't know any other languages to try that out with.)
> 3 votes

# Answer
# Haskell, 52 bytes

```
a=0--
--b tnirp=b#a
niam=main
1#a=niam
main=print a

```

==\> prints "1"

```
a tnirp=niam
main=a#1
niam=main
a#b=print b--
--0=a

```

==\> prints "0"

Explanation:

```
a=0--
-- FWD: define constant "a" to be 0 / BWD: No-op                                 --

--b tnirp=b#a
-- FWD: No-op / BWD: define a function "#" in two arguments and prints the       --
-- second                                                                        --

niam=main
-- FWD & BWD: define constant "niam" to be the same as "main"                    --

1#a=niam
-- FWD: define a function "#" in two arguments that produces "main" if the first --
-- argument is 1 / BWD: define constant "main" to be the result of the function  --
-- "#" applied to the arguments "a" and 1                                        --

main=print a
-- FWD: define constant "main" to be an IO action that prints the value of "a" / --
-- BWD: define a function "a" in one argument that always produces the value     --
-- of "niam"                                                                     --

```

Of course, there is also the shorter item:

# Haskell, 29 bytes

```
main=print 1--
--0 tnirp=niam

```

which is much less interesting.
> 3 votes

# Answer
# Dyalog APL

Boring solution using comments

```
0⍝1   => 0
1⍝0   => 1

```

Even more boring numeric solution:

```
10    => 10
01    => 1

```

Basic arithmetics:

```
2-1    => 1
1-2    => ¯1

```
> 3 votes

# Answer
# Whispers v3, 31 bytes

```
1 tuptuO >>
> 1
>> Output 1
0 >

```

Try it online!, !enilnO tI yrT

Hooray for strict parsing rules!

The first and last lines are ignored, because they don't fit the right syntax. They come into action when reversed.
> 3 votes

# Answer
# Fig 0.1.0, \\$2\log\_{256}(96)\approx\\$ 1.646 bytes

```
,"

```

See the README to see how to run this

Argh. Beaten by Halfwit by more than half a byte. In the forward position, it prints a single newline. Backwards, `",`, it prints a comma followed by a newline.
> 3 votes

# Answer
# Make, ~~14~~ 15 bytes

```
x:#
	#$@$#
#:y

```

Try it online!

*Updated to add a trailing tab on the second line...*

Here's another one that's not as short, but seems interesting enough to post...

Forwards it prints `x` and backwards it prints `y`. It works by referencing the `$@` symbol, which is defined as the target being made. The "command" run is just a comment to the shell, so it's a no-op. But by default Make echos the commands it runs.

Also, the `$#` reference doesn't cause an error, and evaluates to an empty string, which allows `#$@$#` to work both directions without having to add more characters.
> 3 votes

# Answer
# Vyxal, 4 bits1, 0.5 bytes

```
2

```

Try it Online! (link is to bitstring) The bitstring form of this is `0101`, which translates to 2.

Reversed - Try it Online! (outputs 0)

If we stretch the rules a bit, we can get two bits: Try it Online! !enilnO ti yrT, which respectively output an empty string and 0 - 0 and 1 in unary.
> 3 votes

# Answer
# Pyth, 2 bytes

```
\"

```

Try it online!

Returns the string ' " ' (one set of double quotes)

# Pyth, 2 bytes

```
"\

```

Try it online!

Returns "\\"

Oops, my earlier answer missed that they had to be the same data type. This answer returns two different strings, and relies on the fact that '\\' makes a one character string of the input and that Pyth closes strings implicitly
> 2 votes

# Answer
# Python 3, 17 bytes

```
print(1)#)2(tnirp

```

Try it online!

I promise this is the last trivial/cheese one I post; I'm trying to think of a more interesting solution. If I remember I'll see where I can get with this.
> 2 votes

# Answer
# Japt, 2 bytes

```
1g

```

Returns `1`. Reverse returns `-1`.

`g` is the sign function when it has no arguments, and returns the sign of the argument minus the caller if called with an argument. So `g1` would be the sign of zero minus one because the default input is 0

Test it
> 2 votes

# Answer
# Wren, 32 bytes

Basically just a port of the Python answer.

```
System.write(1)//)0(etirw.metsyS

```

Try it online!
> 2 votes

# Answer
# 05AB1E, 2 bytes

Push 1 onto the stack & negates. (This results in -1)

```
1(

```

Negate empty value & push 1. Output 1 implicitly.

```
(1

```

Try it online!
> 2 votes

# Answer
## Ruby, 6 bytes

```
p:stup

```

Output

```
:stup

```

Reversed output

```
p

```
> 2 votes

# Answer
# Ceylon (Snippet), 20

The same trivial thing as in many other languages:

```
print(1);//;)2(tnirp

```

Outputs 1.

```
print(2);//;)1(tnirp

```

Outputs 2.

Given that parentheses need to be in the right order and you need `print` for output, I don't think this can be improved.

A full program or function needs even more braces/parentheses mirrored, so no chance of getting it better.

# Ceylon (anonymous function), 17

If we don't need to output anything, but just return it from an anonymous function, then this is enough:

```
()=>//
1.2
//>=)(

```

A function which returns 1.2 (a floating point value).

```
()=>//
2.1
//>=)(

```

A function which returns 2.1 (a floating point value).

# Ceylon (expression with return value), 3

If we accept just an expression (which then can be printed), then we don't even need any comments:

```
2.1

```

Gives 2.1 (a floating point value).

```
1.2

```

Gives 1.2 (a floating point value).

Try all of them online
> 2 votes

# Answer
# Turing Machine Code, no comments or string literals, 19 bytes

```
0 * 0 * 0
0 * 1 * 0

```

Reversed:

```
0 * 1 * 0
0 * 0 * 0

```

Try it online!

The code runs without errors, but does loop forever. Prints '0' forward, prints '1' reversed.
> 2 votes

# Answer
# Befunge-98 (PyFunge), 2 bytes

```
@,

```

Try it online!

Prints nothing by default, prints a null byte if reversed
> 2 votes

# Answer
# Deadfish~, 2 bytes

```
oi

```

Try it online!

Boy, if that fruit hanged any lower, it'd be underground I tell you.
> 2 votes

# Answer
# TI-BASIC Non-trivial, 4 ~~5~~ bytes

```
Disp "Disp :

```

This outputs 'Disp :'

Since TI-BASIC is token based, reversing it gives

```
:Disp "Disp

```

which outputs 'Disp'

Let me explain. 'Disp ' is one token which prints the given string to the home screen. First we are giving it a string of 'Disp :', so simple there. When reversed, since each 'Disp ' is one byte, we get the reversed code above. This reversed code starts with a ':', which ends the line, and means nothing here. The remaining code is 'Disp "Disp ', which runs and outputs 'Disp ' to the home screen.

# TI-BASIC Trivial, 2 bytes

If a program ends with a values, then it outputs it. This lets us do

```
12

```

which outputs 12, and reversed is

```
21

```

which outputs 21.
> 2 votes

# Answer
# Java, 14 bytes

```
()->1;//;0>-)(

```

Simple function that uses comments to exclude the other part. Outputs 1, and reversed outputs 0.
> 2 votes

# Answer
## Bitwise Cyclic Tag, 2 bits (0.25 bytes)

With an input of `1` this should either set the data string to a null string or a string of length 2 in its next iteration.

```
01

```

## Explanation:

```
0  Delete the leftmost data bit.
   Halt. No more instructions executed.
 1 Not executed

```

## Reversed:

```
1  If the left-most data-bit is 1,
 0 Append a 0 to the data-string.

```
> 2 votes

# Answer
# AppleSoft Basic, 3 bytes

`0?1` outputs `1`
`1?0` outputs `0`

~~`0?"?1` \<=\> `1?"?0`~~

verified here
> 2 votes

# Answer
# Halfwit, 1 byte

```
*k

```

Try It Online!

The *second* valid one-byte solution :P

`*` is multiplication, multiplying two 0s. `k` is a digraph character, and on its own a NOP, but `k*` is exponentiation.

Alternatively, anything that's a single char before `>` works as `>` delimits a compressed integer, so `>x` will push some number, and `x>` will apply `x` then push 0.
> 2 votes

# Answer
# Ly, 2 bytes

```
-`

```

Try it online!

Forwards outputs `1` and backwards shows `-1`.

Why? Forwards:

```
 -   : subtract top two stack entries, when empty produces "0"
  `  : increment top of stack, produces "1"

```

Backwards:

```
`   : increment top of stack, when empty produces "0"
 -  : subtract top two stack entries, produces "-1"

```
> 2 votes

# Answer
# HBL, 1 byte

```
+2

```

Run forwards, outputs `3`:

```
+   Increment
 2  Two

```

Run backwards, outputs `8`:

```
2   Double
 +  Four

```

In fact, any program consisting of two characters from the set `2<+-/%` will work. Here are all the possible combinations together with their outputs. We could also add `0` to the set if it weren't for the "same data type" restriction.
> 2 votes

# Answer
# Vyxal, 3 bytes

```
2-1

```

Try it Online!

Running it forward gives `1`, running it backwards gives `2`.

This because vyxal's syntax is weird:

```
ab- (vyxal) = a-b (py)

```
> 2 votes

# Answer
# Brachylog, 2 bytes

```
+1

```

Try it online!

There are probably loads of different 2 byte answers.

### Explanation

`+1` states that `1` is the result of the sum of an unknown list of integers, which is obviously `true.` (there are infinitely such lists).

`1+` states that we can sum the list `1` into some result, which is obviously `false.` since `1` isn’t a list.
> 2 votes

# Answer
# Japt, 2 bytes

```
c1

```

Return x rounded up to nearest multiple of N =\> output 0

Test it

```
1c

```

x default to 1 =\> output 1

Test it
> 1 votes

# Answer
# PHP, 2 bytes

```
12

```

Try it online!

Prints `12` ...

```
21

```

Try it online!

Prints `21` ...

---

Looking for non-trivial solution?

# PHP, 11 bytes

```
<?=1;#;2=?<

```

Try it online!

Prints `1` ...

```
<?=2;#;1=?<

```

Try it online!

Prints `2` ...

---

Don't like comment abuse?

# PHP, 13 bytes

```
;echo+1-ohce;

```

Try it online!

Prints `1` ...

```
;echo-1+ohce;

```

Try it online!

Prints `-1` ...

**Note:** this one is an exact copy of my answer here: https://codegolf.stackexchange.com/a/193169
> 1 votes

# Answer
# C (gcc), 21 bytes

```
puts("");//;)"0"(stup

```

Try it online!

!enilno ti yrT
> 1 votes

# Answer
# Runic Enchantments, 3 bytes

```
0@1

```

Try it online!

Prints `0` forwards and `1` backwards.

If no output is allowed, then `@1` saves a byte.
> 1 votes

# Answer
# Rebol, 2 bytes

```
#1

```

Prints #1

```
1#

```

Prints ##
> 1 votes

# Answer
# Whitespace, 20 bytes

```
S S S N
T   N
S T N
N
N
T   S N
T   N
T   T   S S

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.

Outputs `0`/`-1`.

Try it online or try it online reversed (with raw spaces, tabs and new-lines only).

**Explanation:**

Very minor modification of my answer here (outputting `0` is 1 byte shorter than `1`), so I'm just gonna copy-paste the explanation:

Utilizing the *Exit Program* builtin being a short palindrome `NNN` (also note that without an exit, every Whitespace program would result in an error, making it invalid for this challenge).
The regular program will:

```
SSSN   # Push 0 to the stack
TNST   # Pop and print the top of the stack as number
NNN    # Exit the program, making everything after it no-ops

```

The reverse program will:

```
SSTTN  # Push -1 to the stack
TNST   # Pop and print the top of the stack as number
NNN    # Exit the program, making everything after it no-ops

```

Small additional explanation of pushing a number:

* First `S`: Enable Stack Manipulation
* Second `S`: Push a number to the stack
* `S` or `T`: Positive/negative respectively
* Some `S`/`T` followed by a trailing `N`: number in binary, where `S=0` and `T=1`

I.e. `SSTTSTSN` pushes `-10`. Only the first three and trailing `N` are mandatory, so `SSSN`/`SSTN` will both push `0`.
> 1 votes

# Answer
# SimpleTemplate, 10 bytes

This was actually hard to optimize, without going into the trivial answer.

```
{@echo"1"}

```

Outputs the **string** `"1"`.

When reversing, you get the following:

```
}"1"ohce@{

```

Outputs the string `}"1"ohce@{`.

As stated in the question: "The output can be **any two distinct values**, of the same **data type**.", and both solutions output a distinct string.

You can test this on http://sandbox.onlinephpfunctions.com/code/ec4bf4b3efa93c63c6c5c9f1458330da0178b6cd
(On line 960, change between the `$code` and `$reversed` variables)

---

---

**SimpleTemplate, 2 bytes**

This one is extremelly trivial:

```
<any 2 different bytes>

```

Reversing them will output whatever is reversed.
> 1 votes

# Answer
# Ahead, 4 bytes

```
O@j1

```

Prints `0` forward and `1` backward.

## Forward

```
O     pop stack and print number
 @    end
  j1  not reached

```

## Backward

```
1     push 1
 j    jump next cell
   O  pop stack and print number
  @   end

```

Control flow is more interesting backward because I tried to reduce the amount of redundant characters.

Try it online!
> 1 votes

# Answer
# GolfScript, 2 bytes

Simply prints 1 because the duplicate instruction duplicates the null string.

```
.1

```

## Reversed

Outputs `11` because that is the value `1` duplicated.

```
1.

```

Try it online!

# GolfScript, 4 bytes

Outputs 0 because 1 - 1 is 0.

```
1 1-

```

# Reversed

Outputs `-11` due to concatenation.

```
-1 1

```

Try it online!

# GolfScript, 2 bytes (Am I allowed to use the null string?)

Outputs the null string, because the null string from the input minus 1 is still the null string.

```
1-

```

# Reversed:

Pushes -1 onto the stack.

```
-1

```

Try it online!
> 1 votes

# Answer
## , 2 bytes

Outputs `\n1`, where `\n` represents a literal newline.

```
\1

```

## Reversed

Returns 1, the expression after 1 is ignored.

```
1\

```

Try it online!
> 1 votes

# Answer
# 33, 4 bytes

```
o1ao

```

Try it online!

Outputs `01` if run forwards or `00` if run backward
> 1 votes

# Answer
# Actually, 2 bytes

```
12

```

Try it online!

Prints `2\n1\n` forwards, and `1\n2\n` backwards.
> 1 votes

# Answer
# Dis, 2 bytes

```
{!

```

Try on dis.web! Outputs one NULL character.

!bew.sid no yrT Outputs nothing.
> 1 votes

# Answer
# \>\<\> (Fish), 3 bytes

```
0n1

```

Try it forwards

Try it backwards `1n0`
> 1 votes

# Answer
# SmileBASIC, 4 bytes

```
?12?

```

prints `12\n\n` forwards and `21\n\n` backwards
> 0 votes

# Answer
# Triangular, 3 bytes

```
i.%

```

Try it online!

Prints 1.

`%.i` prints 0.

If it weren't invalid to do an integer and a character, `%#` would've been a nice 2-byter.
> 0 votes

---
Tags: code-golf, decision-problem, self-referential
---


title: It's all about the sum of the digits

text:
# Question
Title: It's all about the sum of the digits
## The sequence

Given an integer \\$n\>0\\$, we define \\$a(n)\\$ as the lowest positive integer such that there exists exactly \\$n\\$ positive integers smaller than \\$a(n)\\$ whose sum of digits is equal to the sum of the digits of \\$a(n)\\$.

*Edit: this sequence has since been published as A332046*

## First terms

```
  n | a(n) | sum of digits | matching integers
----+------+---------------+------------------------------------------------------
  1 |  10  |       1       | [1]
  2 |  20  |       2       | [2, 11]
  3 |  30  |       3       | [3, 12, 21]
  4 |  40  |       4       | [4, 13, 22, 31]
  5 |  50  |       5       | [5, 14, 23, 32, 41]
  6 |  60  |       6       | [6, 15, 24, 33, 42, 51]
  7 |  70  |       7       | [7, 16, 25, 34, 43, 52, 61]
  8 |  80  |       8       | [8, 17, 26, 35, 44, 53, 62, 71]
  9 |  90  |       9       | [9, 18, 27, 36, 45, 54, 63, 72, 81]
 10 | 108  |       9       | [9, 18, 27, 36, 45, 54, 63, 72, 81, 90]
 .. |  ..  |      ..       | ..
 20 | 216  |       9       | [9, 18, 27, 36, 45, 54, 63, 72, 81, 90, ..., 207]
 .. |  ..  |      ..       | ..
 30 | 325  |      10       | [19, 28, 37, 46, 55, 64, 73, 82, 91, 109, ..., 316]
 .. |  ..  |      ..       | ..
 40 | 442  |      10       | [19, 28, 37, 46, 55, 64, 73, 82, 91, 109, ..., 433]
 .. |  ..  |      ..       | ..
 50 | 560  |      11       | [29, 38, 47, 56, 65, 74, 83, 92, 119, 128, ..., 551]

```

## More examples

```
a(13) = 135
a(17) = 171
a(42) = 460
a(57) = 660
a(81) = 1093
a(82) = 1128
a(118) = 1507
a(669) = 9900
a(670) = 10089
a(1000) = 14552
a(5000) = 80292
a(10000) = 162085

```

As a side note, you may not assume that the sum of the digits may only increase. For instance, the sum of the digits for \\$a(81)\\$ is \\$1+0+9+3=13\\$, while the sum of the digits for \\$a(82)\\$ is \\$1+1+2+8=12\\$.

## Rules

* You may either:

+ take a 1-indexed integer \\$n\\$ and return \\$a(n)\\$
    + take a 0-indexed integer \\$n\\$ and return \\$a(n+1)\\$
    + take a positive integer \\$n\\$ and return the \\$n\\$ first terms
    + print the sequence indefinitely
* This is !

# Answer
# Pyth, 12 bytes

```
f}hQ_XsjT;H1

```

Try it online!

* `f`: Count up from 1 to find the first number such that:
* `X ... H1`: Increment or insert the value 1 into the dictionary H at index
* `sjT;`: sum of base ten digits of current number
* `_`: values of dictionary
* `}hQ`: check whether input + 1 is contained within.

The first time this is true, exactly input numbers must have the same digit sum as the current number, for the first time.
> 10 votes

# Answer
# Gaia, ~~13~~ 10 bytes

```
1⟨┅Σ¦ṅC=⟩#

```

Try it online!

Straightforward implementation.

## Explanation:

```
1⟨	⟩#	| find the first 1 positive integers N where:
      C		| the count of
     ṅ		| the digital sum d(N)
  ┅Σ¦		| in the list [d(1)..d(N-1)]
       =	| is equal to the (implicit) input

```
> 4 votes

# Answer
# Jelly, 10 bytes

```
D€§ċṪ$=ʋ1#

```

Try it online!

A monadic link taking an integer \\$n\\$ and returning \\$a(n)\\$.

## Explanation

```
       ʋ1# | Find the first integer x where the following is true;
D€         | - Digits of 1..x
  §        | - Sum each
   ċṪ$     | - Count the number equal to the tail (after popping tail)
      =    | - Equal to (implicit original argument to link)

```
> 3 votes

# Answer
# 05AB1E, 10 bytes

```
∞.Δ1Ÿ1öć¢Q

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Unicode), 27 bytesSBCS

```
{⌈⌿+\∘.=⍨1⊥10⊥⍣¯1⍳20×⍵}⍳+∘1

```

Try it online!

### How it works

```
{⌈⌿+\∘.=⍨1⊥10⊥⍣¯1⍳20×⍵}⍳+∘1  ⍝ Right argument: n
{                     }⍳+∘1  ⍝ Find the first index of n+1 from...
 ⌈⌿+\∘.=⍨1⊥10⊥⍣¯1⍳20×⍵       ⍝ ... the list of cumulative count of own digit sum (sort of)
                  20×⍵         ⍝ Practical upper bound 20×n (could also use theoretical 10*⍵)
                 ⍳             ⍝ Range: 1..20×n
           10⊥⍣¯1  ⍝ Extract decimal digits from each
         1⊥        ⍝ Sum the digits of each number
     ∘.=⍨    ⍝ Self outer product by equality
   +\        ⍝ Cumulative sum in row direction; cumulative counts of own digit sum
 ⌈⌿          ⍝ Maximum in column direction; cumulative maximum of cumulative count

```
> 3 votes

# Answer
# Python 2, 71 bytes

```
f=lambda n,x=[0]:x.count(x[-1])+~n and-~f(n,x+[sum(map(int,`len(x)`))])

```

Try it online!
> 3 votes

# Answer
# Charcoal, 16 bytes

```
Ｗ⁻№υΣＬυθ⊞υΣＬυＩＬυ

```

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

```
Ｗ⁻№υΣＬυθ

```

Count the number of entries in the predefined list that are equal to the digital sum of the length of the list and repeat while that does not equal the input...

```
⊞υΣＬυ

```

... append the digital sum of the length of the list to the list.

```
ＩＬυ

```

Output the length of the list.
> 2 votes

# Answer
# Ruby, 55 bytes

```
->n,r=0,*w{w<<k=(r+=1).digits.sum until w.count(k)>n;r}

```

Try it online!
> 2 votes

# Answer
# Python 2, 92 93 bytes

```
f=lambda n,x=1:n==sum(sum(map(int,`i`))==sum(map(int,`x`))for i in range(x))and x or f(n,x+1)

```

Try it online!

All I can get for now but I suspect someone much more competent than I am could do much better.
> 1 votes

# Answer
# JavaScript (Node.js), ~~68~~ ~~67~~ 63 bytes

~~-1~~ -5 byte thanks Arnauld

```
n=>(F=z=>F[g=eval([...z+''].join`+`)]^n?F(-~z,F[g]=-~F[g]):z)``

```

Try it online!
> 1 votes

# Answer
# Java 8, 138 bytes

```
n->{for(int a=9,c,i;;a++){for(c=i=0;++i<a;)c+=(i+"").chars().map(q->q-48).sum()==(a+"").chars().map(q->q-48).sum()?1:0;if(c==n)return a;}}

```

Try it online.

**Explanation:**

```
n->{               // Method with integer as both parameter and return-type
  for(int a=9,     //  Integer `a_i`, starting at 9 (since a(1)=10)
          c,       //  Count-integer
          i;       //  Loop-integer
      ;            //  Loop indefinitely:
       a++){       //    After every iteration: increase `a_i` by 1
    for(c=i=0;     //   Reset both the count and loop integers to 0
        ++i<a;)    //   Inner loop `i` in the range (0,a):
      c+=          //    Increase the count by:
         (i+"").chars().map(q->q-48).sum()
                   //     If the digit-sum of `i`
           ==(a+"").chars().map(q->q-48).sum()?
                   //     equals the digit-sum of `a_i`:
            1      //      Increase the count by 1
           :       //     Else:
            0;     //      Leave the count the same by increasing with 0
    if(c==n)       //   If the count equals the input integer `n` after the inner loop:
      return a;}}  //    Return `a_i` as our `a(n)` result

```
> 1 votes

# Answer
# PowerShell, ~~74~~ 72 bytes

```
$a=@{}
1.."$args"|%{for(;$_-$a.(++$i|%{"$_"[0..9]-join'+'|iex})++){}}
$i

```

Try it online!

`2^31 = 2147483647`, so the expression `"$_"[0..9]` works with any Powershell `[int] > 0`.
> 1 votes

# Answer
# Wolfram Language (Mathematica), 92 or 113 bytes

Brute force short version:

```
(t=Total@IntegerDigits@#&;Catch@Do[If[Count[Range@(k-1),x_/;t@x==t@k]==#,Throw@k],{k,∞}])&

```

Try it online!

Time- and memory-optimized version. Print table of values up to given number:

```
(n=0;a=<||>;r={};Do[While[FreeQ[a,i+1],a[k]=Lookup[a,k=Total@IntegerDigits@++n,0]+1];AppendTo[r,{i,n}],{i,#}];r)&

```

Try it online!

Ungolfed self-explained:

```
next = 0; assoc = <||>;
max = 30; result = {};
Do[
 While[FreeQ[assoc, n + 1],
  next += 1;
  key = Total@IntegerDigits@next;
  assoc[key] = Lookup[assoc, key, 0] + 1
  ];
 AppendTo[result, {n, next}]
 , {n, max}]; result

```
> 0 votes

# Answer
# Scala, 115 bytes

Golfed version. Try it online!

```
def f(n: Int)={var r,k=0;var w=List[Int]();do{r+=1;k=r.toString.map(_.asDigit).sum;w:+=k}while(w.count(_==k)<=n);r}

```

Ungolfed version. Try it online!

```
object RubyToScala {
  def main(args: Array[String]): Unit = {
    println(f(1))
    println(f(2))
    println(f(3))
    println(f(30))
    println(f(50))
    println(f(1000))
  }

  def f(n: Int): Int = {
    var r = 0
    var w = List[Int]()
    var k = 0
    do {
      r += 1
      k = r.toString.map(_.asDigit).sum
      w :+= k
    } while (w.count(_ == k) <= n)
    r
  }
}

```
> 0 votes

# Answer
# Japt, 14 bytes

```
@¶XÇìxÃè¶Xìx}a

```

Try it
> 0 votes

# Answer
# Thunno 2, 6 bytes

```
ƘRʂṪc=

```

Try it online!

#### Explanation

```
ƘRʂṪc=  # Implicit input
Ƙ       # Find the first positive integer, n, where:
 R      #  Push [1..n]
  ʂ     #  Get the digital sum of each number
   Ṫ    #  Remove the last item and push it separately
    c   #  Count the occurrences of this in the list
     =  #  Does this equal the input?

```
> 0 votes

# Answer
# Lua, 93 bytes

```
t={}n=0repeat m=0n=n+1(n..''):gsub('.',load'm=m+...')t[m]=(t[m]or 0)+1until...+0<t[m]print(n)

```

Try it online!

Ungolfed version:

```
t={}n=0
repeat
    m=0 n=n+1                        --Increment n, set m to 0
    (n..''):gsub('.',load'm=m+...')  --Sum digits of n, store in m
    t[m]=(t[m]or 0)+1                --Increment t[m], or set to 1 if null
until...+0<t[m]                      --If input < t[m], stop loop
print(n)

```
> 0 votes

---
Tags: code-golf, sequence
---


title: Decide Contiguous Binary Tree

text:
# Question
Title: Decide Contiguous Binary Tree
# Objective

Given an unlabelled binary tree, decide whether it is contiguous in indices.

# Indices

This challenge gives one-indexing on binary trees. The exact definition expresses all indices in binary numeral:

* The root is indexed `1`.
* For every node, to get the index of its left child, replace the most significant `1` by `10`.
* For every node, to get the index of its right child, replace the most significant `1` by `11`.

For illustration:

A binary tree is **contiguous in indices** iff the indices of its nodes have no gaps.

Note that every binary tree with contiguous indices is balanced.

# I/O Format

Flexible.

# Examples

`L` indicates a leaf. `[ , ]` indicates a branch.

## Truthy

```
L
[L,L]
[[L,L],L]
[[L,L],[L,L]]
[[[L,L],L],[L,L]]
[[[L,L],L],[[L,L],L]]

```

## Falsy

```
[L,[L,L]]
[[[L,L],L],L]
[[[L,L],[L,L]],[L,L]]
[[[L,L],L],[L,[L,L]]]

```

# Answer
# Jelly, ~~11~~ ~~10~~ ~~9~~ ~~8~~ 7 bytes

```
ŒṪ’UḄṬP

```

Try it online!

*-1 thanks to Jonathan Allan--funny that I used `ŒṪ` earlier, but never tried removing `Ż` with it*

~~Very~~ *Embarrassingly* naive solution, using `ŒṪ` "generate multidimensional truthy indices" to directly produce the indices, then  "untruth" to lay them out... if I was sure it works at all, since this doesn't actually produce the stated labeling scheme or represent non-leaf nodes at all. I actually thought it didn't work for a bit, but then I realized my counterexample wasn't a binary tree to begin with.

Requires that the leaf value is truthy.

```
ŒJ         Generate multidimensional 1-indices of truthy values.
  ’        Decrement to 0-indices,
   U       and reverse, so the deepest index is most significant
    Ḅ      when they're converted from binary.
     Ṭ     Generate the shortest array of 1s and 0s that has 1s at exactly those indices,
      P    and check that it doesn't contain any 0s.

```

Since there's no leading 1, this identifies every non-leaf node with its leftmost descendant, but this seems not to matter.
> 11 votes

# Answer
# Wolfram Language (Mathematica), 55 bytes

-6 bytes thanks to @att.

```
Length[l=If[0>##,0,#+2#0@##2]&@@@#~Position~_List]l&

```

Try it online!
> 6 votes

# Answer
# JavaScript (ES6), 69 bytes

Expects a nested list of `1`'s. Returns a Boolean value.

```
a=>!((m=F=(a,v,q)=>+a||a.map(b=>F(b,v+=q,q*2),m|=1<<v))(a,1,1),m&m+2)

```

Try it online!

### Commented

```
a => !(         // a[] = input array
  ( m =         // m = bit mask to store node indices
    F = (       // F is a recursive function taking:
      a,        //   a[] = current node
      v,        //   v = node index
      q         //   q = highest power of 2 such that q ≤ v
    ) =>        //
    +a ||       // stop if this is a leaf
    a.map(b =>  // otherwise, for each child node b[]:
      F(        //   do a recursive call:
        b,      //     pass the child node
        v += q, //     add q to v
        q * 2   //     double q
      ),        //   end of recursive call
      m |=      //   update the bit mask m ...
        1 << v  //   ... so that the current node index is marked
    )           // end of map()
  )(a, 1, 1),   // initial call to F with a[] = input and v = q = 1
  m & m + 2     // test whether m has any bit in common with m + 2
)               // (if not, the only 0 in m is the trailing 0)

```
> 5 votes

# Answer
# 05AB1E, ~~37~~ 34 bytes

```
Δ€`}\NÝ"€"×€"Dÿƶ˜s"J.V\)ø<í2δβ>{āQ

```

Port of *@UnrelatedString*'s Jelly answer, but unfortunately 05AB1E lacks a multi-dimensional indices builtin, so we'll have to do that manually at the cost of 26 bytes.. :/

Uses `1` as leaves.

Try it online or verify all test cases.

**Explanation:**

```
Δ€`}\N         # Determine the depth-1 of the (implicit) multi-dimensional input-list:
Δ              #  Loop until the result no longer changes:
 €`            #   Flatten it one level down
   }\          #  After the loop: discard the resulting flattened list
     N         #  And push the last (0-based) index of the loop instead
Ý              # Pop and push a list in the range [0,depth-1]
 "€"×          # Map each to that many "€" as string
     €         # Then map each string to:
      "Dÿƶ˜s"  #  String "Dÿƶ˜s", where `ÿ` is replaced with the "€"-string
             J # Join this list of strings together
.V             # Evaluate and execute it as 05AB1E code:
       D       #  Duplicate the multi-dimensional list of 1s
        €      #  Zero or more `€`: map to a certain depth:
         ƶ     #   Multiply each value by its 1-based index
          ˜    #  Flatten the multi-dimensional list
           s   #  Swap, so the multi-dimensional list of 1s is at the top again
  \            # Discard the last multi-dimensional list of 1s
   )           # Wrap all flattened lists on the stack into a list
    ø          # Zip/transpose; swapping rows/columns
     <         # Decrease everything from 1-based to 0-based indices
í              # Reverse each inner list of multi-dimensional indices
  δ            # Map over each list:
 2 β           #  Convert it from a base-2 list to an integer
    >          # Increase each 0-based value by 1 to a 1-based value
     {         # Sort it
      ā        # Push a list in the range [1,length] (without popping the list)
       Q       # Check if the two lists are the same, in which case there are no gaps
               # (which is output implicitly as result)

```

Determining the depth of a ragged-list (`Δ€`}\N`) I've done before in this challenge.
Determining the multi-dimensional indices of a ragged-list (`Δ€`}\NÝ"€"×€"Dÿƶ˜s"J.V\)ø<`) I've done before in this challenge.
> 5 votes

# Answer
# Charcoal, 23 bytes

```
Ｆ№⭆¹θ1⊞υ∨¬ιＥ²§υ⊘⁻ικ⁼θ⊟υ

```

Try it online! Link is to verbose version of code. Takes input as a list using `1` for leaves (note that Charcoal takes a list of inputs, so there's an extra set of `[]`s) and outputs a Charcoal boolean, i.e. `-` for contiguous, nothing if not. Explanation: Port of my Retina 0.8.2 answer.

```
Ｆ№⭆¹θ1

```

Count the number of leaves.

```
⊞υ∨¬ιＥ²§υ⊘⁻ικ

```

Generate the balanced tree with that number of leaves.

```
⁼θ⊟υ

```

Compare it to the input.
> 5 votes

# Answer
# Retina 0.8.2, 48 bytes

```
$
¶$`
T`[,]`_`^.+
+`(L+)(\1L?)
[$2,$1]
^(.+)¶\1$

```

Try it online! Link includes test cases. Explanation: Pretty sure this works, but I don't know how to prove it.

```
$
¶$`

```

Duplicate the input.

```
T`[,]`_`^.+

```

Flatten one copy.

```
+`(L+)(\1L?)
[$2,$1]

```

Turn into a balanced tree.

```
^(.+)¶\1$

```

Check whether this equals the original tree.
> 3 votes

# Answer
# Haskell, 53 bytes

```
data T=T T T|L
h L=[0]
h(T l r)=[1+d|d<-h l,h r==[d]]

```

Try it online!
> 3 votes

# Answer
# Python3, 232 bytes:

```
def b(x,c,r,d):
 if isinstance(x,list):d[c]=d.get(c,[])+[r];b(x[0],c+1,'10'+r[1:],d);b(x[1],c+1,'11'+r[1:],d)
def f(t):d={};b(t,0,'1',d);K=sorted([int(i,2)for j in d for i in d[j]]);return all(K[j]+1==K[j+1]for j in range(len(K)-1))

```

Try it online!
> 2 votes

# Answer
# julia, 47 bytes

Expects a nested list of `0`s.

Truthy output: `true` or a positive integer of the total number of leaves

Falsy output: a negative integer

```
c(t)=t==0||(0<=-(c.(t)...)<2)*(+(c.(t)...,1))-1

```

The criterion is that a tree is truthy if, for each neighbouring pair of subtrees \\$T\_1, T\_2\\$ with the same parent node, the number of leaves in \\$T\_1\\$ must be equal to or exactly one more then the number of leaves in \\$T\_2\\$

The function `c` returns `true` on a leaf. Otherwise, we compute recursively `-(c.(t)...)` (which is equivalent to `c(t[1]) - c(t[2])`). This will be either 0 or 1 if `t` is truthy or sometimes if both `t[1]` and `t[2]` are falsy.

In any case, if the condition holds, we return `+(c.(t)...,1)-1` (equivalent to `c(t[1]) + c(t[2])`), which is the total number of leaves if `t` is truthy and negative otherwise. If the condition fails, we return `-1`.

Attempt This Online!
> 1 votes

---
Tags: code-golf, decision-problem, binary-tree
---


title: Solve for N from input string

text:
# Question
Title: Solve for N from input string
# Challenge :

Your job is to find the given number `N`.

---

# Input :

You will be given a string in the following form:

```
dN ± Y = X

```

Where:

```
d, N, X, Y are all numbers with d , X , Y being integers (not decimals).

```

---

# Output :

Solve the equation and output the value of `N` rounded. Round up if decimal is greater than or equal to `0.5` and round down if less than `0.5`

---

# Examples :

```
Input                  Output
 N + 1 = 3        ---> 2
 N - 1 = 5        ---> 6
2N + 1 = 3        ---> 1
2N + 1 = 4        ---> 2

```

---

# Winning criteria :

This is so the shortest code in each language wins.

---

# Notes :

* Answer must be rounded it cannot be a float
* Whitespace do not matter. You can have every element in the string separated by white space if you want or if you don't want leave it as it is.
* You do not need to check for invalid input. i.e. All inputs will be strings in the given format.

---

# Answer
# Python 2, ~~88~~ ~~74~~ 70 bytes

-14 bytes thanks to Chas Brown.
-4 bytes thanks to Sunny Patel.

```
d,w,Y,_,X=input().split()
print round((int(X)-int(w+Y))/float(d[:-1]))

```

Try it online!
> 5 votes

# Answer
under the assumption (according to comments) that we deal only with digits

# JavaScript (Node.js), 30 bytes

\*thanks for @Rick Hitchcock for pointing out i can use 1 instead of space (reduces 13 bytes

```
x=>(x[3]+x[5]-x[9])/-x[0]+.5|0

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~64~~ 63 bytes

Using `eval`

```
d,w,Y,_,X=input().split()
print-eval('('+w+Y+'-'+X+')/'+d[:-1])

```

Try it online!

Saved 1 byte thanks to Keyu Gan
> 3 votes

# Answer
# Java 10, ~~111~~ 94 (or 92) bytes

```
s->{var a=s.split("N|=");return(int)((new Float(a[2])-new Float(a[1]))/new Float(a[0])+.5);}

```

Input is in the format `dN±Y=X` (without any spaces) instead of `dN ± Y = X`.

Try it online.

2 more bytes could be saved if the numbers are never outside the `[-128, 127]` range, in which case the last and one of the two first `Float` can be changed to `Byte`.
Try it online.

**Explanation:**

```
s->{                             // Method with String parameter and integer return-type
  var a=s.split("N|=");          //  And split by "N" or "=" to a String-array
  return(int)((new Float(a[2])   //  Return the third number (after the equal sign),
               -new Float(a[1])) //   minus the second number (including leading +/-),
              /new Float(a[0])   //   divided by the first number
         +.5);}                  //  Rounded by using `(int)(R + 0.5)`

```
> 2 votes

# Answer
# Japt v2.0a0, 20 bytes

```
q/N|=/ f
o!-Uo)r!÷ r

```

Try it

```
q/N|=/ f\no!-Uo)r!÷ r     :Implicit input of string U
                          : e.g. "2N+1=4"  "N+1=4"
q                         :Split on
 /N|=/                    :  "N" or "="
                          > ["2","+1","4"] ["","+1","4"]
       f                  :Filter (removes the first element if the string started with "N")
                          > ["2","+1","4"] ["+1","4"]
        \n                :Reassign to U
             Uo           :Pop last element (X)
                          > "4"            "4"
          o               :Modify last element (Y)
           !-             :X-Y
                          > ["2",3]        [3]
                r         :Reduce by
                 !÷       :  Inverse division
                          > 1.5            3
                    r     :Round
                          > 2              3

```
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~54~~ 46 bytes

```
Round[ToExpression[""<>(#/."="->"-")]~Root~1]&

```

Try it online!
> 1 votes

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

```
x=>([m,a,r]=x.split(/N|=/),r-a)/(+m||1)+.5|0

```

Try it online!

Or, for only single-digit numbers:

# JavaScript (Node.js), 36 bytes

```
([m,,o,a,,r])=>-(o+a-r)/(+m||1)+.5|0

```

Try it online!
> 1 votes

# Answer
# Befunge-93 (FBBI), ~~34~~ 26 bytes

```
&~$~90p0&X&-2*\/-:2%\2/+.@

```

Try it online!

If we didn’t need to bother with rounding correctly, it could be much smaller:

```
&~$~90p0&X&-\/-.@

```

Try it online!

`-\/-`
> 1 votes

# Answer
# C (clang), 133 bytes

```
N,d,y,x,a[9],o;f(*s){sscanf(s," %[0-9N] %c %d = %d",a,&o,&y,&x);d=!sscanf(a,"%d",&d)?1:d;N=(x-(o>43?-y:y))*2/d;printf("%d",N/2+N%2);}

```

Try it online!

This handles all spaces except between `d` and `N`.

\[Removed wrong answer that rounds down\]
> 1 votes

# Answer
# Yabasic, 142 bytes

An anonymous function that takes input as a string and outputs to the console.

```
Line Input""s$
dim n$(5)
k=token(s$,n$())
n$=n$(1)
If n$="N"n$=("1N")
?Int((Val(n$(5))-Val(n$(2)+"1")*Val(n$(3)))/Val(Left$(n$,Len(n$)-1))+.5)

```

Try it online!
> 1 votes

# Answer
# Vyxal, 110 bits1, 13.75 bytes

```
‛Nx*\=/ƒ∆qh.1+ṙ

```

Try it Online!

Python rounding is a little goofy hence the `.1+ṙ` at the end.

Could be 9.125 bytes: `‛Nx*\=/ƒ∆q` if it wasn't for rounding.

## Explained

```
‛Nx*\=/ƒ∆qh.1+ṙ
‛Nx*            # Replace all N with x
    \=/         # split on equal sign
       ƒ∆q      # and solve the equation for x. Yes. There's a built in for it.
          h.1+  # add 0.1 to the result to account for the fact that python seems to round down if <= 0.5 instead of < 0.5
              ṙ # round the answer as required

```
> 1 votes

# Answer
# Scala 3, 168 bytes

```
import java.lang._
import scala.util.chaining._
val c:String=>Int=_.split("N|=").pipe(a=>(new Float(a(2))-new Float(a(1)))/new Float(a(0))).pipe(x=>math.round(x).toInt)

```

Attempt This Online!
> 1 votes

# Answer
# \[Matlab\], 91 bytes

this is the most resilient version.

assuming that s is the input string.

```
syms N;v=str2double(regexp(s,'(?<!\d)(\d)+(?!\d)','match'));round(solve(v(1)*N+v(2)==v(3)))

```

# \[Matlab\], 74 bytes

```
syms N;round(solve(str2double(s(1))*N+str2double(s(4))==str2double(s(6))))

```

but doesnt really work if for example Y was 2 digits (ie 10). I'll try to improve it a bit.

# \[Matlab\], 29 bytes

if the input was just the numbers and not a string

```
sym N;round(solve(d*N+Y==X))

```
> 1 votes

# Answer
# Convex, 19 bytes

```
S-®-?\d+"ô:d~\-\/mo

```

Try it online!
> 0 votes

# Answer
# PHP, 45 bytes

```
<?=round((($s=$argn)[3].$s[5]-$s[9])/-$s[0]);

```

Run with `echo '<input>' | php -nF <filename>` or Try it online.

This requires that `d` always be given, and that the string is the same length each time, e.g.:

* `N + 1 = 3` *won't* work, but `1N + 1 = 3` *will* work.
* `1N +1 =3` *won't* work, but `1N + 1 = 3` *will* work.
> 0 votes

# Answer
# J, 26 Bytes

```
<.({.%~{:-1&{)".>0 2 4{cut

```

Note that the result for N is floored (not rounded), so for the last test case it returns 1 instead of 2. If this is unacceptable I will change the answer.

Input should be of the form `'d N +-Y = X'`

### Explanation:

```
   cut '10 N +2 = 23'  NB. Split on whitespace
┌──┬─┬──┬─┬──┐
│10│N│+2│=│23│
└──┴─┴──┴─┴──┘
   0 2 4{cut '10 N +2 = 23'  NB. Choose relevant portions
┌──┬──┬──┐
│10│+2│23│
└──┴──┴──┘
   ".>0 2 4{cut '10 N +2 = 23'  NB. Eval each
10 2 23
   ({.%~{:-1&{)".>0 2 4{cut'10 N +2 = 23'  NB. Compute (x-y)/d
2.1
   <.({.%~{:-1&{)".>0 2 4{cut'10 N +2 = 23'  NB. Floor
2

```
> 0 votes

# Answer
## C# (149 Bytes)

```
s=>(int)Math.Round(((s=s.Replace(" ",""))[s.Length-1]-48-((s.Contains("-")?-1:1)*(s.Split(new[]{'+','-'})[1][0]-48)))/(decimal)(s[0]=='N'?1:s[0]-48))

```

Craptacular bloated C# solution. Guess I could've ported the Java solution but I try not to look at others' stuff before posting mine, so here we are.

Try it Online
> 0 votes

# Answer
# Ruby, 66 bytes

```
->s{a,_,b,_,c=s.split.map &:to_f;((s[?+]?c-b:c+b)/(a+0**a)).round}

```

Try it online!
> 0 votes

# Answer
# awk, 48 bytes

```
awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

```

Use cases:

```
echo "N + 1 = 3" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

echo "N - 1 = 5" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

echo "2N + 1 = 3" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

echo "2N + 1 = 4" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

```

Extra case:

```
echo "3N + 1 = 11" | awk -F'[ N]' '{printf("%.f",($6-$4)/($1?$1:1))}'

```

Output: 3
> 0 votes

# Answer
## PHP, 83 Bytes

Try it online

Try it online2

For some reason **`round`** does not round to the closest integer on tio run, on this version the solution has some extra bytes **(87 Bytes)**

**Code**

```
<?=round(($c=explode(" ",$argv))[4]-($c[1].$c[2]))/($c[0]==N?1:substr($c[0],0,-1));

```

**Explanation**

```
//ecuation structure xN sign c = m
//array structure like ["xN","sign", "c", "=", "m"]
round(                         //round the result
(                              //first element of the ecuation
   $c=explode(" ",$argv))[4]   //explode the string and get the 4th value
   -                           //substract, php accepts (1-(-1)) so,
                               //it can ve solved like this
   ($c[1].$c[2])               //concat the sign with c
)
/                              //divide by x
($c[0]==N?1:substr($c[0],0,-1) //if the first element xN it's N
                               //divide by 1, else remove N and divide
);

```

**Question**

About negative numbers, my code should work for an equation like `-xN +- c = m`, but when you are considering a `x = -1`, the input will be `-N +- c = m` or `-1N +- c = m`?
> 0 votes

# Answer
# , 90 bytes

```
-round(eval(parse(t=gsub("=","-",gsub("\\dN","",s<-scan(,"")))))/(gsub("N.*$","",s):1)[1])

```

Try it online!

Assumes `d` is present as per the spec. Probably not the shortest option - I am sure there are better regex.
> 0 votes

# Answer
`awk` : safe division without branching ternary condition

```
echo 'N + 1 = 3' |

gawk '$__=sprintf("%.f",($5-($2$3))/(_+=$_)^!!_)'
mawk '{printf("%.f",($5-($2$3))/(_+=$_)^!!_)}'

```

---

```
2

```

---

```
echo '2N + 1 = 4' |

nawk '$!NF=sprintf("%.f",($5-($2$3))/(_+=$!_)^!!_)'

```

---

```
2

```
> 0 votes

---
Tags: code-golf, string, math
---


title: Binary Fibonacci

text:
# Question
Title: Binary Fibonacci
## Challenge

You need to generate a program or function that takes in a positive integer N, calculates the first N terms of the Fibonacci sequence in binary, concatenates it into a single binary number, converts that number back to decimal, and then outputs the decimal as an integer.

For example

```
1 -> [0] -> 0 to decimal outputs 0
3 -> [0, 1, 1] -> 011 to decimal outputs 3
4 -> [0, 1, 1, 10] -> 01110 to decimal outputs 14

```

You do not need to output the `->`, just the number (e.g. if the user types `4`, just output `14`). The arrows are just to help explain what the program must do.

## Test cases

```
1 -> 0
2 -> 1
3 -> 3
4 -> 14
5 -> 59
6 -> 477
7 -> 7640
8 -> 122253
9 -> 3912117
10 -> 250375522
11 -> 16024033463
12 -> 2051076283353
13 -> 525075528538512
14 -> 134419335305859305
15 -> 68822699676599964537
16 -> 70474444468838363686498
17 -> 72165831136090484414974939
18 -> 147795622166713312081868676669
19 -> 605370868394857726287334099638808
20 -> 4959198153890674493745840944241119317

```

The program must be able to output up to the limit of the language in use. No lookup tables or common workarounds allowed.

This is , so the answer with the shortest number of bytes wins!

# Answer
# Python, 64 bytes

```
f=lambda n,a=0,b=1,r=0:n and f(n-1,b,a+b,r<<len(bin(a))-2|a)or r

```

Try it online!
> 11 votes

# Answer
# Jelly,  ~~7~~  6 bytes

```
ḶÆḞBẎḄ

```

**Try it online!**

### How?

```
ḶÆḞBẎḄ - Link: integer, n
Ḷ      - lowered range -> [0,1,2,3,4,5,...,n]
 ÆḞ    - Fibonacci (vectorises) -> [0,1,1,2,3,5...,F(n)]
   B   - to binary (vectorises) -> [[0],[1],[1],[1,0],[1,1],[1,0,1],...,B(F(n))]
    Ẏ  - tighten -> [0,1,1,1,0,1,1,1,0,1,...,B(F(n))[0],B(F(n))[1],...]
     Ḅ - from binary -> answer

```
> 10 votes

# Answer
# Python 3.6, 61 bytes

```
f=lambda n,a=0,b=1:n and int(f'{a:b}{f(n-1,b,a+b)*2:b}',2)//2

```

Try it online!
> 9 votes

# Answer
# Husk, 7 bytes

```
ḋṁḋ↑Θİf

```

Try it online!

### Explanation

```
ḋṁḋ↑Θİf                              4
     İf    The Fibonacci numbers     [1,1,2,3,5,8..]
    Θ      Prepends 0                [0,1,1,2,3,5..]
   ↑     Take n elements from list   [0,1,1,2]
  ḋ        Convert to binary digits  [[0],[1],[1],[1,0]]
 ṁ       Map function then concat    [0,1,1,1,0]
ḋ        Convert from base 2         14

```
> 8 votes

# Answer
# brainfuck, 397 bytes

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

```

Well, that was fun!

Takes ASCII input (e.g. `11`), outputs result in ASCII.

Note: to try this online, make sure you set the cell size to 32 bits (on the right side of the webpage). **If you do not enter an input, your browser might crash.**

The interpreter cannot handle input of `11` and higher because it only supports up to 32 bits.

Try it on copy.sh

## Explanation

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

```

Get decimal input and add one (to mitigate off-by-one)

```
[-<<+>>[-[->+<]<<[->+>+<<]<[->+>+<<]>[-<+>]>>[-<<+>>]>]]

```

Generate fibonacci numbers on the tape.

```
<<[->+>>>>>+<<<<<<]>[-<+>]>+>>+>>>+<

```

Set up for the incoming binary concatenation loop

---

So the cells contain the value, starting from the first position,

```
1 | 0 | 1 | 1 | 2 | 3 | 5 | ... | f_n | 0 | 1 | 0 | 1 | 0 | f_n | 1 | 0 | 0 | 0...

```

Look at these cells:

```
f_n | 0 | 1 | 0 | 1 | 0 | f_n | 1

```

I'll label this:

```
num | sum | cat | 0 | pow | 0 | num | pow

```

`pow` is there to find the maximal power of 2 that is strictly greater than `num`. `sum` is the concatenation of numbers so far. `cat` is the power of 2 that I would need to multiply the `num` in order to concatenate `num` in front of the `sum` (so I would be able to simply add).

---

```
[[->-[<<]>]>

```

**Loop: Check whether `f_n` is strictly less than `pow`.**

**Truthy:**

```
[[-]<<<<<<<[->>[-<+>>+<]>[-<+>]<<<]<[->+>>>>>+<<<<<<]>[-<+>]>[-<+>]>[->>[-<+<<+>>>]<[->+<]<]>+>[-]>>+>]

```

Zero out junk. Then, add `num` * `cat` to `sum`. Next, load the next Fibonacci number (= `f_(n-1)`; if it doesn't exist, exit loop) and set `cat` to `cat` * `pow`. Prepare for next loop (zero out more junk, shift scope by one).

**Falsey:**

```
<<<<<[[->++>+>++<<<]>[-<+>]<<]

```

Set `pow` to 2 * `pow`, restore `num`.

```
]

```

Repeat until there is no Fibonacci number left.

---

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

```

Clean garbage. Take each digit of the resulting number and output each (in ascii).
> 7 votes

# Answer
# Japt, 9 bytes

```
ÆMgX ¤Ã¬Í

```

Run it

## Explanation:

```
ÆMgX ¤Ã¬Í
Æ     Ã     | Iterate X through the range [0...Input]
 MgX        |   Xth Fibonacci number
     ¤      |   Binary
       ¬    | Join into a string
        Í   | Convert into a base-2 number

```
> 5 votes

# Answer
# Pyth, 22 bytes

```
JU2VQ=+Js>2J)is.BM<JQ2

```

Try it here

### Explanation

```
JU2VQ=+Js>2J)is.BM<JQ2
JU2                       Set J = [0, 1].
   VQ       )             <Input> times...
     =+Js>2J              ... add the last 2 elements of J and put that in J.
                  <JQ     Take the first <input> elements...
               .BM        ... convert each to binary...
              s           ... concatenate them...
             i       2    ... and convert back to decimal.

```
> 4 votes

# Answer
# JavaScript (Node.js), 70 65 58 57 55 bytes

* thanks to Shaggy for reducing 2 bytes ('0b+C-0 to '0b'+C)

```
f=(n,a=C=0,b=1)=>--n?f(n,b,a+b,C+=b.toString(2)):'0b'+C

```

Try it online!
> 3 votes

# Answer
# Perl 6, 38 bytes

```
{:2([~] (0,1,*+*...*)[^$_]>>.base(2))}

```

Try it online!
> 3 votes

# Answer
# 05AB1E, 6 bytes

```
LÅfbJC

```

Try it online!

---

1-indexed.
> 2 votes

# Answer
# Pyth, 27 bytes

```
JU2V-Q2=aJ+eJ@J_2)is.BM<JQ2

```

**Test suite**

Python 3 translation:
```
Q=eval(input())
J=list(range(2))
for i in range(Q-2):
    J.append(J[-1]+J[-2])
print(int(''.join(map("{0:b}".format,J[:Q])),2))

```

---

## ~~37 bytes~~

~~```
J[Z1)W<lJQ=aJ+eJ@J_2)Ig1QZ.?ijkm.BdJ2

```
**Test suite**
Python 3 translation:
```
Q=eval(input())
J=[0,1]
while len(J)<Q:
    J.append(J[-1]+J[-2])
if 1>=Q:
    print(0)
else:
    print(int(''.join(map("{0:b}".format,J)),2))

```~~
> 2 votes

# Answer
# x86, ~~37~~ ~~22~~ 21 bytes

**Changelog**

* -13 by using `bsr`. Thanks Peter Cordes!
* -2 by zeroing registers with `mul`.
* -1 by using a while loop instead of `loop` and `push`/`pop` `ecx` (credit Peter Cordes).

Input in `edi`, output in `edx`.

```
.section .text
.globl main
main:
        mov     $5, %edi            # n = 5

start:
        dec     %edi                # Adjust loop count
        xor     %ebx, %ebx          # b = 0
        mul     %ebx                # a = result = 0
        inc     %ebx                # b = 1

fib:
        add     %ebx, %eax          # a += b
        xchg    %eax, %ebx          # swap a,b
        bsr     %eax, %ecx          # c = (bits of a) - 1
        inc     %ecx                # c += 1
        sal     %cl, %edx           # result >>= c
        add     %eax, %edx          # result += a

        dec     %edi                # n--; do while(n)
        jnz     fib

        ret

```

Objdump:

```
00000005 <start>:
   5:   4f                      dec    %edi
   6:   31 db                   xor    %ebx,%ebx
   8:   f7 e3                   mul    %ebx
   a:   43                      inc    %ebx

0000000b <fib>:
   b:   01 d8                   add    %ebx,%eax
   d:   93                      xchg   %eax,%ebx
   e:   0f bd c8                bsr    %eax,%ecx
  11:   41                      inc    %ecx
  12:   d3 e2                   shl    %cl,%edx
  14:   01 c2                   add    %eax,%edx
  16:   4f                      dec    %edi
  17:   75 f2                   jne    b <fib>
  19:   c3                      ret

```
> 2 votes

# Answer
# J, 36 Bytes

```
3 :'#.;<@#:"0]2}.(,{:+_2&{)^:y _1 1'

```

### Explanation:

```
3 :'#.;<@#:"0]2}.(,{:+_2&{)^:y _1 1' | Explicit function
                 (,{:+_2&{)^:y _1 1  | Make n fibonacci numbers, with _1 1 leading
              2}.                    | Drop the _1 1
       <@#:"0]                       | Convert each item to binary and box
      ;                              | Unbox and join
    #.                               | Convert back from binary

```
> 2 votes

# Answer
# Haskell, 89 76 75 bytes

```
f=0:scanl(+)1f
foldr1(\x y->y+x*2*2^floor(logBase 2.read.show$y)).(`take`f)

```

Ungolfed version:

```
import Data.Bits

fib = 0:scanl (+) 1 fib

catInt :: Integer -> Integer -> Integer
catInt x y = x' + y where
    position = floor $ succ $ logBase 2 $ realToFrac y
    x' = shift x position

answer :: Integer -> Integer
answer n = foldr1 catInt fib' where
    fib' = take n fib

```
> 2 votes

# Answer
# APL (Dyalog), ~~26~~ 22 bytes

*4 bytes saved thanks to @H.PWiz*

```
{2⊥∊2∘⊥⍣¯1¨1∧+∘÷\~⍵↑1}

```

Try it online!
> 2 votes

# Answer
# Pari/GP, 59 bytes

```
n->fromdigits(concat([binary(fibonacci(i))|i<-[0..n-1]]),2)

```

Try it online!
> 1 votes

# Answer
# APL+WIN, 55 bytes

Prompts for screen input of integer.

```
v←b←0 1⋄⍎∊(⎕-2)⍴⊂'v←v,c←+/¯2↑v⋄b←b,((1+⌊2⍟c)⍴2)⊤c⋄'⋄2⊥b

```

APL+WIN's maximum integer precision is 17 and integer limit is of the order of 10E300 therefore the maximum input number is 55 and the result is: 1.2492739026634838E300
> 1 votes

# Answer
# Python 3, 94 bytes

```
f=lambda n,a=[0,1]:n>len(a)and f(n,a+[sum(a[-2:])])or int(''.join(bin(v)[2:]for v in a[:n]),2)

```

**Try it online!**
> 1 votes

# Answer
# Jelly, 6 bytes

```
ḶÆḞBFḄ

```

Try it online!

owered range -\> *n*th `ÆḞ`ibonacci number -\> from dec to `B`inary -\> `F`latten -\> from inary to dec
> 1 votes

# Answer
# MATL, 21 bytes

```
0li:"yy+]xx&h"@B]&hXB

```

Try it online!

### Explanation

```
0l        % Push 0, then 1 (initial terms of the Fibonacci sequence)
i:"       % Do n times, where n is the input
  yy+     %   Duplicate top two numbers and push their sum
  ]       % End
xx        % Delete the last two results. The stack now contains the
          % first n Fibonacci numbers, starting at 0
&h        % Concatenate all numbers into a row vector
"         % For each
  @       %   Push current number
  B       %   Convert to binary. Gives a vector of 0 and 1
]         % End
&h        % Concatenate all vectors into a row vector
XB        % Convert from binary to decimal. Implicitly display

```
> 1 votes

# Answer
# Jotlin, 59 bytes

```
g(l(0,1)){l(a.sum(),a[0])}.take(this).j(""){a[0].s(2)}.i(2)

```

## Test Program

```
data class Test(val input: Int, val output: Long)

val tests = listOf(
    Test(1, 0),
    Test(2, 1),
    Test(3, 3),
    Test(4, 14),
    Test(5, 59),
    Test(6, 477),
    Test(7, 7640),
    Test(8, 122253),
    Test(9, 3912117),
    Test(10, 250375522)
)
fun Int.r() = g(l(0,1)){l(a.sum(),a[0])}.take(this).j(""){a[0].s(2)}.i(2)

fun main(args: Array<String>) {
    for (r in tests) {
        println("${r.input.r()} vs ${r.output}")
    }
}

```

It supports up to 10, changing `.i(2)` for `.toLong(2)` would support up to 14 if needed
> 1 votes

# Answer
# , 25 bytes

```
2(#.;)<@#:@(1#.<:!|.)\@i.

```

Try it online!

## Explanation

```
2(#.;)<@#:@(1#.<:!|.)\@i.  Input: n
                       i.  Range [0, n)
                     \@    For each prefix
                  |.         Reverse
                 !           Binomial coefficient (vectorized)
               <:            Decrement
            1#.              Sum
        #:                   Convert to binary
      <                      Box
    ;                        Link. Join the contents in each box
2 #.                         Convert to decimal from base 2

```
> 1 votes

# Answer
# Python 3, 86 bytes

```
def f(N):
 a,b,l=0,1,''
 for _ in range(N):l+=format(a,'b');a,b=b,a+b
 return int(l,2)

```

Try it online!
> 1 votes

# Answer
# Add++, 113 bytes

```
D,f,@@@@*,V$2D+G1+dAppp=0$Qp{f}p
D,k,@,¿1=,1,bM¿
D,g,@,¿1_,1_001${f},1¿{k}
D,w,@,BBbR
D,l,@,ßR€gp€w@0b]@¦+VcG2$Bb

```

Try it online!
> 1 votes

# Answer
## PHP, 124 Bytes

Try it online!

So I was looking for a way to output fibonacci numbers using the series, until I found this. It turns out you can calculate the fibonacci series via rounding, so I tried the challenge with a recursive function.

I found the approach of "rounding" really interesting, also a professor showed me this a while ago.

**Code**

```
function f($n,$i=0,$b=''){ if($n>$i){$b.=
decbin(round(pow((sqrt(5)+1)/2,$i)/sqrt(5)));f($n,$i+1,$b);}else{echo bindec($b);}}

```

**Explanation**

```
function f($n,$i=0,$b=''){           #the function starts with $i=0, our nth-fib number
if($n>$i){                           #it stops once $n (the input) = the nth-fib
    $b.=decbin(                      #decbin returns an integer as bin, concatenates
        round(pow((sqrt(5)+1)/2,$i)/sqrt(5))
                                       #the formula, basically roundign the expression
        );                           #it returns the (in this case) $i-th fib-number
    f($n,$i+1,$b);                   #function is called again for the next index
}else{                               #and the current string for fibonacci

    echo bindec($b);                 #"echo" the result, bindec returns the base 10
                                     #value of a base 2 number
}
}

```

Also check this stackoverflow post the best answer refers to the same article on Wikipedia.
> 1 votes

# Answer
# Stax, 9 bytes

```
ü1∞╓♪εw≤+

```

Run and debug it at staxlang.xyz!

## Unpacked (10 bytes) and explanation:

```
vr{|5|Bm|B
v             Decrement integer from input. Stax's Fibonacci sequence starts with 1 :(
 r            Integer range [0..n).
  {    m      Map a block over each value in an array.
   |5           Push nth Fibonacci number.
     |B         Convert to binary.
        |B    Implicit concatenate. Convert from binary. Implicit print.

```
> 1 votes

# Answer
# Julia 0.6, 65 bytes

```
f(n)=n<2?n:f(n-1)+f(n-2)
n->parse(BigInt,prod(bin.(f.(0:n-1))),2)

```

Try it online!
> 1 votes

# Answer
# Factor \+ `project-euler.025`, 37 bytes

```
[ iota [ fib >bin ] map-concat bin> ]

```

Try it online!
> 1 votes

# Answer
# Vyxal, 44 bits1, 5.5 bytes

```
ʁ∆FbfB

```

Try it Online!

## Explained

```
ʁ∆FbfB
ʁ      # range [0, input)
 ∆F    # 0-indexed fibonacci number of each
   bf  # convert each to binary and flatten the list
     B # convert that from binary

```
> 1 votes

# Answer
# Ruby, 61 bytes

```
->n,a=0,b=1,s=""{s+="%b"%a;a,b=b,a+b;(n-=1)>0?redo:s.to_i(2)}

```

Try it online!
> 0 votes

# Answer
# , ~~244~~ ~~180~~ 179 bytes

```
i=ifelse;g=function(n)i(n<3,1,g(n-1)+g(n-2))
a=scan(,"");i(a==1,0,sum(2^(which(rev(unlist(sapply(g(2:a-1),function(x)(y=rev(as.numeric(intToBits(x))))[which(!!y)[1]:32]))>0))-1)))

```

Try it online!

Saved some bytes by concatenating numeric vectors, not strings. Bloody special case for 0!
> 0 votes

# Answer
# Python 2, 88 bytes

```
def f(n):
 a,b,r=0,1,"0"
 for _ in range(n-1):a,b=b,a+b;r+=bin(a)[2:]
 print int(r,2)

```
> 0 votes

# Answer
# Python 3, 74 bytes

```
w='';a,b=0,1
exec('w+=bin(a)[2:];a,b=b,a+b;'*int(input()))
print(int(w,2))

```

Try it online!

Ungolfed:

```
w = ''
a, b = 0, 1
for _ in ' '*int(input()):  # for 0 to input:
    w += bin(a)[2:]         # append next fib. number as binary
    a, b = b, a + b         #     without leading 0b
print(int(w,2))             # convert whole binary number to decimal int

```
> 0 votes

# Answer
# Julia 0.6, 60 bytes

```
f(n,a=0,b=1,r=big(0))=n<1?r:f(n-1,b,a+b,r<<length(bin(a))|a)

```

Inspired by Dennis's bit fiddling python answer.

Try it online!
> 0 votes

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

Non-recursive solution. (Doesn't beat the recursive one)

```
n=>"0b"+[...Array(n)].map(c=>(c=a,a=b,b+=c,c).toString(2),a=0,b=1).join``-0

```

Try it online!
> 0 votes

# Answer
# Thunno 2, 6 bytes

```
LÆFḃJḂ

```

Port of Jonathan Allan's Jelly answer.

#### Explanation

```
LÆFḃJḂ  # Implicit input                              Input: 4
L       # Lowered range: push [0..input)              Stack: [0, 1, 2, 3]
 ÆF     # nth Fibonacci number (vectorises)           Stack: [0, 1, 1, 2]
   ḃ    # Convert to a binary string (vectorises)     Stack: ["0", "1", "1", "10"]
    J   # Join into a single string                   Stack: "01110"
     Ḃ  # Convert from binary                         Stack: 14
        # Implicit output                            Output: 14

```

#### Screenshot
> 0 votes

---
Tags: code-golf, binary, fibonacci
---