# Question
Title: Inverting string-based binary number in one line in Python
I want to read two strings on separate lines, each string the same length and containing only 0's and 1's, and determine if the first is the one's complement of the second. How succinctly can this be done in Python3? (Sorry to specify the language, but this is for my son who's studying Python)

A list comprehension seems to work but is quite ugly.

```
if ['0' if x=='1' else '1' for x in input()] == list(input()): print('yep')

```

Is there a slicker/shorter way to do this?

# Answer
> 11 votes
# Python 3,  ~~51 44 43~~  41 bytes

-7 thanks to loopy walt's suggestion to use `*open`.
-1 thanks to xnor's suggestion to replace `any(...)` with `1in ...`
-2 thanks to dingledooper's suggestion of using `str.find` instead of `str.__eq__`

```
0in map(str.find,*open(0))or print('yep')

```

**Try it online!**

This is a full program that takes input from stdin until an EOF (which we assume the user provides at the end of the second line) with `open(0)` and `map`s across the two strings by splatting (`*`), calling `str.find` on each pair of characters in turn. If `0` is `in` the result (i.e. the characters are equal and so the index of the first in the second is `0` rather than `-1` for "not found") then the right-hand clause of the `or` is not evaluated, and so we don't `print`.

---

My previous version, with xnor's and dingledooper's suggestions, at \\$48\\$, is interactive without the EOF faff:

```
0in map(str.find,input(),input())or print('yep')

```

---

You *could* save one more byte by printing to stderr instead of stdout by exiting the program early using `exit` in place of `print`.

---

A note to your son - this is not how I'd want someone in my team at work to write code :) - readability counts, a lot.

# Answer
> 4 votes
# Python3, 62 bytes

Since the bits at the similar position need to be set in one of the inputs and unset in the other, their bitwise XOR must have all bits set.

```
x=input()
int(x,2)^~-(1<<len(x))^int(input(),2)or print("yep")

```

Try it online!

*-5 bytes thanks to Arnauld*

Updated from my previous answer where I incorrectly assumed that checking bitwise AND = 0 was a sufficient condition.

---
Tags: code-golf, tips, python, bitwise
---


title: 16-bit binary grid

text:
# Question
Title: 16-bit binary grid
Given any unsigned 16 bit integer, convert its *decimal form* (i.e., base-10) number into a 4x4 ASCII grid of its bits, with the most-significant bit (MSB) at the top left, least-significant bit (LSB) at bottom right, read across and then down (like English text).

## Examples

### Input: 4242

```
+---+---+---+---+
|   |   |   | # |
+---+---+---+---+
|   |   |   |   |
+---+---+---+---+
| # |   |   | # |
+---+---+---+---+
|   |   | # |   |
+---+---+---+---+

```

### Input: 33825

```
+---+---+---+---+
| # |   |   |   |
+---+---+---+---+
|   | # |   |   |
+---+---+---+---+
|   |   | # |   |
+---+---+---+---+
|   |   |   | # |
+---+---+---+---+

```

## Specific Requirements

1. Input *must* be in decimal (base-10), however you may convert to binary any way you wish (including using language built-ins, if available).
2. Output table format must match *exactly*. This means you must use the specific ASCII characters (`-`, `+`, and `|`) for the table grid lines as shown, each cell's interior is 3 characters, and *true* bits are represented by `#` while *false* is represented by a space ().
3. Leading or trailing whitespace is *not permitted.* Final newline is *required*.
4. Bit order must match the examples as described.

## Allowances

1. Input must be a base-10 number on the command line, standard input, or user input, but *must not* be hard-coded into your source code.

May the clearest shortest code win! :-)

# Answer
# J, 26 bytes

```
('   ';' # '){~4 4$_16{.#:

```

An anonymous verb. Thankfully, J is very good at drawing boxes. Let's try it out:

```
   f =. ('   ';' # '){~4 4$_16{.#:
   f 4242
+---+---+---+---+
|   |   |   | # |
+---+---+---+---+
|   |   |   |   |
+---+---+---+---+
| # |   |   | # |
+---+---+---+---+
|   |   | # |   |
+---+---+---+---+

```

As some commenters have mentioned, the way J draws boxes is system-dependent: on some platforms, this code will work under the default settings, but on others, the boxes will be drawn using Unicode line drawing characters. (The commands `9!:6` and `9!:7` allow you to query and set the characters to draw boxed values with, respectively.)
> 22 votes

# Answer
# JavaScript (ES6), 102

... or 96 using `return` instead of `console.log`.

Test running the snippet below in an EcmaScript 6 compliant browser.

```
f=n=>{for(o=h=`
+---+---+---+---+
`,z=16;z--;n/=2)o=(z&3?'':h+'|')+` ${' #'[n&1]} |`+o;console.log(o)}

// TEST
console.log=x=>O.innerHTML=x+O.innerHTML

function test(n) { f(n); console.log(n); }
```

```
<input id=I value=4680><button onclick='test(+I.value)'>-></button>
<pre id=O></pre>
```
> 14 votes

# Answer
# Befunge-93, 196 ~~218~~ bytes

```
&00p12*v>>4>"---+",v v <
v*:*:*:<   | :-1,,,< #
>:*2/10p^  >"+",25*,10g|
     > #v^#         $< @
 25*,^  >4" |",,v ,*<>
v>"#",00g10g-00p 10g
 |`-1g01g00     <>48^
v>" ",10g
>2/10p>"| ",,1-:#^_$>^

```

### To run the program...

1. Go to the online interpreter.
2. Paste this code in the big text box.
3. Click `Show`.
4. Input the desired number in the `Input` box.
5. Click `Run`. (Or change `Slow` to something like 5 milliseconds and then click `Show`.)
6. Ta-da!

Output for 4242:

```
+---+---+---+---+
|   |   |   | # |
+---+---+---+---+
|   |   |   |   |
+---+---+---+---+
| # |   |   | # |
+---+---+---+---+
|   |   | # |   |
+---+---+---+---+

```

Output for 33825:

```
+---+---+---+---+
| # |   |   |   |
+---+---+---+---+
|   | # |   |   |
+---+---+---+---+
|   |   | # |   |
+---+---+---+---+
|   |   |   | # |
+---+---+---+---+

```

## Explanation

Oh goodness, what have I got myself into? Well, here goes! (Irrelevant code is replaced with `.`s.)

### Part 1: Get input (store in 0,0) and calculate 32768 (store in 1,0).

```
&00p12*v>
v*:*:*:<
>:*2/10p^

```

### Part 2: Print out "+---+---+---+---".

```
>4>"---+",v
  | :-1,,,<

```

### Part 3: Print "+" and a newline and check to see if (1,0) is 0 (i.e. we're done). If so, terminate. Otherwise, continue.

```
 ........... v <
   | ....... #
   >"+",25*,10g|
v.#         $< @
>4" |",,v ...

```

### Part 4: Get binary digits of input, updating (0,0) and (1,0) as we go along. Print the right things. I take advantage of Befunge's wrap-around behavior.

```
 .....  >4" |",,v ,*<.
v>"#",00g10g-00p 10g
 |`-1g01g00     <>48^
v>" ",10g
>2/10p>"| ",,1-:#^_...

```

### Part 5: Print a newline and go back to the part that prints "+---+---+---+---+". Wrap-around trick is used.

```
     > #.^.         .. .
 25*,^  ......... ...>
................ ...
 .........      .....
........
.................._$>^

```

### Ta-da!
> 14 votes

# Answer
# Julia, ~~156~~ 143 bytes

```
n->(p=println;l="+"*"---+"^4;for i=1:4 p(l,"\n| ",join([j>"0"?"#":" "for j=reshape(split(lpad(bin(n),16,0),""),4,4)[:,i]]," | ")," |")end;p(l))

```

Ungolfed:

```
function f(n::Int)
    # Convert the input to binary, padded to 16 digits
    b = lpad(bin(n), 16, 0)

    # Split b into a 4x4 matrix
    m = reshape(split(b, ""), 4, 4)

    # Store the line separator for brevity
    l = "+" * "---+"^4

    # Print each column of the matrix as a row
    for i = 1:4
        println(l, "\n| ", join([j > "0" ? "#" : " " for j = m[:,i]], " | "), " |")
    end

    # Print the bottom of the table
    println(l)
end

```

Try it online
> 11 votes

# Answer
# Python 2, ~~157~~ ~~153~~ ~~151~~ 146 bytes

```
J=''.join;R='+---'*4;i=format(input(),'016b')
print J(R+'+\n|'+J(' '+('#'if int(l)else' ')+' |'for l in i[n*4:-~n*4])+'\n'for n in range(4)),R+'+'

```

Thanks to Morgan Thrapp for saving 4 bytes, and to Jonathan Frech for saving 5.

## Usage

```
$ python test.py
33825
+---+---+---+---+
| # |   |   |   |
+---+---+---+---+
|   | # |   |   |
+---+---+---+---+
|   |   | # |   |
+---+---+---+---+
|   |   |   | # |
+---+---+---+---+

```
> 11 votes

# Answer
# Ruby, ~~118~~ 114

```
b="%016b"%gets
l=?++"---+"*4
1.upto(16){|i|puts l if i%4==1
print"| #{b[i-1]==?0?' ':?#} "
puts ?|if i%4<1}
puts l

```

