title: Groups of repeating items

text:
# Question
Title: Groups of repeating items
# Challenge description

Given a list / array of items, display all groups of consecutive repeating items.

# Input / output description

Your input is a list / array of items (you can assume all of them are of the same type). You don't need to support every type your language has, but is has to support at least one (preferably `int`, but types like `boolean`, although not very interesting, are also fine). Sample outputs:

```
[4, 4, 2, 2, 9, 9] -> [[4, 4], [2, 2], [9, 9]]
[1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4] -> [[1, 1, 1], [2, 2], [3, 3, 3], [4, 4, 4, 4]]
[1, 1, 1, 3, 3, 1, 1, 2, 2, 2, 1, 1, 3] -> [[1, 1, 1], [3, 3], [1, 1], [2, 2, 2], [1, 1], [3]]
[9, 7, 8, 6, 5] -> [[9], [7], [8], [6], [5]]
[5, 5, 5] -> [[5, 5, 5]]
['A', 'B', 'B', 'B', 'C', 'D', 'X', 'Y', 'Y', 'Z'] -> [['A'], ['B', 'B', 'B'], ['C'], ['D'], ['X'], ['Y', 'Y'], ['Z']]
[True, True, True, False, False, True, False, False, True, True, True] -> [[True, True, True], [False, False], [True], [False, False], [True, True, True]]
[0] -> [[0]]

```

As for empty lists, output is undefined - it can be nothing, an empty list, or an exception - whatever suits your golfing purposes the best. You don't have to create a separate list of lists either, so this is a perfectly valid output as well:

```
[1, 1, 1, 2, 2, 3, 3, 3, 4, 9] ->

1 1 1
2 2
3 3 3
4
9

```

The important thing is to keep the groups separated in some way. This is so the shortest code in bytes wins

# Answer
> 15 votes
## Mathematica, 5 bytes

```
Split

```

... there's a built-in for that.

# Answer
> 9 votes
# Jelly, 5 bytes

```
I0;œṗ

```

Works for all numeric types. Try it online! or verify all numeric test cases.

### How it works

```
I0;œṗ  Main link. Argument: A (array)

I      Increments; compute the differences of consecutive elements.
 0;    Prepend a zero.
   œṗ  Partition; split A at truthy values in the result to the left.

```

# Answer
> 8 votes
## Retina, ~~15~~ 8 bytes

*Thanks to Lynn for suggesting a simpler I/O format.*

```
!`(.)\1*

```

Treats the input as a list of characters (and uses linefeeds to separate groups).

Try it online!

This simply works by matching groups and printing them all (which uses linefeed separation automatically).

# Answer
> 4 votes
# MATL, 9 bytes

```
Y'v"@Z}Y"

Y'     % Take input. Run-length encoding. Gives two row arrays: values and run lengths
v      % Concatenate vertically
"      % For each column
  @Z}  %   Push column and split into its two elements
  Y"   %   Run-length decoding
       % End for. Implicitly display

```

Input is a row array of **numbers**, with spaces or commas as separators.

Try it online! Test with non-integer numbers.

---

# MATL, 11 bytes

```
lidgvYsG7XQ

```

Input is a column array of either **numbers** or **characters**, using `;` as separator.

Try it online! Test with arbitrary numbers. Test with characters.

```
l     % Push 1
i     % Take input, say [4;4;2;2;9;9]
d     % Consecutive differences of input: [0;-2;0;7;0]
g     % Convert to logical: gives 1 if consecutive entries were different: [0;1;0;1;0]
v     % Concatenate vertically with the initial 1: [1;0;1;0;1;0]
Ys    % Cumulative sum. Each value is a group label: [1;1;2;2;3;3]
G     % Push input again
7XQ   % Split into horizontal arrays as indicated by group labels: {[4 4];[2 2];[9 9]}
      % Implicitly display

```

# Answer
> 4 votes
## JavaScript (ES6), ~~39~~ 37 bytes

```
f=
s=>s.replace(/(\w+) (?!\1\b)/g,`$1
`)
;
```

```
<input oninput=o.textContent=f(this.value);><pre id=o>
```

Works on any space-separated word-like tokens. Saved 2 bytes thanks to @MartinEnder♦. Best I could do for array input and return is 68:

```
a=>a.reduce((l,r)=>(l==r?c.push(r):b.push(c=[r]),r),b=[c=[a[0]]])&&b

```

# Answer
> 3 votes
# , 13 bytes

```
<;.1~1,2~:/\]

```

Since J does not support ragged arrays, each run of equal elements is boxed. The input is an array of values and the output is array of boxed arrays.

## Usage

```
   f =: <;.1~1,2~:/\]
   f 4 4 2 2 9 9
┌───┬───┬───┐
│4 4│2 2│9 9│
└───┴───┴───┘
   f 1 1 1 3 3 1 1 2 2 2 1 1 3
┌─────┬───┬───┬─────┬───┬─┐
│1 1 1│3 3│1 1│2 2 2│1 1│3│
└─────┴───┴───┴─────┴───┴─┘
   f 'ABBBCDXYYZ'
┌─┬───┬─┬─┬─┬──┬─┐
│A│BBB│C│D│X│YY│Z│
└─┴───┴─┴─┴─┴──┴─┘
   f 0
┌─┐
│0│
└─┘

```

## Explanation

```
<;.1~1,2~:/\]  Input: s
            ]  Identify function to get s
       2       The constant 2
           \   Operate on each overlapping sublist of size 2
        ~:/      Are the two values unequal, 1 if true else 0
     1,        Prepend a 1 to it
<;.1~          Using the list just made, chop s at each index equal to 1 and box it
               Return this as the result

```

# Answer
> 3 votes
# Dyalog APL, 9 bytes

```
⊢⊂⍨1,2≠/⊢

```

the argument
`⊂⍨` partitioned at
`1` at the first element
`,` and then
`2≠/` where subsequent pairs differ
in the argument

# Answer
> 3 votes
# gs2, 2 bytes

```
c-

```

Try it online!

`c` is a grouping built-in that does exactly this, so we call it on STDIN (which is a string, i.e., a list of chars) and get a list of strings. Sadly, the result is indistinguishable from the input, so we need to add separators! `-` (join by spaces) does the trick.

An alternative answer is  (2 bytes of CP437), which simply wraps `c` into an anonymous function.

# Answer
> 2 votes
# Brachylog, 13 bytes

```
:{s.dl1}fs.c?

```

**Warning:** this is extremely inefficient, and you will understand why in the explanation.

This expects a list (e.g `[1:1:2:2:2]`) as input. The elements inside the list can be pretty much anything.

### Explanation

```
:{     }f       Find all ordered subsets of the Input with a unique element in them
  s.                Output is a subset of the input
    dl1             Output minus all duplicates has a length of 1 (i.e. one unique value)
         s.     Output is an ordered subset of those subsets
           c?   The concatenation of those subsets is the Input

```

This works only because of the way `s - Subset` unifies: the smallest sets are at the end. Therefore the first thing it finds that concatenates to the Input are the longest runs, e.g. `[[1:1]:[2:2:2]]` and not for example `[[1:1]:[2:2]:[2]]`.

# Answer
> 2 votes
## Python 2, 43 bytes

```
p=-1
for x in input():print"|"[:x^p],x,;p=x

```

Works on lists of booleans. Example:

```
>> [True,True,False,False,False,True,False,True,False]
 True  True | False  False  False | True | False | True | False

```

Iterates through the input list, storing the last seen element. A separator bar is printed before each element that is different than the previous, checked as having bitwise xor `^` of 0. Initializing `p=-1` avoids a separator before the first element.

# Answer
> 2 votes
## CJam, 9 bytes

Two solutions:

```
{e`:a:e~}
{e`{(*}%}

```

Test it here.

### Explanation

```
e`   e# Run-length encode (gives a list of pairs [run-length value]).
:a   e# Wrap each pair in a singleton list.
:e~  e# Run-length decode each list.

```

Or

```
e`   e# Run-length encode.
{    e# Map this block over each pair...
  (  e#   Pull out the run length.
  *  e#   Repeat the list containing only the value that many times.
}%

```

# Answer
> 2 votes
## Haskell, 22 bytes

```
import Data.List
group

```

There's a built-in. Works on any type that supports equality.

# Answer
> 2 votes
# MATL, ~~8~~ 7 bytes

Removed 1 byte thanks to @Suever

```
ly&Y'Y{

```

Works with integers/floats/chars/booleans/unicorn points/other imaginary inputs.
For booleans, inputs are `T/F`, outputs are `1/0`.

Try it online!

---

**Grouped and Repeated**

```
ly&Y'Y{
l          % push 1 onto the stack
 y         % duplicate the input
  &Y'      % run-length encoding (secondary output only)
     Y{    % break up array into cell array of subarrays

```

# Answer
> 2 votes
# Zsh, 28 bytes

```
>$1;for i {mv * $i&&echo;ls}

```

Try it online!

* `>$1`: create the file named the first argument
* `for i {}`: for each argument:
    + `mv * $i`: attempt to move all files in the current directory to the current item
    + If these are the same (i.e. this item is the same as the last), this will fail with `mv: 'X' and 'X' are the same file`.
    + `&&`: if this doesn't fail (i.e. this item is not the same as the last)
        - `echo`: print a blank line to separate the runs
    + `ls`: then list all the files in the current directory. In effect, this just prints `$i`.

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

```
{(&~~':x)_x}

```

Try it online!

A relatively straightforward "idiom". A (verbose) q version is:

```
{(where differ x)cut x}

```

# Answer
> 2 votes
# Husk, 1 byte

```
g

```

Try it online for all the integer test-cases, or here for the "True/False" one

From the Husk Wiki:
`g` `group` Group equal adjacent values

---

# Husk, 10 bytes

```
CẊ-Θ:W≠¹L¹

```

Try it online!

Without `g`...

From the Husk wiki:

```
C            Cut off sublists of input, in lengths given by:
 Ẋ             Map over pairs of adjacent values:
  -              Subtract first argument from second
                 (so Ẋ- = differences)
   Θ           Prepends a falsy value (here = zero) to
    :   L¹     Append the length of the input to
     W≠¹       Indices of input that are not equal to their successor

```

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

```
s=>s.replace(/(.)(?!\1)/g,'$1 ')

```

Try it online!

Support char

# Answer
> 1 votes
## C#, 117 bytes

```
void f(List<String>m){Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));}

```

ungolfed (not really)

```
    public static void f(List<String>m)
    {
        Console.Write(m[0]+String.Join("",m.GetRange(1,m.Count()-1).Select((i,j)=>i==m[j]?i:"\n"+i)));
    }

```

# Answer
> 1 votes
# Pyth, 36 35 bytes

```
VQIqNk=hZ).?=+Y]*]kZ=Z1=kN;t+Y]*]kZ

```

Test link

Edit: explanation:

```
                                      standard variables: Y=[], Z=0, k='', Q=input
VQ                                    iterate over input
  IqNk                                if the current entity is equal to k:
      =hZ)                            increase Z.
          .?                          else:
               ]*]kZ                  list of length Z filled with k
            =+Y                       add it to Y
                    =Z1               set Z to 1
                       =kN            set k to the current entity
                          ;           end loop
                              ]*]kZ   list of length Z filled with k
                            +Y        add it to Y
                           t          implicitly print the tail of Y (removing the first element)

```

# Answer
> 1 votes
# Pyth, ~~9~~ 7 bytes

```
mr9]dr8

```

Credit to @LeakyNun for 2 byte!

Explanation:

```
             input
     r8      run-length decode
m            for each...
   ]d        ...treat each run as standalone encoded form...
 r9          ...decode
             print

