title: Who's next to me in the queue?

text:
# Question
Title: Who's next to me in the queue?
Problem 4 in the 2019 BMO, Round 1 describes the following setup:

> There are \\$2019\\$ penguins waddling towards their favourite restaurant. As the penguins arrive, they are handed tickets numbered in ascending order from \\$1\\$ to \\$2019\\$, and told to join the queue. The first penguin starts the queue. For each \\$n \> 1\\$ the penguin holding ticket number \\$n\\$ finds the greatest \\$m \< n\\$ which divides \\$n\\$ and enters the queue directly behind the penguin holding ticket number \\$m\\$. This continues until all \\$2019\\$ penguins are in the queue.

The second part of the question asked candidates to determine the penguins standing directly in front of, and directly behind, penguin \\$33\\$. This could be done by examining the patterns in the queue, considering prime factors: see the online video solutions for more information.

---

## The Challenge

Your task is to design a program or function which, given a positive integer \\$k\\$ representing the penguin with ticket number \\$k\\$, outputs the ticket numbers of the penguins *directly before and after* this penguin.

For example, penguin \\$33\\$, stands directly behind \\$1760\\$ and directly in front of \\$99\\$, so the program should output, in some reasonable format, \\$\[1760, 99\]\\$.

---

## Rules

* The input will be an integer in the range \\$1 \< k \le 2019\\$.
* Your program should output two integers, in any reasonable format, representing the ticket numbers of the penguins before and after.
* These can be output in any order, (front first or behind first) but this order must be consistent.
* The penguin will not be at the front or back of the queue: so you don't have to handle the edge cases of \\$k = 1\\$ or \\$k = 1024\\$.
* As penguins find it difficult to read human glyphs, your program should be as short as possible. This is a - so the shortest program (in bytes) wins!

---

## Test Cases

These outputs are given in the format `[front, behind]`.

```
33   -> [1760, 99]
512  -> [256, 1024]
7    -> [1408, 49]
56   -> [28, 112]
1387 -> [1679, 1241]
2019 -> [673, 1346]
2017 -> [1, 2011]
2    -> [1536, 4]

```

# Answer
> 7 votes
# Perl 6, ~~79~~ ~~76~~ 71 bytes

```
{($!=sort {[R,] -$_,{first $_%%*,$_^..1}...1},^2020)[+(@$!...$_)X-2,0]}

```

Try it online!

Sorts numbers 1 to 2019 lexicographically by the reversed, negated sequence of largest divisors, then finds the neighbors. Example mappings:

```
1760 => (-1 -11 -55 -110 -220 -440 -880 -1760)
  33 => (-1 -11 -33)
  99 => (-1 -11 -33 -99)

```

In other words, the negated cumulative product of prime factors in descending order.

# Answer
> 4 votes
# JavaScript (ES6),  ~~105 ... 101~~  100 bytes

A straightforward implementation that builds the full queue and looks for the penguin with the input ticket within it.

Returns `[front, behind]`.

```
k=>[eval("for(n=q=[];m=++n%2020;q.splice(q.indexOf(m),0,n))while(n%--m)q")[i=q.indexOf(k)+1],q[i-2]]

```

Try it online!

### Commented

The code in `eval()` builds and returns the queue in reverse order:

```
for(                      // outer loop:
  n = q = [];             //   q[] = queue, n = counter (initially zero'ish)
  m = ++n % 2020;         //   increment n; set m to n mod 2020, so that we
                          //   stop when n = 2020
  q.splice(               //   after each iteration:
    q.indexOf(m), 0, n    //     insert n before m in q[] (should be *after* m to build
  )                       //     the queue from first to last, but it's shorter this way)
) while(n % --m)          //   inner loop: decrement m until it divides n
    q                     //     dummy loop statement so that q[] is returned by eval()

```

which gives \\$q\[\\:\]=\[1024,512,...,2017,1\]\\$.

Wrapper code:

```
k => [                    // k = input
  eval("...")             // build q[]
  [i = q.indexOf(k) + 1], // return the element after k ('in front of')
  q[i - 2]                // and the element before k ('behind')
]                         //

```

# Answer
> 4 votes
# Jelly, 15 bytes

```
⁽¥ØÆfṚNƊÞṣị"@Ø.

```

A monadic Link accepting an integer between 1 and 2019 * which yields a list of two integers, `[in-front, behind]`.

* If `1` or `1024` is input the missing ticket number will be shown as `0`.

**Try it online!**

### How?

```
⁽¥ØÆfṚNƊÞṣị"@Ø. - Link: n
⁽¥Ø             - literal 2019
        Þ       - sort (range [1..2019]) by:
       Ɗ        -   last three links as a monad:
   Æf           -     prime factorisation (e.g. 1100 -> [2,2,5,5,11])
     Ṛ          -     reversed
      N         -     negated
         ṣ      - split at (n)
             Ø. - literal [0,1]
            @   - with swapped arguments:
           "    -   zip with:
          ị     -     index into (1-based & modular)
                      - i.e. [last of left list, first of right list]

```

# Answer
> 3 votes
# Python 2, ~~137~~ ~~133~~ 121 bytes

```
q=[1]
for n in range(2,2020):j=q.index(max(m for m in q if n%m<1))+1;q=q[:j]+[n]+q[j:]
print q[q.index(input())-1::2][:2]

```

Try it online!

4 bytes thx to Arnauld; 11 bytes thx to FlipTack.

Another naive implementation.

# Answer
> 3 votes
# 05AB1E, ~~16~~ 15 bytes

```
Ž7ëLΣÒR(}ûI¡€θ¨

```

Port of *@JonathanAllan*'s Jelly answer, so make sure to upvote him!
-1 byte thanks to *@Grimmy*.

Outputs in the order `[front, behind]`.

Try it online or verify all test cases.

**Explanation:**

```
Ž7ë              # Push compressed integer 2019
   L             # Pop and push a list in the range [1,2019]
    Σ            # Sort this list by:
     Ò           #  Get the prime factors (with duplicates)
      R          #  Reverse it
       (         #  Negate each inner value
        }û       # After the sort: palindromize this list ([a,b,c] → [a,b,c,b,a])
          I¡     # Split this pallindromized list by the input-integer
            €θ   # For each inner list: only leave the last value
              ¨  # And remove the last value, so the pair remains
                 # (after which this pair is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `Ž7ë` is `2019`.

# Answer
> 2 votes
# C++ (clang), ~~288~~ \\$\cdots\\$ ~~210~~ 203 bytes

Saved a whopping ~~22~~ 29 bytes thanks to ceilingcat!!!!
Saved a byte thanks to @AZTECCO!!!!

```
#import<bits/stdc++.h>
#define l find(begin(q),end(q)
using v=std::vector<int>;v f(int p){v q{1};for(int n=1,d,i;d=i=++n<2020;q.insert(l,d),n))for(;++i<n&d<2;)d=n%i?d:n/i;auto t=l,p);return{*++t,t[-2]};}

```

Try it online!

Ungolfed:

```
#include <vector>
#include <algorithm>

auto f(int p)
{
    std::vector<int> q{1};
    for (int n = 2; n <= 2019; ++n)
    {
        int d = 1;
        for (int i = 2; i < n; ++i)
        {
            if (n % i == 0)
            {
                d = n / i;
                break;
            }
        }
        auto it = find(begin(q), end(q), d);
        q.insert(it, n);
    }
    auto it = find(begin(q), end(q), p);
    std::vector<int> r = {*(it + 1), *(it - 1)};
    return r;
}

```

# Answer
> 1 votes
# Perl 5, 88 bytes

```
sub f{$_=1;for$n(2..2019){map{$n%$_ or$m=$_}1..$n/2;s/\b$m\b/$&,$n/}/(\d+),$_[0],(\d+)/}

```

Try it online!

Same ungolfed:

```
sub f {
  $_=1;                             # $_ is the comma separated queue "array string"
                                    # ...with 1 as the first penguin
  for $n (2..2019){                 # process the rest of the penguins 2-2019
    map { $n%$_ or $m=$_ } 1..$n/2; # find max $m divisible by current $n
    s/\b$m\b/$&,$n/                 # search-replace to place current $n behind $m
  }
  /(\d+),$_[0],(\d+)/               # find and return the two numbers:
                                    # the one before and the one after the input
                                    # parameter $_[0] in the $_ array string
}

```

# Answer
> 1 votes
# , ~~90~~ 89 bytes

```
for(i in 2:2019)T=append(T,i,match(max(which(!i%%1:(i-1))),T));T[match(scan(),T)+c(-1,1)]

```

Try it online!

Builds up the list into `T` and extracts the relevant values.

As a bonus, it works for `1` and *almost* works for `1024`, as R's 1-based indexing returns nothing for index `0` and `NA` for index `2020`.

# Answer
> 0 votes
# Jelly, ~~23~~ 21 bytes

```
ḍƇṀ=⁸k⁸j
⁽¥ØRç/ṣ⁸ṪḢƭ€

```

Try it online!

Naïve answer that simply generates the list of penguins and finds the relevant place. A pair of links which, when called as a monad, takes an integer as its argument and returns a pair of integers indicating the penguins before and after in the list of penguins.

# Answer
> 0 votes
# Ruby, ~~104 101~~ 95 bytes

```
->n{*w=1;(2..2019).map{|z|w.insert(1+w.index(w.select{|x|z%x<1}.max),z)};w[w.index(n)-1,3]-[n]}

```

Try it online!

# Answer
> 0 votes
# Retina 0.8.2, 109 bytes

```
^
2019$*_
_
$`_¶
(_+)\1+¶
$1 $&
+m`^(_+)¶((_+¶)*)\1 (_+¶)
$1¶$4$2
_+
$.&
^(.+¶)*(.+)¶(.+)(¶.+)(¶.+)*¶\3$
$2$4

```

Try it online! Note: Link only goes to 201 as 2019 is too slow for TIO. Explanation:

```
^
2019$*_

```

Prepend 2019 in unary.

```
_
$`_¶

```

Count from 1 to 2019.

```
(_+)\1+¶
$1 $&

```

Precede each number with its highest proper factor (except 1, which remains unchanged).

```
+m`^(_+)¶((_+¶)*)\1 (_+¶)
$1¶$4$2

```

Insert in turn each number after its highest proper factor.

```
_+
$.&

```

Convert to decimal.

```
^(.+¶)*(.+)¶(.+)(¶.+)(¶.+)*¶\3$
$2$4

```

Extract the predecessor and successor of the original input.

118 byte version that's fast enough to handle 2019 on TIO:

```
^
2019$*_
_
$`_¶
(_+)\1+\b
$.1;$.&
_
1
m{`^(\d+)¶\1;
$1¶
}`^(\d+¶)(\d+;\d+¶)
$2$1
^(.+¶)*(.+)¶(.+)(¶.+)(¶.+)*¶\3$
$2$4

```