thanks for @w0lf for saving some characters.
> 9 votes

# Answer
# GNU sed + dc, 116

Score includes +1 for `-r` flags to `sed`:

```
s/.*/dc -e2o&p/e
:
s/^.{,15}$/0&/;t
s/./| & /g
s/.{16}/\n+---+---+---+---+\n&|/g
y/01/ #/
s/\n([-+]+)(.*)/\1\2\n\1/

```

Test output:

```
$ { echo 4242 ; echo 33825 ; } | sed -rf 16bitgrid.sed
+---+---+---+---+
|   |   |   | # |
+---+---+---+---+
|   |   |   |   |
+---+---+---+---+
| # |   |   | # |
+---+---+---+---+
|   |   | # |   |
+---+---+---+---+
+---+---+---+---+
| # |   |   |   |
+---+---+---+---+
|   | # |   |   |
+---+---+---+---+
|   |   | # |   |
+---+---+---+---+
|   |   |   | # |
+---+---+---+---+
$

```

---

Alternatively:

# Pure sed, 146

You might think it's cheating to use `sed`'s GNU extension to eval a `dc` command. In that case, we can do this a little differently, according to this meta-answer. Of course the question clearly states that input *must* be in base 10, but here I'm attempting to claim that we can override that for `sed` answers and use unary (base 1) instead.

```
:
s/11/</g
s/<([ #]*)$/< \1/
s/1/#/
y/</1/
t
:a
s/^.{,15}$/0&/;ta
s/./| & /g
s/.{16}/\n+---+---+---+---+\n&|/g
y/01/ #/
s/\n([-+]+)(.*)/\1\2\n\1/

```

### Test output

Using `printf` to generate the necessary unary string:

```
$ printf "%33825s" | tr ' ' 1 | sed -rf 16bitgrid.sed
+---+---+---+---+
| # |   |   |   |
+---+---+---+---+
|   | # |   |   |
+---+---+---+---+
|   |   | # |   |
+---+---+---+---+
|   |   |   | # |
+---+---+---+---+
$

```
> 9 votes

# Answer
# C++11, ~~193~~ ~~191~~ ~~190~~ ~~176~~ 172 bytes

My first solution on codegolf ever, so do not blame me.

```
#include<iostream>
int n,j,i=65536;int main(){std::cin>>n;for(;j<9;){for(int k:{0,0,0,0})if(j%2)printf("| %s",n&(i/=2)?"# ":"  ");else printf("+---");puts(j++%2?"|":"+");}}

```

Ungolfed

```
#include <iostream>
int n, i = 65536, j;

int main()
{
    std::cin >> n;

    for (; j < 9;)
    {
        for(int k:{0,0,0,0})
        {
            if (j % 2)
            {
                printf("| %s", n & (i /= 2) ? "# " : "  ");
            }
            else
            {
                printf("+---");
            }
        }
        puts(j++ % 2 ? "|" : "+");
    }
}

```

Previous version

```
#include <iostream>
using namespace std;

int n, i = 65536, j;
int main()
{
    cin >> n;

    for (; j < 9;)
    {
        for(int k:{0,0,0,0})
        {
            if (j % 2)
            {
                cout << "| " << (n & (i /= 2) ? "# " : "  ");
            }
            else
            {
                cout << "+---";
            }
        }
        cout << (j++ % 2 ? "|\n" : "+\n");
    }
}

```
> 6 votes

# Answer
# Pyth, 37 bytes

```
Jj*3\-*5\+JVc4_m@" #".>Qd16jd.i*5\|NJ

```

Try it online: Demonstration or Test Suite

### Explanation:

```
Jj*3\-*5\+J
  *3\-                       the string "---"
      *5\+                   the string "+++++"
 j                           join second by first string:
                                "+---+---+---+---+"
J                            save in J
          J                  print J

Vc4_m@" #".>Qd16jd.i*5\|NJ
    m         16             map each d in [0, 1, ..., 15] to:
          .>Qd                 input number Q shifted to the right by d
     @" #"                     and take the ^th char in " #" (modulo 2)
   _                         reverse this list of chars
 c4                          split into 4 groups
V                            for each group N in ^:
                    *5\|       the string "|||||"
                  .i    N      interleave ^ with N
                jd             join chars with spaces and print
                         J     print J

```
> 6 votes

# Answer
# CJam, ~~43~~ 41 bytes

```
'+5*'-3**N+ri2bG0e[4/{" #"f='|5*.\S*N2$}/

```

Definitely golfable, but it's a start I guess. Generates the top row, then for each 4 bits it creates an even row and copies the previous odd row.

Try it online.
> 5 votes

# Answer
# PowerShell, ~~203~~ ~~188~~ 182 Bytes

```
param($a)$l="+---+---+---+---+";$l;$b=([int64][convert]::ToString($a,2)).ToString(@(,"0"*16)-join'');@(1..16|%{if($b[$_-1]-eq'1'){"| # "}else{"|   "};if($_%4-eq0){"|`n$l`n"}})-join''

```

Edit - saved 15 bytes by changing the order that `|` are drawn, so we can dump the `.TrimEnd("|")` on the output and instead convert the for-loop into a subcode block that produces an array

Edit2 - saved another 6 bytes by eliminating need for saving into the `$o` variable and just outputting with `-join''` directly.

Ooooooooof.

Drawing in PowerShell is *hard*. Working with binary digits in PowerShell is *hard*.

Uses built-ins to `[convert]` the input integer to a string representation in binary, then re-cast back to an `[int64]` so we can re-call `.ToString()` in order to prepend/pad the appropriate number of zeroes. (Note that creating an array of strings and joining them `@(,"0"*16)-join''` is 1 character shorter than the literal string `"0000000000000000"`)

Then, take a simple for-loop `1..16|%{...}` checking each digit to build up our output array, then finally `-join''` that back together.

---

### Previous, 188

```
param($a)$l="+---+---+---+---+";$l;$b=([int64][convert]::ToString($a,2)).ToString(@(,"0"*16)-join'');$o=@(1..16|%{if($b[$_-1]-eq'1'){"| # "}else{"|   "};if($_%4-eq0){"|`n$l`n"}});$o-join''

```

---

### Previous-er, 203

```
param($a)$l="+---+---+---+---+`n|";$o=$l;$b=([int64][convert]::ToString($a,2)).ToString(@(,"0"*16)-join'');1..16|%{if($b[$_-1]-eq'1'){$o+=" # |"}else{$o+="   |"};if($_%4-eq0){$o+="`n$l"}};$o.TrimEnd('|')

```
> 4 votes

# Answer
# Python 2, ~~122~~ ~~121~~ 120 bytes

```
n=bin(4**8+input())[3:]
i=0
exec"print'| %s |'%' | '.join(' #'[x>'0']for x in n[:4])*i or'+---'*4+'+';n=n[4*i:];i^=1;"*9

```

-1 byte thanks to @xnor's neat `4**8+` trick. The main printing is done by looping 9 times, selecting the appropriate row for odd/even.
> 4 votes

# Answer
## Python 2, 94

```
n=input()
s=();exec"s=(' #'[n%2],)+s;n/=2;"*16
a='+---'*4+'+\n'
print(a+'| %s '*4+'|\n')*4%s+a

```

The idea is to take the pattern

```
+---+---+---+---+
| _ | _ | _ | _ |
+---+---+---+---+
| _ | _ | _ | _ |
+---+---+---+---+
| _ | _ | _ | _ |
+---+---+---+---+
| _ | _ | _ | _ |
+---+---+---+---+