```

---

### Old answer, 12 bytes

```
hf.Am!t{dT./

```

Forgot about run length built-in, but I think this is an okay approach, so I kept it.

Explanation:

```
                input
          ./    all possible partitions
 f       T      filter by...
  .A            ...whether all groups of integers...
    m!t{d       ...have length one after deduplication
h               get the first element (first one has no adjacent [1,1] and [1])
                print

```

# Answer
> 1 votes
# Retina, ~~24~~ 22 bytes

2 bytes thanks to Martin Ender.

A 15-byte answer already exists, so this is just another approach which costs more bytes.

```
S-`(?<=(\d+)) (?!\1\b)

```

Try it online!

It splits on spaces whose preceding number differ from the proceeding.

This is a demonstration of lookarounds.

# Answer
> 1 votes
# C, ~~88~~ 77 bytes

*Moved the* `strmcmp` *inside the* `printf` *saving 11 bytes*

```
f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}

```

### Usage:

```
f(char**a){*a++;char*x;for(;*a;x=*a++)printf(strcmp(*a,x)?"\n%s ":"%s ",*a);}
main(c,v)char**v;{f(v);}

```

### Sample Input:

*(command line parameters)*

```
1 1 1 1 2 2 2 2 3 3 3 3 4 5 6 7777

```

### Sample Output:

```
1 1 1 1
2 2 2 2
3 3 3 3
4
5
6
7777

```

**Tested on:**

```
gcc 4.4.7 (Red Hat 4.4.7-16)  - OK
gcc 5.3.0 (Cygwin)            - Segmetation Fault
gcc 4.8.1 (Windows)           - OK

```

I'm trying to fix the 5.3.0 Segmetation Fault.

**88 Version**

```
f(char**a){*a++;char*x;for(;*a;x=*a++)strcmp(*a,x)?printf("\n%s ",*a):printf("%s ",*a);}

```

# Answer
> 1 votes
# Java 134 bytes

```
void a(String[]a){int i=0,l=a.length;for(;i<l-1;i++)System.out.print(a[i]+((a[i].equals(a[i+1]))?" ":"\n"));System.out.print(a[l-1]);}

```

iterates through, and decides whether to separate with a new line or a space.

# Answer
> 1 votes
## 05AB1E, 13 bytes

```
¬svyÊi¶}yðJ?y

```

**Explained**

```
¬s             # push first element of list to stack and swap with input
  v            # for each X in input
   yÊi¶}       # if X is different from last iteration, push a newline
        yðJ?   # push X followed by a space to stack and join stack to string
            y  # push X to stack for next iterations comparison

```

Should work for any list.
Tested on int and char.

Try it online

# Answer
> 1 votes
# Swift, 43 bytes

```
var p=0;i.map{print($0==p ?"":",",$0);p=$0}

```

Assumes i to be an array of equatable objects; works for anything from ints to strings to custom objects. Kind of cheeky in that the output contains lots of newlines, but making that prettier would cost bytes.

**Prettier, ungolfed version:**

```
var prev = Int.max // unlikely to be the first element, but not the end of the world if it happens to be.
i.map { n in
    print(n == prev ? " " : "\n•", n, terminator: "")
    prev = n
}

```

This version prints every group on a new line at the expense of more code.

## Ideas for Improvement

```
i.reduce(0){print($0==$1 ?"":"•",$1);return $1}

```

This version has 47 bytes, but it's a different approach, so maybe there's something to optimize away there? The biggest problem is the return statement.

# Answer
> 1 votes
## ListSharp, 134 bytes

```
STRG l = READ[<here>+"\\l.txt"]
[FOREACH NUMB IN 1 TO l LENGTH-1 AS i]
{
[IF l[i] ISNOT l[i-1]]
STRG o=o+"\n"
STRG o=o+l[i]
}
SHOW = o

```

ListSharp doesnt support functions so the array is saved in a local file called `l.txt`

# Answer
> 1 votes
# **Ruby, 24 bytes**

In ruby `Array` instances have built-in method `group_by`

So solution will be:

```
a.group_by{|x| x}.values

```

# Answer
> 1 votes
# Jelly, 2 bytes

```
Œg

```

Try it online!

Alternatively, a non-builtin approach:

```
Ik

```

Try it online!

# Answer
> 1 votes
# Vyxal, 1 byte

```
Ġ

```

Try it Online!

Ah yes, the power of triviality.

# Answer
> 1 votes
# PowerShell, 49 bytes

```
$args|%{,$a*!($i=$_-in$a-or!$a)
$a=$a*$i+,$_}
,$a

```

Try it online!

# Answer
> 1 votes
# Thunno 2, 1 byte

```
ġ

```

Try it online!

# Answer
> 0 votes
# TSQL, 132 bytes

This is a little different from the other answers - sql doesn't have arrays, the obvious input for sql is a table.

**Golfed:**

```
DECLARE @ table(i int identity, v varchar(20))
INSERT @ values(1),(1),(1),(3),(3),(1),(1),(2),(2),(2),(1),(1),(3)

SELECT REPLICATE(v+' ',COUNT(*))FROM(SELECT i,i-row_number()over(partition
by v order by i)x,v FROM @)z GROUP BY x,v ORDER BY max(i)

```

**Ungolfed:**

```
DECLARE @ table(i int identity, v varchar(20))
INSERT @ values(1),(1),(1),(3),(3),(1),(1),(2),(2),(2),(1),(1),(3)

SELECT
  REPLICATE(v+' ',COUNT(*))
FROM
  (
     SELECT
       i,
       i-row_number()over(partition by v order by i)x,
       v
     FROM @
  )z
GROUP BY
  x,v
ORDER BY
  max(i)

```

**Fiddle**

# Answer
> 0 votes
## Perl 5 - 39 Bytes

```
print$_.($/)[$_ eq@a[++$-]]for@a=sort@a

```

# Answer
> 0 votes
# sed, ~~33~~ 23+1=24 bytes

```
s/([^ ]+)( \1)* */&\n/g

```

It needs the `-r` option.

Usage example:

```
$ echo '1 1 1 2 2 3 3 3 4 9 9' | sed -r 's/([^ ]+)( \1)* */&\n/g'
1 1 1
2 2
3 3 3
4
9 9

```

# Answer
> 0 votes
## Pyke, 2 bytes (non competitive)

Only supports integers

```
$f

```

Try it here!

```
split_at(input, delta(input))

```

Added split\_at node, splits input when 2nd arg is truthy

# Answer
> 0 votes
# JavaScript (ES6), 56

Input: array of numbers or strings

Output: array of arrays

First time ever using exact comparisong in golfed code

```
a=>a.map(x=>x!==p?o.push(g=[p=x]):g.push(x),p=o=g=[])&&o

```

# Answer
> 0 votes
# Clojure, 19 bytes

```
#(partition-by + %)

```

It's a built-in, but it takes a mapping function. In this case, `+` serves as an identity function.

# Answer
> 0 votes
## Befunge, ~~47~~ ~~41~~ 38 Bytes

```
&:&:.92pv.<
g29:&:-1_@|!-
92p25*,.^ >:

```

Input format:

```
number_of_values-1         values (separated by a space)

```

You may test the code here

---

Previous version with explanations :

```
&:&:.00pv.<
g00:&:-1_@|!-
v*52p00:  <
>,.     ^

```

The interpet's cursor follows the symbols `> v < ^`. If the cursor is at the end of a line and is going to the right, it will loop back to the beginning (same principle for other directions).

`&:` : Gets the first input put it to the stack and duplicates it (to the stack)

`&:.00pv` : Gets the second input, prints it and saves it into the code, at the coordinates (0,0) \[erasing the first '&'\]. Then, go down

`_` : Test if last value of the stack (the number of values) is equals to 0 and set the cursor's direction to the right if it is, to the left if it isn't

`1-:` : Removes 1 from the number of values

`&:00g-!|` : Compares the next input with the one stored at (0,0). Set the cursor's direction to up if they are equal, to down if they aren't

`.` : Displays a numeric value

`:00p52*,.` : Override the last saved value to the current value, then displays `\n` (ascii 10, 5\*2) followed by the value

`@` : Terminates the program

# Answer
> 0 votes
## Javascript (using external library) (178 bytes)

```
(s)=>_.From(s).Aggregate((t,e)=>{if(0===t.Items.length)return t.Items.push([e]),t;var s=t.Items[t.Items.length-1];return s[0]===e?(s.push(e),t):(t.Items.push([e]),t)},{Items:[]})

```

Disclaimer: I am using a library I wrote to implement LINQ from C# into JS. It didn't exactly help me win but oh well

# Answer
> 0 votes
# 05AB1E, 1 byte

```
γ

```

Builtins ftw ¯\\\_(ツ)\_/¯

Try it online or verify all test cases.

Here an alternative without builtins (**6 bytes**):

```
üÊ0šÅ¡

```

Try it online or verify all test cases.

**Explanation:**

```
γ       # Split the (implicit) input-list into chunks of equal adjacent values
        # (after which the resulting list of lists is output implicitly)

ü       # For each overlapping pair of values in the (implicit) input-list:
 Ê      #  Check that they are NOT equal (0 if equal; 1 if not)
  0š    # Prepend a 0 to this list
    Å¡  # Split the (implicit) input-list at the truthy indices
        # (after which the resulting list of lists is output implicitly)

```

# Answer
> 0 votes
# C (gcc), 54 bytes

```
f(char*s){printf("%c%c",*s,*s-s[1]?10:32),*++s&&f(s);}

```

Try it online!

or **55 bytes** iteratively

```
f(char*s){while(printf("%c%c",*s,*s-s[1]?10:32),*++s);}

```

Try it online!

# Answer
> 0 votes
# Charcoal, 35 bytes

```
≔⁰ξ≔⁺θ θＦ⊖Ｌθ«¿¬⁼§θι§θ⊕ι«Ｐ✂θξ⊕ι↓≔⊕ιξ

```

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

Input as a list of characters.

# Answer
> 0 votes
# Brachylog v2, 1 byte

Try it online!

Less built-in and far, far slower:

# Brachylog v2, 4 bytes

```
~c=ᵐ

```

Try it online!

```
~c      The output is a partitioning of the input (with as few partitions as possible)
   ᵐ    such that each partition
  =     contains only one unique element.

```

# Answer
> 0 votes
# Factor, 23 bytes

```
[ [ ] group-by values ]

```

Try it online!

```
[                        ! begin quotation (anonymous function)
  [ ]                    ! A quotation that returns its input
      group-by           ! group adjacent elements with a ( key -- value ) quotation
               values    ! obtain the values of an associative array
                      ]  ! end quotation

```

Factor actually has a combinator called `monotonic-split` that can do this more directly, but it's more bytes.

# Answer
> 0 votes
# Arturo, 16 bytes

```
$=>[chunk&=>[&]]

```

Try it

# Answer
> 0 votes
# Thunno, \\$ 2 \log\_{256}(96) \approx \\$ 1.65 bytes

```
zy

```

Attempt This Online!

Built-in solution.

# Answer
> 0 votes
# Japt, 2 bytes

Can handle all data types.

```
òÀ

```

Try it

```
òÀ     :Implicit input of array
ò      :Partition between elements
 À     :That are not strictly equal

```

# Answer
> 0 votes
# Java 8, 83 bytes

```
s->{char a=0;for(char b:s.toCharArray())System.out.print((a<1|a==b?"":" ")+(a=b));}

```

Try it online!

---

Alternative solution using Streams (**85 bytes**) :

```
s->s.chars().reduce(0,(a,b)->{System.out.print((a<1|a==b?"":" ")+(char)b);return b;})

```

Don't hesitate to ask if this needs any explanation!

# Answer
> 0 votes
# F#, 196 bytes

```
let g x=Seq.foldBack(fun n c->Seq.tryHead c|>function|None->[n,1];|Some i when fst i<>n->(n,1)::c;|_->Seq.head c|>fun h->(fst h,(snd h)+1)::(List.tail c))x []|>Seq.map(fun(i,c)->Seq.replicate c i)

```

Try it online! (includes character and boolean tests cases in the footer, but others must be commented out first).

Essentially, it counts the number of sequential items in the collection, then creates a new collection of each item replicated for their respective counts.

# Answer
> 0 votes
# TypeScript (Type System) 4.9.5 - 156 121 Bytes

* 35 Bytes thanks to **ASCII-only**

```
type F<X,Y=[],Z=any>=X extends[infer A,...infer B]?[Z]extends[A]?Y extends[...infer C,infer D]?F<B,[...C,[...D, A]],A>:F<B,[...Y,[A]],A>:F<B,[...Y,[A]],A>:Y

```

**Un-golfed version**

```
type DistinctGroups<
  Input extends number[],
  Output extends number[][] = [],
  LastElement extends any = never
>=
  Input extends [infer First, ...infer Rest] ?
    [LastElement] extends [First] ?
      Output extends [...infer Head, infer Tail] ?
        DistinctGroups<Rest, [...Head, [...Tail, First]], First> :
        DistinctGroups<Rest, [...Output, [First]], First>
    : DistinctGroups<Rest, [...Output, [First]], First>
  : Output

```

Try it on the TypeScript playground!

# Answer
> 0 votes
# J-uby, 15 bytes

Returns an Enumerator.

```
:slice_when+:!=

```

Attempt This Online!

---
Tags: code-golf, array
---


title: Draw a bowling formation

text:
# Question
Title: Draw a bowling formation
Your goal is to display ASCII art of a formation in ten-pin bowling where only some of the pins remain. Fewest bytes wins.

The tens pins are in a triangular formation:

```
O O O O
 O O O
  O O
   O

```

Pins are labelled from 1 to 10 as:

```
7 8 9 10
 4 5 6
  2 3
   1

```

Drawing pins as `O` and missing pins as `.`, the formation `1 3 5 6 9 10` is:

```
. . O O
 . O O
  . O
   O

```

**Input:**

A space-separated string that lists a nonempty subset of the numbers 1 though 10 in order.

**Output:**

Print the corresponding formation or output it as a string with linebreaks.

The formation should be flush with the left of the screen. Any whitespace is fine as long as the visible image is correct. Empty lines before and after are fine too.

**Test cases:**

```
>> 1 2 3 4 5 6 7 8 9 10

O O O O
 O O O
  O O
   O

>> 7 10

O . . O
 . . .
  . .
   .

>> 3 5 7 9 10

O . O O
 . O .
  . O
   .

>> 1

. . . .
 . . .
  . .
   O

```

# Answer
# brainfuck - ~~617~~ ~~616~~ 604 bytes

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

```

This took me the better part of two days. I think it was worth it. There's probably parts that can be golfed more by changing what cell something is stored in or whatever, but right now I'm just happy I got it working.

This program would have to be completely different if the question didn't specify that the input would be sorted. The way this works is by constructing a list of 10 pins around the ones that are input. That's kind of confusing but maybe this will explain it better:

```
If you input these pins:           [2, 3, 6, 8, 9]
First, the program does this:      [2, 3, 6, 8, 9] + [10]
Then this:                         [2, 3, 6] + [7] + [8, 9, 10]
Then this:                         [2, 3] + [4, 5] + [6, 7, 8, 9, 10]
Finally, this:                     [1] + [2, 3, 4, 5, 6, 7, 8, 9, 10]
To build this:                     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

```

While it's doing that, it remembers which of the pins the user put there and which ones it put there. This strategy would be very difficult to use if the input wasn't sorted.

Another thing that the sorting make easier is detection of the number 10. Since brainfuck deals with individual bytes, not "numbers" per se, it could have been a pain in the ass, but the sorted input made it much easier for me to deal with. The reason for that has to do with how I stored data in the program. I take the input one character at time and subtract 32 from the result. If the cell is non-zero after that, I move forward 4 cells. before repeating. This means that I get a non-space byte of input every 4 cells, and I effectively store pins as their number + 16. However, 10 takes two bytes to type, so I had to special case it. If the input wasn't sorted, I'd have to look through the pins, but since it is sorted it will always be the last pin if it appears. I check if the (last byte of input + 1) == (the second last byte of input) and if so, it must be 10. I get rid of the last byte and set the second last one to what my system understands as "10". The characters `'1'` and `'0'` don't fit in a single byte, but the number 26 sure does!

Coming up with tricks just to make something work at all is my favourite part of using this language. :)

If you're interested in how this program works in more detail, you can see the program with the comments I used while writing it to make sure I remembered what everything did. Even writing comments in brainfuck is hard, since there's no comment syntax. Instead, every character except those in `<[+.,-]>` are no-ops. It's easy to introduce bugs by accidentally including `.` or `,` in your comments! That's why the grammar is so wonky and semicolons are everywhere.

**EDIT:** As an example of how easy this is to screw up: I used "non-space" in one of the comments! When I stripped all the non-bf characters from the source, the program I used to do that kept in the `-`. Luckily it didn't break anything, but now I've removed it to save a byte. :)

**EDIT II:** It's been a while since I touched this one, haha. In another brainfuck answer on this site, I noticed that I accidentally used a comma in the commented version. Since the input had already been exhausted, it set the current cell to 0 (this is implementation dependant, but in my experience it's the most common behaviour). I fixed the bug, but it got me thinking. The idiomatic way to set a cell to 0 is `[-]` (roughly `while (*p) { *p--; }`), which is two bytes longer. Any time all the input has been read, I can use `,` instead. This saved me 2 bytes in that answer, and 12 in this one!

```
one flag at the very left; will be important later
+>>>>

all nonspace bytes of input separated by 3 empty cells; pin number `n` stored with value `n` plus 16
,[>++++[<-------->-]<[>>>>],]<<<<

test if last pin is 10
[>+<<+<+>>-]<[>+<-]+<+<<[>+>-<<-]>[<+>-]>

[
    if not: find 10 minus the number it is; put that many placeholder pins (cells with value 1) at the end
    ,+++++[>+++++<-]>>[<->-]<[>>>>>[>>>>]+[<<<<]<-]>>[<+>-]<<<
]>

[
    if so: get rid of '0' byte; convert '1' byte to 26 (10 plus 16)
    >>[,<]<<+++++++++<
]<<<

pointer now sitting on the cell with the second greatest pin that was inputted (ie not a placeholder)

;;;;;;;

[
    check for flag placed at the very beginning of the program; if present: break
    -[+>>-<]>
    [
        find ((pin to our right) minus 1) minus pin to our left
        move all pins left of us 4*(that value) cells and insert placeholder pins
        >>[<+<+>>-]<<<<[>+>-<<-]>[<+>-]>[<<[<<<<]>>>>[[<<<<+>>>>-]>>>>]<<<<+>>-]>[>+<-]
    ]

    find first non placeholder pin to our left
    there has to be one because we haven't hit the flag yet
    <<<[-[+>]+<<<<]>>>>-<<<<<
]>>>>>+

we have now added placeholder pins at the end and in the middle; all that's left is the beginning

subtract 17 from lowest pin and put that many placeholders to the left
++++[>----<-]>->[<+>>+<-]<[<<<[<<<<]+[>>>>]<-]>>[<+>-]

subtract 32 from an empty cell 2 to the left of the lowest pin; will be useful later
<[<<<<]>>>++++[<-------->-]>

placeholder pins have the value 1; real pins have a value somewhere between 17 and 26
normalize it by stepping through and setting every pin with value != 1 to 3 (0's ascii code is 2 higher than period so this will make it easier to print later)
[-[,+++>]+>>>[<<<->>]>]<<<<<[>-]>[>>]>>

start writing 32s across the board; hitting every second cell
that's every pin and the cell 2 to the right of each pin
this is done in such a way that it will only halt if adding 32 to a cell sets it to 0; which is why we subtracted 0 from an empty cell earlier
it will catch us and prevent an infinite loop
+[<++++[<++++++++>-]<]

now write 13 to each pin; this adds up to 46 or 48; which are exactly the ascii values we want
>>[+++++++++++++>>>>]

we happen to have made a 14; turn it into a 10 for a newline
<<<<----

we're so close now; i can taste it
we have a list of 10 pins; each one with the ascii value that needs to be written
we have 32 everywhere because we'll need spaces
we even have a newline

the only problem now is that our list looks like this:
;;;;;;;;;;;;;;;;;;;;;;;;
;;1 2 3 4 5 6 7 8 9 10;;
;;;;;;;;;;;;;;;;;;;;;;;;

and we need to print in this order:
;;;;;;;;;;;;;;;;;;;;;;;;
;;7 8 9 10 4 5 6 2 3 1;;
;;;;;;;;;;;;;;;;;;;;;;;;

it's a pretty simple fix
once we print a pin we obviously don't need to remember it any more
so we simply print the last 4 pins on the list; destroying them on the way
then we print the last 3; which have become the ones we want
then two; then one
<+++[<<+<<[<<+<<]+[>>>>]<<<<-]<<<<[-<<<<]

print pins 7 8 9 10
>[.,>>]

print pins 4 5 6
<<<<<[<<<<]<++++++++++<<.<+<<+<<+<<+<<+<[.,>>]

print pins 3 2
<<<<<[<<]>++++++++++<+<<+<<+<..<+<[.,>>]

print the final pin!! :)
<[<<]<...<<.

```
> 18 votes

# Answer
# Python 2, 108 bytes

```
def f(x):
 for i in 4,3,2,1:print" "*(4-i)+" ".join(".O"[i*~-i/2-~z in map(int,x.split())]for z in range(i))

```

Call with `f("3 5 7 9 10")`.

`i` is the row number, with 4 being the first row and 1 being the last. `z` is the nth pin on that row, with 0 meaning it's the first pin in the row and `i-1` meaning it's the last pin in the row.

The main hack is `i*~-i/2-~z`, which converts `(i, z) -> pin number`. For example, `(4, 0) -> 7` as pin 7 is the first pin on row 4 (the first row). The derivation goes like this:

* We want a function taking `i` to the first pin on row `i`, i.e. `4 -> 7, 3 -> 4, 2 -> 2, 1 -> 1`. This is satisfied by `(i**2-i)/2 + 1`, and thus `(i**2-i)/2 + 1 + z` gives the correct pin number for input `(i, z)`
* Then simplify:

```
(i**2-i)/2 + 1 + z
  = (i*(i-1))/2 + 1 + z
  = i*~-i/2 + 1 + z
  = i*~-i/2-~z

```

---

# Pyth, 33 bytes

```
V4~Z-4N+*dNjdm@".O"}+d-11Zrz7U-4N

```

Try it online.

The program roughly translates to:

```
z = input()
Z = 0

for N in range(4):
  Z += 4-N
  print(" "*N + " ".join(".O"[d+11-Z in map(int, z.split())] for d in range(4-N)))

```

*(Thanks to isaacg for tips)*
> 13 votes

# Answer
# Pyth, 31

```
V4+*dNjdm?\O}+7+dZrz7\.rN4~Z-N4