Try it online! Explanation:

```
^
2019$*_
_
$`_¶

```

Prepend all of the unary numbers from 1 to 2019.

```
(_+)\1+\b
$.1;$.&

```

Convert to decimal and prepend the largest factor.

```
_
1

```

Except 1, which just becomes the first entry in the list.

```
m{`^(\d+)¶\1;
$1¶
}`^(\d+¶)(\d+;\d+¶)
$2$1

```

Bubble up each line until it finds its insertion point.

```
^(.+¶)*(.+)¶(.+)(¶.+)(¶.+)*¶\3$
$2$4

```

Extract the predecessor and successor of the original input.

# Answer
> 0 votes
# Japt, 36 bytes

```
1k
#É9ò2@iUaXâ n- gJÑ)ÄX
g[J1]c+UaNg

```

Try it

```
1k               assign [1] to U

#É9ò2            pass range 2...2019 to function:
     @i ...  X   insert each value in U at index:
 Ua               find max divisor of X in U:
   Xâ              divisors
      n-           sorted
         gJÑ)Ä     2nd to last

g                get elements at
 [J1]             [-1,1]
     c+UaNg       add index of 1st input in U

```

# Answer
> 0 votes
# Scala, 163 bytes

```
n=>{val a=(2 to 2019).map(x=>(x,((1 to x/2).filter(x%_==0)).max)).foldLeft(Seq(1))((l,e)=>l.patch(l.indexOf(e._2)+1,Seq(e._1),0));val i=a indexOf n;(a(i-1),a(i+1))

```

Try it online!

---
Tags: code-golf, arithmetic, number-theory
---


# Question
Title: Tips for golfing javascript code, especially converting while loop to expression
The code:

```
function L(){N=null;E=[N,N];t=this;h=E;t.u=i=>h=[i,h];
t.o=_=>h==E?N:h[+!(h=h[1])];t.e=(i,l)=>h=(l||h)==E?[i,
E]:[(l||h)[0],t.e(i,(l||h)[1])];t.s=_=>{o="";while(i=t.o())
{o+=i+","}return o}}

```

For my response to this (old) question: https://codegolf.stackexchange.com/a/196783/72421 (my linked answer has a commented version of the code and some disclaimers about valid inputs and outputs)

I'm looking for suggestions on how to golf it further. I feel the last function is especially verbose. I managed to make every other function a single expression so I didn't need curly brackets or a return statement, but couldn't figure out how to make the last one not require a while loop.

# Answer
I think the best way to get rid of the curly brackets is to go recursive.

### Original function (46 bytes)

```
t.s=_=>{o="";while(i=t.o()){o+=i+","}return o}

```

### Recursive version (29 bytes)

```
t.s=_=>(i=t.o())?i+[,t.s()]:i

```

The `i+[,t.s()]` trick saves a byte over `i+','+t.s()`.

Because you stop when `t.o()` returns `null`, the result of your original version always ends with a comma. In the new version, we actually append `null` at the end (that's the `:i`) but it's coerced to an empty string because of the above trick, leading to the same behavior.
> 8 votes

# Answer
## Shortening `t.s`

### Favor recursion over while loop

Given your `t.s` function

```
t.s=_=>{o="";while(i=t.o()){o+=i+","}return o}

```

Observe that `o` is a simple accumulator, so we can easily convert the loop into a recursive function. There are several ways to write the recursive function:

```
// explicit accumulator, aka tail-recursion
t.s=(o="")=>(i=t.o())?t.s(o+i+","):o
// implicit accumulator, shorter, saves 15 bytes from OP's code
t.s=_=>(i=t.o())?i+","+t.s():""

```

### Free commas

`i+","+t.s()` can be shortened to `i+[,t.s()]`, saving 1 byte.

## Shortening the rest

### Initialize the second parameter of `t.e` to `h`

The function `t.e` is using `(l||h)` several times, just to handle the initial call. JS's default argument is very permissive, so we can do this:

```
// instead of
t.e=(i,l)=>h=(l||h)==E?[i,E]:[(l||h)[0],t.e(i,(l||h)[1])];
// do this
t.e=(i,l=h)=>h=l==E?[i,E]:[l[0],t.e(i,l[1])];

```

### Simplify base case

Instead of `E=[N,N]`, simply `E=[]` works too. This has several golfing opportunities regarding string coercion:

* `h==E` is equivalent to `h==[]`, and `[]` coerces to `""`. Anything that stringifies into something other than `""` is greater than `E`, so we can rewrite `h==E?A:B` into `h>E?B:A`.
* `h` is now a linked list where `3::2::1::nil` looks like `[3,[2,[1,[]]]]`, which exactly stringifies into `"3,2,1,"`. So we can simply coerce `h` to string: `t.s=_=>h+""`, or even better, `t.s=_=>h+E`.

### Array unpacking

We can slightly do better here too:

```
// instead of
t.o=_=>h>E?h[+!(h=h[1])]:N;
// do this
t.o=_=>h>E?([a,h]=h,a):N;

```

And this also applies to `t.e`:

```
// instead of this
t.e=(i,l=h)=>h=l>E?[l[0],t.e(i,l[1])]:[i,E];
// do this
t.e=(i,[a,l]=h)=>h=l?[a,t.e(i,l)]:[i,E];

```

I chose `l?` because whenever `h` is nonempty, `l` is a reference so it always evaluates to true. If `h` is empty, both `a` and `l` become `undefined`.

Side note: I found that the OP's code actually works with falsy list items, because the only real comparison is `h==E`, that is, comparing ~~stringification~~ reference of whole array. Whatever `E` is, `h==E` cannot be true if the list `h` has at least one item, since ~~its string will have at least one more comma than `E`'s~~ the reference becomes different.

## Final result, <sub>~~125~~</sub> 121 bytes

```
function L(){h=E=[];t=this;t.u=i=>h=[i,h];t.o=_=>h>E?([a,h]=h,a):null;t.e=(i,[a,l]=h)=>h=l?[a,t.e(i,l)]:[i,E];t.s=_=>h+E}

```

Try it online!
> 5 votes

---
Tags: code-golf, tips, javascript
---


# Question
Title: How many ways can given subsequence occur in given sequence?
Let me know if this task has already been posed. I haven't found it when I looked.

---

### Input

* ***master sequence \\$\ X = x\_1\dots x\_n\\$***: sequence of characters, eg. \\$\rm international\\$
* ***subsequence \\$\ Y = y\_1\dots y\_m\\$***: sequence of characters, eg. \\$\rm intl\\$

### Output

Number of possible mappings \\$\mu: \[1\dots m\] \rightarrow \[1\dots n\]\\$ of positions in subsequence to positions in the master sequence, such that for all \\$j\in\[1\ldots m\]\\$:

1. \\$y\_j = x\_{\mu(j)}\\$, viz. an occurrence of a character in the subsequence maps to an occurrence of the same character in the master sequence
2. \\$\forall\ i \lt j:\ \mu(i) \lt \mu(j)\\$, viz. the mapping preserves mutual position of character occurrences.

In the example above, there are 3 possible mappings:

* \\$\rm\underline{int}ernationa\underline{l}\\$
* \\$\rm\underline{in}terna\underline{t}iona\underline{l}\\$
* \\$\rm\underline{i}nter\underline{n}a\underline{t}iona\underline{l}\\$

### Rules

Lowest average asymptotic time complexity with respect to \\$n+m\\$ wins.

If it helps you, you can assume the input is a sequence of bytes (values 0-255).

### Test cases

```
master sequence, subsequence -> number of possible mappings
international, intl -> 3
aaabbb, ab -> 9
aaabbb, aabb -> 9
only one, onl -> 1
none, en -> 0

```

# Answer
# Ruby, \\$\mathcal{O}(nm)\\$

I think I got the analysis for this right. Should be \\$\mathcal{O}(nm)\\$ because for each of the \\$n\\$ characters in the master sequence, it goes through at most \\$m\\$ steps to check each character of the subsequence (if they are all the same character). It's also optimized to try to be \\$\Omega(n+m)\\$ best case complexity, which occurs if all the characters in the subsequence are unique.

```
def submap master, sub
  subIndex = Hash.new{ |hash, key| hash[key] = [] }

  sub.chars.map.with_index do |c, i|
    subIndex[c] << i
  end

  subCount = [0] * sub.length

  master.chars do |c|
    indices = subIndex[c]
    indices.reverse_each do |i|
      subCount[i] += i > 0 ? subCount[i-1] : 1
    end
  end
  return subCount[-1]
end

```

Try it online!

## Explanation

Define the function \\$f(X\_i,Y\_j)\\$ as the number of occurrences of the subsequence \\$Y\_j=y\_1...y\_j\\$ in the sequence \\$X\_i=x\_1...x\_i\\$. In this situation, it can be shown that

$$f(X\_i,Y\_j)=\begin{cases} f(X\_{i-1},Y\_j) & \text{if } x\_i\ne y\_j,i \> 1\\ 0 & \text{if } x\_i\ne y\_j, i=1\\ f(X\_{i-1},Y\_j)+f(X\_{i-1},Y\_{j-1}) & \text{if } x\_i=y\_j,j \> 1\\ \sum\_{k=1}^i \[x\_k = y\_j\] & \text{if }j=1 \end{cases}$$

That is, if the subsequence is 1 character long, count how many there are in the master sequence. If \\$x\_i=y\_j\\$, add the number of times the subsequence \\$Y\_{j-1}\\$ occurred previously in \\$X\_{i-1}\\$, as that is the number of times you can find this subsequence using this specific position \\$x\_i\\$. Otherwise, ignore the character and only look at the sequence before \\$x\_i\\$, that is, \\$X\_{i-1}\\$.

With that, we write our code.

```
def submap master, sub
  # Minor optimization: Map the characters to indices. This way, we don't have
  # to go through the subsequence every time, which gives the best case scenario
  # a complexity of O(n+m) if all characters in Y are unique.
  subIndex = Hash.new{ |hash, key| hash[key] = [] }
                                        # Initialize hash with default value []
  sub.chars.map.with_index do |c, i|    # For each character in Y
    subIndex[c] << i                    # Add the index to the hash for that char.
  end

  subCount = [0] * sub.length           # Initialize the previous results f(X, Y_j).

  master.chars do |c|                   # For each character in X
    indices = subIndex[c]               # Look up the indices for that character
    indices.reverse_each do |i|         # For each index (in reverse order)
      subCount[i] += i > 0 ? subCount[i-1] : 1
                                        # Increment f(X, Y_j) by f(X, Y_{j-1}).
    end
  end
  return subCount[-1]                   # Return f(X, Y_m).
end

```
> 4 votes

# Answer
# Python 3, \\$O(n^m)\\$

```
def submappings(master, sub):
  if len(sub) == 0:
    return 1
  count = 0
  for i, c in enumerate(master[:len(master)-len(sub)+1]):
    if c == sub[0]:
      count += submappings(master[i+1:], sub[1:])
  return count

```

Try it online!

For each character in the subsequence, it looks through (what's left of) the master sequence for it, and moves onto the next one, counting how many combinations there are.

I've made a version that also counts the number of comparisons.

```
def submappings(master, sub):
  if len(sub) == 0:
    return 1, 0
  count, ops = 0, 0
  for i, c in enumerate(master[:len(master)-len(sub)+1]):
    ops += 1
    if c == sub[0]:
      rec = submappings(master[i+1:], sub[1:])
      count += rec[0]
      ops += rec[1]
  return count, ops

```

Try it online!
> 1 votes

---
Tags: subsequence, fastest-algorithm
---


title: Split a byte array into a bit array

text:
# Question
Title: Split a byte array into a bit array
Write a function that when given a buffer `b` (1 - 104857600 bytes long) and a number of bits `n` (1 \<= n \<= 64), splits the buffer into chunks of `n` bits. Right-pad the last chunk with `0`s up to `n` bits.

e.g.

Given the buffer `b = "f0oBaR"` or equivalently `[102,48,111,66,97,82]` and `n = 5`, return

```
[12, 24, 24, 6, 30, 16, 19, 1, 10, 8]

```

This is because the above buffer, when represented as binary looks like:

```
01100110 00110000 01101111 01000010 01100001 01010010

```

And when re-grouped into 5s looks like:

```
01100 11000 11000 00110 11110 10000 10011 00001 01010 010[00]

```

Which when converted back into decimal gives the answer.

## Notes

* You may use whatever data type makes the most sense in your language to represent the buffer. In PHP you'd probably use a string, in Node you might want to use a Buffer
    + If you use a string to represent the buffer, assume it's ASCII for the char -\> int conversion
    + You may use an array of ints (0-255) for input if you prefer
* Return value must be an array or list of ints

## Test Cases

```
> b = "Hello World", n = 50
318401791769729, 412278856237056

> b = [1,2,3,4,5], n = 1
0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1

> b = "codegolf", n = 32
1668244581, 1735355494

> b = "codegolf" n = 64
7165055918859578470

> b = "codegolf" n = 7
49, 91, 108, 70, 43, 29, 94, 108, 51, 0

> b = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque vel est eu velit lacinia iaculis. Nulla facilisi. Mauris vitae elit sapien. Nullam odio nulla, laoreet at lorem eu, elementum ultricies libero. Praesent orci elit, sodales consectetur magna eget, pulvinar eleifend mi. Ut euismod leo ut tortor ultrices blandit. Praesent dapibus tincidunt velit vitae viverra. Nam posuere dui quis ipsum iaculis, quis tristique nisl tincidunt. Aliquam ac ligula a diam congue tempus sit amet quis nisl. Nam lacinia ante vitae leo efficitur, eu tincidunt metus condimentum. Cras euismod quis quam vitae imperdiet. Ut at est turpis.", n = 16
19567, 29285, 27936, 26992, 29557, 27936, 25711, 27759, 29216, 29545, 29728, 24941, 25972, 11296, 25455, 28275, 25955, 29797, 29813, 29216, 24932, 26992, 26995, 25449, 28263, 8293, 27753, 29742, 8272, 25964, 27749, 28276, 25971, 29045, 25888, 30309, 27680, 25971, 29728, 25973, 8310, 25964, 26996, 8300, 24931, 26990, 26977, 8297, 24931, 30060, 26995, 11808, 20085, 27756, 24864, 26209, 25449, 27753, 29545, 11808, 19809, 30066, 26995, 8310, 26996, 24933, 8293, 27753, 29728, 29537, 28777, 25966, 11808, 20085, 27756, 24941, 8303, 25705, 28448, 28277, 27756, 24876, 8300, 24943, 29285, 25972, 8289, 29728, 27759, 29285, 27936, 25973, 11296, 25964, 25965, 25966, 29813, 27936, 30060, 29810, 26979, 26981, 29472, 27753, 25189, 29295, 11808, 20594, 24933, 29541, 28276, 8303, 29283, 26912, 25964, 26996, 11296, 29551, 25697, 27749, 29472, 25455, 28275, 25955, 29797, 29813, 29216, 28001, 26478, 24864, 25959, 25972, 11296, 28789, 27766, 26990, 24946, 8293, 27749, 26982, 25966, 25632, 28009, 11808, 21876, 8293, 30057, 29549, 28516, 8300, 25967, 8309, 29728, 29807, 29300, 28530, 8309, 27764, 29289, 25445, 29472, 25196, 24942, 25705, 29742, 8272, 29281, 25971, 25966, 29728, 25697, 28777, 25205, 29472, 29801, 28259, 26980, 30062, 29728, 30309, 27753, 29728, 30313, 29793, 25888, 30313, 30309, 29298, 24878, 8270, 24941, 8304, 28531, 30053, 29285, 8292, 30057, 8305, 30057, 29472, 26992, 29557, 27936, 26977, 25461, 27753, 29484, 8305, 30057, 29472, 29810, 26995, 29801, 29045, 25888, 28265, 29548, 8308, 26990, 25449, 25717, 28276, 11808, 16748, 26993, 30049, 27936, 24931, 8300, 26983, 30060, 24864, 24864, 25705, 24941, 8291, 28526, 26485, 25888, 29797, 28016, 30067, 8307, 26996, 8289, 28005, 29728, 29045, 26995, 8302, 26995, 27694, 8270, 24941, 8300, 24931, 26990, 26977, 8289, 28276, 25888, 30313, 29793, 25888, 27749, 28448, 25958, 26217, 25449, 29813, 29228, 8293, 29984, 29801, 28259, 26980, 30062, 29728, 28005, 29813, 29472, 25455, 28260, 26989, 25966, 29813, 27950, 8259, 29281, 29472, 25973, 26995, 28015, 25632, 29045, 26995, 8305, 30049, 27936, 30313, 29793, 25888, 26989, 28773, 29284, 26981, 29742, 8277, 29728, 24948, 8293, 29556, 8308, 30066, 28777, 29486

> b = [2,31,73,127,179,233], n = 8
2, 31, 73, 127, 179, 233

```

# Answer
> 15 votes
## Pyth, ~~18~~ 17 bytes

```
iR2c.[t.B+C1z\0QQ

```

Thanks to @lirtosiast for a byte!

```
            z      get input
         +C1       prepend a 0x01 to prevent leading zeroes from disappearing
       .B          convert to binary string
      t            remove the leading 1 from ^^
    .[       \0Q   pad right with zeroes to multiple of second input
   c            Q  get chunks/slices of length second input
iR2                map(x: int(x, 2))

```

# Answer
> 13 votes
# Jelly, 13 bytes

```
1;ḅ256æ«BḊsḄṖ

```

This takes the input as a list of integers. Try it online!

### How it works

```
1;ḅ256æ«BḊsḄṖ  Main link. Arguments: A (list), n (integer)

1;             Prepend 1 to A.
  ḅ256         Convert from base 256 to integer.
      æ«       Bitshift the result n units to the left.
        B      Convert to binary.
         Ḋ     Discard the first binary digit (corresponds to prepended 1).
          s    Split into chunks of length n.
           Ḅ   Convert each chunk from binary to integer.
            Ṗ  Discard the last integer (corresponds to bitshift/padding).

```

# Answer
> 5 votes
# Julia, 117 bytes

```
f(x,n,b=join(map(i->bin(i,8),x)),d=endof,z=rpad(b,d(b)+d(b)%n,0))=map(i->parse(Int,i,2),[z[i:i+n-1]for i=1:n:d(z)-n])

```

This is a function that accepts an integer array and an integer and returns an integer array. It's an exercise in function argument abuse.

Ungolfed:

```
function f(x::Array{Int,1},                  # Input array
           n::Int,                           # Input integer
           b = join(map(i -> bin(i, 8), x)), # `x` joined as a binary string
           d = endof,                        # Store the `endof` function
           z = rpad(b, d(b) + d(b) % n, 0))  # `b` padded to a multiple of n

    # Parse out the integers in base 2
    map(i -> parse(Int, i, 2), [z[i:i+n-1] for i = 1:n:d(z)-n])
end

```

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

```
f=(a,n,b=0,t=0,r=[])=>b<n?a.length?f(a.slice(1),n,b+8,t*256+a[0],r):b?[...r,t<<n-b]:r:f(a,n,b-=n,t&(1<<b)-1,[...r,t>>b])

```

Recursive bit twiddling on integer arrays. Ungolfed:

```
function bits(array, nbits) {
    var count = 0;
    var total = 0;
    var result = [];
    for (;;) {
        if (nbits <= count) {
            // We have enough bits to be able to add to the result
            count -= nbits;
            result.push(total >> count);
            total &= (1 << count) - 1;
        } else if (array.length) {
            // Grab the next 8 bits from the array element
            count += 8;
            total <<= 8;
            total += array.shift();
        } else {
            // Deal with any leftover bits
            if (count) result.push(total << nbits - count);
            return result;
        }
    }
}

```

# Answer
> 5 votes
## Python 3, 102 bytes

```
j=''.join
lambda s,n:[int(j(k),2)for k in zip(*[iter(j([bin(i)[2:].zfill(8)for i in s+[0]]))]*n)][:-1]

```

use iter trick to group string

* `s`: the input string/buffer
* `n`: the number of bits in each splitted chunk

## Results

```
>>> f([102,48,111,66,97,82],4)
[6, 6, 3, 0, 6, 15, 4, 2, 6, 1, 5, 2, 0]

>>> f([102,48,111,66,97,82],5)
[12, 24, 24, 6, 30, 16, 19, 1, 10, 8]

>>> f([102,48,111,66,97,82],6)
[25, 35, 1, 47, 16, 38, 5, 18]

>>> f([102,48,111,66,97,82],8)
[102, 48, 111, 66, 97, 82]

```

# Answer
> 4 votes
# Ruby, 114 bytes

```
->s,n{a=s.bytes.map{|b|b.to_s(2).rjust 8,?0}.join.split""
r=[]
r<<a.shift(n).join.ljust(n,?0).to_i(2)while a[0]
r}

```

Slightly cleaner:

```
f = -> str, num {
    arr = str.bytes.map {|byte|
        byte.to_s(2).rjust(8, "0")
    }.join.split("")
    result = []
    while arr.size > 0
        result << arr.shift(num).join.ljust(num, "0").to_i(2)
    end
    result
}

puts f["f0oBaR", 5]

```

# Answer
> 4 votes
# Perl 6, ~~93~~ 68 bytes

```
{@^a».&{sprintf "%08b",$_}.join.comb($^b)».&{:2($_~0 x$b-.chars)}}

```

# Answer
> 3 votes
## PHP, ~~262~~ ~~217~~ 189 bytes

```
function f($b,$n){$M='array_map';return$M('bindec',$M(function($x)use($n){return str_pad($x,$n,0);},str_split(implode('',$M(function($s){return str_pad($s,8,0,0);},$M('decbin',$b))),$n)));}

```

(updated with tips from Ismael Miguel)

Formatted for readability:

```
function f($b, $n) {
    $M = 'array_map';
    return $M('bindec', $M(function ($x) use ($n) {
        return str_pad($x, $n, 0);
    }, str_split(implode('', $M(function ($s) {
        return str_pad($s, 8, 0, 0);
    }, $M('decbin', $b))), $n)));
}

```

Example:

```
> implode(', ',f(array_map('ord',str_split('f0oBaR')),5));
"12, 24, 24, 6, 30, 16, 19, 1, 10, 8"

```

# Answer
> 3 votes
# JavaScript (ES6) 104

Iterative bit by bit fiddling,

**Edit** 5 bytes save thx @Neil

```
(s,g,c=g,t=0)=>(s.map(x=>{for(i=8;i--;--c||(s.push(t),c=g,t=0))t+=t+(x>>i)%2},s=[]),c-g&&s.push(t<<c),s)

```

*Less golfed*

```
(
 // parameters
 s, // byte source array
 g, // output bit group size
 // default parameters used as locals
 c = g, // output bit counter
 t = 0  // temp bit accumulator
) => (
  s.map(x =>
    { // for each byte in s
      for(i = 8; // loop for 8 bits
        i--;
        )
        // loop body
        t += t + (x>>i) % 2, // shift t to left and add next bit
        --c // decrement c,if c==0 add bit group to output and reset count and accumulator
          ||(s.push(t), c=g, t=0)
    },
    s=[] // init output, reusing s to avoid wasting another global
  ),
  c-g && s.push(t<<c), // add remaining bits, if any
  s // return result
)

```

**Test**

```
f=(s,g,c=g,t=0)=>(s.map(x=>{for(i=8;i--;--c||(s.push(t),c=g,t=0))t+=t+(x>>i)%2},s=[]),c-g&&s.push(t<<c),s)

function test()
{
  var a = A.value.match(/\d+/g)||[]
  var g = +G.value
  var r = f(a,g)

  O.textContent = r
  K.innerHTML = a.map(x=>`<i>${(256- -x).toString(2).slice(-8)}</i>`).join``
  + '\n'+ r.map(x=>`<i>${(256*256*256*256+x).toString(2).slice(-g)}</i>`).join``
}

test()
```

```
#A { width: 50% }
#G { width: 5% }
i:nth-child(even) { color: #00c }
i:nth-child(odd) { color: #c00 }
```

```
Input array <input id=A value="102,48,111,66,97,82">
Group by bits <input id=G value=5> (up to 32)<br>
Output <button onclick="test()">-></button>
<span id=O></span>
<pre id=K></pre>
```

# Answer
> 3 votes
# CJam, 30 bytes

```
{_@{2b8 0e[}%e_0a@*+/-1<{2b}%}

```

Try it online!

This is an unnamed block which expects the int buffer and the amount of chunks on the stack and leaves the result on the stack.

Decided to give CJam a try. Only took me 2 hours to get it done ^^ This is probably too long, suggestions are very welcome!

## Explanation

```
_         e# duplicate the chunk count
@         e# rotate stack, array now on top and chunk counts on the bottom
{         e# start a new block
 2b       e# convert to binary
 8 0e[    e# add zeros on the left, so the binary is 8 bits
}         e# end previous block
%         e# apply this block to each array-element (map)
e_        e# flatten array
0a        e# push an array with a single zero to the stack
@         e# rotate stack, stack contain now n [array] [0] n
*         e# repeat the array [0] n times
+         e# concat the two array
/         e# split into chunks of length n, now the stacks only contains the array
-1<       e# discard the last chunk
{2b}%     e# convert every chunk back to decimal

```

# Answer
> 3 votes
# Ruby, 66 bytes

```
->s,n{(s.unpack('B*')[0]+?0*~-n).scan(/.{#{n}}/).map{|x|x.to_i 2}}

```

Try it online!

Takes input buffer as a string, so that a few test strings were constructed directly in the footer to avoid unprintables.

# Answer
> 2 votes
## Java, ~~313~~ ~~306~~ 322 bytes

I hope this beats PHP... And nope. Stupid long function names.

-7 thanks to @quartata for getting rid of public +16 to fix an error when the split was exact, thanks to @TheCoder for catching it

```
int[] f(String b,int s){int i=0,o[]=new int[(int)Math.ceil(b.length()*8.0/s)],a=0;String x="",t;for(char c:b.toCharArray()){t=Integer.toString(c,2);while(t.length()<8)t="0"+t;x+=t;a+=8;while(a>=s){o[i++]=Integer.parseInt(x.substring(0,s),2);x=x.substring(s,a);a-=s;}}while(a++<s)x+="0";o[i]=Integer.parseInt(x,2);return o;}

```

# Answer
> 2 votes
# J, 24 bytes

```
[:#.-@[>\;@(_8:{."1#:@])

```

This is an anonymous function, which takes `n` as its left argument and `b` as numbers as its right argument.

Test:

```
      5 ([:#.-@[>\;@(_8:{."1#:@])) 102 48 111 66 97 82
12 24 24 6 30 16 19 1 10 8

```

Explanation:

```
[:#.-@[>\;@(_8:{."1#:@])

                   #:@]   NB. Convert each number in `b` to bits
            _8:{."1       NB. Take the last 8 items for each
                          NB.    (padding with zeroes at the front)
         ;@               NB. Make a list of all the bits
    -@[                   NB. Negate `n`
                          NB. (\ gives non-overlapping infixes if [<0)
       >\                 NB. Get non-overlapping n-sized infixes
 [:#.                     NB. Convert those back to decimal

```

# Answer
> 2 votes
## Haskell, ~~112~~ 109 bytes

```
import Data.Digits
import Data.Lists
n#x=unDigits 2.take n.(++[0,0..])<$>chunksOf n(tail.digits 2.(+256)=<<x)

```

Usage example: `5 # [102,48,111,66,97,82]` -\> `[12,24,24,6,30,16,19,1,10,8]`.

How it works

```
import Data.Digits                  -- needed for base 2 conversion
import Data.Lists                   -- needed for "chunksOf", i.e. splitting in
                                    -- sublists of length n

           (                  =<<x) -- map over the input list and combine the
                                    -- results into a single list:
            tail.digits 2.(+256)    -- convert to base two with exactly 8 digits
         chunksOf n                 -- split into chunks of length n
       <$>                          -- convert every chunk (<$> is map)
    take n.(++[0,0..])              -- pad with 0s
unDigits 2                          -- convert from base 2

```

# Answer
> 2 votes
# MATL, 9 bytes

```
8&B!we!XB

```

Try it online!

Takes input `b` as a string delimited by `''` or as an array of comma-separated values like `[102, 48, 111]`, then `n`.

```
8           # push 8
&B          # implicitly take input b, and use 2-element convert to binary
            # to push a binary matrix of 8 bits
!           # transpose, so each column represents an input
w           # implicitly take input n and swap it with binary matrix to top of stack
e           # reshape into n rows, padding with zeros at end
            # this matrix will have each column as an n-bit integer
!           # transpose, so each row is now the n-bit integer
XB          # convert each row to decimal
            # implicit output

```

# Answer
> 2 votes
# Perl 5 `-nl -MData::Dump=pp` , 96 bytes

```
$}=$_;pp map{$_=sprintf"%-$}s",$_;y/ /0/;oct"0b$_"}(join'',map{sprintf"%08b",$_}<>)=~m/.{1,$_}/g

```

Try it online!

Requires the `Data::Dump` module.

Takes `n` on the first line of input and the numbers on each line after that.

Outputs to STDERR (the Debug field on TIO).

Deparsed and tidied:

```
BEGIN { $/ = "\n"; $\ = "\n"; }
use Data::Dump ( split( /,/, 'pp', 0 ) );
LINE: while ( defined( $_ = readline ARGV ) ) {
    chomp $_;
    $} = $_;
    pp(
        map( {
                $_ = sprintf( "%-$}s", $_ );
                tr/ /0/;
                oct "0b$_";
            } join( '', map( { sprintf '%08b', $_; } readline ARGV ) ) =~
              /.{1,$_}/g )
    );
}

```

# Answer
> 1 votes
# Powershell 146 bytes

```
param([int[]][char[]]$b,$n)-join($b|%{[convert]::ToString($_,2).PadLeft(8,"0")})-split"(.{$n})"|?{$_}|%{[convert]::ToInt32($_.PadRight($n,"0"),2)}

```

---

Take in the buffer and convert it to a char array and then an integer array. For each of those convert to binary, pad the entries with 0's where needed, and join as one large string. Split that string on *n* characters and drop the blanks that are created. Each element from the split is padded (only the last element really would need it) and converted back into an integer. Output is an array

# Answer
> 1 votes
# Python 3.5 - 312 292 bytes:

```
def d(a, b):
    o=[];o+=([str(bin(g)).lstrip('0b')if str(type(g))=="<class 'int'>"else str(bin(ord(g))).lstrip('0b')for g in a]);n=[''.join(o)[i:i+b]for i in range(0,len(''.join(o)),b)];v=[]
    for t in n:
        if len(t)!=b:n[n.index(t)]=str(t)+'0'*(b-len(t))
    v+=([int(str(f),2)for f in n])
    return v

```

Although this may be long, this is, in my knowledge, is the shortest way to accept both functions and arrays without errors, and still being able to retain *some* accuracy in Python 3.5.

# Answer
> 1 votes
## Java, ~~253~~ 247 bytes

**Golfed**

```
int i,l,a[];Integer I;String f="";int[]c(String s,int n){for(char c:s.toCharArray())f+=f.format("%08d",I.parseInt(I.toString(c, 2)));while(((l=f.length())%n)>0)f+="0";for(a=new int[l=l/n];i<l;)a[i]=I.parseInt(f.substring(i*n,i++*n+n),2);return a;}

```

**UnGolfed**

```
int i,l,a[];
Integer I;
String f="";
int[]c(String s,int n) {
    for(char c:s.toCharArray())
        f+=f.format("%08d",I.parseInt(I.toString(c,2)));
    while(((l=f.length())%n)>0)
        f+="0";
    for(a=new int[l=l/n];i<l;)
        a[i]=I.parseInt(f.substring(i*n,i++*n+n),2);
    return a;
}

```

# Answer
> 1 votes
# Jelly, 13 bytes

```
+256BḊ€Ẏsz0ZḄ

```

Try it online!

Different from Dennis's answer.

Note: The input is actually a list of non-negative integers, but the TIO link eases the pain for you, and accepts either such a list or a string.

# Answer
> 1 votes
# Stax, 12 bytes

```
è■àåk┘K¥xk└╣

```

Run and debug it

This isn't a function as specified in the challenge, but a program, since stax doesn't support functions. It supports input of strings or array literals.

# Answer
> 1 votes
# Python 2, 101 bytes

```
lambda a,n:[int(''.join(bin(x+256)[3:]for x in a+[0]*n)[n*i:][:n],2)for i in range((len(a)*8-1)/n+1)]

```

Try it online!

# Answer
> 1 votes
# Dyalog APL, 36 bytes

```
{2∘⊥¨↓A⍴(×/A←⍺,⍨⌈⍺÷⍨8×≢⍵)↑∊↓⍉⍵⊤⍨8/2}

```

Try it online!

This probably could be golfed down more.

# Answer
> 1 votes
# Elixir, ~~63~~ 60 bytes

```
&(s=&2-1)&&for<<x::size(&2)<-<<"#{&1}",0::size(s)>> >>,do: x

```

Try it online!

Takes input as Elixir binary, outputs a list of integers.

This code makes use of Elixir bitstring generator comprehension to chunk input binary `&1` into bit blocks of size provided as argument `&2`. To account for any leftover bits at the end, we pad the binary with `&2 - 1` zero bits. Here is also the place where some unwanted verbosity kicks in: Elixir complains if we don't explicitly declare `&1` as bitstring, and it also doesn't support expressions in `size(...)`, hence the need for an extra variable assignment.

Easter egg: in the footer, replace `IO.inspect` with `IO.puts`, and our function magically "translates" Lorem ipsum from Latin to Chinese - Try it online!

# Answer
> 1 votes
# PHP, ~~135~~ ~~129~~ 124 bytes

```
function($b,$n){foreach($b as$c)$a.=sprintf('%08b',$c);foreach(str_split($a,$n)as$s)$d[]=bindec(str_pad($s,$n,0));return$d;}

```

Try it online!

Implemented as a function, input buffer is an array of ints and returns an array of ints.

**Output**

```
> b = "f0oBaR", n = 5
[12,24,24,6,30,16,19,1,10,8]

> b = "Hello World", n = 50
[318401791769729,412278856237056]

> b = [1,2,3,4,5], n = 1
[0,0,0,0,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,0,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,1,0,1]

```

Verify all test cases

# Answer
> 1 votes
# Japt, 16 bytes

After a long day of meetings, it feels like I've forgotten how to golf! Will play around with this on the train home later, see if I can improve on it.

```
c_¤ùT8ÃòV úTV mÍ

```

Try it

# Answer
> 0 votes
# APL(NARS), 471 chars, 942 bytes

```
TH←{v←↑⍴⍴⍵⋄v>2:64⋄v=2:32⋄(v=1)∧''≡0↑⍵:20⋄''≡0↑⍵:4⋄v=1:16⋄⍵≢+⍵:8⋄⍵=⌈⍵:2⋄1}
TV←{x←TH¨⍵⋄k←↑x⋄t←↑⍴⍵⋄t=+/x=2:2⋄t=+/x≤2:1⋄(k≤8)∧⍬≡x∼k:k⋄0}
T←{v←↑⍴⍴⍵⋄v>2:64+TV⍵⋄v=2:32+TV⍵⋄(v=1)∧''≡0↑⍵:20⋄''≡0↑⍵:4⋄v=1:16+TV⍵⋄⍵≢+⍵:8⋄⍵=⌈⍵:2⋄1}
RI←{t←T⍵⋄(t≠1)∧(t≠2)∧(t≠17)∧(t≠18):0⋄∧/((1⊃⍺)≤⍵)∧⍵≤(2⊃⍺)}
B←{(8⍴2)⊤⍵}⋄C←{¯1+⎕AV⍳⍵}⋄f←{t←T⍵⋄(0 255 RI⍵)∧18=t:∊B¨⍵⋄(0 255 RI x←C¨⍵)∧20=t:∊B¨x⋄,¯1}⋄W←{((↑⍴⍵)⍴2)⊥⍵}
q←{(∼1 64 RI,⍺)∨2≠T⍺:,¯1⋄x←f⍵⋄¯1=↑x:,¯1⋄t←↑⍴x⋄k←(⍺-m)×0≠m←⍺∣t⋄W⍉((t+k)÷⍺)⍺⍴(((t⍴1),k⍴0)\x)}

```

commented code and test:

```
  ⍝TH⍵ return type its argument
  TH←{v←↑⍴⍴⍵⋄v>2:64⋄v=2:32⋄(v=1)∧''≡0↑⍵:20⋄''≡0↑⍵:4⋄v=1:16⋄⍵≢+⍵:8⋄⍵=⌈⍵:2⋄1}
  ⍝ TV⍵ check if type each element of array ⍵ is the same and basic
  ⍝ (float(int and float too),int,char,complex) and return its number (or 0 if it is not basic)
  TV←{x←TH¨⍵⋄k←↑x⋄t←↑⍴⍵⋄t=+/x=2:2⋄t=+/x≤2:1⋄(k≤8)∧⍬≡x∼k:k⋄0}
  ⍝ T⍵ return the type of ⍵ [it would be ok if ⍵ is not a function]
  ⍝|1 Float|2 Int|4 Char|8 Complex,Quaternion or Oction|16 List|32 Matrix|64 Tensor
  ⍝|17 List Float|18 List Int|20 List Char=string|etc
  T←{v←↑⍴⍴⍵⋄v>2:64+TV⍵⋄v=2:32+TV⍵⋄(v=1)∧''≡0↑⍵:20⋄''≡0↑⍵:4⋄v=1:16+TV⍵⋄⍵≢+⍵:8⋄⍵=⌈⍵:2⋄1}
  ⍝ ⍺RI⍵ check if the numeric array ⍵ has elements in [1⊃⍺ 2⊃⍺]; if type is not ok return 0(false)
  RI←{t←T⍵⋄(t≠1)∧(t≠2)∧(t≠17)∧(t≠18):0⋄∧/((1⊃⍺)≤⍵)∧⍵≤(2⊃⍺)}

  B←{(8⍴2)⊤⍵}   ⍝ from decimal to binary of element 0..255
  C←{¯1+⎕AV⍳⍵}   ⍝ return the number of char that is in array AV seems the ascii number
  ⍝ f⍵ with ⍵ List int element in 0..255 or String with numeric element 0..255
  ⍝ return the corrispondence disclosed binary array
  f←{t←T⍵⋄(0 255 RI⍵)∧18=t:∊B¨⍵⋄(0 255 RI x←C¨⍵)∧20=t:∊B¨x⋄,¯1}
  W←{((↑⍴⍵)⍴2)⊥⍵} ⍝ from list of binary digit to decimal
  ⍝ the function for the exercise
  q←{(∼1 64 RI,⍺)∨2≠T⍺:,¯1⋄x←f⍵⋄¯1=↑x:,¯1⋄t←↑⍴x⋄k←(⍺-m)×0≠m←⍺∣t⋄W⍉((t+k)÷⍺)⍺⍴(((t⍴1),k⍴0)\x)}

  5 q    'f0oBaR'
12 24 24 6 30 16 19 1 10 8
  50 q "Hello World"
318401791769729 412278856237056
  1  q 1 2 3 4 5
0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 1
  32 q "codegolf"
1668244581 1735355494
  7 q "codegolf"
49 91 108 70 43 29 94 108 51 0
  8 q 2 31 73 127 179 233
2 31 73 127 179 233
  64 q 2 31 73 127 179 233
1.529217252E17
  65 q 2 31 73 127 179 233
¯1
  0 q 2 31 73 127 179 233
¯1
  23 q '123'
1612057 4194304
  23 q '123∞'
¯1
  23 q '1' 2 3
¯1
  23 q 2 3.3
¯1
  23 q 2
¯1
  23 q '1'
¯1
  23 q ,2
65536
  23 q ,'1'
1605632

```

---
Tags: code-golf, bitwise
---


title: Is this board Latin-style?

text:
# Question
Title: Is this board Latin-style?
Inspired by *Flow Fit: Sudoku*, a brand-new mobile puzzle game (as of Nov 2019).

## Background

A **Latin square** is a square grid of side length \\$ n \\$ filled with \\$ n \\$ different symbols, where each row and column contains each symbol exactly once.

Let's define a **row** (resp. a **column**) as a **maximally consecutive group of cells** in horizontal (resp. vertical) direction. For example, the following board (`O` is a cell, `-` is a hole) has 8 rows and 8 columns in total:

```
The board    |  Rows         |  Columns
O O O O O O  |  A A A A A A  |  A B C E G H
O O O O O O  |  B B B B B B  |  A B C E G H
O O - O O O  |  C C - D D D  |  A B - E G H
O O O - O O  |  E E E - F F  |  A B D - G H
O O O O O O  |  G G G G G G  |  A B D F G H
O O O O O O  |  H H H H H H  |  A B D F G H

```

Then, place the numbers \\$ 1, \cdots, k \\$ exactly once on each row and column, where \\$ k \\$ is the length of that row or column. For the board above, here is one solution:

```
3 4 1 2 5 6
4 3 2 1 6 5
1 2 - 3 1 2
2 1 3 - 2 1
5 6 1 2 3 4
6 5 2 1 4 3

```

A board is **Latin-style** if such a placement is possible.

Note that a row/column of size 1 is still a row/column, and therefore it can only have a single 1.

## Challenge

Given a grid, **determine if it is Latin-style**, i.e. it is possible to place numbers on the grid so that each row/column of length \\$ k \\$ contains each of the numbers \\$ 1, \cdots, k \\$ exactly once.

### Example Latin-style boards

```
O O O O O
- O O O O
- - O O O
- - - O O
- - - - O

```

```
- O O O -
O O O O O
O O O O O
O O O O O
- O O O -

```

```
- - O O O
- O O O O
O O O O O
O O O O -
O O O - -

```

```
O O - - O O
O O O O O O
- O O O O -
- O O O O -
O O O O O O
O O - - O O

```

```
O O O - O O O O
O O O O O O O O
O O O O O O O O
O O O O O O O -
- O O O O O O O
O O O O O O O O
O O O O O O O O
O O O O - O O O

```

```
O O O - O
O O - O O
O - O O O

```

```
- - O - -
- O O O -
O O - O O
- O O O O
O O O - O

```

### Example non-Latin-style boards

```
- O -
O O O
- O -

```

```
O O O

```

```
O O - - -
O O - - -
O O - - -
O O O O O
O O O O O

```

```
O O O - -
O O O - -
O O O O O
- - O O O
- - O O O

```

```
- - - O O - -
- - O O O - -
O O O O O O -
O O O O O O O
- O O O O O O
- - O O O - -
- - O O - - -

```

```
O O - - - -
O O - O O O
O O - O O O

```

```
O O - - -
O O - - -
O O O - -
- - O O O
- - O O O

```

## Input and output

You can take the grid input in any reasonable way. The grid's bounding box can be non-square, and the grid may contain multiple connected components.

You can give the output in one of two ways:

* Truthy/falsy values following the language's convention
    + Swapping truthy/falsy is ~~not allowed~~ also allowed.
* One consistent value for true, another consistent value for false

## Scoring and winning criterion

The standard rules apply. The shortest code in bytes wins.

# Answer
# Jelly, 24 bytes

```
,ZµŒgaS$€F)Zṣ€0Ṣ<JƊ€€)FẸ

```

Try it online!

A monadic link taking as its argument the grid as a matrix with 1 representing squares needing a number and 0 representing the spacers. Returns 0 if the grid is Latin and 1 if not.

## Explanation

```
Main link, takes a matrix of 1s and 0s as its argument, z

,                         | Pair with:
 Z                        | - z transposed
  µ                       | Start a new monadic chain
                     )    | For each matrix (z and transpose(z)):
          )               | - For each row:
   Œg                     |   - Group runs of equal elements
       $€                 |   - For each group:
     a                    |     - And with:
      S                   |       - Sum of group
         F                |   - Flatten
           Z              | - Transpose
            ṣ€0           | - Split each at zeros
                  Ɗ€€     | - For each group:
               Ṣ<         |   - Check whether sorted group is less than:
                 J        |     - Sequence along group
                      F   | Finally, flatten
                       Ẹ  | And check if any group returned true

```

# Alternative in case true=true/false=false required:

## Jelly, 24 bytes

```
,ZµŒgaS$€F)Zṣ€0Ṣ_JƊ€€)AƑ

```

Try it online!
> 6 votes

# Answer
# Prolog (SWI) \+ CLPFD, 192 bytes

```
A/B:-transpose(A,B).
[]*[]*_*1*_.
[0|T]*[0|B]*_*1*_:-T*B*L*L*[].
[1|T]*[A|B]*L*C*Z:-all_distinct([A|Z]),A#>0,A#<L,R#=C-1,T*B*L*R*[A|Z].
[]-[].
[X|T]-[Y|B]:-X*Y*L*L*[],T-B.
+A:-A-B,A/T,B/U,T-U.

```

Try it online!

The main predicate is `+/1`.

### Verbose

```
t(A,B):-transpose(A,B).
h([],[],_,1,_).
h([0|T],[0|B],_,1,_):-h(T,B,L,L,[]).
h([1|T],[A|B],L,C,Z):-all_distinct([A|Z]),A#>0,A#<L,R#=C-1,h(T,B,L,R,[A|Z]).
q([],[]). q([X|T],[Y|B]):-h(X,Y,L,L,[]),q(T,B).
g(A):-q(A,B),t(A,T),t(B,U),q(T,U).

```

Try it online!

`g/1` takes the grid as a list of lists, each element being a 1 for a cell or a 0 for a hole. `q/2` takes a grid as the first argument and unifies the second argument with a solution of the grid. `h(A,B,L,L,[])` takes a row of this grid as A, and unifies a solution for the row to B, and `q/2` recursively calls `h/5` on each of its rows.

`h(A,B,L,C,Z)` has row A of the grid, a solution B, L is the length of the current length of 1s plus one so that the cells of B can be constrained to the exclusive range (1, L), C is the count of the remaining length so that L is unified to the length, and Z is the solution for the current contiguous sequence of cells so that `all_distinct/2` can be called. The end cases are stated as conditions so that these constraints are fulfilled.

Because this is Prolog, converting the main predicate to take two arguments, like `A+B` or `g(A,B)`, Prolog will unify the solutions with the variable B, thus also allowing you to see all available solutions. It can also generate valid grids, but running this makes Prolog list all grids with empty rows.
> 3 votes

# Answer
# , 169 bytes

```
function(x)any(unlist(lapply(1:2,function(m)apply(apply(x,m,function(y,r=rle(y))rep(r$l*r$v,r$l)),1,function(a)tapply(a,cumsum(!a),function(d)sort(e<-d[!!d])<seq(e))))))

```

Try it online!

An R translation of my Jelly answer. I’m not sure it’s much easier to follow! Takes a matrix of 0s and 1s and returns a logical scalar (`FALSE` if Latin, `TRUE` if not). Note because of the way base R tends to collapse matrices to vectors, the input has to have at least 2 rows and columns, but this can be done by padding input with an extra row or column of `FALSE`s. If this is unacceptable, I can work around it at the cost of extra bytes to handle the edge case.
> 1 votes

---
Tags: code-golf, decision-problem, grid, sudoku
---


title: Binary Convolution

text:
# Question
Title: Binary Convolution
A binary convolution is described by a number `M`, and is applied to a number `N`. For each bit in the binary representation of `M`, if the bit is set (`1`), the corresponding bit in the output is given by XORing the two bits adjacent to the corresponding bit in `N` (wrapping around when necessary). If the bit is not set (`0`), then the corresponding bit in the output is given by the corresponding bit in `N`.

A worked example (with 8-bit values):

1. Let `N = 150`, `M = 59`. Their binary respresentations are (respectively) `10010110` and `00111011`.
2. Based on `M`'s binary representation, bits 0, 1, 3, 4, and 5 are convolved.
    1. The result for bit 0 is given by XORing bits 1 and 7 (since we wrap around), yielding `1`.
    2. The result for bit 1 is given by XORing bits 0 and 2, yielding `0`.
    3. The result for bit 2 is given by the original bit 2, yielding `1`.
    4. The result for bit 3 is given by XORing bits 2 and 4, yielding `0`.
    5. The result for bit 4 is given by XORing bits 3 and 5, yielding `0`.
    6. The result for bit 5 is given by XORing bits 4 and 6, yielding `1`.
    7. The results for bits 6 and 7 are given by the original bits 6 and 7, yielding `0` and `1`.
3. The output is thus `10100110` (`166`).

## The Challenge

Given `N` and `M`, output the result of performing the binary convolution described by `M` upon `N`. Input and output may be in any convenient, consistent, and unambiguous format. `N` and `M` will always be in the (inclusive) range `[0, 255]` (8-bit unsigned integers), and their binary representations should be padded to 8 bits for performing the binary convolution.

## Test Cases

```
150 59 -> 166
242 209 -> 178
1 17 -> 0
189 139 -> 181
215 104 -> 215
79 214 -> 25
190 207 -> 50
61 139 -> 180
140 110 -> 206
252 115 -> 143
83 76 -> 31
244 25 -> 245
24 124 -> 60
180 41 -> 181
105 239 -> 102
215 125 -> 198
49 183 -> 178
183 158 -> 181
158 55 -> 186
215 117 -> 198
255 12 -> 243

```

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

```
(n,m)=>n^m&(n^(n*=257)>>1^n>>7)

```

# Answer
> 8 votes
## Python 2, 35 bytes

```
lambda m,n:n^m&(n^n*257/2^n*2^n>>7)

```

# Answer
> 2 votes
# J, 34 bytes

```
2#.[:({"_1],._1&|.~:1&|.)/(8#2)#:]

```

Straight-forward approach that applies the process defined in the challenge. Takes input as an array `[n, m]`.

Forms seven smileys, `[:`, `:(`, `:1`, `(8`, `8#`, `#:`, and `:]`.

## Usage

```
   f =: 2#.[:({"_1],._1&|.~:1&|.)/(8#2)#:]
   f 150 59
171
   f 59 150
166
   f 209 242
178
   f 17 1
0
   f 139 189
181

```

# Answer
> 2 votes
# x64 machine code, 17 bytes

```
88CD88C8D0C9D0C530E930C120D130C8C3

```

Disassembled:

```
0:  88 cd                   mov    ch,cl
2:  88 c8                   mov    al,cl
4:  d0 c9                   ror    cl,1
6:  d0 c5                   rol    ch,1
8:  30 e9                   xor    cl,ch
a:  30 c1                   xor    cl,al
c:  20 d1                   and    cl,dl
e:  30 c8                   xor    al,cl
10: c3                      ret

```

Suitable for the Win64 calling convention (arguments in rcx, rdx).

# Answer
> 1 votes
# Haskell, 66 bytes

```
import Data.Bits
n%m=n.&.(255-m)+(rotate n 1`xor`rotate n(-1)).&.m

```

Works as intended when called with `Word8` data. Replace `(255-m)` with `complement m` (+5 bytes) to make the function work with any unsigned integral datatype.

---
Tags: code-golf, binary, integer, bitwise
---


# Question
Title: Play Big 2 by yourself, as fast as you can
# Introduction

Big 2 is a card game popular in East Asia and South East Asia, in which 4 players are dealt 13 cards each (ie, an equal division of a standard deck without jokers). The goal is to empty your hand before any of the other players. Players take turns playing combinations of a Big 2 subset of standard poker hands until their hands are empty. When cards are played, they are considered to be in a discard pile and cannot be reused.

The challenge here is to determine the fewest number of poker hands needed to completely empty a starting hand assuming that there are no other players. In other words, given 13 cards, produce a list of the poker hands that would empty your hand the fastest (ie, the fewest number of 'turns').

# Challenge

Given a list of 13 cards of the format `<rank><suit>`, produce a delimited combination of Big 2 poker hands that would allow the player to empty their hands as fast as possible. Assume that the given hand can be realistically produced from a single deck of cards (ie, you won't receive 10 aces in your hand).

## Inputs

* An unsorted list of 13 cards, meaning that the ranks and suits are not in any patterned/sorted order
    + The ranks can be any of `A,2,3,4,5,6,7,8,9,0,J,Q,K`, where '0' is a 10. You may use rank `10` in your program if that suits you better.
    + The suits can be any of `D,C,H,S`, which correspond to diamonds, clubs, hearts, and spades, respectively.
    + Sample cards would be `AD` for ace of diamonds, or `0H` for 10 of hearts.
* For this example, the inputs are separated by commas, but you can delimit the string however you like, or even use an entirely different representation of a deck of cards that suits your fancy

## Outputs

* A list (or some delimited string) of cards that indicate play order of your cards. For example the following output formats are valid:

```
2H, 3D, 4H, 5C, 6S
7S, 7D, 7H
0D, JD, QD, KD, AH

```

+ or `[[2H, 3D, 4H, 5C, 6S], [7S, 7D, 7H], [0D, JD, QD, KD, AH]]`
    + or `2H3D4H5C6S, 7S7D7H, 0DJDQDKDAH`
    + **or anything else that can delineate hand combinations (aka convenient inputs and outputs)**
* All three sample outputs indicate that 13 cards were played in the following order: a straight from 2-6, a triplet of 7s, and then a straight from 10-A
* When outputting a 5 card combination, such as for straights or full houses, the cards' ranks/suits do not have to be sorted or grouped in any way - they're mostly shown here for legibility. For example, the straight `2S3S4S5S6S` is equivalent to `6S4S2S5S3S`. (`23456 == 64253`)
* The actual order of moves does not matter as cards cannot be reused anyways

## Big 2 Poker Hands

In Big 2, the following poker hands are legal:

* A single card
* A pair of cards, meaning two cards of the same rank regardless of suit
* A triplet of cards, meaning three cards of the same rank regardless of suit
* A straight, a 5 card combination of consecutive ranks regardless of suit.
    + Straights cannot start from a jack, queen, or king (ie, the straights of ranks (regardless of suit) `JQKA2`, `QKA23`, and `KA234` are invalid)
    + Straights can start from any other rank
    + Aces can either be the high card or the low card in a straight, but it cannot appear in the middle of a straight. Namely, the only 2 valid straights that include an ace are `0JQKA` and `A2345`.
* A full house, a 5 card combination made of three cards of the same rank, and 2 cards of the same, but different rank.
    + For example, `000QQ` is a full house with triplet 10s and a pair of queens, but the combination `000KQ` is invalid because a pair is needed to complete the triplet
* A quad, a 5 card combination made of four cards of the same rank, plus any card of a different rank
* A flush, a 5 card combination of 5 cards of the same suit regardless of rank
* And just for completion's sake: a straight flush, a 5 card combination where the 5 cards are a straight in terms of ranks but also share the same suit.
    + **Note** the straight flush can be computed from either the definition of a straight or a flush, meaning its own distinct definition here isn't necessary for the completion of this challenge.

# Tests

**Input**: `AS,4H,6D,8C,7C,3S,5H,8D,4C,2S,0C,AD,AH`

**Sample output**: `ASAHAD8D8C, 2S3S4H5H6D, 4C, 7C, 0C` OR `7C, 2S6D3S5H4H, 0C, 4C, 8C8DASAHAD`

**Explanation:** Given the above input, it's possible to generate 2 distinct 5-card combination poker hands. After we play those 2 hands, we only have 3 remaining singles. Thus, the minimum amount of hands we must play is 5. Again, the output card hand combinations do not have to be sorted or played in this specific order (or even in this format) - just leaving it here for legibility.

---

**Input:** `2D,0H,5S,0S,4H,AS,4C,6C,6H,KC,8H,5H,8S`

**Sample output:** `5S5H, 4H4C, 0S0H, 6C6H, 8H8S, KC, AS, 2D`

**Explanation:** In this case, it is faster to output 5 pairs instead of a flush (of `5H4H0H6H8H`) because the flush would create 5 dangling single cards that must be played one at a time. Playing the flush would yield 9 turns (1 for flush + 5 singles created from flush + 3 standalone singles), whereas the pair method would require 8 turns (5 turns for 5 pairs, 3 for the leftover singles)

---

**Input:** `4D,4S,4H,4C,5H,5D,5C,5S,9S,9D,9H,9C,AD`

**Sample output:** `4D4S4H4CAD, 5D5H5C5S9S, 9D9H9C`

**Explanation:** Outputting quads using the dangling `AD` is more efficient than picking the quad's last card from another quad because we can finish off with a triplet.

# Rules

* Standard loopholes are forbidden
* Convenient inputs and outputs are allowed
* This is codegolf, so shortest code in bytes wins

# Answer
# JavaScript (ES6),  ~~298 ... 256~~  253 bytes

Takes input as a list of integers in \\$\[0..51\]\\$, where the suit is encoded in the 2 least significant bits and the rank in the 4 upper bits.

Returns a list of lists in the same format.

```
f=(a,k=2)=>(F=(a,H=[])=>H[k]?a+a?0:O=H:a.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).some(h=>[b=c=m=s=0,h.map(x=>(c++,b+=m!=(m|=1<<x/4),s|=1<<x%4)),b<2,b<2,,b<3|m==4111|m==31*(m&-m)|8%s<1][c]&&F(a.filter(n=>!h.includes(n)),[...H,h])))(a)?O:f(a,k+1)

```

Try it online!

This is rather inefficient when more than 5 or 6 turns are required. The 2nd test case completes in a bit less than 2 minutes on my laptop and times out on TIO.

## How?

### Wrapper code

The wrapper code invokes the search function \\$F\\$ for a maximum number of turns \\$k+1\\$. This threshold is incremented until the call is successful. We start with \\$k=2\\$ because we need at least 3 turns to get rid of all cards.

```
f = (                 // f is the main function taking:
  a,                  //   a[] = list of cards
  k = 2               //   k   = maximum number of turns, minus 1
) =>                  //
  (F = ...)(a) ?      // invoke the search function F; if successful:
    O                 //   return the output
  :                   // else:
    f(a, k + 1)       //   try again with k + 1

```

### Generating the hands

In the search function, we first build the powerset of the input \\$a\[\\:\]\\$:

```
a.reduce((a, x) =>
  [ ...a,
    ...a.map(y => [...y, x])
  ],
  [[]]
)

```

That is, we build all possible hands, including invalid ones made of more than 5 cards.

### Hand variables

We then iterate over each hand \\$h\\$, and each card \\$x\\$ in this hand to set up the following variables:

* \\$c\\$ is the number of cards in the hand
* \\$m\\$ is a 13-bit rank bitmask
* \\$s\\$ is a 4-bit suit bitmask
* \\$b\\$ is the number of bits set in \\$m\\$, i.e. the number of distinct ranks in the hand

```
h.map(x => (       // for each card x in h[]:
  c++,             //   increment c
  b +=             //   increment b if
    m != (         //   the current value of m is different from
      m |=         //     the updated value of m
        1 << x / 4 //     where the new rank bit is set
    ),             //
  s |= 1 << x % 4  //   update s with the suit bit
))                 // end of map()

```

*Example*

*a random hand, courtesy of random.org*

```
c = 5

m = 0101010010000 (binary value)
     K J 9  6

b = 4

s = 1110 (binary value)
    SHD

```

### Hand validation

We finally figure out whether the hand is valid by picking the result of the relevant test from a lookup table, according to the number of cards \\$c\\$:

* \\$0\\$ card: always invalid (variables are initialized to \\$0\\$ in this slot)
* \\$1\\$ card: always valid (the above `map()` is performed in this slot and returns a truthy value)
* \\$2\\$ cards: valid if \\$b\<2\\$ (there's only one rank, which means that we have a *pair*)
* \\$3\\$ cards: valid if \\$b\<2\\$ (there's only one rank, which means that we have a *three-of-a-kind*)
* \\$4\\$ cards: always invalid (undefined slot)
* \\$5\\$ cards, valid if:

+ \\$b\<3\\$ because both a *quad + another card* and a *full house* lead to \\$b=2\\$ (two distinct ranks in the hand) while all other patterns result in \\$b\ge3\\$
    + OR \\$m=4111\\$ (1000000001111 in binary), which represents the special *straight* **A**,**2**,**3**,**4**,**5**
    + OR \\$m\\$ has 5 consecutive bits set, which means that we have a standard *straight*

    ```
    m == 31 * (m & -m)

    ```
    + OR \\$s\\$ has only one bit set, which means that we have a *flush*

    ```
    8 % s < 1

    ```
* more than \\$5\\$ cards: always invalid (undefined slots)

### Recursion

If the hand is valid, we do a recursive call to \\$F\\$ with all cards in \\$h\[\\:\]\\$ removed from \\$a\[\\:\]\\$.

```
F(                  // recursive call:
  a.filter(n =>     //   keep only in a[] ...
    !h.includes(n)  //     ... the cards that do not appear in h[]
  ),                //
  [...H, h]         //   append h[] to the list of hands
)                   // end

```

We know that we have reached the maximum number of turns when \\$H\[k\]\\$ is defined. If we have no more cards when this happens, it means that \\$H\\$ is a valid list of hands, which is saved in the output variable \\$O\\$ and eventually returned by the wrapper code.
> 8 votes

# Answer
# 05AB1E, 38 bytes

```
{æʒ€þ©Ùgyg5Qi3‹y€áË®¥ć8%šPΘ)à]æé.Δ˜I¢P

```

Try it online!

Input/output uses 1 for Ace, 10 for 10, 11 for Jack, 12 for Queen, 13 for King.

Runtime is exponential in the number of possible hands, making it timeout for all test cases. The TIO link shows an 8 card input, but the algorithm would theoretically work for inputs of any size, including the specified 13.

```
# The first step is to get a list of all valid hands

{                               # sort the input
 æ                              # all subsets of the input (aka all hands)
  ʒ                          ]  # filter:
   €þ                           #  get the rank of each card in the suit
     ©                          #  save that in the register, without popping
      Ù                         #  uniquify
       g                        #  length (=> number of distinct ranks in the hand)
        yg5Qi                ]  #  if the hand has exactly 5 cards:
             3‹                 #   is the number of distinct ranks < 3? (full house or quad)
               y€áË             #   are all suits of the hand equal? (flush)
                   ®¥           #   deltas of the list of ranks (restored from the register)
                     ć8%š       #   mod 8 the first one (to handle the A0JQK case)
                         PΘ     #   is the product equal to 1? (straight)
                           )    #   wrap those three tests in an array
                            à   #   keep the hand if the maximum is 1 (one of the tests was true)
                                #  else (implicit):
                                #   keep the hand if number of distinct ranks is 1
                                #   this catches singles, pairs, and triplets

æ                               # get all subsets of the list of valid hands
 é                              # sort those subsets by length
  .Δ                            # find the first one such that:
    ˜                           #  deep flattened
     I¢                         #  count occurences of each card of the input in the result
       P                        #  product is 1

```
> 2 votes

---
Tags: code-golf, decision-problem, game, card-games
---


# Question
Title: Shortest code to check if a number is in a range in JavaScript
This is how I checkout to see if a number is in a range (in between two other numbers):

```
var a = 10,
    b = 30,
    x = 15,
    y = 35;

x < Math.max(a,b) && x > Math.min(a,b) // -> true
y < Math.max(a,b) && y > Math.min(a,b) // -> false

```

I have to do this math in my code a lot and I'm looking for shorter equivalent code.

This is a shorter version I came up with. But I am sure it can get much shorter:

```
a < x && x < b
true
a < y && y < b
false

```

But downside is I have to repeat `x` or `y`

# Answer
> 13 votes
13 chars, checks both variants a\<b and b\<a

```
(x-a)*(x-b)<0

```

In C may be used expression (may be also in JavaScript). 11 chars, No multiplications (fast)

```
(x-a^x-b)<0

```

# Answer
> 9 votes
```
a<x==x<b

```

JavaScript, 8 chars.

# Answer
> 3 votes
# JavaScript, 7 bytes

```
a<n&n<b

```

---
Tags: code-golf, tips, javascript
---


title: Polyglot Iterative Quine

text:
# Question
Title: Polyglot Iterative Quine
# Introduction

A polyglot is a program that is valid in multiple languages at once. An iterative quine is a program that outputs another program that outputs another program that outputs the source of the original program. Note that the number of chained programs does not have to be 3; it could be 2, 4, or 97384.

# Challenge

Your task is to write a polyglot iterative quine. Each program in the program chain must be a polyglot.

* Each of your programs must take no input.
* As stated above, each of the programs must output the source of the next program in the chain. The last program in the chain must output the source code of the first program.

# Scoring

Your score is calculated as follows:

* For each program in the chain, take the number of languages it is valid in. Sum the results.
* Sum the byte count of each program in the chain.
* Divide the byte count by the number from the first program.

# Rules

* The length of the chain must be at least 2.
* Each program in the chain must be valid in at least 2 languages.
* The program with the lowest score wins.
* "Different language" is defined as follows:
    + A language where the source code of the compiler or interpreter is not the same as another, and the compiler or interpreter does not run the same language as another. Some examples of different languages are: Python 2 and 3, C and C++, Java and C, and Lua and Ruby. However, by this definition, using `tcc` instead of `gcc` does not count as a different language, because `tcc` runs the same language as `gcc`: C.
* Programs are allowed to throw errors, but only *after* they print out the output of the program. For example, `print(1/0);print(<quine stuff>)` in Python 3 would be invalid, but `print(<quine stuff);print(1/0)` would be.

# Answer
# Wumpus, \>\<\>, Befunge-98, \\$\frac{57+57}{3+3}=19\\$

```
"]<0~[#34ooo!O;#53&o@,k*4e-1#'$ #o#!-1'#'+3*a9*c5+*68%2++

```

Try it in Wumpus! Try it in \>\<\>! Try it in Befunge-98!

A modified version of a previous polyglot of mine that makes it iterative by flipping the first `0` to a `1` and back again.
> 2 votes

---
Tags: code-challenge, quine, polyglot
---


title: Generate Matlab plot markers

text:
# Question
Title: Generate Matlab plot markers
Matlab has a useful command for visualizing data: `plot`. It draws data points using "markers" in 2-D space, connecting them with lines; however, for this challenge, let's ignore the lines and use only markers. In fact, only one marker.

Input: one of Matlab's marker symbols: `.` `o` `x` `+` `*` `s` `d` `v` `^` `<` `>` `p` `h`

Output: corresponding image for that marker, which is one of the following 13 icons:

To make it clearer, here are the same icons enlarged, so the pixels can be easily seen:

* Take the input as a string, a `char`, an integer ASCII code, or anything equivalent
* Produce the output by displaying the image, returning it as a function's return value, saving it to a file, etc
* The image should have pixels of two different colours in it. I used blue on white, because this is what Matlab uses by default, but any other colour scheme is OK, e.g. white on black.
* The image can have padding of background colour of any size
* The pixels can be enlarged by any integer ratio, e.g. instead of the original 11-by-9 image for the triangle, you can output a 110-by-72 image, in which 10-by-8 blocks represent the original pixels

+ As a corollary of the above, you can output text with glyphs like  instead of an image, if you can print this text properly (i.e. without gaps between glyphs) on the same system which runs the code

---

For quick reference, here are the bitmaps for each input:

* `.`

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

```
* `o`

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

```
* `x`

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

```
* `+`

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

```
* `*`

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

```
* `s`

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

```
* `d`

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

```
* `v`

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

```
* `^`

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

```
* `<`

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

```
* `>`

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

```
* `p`

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

```
* `h`

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

```

Any padding with zeros which exists in these bitmaps is optional. So e.g. for the `.` input, a 5x5 image would be sufficient.

# Answer
> 2 votes
# Node.js, 310 bytes

Takes the ASCII code of the symbol as input.

```
n=>Buffer(`~A<<13)$$"~"6+'?'+6"~'81<<<18'~/973202459/~"$$)31<<A~"%;3)3;%"~~ !&(=@=-#! ~""""?""""~"%>3*,:3~~"$))1<1))$"~"'.'"~?<<<<<<<?~1)$"$)1`.split`~`[n*7%86%17]).map(c=>s+=(g=n=>n--?' █'[[...Buffer('$8$$L0$,4$(8(4T(!#""0($,|T8$F'),290,280,34,38,1051].map(c=>p+=c-32,p=0)[c-32]>>n&1]+g(n):`
`)(11),s='')&&s

```

Try it online!

### How?

All symbols can be generated by combining \\$34\\$ distinct binary patterns.

Each pattern is identified with a character \\$C\\$ (from space to "A").

The patterns are ordered from lowest to highest, using their decimal representation \\$N\\$. What's actually stored is the difference \\$d\\$ between two consecutive patterns, plus \\$32\\$.

```
 ID |  C  | pattern     |    N |    d | d+32
----+-----+-------------+------+------+------
  0 | ` ` | 00000000100 |    4 |    4 |   36
  1 | `!` | 00000011100 |   28 |   24 |   56
  2 | `"` | 00000100000 |   32 |    4 |   36
  3 | `#` | 00000100100 |   36 |    4 |   36
  4 | `$` | 00001010000 |   80 |   44 |   76
  5 | `%` | 00001100000 |   96 |   16 |   48
  6 | `&` | 00001100100 |  100 |    4 |   36
  7 | `'` | 00001110000 |  112 |   12 |   44
  8 | `(` | 00010000100 |  132 |   20 |   52
  9 | `)` | 00010001000 |  136 |    4 |   36
 10 | `*` | 00010010000 |  144 |    8 |   40
 11 | `+` | 00010101000 |  168 |   24 |   56
 12 | `,` | 00010110000 |  176 |    8 |   40
 13 | `-` | 00011000100 |  196 |   20 |   52
 14 | `.` | 00011111000 |  248 |   52 |   84
 15 | `/` | 00100000000 |  256 |    8 |   40
 16 | `0` | 00100000001 |  257 |    1 |   33
 17 | `1` | 00100000100 |  260 |    3 |   35
 18 | `2` | 00100000110 |  262 |    2 |   34
 19 | `3` | 00100001000 |  264 |    2 |   34
 20 | `4` | 00100011000 |  280 |   16 |   48
 21 | `5` | 00100100000 |  288 |    8 |   40
 22 | `6` | 00100100100 |  292 |    4 |   36
 23 | `7` | 00100110000 |  304 |   12 |   44
 24 | `8` | 00110001100 |  396 |   92 |  124
 25 | `9` | 00111000000 |  448 |   52 |   84
 26 | `:` | 00111011000 |  472 |   24 |   56
 27 | `;` | 00111011100 |  476 |    4 |   36
 28 | `<` | 01000000010 |  514 |   38 |   70
 29 | `=` | 01100000100 |  772 |  258 |  290
 30 | `>` | 01111111100 | 1020 |  248 |  280
 31 | `?` | 01111111110 | 1022 |    2 |   34
 32 | `@` | 10000000100 | 1028 |    6 |   38
 33 | `A` | 11111111111 | 2047 | 1019 | 1051

```

The 29 first values \\$d+32\\$ can be directly converted to ASCII characters and stored as a Buffer. The last 5 ones are stored as number literals.

```
[...Buffer('$8$$L0$,4$(8(4T(!#""0($,|T8$F'),290,280,34,38,1051]

```

Using the characters \\$C\\$ defined above, we can encode each symbol as a string.

*Example:*

```
..█........     00100000000 --> '/'
..███......     00111000000 --> '9'
..█..██....     00100110000 --> '7'
..█....█...     00100001000 --> '3'
..█.....██.     00100000110 --> '2'
..█.......█ --> 00100000001 --> '0' --> '/973202459/'
..█.....██.     00100000110 --> '2'
..█...██...     00100011000 --> '4'
..█..█.....     00100100000 --> '5'
..███......     00111000000 --> '9'
..█........     00100000000 --> '/'

```

All symbols are stored in a single string, delimited with `~`. We use a hash function to convert the input ASCII code into the position of the symbol in the list.

# Answer
> 2 votes
# Charcoal, ~~163~~ ~~154~~ 152 bytes

```
≔█η≡θo«Ｇ→↘→²η‖Ｏ↘¬»d«Ｇ↘³↓²↘³η‖Ｏ¬»h«ＧＨ↖↑→→↑↗↓↘→→↙↓²η‖Ｏ↓».ＧX³ηpＧ↑²↙⁴↖²→⁸↙³↓³→²↓²↖³↙²←³↓²↗²↑³ηsＢ⁹η¿№x+*θ«Ｆ¬⁼θ+ＰX×⁴ηＦ¬⁼θxＰ+×⁵η»«ＧＨ←←←←←↘↓↘↓↘↘↓↘²η‖Ｏ⟲⊗⌕v>^<θ

```

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

```
≔█η

```

Get the  character into a variable. As @ASCII-only explains, a properly encoded Charcoal file would use three bytes to express this character, so it needs to be in a variable as it gets used a lot. (But it's still 2 bytes shorter than the previous approach.)

```
≡θ

```

Use a switch statement for the six easy characters.

```
o«Ｇ→↘→²η‖Ｏ↘¬»

```

Handle the `o` by drawing one eighth of the figure and mirroring it three times.

```
d«Ｇ↘³↓²↘³η‖Ｏ¬»

```

Handle the `d` by drawing one quarter of the figure and mirroring it twice.

```
h«ＧＨ↖↑→→↑↗↓↘→→↙↓²η‖Ｏ↓»

```

Handle the `h` by drawing the top half and mirroring it.

```
.ＧX³η

```

Handle the `.` by drawing a diamond.

```
pＧ↑²↙⁴↖²→⁸↙³↓³→²↓²↖³↙²←³↓²↗²↑³η

```

Handle the `p` by drawing it manually.

```
sＢ⁹η

```

Handle the `s` by drawing a hollow rectangle. (This one is the last of the six because `Box` can take 3 parameters but the following `¿` isn't legal as a parameter.)

```
¿№x+*θ«Ｆ¬⁼θ+ＰX×⁴ηＦ¬⁼θxＰ+×⁵η»

```

Handle the `x`, `+` and `*`, the latter by overlapping the former.

```
«ＧＨ←←←←←↘↓↘↓↘↘↓↘²η‖Ｏ⟲⊗⌕v>^<θ

```

Draw the left half of the `v`, then mirror it, then rotate it if the character happens to be `>`, `^` or `<`.

# Answer
> 1 votes
# MATL, 9 bytes

```
1w&XG7lZG

```

Cheating? Maybe. Try it on MATL Online.

Literal translation of the MATLAB code `plot(1,input(''));axis off` (26 bytes). The online version compresses the image, but on a local machine it will simply use the MATLAB plot defaults.

# Answer
> 0 votes
# Python, 58 bytes

```
from matplotlib.pyplot import*
plot(0,input())
axis('off')

```

Fun to take advantage of matplotlib doing all the heavy lifting.

---
Tags: code-golf, graphical-output, compression, matlab, octave
---