```

except with `%s` in place of blanks and perform tuple substitution. The tuple looks like

```
('#', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#')

```

It is created by taking taking off digits from the input in binary and adding the corresponding symbol to the front of the tuple. An expression with explicit tuple gave equal length.

```
%tuple(' #'[c>'0']for c in bin(input()+4**8)[3:])

```

Thanks to Sp3000 for 2 bytes.
> 4 votes

# Answer
# Javascript (ES6), ~~216~~ 207 bytes

Defines an anonymous function.

```
i=>(","+("0".repeat(16)+i.toString(2)).slice(-16).split``.map((v,l,a)=>l%4<1?"| "+a.slice(l,l+4).map(v=>v?"#":" ").join` | `+" |":"").filter(v=>!!v).join`,`+",").replace(/,/g, `
+---+---+---+---+
`).slice(1)

```

Thanks to ETHproductions for tips!
> 3 votes

# Answer
# CJam, 62 bytes

```
"+---|   "4/{4*_c+N+}%4*_0=]sqi2bG0e[ee{~{_9*\4%5*-K+'#t0}&;}/

```

Try it online.
> 2 votes

# Answer
# Pyth, 50 bytes

```
j.i*5]<3*5"+---"ms.i*5\|dc4mj@" #"qd\1*2\ .[Z16.BQ

```

Explanation will have to wait until another time, I'm posting this on my phone!
> 2 votes

# Answer
# Ruby, 102

```
n=gets.to_i
print j="+---"*4+"+
"
19.downto(0){|i|print i%5>0?"| #{((n>>i*4/5)%2*3+32).chr} ":"|
"+j}

```

**Algorithm**

Print a horizontal divider

Loop 20 times (19..0)

If loop number does not divide by 5, convert into a number in the range 16..0 by multiplying by 4/5. Print a space (ascii 32) or `#` (ascii 32+3=35) preceded by `|`  and followed by a space.

If loop number divides by 5, print a terminating |, newline, and a horizontal divider identical to the first.
> 2 votes

# Answer
# Perl, 103 bytes

```
$_=(($l='+---'x4 .'+
').'| x 'x4 .'|
')x4 .$l;@n=(sprintf'%016b',<>)=~/./g;s/x/$n[$x++]?'#':$"/eg;print

```

Lots of string repetition to make a grid of `x`s, convert the input to binary and then `s///` the `x`s to `#` or `$"` () depending on the flag at the specified position (`$x`).
> 2 votes

# Answer
# PHP, 159 bytes

`bingrid16.php`:

```
<?$r=10;while(--$r){if($r%2){echo str_repeat('+---',4).'+';}else{$c=9;echo'|';while(--$c){echo' '.($c%2?'|':($argv[1]&pow(2,$r*2+$c/2-5)?'#':' '));}}echo"\n";}

```

Usage:

```
php bingrid16.php 4242

```

Nothing fancy, just brute-forced the rendering.

I tried another angle using arrays instead of loops, but it was longer at 224 bytes:

```
<?=implode(array_map(function($r)use($argv){return($r%2?str_repeat('+---',4).'+':'|'.implode(array_map(function($c)use($r,$argv){return' '.($c%2?'|':($argv[1]&pow(2,$r*2+$c/2-5)?'#':' '));},range(8,1))))."\n";},range(9,1)));

```
> 2 votes

# Answer
# Perl 5, ~~85~~ 84 bytes

~~84~~ 83 bytes of code + `-p` flag

*-1 byte after Dom reminded me to use a newline*

```
say$\='+'."---+"x4,"
| ",map y/01/ #/r.' | ',/./g for(sprintf"%016b",$_)=~/..../g}{

```

Try it online!
> 2 votes

# Answer
# Vyxal `j`, 47 bytes

```
b:L16-(0p)4ẇƛƛ‛ #$i`| % `$%;ṅ\|+;\+:3-4*pw5ẋf$Y

```

Try it Online! A big mess
> 2 votes

# Answer
# Japt `-R`, ~~40~~ 36 bytes

This'll need another pass once I'm properly caffeinated!

```
5Æ17î-³i+ÃíUs'#iS)ùG ®û3 i|ÃòG)cf ú|

```

Try it

```
5Æ17î-³i+ÃíUs'#iS)ùG ®û3 i|ÃòG)cf ú|     :Implicit input of integer U
5Æ                                       :Map the range [0,5)
  17î                                    :  Repeat the following to length 17
     -³                                  :    "-" repeated 3 times
       i+                                :    Prepend a "+"
         Ã                               :End map
          í                              :Interleave with
           Us                            :  U converted to a string in the following base
             '#i                         :    "#" prepended with
                S                        :    A space
                 )                       :  End base conversion
                  ù                      :  Left pad with spaces to length
                   G                     :    16
                     ®                   :  Map each character
                      û3                 :    Centre pad with spaces to length 3
                         i|              :    Prepend a "|"
                           Ã             :  End map
                            òG           :  Partitions of length 16
                              )          :End interleave
                               c         :Flatten
                                f        :Filter out falsey elements (If the second array being interleaved is shorter than the first, it's padded with null)
                                  ú|     :Left pad each with "|" to the length of the longest
                                         :Implicit output joined with newlines

```
> 2 votes

# Answer
# Vyxal, 31 bytes

```
\+3-4*\|?b16∆Z\#*2↳ʁ+4ẇṠv"fǏvǏ⁋

```

Try it Online!

```
        ?                       # Input
         b                      # To binary
          16∆Z                  # Pad to length 16 with 0s
              \#*               # That many #s, for each bit
                 2↳ʁ            # Pad to length 2 with spaces and mirror
      \|            +           # Prepend | to each
                     4ẇṠ        # Divide into rows and stringify each
                        v"f     # Interleave with...
\+3-                            # "+---"
    4*                          # Repeated four times
                           Ǐ    # Append the first line
                            vǏ  # For each line, append the firstt character
                              ⁋ # Join the result by newlines

```
> 2 votes

# Answer
# c99 263 bytes

golfed:

```
main(int argc,char **argv){short i=atoi(argv[argc-1]);char *t="| # ", *f="|   ",*a[16],**p=a,*b="+---+---+---+---+\r\n";while(p<a+16){if((i|0x8000)==i)(*(p++))=t;else(*(p++))=f;i<<=1;}for(p=a;p<a+16;p+=4)printf("%s%s%s%s%s|\n",b,*p,p[1],p[2],p[3]);printf("%s",b);}

```

ungolfed:

```
main(int argc, char **argv)
{
    short i=atoi(argv[argc -1]);
    char *t ="| # ", *f="|   ",*a[16],**p=a,*b="+---+---+---+---+\r\n";

    while (p<a+16)
    {
        if((i|32768)==i)
            (*(p++))=t;
        else
            (*(p++))=f;

        i<<=1;
    }

    for (p=a;p<a+16;p+=4)
        printf("%s%s%s%s%s|\n",b,*p,p[1],p[2],p[3]);
    printf("%s",b);
}

```

I just liked to present a bit shifting variant and felt this is the first time its appropriate (even its costing me some bytes, but C can't this challange in bytes even with a chance so I don't care) to use the argc/argv
> 1 votes

# Answer
## C# 227 Bytes

Golfed:

```
class B{public static string G(short v){string s="",b=System.Convert.ToString(v,2).PadLeft(16,'0');for(int i=9;i>0;){s+=i--%2!=0?"+---+---+---+---+\n":"| "+b[i*2+1]+" | "+b[i*2]+" | "+b[i*2-1]+" | "+b[i*2-2]+" |\n";}return s;}}

```

Indention:

```
class B
{
    public static string G(short v)
    {
        string s="",b=System.Convert.ToString(v, 2).PadLeft(16,'0');
        for(int i=9;i>0;)
            s+=i--%2!=0?"+---+---+---+---+\n":"| "+b[i*2+1]+" | "+b[i*2]+" | "+b[i*2-1]+" | "+b[i*2-2]+" |\n";
        return s;
    }
}

```

First time I'm trying something like this, tips would be welcome!
> 1 votes

# Answer
# Ruby, 95

Nod to Mhmd for a concise String conversion, but I wanted to try using string methods instead of number methods.

```
->i{puts g='+---'*4+?+;("%016b"%i).scan(/.{4}/){puts$&.gsub(/./){"| #{$&<?1?' ':?#} "}+"|
"+g}}

```
> 1 votes

# Answer
# Ruby, 93

A slightly shorter version using only numeric operations.

```
->i{n=g='+---'*4+"+
";15.downto(0){|m|n+="| #{[' ',?#][1&i>>m]} "
n+="|
"+g if m%4<1}
puts n}

```
> 1 votes

# Answer
# Python 3, ~~145~~ 144 Bytes

Inline:

```
a="|";b="+"+"---+"*4+"\n";r=0,1,2,3;(lambda x:print(b+b.join(a+a.join(" %s "%'# '[x&2**(i+j*4)<1]for i in r)+a+"\n"for j in r)+b))(int(input()))

```

With newlines:

```
a="|"
b="+"+"---+"*4+"\n"
r=0,1,2,3
lambda x:print(b+b.join(a+a.join(" %s "%'# '[x&2**(i+j*4)<1]for i in r)+a+"\n"for j in r)+b)
x(int(input()))

```

Edit: Tanks @manatwork for saving 1 byte
> 1 votes

# Answer
# x86-16 machine code, IBM PC DOS, 80 bytes

Binary:

```
00000000: b805 09ba 2801 cd21 fec8 741b be3e 01b1  ....(..!..t..>..
00000010: 04d1 e3c6 0420 7303 c604 2383 c604 e2f1  ..... s...#.....
00000020: ba3c 01cd 21eb dcc3 2b2d 2d2d 2b2d 2d2d  .<..!...+---+---
00000030: 2b2d 2d2d 2b2d 2d2d 2b0d 0a24 7c20 2020  +---+---+..$|
00000040: 7c20 2020 7c20 2020 7c20 2020 7c0d 0a24  |   |   |   |..$

```

Listing:

```
B8 0905         MOV  AX, 0905H              ; AH = DOS write string, AL = row counter
            ROW_LOOP:
BA 0128         MOV  DX, OFFSET SEP         ; show separator row
CD 21           INT  21H                    ; write to console
FE C8           DEC  AL                     ; displayed 5 separators?
74 1B           JZ   EXIT                   ; if so, exit
BE 013E         MOV  SI, OFFSET ROW+2       ; start SI at location of first bit in row
B1 04           MOV  CL, 4                  ; loop count 4
            BIT_LOOP:
D1 E3           SHL  BX, 1                  ; shift MSb into CF
C6 04 20        MOV  BYTE PTR[SI], ' '      ; reset to space char
73 03           JNC  BIT_DONE               ; if not CF, leave as a space
C6 04 23        MOV  BYTE PTR[SI], '#'      ; otherwise change to a #
            BIT_DONE:
83 C6 04        ADD  SI, 4                  ; increment index 4 bytes
E2 F1           LOOP BIT_LOOP               ; keep looping through bits
BA 013C         MOV  DX, OFFSET ROW         ; show bit column row
CD 21           INT  21H                    ; write to console
EB DC           JMP  ROW_LOOP               ; keep looping
            EXIT:
C3              RET                         ; return to caller
            SEP DB  '+---+---+---+---+',0DH,0AH,'$'
            ROW DB  '|   |   |   |   |',0DH,0AH,'$'

```

Callable function, input in `BX` output to `STDOUT`.

Example test program:
> 1 votes

# Answer
# Kotlin, 192 bytes

```
{val v=it.toString(2).padStart(16,'0')
fun p(){(0..3).map{print("+---")}
println("+")}
(0..3).map{p()
v.subSequence(it*4,(it+1)*4).map{print("| ${if(it>'0')'#' else ' '} ")}
println("|")}
p()}

```

## Beautified

```
{
    val v = it.toString(2).padStart(16, '0')
    fun p() {
        (0..3).map { print("+---") }
        println("+")
    }
    (0..3).map {
        p()
        v.subSequence(it *4, (it +1) *4).map {print("| ${if (it > '0') '#' else ' '} ")}
        println("|")
    }
    p()
}

```

## Test

```
var b:(Int) -> Unit =
{val v=it.toString(2).padStart(16,'0')
fun p(){(0..3).map{print("+---")}
println("+")}
(0..3).map{p()
v.subSequence(it*4,(it+1)*4).map{print("| ${if(it>'0')'#' else ' '} ")}
println("|")}
p()}

fun main(args: Array<String>) {
    b(255)
}

```
> 0 votes

# Answer
# 05AB1E, 45 bytes

```
bDg16αúS4ôεεð.ø}õ.ø'|ý}õ.ø…+--3F.∞}¶.øý10„# ‡

```

Try it online!
> 0 votes

# Answer
# Pip, 85 bytes

```
a:TBa
(("   "X16-#a).aR0"   "R1" # "<>3JW'|<>16J'|<>17JWn."+---+---+---+---+".n)@<-20

```

Does a straightforward bunch of splits and replacement to get the final grid.

Try it online!
> 0 votes

---
Tags: code-golf, ascii-art, base-conversion, binary
---


# Question
Title: Count spelling errors in text; minimize the number of spelling errors in your code
Write a program or function that takes two inputs:

1. A text message
2. The dictionary of English language, as it appears in this Github file (containing about 60000 words)

and outputs the number of spelling errors in the message (see below for definition and test cases).

You can receive the dictionary as a parameter to your function, as a pre-defined file that your program expects to find, as hard-coded data in your code, or in any other sensible manner.

---

Your code should itself look like a text message, with a minimal number of spelling errors. So, you will calculate the **score** of your code by feeding it to itself as input.

The winner is code that has the lowest score (minimal possible score is 0). If there are several answers with the same score, the winner is decided by code size (in characters). If two answers are still tied, the winner is the earlier one.

---

If required, you can assume the input message to be ASCII (bytes 32...126) with newlines encoded in a conventional manner (1 byte "10" or 2 bytes "13 10"), and non-empty. However, if your code has non-ASCII characters, it should also support non-ASCII input (so it can calculate its own score).

Characters are subdivided into the following classes:

* *Letters* a...z and A...Z
* *Whitespace* (defined here as either the space character or the newline character)
* *Punctuation* `.` `,` `;` `:` `!` `?`
    + *Sentence-ending* `.` `!` `?`
* *Garbage* (all the rest)

A *word* is defined as a sequence of letters, which is maximal (i.e. neither preceded nor followed by a letter).

A *sentence* is defined as a maximal sequence of characters that are not sentence-ending.

A character is a *spelling error* if it violates any of the spelling rules:

1. A letter must belong to a dictionary word (or, in other words: each word of length N that doesn't appear in the dictionary counts as N spelling errors)
2. The first character in a sentence, ignoring any initial whitespace characters, must be an uppercase letter
3. All letters must be lowercase, except those specified by the previous rule
4. A punctuation character is only allowed after a letter or garbage
5. A newline character is only allowed after a sentence-ending character
6. Whitespace characters are not allowed in the beginning of the message and after whitespace characters
7. There should be no garbage (or, in other words: each garbage character counts is a spelling error)

In addition, the last sentence must be either empty or consist of exactly one newline character (i.e. the message should end with a sentence-ending character and an optional newline - let's call it rule 8).

Test cases (below each character is a rule that it violates; after `=>` is the required answer):

```
Here is my 1st test case!!
           711           4                => 4

main(){puts("Hello World!");}
2   777    883     3     77 78            => 12

  This message starts with two spaces
66                                   8    => 3

What ? No apostrophe's??
     4              71 4                  => 4

  Extra   whitespace   is   BAD!
66      661111111111 66   66333           => 21

Several
lines?
Must be used only to separate sentences.
                                          => 1 (first linebreak is en error: rule 5)

"Come here," he said.
73         7                              => 3 (sentence starts with '"', not 'C')

```

# Answer
> 6 votes
# Perl 6, 134 spelling errors

```
my token punctuation {<[.,;:!?]>}
my \text = slurp; my \mistakes=[]; for split /\.|\!|\?/, text { for .trim.match: :g, /<:letter>+/ -> \word { (append mistakes, .comb when none words slurp pi given lc word) or (push mistakes, $_ if ((.from or word.from) xor m/<[a..z]>/) for word.match: :g, /./) }}
append mistakes, comb / <after \s | <punctuation>> <punctuation> | <!before <punctuation> | <:letter> | \s> . | <!after \.|\!|\?> \n | [<before ^> | <after \s>] \s /, text; say mistakes.Numeric

```

With extra whitespace for readability:

```
my token punctuation {<[.,;:!?]>}
my \text = slurp;
my \mistakes=[];
for split /\.|\!|\?/, text {
    for .trim.match: :g, /<:letter>+/ -> \word {
        (append mistakes, .comb when none words slurp pi given lc word)
        or
        (push mistakes, $_ if ((.from or word.from) xor m/<[a..z]>/) for word.match: :g, /./)
    }
}
append mistakes, comb /
  <after \s | <punctuation>> <punctuation>
  | <!before <punctuation> | <:letter> | \s> .
  | <!after \.|\!|\?> \n
  | [<before ^> | <after \s>] \s
/, text;
say mistakes.Numeric

```

Notes:

* Expects the dictionary in a file called `3.14159265358979` in the current working directory.
* The only inspired part is the line
`append mistakes, .comb when none words slurp pi given lc word`,
the rest is pretty bad. But maybe it can at least serve as a baseline for better solutions... :)

# Answer
> 2 votes
# Python 3, 287 spelling errors

```
    import re
    def function(message):file = open("dictionary", "r");dictionary = file.read().split();words = re.findall("[a-zA-Z]+", message);sentences = re.findall("[^.!?]+", message);return sum(len(word) if word.lower() not in dictionary else 0 for word in words)+sum(1 if sentence.strip()[0].isalpha() and not sentence.strip()[0].isupper() else 0 for sentence in sentences)+sum(sum(1 if character.isupper() else 0 for character in sentence.strip()[1:]) for sentence in sentences)+len(re.findall("[\s.,;:!?][.,;:!?]", message))+len(re.findall("[^.!?]\n", message))+len(re.findall("^\s", message))+len(re.findall("\s\s", message))+len(re.findall("[^a-zA-Z\s.,;:!?]", message))+int(not sentences[-1] and count(sentences[-1], '\n') != 1)

```

Try it online!

Definitely not the best, but I gave it a solid shot, I think! Here it is in an actually readable format. Assumes there is a file called "dictionary" (no extension) in the cwd.

```

import re
def function(message):
    file = open("dictionary", "r")
    dictionary = file.read().split()
    words = re.findall("[a-zA-Z]+", message)
    sentences = re.findall("[^.!?]+", message)
    errors = 0
    errors += sum(len(word) if word.lower() not in dictionary else 0 for word in words)
    errors += sum(1 if sentence.strip()[0].isalpha() and not sentence.strip()[0].isupper() else 0 for sentence in sentences)
    errors += sum(sum(1 if character.isupper() else 0 for character in sentence.strip()[1:]) for sentence in sentences)
    errors += len(re.findall("[\s.,;:!?][.,;:!?]", message))
    errors += len(re.findall("[^.!?]\n", message))
    errors += len(re.findall("^\s", message))
    errors += len(re.findall("\s\s", message))
    errors += len(re.findall("[^a-zA-Z\s.,;:!?]", message))
    errors += int(not sentences[-1] and count(sentences[-1], '\n') != 1)
    return errors

```

# Answer
> 1 votes
# Python, 32 spelling errors

```
import re;be = open('be').read().split();exec(''.join(chr(be.index(it)) for it in 'aboriginal abominable aborting aborting abolishing abominate abominable abbreviated abetting abbreviated abominates aboriginals aborigines abortionist abortion abdicating abdication abets abortions aborigine aborted abolitionists aborting abbreviated abetting abbreviated aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolishing abdominal abound abhorrent abdominal abnormally abodes abdomen abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abets aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting abbreviated abetting abbreviated aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolish abduct abbreviates abhorred abodes abdomen abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abets aborigines aborted abominates aboriginals abortion abdicating aborting abortionist aboriginal abdicating abominations abominable aboriginals abdicating abortions aborigine aborted abolitionists abdication abbreviated abominates abominably abbreviated abortions aborigine aborted abolitionists abduct abominations aborigine abortions abominable aborted abdicating abdication abbreviated aboriginals aborigine abortion abbreviated abominates aboriginals abbreviated abolition abominable abbreviated abominable abominations aborting abominable abbreviated abducting abbreviated abominably aborigine aborted abbreviated abortions aborigine aborted abolitionists abbreviated abominates aboriginals abbreviated abortions aborigine aborted abolitionists aborting abdication abdomen aborting abortionist aboriginal abdicating abduction abbreviated abominates abominably abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abduct aborting abortion aborted abominates aborigines abdicating abdication aboard abducting abodes abduct abominates aborting abolishing abominations aborigines abominated abolishing abdicating abdication abbreviated abolishing aboriginals abolitionists abbreviated aboriginals aborigine abortion abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abduct aborting abortion aborted abominates aborigines abdicating abdication aboard abducting abodes abduct abominates aborting abortionist aborigines aborigines abominable aborted abdicating abdication abbreviated abominable abominations aborting abominable abbreviated abducting abbreviated abominably aborigine aborted abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abbreviated abominates aboriginals abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting abdication abdomen aborting abortionist aboriginal abdicating aborting abortionist aboriginal abdicating abduction abbreviated abominates abominably abbreviated abolitionist abominated abolishing aborted abolishing abolitionist abortion abominable aborted abduct abominates aborting abortionist aborigines aborigines abominable aborted abdicating abdication abbreviated abominable abominations aborting abominable abbreviated abducting abbreviated abominably aborigine aborted abbreviated abolitionist abominated abolishing aborted abolishing abolitionist abortion abominable aborted abbreviated abominates aboriginals abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abduct aborting abortion aborted abominates aborigines abdicating abdication aboard abduction abet abodes abdication abbreviated abominably aborigine aborted abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable abbreviated abominates aboriginals abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abode aborting abduct abdomens abets abet abbreviates abhorred abodes aboard abduct abdomens abets abet abbreviates abhorred abodes abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolish abduct abbreviates abhorred abodes abode aboriginals abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating abolish abode aborting abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating abode aborting abode aborting abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominations abominable aboriginals abdicating aborted abominable abduct abominably abominates aboriginals abolitionists abolishing abominations abominations abdicating abbreviating aboard abolish abolishing abdominal abound abhorrent abdominal abnormally abode aborting abduct abdomens abets abet abbreviates abhorred abodes abbreviating abdomens abbreviated aboriginal abominable aborting aborting abolishing abominate abominable abdication abdication abdomen abominates aboriginals abortion abdicating aboriginals aborigine abortion abbreviated aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting aboard abdominal abduction abodes abbreviated abolishing aboriginals abolitionists abbreviated abolitionist aborigine abortionist aboriginals abortion abdicating aborting abominable aboriginals abortion abominable aboriginals abolitionist abominable aborting aboard abdominal abduction abodes abdomens abbreviated abdicates abode aboriginals abdicates abdication abbreviated abbreviates abetting abbreviated abduction abdication abdication'.split()))

```

Takes in input from standard in and outputs to standard out. This requires a dictionary in a file called `be` the same directory as the code.

I took the Python answer from GotCubes and encoded each character as an index into the dictionary, interpreted as an ASCII code point.

Here's the code that I used to generate my code:

```
be=open("be").read().split()
code="""message = input();words = re.findall("[a-zA-Z]+", message);sentences = re.findall("[^.!?]+", message);print(sum(len(word) if word.lower() not in be else 0 for word in words)+sum(1 if sentence.strip()[0].isalpha() and not sentence.strip()[0].isupper() else 0 for sentence in sentences)+sum(sum(1 if character.isupper() else 0 for character in sentence.strip()[1:]) for sentence in sentences)+len(re.findall("[\s.,;:!?][.,;:!?]", message))+len(re.findall("[^.!?]\\n", message))+len(re.findall("^\s", message))+len(re.findall("\s\s", message))+len(re.findall("[^a-zA-Z\s.,;:!?]", message))+int(not sentences[-1] and count(sentences[-1], '\\n') != 1))"""
words=" ".join(be[ord(c)] for c in code)
print(f"""import re;be=open('be').read().split();exec(''.join(chr(be.index(it))for it in '{words}'.split()))""")

```

*You can definitely lower the score even more, but I will try that when it's not past midnight in my time zone.*

---
Tags: string, code-challenge, parsing, natural-language, self-scoring
---


title: The dragon Curve sequence

text:
# Question
Title: The dragon Curve sequence
The dragon curve sequence (or the regular paper folding sequence) is a binary sequence. `a(n)` is given by negation of the bit left of the least significant 1 of `n`. For example to calculate `a(2136)` we first convert to binary:

```
100001011000

```

We find our least significant bit

```
100001011000
        ^

```

Take the bit to its left

```
100001011000
       ^

```

And return its negation

```
0

```

# Task

Given a positive integer as input, output `a(n)`. (You may output by integer or by boolean). You should aim to make your code as small as possible as measured by bytes.

# Test Cases

Here are the first 100 entries in order

```
1 1 0 1 1 0 0 1 1 1 0 0 1 0 0 1 1 1 0 1 1 0 0 0 1 1 0 0 1 0 0 1 1 1 0 1 1 0 0 1 1 1 0 0 1 0 0 0 1 1 0 1 1 0 0 0 1 1 0 0 1 0 0 1 1 1 0 1 1 0 0 1 1 1 0 0 1 0 0 1 1 1 0 1 1 0 0 0 1 1 0 0 1 0 0 0 1 1 0 1

```

# Answer
> 18 votes
## Mathematica 25 Bytes

```
1/2+JacobiSymbol[-1,#]/2&

```

Other ways of doing this:

56 bytes

```
(v:=1-IntegerDigits[#,2,i][[1]];For[i=1,v>0,i++];i++;v)&

```

58 bytes

```
1-Nest[Join[#,{0},Reverse[1-#]]&,{0},Floor@Log[2,#]][[#]]&

```

# Answer
> 7 votes
# Python 3, ~~22~~ 21 bytes

1 byte thanks to ETHproductions.

```
lambda n:n&2*(n&-n)<1

```

Try it online!

Bitwise arithmetic ftw.

# Answer
> 6 votes
# Retina, ~~38~~ ~~34~~ 29 bytes

```
\d+
$*
+`^(1+)\1$|1111
$1
^1$

```

Try it online!

Martin and Leaky essentially came up with this idea, for 5 more bytes off!

Converts the input to unary, and then progressively divides the number by 2. Once it can't do that evenly anymore (i.e. the number is odd) it then removes patches of 4 from the input, computing the result of the last operation mod 4. Finally, this checks if the result was 1, which means that digit to the left of the least significant 1 bit was zero. If that is true, the final result is 1, otherwise it is zero.

# Answer
> 6 votes
# Jelly, 5 bytes

```
&N&HṆ

```

Try it online!

### How it works

```
&N&HṆ  Main link. Argument: n

 N     Negate; yield -n.
&      Bitwise AND; compute n&-n.
       This yields the highest power of 2 that divides n evenly.
   H   Halve; yield n/2.
  &    Bitwise AND; compute n&-n&n/2. This rounds n/2 down if n is odd.
    Ṇ  Take the logical NOT of the result.

```

# Answer
> 4 votes
## Alice, 8 bytes

```
I2z1xnO@

```

Try it online!

Takes input as the code point of a Unicode character and outputs the result as a 0x00 or 0x01 byte accordingly.

For testability, here is a decimal I/O version at 12 bytes which uses the exact same algorithm (only I/O is different):

```
/o
\i@/2z1xn

```

Try it online!

If Alice was a golfing language and didn't require explicit I/O and program termination, this would clock in at a mere 5 bytes (`2z1xn`) beating both 05AB1E and Jelly.

### Explanation

```
I    Read input.
2z   Drop all factors of 2 from the input, i.e. divide it by 2 as long
     as its even. This shifts the binary representation to the right
     until there are no more trailing zeros.
1x   Extract the second-least significant bit.
n    Negate it.
O    Output it.
@    Terminate the program.

```

# Answer
> 4 votes
# Haskell, 33 bytes

```
g~(a:b:c)=1:a:0:b:g c
d=g d
(d!!)

```

Try it online!

Uses 0-indexing.

# Answer
> 4 votes
# Haskell, 26 bytes

```
f n=even$div n$2*gcd(2^n)n

```

Try it online!

Boolean output.

**32 bytes**

```
(d!!)
d=d%1
~(h:t)%k=k:h:t%(1-k)

```

Try it online!

Saves one byte off of Anders Kaseorg's recursive-list solution.

# Answer
> 4 votes
# APL (Dyalog Unicode), <sup>~~24 23~~</sup> 21 bytes

```
{~⍵[¯1+⌈/⍸⍵]}0,2⊥⍣¯1⊢

```

Try it online!

Bitwise operations are a bit long in APL, so I went with the method in the question.

-1 byte from dzaima.

-2 bytes from Adám.

## Explanation

```
{~⍵[¯1+⌈/⍸⍵]}0,2⊥⍣¯1⊢ input n taken on the right
               2⊥⍣¯1⊢ n in binary
             0,       with 0 prepended in case the LSB is at first index
{           }         do the following to the array ⍵:
         ⍸⍵           get indices of 1's in ⍵
       ⌈/             find maximum index
    ¯1+               subtract 1 from it to get the previous index
  ⍵[       ]          Find the element at that index in ⍵
 ~                    bitwise NOT

```

# Answer
> 3 votes
# 05AB1E, 6 bytes

```
b0Ü¨θ≠

```

Try it online!

# Answer
> 3 votes
# Wise, ~~28~~ ~~20~~ 16 bytes

```
::-~^~-&:[?>]~-^

```

Try it online!

## Explanation

This is a port of Leaky Nun's Python answer. It unfortunately does not work on TIO because TIO's version of the interpreter is a bit outdated.

We start by making 3 copies of our input with `::`, we then decrement the top copy by 1. This will flip all the bits up until the first 1. We then xor this with another copy of our input. Since all of the bits up until the first 1 on our input have been flipped this will result in all those bits being 1 on the result. If we then add one `~-` to the result we will get a single 1 at the place *to the left of* our least significant 1. We AND this with the input to get that bit from the input. Now we will have `0` iff that bit was off and a power of 2 iff that bit was on, we can change this into a single `1` or `0` with `:[?>]`. Once this is done we need only negate the bit `~-^` and we are done.

# Answer
> 3 votes
# Haskell, ~~45~~ ~~43~~ 39 bytes

*6 bytes saved thanks to nimi*

```
f x|d<-div x 2=[f d,mod(1+d)2]!!mod x 2

```

Try it online!

# Answer
> 3 votes
# x86 Machine Code, ~~17~~ ~~16~~ 15 bytes:

Assumes an ABI where parameters are pushed on the stack and the return value is in the `AL` register.

```
8B 44 24 04 0F BC C8 41 0F BB C8 0F 93 C0 C3

```

This is disassembled as follows:

```
_dragoncurve:
  00000000: 8B 44 24 04        mov         eax,dword ptr [esp+4]
  00000004: 0F BC C8           bsf         ecx,eax
  00000007: 41                 inc         ecx
  00000008: 0F BB C8           btc         eax,ecx
  0000000B: 0F 93 C0           setae       al
  0000000E: C3                 ret

```

# Answer
> 3 votes
# Python 2, 19 bytes

```
lambda n:n&-n&n/2<1

```

Try it online!

# Answer
> 3 votes
## JavaScript (ES6), ~~17~~ 14 bytes

```
f=
n=>!(n&-n&n/2)
```

```
<input type=number min=0 oninput=o.textContent=f(this.value)><pre id=o>
```

Edit: Saved 3 bytes by porting @Dennis's answer once I noticed that boolean output was acceptable.

# Answer
> 3 votes
# C (gcc), 20 bytes

```
f(n){n=!(n&-n&n/2);}

```

Try it online!

# Answer
> 3 votes
# INTERCAL, 50 bytes

```
DOWRITEIN.1DO.1<-!?1~.1'~#1DOREADOUT.1PLEASEGIVEUP

```

INTERCALs unary operators are quite suitable for this, so I decided to write my first post.

```
DO WRITE IN .1
DO .1 <- !?1~.1'~#1
DO READ OUT .1
PLEASE GIVE UP

```

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

1 byte thanks to Erik the Outgolfer.

```
Bt0ṖṪṆ

```

Try it online!

## Longer programs

# Answer
> 2 votes
# Befunge-98, 19 bytes

```
&#;:2%\2/\#;_;@.!%2

```

Try it online!

```
&#                       Initial input: Read a number an skip the next command
  ;:2%\2/\#;_;           Main loop: (Direction: East)
   :2%                    Duplicate the current number and read the last bit
      \2/                 Swap the first two items on stack (last bit and number)
                          and divide the number by two => remove last bit
         \                swap last bit and number again
          #;_;            If the last bit is 0, keep going East and jump to the beginning of the loop
                          If the last bit is 1, turn West and jump to the beginning of the loop, but in a different direction.
&#;           @.!%2      End: (Direction: West)
&#                        Jump over the input, wrap around
                 %2       Take the number mod 2 => read the last bit
               .!         Negate the bit and print as a number
              @          Terminate

```

# Answer
> 2 votes
# Octave, 34 bytes

```
@(x)~(k=[de2bi(x),0])(find(k,1)+1)

```

Try it online!

**Explanation:**

```
@(x)                               % Anonymous function taking a decimal number as input
    ~....                          % Negate whatever comes next
     (   de2bi(x)   )              % Convert x to a binary array that's conveniently
                                   % ordered with the least significant bits first
        [de2bi(x),0]               % Append a zero to the end, to avoid out of bound index
     (k=[de2bi(x),0])              % Store the vector as a variable 'k'
                     (find(k,1)    % Find the first '1' in k (the least significant 1-bit)
                               +1  % Add 1 to the index to get the next bit
     (k=[de2bi(x),0])(find(k,1)+1) % Use as index to the vector k to get the correct bit

```

# Answer
> 2 votes
# ,,,, ~~10~~ 9 bytes

```
::0-&2*&¬

```

## Explanation

Take input as 3 for example.

```
::0-&2*&1≥
               implicitly push command line argument       [3]
::             duplicate twice                             [3, 3, 3]
  0            push 0 on to the stack                      [3, 3, 3, 0]
   -           pop 0 and 3 and push 0 - 3                  [3, 3, -3]
    &          pop -3 and 3 and push -3 & 3 (bitwise AND)  [3, 1]
     2         push 2 on to the stack                      [3, 1, 2]
      *        pop 2 and 1 and push 2 * 1                  [3, 2]
       &       pop 2 and 3 and push 2 & 3                  [2]
        ¬      pop 2 and push ¬ 2 (logical NOT)            [0]
               implicit output                             []

```

# Answer
> 2 votes
# tinylisp, 71 bytes

```
(load library
(q((x)(not(nth(c 0(to-base 2 x))(last-index(to-base 2 x)1

```

Anonymous function that takes a number and returns 0 or 1. Try it online!

### Ungolfed/explanation

Surprisingly, tinylisp's library lets us implement the spec almost directly.

```
(load library)

(lambda (x)                   ; Anonymous function with one argument
  (not                        ; Logical negation of
    (nth                      ; The element of _ at index __:
      (cons 0 (to-base 2 x))  ; The binary representation of x with a 0 prepended
      (last-index             ; Index of the last occurrence
        (to-base 2 x)         ; in the binary representation of x
        1)))))                ; of 1

```

Prepending a 0 handles the "previous bit" logic by shifting all elements down one spot, and it keeps us from walking off the left end of the list when there is only a single 1 bit.

# Answer
> 1 votes
# MATL, ~~11~~ 10 bytes

```
t4*YF1)Z.~

```

Try it online! Or see the first 100 outputs.

### Explanation

```
t    % Implicit input. Duplicate
4*   % Multiply by 4. This ensures that the input is a multiple of 2, and
     % takes into account that bit positions are 1 based
YF   % Exponents of prime factorization
1)   % Get first exponent, which is that of factor 2
Z.   % Get bit of input at that (1-based) position
~    % Negate. Implicit display

```

# Answer
> 1 votes
# Submission:

# Python 2, ~~41~~ 39 bytes

```
x=input()
while~-x&1:x/=2
print 1-x/2%2

```

Try it online!

-2 bytes thanks to FryAmTheEggman

# Initial Solution:

# Python 2, 43 bytes

```
lambda x:1-int(bin(x)[bin(x).rfind('1')-1])

```

Try it online!

# Answer
> 1 votes
# Pari/GP, 20 bytes

```
n->kronecker(-1,n)>0

```

Using the Kronecker symbol.

Try it online!

# Answer
> 1 votes
# SCALA, 99(78?) chars, 99(78?) bytes

```
if(i==0)print(1)else
print(if(('0'+i.toBinaryString).reverse.dropWhile(x=>x=='0')(1)=='1')0 else 1)

```

where `i` is the input.

As you can see, I do save 21 bytes if I don't take care of the zero (as the author did in his test case) :

```
print(if(('0'+i.toBinaryString).reverse.dropWhile(x=>x=='0')(1)=='1')0 else 1)

```

This is my first codegolf so I hope I did well :)

Try it online! Though it's quite long to compute lol.

# Answer
> 1 votes
# C (gcc), ~~35~~ 31 bytes

```
f(x){return~x&1?f(x/2):!(x&2);}

```

Switched to a recursive implementation. Try it online!

# Answer
> 1 votes
# Java 8, 17 bytes

```
n->(n&2*(n&-n))<1

```

Straightforward port of LeakyNun's Python 3 answer. I'm not familiar enough with bitwise operations and operator precedence to see a shorter solution; maybe there's a way to avoid the extra parentehesis?

# Answer
> 1 votes
# Chip, 93 bytes

```
HZABCDEFG,t
 ))))))))^~S
H\\\\\\\/v~a
G\\\\\\/v'
F\\\\\/v'
E\\\\/v'
D\\\/v'
C\\/v'
B\/v'
A/-'

```

Takes input as little endian bytes. (The TIO has a bit of python that does this for you). Gives output as either `0x0` or `0x1`. (The TIO uses xxd to inspect the value).

Try it online!

### How do it this?

Chip looks at input one byte at a time, so handling multibyte input adds some bulk, but not near as much as I had feared.

Let's go into it:

```
HZABCDEFG

```

These are `HZ`, high bit of the previous byte (if there was one), and `A`-`G`, the seven lower bits of the current byte. These are used to locate the lowest set bit of the number.

```
        ,t
))))))))^~S