```

Try it here.

`V4` sets up a for loop, with N as the variable over \[0,1,2,3\].

`*dN` provides the initial spaces, because `d` is space.

To find the pin locations, it uses `+7+dZ` \- 7 + d + Z.

`d` is:

```
0 1 2 3
 1 2 3
  2 3
   3

```

while `Z` is 0 in the first line, -4 in the second, -7 in the third and -9 in the forth. This is becasue `Z` starts as 0, and `~Z-N4` decrements `Z` by 4, then 3, then 2.

Then, it checks if the pin location is in the input, using `}+7+dZrz7`. `rz7` is the desired pins in list-of-int form.

Then, it creates an `O` if it was present, and `.` otherwise. This is space separated, with `jd`, and printed implicitly.
> 9 votes

# Answer
# Python 2, ~~97~~ 94

This uses the translate function, which allows one to make character-for-character substitutions in a string. Like tr in perl, except much longer to type. I get a list of decimal digits by making a string from 9 to the 99th power.

```
lambda a:u"7890\n 456\n  23\n   1".translate({ord(n):u'.O'[n+' 'in a+' ']+' 'for n in`9**99`})

```
> 5 votes

# Answer
# Perl 5: 51 (50 + 1 for `-p`)

Using `r` flag for `s///` which is one of the recent perl 5 additions.

```
#!perl -p
$_="7890
 456
  23
   1
"=~s!\d!'. '^a
x/$&\b/!egr

```
> 5 votes

# Answer
# CJam, ~~48~~ 41 bytes

Wow, this got horribly long

```
"6789345 12  0"S*7/N*[l~]:(s"O"erA,s"."er

```

Test it here.

## Explanation

First we generate the layout:

```
"6789345 12  0"       "Push this string.";
               S*     "Riffle with spaces.";
                 7/   "Split into substrings of length 7.";
                   N* "Join with newlines.";

```

This yields

```
6 7 8 9
 3 4 5
  1 2
   0

```

And now we replace the digit characters according to the input:

```
[l~]                 "Read the input and turn it into an array of integers.";
    :(s              "Decrement each number and turn the array into a string of digits.";
       "O"           "Push this string.";
          er         "Character transliteration, replaces the input digits with O.";
            A,s      "Create the string '0123456789'.";
               "."   "Push this string.";
                  er "Character transliteration, replaces all remaining digits with periods.";

```
> 5 votes

# Answer
# GNU sed, 75

* Saved 6 bytes thanks to @Jordan.

Score includes 1 extra for `-r` option:

```
s/^/7 8 9 10\
 4 5 6\
  2 3\
   1 /
:
s/([0-9]+)(.*)\1/O\2/
t
s/[0-9]+/./g

```

Input via STDIN:

```
$ echo 3 5 7 9 10 | sed -rf ./bowling.sed
O . O O
 . O .
  . O
   .
$

```

Try it online.
> 5 votes

# Answer
# Javascript, 155

First golf, can probably be shorter.

```
function f(i){q='replace',s='7 8 9 0\n 4 5 6\n  2 3\n   1';alert(s[q](RegExp(i[q]('10','0')[q](/ /g,'|'),'g'),function(a){return a?'O':a})[q](/\d+/g,'.'))}

```

call with

```
f('1 2 3 4 5 6 7 8 9 10')
f('1 5 10')
f('')

```

**EDIT**

# ES6 version, 130

```
f=i=>{q='replace',s='7 8 9 0\n 4 5 6\n  2 3\n   1';alert(s[q](RegExp(i[q]('10','0')[q](/ /g,'|'),'g'),a=>a?'O':a)[q](/\d+/g,'.'))}

```

**EDIT**

# ~~ES6 version, 79~~ fails

```
f=i=>alert('7890\n 456\n  23\n   1'.replace(/\d/g,a=>i.indexOf(a)<0?'. ':'O '))

```

# ES6 version, ~~72~~ 77, no alert, just returns

```
f=i=>'7890\n 456\n  23\n   1'.replace(/\d/g,a=>i.search(a+'\\b')<0?'. ':'O ')

```
> 5 votes

# Answer
# Ruby, 91

```
x=(1..10).map{|i|i.to_s==$*[0]?($*.shift;?0):?.}
4.times{|i|puts (x.pop(4-i)*' ').center 8}

```

Simply substitutes the command line arguments with `.`s and `0`s and prints them using a loop of 4 cycles.

### Readable version

```
x = (1..10).map do |i|
  if i.to_s == ARGV[0]
    ARGV.shift
    "0"
  else
    "."
  end
end

4.times do |i|
  row = x.pop(4 - i)
  puts row.join(' ').center 8
end

```
> 4 votes

# Answer
# CJam, ~~40~~ 39 bytes

```
4,Sf*'-A*[q~]{('ot}/3,{)/(\s}%Sf*W%]zN*

```

I know there is a shorter way, don't have time to figure it out right now.

How it works:

```
4,Sf*'-A*[q~]{('ot}/3,{)/(\s}%Sf*W%]zN*
4,                                          "Get the array [0,1,2,3]";
  Sf*                                       "Covert each number to that many spaces to";
                                            "get ["", " ", "  ", "   "] array";
     '-A*                                   "String '----------'";
         [q~]                               "Input numbers in an array";
             {    }/                        "For each input number";
              ('ot                          "Put 'o' at the corresponding index";
                    3,                      "Array [0,1,2]";
                      {     }%              "For each of the above number";
                       )                    "Increment the number";
                        /                   "Split the string into pieces of that length";
                         (\s                "Take the first string and join the rest back";
                              Sf*           "Riffle each string in array with space";
                                 W%         "Reverse the array of strings";
                                   ]z       "Zip together the space array and this one";
                                     N*     "Join by new line";

```

Try it online here
> 3 votes

# Answer
# Pure bash (no coreutils), 85

Simple pattern replacement:

```
f="7 8 9 0
 4 5 6
  2 3
   1"
a=${@/10/0}
f="${f//[${a// /}]/O}"
echo "${f//[0-9]/.}"

```

List is input via the command-line args.
> 3 votes

# Answer
## APL (35)

```
⊖4 7⍴'.O'[1+⎕∊⍨⍳10]\⍨17110357⊤⍨28/2

```

Test:

```
      ⊖4 7⍴'.O'[1+⎕∊⍨⍳10]\⍨17110357⊤⍨28/2
⎕:
      1 3 5 6 9 10
. . O O
 . O O
  . O
   O

```

Explanation:

* `17110357⊤⍨28/2`: the 28-bit representation of `17110357`:

```
      4 7⍴17110357⊤⍨28/2
0 0 0 1 0 0 0
0 0 1 0 1 0 0
0 1 0 1 0 1 0
1 0 1 0 1 0 1

```
* `\⍨`: For every `0`, give a space, and for every `1`, take an item from the string on the left.
* `⎕∊⍨⍳10`: Read a line from the keyboard and evaluate it (), then check for every number from 1 to 10 (`⍳10`) whether or not it is contained in the input (`∊⍨`).
* `'.O'[1+`...`]`: Add 1 to every value (giving 1s and 2s instead of 0s and 1s), and then replace every 1 by `.` and every 2 by `O`.
* `4 7⍴`: turn the generated string into a 4-by-7 matrix
* : flip it horizontally
> 3 votes

# Answer
# Powershell: 109

Input is in $i

```
(7..10),(4..6),(2,3),1|%{$c=0}{$_|%{$o=(" "*$c++)}{$o="$o $(if($i.split() -contains $_){'O'}else{'.'})"};$o}

```

That was fun. Learned a bunch of stuff about how the pipeline works, too.
> 3 votes

# Answer
## Haskell: ~~163~~ 160 bytes

This accepts a line of space separated numbers from `stdin`.

```
m=map
y?x|x`elem`y="O "|0<1=". "
f y=putStr.unlines.zipWith(++)(m(`replicate`' ')[0..])$m(concat.m(y?))[[7..10],[4..6],[2,3],[1]]
main=getLine>>=f.m read.words

```

### Ungolfed:

```
layout :: [[Int]]
layout = [[7,8,9,10]
         ,[ 4,5,6  ]
         ,[  2,3   ]
         ,[   1    ]
         ]

indentBy :: Int -> String
indentBy n = replicate n ' '

indentLines :: [String] -> [String]
indentLines
  = zipWith (++)
            (map indentBy [0..])

bowling :: [Int] -> String
bowling pins
  = unlines
  . indentLines
  $ map (concatMap showPlace)
        layout
  where
    showPlace :: Int -> String
    showPlace index
      | index `elem` pins = "O "
      | otherwise         = ". "

parseInput :: String -> [Int]
parseInput = map read . words

main :: IO ()
main = do
  pins <- fmap parseInput getLine
  putStr (bowling pins)

```

---

And a bonus:

## C: 250 bytes

This version expects its command line arguments to be the list of numbers.

```
#define w int
main(w
z,char**a){w
b[10]={1,3,2,6,5,4,10,9,8,7};w
q=9;for(w
k=4;k>0;--k){w
i;for(i=0;i<4-k;++i)printf(" ");for(i=0;i<k;++i,--q){w
g=0;w
c;for(w
p=1;p<z;++p){sscanf(a[p],"%d",&c);g|=b[q]==c;}c=g?'O':'.';printf("%c ",c);}printf("\n");}}

```
> 3 votes

# Answer
# Perl, 73

```
$_="7 8 9 10\n 4 5 6\n  2 3\n   1";for$v(<>=~/\d+/g){s/$v/O/g};s/\d+/./g;print

```

And a goofy bonus approach that didn't pan out, 90 characters:

```
srand(1488068);$i=<>;print+(($i=~/$_\b/?O:".")." "x rand 5)=~s/  /\n /r for 7..10,4..6,2,3,1

```
> 2 votes

# Answer
# Mathematica, 109 bytes

Function:

```
f=(i=0;Reverse@Table[Row@Table[If[MemberQ[ToExpression/@StringSplit@#,++i],O,"."],{n}],{n,4}]~Column~Center&)

```

Called by:

```
f@"3 5 7 9 10"

```

If anonymous functions are allowed, this can be shortened to **105 bytes**:

```
i=0;Reverse@Table[Row@Table[If[MemberQ[ToExpression/@StringSplit@#,++i],O,"."],{n}],{n,4}]~Column~Center&

```

If the input didn't have to be a space-delimited string, but could be an array of numbers in the form `{3,5,7,9,10}`, this can be further shortened to **79 bytes**:

```
i=0;Reverse@Table[Row@Table[If[MemberQ[#,++i],O,"."],{n}],{n,4}]~Column~Center&

```
> 2 votes

# Answer
# Rebol - 117

```
s: array/initial 10"."b:""foreach n to-block input[s/:n:"0"]for n 4 1 -1[prin b print take/last/part s n append b" "]

```

Ungolfed:

```
s: array/initial 10 "."
b: ""
foreach n to-block input [s/:n: "0"]
for n 4 1 -1 [prin b print take/last/part s n append b " "]

```
> 2 votes

# Answer
## Brainfuck, 179 bytes

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

```

Formatted:

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

```

Expects input without a trailing newline.

Try it online.

The tape is initialised with ten nodes, each of which contains a one followed by a zero. The one is the initial value of the pin, and the zero facilitates navigation and acts as a placeholder for the space character. For each number in the input, that pin is incremented by 3; note that `ord('O') - ord('.') = 33`, and during the printing phase, the pin's value will be multiplied by 11. (This multiplication is also used to generate the space character.) The order of the pins from left to right on the tape is simply `1` up to `10`. If the input ends with a `10`, a correction is made, since the `10` is initially treated as a `1`.

After the input has been processed, a negative one is placed after each row. Then the rows are printed in a loop, with the number of leading spaces determined by the number of rows previously processed.
> 2 votes

# Answer
# Powershell, 84 bytes

```
$p='6789
 345
  12
   0'
-split$args|%{$p=$p-replace($_-1),'O '}
$p-replace'\d','. '

```

Test script:

```
$f = {

$p='6789
 345
  12
   0'
-split$args|%{$p=$p-replace($_-1),'O '}
$p-replace'\d','. '

}

# one space at the end of each line with pins
@(
,("1 2 3 4 5 6 7 8 9 10",
@"
O O O O
 O O O
  O O
   O
"@)

,("7 10",
@"
O . . O
 . . .
  . .
   .
"@)

,("3 5 7 9 10",
@"
O . O O
 . O .
  . O
   .
"@)

,("1",
@"
. . . .
 . . .
  . .
   O
"@)
) | % {
    $s, $expected = $_
    $result = &$f $s
    $result-eq$expected
    $result
}

```

Output:

```
True
O O O O
 O O O
  O O
   O
True
O . . O
 . . .
  . .
   .
True
O . O O
 . O .
  . O
   .
True
. . . .
 . . .
  . .
   O

```
> 2 votes

# Answer
# Clojure, 216 chars (ugh)

I'm sure this can be golfed further.

```
(let[s(map #(dec(read-string %))(.split(slurp *in*)" +"))](println(apply str(replace(apply hash-map(interleave(map #(char(+ 48 %))(range 10))(map #(if(some #{%}s)"O"".")(range 10))))"6 7 8 9\n 3 4 5\n  1 2\n   0"))))

```

Use like this:

```
echo -n "2 4 9 8 10 5" | clojure a-file-which-contains-this-program.clj

```
> 1 votes

# Answer
## AWK: 96 bytes

```
{gsub(/ /,"");a="6 7 8 9\n 3 4 5\n  1 2\n   0";gsub("["$0"]","O",a);gsub(/[0-9]/,".",a);print a}

```

Note:

* The spaces separators on the input value are optional (but it works also with them as required)
* The numbers don't have to be in order
* The input is read on STDIN
> 1 votes

# Answer
# C# - 192 bytes

Because C#!

I started out trying to build the output with math, but the simple replace-tokens-in-string method seems best for higher-level languages. Linq dependency is longish but still shorter than keeping a counter and doing range checks.

```
using System.Linq;class A{static void Main(string[]a){var s=@"7 8 9 0
 4 5 6
  2 3
   1";for(int c=11;c-->1;)s=s.Replace((char)(48+c%10),a.Contains(""+c)?'O':'.');System.Console.Write(s);}}

```

EDIT: unix line returns (-3 bytes)
> 1 votes

# Answer
# Scala, ~~150~~148

```
def t(n:Any)=("G H I J D E F   B C     A"/:('A'to'J'))((j,i)=>j.replace(i,(if((n+" ").indexOf((i-64)+" ")>=0)'0'else'.'))).grouped(7).maxBy(println)

```