```

When the lowest set bit is found, we have a few things to do. This first chunk says "if we have a set bit (the `)`'s), then stop `S`uppressing the output, and `t`erminate after we print the answer.

```
H\\\\\\\/v~a
G\\\\\\/v'
...
A/-'

```

Whichever bit of the current byte (`A`-`H`) is only preceded by a bunch of zeroes then a one (`\` and `/`: these look at the bits directly north of them; we can trust that all previous bits were zero) is passed through to the wires on the right (`v`, `'`, ...), then whichever value it is is inverted and given as the low bit of output (`~a`).

# Answer
> 1 votes
# APL (Dyalog Extended), 12 bytes

```
1≠¯1⊥2↑⍸∘⌽∘⊤

```

Try it online!

Took the idea of using  from Razetime's answer.

### How it works

```
1≠¯1⊥2↑⍸∘⌽∘⊤  ⍝ Input: n
           ⊤  ⍝ Binary representation of n
         ⌽∘   ⍝ Reverse
       ⍸∘     ⍝ Get indices of ones, in increasing order
              ⍝   LSB index (l) comes first, and the next number is l+1
              ⍝   iff the bit on the left of LSB is also 1
     2↑       ⍝ Take first two numbers, filling with 0 if too short
  ¯1⊥         ⍝ From [a, b] compute -a + b
1≠            ⍝ Is it not equal to 1?

```

Equivalent non-extended program:

# APL (Dyalog Unicode), 17 bytes

```
1≠¯1⊥2↑∘⍸∘⌽2∘⊥⍣¯1

```

Try it online!

# Answer
> 1 votes
# Husk, ~~10~~ 8 bytes

```
¬!2↓¬↔Θḋ

```

Try it online!

```
¬          # logical NOT of
 !2        # the second element
   ↓¬      # after chopping-off initial zeros
     ↔     # of the reverse of
      Θḋ   # the binary digits of the input

```

# Answer
> 1 votes
# K (ngn/k), 12 bytes

```
~1=-/|-2#&2\

```

Modeled after @Bubbler's APL answer.

* `2\` convert input to base-2
* `-2#&` get the last two indices containing 1's
* `-/|` subtract the smaller index from the larger one
* `~1=` if the last truthy index isn't preceded by another truthy value, return 0. otherwise, return 1

Try it online!

# Answer
> 1 votes
# Stax, 5 bytes

```
éò/ú╗

```

Run and debug it

# Answer
> 1 votes
# Vyxal, 6 bytes

```
b0PṪt⌐

```

Try it Online!

```
b      # Convert to binary
 0P    # Strip zeroes
   Ṫt  # Second-to-last item
     ⌐ # The NOT of that

```