Accepts space-delimited set of strings
> 1 votes

# Answer
# JavaScript ES6, 78 bytes

```
F=i=>'7890\n 456\n  23\n   1'.replace(/\d/g,e=>'0.'[+!~i.search(e+'\\b')]+' ')

```

Use the following snippet to test. It uses prompts and alerts and regular function notation for ease of testing.

```
i=prompt()
alert('7890\n 456\n  23\n   1'.replace(/\d/g,function(e){return'0.'[+!~i.search(e+'\\b')]+' '}))
```
> 1 votes

# Answer
**VB/Basic-229**

My goal was to beat java^^

```
Dim f
Sub m()
f = " 1 2 3 4 5 6 7 8 9 10"
a = l(7, 10) + l(4, 6) + l(2, 3) + l(1, 1)
MsgBox a
End Sub
Function l(b, e)
r = Space(3 - (e - b))
For i = b To e
r = r + IIf(InStr(f, Str(i)), "0 ", ". ")
Next
l = r + vbCr
End Function

```

edit vbCr instead of chr(13)

r = r + Space(3 - (e - b))

shorthand if

use of function instead of sub

sub MAIN() - \> sub m()
> 1 votes

# Answer
# Java - 223 chars

```
public class Pins {public static void main(String[] args) {String s = "7 8 9 0\n 4 5 6\n  2 3\n   1";for (String arg : args) {s = s.replace(arg.replace("10", "0"), "o");}s = s.replaceAll("\\d", ".");System.out.println(s);}}

```

I used to like this way of doing it, then I realized I needed a small hack, still kind of like my solution.

```
public class Pins {
public static void main(String[] args) {
    String s = "7 8 9 0\n 4 5 6\n  2 3\n   1";
    for (String arg : args) {
        s = s.replace(arg.replace("10", "0"), "o");
    }
    s = s.replaceAll("\\d", ".");
    System.out.println(s);
}
}

```
> 1 votes

# Answer
# K, 57 bytes

Not very competitive yet, but it's a start:

```
`0:((!4)#\:" "),',/'|0 1 3 6_(". ";"O ")@|/(1+!10)=/:(),.

```

Usage example:

```
  `0:((!4)#\:" "),',/'|0 1 3 6_(". ";"O ")@|/(1+!10)=/:(),."3 5 7 9 10"
O . O O
 . O .
  . O
   .
  `0:((!4)#\:" "),',/'|0 1 3 6_(". ";"O ")@|/(1+!10)=/:(),."1"
. . . .
 . . .
  . .
   O

```

I begin by evaluating the input string with `.`\- fortunately, space separated numbers are a valid list literal in K. By prepending an empty list to the result of eval I can ensure it's a list even in the case of a single pin. Then I create a boolean vector representing the positions of pins:

```
  (1+!10)=/:3 5 7 9 10
(0 0 1 0 0 0 0 0 0 0
 0 0 0 0 1 0 0 0 0 0
 0 0 0 0 0 0 1 0 0 0
 0 0 0 0 0 0 0 0 1 0
 0 0 0 0 0 0 0 0 0 1)
  |/(1+!10)=/:3 5 7 9 10
0 0 1 0 1 0 1 0 1 1

```

Then I index into a list of strings to get space-padded characters for each pin position.

```
  (". ";"O ")@0 0 1 0 1 0 1 0 1 1
(". "
 ". "
 "O "
 ". "
 "O "
 ". "
 "O "
 ". "
 "O "
 "O ")

```

I slice that sequence into rows (`_`), reverse them (`|`) and join together each fragment (`,/'`):

```
  ,/'|0 1 3 6_(". ";"O ")@0 0 1 0 1 0 1 0 1 1
("O . O O "
 ". O . "
 ". O "
 ". ")

```

Now it's starting to look like the pattern we want. All that's left is to tack on some leading spaces to each row (`((!4)#\:" "),'`) and print the rows to stdout (`0:`).
> 1 votes

# Answer
# Japt `-Rx`, ~~29~~ ~~19~~ ~~18~~ 17 bytes

```
5ÇÆ".O"gUø°TÃ¸ÃÔû

```

Try it

---

## Explanation

```
                      :Implicit input of integer array U
5Ç                    :Map each Z in the range [0,5)
  Æ                   :  Map the range [0,Z)
          °T          :    Increment T (initially 0)
        Uø            :    Does U contain T? (false=0, true=1)
   ".O"g              :    Get the character in the string ".O" at that index
            Ã         :  End mapping
             ¸        :  Join with spaces
              Ã       :End mapping
               Ô      :Reverse
                û     :Centre pad each element with spaces to the length of the longest
                      :Implicitly join with newlines, trim (not strictly necessary) and output

```
> 1 votes

# Answer
# Pascal (FPC), 165 bytes

```
var f:string='. . . .'#10' . . .'#10'  . .'#10'   .';i:byte;z:array[1..10]of byte=(25,18,20,10,12,14,1,3,5,7);begin repeat read(i);f[z[i]]:='O'until eof;write(f)end.

```

Try it online!

Takes numbers from standard input, prints the formation to standard output.

### Pascal (FPC), 175 bytes

```
function f(q:array of byte):string;var i:byte;z:array[1..10]of byte=(25,18,20,10,12,14,1,3,5,7);begin f:='. . . .'#10' . . .'#10'  . .'#10'   .';for i in q do f[z[i]]:='O'end;

```

Try it online!

A function which does the same thing, taking an array of pin positions and returning a formatted string.
> 1 votes

# Answer
# Vyxal, 43 bytes

```
`7 8 9 0
 4 5 6
  2 3
   1`?⌈(nt\OV)‛\d\.øṙ

```

Try it Online!

Nothing clever, just a simple substitution.
> 1 votes

# Answer
# Haskell, 96 bytes

```
main=interact$ \a->do
c<-"7 8 9 0\n 4 5 6\n  2 3\n   1"
max['O'|elem c$last<$>words a]$min"."[c]

```

Try it online!
> 1 votes

# Answer
# JavaScript (Node.js), ~~73~~ 69 bytes

Thanks @l4m2 for saving 4 bytes

```
s=>`7890
 456
  23
   1`.replace(/\d/g,d=>s.match(d+"\\b")?"0 ":". ")

```

Attempt This Online!

Explanation:

* `s=>...` Anonymous function taking string argument `s`
* ``7890...`` Multiline string
* `.replace(/\d/g,d=>...)` Replace each digit `d` with:
* `s.match(d+"\\b")` Check if `s` contains `d` followed by a word boundary
* `?"0 ":". "` If it does, replace with `"0 "`, else with `". "`
> 1 votes

# Answer
# Java - ~~371~~ ~~316~~ 294 chars

```
public class Bowling{public static void main(String[] a){boolean[] o=new boolean[10];int i;for(String s:a){i=Integer.parseInt(s)-1;o[i]=true;}for(int j=9;j>=0;j--){p((o[j]?"0 ":". "));p(j==6?"\n ":"");p(j==3?"\n  ":"");p(j==1?"\n   ":"");}p("\n");}static void p(String l){System.out.print(l);}}

```

First time doing this, I'm pretty sure it's shitty, but I'm a novice. It also works when the numbers aren't ordered. The numbering is wrong but I don't have time to find out how to fix it...

```
public class Bowling {
    public static void main(String[] args) {
        boolean[] ordened = new boolean[10];
        int i;
        for (String s : args) {
            i = Integer.parseInt(s) - 1;
            ordened[i] = true;
        }
        for (int j = 9; j >= 0; j--) {
            p((ordened[j] ? "0 " : ". "));
            p(j == 6 ? "\n " : "");
            p(j == 3 ? "\n  " : "");
            p(j == 1 ? "\n   " : "");
        }
        p("\n");
    }
    static void p(String l){
        System.out.print(l);
    }
}

```

input is given by `java B 1 2 3 5 10` for example. Output will then be:

```
0 . . .
 . 0 .
  0 0
   0

```
> 0 votes

# Answer
# 05AB1E, 15 bytes

```
TLå4L£R».cT„O.‡

```

Input as a list (if input as a space-delimited string is mandatory, a leading `#` (+1 byte) can be added to split the implicit input-string by spaces to the necessary list).

Try it online or verify all test cases.

**Explanation:**

```
                #  (e.g. input = [2,7,10])
TL              # Push a list in the range [1,10]
                #  STACK: [1,2,3,4,5,6,7,8,9,10]
  å             # Check for each whether it's in the (implicit) input-list,
                # resulting in a list of 1s and 0s
                #  STACK: [0,1,0,0,0,0,1,0,0,1]
   4L           # Push a list in the range [1,4]
                #  STACK: [0,1,0,0,0,0,1,0,0,1],[1,2,3,4]
     £          # Split the earlier list into parts of those sizes:
                #  STACK: [[0],[1,0],[0,0,0],[1,0,0,1]]
      R         # Reverse it
                #  STACK: [[1,0,0,1],[0,0,0],[1,0],[0]]
       »        # Join each inner list by spaces, and then each line by newlines
                #  STACK: "1 0 0 1\n
                #          0 0 0\n
                #          1 0\n
                #          0"
        .c      # Centralize it by prepending spaces where necessary
                #  STACK: "1 0 0 1\n
                #           0 0 0\n
                #            1 0\n
                #             0"
              ‡ # Transliterate
          T     # the digits of "10"
           „O.  # to the characters of "O."
                # (which replaces all "1" with "O" and "0" with "." respectively)
                #  STACK: "O . . O\n
                #           . . .\n
                #            O .\n
                #             ."
                # (after which the result is output implicitly)

```
> 0 votes

# Answer
# R 4.2, 159 bytes

```
f=function(x)cat(sapply(X=4:1,FUN=function(X){i=((X^2-X)/2+1);c(rep(" ",4-X),paste0(ifelse(1:10%in%strsplit(x," ")[[1]],"0",".")[i:(i+X-1)]," "),"\n")}),sep="")

```

Try it online!

```
# ungolfed:
f = function(s) {
  nums = strsplit(s, " ")[[1]]  # split input string
  idx = 1:10 %in% nums          # convert 1:10 to logical vector for given pins
  ind01 = ifelse(idx,"0",".")   # convert to ASCII characters
  cat(                          # concatenate rows of output
    sapply(X=4:1,               # iterate through rows
           FUN=function(X){
             i=((X^2-X)/2+1);   # same hack as @Sp3000 (nice!)
               c(rep(x=" ",times=4-X), # add leading spaces
                 paste0(ind01[i:(i+X-1)]," "),  # print ASCII chars separated by space
                 "\n")          # new line after each row
             }
           ),
    sep="")                     # remove default space between elements
}

f("1 2 3 4 5 6 7 8 9")
f("7 10")
f("3 5 7 9 10")
f("1")

```
> 0 votes

---
Tags: code-golf, ascii-art, hexagonal-grid
---


title: Hypercube elements

text:
# Question
Title: Hypercube elements
Write a function or program that outputs the number of each type of element (vertex, edge, face, etc.) of an N-dimensional hypercube.

As an example, the 3 dimensional cube has 1 cell (i.e. 1 3-dimensional cube), 6 faces (i.e. 6 2-dimensional cubes), 12 edges (i.e. 12 2-dimensional cubes) and 8 vertices (i.e. 8 0-dimensional cubes).

More details about Hypercube elements can be found here

You can as well take a look at the following OEIS sequence.

### Input

Your code will take as input (via STDIN or a function parameter or similar things) an integer greater or equal to 0, which is the dimension of the hypercube.

Your code has to theoretically work for any input \>= 0, disregarding memory and time issues (that is, speed and potential stack overflows are not a problem for your answer if the input is big). Inputs given as test cases will not be above 12.

### Output

You will ouput a list of all elements of the hypercube, starting with the "highest dimension" element. For example, for a cube (input = 3), you will output the list `[1,6,12,8]` (1 cell, 6 faces, 12 edges, 8 vertices).

The format of the list in the output is relatively free, as long as it looks like a list.

You can output the result to STDOUT or return it from a function.

### Test cases

```
Input = 0
Output = [1]

Input = 1
Output = [1,2]

Input = 3
Output = [1,6,12,8]

Input = 10
Output = [1, 20, 180, 960, 3360, 8064, 13440, 15360, 11520, 5120, 1024]

Input = 12
Output = [1, 24, 264, 1760, 7920, 25344, 59136, 101376, 126720, 112640, 67584, 24576, 4096]

```

### Scoring

This is , so the shortest answer in bytes wins.

# Answer
# Samau, ~~8~~ 5 bytes

Saved 3 bytes thanks to Dennis.

```
▌2\$ⁿ

```

Hex dump (Samau uses CP737 encoding):

```
dd 32 2f 24 fc

```

Explanation:

```
▌        read a number
 2\      push the array [1 2]
   $     swap
    ⁿ    take the convolution power

```

Convolving two vectors is equivalent to multiplying two polynomials. Similarly, taking the n-th convolution power is equivalent to taking the n-th power of a polynomial.
> 10 votes

# Answer
# J, 13 bytes

```
[:p.2&^;$&_.5

```

Inspired by @alephalpha's PARI/GP answer. Try it online with J.js.

### Background

By the binomial theorem,

Thus, the output for input **n** consist precisely of the coefficients of the above polynomial.

### Code

```
[:p.2&^;$&_.5  Monadic verb. Argument: n

        $&_.5  Yield an array of n instances of -0.5.
    2&^        Compute 2^n.
       ;       Link the results to the left and right.
               This specifies a polynomial of n roots (all -0.5)
               with leading term 2^n.
[:p.           Convert from roots to coefficients.

```
> 11 votes

# Answer
# MATL, 8 bytes

```
1i:"2:X+

```

Inspired by @alephalpha's PARI/GP answer.

Try it online! (uses `Y+` for modern day MATL)

### How it works

```
1        % Push 1.
 i:      % Push [1 ... input].
   "     % Begin for-each loop:
    2:   %   Push [1 2].
      X+ %   Take the convolution product of the bottom-most stack item and [1 2].

```
> 10 votes

# Answer
## MATL, 12 bytes

```
Q:q"H@^G@Xn*

```

**Try it online**

### Explanation

```
         % implicit: input number "n"
Q:q      % generate array[0,1,...,n]
"        % for each element "m" from that array
  H@^    % compute 2^m
  G      % push n
  @      % push m
  Xn     % compute n choose m
  *      % multiply
         % implicit: close loop and display stack contents

```
> 8 votes

# Answer
# Mathematica, 29 bytes

```
CoefficientList[(1+2x)^#,x]&

```

My first Mathematica answer! This is a pure function that uses the same approach as Alephalpha's PARI/GP answer. We construct the polynomial `(1+2x)^n` and get the list of coefficients, listed in order of ascending power (i.e. constant first).

Example usage:

```
> F := CoefficientList[(1+2x)^#,x]&`
> F[10]
{1,20,180,960,3360,8064,13440,15360,11520,5120,1024}

```
> 8 votes

# Answer
# PARI/GP, ~~20~~ 15 bytes

```
n->Vec((x+2)^n)

```
> 6 votes

# Answer
# APL, ~~15~~ 11 bytes

```
1,(2*⍳)×⍳!⊢

```

This is a monadic function train that accepts an integer on the right and returns an integer array.

Explanation, calling the input `n`:

```
        ⍳!⊢  ⍝ Get n choose m for each m from 1 to n
       ×     ⍝ Multiply elementwise by
  (2*⍳)      ⍝ 2^m for m from 1 to n
1,           ⍝ Tack 1 onto the front to cover the m=0 case

```

Try it online

Saved 4 bytes thanks to Dennis!
> 6 votes

# Answer
# Jelly, 8 bytes

```
0rð2*×c@

```

I should really stop writing Jelly on my phone.

```
0r            Helper link. Input is n, inclusive range from 0 to n. Call the result r.
  ð           Start a new, dyadic link. Input is r, n.
   2*         Vectorized 2 to the power of r
     ×c@      Vectorized multiply by n nCr r. @ switches argument order.

```

Try it here.
> 5 votes

# Answer
## TI-BASIC, 10 bytes

```
3^Ansbinompdf(Ans,2/3

```
> 4 votes

# Answer
## CJam (17 14 bytes)

```
ri_3@#_2+@#\b`

```

Online demo

This approach uses the ordinary generating function `(x + 2)^n`. The OEIS mentions `(2x + 1)^n`, but this question indexes the coefficients in the opposite order. I'm kicking myself for not thinking to reverse the g.f. until I saw Alephalpha's update to the PARI/GP answer which did the same.

The interesting trick in this answer is to use integer powers for the polynomial power operation by operating in a base higher than any possible coefficient. In general, given a polynomial `p(x)` whose coefficients are all non-negative integers less than `b`, `p(b)` is a base-`b` representation of the coefficients (because the individual monomials don't "overlap"). Clearly `(x + 2)^n` will have coefficients which are positive integers and which sum to `3^n`, so each of them will individually be less than `3^n`.

```
ri     e# Read an integer n from stdin
_3@#   e# Push 3^n to the stack
_2+    e# Duplicate and add 2, giving a base-3^n representation of x+2
@#     e# Raise to the power of n
\b`    e# Convert into a vector of base-3^n digits and format for output

```

---

Alternative approaches: at 17 bytes

```
1a{0X$2f*+.+}ri*`

```

Online demo

or

```
1a{0X$+_]:.+}ri*`

```

Online demo

both work by summing the previous row with an offset-and-doubled row (in a similar style to the standard manual construction of Pascal's triangle).

A "direct" approach using Cartesian powers (as opposed to integer powers) for the polynomial power operation, comes in at 24 bytes:

```
2,rim*{1b_0a*2@#+}%z1fb`

```

where the map is, unusually, complicated enough that it's shorter to use `%` than `f`:

```
2,rim*1fb_0af*2@f#.+z1fb`

```
> 4 votes

# Answer
## ES6, 71 bytes

```
n=>[...Array(n+1)].fill(n).map(b=(n,i)=>!i?1:i>n?0:b(--n,i-1)*2+b(n,i))

```

Simple recursive formula. Each hypercube is created by moving the previous hypercube 1 unit through the Nth dimension. This means that the M-dimensional objects are duplicated at the start and end of the unit, but also the (M-1)-dimensional objects gain an extra dimension, turning into M-dimensional objects. In other words, `c(n, m) = c(n - 1, m) * 2 + c(n - 1, m - 1)`. (The actual submission reverses the parameters so that the formula outputs in the desired order.)

Ingeniously, `fill` allows `map` to provide the correct arguments to the recursive function, saving me 6 bytes.
> 3 votes

# Answer
# 05AB1E, 9 bytes

Code:

```
WƒNoZNc*,

```

Explanation:

```
W          # Push input and store in Z
 ƒ         # For N in range(0, input + 1)
  No       # Compute 2**N
    ZNc    # Compute Z nCr N
       *   # Multiply
        ,  # Pop and print

```

Uses CP-1252 encoding.
> 3 votes

# Answer
# Pyth, 10 9 bytes

```
.<L.cQdhQ

```

Uses the nCr algorithm everyone seems to be using.
> 3 votes

# Answer
# Octave, 31 bytes

Use the formula from A013609: T(n,k) = 2^k\*binomial(n,k).

Try it online!

```
f=@(n)bincoeff(n,0:n).*2.^(0:n)

```
> 3 votes

# Answer
# Julia, 31 bytes

```
n->[2^m*binomial(n,m)for m=0:n]

```

This is a lambda function that accepts an integer and returns an integer array. To call it, assign it to a variable.

For each *m* from 0 to the input *n*, we count the number of (*n*-*m*)-dimensional hypercubes on the boundary of the parent *n*-dimensional hypercube. Using the formula on Wikipedia, it's simply 2*m* * choose(*n*, *m*). The case of *m* = 0 refers to the *n*-cube itself, so the output begins with 1 regardless of the input. Edges are given by *m* = *n*, vertices by *m* = *n* \- 1, etc.
> 2 votes

# Answer
# , 11 bytes

```
(,+2*,~)&0#

```

Attempt This Online!

```
(,+2*,~)&0#
          #    constant 1
(      )&0     inner function bound to 0 on the right, repeated n times to 1...
 ,               append 0
   2*,~          prepend 0, and then double each number
  +              elementwise add the two

```

# , 12 bytes

```
1|.@p.@;$&_2

```

A minor variation of Dennis's J solution. Attempt This Online!

```
(!~*2^])i.,]

```

A minor variation of Alex A's APL solution. Attempt This Online!

```
1|.@p.@;$&_2
1      ;$&_2    create an array (1; -2 -2 ... -2)
    p.          construct a polynomial having that many -2s as roots
 |.             reverse it

(!~*2^])i.,]
        i.,]    create an array 0, 1, 2, ..., n
    2^]         2^0, 2^1, ..., 2^n
 !~             nC0, nC1, ..., nCn
   *            elementwise multiply