# Answer
> 1 votes
# tinylisp, 83 bytes

```
(load library
(d F(q((x)(i(h x)x(F(t x
(d G(q((x)(- 1(h(t(F(reverse(c 0(to-base 2 x

```

Try it online!

fixed with dlosc's help.

# Answer
> 0 votes
# Japt, ~~10 8~~ 9 bytes

```
!+¢g¢a1 É

```

Try it online!

# Explanation

```
!+¢   g    a1 É
!+Us2 gUs2 a1 -1 # Implicit input (U) as number
!+               # Return the boolean NOT of
      g          #   the character at index
       Us2       #     the input converted to binary
           a1    #     the index of its last 1
              -1 #     minus 1
      g          #   in string
  Us2            #     the input converted to binary

```

# Answer
> 0 votes
# JavaScript (ES6), ~~53~~ 34 bytes

```
a=>eval("for(;~a&1;a/=2);~a>>1&1")

```

# Answer
> 0 votes
# PHP\>=7.1, 32 bytes

```
<?=1^!trim(decbin($argn),0)[-2];

```

PHP Sandbox Online

# PHP, 40 bytes

```
for($i=$argn;$i%2<1;)$i/=2;echo$i/2%2^1;

```

Try it online!

# PHP, 41 bytes

```
<?=1^preg_match("#110*$#",decbin($argn));

```

Try it online!

# Answer
> 0 votes
# Common Lisp, 56 bytes

```
(defun f(n)(if(oddp n)(- 1(mod #1=(ash n -1)2))(f #1#)))

```

Try it online!

# Answer
> 0 votes
# MMIX, 24 bytes (6 instrs)

```
00000000: 36ff0000 c8ffff00 3bffff01 c80000ff  6”¡¡Ṁ””¡;””¢Ṁ¡¡”
00000010: 73000001 f8010000                    s¡¡¢ẏ¢¡¡

```

Disassembled

```
dragon  NEGU $255,0,$0      // t = -n
        AND  $255,$255,$0   // t &= n (gets last 1 bit)
        SLU  $255,$255,1    // t <<= 1
        AND  $0,$0,$255     // n &= t
        ZSZ  $0,$0,1        // n = !n
        POP  1,0            // return n

```

# Answer
> 0 votes
# Japt `-!`, 6 bytes

```
&n)Ñ&U

```

Try it

```
&n)Ñ&U     :Implicit input of integer U
&          :Bitwise AND of U with
 n         :Its negation
  )        :Group that together
   Ñ       :Multiply by 2
    &U     :Bitwise AND with U

```

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


# Question
Title: Find a word in the dictionary of all possible words
Given an alphabet represented as a nonempty set of positive integers, and a word made up of symbols from that alphabet, find that word's position in the lexicographically ordered set of all words, assuming words can't contain duplicate symbols.

## Example

Consider the alphabet `{1, 2, 3}` and the word `[2, 3, 1]`. The set of all possible words, ordered via lexicographic order is

```
{
  [1],
  [1, 2],
  [1, 2, 3],
  [1, 3],
  [1, 3, 2],
  [2],
  [2, 1],
  [2, 1, 3],
  [2, 3],
  [2, 3, 1],
  [3],
  [3, 1],
  [3, 1, 2],
  [3, 2],
  [3, 2, 1]
}

```

`[2, 3, 1]` is the tenth element in the set, so the answer is 10 (9 if you use zero indexing).

## Input/Output

Input can be taken in any reasonable format, including taking the alphabet as a sorted list, or taking the alphabet/word as a string.

Output can be zero or one indexed, please say which one you choose in your answer.

This is , so the shortest answer wins.

## Testcases

One indexed:

```
alphabet, word -> location (1 indexed)
{1, 2, 3} , [] -> undefined
{1, 2, 3}, [1] -> 1
{1, 2, 3}, [3] -> 11
{1, 2, 3}, [2, 3, 1] -> 10
{1, 2, 3}, [3, 2, 1] -> 15
{1, 3, 4, 6}, [3, 1, 4] -> 19
{1, 3, 4, 6}, [3, 1, 6, 4] -> 22
{1,3, 4, 16, 23, 37, 43, 57}, [37, 43, 16, 3] -> 79332
{41, 57, 60, 61, 71, 80, 113, 125, 131, 139, 141, 184, 197, 200, 201, 214, 215, 216, 223, 236, 238, 240, 244, 252, 264, 279, 300, 335, 340, 393, 410, 414, 421, 436, 441, 447, 461, 466, 483, 490, 525, 537, 540, 543, 547, 551, 552, 557, 569, 583, 584, 591, 593, 595, 596, 607, 610, 613, 614, 620, 621, 634, 637, 643, 652, 683, 691, 713, 726, 733, 738, 750, 757, 767, 777, 789, 803, 812, 813, 817, 844, 850, 856, 878, 901, 910, 926, 947, 949, 951, 953, 958, 962, 969, 982, 995}, [252, 300, 969, 844, 856, 713, 60, 621, 393, 637, 634, 441, 817, 264, 551, 757, 926, 240, 461, 421, 767, 726, 223, 610, 547, 141, 593, 184, 200, 643, 583, 614, 958, 540, 201, 214, 584, 591, 525, 652, 466, 414, 995, 125, 813, 951, 901, 215, 947, 410, 113, 279, 238, 57, 750, 607, 61, 131, 216, 340, 569, 803, 557, 878, 691, 80, 850, 483, 71, 613, 41, 244, 789, 595, 447, 596, 812, 543, 953, 620, 962, 436, 537, 733, 738, 197, 949, 982, 139, 683, 910, 236, 552, 490, 777, 335] -> 653513463887666116337968717018588523734749776398084200209718028326146195147009645472571018754197481757464478858415475671625444580437153140577102475638

```

Zero indexed:

```
alphabet, word -> location (0 indexed)
{1, 2, 3} , [] -> undefined
{1, 2, 3}, [1] -> 0
{1, 2, 3}, [3] -> 10
{1, 2, 3}, [2, 3, 1] -> 9
{1, 2, 3}, [3, 2, 1] -> 14
{1, 3, 4, 6}, [3, 1, 4] -> 18
{1, 3, 4, 6}, [3, 1, 6, 4] -> 21
{1,3, 4, 16, 23, 37, 43, 57}, [37, 43, 16, 3] -> 79331
{41, 57, 60, 61, 71, 80, 113, 125, 131, 139, 141, 184, 197, 200, 201, 214, 215, 216, 223, 236, 238, 240, 244, 252, 264, 279, 300, 335, 340, 393, 410, 414, 421, 436, 441, 447, 461, 466, 483, 490, 525, 537, 540, 543, 547, 551, 552, 557, 569, 583, 584, 591, 593, 595, 596, 607, 610, 613, 614, 620, 621, 634, 637, 643, 652, 683, 691, 713, 726, 733, 738, 750, 757, 767, 777, 789, 803, 812, 813, 817, 844, 850, 856, 878, 901, 910, 926, 947, 949, 951, 953, 958, 962, 969, 982, 995}, [252, 300, 969, 844, 856, 713, 60, 621, 393, 637, 634, 441, 817, 264, 551, 757, 926, 240, 461, 421, 767, 726, 223, 610, 547, 141, 593, 184, 200, 643, 583, 614, 958, 540, 201, 214, 584, 591, 525, 652, 466, 414, 995, 125, 813, 951, 901, 215, 947, 410, 113, 279, 238, 57, 750, 607, 61, 131, 216, 340, 569, 803, 557, 878, 691, 80, 850, 483, 71, 613, 41, 244, 789, 595, 447, 596, 812, 543, 953, 620, 962, 436, 537, 733, 738, 197, 949, 982, 139, 683, 910, 236, 552, 490, 777, 335] -> 653513463887666116337968717018588523734749776398084200209718028326146195147009645472571018754197481757464478858415475671625444580437153140577102475637

```

Note: This challenge is loosely based upon an old weekly challenge on replit.

# Answer
> 7 votes
# Python 3.8, 93 bytes

```
lambda a,w:sum(sum(map(e.__gt__,a:=a-{e}))*h(len(a))+1for e in w)
h=lambda n:n<1or 1+n*h(n-1)

```

An unamed function that accepts the alphabet, `a`, as a `set` and the word, `w`, as an `Iterable` and returns the 1-indexed index of the word (an empty word will give `0`).

**Try it online!**

### How?

We calculate the number of "blocks" in the set of valid words that we need to pass for each character in the word and multiply by the size of said "blocks", moving forward one more for each character.

The size of the block at each step is the number of words that may be formed from the alphabet once we've removed the current character and any previously processed characters. This is OEIS: A000522 and is calculated with the recursive helper function, `h`.

The number of blocks to pass at each step is the number of characters that come before the current character in the alphabet once we've removed any previously processed characters and is calculated with `sum(map(e.__gt__,a:=a-{e}))` which deals with removing the word character from the alphabet.

# Answer
> 6 votes
# Vyxal, 5 bytes

```
Þxs?ḟ

```

Try it Online!

**Explanation**:

```
Þxs?ḟ
Þx    All possible combinations of the set (without replacements)
  s   Sort
   ?ḟ Output index of the word

```

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

Expects `(word)(alphabet)`. The result is 1-indexed.

```
b=>g=(a,w=k=0)=>w==b||a.some((v,i)=>g(a.filter(_=>i--),w?w+[,v]:v),k++)*k

```

Try it online!

### Commented

```
b =>              // outer function taking the word array b[]
g = (             // inner recursive function taking:
  a,              //   the alphabet array a[]
  w = k = 0       //   the current word w and the corresponding index k
) =>              //
w == b ||         // stop if w is equal to b (implicit string coercion)
a.some((v, i) =>  // otherwise, for each value v at position i in a[]:
  g(              //   do a recursive call:
    a.filter(_ => //     pass a copy of a[] with ...
      i--         //       ... the i-th entry removed
    ),            //
    w ?           //     if w is already initialized:
      w + [, v]   //       append a comma followed by v to w
    :             //     otherwise:
      v           //       set w to v
  ),              //   end of recursive call
  k++             //   before some() is actually processed: increment k
) * k             // end of some(); return k

```

# Answer
> 4 votes
# Factor \+ `math.combinatorics`, 64 bytes

```
[ all-subsets [ <permutations> ] map concat natural-sort index ]

```

Try it online!

1-indexed. Takes input as `word alphabet`.

* `all-subsets` get all subsets of the alphabet
* `[ <permutations> ] map concat` get each permutation of each set and flatten it to a list
* `natural-sort` sort
* `index` find the index of the word

# Answer
> 2 votes
# Python, 101 bytes

```
f=lambda a,w:w>[]and sorted(a).index(w[0])*g(len(a))+f(a-{w[0]},w[1:])+1
g=lambda n:n and~-n*g(n-1)+1

```

Attempt This Online!

Does actually calculate the index. 1-based, 0 for undefined.

# Answer
> 2 votes
# Ruby, ~~62~~ 57 bytes

```
->a,w{a.product(*a.map{a}).map(&:uniq).sort.uniq.index w}

```

Try it online!

Thanks Jordan for the hint that saved 5 bytes.

# Answer
> 1 votes
# Charcoal, 30 bytes

```
≔⟦υ⟧ζＦζＦ⁻θι⊞ζ⁺ι⟦κ⟧Ｗ⁻ζυ⊞υ⌊ιＩ⌕υη

```

Try it online! Link is to verbose version of code. 1(!)-indexed. Explanation:

```
≔⟦υ⟧ζＦζ

```

Start a breadth-first search for words with the empty word (this consumes index 0, which is why the output becomes 1-indexed.)

```
Ｆ⁻θι⊞ζ⁺ι⟦κ⟧

```

For each word, create new words by suffixing all symbols not already used.

```
Ｗ⁻ζυ⊞υ⌊ι

```

Sort the words lexicographically.

```
Ｉ⌕υη

```

Output the desired word's position.

# Answer
> 1 votes
# Python 3, 107 bytes

```
lambda a,b:sorted([[*p]for i in range(len(a))for p in permutations(a,i+1)]).index(b)
from itertools import*

```

Try it online!

Get permutations of all sizes, sort them and return index of required word.

# Answer
> 1 votes
# Japt, ~~10~~ 8 bytes

```
à cá ÍbV

```

Try it

1-indexed output. Takes the alphabet as a sorted string with each symbol represented by a unique byte, then the word as another string.

```
à cá ÍbV
à        # Get all substrings of the alphabet
   á     # Get all the permutations of each substring
  c      # Flatten to a single array
     Í   # Sort lexicographically by the alphabet
      bV # Find the index of the word

```

The last test case runs slow enough that I haven't been able to check its output, but alphabets of that length should be supported.

# Answer
> 1 votes
# PARI/GP, 67 bytes

```
f(a,w)=sum(l=1,#w,sum(i=0,k=#a=a[^1+n=#[1|b<-a,b<w[l]]],k!/i!)*n+1)

```

Attempt This Online!

Takes the alphabet as a sorted list. 1-indexed.

A port of Jonathan Allan's Python answer, but using the formula \\$a(n)=\sum\_{i=0}^n k!/i!\\$ for OEIS A000522.

# Answer
> 1 votes
# Pyth, 8 bytes

```
xSs.pMyE

```

Test suite

Takes the word as a list as the first input and the alphabet as a list as the second input, outputs the 1-index of the word. Unfortunately hits a MemoryError / times out for that last one, but I can't think of a reason it shouldn't work in theory.

#### Explanation:

```
xSs.pMyE  | Full code
xSs.pMyEQ | with implicit variables
----------+-----------------------------------------
      yE  | Generate all subsets of alphabet
   .pM    | Generate all permutations of each subset
  s       | Flatten the list
 S        | Sort the list
x       Q | Find the index of the word

```

# Answer
> 1 votes
# Nibbles, ~~9~~ 8 bytes (16 nibbles)

```
?`<+.`_0$``p$

```

```
?`<>>+.`_0$``p$
       `_0$      # get all subsequences of arg1
      .          # and map over this
           ``p$  # getting all permutations of each list,
     +           # and flatten this list-of-list-of-lists,
   >>            # remove the first element (the empty list),
 `<              # and sort the list-of-lists,
?                # finally, get the index of arg2.

```

# Answer
> 1 votes
# Haskell, ~~60~~ 58 bytes

```
f l=do y<-l;(y:)<$>[]:f[x|x<-l,x/=y]
a!w=sum[1|x<-f a,w>x]

```

Try it online!

Thanks to @Laikoni for saving 2 Bytes using *do* notation.

* 0 indexed

*f l* generates vocabulary of set *l*

*a!w* counts words less than *w*

# Answer
> 0 votes
# 05AB1E, 9 bytes

```
œ€æ€`êÅΔQ

```

1-based indexing (or actually 0-based indexing, by also handling `[]` at index `0`).

Try it online or verify (almost) all test cases (the last two test cases are omitted, because they time-out on TIO).

**Explanation:**

```
œ          # Get the powerset of the (implicit) input-list, including empty list
 €æ        # Get all permutations of each sublist
   €`      # Flatten it one level down
     ê     # Sorted-uniquify the inner lists lexicographically
      ÅΔ   # Get the first (0-based) index which is truthy for:
        Q  #  Is it equal to the second (implicit) input-list?
           # (which is output implicitly as result)

```

---
Tags: code-golf, combinatorics
---