```
> 2 votes

# Answer
# Ruby, Rev B 57 bytes

```
->n{a=[1]+[0]*n
(n*n).downto(n){|i|a[1+j=i%n]+=2*a[j]}
a}

```

The previous rev only scanned through the used part of the array each time. This rev scans through the entire array on every iteration. This is slower, but it saves bytes. A further byte is saved by using 1 loop to do the job of 2.

# Ruby, Rev A 61 bytes

```
->n{a=[1]+[0]*n
n.times{|i|i.downto(0){|j|a[j+1]+=2*a[j]}}
a}

```

Starts with a point and iteratively creates the next dimension

In each iteration, each existing element increases in dimensionality and generates 2 new elements of its original dimensionality. For example, for a square in the horizontal plane that is extended vertically to become a cube:

The 1 face becomes a cube and generates 1 pair of faces (1 above, 1 below)

The 4 edges become faces and generate 4 pairs of edges (4 above, 4 below)

The 4 vertices become edges and generate 4 pairs of vertices (4 above, 4 below)

**Ungolfed in test program**

```
f=->n{a=[1]+[0]*n                  #make an array with the inital point and space for other dimensions
  n.times{|i|                      #iteratively expand dimension by dimension
    i.downto(0){|j|a[j+1]+=2*a[j]} #iterating downwards (to avoid interferences) add the 2 new elements generated by each existing element.
  }
a}                                 #return the array

p f[gets.to_i]

```
> 1 votes

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

```
f=n=>n?[...f(n-1),i=0].map(v=>i*2+(i=v)):[1]

```

Try it online!

~~\# JavaScript (Node.js), 51 bytes~~

~~```
f=n=>n?[0,...f(n-1)].map((v,i,e)=>~~e[++i]+v*2):[1]

```
Try it online!
~~

~~binomial(n,m)\*2^m~~
> 1 votes

---
Tags: code-golf, math, sequence, geometry, counting
---


title: Critical Calculations

text:
# Question
Title: Critical Calculations
## Background

In the game stick ranger, there is an item which grants the character the ability to get critical hits. Each time a projectile hits an enemy, it has some probability to be a critical hit (crit). For most weapons this is calculated independently each time, but for one class (the angel) things work differently. The angel throws multiple rings per volley, and each has a chance to crit. But, (and apparently this is not a bug) once a ring crits, that crit multiplier stays. And in fact if one is lucky enough for a second ring to crit in the same volley, the crits will multiply. So if the first crit is 10X the original damage, the second will be 100X. All crits persist until the next volley is reached. This is great, but I want to know what my damage per second is given a particular set up. I know the base damage and hit rate, but this crit multiplier business is tricky, and I could use a short program to help me out.

## The challenge

You will be given three inputs: the crit probability, the crit multiplier, and the number of rings. We'll assume each ring hits some enemy exactly once. You must then output the average damage per ring (or per volley) gained by having the crit applied.

Standard I/O rules apply, the inputs and output may be in any logical format including fractions, decimals, and percentages. You may assume \\$0\<\text{odds}\<1\\$, \\$1\<\text{multiplier}\\$, and \\$0\<\text{hits}\\$. The output from your program must be within \\$0.1\\%\\$ of the true value at least \\$90\\%\\$ of the time.

This is , so the shortest answer in bytes wins.

## Worked example

Let's work through the answer with a crit chance of 0.2, multiplier of 6, and 2 rings. For this example all I/O uses decimals, and I'll find the average damage per ring. There are four distinct outcomes

```
outcome             damage          probability         weighted

no crits            1 + 1 = 2       0.8 * 0.8 = 0.64    2  * 0.64 = 1.28
no crit then crit   1 + 6 = 7       0.8 * 0.2 = 0.16    7  * 0.16 = 1.12
crit then no crit   6 + 6 = 12      0.2 * 0.8 = 0.16    12 * 0.16 = 1.92
two crits           6 + 36 = 42     0.2 * 0.2 = 0.04    42 * 0.04 = 1.68
                                                                    ----
total                                                               6.00

```

Thus our answer is `6/2 = 3` average damage per ring. This is much higher than what a simple crit system would yield `1*0.8 + 6*0.2 = 2`

## Test cases

odds, multiplier, hits -> output

0.2, 6, 2 -> 3
0.3, 5, 3 -> 5.896
0.5, 2, 4 -> 3.046875
0.2, 7, 5 -> 18.529984
0.15, 10, 5 -> 24.6037391875
```
</code></pre>

# Answer
# Charcoal, 16 bytes

```
ＮθＩ∕ΣＸ⊕×Ｎ⊖Ｎ…·¹θθ

```

Try it online! Link is to verbose version of code. Takes the number of rings as the first parameter, then the odds and multiplier. Explanation: Each ring has a `p` chance of dealing `m` times as much damage as the previous ring and a `1-p` chance of dealing the same damage as the previous ring. The expected damage of the ring is therefore `1-p+pm` times the expected damage of the previous ring and each ring's expected damage is therefore the `n`th power of that. It then remains to take the average of these values.

```
Ｎθ                  Number of rings as an integer
        Ｎ           Odds as a number
       ×            Multiplied by
          Ｎ         Multiplier as a number
         ⊖          Decremented
      ⊕             Incremented
     Ｘ              Vectorised raise to power
           …·       Inclusive range from
             ¹      Literal integer `1` to
              θ     Number of rings
    Σ               Take the sum
   ∕                Divide by
               θ    Number of rings
  Ｉ                 Cast to string
                    Implicitly print

```
> 8 votes

# Answer
# Python 3, 40 bytes

```
lambda p,m,n:((c:=1-p+p*m)**n-1)/(n-n/c)

```

Try it online!

A formula I derived. With crit probability \\$p\\$, multiplier \\$m\\$, and \\$n\\$ hits, the average damage per hit is

$$ \frac{c}{n} \frac{c^n-1}{c-1}, \text{ where } c=1-p+pm$$

*Thanks to dingledooper for -2 bytes.*
> 7 votes

# Answer
# 05AB1E, 8 bytes

```
<*>ILmÅA

```

Inputs in the order *critDamageMultiplier* (\\$m\\$), *critProbability* (\\$p\\$), *amountOfRings* (\\$n\\$).

Port of *@Neil*'s Charcoal answer, so make sure to upvote him as well!

Try it online or verify all test cases.

**Explanation:**

Uses the formula:

$$a(m,p,n)=\frac{\sum\_{i=1}^n{(p(m-1)+1)^i}}{n}$$

```
<         # Decrease the first (implicit) input-integer (the multiplier) by 1
 *        # Multiply it to the second (implicit) input-decimal (the probability)
  >       # Increase it by 1
   IL     # Push a list in the range [1, third input-integer (the amount of rings)]
     m    # Take the earlier value to the power of each of these integers
      ÅA  # Pop and get the average of this list
          # (after which it is output implicitly as result)

```
> 4 votes

# Answer
# JavaScript (ES7), 96 bytes

Naive implementation of the algorithm.

```
(p,m,n)=>eval("for(t=0,i=2**n;i--;t+=d*q)for(q=x=1,d=0,j=n;j--;d+=x)q*=i>>j&1?(x*=m,p):1-p;t/n")

```

Try it online!
> 3 votes

# Answer
# Arturo, 34 bytes

```
$[p m n][c:+1-p p*m(-c^n 1)/n-n/c]

```

Try it!

Port of xnor's Python answer.
> 2 votes

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

```
p=>m=>g=(h,w=1/h)=>h--&&(1-p)*(g(h,w)+w)+p*(g(h,w*=m)+w)

```

Try it online!

Recursive fork possibility

# JavaScript (Node.js), 35 bytes

```
(p,m,n)=>((c=1-p+p*m)**n-1)/(n-n/c)

```

Try it online!

Port of formula
> 2 votes

---
Tags: code-golf, game, statistics
---


# Question
Title: What is the reverse (binary) bit number?
So you are given a **POSITIVE** base 10 (decimal) number. Your job is to reverse the binary digits and return that base 10 number.

### Examples:

```
1 => 1 (1 => 1)
2 => 1 (10 => 01)
3 => 3 (11 => 11)
4 => 1 (100 => 001)
5 => 5 (101 => 101)
6 => 3 (110 => 011)
7 => 7 (111 => 111)
8 => 1 (1000 => 0001)
9 => 9 (1001 => 1001)
10 => 5 (1010 => 0101)

```

This is a challenge, so the solution that uses the least bytes wins.

This is A030101 in the OEIS.

# Answer
> 22 votes
# Python, 29 bytes

```
lambda n:int(bin(n)[:1:-1],2)

```

**Try it online!**

This is an anonymous, unnamed function which returns the result.

---

First, `bin(n)` converts the argument to a binary string. We would ordinarily reverse this with the slice notation `[::-1]`. This reads the string with a step of **-1**, i.e. backwards. However, binary strings in Python are prefixed with an `0b`, and therefore we give the slicing's second argument as **1**, telling Python to read backwards terminating at index **1**, thus not reading indexes **1** and **0**.

Now that we have the backwards binary string, we pass it to `int(...)` with the second argument as **2**. This reads the string as a base 2 integer, which is then implicity returned by the lambda expression.

# Answer
> 17 votes
# Python, 29 bytes

```
lambda n:int(bin(n)[:1:-1],2)

```

**Try it online**

# Answer
> 13 votes
## JavaScript (ES6), ~~30~~ 28 bytes

*Saved 2 bytes thanks to @Arnauld*

```
f=(n,q)=>n?f(n>>1,q*2|n%2):q

```

This basically calculates the reverse one bit at a time: We start with **q = 0**; while **n** is positive, we multiply **q** by 2, sever the last bit off of **n** with `n>>1`, and add it to **q** with `|n%2`. When **n** reaches 0, the number has been successfully reversed, and we return **q**.

Thanks to JS's long built-in names, solving this challenge the easy way takes 44 bytes:

```
n=>+[...n.toString(2),'0b'].reverse().join``

```

Using recursion and a string, you can get a 32 byte solution that does the same thing:

```
f=(n,q='0b')=>n?f(n>>1,q+n%2):+q

```

# Answer
> 10 votes
# Java 8, ~~53~~ ~~47~~ ~~46~~ 45 bytes

* *-4 bytes thanks to Titus*
* *-1 byte thanks to Kevin Cruijssen*

This is a lambda expression which has the same principle as ETH's answer (although recursion would have been too verbose in Java, so we loop instead):

```
x->{int t=0;for(;x>0;x/=2)t+=t+x%2;return t;}

```

**Try it online!**

This can be assigned with `IntFunction<Integer> f = ...`, and then called with `f.apply(num)`. Expanded, ungolfed and commented, it looks like this:

```
x -> {
    int t = 0;           // Initialize result holder
    while (x > 0) {      // While there are bits left in input:
        t <<= 1;         //   Add a 0 bit at the end of result
        t += x%2;        //   Set it to the last bit of x
        x >>= 1;         //   Hack off the last bit of x
    }
    return t;            // Return the final result
};

```

# Answer
> 9 votes
# J, 6 bytes

```
|.&.#:

```

`|.` reverse

`&.` under

`#:` base 2

# Answer
> 8 votes
# Jelly, 3 bytes

```
BUḄ

```

Try it online!

```
B   # convert to binary
 U  # reverse
  Ḅ # convert to decimal

```

# Answer
> 8 votes
## Mathematica, 19 bytes

```
#~IntegerReverse~2&

```

# Answer
> 7 votes
# C, ~~48~~ ~~44~~ ~~43~~ 42 bytes

-1 byte thanks to gurka and -1 byte thanks to anatolyg:

```
r;f(n){for(r=n&1;n/=2;r+=r+n%2);return r;}

```

Previous 44 bytes solution:

```
r;f(n){r=n&1;while(n/=2)r=2*r+n%2;return r;}

```

Previous 48 bytes solution:

```
r;f(n){r=0;while(n)r=2*(r+n%2),n/=2;return r/2;}

```

Ungolfed and usage:

```
r;
f(n){
 for(
  r=n&1;
  n/=2;
  r+=r+n%2
 );
 return r;}
}

main() {
#define P(x) printf("%d %d\n",x,f(x))
P(1);
P(2);
P(3);
P(4);
P(5);
P(6);
P(7);
P(8);
P(9);
P(10);
}

```

# Answer
> 7 votes
# Labyrinth, 23 bytes

```
?_";:_2
  :   %
 @/2_"!

```

Well, this is awkward... this returns the reverse BINARY number... Thanks @Martin Ender for pointing out both my bug and my ID 10T error. So this doesn't work, I'll have to find another solution.

# Answer
> 5 votes
# Ruby, ~~29~~ 28 bytes

```
->n{("%b"%n).reverse.to_i 2}

```

"%b" % n formats the input n as a binary string, reverse, then convert back to a number

Usage/Test cases:

```
m=->n{("%b"%n).reverse.to_i 2}
m[1] #=> 1
m[2] #=> 1
m[3] #=> 3
m[4] #=> 1
m[5] #=> 5
m[6] #=> 3
m[7] #=> 7
m[8] #=> 1
m[9] #=> 9
m[10] #=> 5

```

# Answer
> 4 votes
# 05AB1E, 3 bytes

```
bRC

```

Try it online!

# Answer
> 4 votes
# Java (OpenJDK), 63 bytes

```
a->a.valueOf(new StringBuffer(a.toString(a,2)).reverse()+"",2);

```

Try it online!

Thanks to poke for -12 bytes and to Cyoce for -8 bytes!

# Answer
> 3 votes
# Japt, ~~5~~ 3 bytes

-2 bytes thanks to Shaggy

```
¢ÔÍ

```

Try it online!

# Answer
> 3 votes
# Perl 6, 19 bytes

```
{:2(.base(2).flip)}

```

# Answer
> 3 votes
# Bash/Unix utilities, ~~24~~ 23 bytes

```
dc -e2i`dc -e2o?p|rev`p

```

Try it online!

# Answer
> 3 votes
# Haskell, 36 bytes

```
0!b=b
a!b=div a 2!(b+b+mod a 2)
(!0)

```

Same algorithm (and length!) as ETHproductions’ JavaScript answer.

# Answer
> 3 votes
# PHP, 33 bytes

```
<?=bindec(strrev(decbin($argn)));

```

convert to base2, reverse string, convert to decimal. Save to file and run as pipe with `-F`.

**no builtins:**

**iterative, 41 bytes**

```
for(;$n=&$argn;$n>>=1)$r+=$r+$n%2;echo$r;

```

While input has set bits, pop a bit from input and push it to output. Run as pipe with `-nR`.

**recursive, 52 bytes**

```
function r($n,$r=0){return$n?r($n>>1,$r*2+$n%2):$r;}

```

# Answer
> 2 votes
# MATL, 4 bytes

```
BPXB

```

Try it online!

### Explanation

```
B     % Input a number implicitly. Convert to binary array
P     % Reverse array
XB    % Convert from binary array to number. Display implicitly

```

# Answer
> 2 votes
# Pyth, 6 bytes

```
i_.BQ2

```

Test suite available here.

### Explanation

```
i_.BQ2
    Q     eval(input())
  .B      convert to binary
 _        reverse
i    2    convert from base 2 to base 10

```

# Answer
> 2 votes
# Scala, 40 bytes

```
i=>BigInt(BigInt(i)toString 2 reverse,2)

```

### Usage:

```
val f:(Int=>Any)=i=>BigInt(BigInt(i)toString 2 reverse,2)
f(10) //returns 5

```

### Explanation:

```
i =>          // create an anonymous function with a parameter i
  BigInt(       //return a BigInt contructed from
    BigInt(i)     //i converted to a BigInt
    toString 2    //converted to a binary string
    reverse       //revered
    ,
    2             //interpreted as a binary string
  )

```

# Answer
> 2 votes
# APL (Dyalog Unicode), 10 bytes

```
2⊥∘⊖2∘⊥⍣¯1

```

Try it!

Thanks to @Adám for 2 bytes.

### How it works:

This is a tacit function. To use it, it has to be assigned a name (like `f←`) and then called over an input; for the test cases: `f 1`, `f 2`, etc.

```
2⊥∘⊖2∘⊥⍣¯1  # Main function; tacit.
       ⍣¯1  # invert
    2∘⊥     # convert from base 2 (which is inverted to 'convert to base 2')
  ∘⊖        # flip, then
2⊥          # convert from base 2

```

# Answer
> 1 votes
# Mathematica, 38 bytes

```
#+##&~Fold~Reverse[#~IntegerDigits~2]&

```

# Answer
> 1 votes
# Groovy, 46 bytes

```
{0.parseInt(0.toBinaryString(it).reverse(),2)}

```

# Answer
> 1 votes
# CJam, 8 bytes

```
ri2bW%2b

```

Try it online!

### Explanation

```
ri          e# Read integer
  2b        e# Convert to binary array
    W%      e# Reverse array
      2b    e# Convert from binary array to number. Implicitly display

```

# Answer
> 1 votes
## Batch, 62 bytes

```
@set/an=%1/2,r=%2+%1%%2
@if %n% gtr 0 %0 %n% %r%*2
@echo %r%

```

Explanation: On the first pass, `%1` contains the input parameter while `%2` is empty. We therefore evaluate `n` as half of `%1` and `r` as `+%1` modulo 2 (the `%` operator has to be doubled to quote it). If `n` is not zero, we then call ourselves tail recursively passing in `n` and an expression that gets evaluated on the next pass effectively doubling `r` each time.

# Answer
> 1 votes
# C#, 98 bytes

```
using System.Linq;using b=System.Convert;a=>b.ToInt64(string.Concat(b.ToString(a,2).Reverse()),2);

```

# Answer
> 1 votes
## R, 55 bytes

```
sum(2^((length(y<-rev(miscFuncs::bin(scan()))):1)-1)*y)

```

Reads input from stdin and consequently uses the `bin` function from the `miscFuncs` package to convert from decimal to a binary vector.

# Answer
> 1 votes
# Pushy, 19 bytes

No builtin base conversion!

```
$&2%v2/;FL:vK2*;OS#

```

**Try it online!**

Pushy has two stacks, and this answer makes use of this extensively.

There are two parts two this program. First, `$&2%v2/;F`, converts the number to its reverse binary representation:

```
            \ Implicit: Input is an integer on main stack.
$      ;    \ While i != 0:
 &2%v       \   Put i % 2 on auxiliary stack
     2/     \   i = i // 2 (integer division)
        F   \ Swap stacks (so result is on main stack)

```

Given the example 10, the stacks would appear as following on each iteration:

```
1: [10]
2: []

1: [5]
2: [0]

1: [2]
2: [0, 1]

1: [1]
2: [0, 1, 0]

1: [0]
2: [0, 1, 0, 1]

```

We can see that after the final iteration, `0, 1, 0, 1` has been created on the second stack - the reverse binary digits of 10, `0b1010`.

The second part of the code, `L:vK2*;OS#`, is taken from my previous answer which converts binary to decimal. Using the method decsribed and explained in that answer, it converts the binary digits on the stack into a base 10 integer, and prints the result.

# Answer
> 1 votes
## Labyrinth, 22 bytes

```
_2/?+:{!
}    "
++:{%#

```

Try it online!

### Explanation

The idea is to disassemble the input bit-by-bit while assembling the output from the other end. Luckily, it's easiest to deconstruct a number from the right, and build one up from the left, so this automatically reverses the bits. We'll generally be keeping what's left of the input on top the main stack, and what we've already computed of the result on top of the auxiliary stack.

```
_2/  When the program starts out, this doesn't really do anything, because it
     just divides an implicit zero by 2.
?+   Read an integer N from STDIN and add it to the implicit zero on top of
     the stack.

     The main loop starts here:

:    Duplicate what's left of N. This is also used as the conditional to end
     the loop. Once this reaches zero, the IP moves straight ahead, exiting
     the loop. Otherwise, the IP turns south which continues the loop.
#    Push the stack depth, 2.
%    Take N modulo 2, i.e. get its least significant bit.
{    Fetch the intermediate result R from the auxiliary stack.
:+   Double it (shifting its existing bits left by one position).
+    Add the bit we just extracted from N to R.
}    Put R back on the auxiliary stack.
_2/  Divide N by 2, dropping its least significant bit.
?+   We're at EOF, so ? just pushes zero and the + gets rid of that zero.

     Then the main loop starts over.
     When we exit the loop (once N is zero), this bit is run:

{    Retrieve R from the auxiliary stack.
!    Print it.
     The IP hits a dead end and turns around.
{:+? Various shenanigans which simply leave a zero on top of the stack.
/    Terminates the program due to the attempted division by zero.

```

# Answer
> 1 votes
# Vyxal, 3 bytes

```
bṘB

```

Try it Online!

Converts to a binary string, reverses it, then puts it back in base 10.

# Answer
> 0 votes
# k, 18 bytes

```
{2/:|X@&|\X:0b\:x}

```

Example:

```
k){2/:|X@&|\X:0b\:x}6
3

```

# Answer
> 0 votes
## Perl 5 (5.12+), 32 bytes

```
say oct reverse sprintf"%bb0",<>

```

(Input on stdin, output on stdout, requires `-E` or `-M5.012` at no cost).

Straightforward but not all that short. Too bad "reverse" and "sprintf" are such weighty keywords.

`oct` is an odd legacy name; `oct "123"` gives the decimal equivalent of octal 123 as you'd expect, but `oct "0x123"` interprets its input as hex and `oct "0b101"` interprets it as binary.

# Answer
> 0 votes
# Java 7, ~~94~~ 89 bytes

Golfed:

```
int x(int n){return Long.parseLong(new StringBuffer(Long.toString(n,2)).reverse()+"",2)};

```

Ungolfed:

```
int x(int n)
{
    return Integer.parseInt(new StringBuffer(Integer.toString(n, 2)).reverse() + "", 2);
}

```

5 bytes saved thanks to @corvus\_192

# Answer
> 0 votes
# C#, 167 bytes

```
 for(int i = 1; i <= 10; i++)
 {
 var bytes= Convert.ToString(i, 2);
 var value= Convert.ToInt32(byteValue.Reverse());
 console.WriteLine(value);
}

```

**Explanation:**

Here I will iterate n values and each time iterated integer value is convert to byte value then reverse that byte value and that byte value is converted to integer value.

# Answer
> 0 votes
**c/c++ 136 bytes**

```
uint8_t f(uint8_t n){int s=8*sizeof(n)-ceil(log2(n));n=(n&240)>>4|(n&15)<<4;n=(n&204)>>2|(n&51)<<2;n=(n&172)>>1|(n&85)<<1;return(n>>s);}

```

It's not going to win, but I wanted to take a different approach in c/c++ 120 bytes in the function

```
#include <math.h>
#include <stdio.h>
#include <stdint.h>

uint8_t f(uint8_t n){
    int s=8*sizeof(n)-ceil(log2(n));
    n=(n&240)>>4|(n&15)<<4;
    n=(n&204)>>2|(n&51)<<2;
    n=(n&172)>>1|(n&85)<<1;
    return (n>>s);
}

int main(){
    printf("%u\n",f(6));
    return 0;
}

```

To elaborate on what I am doing, I used the log function to determine the number of bits utilized by the input. Than a series of three bit shifts left/right, inside/outside, even/odd which flips the entire integer. Finally a bit shift to shift the number back to the right. Using decimals for bit shifts instead of hex is a pain but it saved a few bytes.

# Answer
> 0 votes
# Pari/GP , 28 byte

The value to be "reversed" is expected in variable a; i.e. do `a=37` first. Then execute the cmd. Because Pari/GP is interpreting you do not need to add an extra `print(b)` because referencing a variable or a result just prints it to the console:

```
  b=a%2;while(a\=2,b+=b+a%2);b

```

Example:

```
  a=37
  b=a%2;while(a\=2,b+=b+a%2);b
  \\ printed result is: 41

```

Try it online!

# Answer
> 0 votes
# SmileBASIC, 41 bytes

```
INPUT N
WHILE N:T=T+T+N MOD 2N=N>>1WEND?T

```

Basically a port of the C/Java versions.

# Answer
> 0 votes
# 8th, ~~41~~ 29 bytes

```
2 base drop >s rev >n decimal

```

**Usage**

```
ok> 37 2 base drop >s rev >n decimal .
41

```

**Test case**

```
: f 2 base drop >s s:rev >n decimal ;
( dup . " => " . f . cr ) 1 10 loop

1 => 1
2 => 1
3 => 3
4 => 1
5 => 5
6 => 3
7 => 7
8 => 1
9 => 9
10 => 5

```

# Answer
> 0 votes
# Scala 47 bytes

Handles BigInt

```
((i:BigInt)=>BigInt(i.toString(2).reverse,2))([Number to Reverse])

```

if only we could:

```
(i=>BigInt(i.toString(2).reverse,2))([Number to Reverse])

```

or

```
(BigInt(_.toString(2).reverse,2))([Number to Reverse])

```

### Example (REPL):

```
scala> ((i:Int)=>BigInt(i.toString(2).reverse,2))(100)
res1: scala.math.BigInt = 19

```

### Example (in Situ):

```
object main extends App {
    val arg = Option(args).getOrElse(Array[String]("100"))
    (BigInt(arg(0)) to BigInt(arg(1))).map((n)=>
    (println(n + "-->" + BigInt(n.toString(2).reverse, 2))))
}

```

run:

```
run 20 30

```

result:

```
[debug] Waiting for thread run-main-23 to terminate.
20-->5
21-->21
22-->13
23-->29
24-->3
25-->19
26-->11
27-->27
28-->7
29-->23
30-->15
[debug]         Thread run-main-23 exited.

```

# Answer
> 0 votes
# C 41 bytes

```
g(i,r){for(r=0;r+=r+i%2,i/=2;);return r;}

```

Input in "i" output the result

Try it online!

# Answer
> 0 votes
# Common Lisp, 52 bytes

```
(parse-integer(reverse(format()"~b"(read))):radix 2)

```

Try it online!

# Answer
> 0 votes
# Julia, 32 bytes

```
f(n)=parseint(reverse(bin(n)),2)

```

gives a warning but still runs

# Answer
> 0 votes
# Husk, 3 bytes

```
ḋ↔ḋ

```

Try it online!

# Explanation

Here's an explanation, even if there's not much to it:

```
     -- implicit input N    | 10
  ḋ  -- convert to base2    | [1,0,1,0]
 ↔   -- reverse             | [0,1,0,1]
ḋ    -- convert from base2  | 5

```

# Answer
> 0 votes
# JavaScript, 44 bytes

```
f=i=>(a=0,(x=i=>i?(a=a*2+i%2,x(i>>1)):a)(i))

for(i=1;i<10;i++){console.log(i,f(i))}
```

# Answer
> 0 votes
# Add++, 14 bytes

```
D,f,@,BBBR2@Bb

```

Try it online!

## How it works

```
D,f,@,   - Create a monadic function named f. Example argument: [10]
      BB - Convert to binary;     STACK = ['1010']
      BR - Reverse the top value; STACK = ['0101']
      2  - Push 2;                STACK = ['0101' 2]
      @  - Reverse the stack;     STACK = [2 '0101']
      Bb - Convert from base;     STACK = [5]
         - Implicit return

```

# Answer
> 0 votes
# RProgN 2, 6 bytes

```
2Bi2iB

```

Try it online!

# Answer
> 0 votes
## REXX, 46 bytes

```
say x2d(b2x(reverse(trunc(x2b(d2x(arg(1)))))))

```

# Answer
> 0 votes
# Go, 49 bytes

A function literal based off my Java answer:

```
func(x int)(t int){for;x>0;x/=2{t+=t+x%2};return}

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 3 bytes

```
ḃrḂ

```

Try it online!

#### Explanation

```
ḃrḂ  # Implicit input
ḃ    # To binary
 r   # Reverse
  Ḃ  # From binary
     # Implicit output

```

---
Tags: code-golf, number, base-conversion, binary
---