title: Close neighbours stick together

text:
# Question
Title: Close neighbours stick together
Given a list of positive digits, return that list with consecutive elements grouped together. For example:

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

```

Essentially, all adjacent elements whose absolute difference is 1 should be grouped together.

The input array will only ever contain positive digits (`123456789`) and it's length will always fit within your language's integer limit. You may take input in any reasonable format, including as a string or a single integer (so the example would be \\$123565441\\$). The input will never be empty and will always contain at least 1 element

You may output in any reasonable format that clearly shows the separate groups. There must be clear, non-digit delimiters between the groups. There doesn't have to be clear delimiters between the elements of the groups. If there are, the delimiters between groups and the elements of groups should be distinct (basically, you can't just print the input saying that both are separated by `,`  or whatever).

One example output is shown above. Another could be outputting each group on a separate line, as single strings of digits such as

```
123
5654
4
1

```

The input is not guaranteed to be sorted. The order of the outputs, or the elements in the outputs, does not have to match the order of the inputs, so long as the groups and elements are correct.

This is so the shortest code in bytes wins.

## Test cases

```
[1] -> [1]
[1, 2] -> [[1, 2]]
[1, 3] -> [[1], [3]]
[2, 1] -> [[2, 1]]
[2, 4, 1, 2, 7, 6, 5, 1] -> [[2], [4], [1, 2], [7, 6, 5], [1]]
[4, 1, 8, 1, 3, 5, 3, 7, 1] -> [[4], [1], [8], [1], [3], [5], [3], [7], [1]]
[1, 2, 3, 4, 5, 6, 7, 9, 8] -> [[1, 2, 3, 4, 5, 6, 7], [9, 8]]
[1, 2, 3, 5, 6, 5, 4, 4, 1] -> [[1, 2, 3], [5, 6, 5, 4], [4], [1]]
[6, 1, 4, 4, 1, 2, 1, 4, 3, 2, 9, 2, 7, 5, 7, 3, 1, 7, 6, 5] -> [[6], [1], [4], [4], [1, 2, 1], [4, 3, 2], [9], [2], [7], [5], [7], [3], [1], [7, 6, 5]]
[6, 1, 4, 4, 1, 2, 3, 4, 3, 2, 9, 2, 7, 5, 7, 3, 1, 7, 6, 5] -> [[6], [1], [4], [4], [1, 2, 3, 4, 3, 2], [9], [2], [7], [5], [7], [3], [1], [7, 6, 5]]

```

# Answer
# , 17 bytes

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

```

Try it online!

Thanks to rak for pointing out that repeated elements should start a new group

* `2-/\]` Take successive deltas
* `1~:&|` Is the absolute value not equal to 1?
* `1,` Append one (since first element always starts a new group)
* `<;.1~` Group by that mask (ie, start new group every time there's a one)
> 9 votes

# Answer
# APL (Dyalog Extended), 13 bytes

```
⊢⊂⍨1,1≠∘|2-/⊢

```

```
⊢⊂⍨1,1≠∘|2-/⊢
         2-/⊢  pairwise differences
     1≠∘|      1 not equal to absolute value
⊢⊂⍨1,          prepend 1 and partition

```

Try it online!
> 9 votes

# Answer
# convey, 36 bytes

Outputs the groups separated by newlines.

```
{"">>v>v}
1~?`]>^,`
 >-|=.!`
   _1 _

```

Try it online!

Copies `"` each element, delays it by one step `1~`, so it matches up at `-` with the next element. The first element gets discarded with `?`]`. Take the absolute value of the difference `|_`, is it different from 1 `1=.`? Then take either 0 or 1 `_` values, which will be interpreted as newline by the output.

Meanwhile the original outputs trots along the upper line, so its output is aligned with the newlines.
> 9 votes

# Answer
# Jelly, 4 bytes

```
I²’k

```

Try it online!

~~Possibly~~ caird's solution:

# Jelly, 4 bytes

```
IACk

```

Try it online!

```
   k    Split the input after
I       the deltas of the input
 ……     equal to ±1:

 ²      square each
  ’     and decrement each

 A      take the absolute value of each
  C     and subtract from 1

```
> 8 votes

# Answer
# , 38 bytes

```
split(a<-scan(),diffinv(diff(a)^2!=1))

```

Try it online!
> 8 votes

# Answer
# Factor, ~~33~~ 32 bytes

```
[ [ - sq 1 = ] monotonic-split ]

```

Try it online!

*Saved a byte by peeking at @xnor's Haskell answer! Take the square instead of the absolute value.*

## Explanation:

It's a quotation (anonymous function) that takes a sequence from the data stack as input and leaves a sequence (of sequences) on the data stack as output. Assuming `{ 1 2 4 }` is on the data stack when this quotation is called...

* `[ - sq 1 = ]` Push a quotation for `monotonic-split` to use later. It's a function that tests whether two numbers have an absolute difference of 1.

**Stack:** `{ 1 2 4 } [ - sq 1 = ]`
* `monotonic-split` Take a sequence and a quotation and apply the quotation to each pair of adjacent members of the sequence, splitting the sequence when the result is `f` but grouping elements together when the result is `t`. Inside the quotation during the first iteration now...

**Stack:** `1 2`
* `-` Subtract.

**Stack:** `-1`
* `sq` Raise to the power of 2.

**Stack:** `1`
* `1` Push `1`.

**Stack:** `1 1`
* `=` Test whether two objects are equal.

**Stack:** `t`, thus 1 and 2 belong to the same group.

Now the next iteration begins, `2` and `4` produce `f`, so `4` is in a different group from `1` and `2`.
> 7 votes

# Answer
# Haskell, 74 bytes

```
p%(a:b:t)|abs(a-b)/=1=(p++[a]):[]%(b:t)|x<-p++[a]=x%(b:t)
p%t=[p++t]
([]%)

```

Try it online!

I don't like the repetition here, but I can't see a way to get around it.
> 5 votes

# Answer
# Retina 0.8.2, 54 bytes

```
\B
¶
.
$&$&
%T`d`_d`^.
(?<=(.)(.))¶(\2|.(?=\1))

%`^.

```

Try it online! No test suite because the multiline output makes it confusing. Explanation:

```
\B
¶

```

Split the string into individual digits.

```
.
$&$&
%T`d`_d`^.

```

Duplicate each digit and decrement the first digit of each pair.

```
(?<=(.)(.))¶(\2|.(?=\1))

```

Merge together consecutive digits, removing the decremented duplicate of the second digit.

```
%`^.

```

Remove the remaining decremented duplicates.
> 5 votes

# Answer
# Branch, 28 bytes

```
/,^\b[N^-b;c;^*{[10.0]\n.b,]

```

Try it on the online Branch interpreter!

Takes input as a string of digits. Outputs with groups newline-separated and elements of a group joined in one string on each line. There is a leading newline; hopefully that's acceptable.

## Explanation

```
/,                       Go to the left child and read a character (stores codepoint)
^\                       Go to the right child (just creates this node for operating on)
b                        Go to register B; this is the left child since it was created second
[                     ]  While [the left child] is true
 N                       Save the most recently inputted byte as register N
  ^-                     Go to the root and perform (left child) - (right child); the right child saves the previous input; initially codepoint 0
    b;c;                 Go to register B (left child) and copy parent; go to C (right child) and copy parent
        ^*               Go to parent and perform (left child) * (right child) (this could've been done with b;c2^' as well to square with conventional exponentiation)
          {              Decrement; this is now 0 if the absolute difference was 1 and non-zero otherwise
           [   0]        While statement; zeroes the value at the end so this is transformed into an if statement
            10.          Set value 10 and output as character (outputs a newline if the difference isn't 1 / -1)
                 \n      Go to the right child and save N
                   b,    Go to the left child and read a new character, setting the state for the next iteration of the while loop

```

Reading from STDIN when nothing is left gives 0, so this terminates once input ends.
> 5 votes

# Answer
# Haskell, 59 bytes

```
f[]=[]
f(x:y)|(a:b):t<-f y,(x-a)^2==1=(x:a:b):t|0<1=[x]:f y

```

Try it online!

The relevant function is `f`, which takes a list as input and returns a list of lists as output.

---

Unfortunately the builtin

```
groupBy(\x y->(x-y)^2==1)
import Data.List

```

doesn't work, since Haskell's `groupBy` always compares new elements to the first element of the group.
> 5 votes

# Answer
# Vim, ~~43~~ 38 bytes

*-5 bytes thanks to @DLosc by using clever hyphen evaluating shenanigans.*

```
qqy3ll:if abs(<C-r>0)!=1
norm r|
en
l@qq@q

```

Try it online!

Takes input as a hyphen-separated list of numbers.

Explanation:

```
qq                        # Start recording macro 'q'
  y3l                     # Yank this character and the next two; this will be 'X-X'
     l                    # Move right one character
      :if                 # If...
          abs(      )     # The absolute value of...
              <C-r>0      # The previously yanked text, evaluated...
                     !=1  # Does not equal 1:
norm r|                   #   Replace the current character with '|'
en                        #   End if
l                         # Move right one character
 @q                       # Call macro 'q' recursively
   q                      # End macro
    @q                    # Call macro 'q'

```
> 5 votes

# Answer
# brainfuck, 51 bytes

This beats some of the mainstream language answers!

(byte count excludes 4 unnecessary newlines added for clarity.)

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

```

Try it online!

Outputs each group of characters preceded by an ASCII 1 for example as below

```
123565441
```

The digits are interpreted as ASCII characters and the initial ASCII 1 separator appears because the ASCII codes 48-57 of the digits are not consecutive to the zeroes which fill the Brainfuck memory at the start. Removing the initial separator would take another few bytes of code (I think it's no more of an issue than a trailing newline separator. Others may disagree.)

**Commented code**

```
,[[<->>+<-]<  Take input in cell 0 and copy it to the cell 1 while subtracting from cell minus 1
-[>]>[>+<<]<+ Subtract 1 from cell minus 1 and if it is not now zero add 1 to cell 2 (relies on the fact that cell 0 is zero and cell 1 is positive)
+[>]>[>+<<]<- Add 1 to cell minus 1 and if it is not now zero add 1 to cell 2
>>>-[.-]      Subtract 1 from cell 2 and if not now zero both tests above failed so output ascii 1 and then zero the cell
<.>,]         Output the input character now in cell 1 and loop again until a zero byte terminator is encountered
              Second input character will go into cell 2 and will be copied into cell 3 and compared with the previous character in cell 1 and so on advancing 2 cells each time

```
> 4 votes

# Answer
# JavaScript (ES7), 43 bytes

*Saved 4 bytes thanks to @tsh*

Expects an array of digit characters. Returns a string with the groups separated with commas.

```
a=>a.map(p=v=>(p-(p=v))**2-1?[,v]:v).join``

```

Try it online!
> 3 votes

# Answer
# Husk, 5 bytes

```
ġo=1≠

```

Try it online!

group on absolute difference = 1.
> 3 votes

# Answer
# Wolfram Language (Mathematica), 23 bytes

```
Split[#,!-1!=#2-#!=1&]&

```

Try it online!

`Split` can take a second argument, which is applied to adjacent pairs to see if they should be in the same group.

`!-1!=#2-#!=1` has the same length as `Abs[#2-#]==1`, and asserts that `-1`, `#2-#`, and `1` are not all unequal - that is, `-1==1 || -1==#2-# || #2-#==1`.
> 3 votes

# Answer
# Japt, 6 bytes

Outputs a 2D array.

```
òÈaY É

```

Try it

```
òÈaY É     :Implicit input of array
ò          :Partition between pairs that return falsey (0)
 È         :When passed through this function as X & Y
  aY       :  Absolute difference
     É     :  Minus 1

```
> 3 votes

# Answer
# K (oK), ~~24~~ 21 bytes

-3 bytes thanks to streetster!

```
{(?0,&~1=d*d:-':x)_x}

```

Try it online!
> 3 votes

# Answer
# Ruby, 48 bytes

```
->l{y=0;l.chunk{|x|$.+=(y-y=x)**2-1}.map &:last}

```

Try it online!
> 2 votes

# Answer
# Julia, ~~47~~ 46 bytes

```
f(s,p='a')=join(s.|>i->' '^((p-i)^2!=1)*(p=i))

```

Try it online!

Input is a list of `Chars` and output is a string with spaces to delimit groups, example:

`f(['2','4','1','2','7','6','5','1']) = " 2 4 12 765 1"`
> 2 votes

# Answer
# Python 2, 52 bytes

```
p=0
for n in input():print"X"*p*(abs(n-p)!=1),n,;p=n

```

The program separates the input with the character `"X"`.

Try it online!

# 55 bytes

```
lambda n:reduce(lambda a,b:a+[abs(a[-1]-b)==1,b],n,[0])

```

Alternate **55 byte** solution that uses reduce.

Try it online!
> 2 votes

# Answer
# PHP -F, 59 bytes

```
for(;$n=$argn[$i++];$m=$n)$a.=abs($n-$m)-1?",$n":$n;echo$a;

```

Try it online!

Takes a string of digits, outputs a string with delimiter ",". Has a preceding delimiter except when first digit is 1.

Well, at least it beats the Scratch answer :P
> 2 votes

# Answer
# Racket, 241 bytes

```
(λ(s)(letrec([d(λ(t n c)(if(null?(cdr t))(reverse c)(if(=(sqr(-(car t)(cadr t)))1)(d(cdr t)(+ 1 n)c)(d(cdr t)1(cons n c)))))][g(λ(t c a)(if(null? c)(cons t a)(g(drop t(car c))(cdr c)(cons(take t(car c))a))))])(reverse(g s(d s 1'())'()))))

```

Try it online!

What a monstrosity! I won't be surprised if it can be done in under 100 bytes.
> 2 votes

# Answer
# C (gcc), ~~56~~ 54 bytes

```
f(char*n){for(;*n;~-abs(putchar(*n)-*++n)&&puts(""));}

```

Try it online!

Takes a string of digits as input; prints output to STDOUT with each group on a separate line.

*-2 thanks to @ceilingcat*
> 2 votes

# Answer
# Charcoal, 21 bytes

```
Ｐ§θ⁰ＦΦθκ«¿⊖↔⁻ＩＫＫι⸿→Ｐι

```

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

```
Ｐ§θ⁰

```

Output the first character of the input without moving the cursor.

```
ＦΦθκ«

```

Loop over the remaining characters.

```
¿⊖↔⁻ＩＫＫι

```

If the current character is not a neighbour of the character under the cursor, then ...

```
⸿

```

... move to the start of the next line, ...

... otherwise move right one character.

```
Ｐι

```

Output the current character without moving the cursor.
> 1 votes

# Answer
# Scratch, (by @att) 184 bytes

Try it online!

All credit goes to @att

```
define(x
set[a v]to(
set[i v]to(
repeat(length of(x
change[i v]by(1
set[t v]to(letter(i)of(x
set[a v]to(join(a)((t)*(((2)*<(-1)contains((t)-(letter(length of(a))of(a)))?>)-(1
end
say(a

```
> 1 votes

# Answer
# Zsh `-o extendedglob`, 38 bytes

```
>-1;for a {wc<^*$[b?a-b:1];b=$a;<<<$a}

```

Try it online!

I really feel like there's some way to shave off 1 or 2 bytes from the `$[b?a-b:1]`.

* `>-1`: create the empty file `-1`
* `for a {}`: for each input element:
    + `$[]`: arithmetic expansion
        - `a-b`: take the difference between this element and the previous `b`
        - `b?:1`: if `b` is not defined (because we're on the first iteration), then assume the difference is 1
    + `*...`: match files that end with that difference. This is so the file `-1` will be matched by a difference of either `1` or `-1`
    + `^*...`: inverted match; matches files that *don't* end with that difference
    + `<`: and feed them as input to:
    + `wc` word count; outputs `0 0 0` (our separator) since the file is empty
    + So if the difference is `1` or `-1`, it will not match, so there will be no files as input to `wc` and it won't output the separator
    + `b=$a`: set `b` for the next iteration
    + `<<<$a`: print `a`
> 1 votes

# Answer
# \>\<\>, 19 bytes

```
:n$:@-:1=$i=+1$-a*o

```

Looks like TIO's `-v` flag support broke, and fishlanguage.com is down, so no link.

Takes the list on the stack, from top to bottom.
> 1 votes

# Answer
# Arn 1.0, 6 bytes

```
PWº··,

```

# Explained

Unpacked: `::-.|=1`

```
  _         Input; implied
::          Sort adjacent by
        _   First value
      -     Minus
        _   Second value
    .|      Absolute value
  =         Equals
    1       One

```
> 1 votes

# Answer
# Python 2, ~~47~~ 45 bytes (43 bytes?)

## 45 bytes :

```
p=0
for n in input():print`-n`[n-p:]or-n,;p=n

```

Try it online!

* Separator inside a group is  (space)
* Separator between groups is  `-` (space and minus sign)
* If the array start with a `1`, it prepends a separator

how it work:

* ``-n`` is the string representation of `-n` (it is 2 character long)

With strings:

* if 2 consecutive number are equal : `n-p = 0` =\> `"-n"[0:] = "-n"`
* if the absolute difference is equal to 1: `n-p = 1 or -1` =\> `"-n"[1:] = "-n"[-1:] = "n"`
* if the difference is greater than 1 (say for example 2): `n-p = 2` =\> `"-n"[2:] = ""` but `""or-n = -n`
* if the difference is lesser than -1 (say for example -2): `n-p = -2` =\> `"-n"[-2:] = "-n"`

## 43 bytes?

I also have a "edgy" solution in 43 bytes, don't know if the output format is "reasonable" :

```
p=0
for n in input():print(n-p)**2==1,n;p=n

```
* Separator inside a group is `\nTrue`
* Separator between groups is `\nFalse`

Try it online!
> 1 votes

# Answer
# 05AB1E, 7 bytes

```
üα≠0šÅ¡

```

Try it online or verify all test cases.

**Explanation:**

```
ü        # For each overlapping pair in the (implicit) input-list:
 α       #  Get the absolute difference
  ≠      # Check for each that they're NOT 1 (0 if 1; 1 otherwise)
   0š    # Prepend a 0 to the list
     Å¡  # Split the (implicit) input-list at the truthy indices

```
> 1 votes

# Answer
# Pip, 14 bytes

```
aWV(k1N_-BMPa)

```

Takes input via command-line argument as a string of digits. Outputs with separator `,` between groups and  within groups. Try it online!

### Explanation

```
          MPa   Map this function to each pair of digits in the input:
     1N          Count the number of 1's in
       _-B       the first digit minus the second (1 if the difference is +/-1, 0 otherwise)
   (k        )  Use that list of 1's and 0's to index into the preset variable k == ", "
                We now have a list of length len(a)-1 containing spaces and commas
aWV             Weave the input string with that list
                Autoprint (implicit)

```
> 1 votes

# Answer
# J-uby, 27 bytes

```
:slice_when+(:-|:abs|:!=&1)

```

Returns an Enumerator.

Attempt This Online!
> 1 votes

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


title: Output the van der Corput sequence

text:
# Question
Title: Output the van der Corput sequence
The van der Corput sequence is one of the simplest example of low-discrepancy sequence. Its `n`-th term is just `0.(n written in base 10 and mirrored)`, so its first terms are :

`0.1`, `0.2`,`0.3`,`0.4`, `0.5`,`0.6`,`0.7`, `0.8`,`0.9`, `0.01`, `0.11`,`0.21`,`0.31`, `0.41`,`0.51`,`0.61`, `0.71`,`0.81`,`0.91`, `0.02`, `0.12`,`0.22`,`0.32`, `0.42`,`0.52`,`0.62`, `0.72`,`0.82`,`0.92`, ...

# The challenge

Write a program or a function in any programming language that takes as input a positive integer `n` less than `10^6` and returns or print the first `n` terms of the van der Corput sequence. The output format can be a list of floating point numbers, a list of strings of the form `0.digits`, or a unique string where the terms are separated by commas and/or whitespaces, newlines.

Standard loopholes are forbidden. The shortest source code wins.

# Answer
# 05AB1E, 6 bytes

Code:

```
>GNÞR,

```

Try it online!

Explanation:

```
>       # Increment, pushes input + 1
 G      # For N in range(1, input + 1):
  N     # Push N
   Þ    # Convert to double, which appends `.0` at the end of an integer
    R   # Reverse top of the stack
     ,  # Pop and print with a newline

```

Uses CP-1252 encoding.
> 18 votes

# Answer
# Oracle SQL 11.2, ~~64~~ ~~62~~ 58 bytes

```
SELECT REVERSE(LEVEL||'.0')FROM DUAL CONNECT BY LEVEL<=:1;

```

Old version

```
SELECT '0.'||REVERSE(TRIM(LEVEL))FROM DUAL CONNECT BY LEVEL<=:1;

```

Concatenating '' to a number casts it to a string. It is 2 bytes shorter than using TRIM(), which is shorter than TO\_CHAR().

Since concatenating a string to a NUMBER results in a string, it is possible to use that string to manage the '0.' part of the result.
> 8 votes

# Answer
## CJam, ~~14~~ 11 bytes

*Thanks to Sp3000 for saving 3 bytes.*

```
ri{)d`W%S}/

```

Test it here.

### Explanation

```
ri     e# Read input and convert to integer N.
{      e# For each i from 0 to N-1...
  )    e#   Increment.
  d    e#   Convert to double.
  `    e#   Get string representation (which ends in ".0").
  W%   e#   Reverse.
  S    e#   Push a space.
}/

```
> 7 votes

# Answer
# Perl 6, ~~24~~ ~~22~~ 20 bytes

```
{"0."X~(^$_)».flip}

```

Thanks Aleks-Daniel Jakimenko-A. for yet another two bytes

**old version**

```
{("0."~.flip for ^$_)}
# Alternate below, same byte count
{map ^$_: "0."~*.flip}

```

EDIT: Thanks raiph for extra 2 bytes

**usage**

```
> my &f = {"0."X~(^$_)».flip}
-> ;; $_? is raw { #`(Block|333498568) ... }
> f(25)
(0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.01 0.11 0.21 0.31 0.41 0.51 0.61 0.71 0.81 0.91 0.02 0.12 0.22 0.32 0.42)

```
> 7 votes

# Answer
# Mathematica, 40 bytes

```
"0."<>StringReverse@ToString@#&~Array~#&

```

---

**Test case**

```
%[20]
(* {0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,0.01,0.11,0.21,0.31,0.41,0.51,0.61,0.71,0.81,0.91,0.02} *)

```
> 6 votes

# Answer
# JavaScript (ES6), 58

An anonymous function returning a string with comma separated values

```
n=>[...[...Array(n)].map(_=>n--+'.0')+''].reverse().join``

```

**TEST**

```
f=n=>[...[...Array(n)].map(_=>n--+'.0')+''].reverse().join``

function test() { R.textContent = f(+I.value) }

test()
```

```
N:<input id=I type=number value=20 oninput="test()"><br><pre id=R></pre>
```
> 5 votes

# Answer
# Pyth, 8 bytes

```
m_`cd1SQ

```

Try it online.

This is really just a combination of this and this answer. Therefore I'm making it a community wiki.
> 5 votes

# Answer
# Brachylog, 23 bytes

```
:0re:""rcr:"0."rcw,@Sw\

```

This takes a number as input and outputs the result to STDOUT, separated by spaces.

Fairly straightforward. Unfortunately we have to concatenate the number with an empty string to convert this number to a string (`:""rc`), because there is no built-in conversion predicate yet.

The conversion to string is necessary, because if we reverse the digits of the number, then the leading zeros (e.g. `10` becomes `01`) would be lost.
> 4 votes

# Answer
## Python 3, ~~47~~ 44 bytes

```
lambda n:[f'{i+1}.0'[::-1]for i in range(n)]

```

a shorter solution with Python 2

```
lambda n:['0.'+`i+1`[::-1]for i in range(n)]

```

Edit: gain 3 bytes using f-string interpolation from python 3.6, now we are even with python 2 solution.

**Test case**

```
>>> f(25)
['0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '0.01', '0.11', '0.21', '0.31', '0.41', '0.51', '0.61', '0.71', '0.81', '0.91', '0.02', '0.12', '0.22', '0.32', '0.42', '0.52']

```
> 4 votes

# Answer
# Pyth, 11 bytes

```
m+"0."_`dSQ

```

Try it here!

### Explanation

```
m+"0."_`dSQ  # Q = input

m        SQ  # Map the range(1,Q) to...
 +           # ...the concatenation of:
  "0."_`d    # "0." and the reversed element

```
> 4 votes

# Answer
# Pyth - 10 bytes

```
_M+R".0"SQ

```

Try it online here.
> 4 votes

# Answer
# MATL, 10 bytes

```
:"'0.'@VPh

```

**Try it online!**

```
:          % implicit input. Generate vector [1,2,...,input]
"          % for each
  '0.'     %   push string '0.'
  @        %   push loop variable (that is, 1,2,3,... in each iteration)
  V        %   convert to string
  P        %   reverse
  h        %   concatenate horizontally
           % implicit end of loop
           % implicit display of all stack contents

```
> 4 votes

# Answer
# Haskell, ~~36~~, 27 bytes

```
f n=reverse.show<$>[1.0..n]

```

Two bytes saved by nimi and an additional 7 by Lynn.
> 4 votes

# Answer
# Gol\>\<\>, ~~22~~, 16 bytes

*4 bytes saved by JoKing*

```
IFS" 0."LPWaSDn|

```

Try it online!
> 4 votes

# Answer
## PowerShell, 52 bytes

```
while($a++-$args[0]){"0."+-join"$a"["$a".Length..0]}

```

A little longer than I'd like, but uses a couple of neat tricks.

The `while` loop is obvious, but the conditional is a little tricky - we have `$a` (which starts as `$null` when first referenced) and then subtract our input number `$args[0]`. In PowerShell, math operations on `$null` treat it as zero, so for input `20` for example this will result in `-20`. Since any non-zero number is `$true`, the loop conditional will be `$true` right up until `$a` equals our input number (at which point the subtraction will equal `0` or `$false`). The trick comes from the post-increment `++`, which doesn't execute until *after* the subtraction is calculated, so handling input of `1` will correctly output `0.1` and then stop the loop on the next iteration.

Each time in the loop, we just create a string literal which gets left on the pipeline and output accordingly. We construct this from `"0."` concatenated with the result of the unary `-join` operator that has acted on the char-array created from taking the string `"$a"` backwards (by indexing via the range `"$a".length..0`).

### Test Runs

```
PS C:\Tools\Scripts\golfing> .\van-der-corput-sequence.ps1 1
0.1

PS C:\Tools\Scripts\golfing> .\van-der-corput-sequence.ps1 20
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
0.01
0.11
0.21
0.31
0.41
0.51
0.61
0.71
0.81
0.91
0.02

```
> 3 votes

# Answer
# Bash, 36 bytes

```
for i in `seq $1`;do rev<<<$i.0;done

```

Takes a number as a command line argument, and outputs each term on a separate line. For example:

```
$ ./vdc.sh 12
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
0.01
0.11
0.21

```
> 3 votes

# Answer
# Japt, 12 bytes

```
Uò1 ®+".0" w

```

Test it online!

### How it works

```
           // Implicit: U = input integer
Uò1 ®      // Create the inclusive range [1..U], and map each item Z to:
+".0" w    //  Z + ".0", reversed.
           // Implicit: output last expression

```
> 3 votes

# Answer
# beeswax, ~~57~~ 53 bytes

Working on the binary digit output problem for rosettacode I noticed that I could use the same short division algorithm for the van der Corput sequence, just using division and modulo by 10 instead of 2. The output is reversed in both cases.

Golfed down by 4 bytes, by mirroring the code:

```
`.0` XfE@~@L#;
 { %X<#dP@T~P9_
   q<#   N
    >:'bg?b

```

Hexagonal prettyprint, for easier orientation:

```
` . 0 `   X f E @ ~ @ L # ;
 {   % X < # d P @ T ~ P 9 _
    q < #       N
     > : ' b g ? b

```

Explanation of one cycle through the program, using the original code:

```
;#L@~@EfX `0.`
_9P~T@Pb#>X% {
      N   #>p
      d?gd':<

                                                  lstack   gstack
                                _9P              [0,0,10]•         create bee, set top to 10
                                   ~T            [0,10,n]•         flip top and 2nd, enter n
                                     @P          [n,10,1]•         flip top and 3rd, increment top
                                       b                           redirect to upper left
                     [n,10,1]•        E          [n,10,1]•      (2)clone bee in horizontal direction
flip lstack 1st/3rd  [1,10,n]•       @ f         [n,10,1]•  [1]•   push lstack top on gstack
flip lstack 1st/2nd  [1,n,10]•       ~   X                         clone bee in all directions
flip 1st/3rd         [10,n,1]•      @     `0.`                     print "0." to STDOUT
skip if 1st>2nd      [10,n,1]•     L      >                     (1)redirect
if 1st<2nd, del. bee              #        X                       clone bee in all directions
(if 1st>2nd, terminate program)  ;          % {  [n,10,1]•         1st=1st%2nd, output lstack 1st to STDOUT
                                            >p                     redirect
                                             <                     redirect
                                            :    [n,10,0]•         1st=1st/2nd
                                           '                       skip next instr. if 1st=0
                                          d                        redirect to upper right, loop back to (1)
                                         g       [n,10,1]   [1]•   push gstack top on lstack 1st
                                       d?                   []•    pop gstack, redirect to upper right
                                       N                           print newline to STDOUT
                                       P         [n,10,2]          increment lstack 1st
                                       E                           looped back to (2)

```

Example:

```
julia> beeswax("vandercorput.bswx",0,0.0,Int(20000))
i300
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
0.01
0.11
0.21
0.31
0.41
  .
  .
  .
0.492
0.592
0.692
0.792
0.892
0.992
0.003

Program finished!

```
> 3 votes

# Answer
# R, 59 Bytes

```
example(strsplit);cat(strReverse(sprintf('%s.0',1:scan())))

```

*explanation*

`example(strsplit)` creates the function `strReverse` (then it should be obvious)

Using `IRanges::reverse`, this could be golfed to 47 bytes

```
cat(IRanges::reverse(sprintf('%s.0',1:scan())))

```
> 2 votes

# Answer
# PHP, ~~45~~ 41 bytes

```
for(;$i++<$argv[1];)echo strrev(",$i.0");

```

Takes the input argument from CLI. Run like this:

```
php -r 'for(;$i++<$argv[1];)echo strrev(",$i.0");' 100

```
* Saved 3 bytes by concatenating the string before reversing
> 1 votes

# Answer
# Julia, ~~50~~ ~~38~~ ~~33~~ 31 bytes

I went for a different output format to shorten the code by 12 bytes. The function returns an array of strings now. Shortened by 5 more bytes. Thanks to *Alex A.* for reminding me of string interpolation and using an anonymous function (getting rid of 2 more bytes).

```
n->["0."reverse("$i")for i=1:n]

```

or alternatively

```
n->[reverse("$(i/1)")for i=1:n]

```

Test

```
julia> @time f(10000)
  0.002260 seconds (60.01 k allocations: 2.823 MB)
10000-element Array{ASCIIString,1}:
 "0.1"
 "0.2"
 "0.3"
 "0.4"
 "0.5"
 "0.6"
 "0.7"
 "0.8"
 "0.9"
 "0.01"
 "0.11"
 "0.21"
 "0.31"
 "0.41"
 "0.51"
 "0.61"
 "0.71"
 "0.81"
 "0.91"
 "0.02"
 "0.12"
 "0.22"
 "0.32"
 ⋮
 "0.8799"
 "0.9799"
 "0.0899"
 "0.1899"
 "0.2899"
 "0.3899"
 "0.4899"
 "0.5899"
 "0.6899"
 "0.7899"
 "0.8899"
 "0.9899"
 "0.0999"
 "0.1999"
 "0.2999"
 "0.3999"
 "0.4999"
 "0.5999"
 "0.6999"
 "0.7999"
 "0.8999"
 "0.9999"
 "0.00001"

```
> 1 votes

# Answer
# , 12 chars / 15 bytes

```
⩤⁽1ï⒨ß)Ė⍞.0ᴙ

```

`Try it here (Firefox only).`

It's... okay.

# Explanation

`⩤⁽1ï⒨` creates a range `[1,ï]` to map over, `ß)` converts mapitem (number) to string, `Ė⍞.0` concats `.0` to the end, and  reverses the whole string.
> 1 votes

# Answer
# Python 2, 54 Bytes

```
def f(i):
    for i in range(1,i):print("."+str(i)[::-1])

```

**Explanation:**

Iterate through the set `[1,input)` and appends the reversed `i` to `.`.

*Still an be golfed more.*
> 1 votes

# Answer
# Retina, 39 bytes

```
1
1$`0.
(1)+
$#1
+`(\d)0\.(\d*)
0.$2$1

```

Takes input in unary.

Try it online here.
> 1 votes

# Answer
# Dyalog APL, 12 bytes

```
{'0.',⌽⍕⍵}¨⍳

```

Try it online!

Straight-forward: the function `{` string `'0.'` before `,` the reversed  string-representation  of the argument  to the function `}` for each `¨` of the numbers 1 through *n* .
> 1 votes

# Answer
# Gema, 45 characters

```
*=@set{i;0}@repeat{*;@incr{i}0.@reverse{$i} }

```

Sample run:

```
bash-4.3$ gema '*=@set{i;0}@repeat{*;@incr{i}0.@reverse{$i} }' <<< 12
0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 0.01 0.11 0.21

```
> 1 votes

# Answer
## APL, 7

```
⌽⍎⌽1⍕⍳⎕

```

Explanation:

```
⍳⎕    creates a vector of numbers from 1 to user input
1⍕⍳⎕  formats these numbers like ##.0
⌽     inverts the whole string
⌽⍎   transforms back to numbers and inverts order

```
> 1 votes

# Answer
# jq 1.5, ~~40~~ 35 characters

(34 characters code + 1 character command line option.)

```
range(.)|"\(.+1).0"/""|reverse|add

```

Sample run:

```
bash-4.3$ jq -r 'range(.)|"\(.+1).0"/""|reverse|add' <<< 12
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
0.01
0.11
0.21

```

On-line test (Passing `-r` through URL is not supported – check Raw Output yourself.)

The same with links to documentation:

```
range()  "\(.  1.0"  "" | reverse | add

```

As a more readable alternative, the above could be also written like this (on-line):

```
range(.) | . + 1 | tostring | . + ".0" | split("") | reverse | join("")

```
> 1 votes

# Answer
# Python 2, 40 bytes

```
lambda n:[`i+1.`[::-1]for i in range(n)]

```

Example:

```
>>> f=lambda n:[`i+1.`[::-1]for i in range(n)]
>>> f(30)
['0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '0.01', '0.11', '0.21', '0.31', '0.41', '0.51', '0.61', '0.71', '0.81', '0.91', '0.02', '0.12', '0.22', '0.32', '0.42', '0.52', '0.62', '0.72', '0.82', '0.92', '0.03']

```

Algebraic solving:

```
corput(x) = reversed(str(float(x+1)))
          = reversed(str(x+1.))
          = str(x+1.)[::-1]
          = `x+1.`[::-1]

```
> 1 votes

# Answer
# BBC BASIC, ~~89~~ ~~88~~ 87 bytes

```
0T=1:REP.P."0."FNR(STR$T):T=T+1:U.0
1DEFFNR(S$)IFS$="":=""EL.=FNR(MI.S$,2))+LE.S$,1)

```

Used abbreviations to shorten things as much as possible. Compatible with both Brandy Basic and BASIC 2 on the original machine.

For modern BBC BASICs you could also leave off the line numbers to save two more bytes.
> 1 votes

# Answer
# Dyalog APL, 6

```
⌽¨1⍕¨⍳

```

This is an anonymous function that takes one argument, i.e.:

```
      ⌽¨1⍕¨⍳ 20
 0.1   0.2   0.3   0.4   0.5   0.6   0.7   0.8   0.9   0.01   0.11   0.21   0.31   0.41   0.51   0.61   0.71   0.81   0.91
         0.02
      f←⌽¨1⍕¨⍳
      f 20
 0.1   0.2   0.3   0.4   0.5   0.6   0.7   0.8   0.9   0.01   0.11   0.21   0.31   0.41   0.51   0.61   0.71   0.81   0.91
         0.02

```

Explanation:

```
     ⍳    ⍝ get the integers from 1..n
  1⍕¨     ⍝ format each with 1 decimal
⌽¨        ⍝ reverse each string

```
> 1 votes

# Answer
# Lua, 53 bytes

```
for i=1,io.read()do print("0."..(i..""):reverse())end

```

Try it online!
> 1 votes

# Answer
# Stax, 5 bytes

```
Öå┴I←

```

Run and debug it
> 1 votes

# Answer
# Factor, 39 bytes

```
[ [1,b] [ "%d.0"sprintf reverse ] map ]

```

Try it online!

* `[1,b] [ ... ] map` Map over the range 1..input.
* `"%d.0"sprintf reverse` String interpolate and reverse.
> 1 votes

# Answer
# Vyxal, 4 bytes

```
ƛ²√Ṙ

```

Try it Online!

Outputs as a list of what I think are strings.

```
ƛ    # 1..n mapped to...
 ²√  # Cast to float with √(x^2)
   Ṙ # Reverse

```
> 1 votes

# Answer
# Japt, 6 bytes

Outputs an array of strings

```
õx1 mw

```

Try it

```
õx1 mw     :Implicit input of integer U
õ          :Range [1,U]
 x1        :  Force each to 1 decimal place, converting to a string
    m      :Map
     w     :  Reverse

```
> 1 votes

# Answer
## JS, 66

```
T=101; // set T to the number of iterations wanted
for(o=[],i=0;i<T;i++)o[i]="0."+(""+i).split("").reverse().join("") // 66b

```

Output is the array called "o"
> 0 votes

# Answer
# Perl 5, 25 bytes

```
say'0.'.reverse for 1..<>

```
> 0 votes

# Answer
# Ruby, ~~46~~ ~~45~~ 40 bytes

```
->n{(1..n).map{|i|puts"#{i}.0".reverse}}

```

I'm new to golfing so any tips would be helpful :)
> 0 votes

# Answer
# Groovy, 36 characters

```
{(1..it).collect{"$it.0".reverse()}}

```

Sample run:

```
groovy:000> ({(1..it).collect{"$it.0".reverse()}})(12)
===> [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.01, 0.11, 0.21]

```
> 0 votes

# Answer
## Seriously, 8 bytes

```
,R`K$R`M

```

Try it online!

Explanation:

```
,R`K$R`M
,R        range(1, input()+1)
  `   `M  map:
   K        ceil (cast int to float; L would also work for floor)
    $R      stringify and reverse

```
> 0 votes

# Answer
# J-uby, 20 bytes

```
:+|:*&(S|:~|:+&"0.")

```

Attempt This Online!

## Explanation

```
:+ | :* & (S | :~ | :+ & "0.")

:+ |                            # Get range 1..n, then
     :* & (                  )  # Map with...
           S | :~ |             #   Convert to string then reverse, then
                    :+ & "0."   #   Append to "0."

```
> 0 votes

# Answer
# TI-Basic, 35 bytes

```
For(I,1,Ans
Disp sum(seq(fPart(.1int(I/₁₀^(J)))/₁₀^(J),J,0,int(log(I
End

```

Takes input in `Ans`.
> 0 votes

# Answer
# Thunno 2, 4 bytes

```
ı1/r

```

Try it online!

#### Explanation

```
ı1/r  # Implicit input
ı     # Map over [1..input]:
 1/   #   Divide by 1 (convert to float)
      #     (1     ->     1.0)
      #     (10    ->    10.0)
      #     (1234  ->  1234.0)
   r  #   Reverse this number
      #     (1.0     ->     0.1)
      #     (10.0    ->    0.01)
      #     (1234.0  ->  0.4321)
      # Implicit output

```
> 0 votes

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


title: Mean bits: an average challenge

text:
# Question
Title: Mean bits: an average challenge
Given an integer N \>= 1, output the mean number of bits in an integer from 0 to N - 1

# Specification

* The output can be calculated as the sum of the number of bits in the binary representation of each integer from 0 to N-1, divided by N.
* The binary representation of an integer has no leading zeroes in this context, with the exception of zero, which is represented as 0 in binary.
* The output should be accurate to at least 7 significant figures.

# Example

N = 6

```
0: 0   : 1 bit
1: 1   : 1 bit
2: 10  : 2 bits
3: 11  : 2 bits
4: 100 : 3 bits
5: 101 : 3 bits

```

Mean number of bits = (1 + 1 + 2 + 2 + 3 + 3) / 6 = 2

# Test cases

Input =\> output

```
1 => 1
2 => 1
3 => 1.3333333
4 => 1.5
5 => 1.8
6 => 2
7 => 2.1428571

```

---

# Leaderboard Snippet

(from here)

```
var QUESTION_ID=80586,OVERRIDE_USER=20283;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```

```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:400px;float:left}table thead{font-weight:700}table td{padding:5px}
```

```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```

Note that the sum (before dividing to find the mean) is a sequence on OEIS.

# Answer
> 13 votes
# Pyth, 6 bytes

```
.Oml.B

```

Try it online here.

```
.Oml.BdUQ              Filling in implict vars

.O                     Average of list
 m   UQ                Map over [0..input)
  l                    Length of
   .B                  Binary string representation of int
    d                  Lambda var

```

# Answer
> 9 votes
# Jelly, 6 bytes

```
R’BFL÷

```

Try it online!

```
R’BFL÷  Main monadic chain. Argument: n

R       yield [1, 2, ..., n]
 ’      decrement; yield [0, 1, ..., n-1]
  B     convert to binary; yield [[0], [1], [1,0], [1,1], ...]
   F    flatten list; yield [0, 1, 1, 0, 1, 1, ...]
    L   length of list
     ÷  divide [by n]

```

# Answer
> 7 votes
# Octave, 29 bytes

```
@(n)1+sum(fix(log2(1:n-1)))/n

```

**Explanation**

```
              log2(1:n-1)       % log2 of numbers in range [1..n-1]
                                % why no 0? because log2(0) = -Inf  :/
          fix(           )      % floor (more or less, for positive numbers)
      sum(                )     % sum... wait, didn't we miss a +1 somewhere?
                                % and what about that missing 0?
                           /n   % divide by n for the mean
    1+                          % and add (1/n) for each of the n bit lengths
                                % (including 0!)

```

Sample run on ideone.

# Answer
> 6 votes
# Python 3, 43 bytes

```
def f(n):x=len(bin(n))-2;return(2-2**x)/n+x

```

Makes use of the formula on the OEIS page. Surprisingly, a named function is somehow cheaper here because of the assignment to `x`.

Alternative approach for 46 bytes:

```
lambda n:-~sum(map(int.bit_length,range(n)))/n

```

Unfortunately, the `-~` is necessary since `(0).bit_length()` is `0`, but even then it'd be a byte too long.

# Answer
> 6 votes
# Julia, 27 bytes

```
n->endof(prod(bin,0:n-1))/n

```

Try it online!

### How it works

Since `*` is string concatenation in Julia, `prod` can be used to concatenate an array of strings. It optionally takes a function as first argument that it maps over the second one before taking the actual "product", so `prod(bin,0:n-1)` is the string of the binary representation of all integers in the desired range. Taking the length with `endof` and dividing by **n** yields the mean.

# Answer
> 5 votes
## Julia, 28 bytes

```
n->mean(ceil(log2([2;2:n])))

```

Since `bin` doesn't automatically map over arrays, we're using `ceil(log2(n))` to get the number of bits in `n-1`. This works out nicely because Julia's `a:b` notation is inclusive on both ends, so `2:n` is a range from 2 to `n`, but we're really calculating the number of bits for numbers in the range `1:n-1`. Unfortunately though, we need to tack on an extra `2` to account for 0.

Try it online!

# Answer
> 5 votes
# MATL, 9 bytes

```
q:ZlksG/Q

```

**Try it Online!**

Modified version with all test cases

**Explanation**

```
    % Implicitly grab input (N)
q:  % Create array from 1:N-1
Zl  % Compute log2 for each element of the array
k   % Round down to the nearest integer
s   % Sum all values in the array
G   % Explicitly grab input again
/   % Divide by the input
Q   % Add 1 to account for 0 in [0, ... N - 1]
    % Implicitly display the result

```

# Answer
> 5 votes
# MATL, 9 bytes

```
:qBYszQG/

```

Try it online!

**Explanation**

```
:qBYszQG/
:               % take vector [1..n]
 q              % decrement by 1 to get [0..n-1]
  B             % convert from decimal to binary
   Ys           % cumulative sum (fills in 0's after first 1)
     z          % number of nonzero elements
      Q         % increment by 1 to account for zero
       G        % paste original input (n)
        /       % divide for the mean

```

# Answer
> 5 votes
# Jelly, 8 bytes

Not shorter, but interesting algorithm, and my first Jelly submission:

```
Rl2Ċ»1S÷

R         1 to n
 l2       log2
   Ċ      ceiling
    »1    max of 1 and...
      S   sum
       ÷  divided by n

```

# Answer
> 4 votes
# Java, ~~135~~ ~~95~~ 90 bytes

```
float a(int n){int i=0,t=0;for(;i<n;)t+=Integer.toString(i++,2).length();return t/(n+0f);}

```

# Answer
> 4 votes
# Jelly, 10 bytes

```
BL©2*2_÷+®

```

From Sp3000's suggestion.

Try it here.

# Jelly, 11 bytes

```
æḟ2’Ḥ÷_BL$N

```

Not very short but I need some tips.

Try it here.

Using the same formula as in Sp3000's answer. (It's not very hard to get it yourself, by differentiating geometric progression.)

# Answer
> 3 votes
# Python 3, 46 Bytes

```
lambda x:sum(len(bin(i))-2for i in range(x))/x

```

Call it like

```
f = lambda x: sum(len(bin(i))-2for i in range(x))/x
print(f(6))
# 2.0

```

*I had to revert the map revision because it failed for input of 5*

# Answer
> 3 votes
# J, ~~21~~ ~~17~~ 15 bytes

From 17 bytes to 15 bytes thanks to @Dennis.

```
+/@:%~#@#:"0@i.

```

Can anyone help me golf this?...

### Ungolfed version

```
range        =: i.
length       =: #
binary       =: #:
sum          =: +/
divide       =: %
itself       =: ~
of           =: @
ofall        =: @:
binarylength =: length of binary "0
average      =: sum ofall divide itself
f            =: average binarylength of range

```

# Answer
> 3 votes
## 05AB1E, ~~9~~ 7 bytes

**Code:**

```
L<bJg¹/

```

**Explanation:**

```
L<         # range from 0..input-1
  b        # convert numbers to binary
   J       # join list of binary numbers into a string
    g      # get length of string (number of bits)
     ¹/    # divide by input

```

Try it online

Edit: saved 2 bytes thanks to @Adnan

# Answer
> 3 votes
## Clojure, ~~71~~ ~~64~~ 63 bytes

It looks like ratios are ok according to Which number formats are acceptable in output?

`(fn[n](/(inc(apply +(map #(.bitLength(bigint %))(range n))))n))`

* n=1 =\> 1
* n=7 =\> 15/7

ungolfed (and slightly rewritten for ease of explanation)

```
(fn [n]
 (->
  (->>
   (range n)                      ;;Get numbers from 0 to N
   (map #(.bitLength (bigint %))) ;;Cast numbers to BigInt so bitLength can be used
   (apply +)                      ;;Sum the results of the mapping
   (inc))                         ;;Increment by 1 since bitLength of 0 is 0
  (/ n)))                         ;;Divide the sum by N

```

### old answer that used (float):

`(fn[n](float(/(inc(apply +(map #(..(bigint %)bitLength)(range n))))n)))`

output is like:

* n=1 =\> 1.0
* n=7 =\> 2.142857

# Answer
> 3 votes
# C#, 87 bytes

```
double f(int n){return Enumerable.Range(0,n).Average(i=>Convert.ToString(i,2).Length);}

```

I wrote a C# answer because I didn't see one. This is my first post to one of these, so please let me know if I'm doing anything wrong.

# Answer
> 3 votes
# Vyxal `r`, 5 bytes

```
ʁbfL/

```

Try it Online!

```
ʁ     # 0...a
 b    # Turn each into base 2
  f   # Flatten
   L  # Get the length
    / # Divide by the input

```

# Answer
> 2 votes
## JavaScript (ES7), ~~38~~ 32 bytes

```
n=>(l=-~Math.log2(n))-(2**l-2)/n

```

Using @sp3000's formula (previous version was a recursive solution). ES6 version for 34 bytes:

```
n=>(l=-~Math.log2(n))-((1<<l)-2)/n

```

Explanation of formula: Consider the case of N=55. If we write the binary numbers (vertically to save space), we get:

```
                                11111111111111111111111
                111111111111111100000000000000001111111
        11111111000000001111111100000000111111110000000
    111100001111000011110000111100001111000011110000111
  11001100110011001100110011001100110011001100110011001
0101010101010101010101010101010101010101010101010101010

```

The size of this rectangle is *nl* so the average is just *l* but we need to exclude the blanks. Each row of blanks is twice as long as the previous so the total is 2 + 4 + 8 + 16 + 32 = 64 - 2 = 2l \- 2.

# Answer
> 2 votes
# Perl 6,  ~~34~~  32 bytes

~~```
{$_ R/[+] map *.base(2).chars,^$_}

```~~
```
{$_ R/[+] map {(.msb||0)+1},^$_}

```

### Explanation:

```
{
  $_  # the input
  R/  # divides ( ｢$a R/ $b｣ is the same as ｢$b / $a｣ )
  [+] # the sum of:
  map
    {
      (
       .msb # the most significant digit (0 based)
       || 0 # which returns Nil for ｢0.msb｣ so use 0 instead
            # should be ｢(.msb//0)｣ but the highlighting gets it wrong
            # it still works because it has the same end result
      )
      + 1   # make it 1 based
    },
    ^$_ # ｢0 ..^ $_｣ all the numbers up to the input, excluding the input
}

```

### Test:

```
use v6.c;

# give it a name
my &mean-bits = {$_ R/[+] map {(.msb||0)+1},^$_}

for 1..7 {
  say .&mean-bits
}

say '';

say mean-bits(7).perl;
say mean-bits(7).base-repeating(10);

```

```
1
1
1.333333
1.5
1.8
2
2.142857

<15/7>
(2. 142857)

```

# Answer
> 2 votes
# Dyalog APL, 14 bytes

```
(+/1⌈(⌈2⍟⍳))÷⊢

range ← ⍳
log   ← ⍟
log2  ← 2 log range
ceil  ← ⌈
bits  ← ceil log2
max   ← ⌈
fix0  ← 1 max bits
sum   ← +/
total ← sum fix0
self  ← ⊢
div   ← ÷
mean  ← sum div self

```

# Answer
> 1 votes
## Minkolang 0.15, 23 bytes

```
n$z1z[i1+2l$M$Y+]kz$:N.

```

Try it here!

### Explanation

```
n$z                       Take number from input and store it in register (n)
   1                      Push 1 onto the stack
    z[                    For loop that repeats n times
      i1+                 Loop counter + 1
         2l$M             log_2
             $Y           Ceiling
               +          Add top two elements of stack
                ]         Close for loop
                 z$:      Float divide by n
                    N.    Output as number and stop.

```

Pretty straightfoward implementation.

# Answer
> 1 votes
# JavaScript ES5, 55 bytes

```
n=>eval(`for(o=0,p=n;n--;o+=n.toString(2).length/p);o`)

```

## Explanation

```
n =>   // anonymous function w/ arg `n`
  for( // loop
      o=0,  // initalize bit counter to zero
      p=n   // copy the input
    ;n-- // will decrease input every iteration, will decrease until it's zero
    ;o+=    // add to the bitcounter
        n.toString(2)  // the binary representation of the current itearations's
                     .length // length
        /p   // divided by input copy (to avergage)
   );o       // return o variable

```

# Answer
> 1 votes
## Hoon, 71 bytes

```
|=
r/@
(^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq

```

...I'm pretty sure this is actually the first time I've used Hoon's floating point cores. It's actually an implementation written in Hoon that jets out to SoftFloat, since the only data types in Hoon are atoms and cells.

Create a function that takes an atom, `r`. Create a list from \[0..(r - 1)\], map over the list taking the binary logarithm of the number, then fold over that list with `++add`. Convert both the output of the fold and `r` to `@rq` (quad-precision floating point numbers) with `++sun:rq`, and then divide one by the other.

The oddest thing in this snippet is the `:.^rq` at the end. `a:b` in Hoon means "evaluate a in the context of b". `++rq` is the core that contains the entire quad-precision implementation, like a library. So running `(sun 5):rq` is the same thing as doing `(sun:rq 5)`.

Luckily, cores in Hoon are like nesting dolls; when you evaluate the arm `++rq` to get the core, it adds the entire stdlib to it as well, so you get to keep roll and turn and gulf and all that fun stuff instead of being stuck with *only* the arms defined in `++rq`. Unluckily, rq redefines `++add` to be floating-point add instead, along with not having `r` in its context. `.` (the entire current context) does, however.

When evaluating an expression in a context, the compiler looks for the limb depth-first. In our case of `a:[. rq]` it would look in the entire current context for `a` before moving on to looking in `rq`. So `add` will look up the function that works on atoms instead of floating-point numbers...but so will `div`. Hoon also has a feature where using `^name` will ignore the first found reference, and look for the second.

From there, it's simply using the syntatic sugar of `a^b` being equal to `[a b]` to evaluate our snippet with both our current context and the quad-precision float library, ignoring the atomic div in favor of `++div:rq`.

```
> %.  7
  |=
  r/@
  (^div (sun (roll (turn (gulf 0 (dec r)) xeb) add)) (sun r)):.^rq
.~~~2.1428571428571428571428571428571428

```

# Answer
> 1 votes
## Actually, 7 bytes:

```
;r♂├Σl/

```

Try it online!

Explanation:

```
;r♂├Σl/
;        duplicate input
 r       push range(0, n) ([0, n-1])
  ♂├     map binary representation
    Σ    sum (concatenate strings)
     l/  divide length of string (total # of bits) by n

```

If it weren't for a bug that I just discovered, this solution would work for 6 bytes:

```
r♂├♂læ

```

`æ` is the builtin mean command.

# Answer
> 1 votes
# CJam, ~~13~~ ~~12~~ 11 bytes

*One byte saved thanks to @Sp3000, and another thanks to @jimmy23013*

```
rd_,2fbs,\/

```

**Try it online!**

### Explanation

Straightforward. Applies the definition.

```
rd      e# read input and convert to double
_       e# duplicate
,       e# range from 0 to input minus 1
2fb     e# convert each element of the array to binary
s       e# convert to string. This flattens the array
,       e# length of array
\       e# swap
/       e# divide

```

# Answer
> 1 votes
# Vitsy, 26 bytes

This is a first attempt, I'll golf this down more and add an explanation later.

```
0vVV1HV1-\[2L_1+v+v]v1+V/N
```

Try it online!

# Answer
> 1 votes
## Perl 5.10, 54 bytes

```
for(1..<>){$u+=length sprintf"%b",$_;$n++}$u/=$n;say$u

```

Pretty much straightforward. `sprintf"%b"` is a neat way to output a number in binary in Perl without using additional libraries.

Try it online!

# Answer
> 1 votes
## PowerShell v2+, 64 bytes

```
param($n)0..($n-1)|%{$o+=[convert]::ToString($_,2).Length};$o/$n

```

Very straightforward implementation of the spec. Loops from `0` to `$n-1` with `|%{...}`. Each iteration, we `[convert]` our input number `$_` to a string base`2` and take its `length`. We accumulate that in `$o`. After the loops, we simply divide `$o/$n`, leaving that on the pipeline, and output is implicit.

As long as this is, it's actually shorter than the formula that Sp & others are using, since `[math]::Ceiling()` and `[math]::Log()` are ridiculously wordy. Base conversion in PowerShell is yucky.

# Answer
> 1 votes
# Jolf, 10 bytes

```
/uΜr0xdlBH

```

Try it here!

## Explanation

```
/uΜr0xdlBH
  Μr0x      map range 0..x
      dlBH  over lengths of binary elements
/u          divide sum of this
            by implicit input (x)

```

# Answer
> 1 votes
# Swift, 72 bytes

```
func f(n:Double)->Double{return n<1 ?1:f(n-1)+1+floor(log2(n))}
f(N-1)/N

```

# Answer
> 1 votes
## J, 15 bytes

```
%~[:+/#@#:"0@i.

```

This is a monadic verb, used as follows:

```
   f =: %~[:+/#@#:"0@i.
   f 7
2.14286

```

Try it here!

## Explanation

I implemented the challenge spec pretty literally. There are other approaches, but all turned out to be longer.

```
%~[:+/#@#:"0@i.  Input is y
             i.  Range from 0 to y-1.
          "0@    For each number in this range:
      #@           Compute the length of
        #:         its base-2 representation.
  [:+/           Take the sum of the lengths, and
%~               divide by y.

```

# Answer
> 1 votes
# AWK, 59 bytes

```
{for(s=1;++n<$0;s+=int(log(n*2)/log(2)));printf"%.8g",s/$0}

```

Since `AWK` only does base-10 logs, I had to convert to base-2 and I chose to multiply the argument by 2 rather than add 1 to the result. It's the same byte-count, but I like it. :)

Try it online!

# Answer
> 1 votes
# Japt, 6 bytes

```
o¤xÊ/U

```

Try it

---

## Explanation

```
           :Implicit input of integer U
o          :Range [0,U)
 ¤         :Convert each to a base-2 string
   Ê       :Get length of each
  x        :Reduce by addition
    /U     :Divide by U
           :Implicit output of result

```

# Answer
> 1 votes
# K4, 16 bytes

**Solution:**

```
(1+#,/2\:'!x)%x:

```

**Example:**

```
(1+#,/2\:'!x)%x:5
1.8
(1+#,/2\:'!x)%x:6
2f
(1+#,/2\:'!x)%x:7
2.142857

```

**Explanation:**

Convert each number to binary, sum up the bits, add `1` for `0`, divide by input.

```
(1+#,/2\:'!x)%x: / the solution
              x: / store input as x
(           )%   / divide left by right
          !x     / range 0..x-1
      2\:'       / convert each (') to bits (2\:)
    ,/           / flatten result
   #             / count length of list
 1+              / add one (as 0 contains 0 bits!)

```

**Extra:**

Precision is determined by the `P` system setting. Default is `7`, max is `17`

```
\P 7
(1+#,/2\:'!x)%x:7
2.142857

\P 12
(1+#,/2\:'!x)%x:7
2.14285714286

\P 17
(1+#,/2\:'!x)%x:7
2.1428571428571428

```

# Answer
> 1 votes
# Pyt, 8 bytes

```
⁻řļ⌊⁺Á1µ

```

Explanation:

```
                Implicit input (N)
⁻               Decrement by 1 (N-1)
 ř              Push [1,2,...,N-1]
  ļ             element-wise log base 2 of [1,2,...,N-1]
   ⌊⁺           element-wise floor and increment
     Á          Push contents of array onto stack
      1         Push 1
       µ        Get mean of stack
                Implicit output

```

Try it online!

# Answer
> 1 votes
# , 51 bytes

Takes input from stdin. Uses the OEIS formula and then divides by `n`.

```
(2+ceiling(log2(n<-scan()))*n-2^ceiling(log2(n)))/n

```

Try it online!

# Answer
> 0 votes
# Ruby, ~~44~~ 34 bytes

Now starring the formula used by @Sp3000

```
->x{(2.0-2**b=x.to_s(2).size)/x+b}

```

Old version:

```
->x{r=0.0;x.times{|i|r+=i.to_s(2).size};r/x}

```

# Answer
> 0 votes
## Mathematica, 28 bytes

```
(Tr@⌈Log2@Range@#⌉+1)/#&

```

or

```
Tr@⌈Log2@Range@#⌉/#+1/#&

```

In either case, it's an unnamed function which takes `N` as an input and returns an exact (rational) result for the mean.

# Answer
> 0 votes
## Pyke, 8 bytes

```
Qmb2slQ/

```

Try it here!

# Answer
> 0 votes
# Haskell, 50 bytes

```
r x|x<1=0|1<2=1+r(x/2)
f n=(sum(r<$>[0..n-1])+1)/n

```

# Answer
> 0 votes
# J, 22 bytes

`[:(+/%#)[:([:##:)"0 i.` Usage:

```
    bin =: [:(+/%#)[:([:##:)"0 i.
    bin 7
2.14286

```

# Answer
> 0 votes
# PHP, 48 bytes

a direct port of Sp3000´s answer

```
<?=(2-2**$x=strlen(decbin($n=$argv[1]))-2)/$n+$x

```

# Answer
> 0 votes
# Perl 5, ~~44~~ 43 + 2 (`-pa`) = 45 bytes

*-1 thanks to @DomHastings*

```
$\+=(length sprintf'%b',$_)/"@F"while$_--}{

```

Try it online!

# Answer
> 0 votes
# Thunno 2, 4 bytes

```
Lḃḷm

```

Try it online!

#### Explanation

```
Lḃḷm  # Implicit input
L     # Push [0..input)
 ḃ    # Convert each to binary
  ḷ   # And get the length of each one
   m  # Take the average of the result
      # Implicit output

```

---
Tags: code-golf, math, binary, bitwise, statistics
---


title: Who has a comma for a middle name?

text:
# Question
Title: Who has a comma for a middle name?
Your challenge is to take a name (string) as input, like

```
Albert Einstein

```

and output:

```
Einstein, Albert

```

## Pseudocode:

```
set in to input
set arr to in split by " "
set last to the last element of arr
remove the last element of arr
set out to arr joined with " "
prepend ", " to out
prepend last to out
output out

```

## More test cases:

```
John Fitzgerald Kennedy => Kennedy, John Fitzgerald
Abraham Lincoln => Lincoln, Abraham

```

## Rules

* The input will always match the regex `^([A-Z][a-z]+ )+([A-Z][a-z]+)$`.
* You don't need to handle weird names, even if the output is technically incorrect it is fine here.
* Trailing whitespace / newline is OK.
* Any questions? Comment below!

# Answer
# 05AB1E, 7 bytes

### Code:

```
',ì#Áðý

```

Uses the **05AB1E** encoding. Try it online!

### Explanation:

```
',ì         # Prepend the input to ","
   #        # Split on spaces
    Á       # Rotate every element one position to the right (wrapping)
     ðý     # Join the array by spaces

```
> 10 votes

# Answer
# JavaScript (ES6), 34 bytes

```
s=>s.replace(/(.+) (.+)/,'$2, $1')

```

# Demo:

```
let f = s=>s.replace(/(.+) (.+)/,'$2, $1')

;[ 'Albert Einstein', 'John Fitzgerald Kennedy', 'Abraham Lincoln' ].forEach(
  s => console.log(`${s} => ${f(s)}`)
)
```
> 8 votes

# Answer
# Retina, ~~19~~ ~~17~~ 16 bytes

*Edit: Thanks to Riker for saving 3 bytes*

```
(.+) (.+)
$2, $1

```

Try it online!
> 7 votes

# Answer
# Jelly, 7 bytes

```
;”,Ḳṙ-K

```

Try it online!

I don't know Jelly very well, but reading other answers it looked like they didn't use an optimal algorithm... so here it is:

### Explanation

```
;”,Ḳṙ-K
;”,        Append a comma to the end of the string
   Ḳ       Split on spaces
    ṙ-     Rotate the array by -1 (1 time towards the right)
      K    Join with spaces

```
> 6 votes

# Answer
# / vim, ~~9~~ 8 bytes

```
$bD0Pa,

```

Try it online!

Saved one Byte thanks to

Note there is a trailing space character. Leaves a trailing space, which is allowed per the rules.

Explanation:

```
$       " move the cursor to the end of the line
 b      " move the cursor to the beginning of the current word
  D     " delete to the end of the line
   0    " move the cursor to the start of the line
    P   " paste in front of the cursor.
     a  " append (enter insert mode with the cursor one character forward)
      , " Literal text, ", "

```
> 6 votes

# Answer
## Mathematica, 52 40 bytes

```
StringReplace[x__~~" "~~y__:>y<>", "<>x]

```
> 5 votes

# Answer
# Python 2, 39 bytes

```
f,l=input().rsplit(' ',1);print l+',',f

```

Try it online!

Yup, `rsplit`.
> 5 votes

# Answer
# Vim, 10 bytes/keystrokes

```
v$F dA, <esc>p

```

Try it online!
> 5 votes

# Answer
# C, 45 bytes

EDIT: I just now noticed the requirement for the input possibly having more than two words. I'll leave it as-is with a note that this only works for two words.

EDIT: removed `\n`. Add 2 bytes if you consider it necessary.

```
main(a,b)int**b;{printf("%s, %s",b[2],b[1]);}

```

Compiles with `gcc name.c`, GCC 6.3.1. Ignore warnings. Usage:

```
$./a.out Albert Einstein
Einstein, Albert

```

Abuse of language:

* Implicit return type `int` of `main` and nothing returned.
* Implicit declaration of `printf`. GCC will include it anyway.
* Wrong type of `b`. Doesn't matter with `%s`

Thanks to @Khaled.K for the tips on using `main(a,b)int**b;` rather than `main(int a, int **b)`.
> 4 votes

# Answer
# \>\<\>, 27 bytes

```
i:0(?v
" ,"~<^r/
=" ":}o!/?

```

Try it online!
> 4 votes

# Answer
# Ruby, 22 bytes

```
->s{s[/\w+$/]+", #$`"}

```

Try it online!
> 3 votes

# Answer
# C, 68 bytes

Hope it's not wrong to add another post but here's a slightly different solution than my previously posted C solution. This one accepts any number of names.

```
main(a,b)int**b;{for(printf("%s,",b[--a]);--a;printf(" %s",*++b));}

```

Compile with `gcc name.c` (GCC 6.3.1) and ignore warnings. Usage:

```
$./a.out John Fitzgerald Kennedy
Kennedy, John Fitzgerald

```

Thanks to @Khaled.K for the tips on `main(a,b)int**b;`

Thanks for the tip on the for loop to @Alkano.
> 3 votes

# Answer
# sed, 19 + 1 for -E = 20 bytes

```
s/(.*) (.*)/\2, \1/

```

Must use -r (GNU) or -E (BSD, recent GNUs) to avoid having to escape the grouping parenthesis.

If written on the command-line, must be enclosed in quotes to avoid being parsed as multiple tokens by the shell :

```
sed -E 's/(.*) (.*)/\2, \1/'

```
> 3 votes

# Answer
# Mathematica, 45 bytes

```
#/.{a__,s=" ",b__}/;{b}~FreeQ~s->{b,",",s,a}&

```

Saved a few bytes over ngenisis's answer by taking input as a list of characters rather than as a string. Pure function that uses a pattern-replacement rule.

## Mathematica, 49 bytes

```
#~Join~{","," "}~RotateLeft~Last@Position[#," "]&

```

Another pure function taking a list of characters as input and returning a list of characters. This one appends `","` and `" "` to the input and then rotates the list of characters until the last space is at the end. (Thus the output has a trailing space, unlike the first function above.)
> 2 votes

# Answer
# C#, ~~76~~ 72 bytes

```
s=>System.Text.RegularExpressions.Regex.Replace(s,"(.+) (.+)","$2, $1");

```

*Saved 4 bytes with the help of @KevinCruijssen*

Old version using substrings for 76 bytes:

```
s=>s.Substring(s.LastIndexOf(' ')+1)+", "+s.Substring(0,s.LastIndexOf(' '));

```
> 2 votes

# Answer
# Awk, 18 characters

```
{$1=$NF", "$1}NF--

```

Sample run:

```
bash-4.4$ awk '{$1=$NF", "$1}NF--' <<< 'John Fitzgerald Kennedy'
Kennedy, John Fitzgerald

```

Try it online!
> 2 votes

# Answer
# JS (ES6), ~~52~~ 44 bytes

```
i=>(i=i.split` `,l=i.pop(),l+", "+i.join` `)

```
> 1 votes

# Answer
# Jelly, 8 bytes

```
Ḳ©Ṫ”,⁶®K

```

Try it online!
> 1 votes

# Answer
# Jelly, 9 bytes

```
ḲµṪ;⁾, ;K

```

## Explained, ish:

```
ḲµṪ;⁾, ;K
Ḳ           # Split the input by spaces
 µ          # Separate the link into two chains. Essentially calls the right half with the split string monadically.
  Ṫ         # The last element, (The last name), modifying the array.
   ;        # Concatenated with...
    ⁾,      # The string literal; ", "
       ;    # Concatenated with...
        K   # The rest of the array, joined at spaces.

```

Try it online!

Try on all test cases.
> 1 votes

# Answer
# Java, ~~110~~ 62 bytes

```
String d(String s){return s.replaceAll("(.+) (.+)","$2, $1");}

```

Non-static method.

-48 bytes thanks to Kevin Cruijssen
> 1 votes

# Answer
# 05AB1E, 9 bytes

```
#`',«.Áðý

```

Try it online!

**Explanation**

```
#           # split input on spaces
 `          # push each name separately to stack
  ',«       # concatenate a comma to the last name
     .Á     # rotate stack right
       ðý   # join stack by spaces

```
> 1 votes

# Answer
# PHP, 62 59 bytes

-3 bytes, thanks Jörg

```
$a=explode(' ',$argn);echo array_pop($a).', '.join(' ',$a);

```

Try it online!

Old solution, 63 Bytes

Doesn't work if the person has 3 repeating names.

```
<?=($a=strrchr($argv[1]," ")).", ".str_replace($a,'',$argv[1]);

```

Try it online
> 1 votes

# Answer
# MATLAB/Octave, 37 bytes

```
@(a)regexprep(a,'(.+) (.+)','$2, $1')

```

Try it online!

Based on @ngenisis' Retina answer, we can also play the regex game in both Octave and MATLAB, saving a fair few bytes over my previous answer.

---

### Old Answer:

I'm going to leave this answer here as well considering it is a more unique way of doing it compared to a simple regex.

# Octave, ~~49~~ 47 bytes

```
@(a)[a((b=find(a==32)(end))+1:end) ', ' a(1:b)]

```

Old try it online!

An anonymous function to generate the output.

Basically the code first finds the last space in the string using `b=find(a==32)(end)`. Then It takes the end part of the string (after the space) using `a(b+1:end)`, where `b` is the output of finding the last space. It also takes the start of the string with `a(1:b-1)`, and concatenates both together with a `', '` in between.

I've already saved a few bytes vs the typical `find(a==32,1,'last')`. Not quite sure there is much more to save.
> 1 votes

# Answer
# PHP, 45 Bytes

```
<?=preg_filter("#(.*) (.+)#","$2, $1",$argn);

```

Try it online!
> 1 votes

# Answer
# Pyth, 11 bytes

```
jd.>c+z\,d1

```

**Explanation:**

```
jd.>c+z\,d1
     +z\,      Append the "," to the input
    c+z\,d     Split the string on " "
  .>c+z\,d1    Rotate the array one element right
jd.>c+z\,d1    Join the array on " "

```

Test it online!
> 1 votes

# Answer
# Bash, 26 bytes

```
echo ${!#}, ${@:1:$[$#-1]}

```

Try it online!
> 1 votes

# Answer
# Excel, ~~174~~ ~~170~~ 168 bytes

Saved 2 bytes thanks to Wernisch

```
=MID(A1,FIND("^",SUBSTITUTE(A1," ","^",LEN(A1)-LEN(SUBSTITUTE(A1," ",""))))+1,LEN(A1))&", "&LEFT(A1,FIND("^",SUBSTITUTE(A1," ","^",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))))

```

This is not fancy or clever. It's a fairly basic method. It feels like there should be a shorter way with array formulas but I can't find one that works.
> 1 votes

# Answer
# Japt, 14 bytes

```
U+', q'  é q'

```

A port of @programmer5000's JavaScript answer.

Try it online!
> 1 votes

# Answer
# Python 3, 52 bytes

```
lambda s:s.split()[-1]+", "+" ".join(s.split()[:-1])

```

Very simple, could use golfing help. Just puts the last word at the front and joins them with ", ".

Testcase:

```
>>> f=lambda s:s.split()[-1]+", "+" ".join(s.split()[:-1])
>>> f("Monty Python")
'Python, Monty'
>>> f("Albus Percival Wulfric Brian Dumbledore")
'Dumbledore, Albus Percival Wulfric Brian'

```
> 1 votes

# Answer
## Perl 18+1=19 bytes

```
perl -pe '/\S+$/;$_="$&, $`"'

```

+1 for `-p`
> 1 votes

# Answer
# Vim, 6 keystrokes

```
i<C-p>, <End><C-w>

```

Leaves a trailing space character, which is allowed by the rules

Explanation:
```
i      Enter insert mode
<C-p>  Autocomplete with last word
,      Write ", "
<End>  Move the cursor to the end of the line
<C-w>  Delete the word behind the cursor

```
> 1 votes

# Answer
# Thunno 2 , 5 bytes

```
',+OṾ

```

Try it online!

#### Explanation

```
',+OṾ  '# Implicit input
',+    '# Append a ","
   O    # Split on spaces
    Ṿ   # Rotate right
        # Join by spaces
        # Implicit output

```
> 1 votes

# Answer
# Nibbles, 7.5 bytes

```
*" "::`(\%$~","\

```

Attempt This Online!
> 1 votes

# Answer
# Vyxal `S`, 38 bitsv1, 4.75 bytes

```
\,+⌈ǔ

```

Try it Online!

I do not have a comma for a middle name. Ports Thunno 2 but with a range coder.

```
\,+⌈ǔ
\,+    # Append a comma
   ⌈   # Split on spaces
    ǔ  # Rotate right once
# The S flag joins on spaces

```

Created with the help of Luminespire.
> 1 votes

# Answer
# Python 3, ~~52~~ 51 bytes:

```
k=input().split()
print(k[-1]+',',' '.join(k[:-1]))

```

-1 byte thanks to ovs
> 0 votes

# Answer
# Ruby, 26+1 = 27 bytes

Uses the `-p` flag for +1 byte. Probably can be redone shorter in Retina. And it was!

-1 byte from Kevin Cruijssen.

```
gsub /(.+) (.+)/,'\2, \1'

```

Try it online!
> 0 votes

# Answer
# MATL, 10 bytes

```
44hYb1YSZc

```

Try it online!

### Explanation

```
44h    % Implicitly input a string. Postpend a comma
       % STACK: 'John Fitzgerald Kennedy,'
Yb     % Split on spaces
       % STACK: {'John', 'Fitzgerald', 'Kennedy,'}
1YS    % Circularly shift 1 step to the right
       % STACK: {'Kennedy,', 'John', 'Fitzgerald'}
Zc     % Join with spaces between. Implicitly display
       % STACK: 'Kennedy, John Fitzgerald'

```
> 0 votes

# Answer
# Gema, 23 characters

```
* =@append{s; *}
\Z=,$s

```

The only remarkable thing here is how the challenge managed to hit the weakness of the Gema patterns non-greediness.

Sample run:

```
bash-4.4$ echo -n 'John Fitzgerald Kennedy' | gema '* =@append{s; *};\Z=,$s'
Kennedy, John Fitzgerald

```
> 0 votes

# Answer
# jq, ~~39~~ 38 characters

(~~35~~ 34 characters code + 4 characters command line options)

```
./" "|last+", "+(.[:-1]|join(" "))

```

Sample run:

```
bash-4.4$ jq -Rr './" "|last+", "+(.[:-1]|join(" "))' <<< 'John Fitzgerald Kennedy'
Kennedy, John Fitzgerald

```

Try in jq‣play

### jq, 43 characters

(39 characters code + 4 characters command line options)

```
sub("(?<f>.+) (?<l>.+)";"\(.l), \(.f)")

```

Just a curiosity: `jq` only captures named groups, which helps readability, but nothing else.

Sample run:

```
bash-4.4$ jq -Rr 'sub("(?<f>.+) (?<l>.+)";"\(.l), \(.f)")' <<< 'John Fitzgerald Kennedy'
Kennedy, John Fitzgerald

```

Try in jq‣play
> 0 votes

# Answer
# Scala, 65 bytes

```
(s:String)=>{val n=s.split(' ');n.last+", "+n.init.mkString(" ")}

```
> 0 votes

# Answer
# R, 90 bytes

```
function(s){b=el(strsplit(s,' '))
l=length(b)
paste0(b[l],', ',paste(b[-l],collapse=' '))}

```

Anonymous function. Takes the string, splits it, outputs the last name, a comma, and the rest of the names from the beginning. Would love to see something better, I'm not too good at manipulating strings in R.
> 0 votes

# Answer
# SNOBOL4, 77 bytes

```
begin
 input arb . f span(&lcase &ucase) . l rpos(0)
 output = l ', ' f
end

```

This is a pretty straightforward case of pattern matching.

1. Read a line of input, then match it against:
2. arbitrary characters (which we'll assign to `f`), followed by
3. a span of upper- and lower-case letters (which we'll assign to `l`) which
4. matches to the end of the input (`rpos(0)`).

Having matched those, we write out `l`, comma and space, `f`.
> 0 votes

# Answer
# Carrot, 56 bytes

```
#^//\w+$|^.+(?= )/gS";"^ ^*1//;.+(?=;)/S0-1//^\w+| .+$/g

```

Try it online!

### Explanation

Carrot has several global variables, one for each type: string, float and array. The program starts in string-mode, where all the operators will affect the global string variable. And I call these variables the "stack".

Example input is `John Fitzgerald Kennedy`.

```
#^                       Set stack-string to the value of the input string
/                        Operator, get matches of this regex on the stack-string and store the matches in stack-array
 /\w+$|^.+(?= )/g        The last name or the first names
S";"                     Convert to string-mode by joining on ";"
                         stack-string = "John Fitzgerald;Kennedy"
^ ^                      Append a space to the stack-string
*1                       Append one copy of the stack-string to itself
                         stack-string = "John Fitzgerald;Kennedy John Fitzgerald;Kennedy "
/                        The match operator
 /;.+(?=;)/              Anything bounded by ";"s except for the last ";"
S0                       Since we are guaranteed to get one match, we can join with any literal, it does not matter. Here we are joining using a 0.
-1                       Remove the first character in the stack-string (the first ";")
                         stack-string = "Kennedy John Fitzgerald"
/                        The match operator
 /^\w+| .+$/g            The first word or the last ones
                         stack-array = ["Kennedy", " John Fitzgerald"]

```

Luckily for us, the interpreter is bad and displays the result as just `Kennedy, John Fitzgerald`.
> 0 votes

# Answer
# PowerShell, 35 Bytes

simple regex solution, not too interesting:

```
"$args"-replace'(.+) (.+)','$2, $1'

```
> 0 votes

# Answer
# Aceto, ~~21~~ 17 bytes

```
,p p
'@'p
pQ$d
r-

```

~~I'm *sure* we can fit this into a 4x4, but I just couldn't do it..~~

Reads a value, splits it on whitespace, "unqueues" it (a b c -\> c a b), prints the first element, prints a comma, sets a catchmark.

Prints a space and the next element (i.e. the first given name). Duplicate the top stack element (a zero if we're done, otherwise the next given name). If that value is truthy (i.e. not 0), jump to the catch mark.
> 0 votes

# Answer
# PHP, 49+1 bytes

```
<?=preg_replace("#^(.*) (\w+)$#","$2, $1",$argn);

```

Run as pipe with `-nF`.
> 0 votes

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


# Question
Title: Convert a 32 bit binary IPv4 address to its quad-dotted notation
# Challenge

Write a program or function that converts a 32 bit binary number to its quad-dotted decimal notation (often used for representing IPv4)

# Quad-dotted decimal

A quad-dotted decimal is formed like so:

1. Split the binary representation into its 4 individual bytes
2. Convert each byte into denary
3. place "." between each number

Example:

```
input:  10001011111100010111110001111110
step 1: 10001011 11110001 01111100 01111110
step 2:    139      241      124      126
step 3: 139.241.124.126

```

# I/O examples

```
input --> output

10001011111100010111110001111110 --> 139.241.124.126
00000000000000000000000000000000 --> 0.0.0.0
01111111000000000000000000000001 --> 127.0.0.1
11000000101010000000000111111111 --> 192.168.1.255

```

# Rules

# Answer
# 05AB1E, 6 bytes

```
4äC'.ý

```

Try it online or verify all test cases.

**Explanation:**

```
4ä       # Convert the (implicit) input-string into 4 equal-sized parts
  C      # Convert each part from binary to an integer
   '.ý  '# Join this list by "."
         # (after which the result is output implicitly)

```
> 10 votes

# Answer
# x86-16 machine code, IBM PC DOS, ~~54~~ ~~47~~ 45 bytes

**Binary:**

```
00000000: be82 00b3 04b1 08ac d0d8 d0d4 e2f9 8ac4  ................
00000010: 41d4 0a50 8ac4 84c0 75f6 580c 30b4 0ecd  A..P....u.X.0...
00000020: 10e2 f74b 7406 b02e cd10 ebd9 c3         ...Kt........

```

Build and test `BIN2IP.COM` using `xxd -r` from above.

**Unassembled listing:**

```
BE 0082     MOV  SI, 82H        ; command line input address
B3 04       MOV  BL, 4          ; loop 4 bytes
        BYTE_LOOP:
B1 08       MOV  CL, 8          ; loop 8 bits
        BIT_LOOP:
AC          LODSB               ; load next bit char into AL
D0 D8       RCR  AL, 1          ; put LSB of char into CF
D0 D4       RCL  AH, 1          ; put CF into LSB of byte value, then shift left
E2 F9       LOOP BIT_LOOP       ; continue bit loop
8A C4       MOV  AL, AH         ; put byte result into AL
        GET_DIGIT:
D4 0A       AAM                 ; byte divide by 10, AH = AL / 10, AL = AL % 10
50          PUSH AX             ; save remainder in AL on stack
8A C4       MOV  AL, AH         ; put quotient back into AL
41          INC  CX             ; increment decimal digit count
D4 C0       TEST AL, AL         ; quotient = 0?
75 F6       JNZ  GET_DIGIT      ; if not, continue looping
        PRINT_DIGIT:
58          POP  AX             ; restore digit in AL
0C 30       OR   AL, '0'        ; ASCII convert
B4 0E       MOV  AH, 0EH        ; BIOS write char function
CD 10       INT  10H            ; write to console
E2 F7       LOOP PRINT_DIGIT    ; loop until done
4B          DEC  BX             ; is last byte?
74 06       JZ   END_LOOP       ; if so, don't display a '.'
B0 2E       MOV  AL, '.'        ; otherwise display '.'
CD 10       INT  10H            ; write to console
        END_LOOP:
75 D7       JNZ  BYTE_LOOP      ; continue byte loop
C3          RET                 ; exit to DOS

```

**Output:**

A standalone PC DOS executable. Input is command line, output to console.

**Notes:**

The "interesting part" (converting binary string to bytes) is about 15 bytes, whereas the rest of code is writing the `itoa()` function to convert binary bytes into a decimal string representation for display.

* -2 bytes eliminating unnecessary `PUSH/POP` thx to @PeterCordes!
> 20 votes

# Answer
# C (gcc), 48 bytes

```
i;f(n){for(i=4;i--;)printf(".%hhu"+i/3,n>>i*8);}

```

Takes as input a 32-bit integer.

*Thanks to ceilingcat and gastropner for getting this answer where it is now!*

Try it online!
> 9 votes

# Answer
# Jelly, ~~10~~ 6 bytes

```
s8Ḅj“.

```

Try it online!

```
s            Slice input list
 8           into size 8 chunks
  Ḅ          Convert from binary list to integer
   j“.       Join with dots as the separator
             Implicit output

```
> 7 votes

# Answer
# PHP, 26 bytes

```
<?=long2ip(bindec($argn));

```

Try it online!

### OR taking input as a integer as an anonymous function :

# PHP, 7 bytes

```
long2ip

```

Try it online!
> 5 votes

# Answer
# PowerShell, 46 bytes

```
""+[IPAddress]"$([Convert]::ToInt64($args,2))"

```

Try it online!

First takes input `$args` binary string and `[System.Convert]`s it into `Int64`. Uses the .NET type call `[System.Net.Ipaddress]` to parse that Int64 into an IPAddress object, then coerces the `.IPAddressToString()` method by prepending `""+`.
> 4 votes

# Answer
# Python 2, 47 bytes

```
f=lambda n,k=-2:k*`n`or f(n>>8,k+1)+'.'+`n%256`

```

Try it online!

---

# Python 3, 46 bytes

```
lambda n:('.%d'*4%(*n.to_bytes(4,"big"),))[1:]

```

Try it online!

Shaving a byte from David Foerster's `to_bytes` solution using string formatting.
> 4 votes

# Answer
# APL (Dyalog Unicode), ~~20~~ 19 bytesSBCS

-1 thanks to Kritixi Lithos.

Full program. Prompts for 32-bit integer, optionally as list of bits.

```
' '⎕R'.'⍕256|83⎕DR⎕

```

Try it online!

console prompt for numeric input

`83⎕DR` interpret the bits of that data as **8**-bit integers (internal **D**ata **R**epresentation type **3**)

`256|` convert to unsigned integers (lit. 256-mod of that)

stringify (makes space-separated string)

`' '⎕R'.'`**R**eplace spaces with dots
> 3 votes

# Answer
# MathGolf, 6 bytes

```
8/å'.u

```

Try it online.

**Explanation:**

```
8/       # Split the (implicit) input-string into parts of size 8
  å      # Convert each part from a binary-string to an integer
   '.u  '# Join by "."
         # (after which the entire stack joined together is output implicitly)

```
> 3 votes

# Answer
# JavaScript (V8), ~~49~~ 44 bytes

*-5 bytes thanks to Arnauld*

```
s=>s.match(/.{8}/g).map(x=>'0b'+x|0).join`.`

```

Try it online!
> 3 votes

# Answer
# C#7+, ~~117~~ 73 bytes

```
s=>string.Join('.',(new System.Net.IPAddress(s)+"").Split('.').Reverse())

```

Accepts the bit representation of an IP address to transform it into a four-number notation, converts it to a string array, reverses the elements to account for the endianness differences of machines, then joins them together again with a dot.

Try it online!

* Reduced to 73 bytes by utilizing the string hack and chaining (c/o @Expired Data)

---

# Initial answer, 117 bytes

```
string I(long b){var x=new System.Net.IPAddress(b).ToString().Split('.');Array.Reverse(x);return string.Join(".",x);}

```

Use it like:

```
void Main()
{
    Console.WriteLine(I(0b_10001011111100010111110001111110));
}

public string I(long b)
{
    var x = new System.Net.IPAddress(b).ToString().Split('.');
    Array.Reverse(x);
    return string.Join(".", x);
}

```
> 3 votes

# Answer
# Java 9, ~~97~~ ~~94~~ ~~92~~ 81 bytes

```
s->{for(int i=0;i<32;)System.out.print((i>0?".":"")+Long.parseLong(s,i,i+=8,2));}

```

-2 bytes thanks to *@AZTECCO*.
-11 bytes thanks to @Holger by combining the `Long.parseLong(s.substring(i,i+=8),2)` into `Long.parseLong(s,i,i+=8,2)`.

Try it online.

**Explanation:**

```
s->{                   // Method with String parameter and no return-type
  for(int i=0;i<32;)   //  Loop `i` in the range [0, 32):
    System.out.print(  //   Print:
      (i>0?            //    If `i` is larger than 0 (so it's not the first iteration):
        "."            //     Print a dot
       :               //    Else:
        "")            //     Print nothing instead
      +                //    Appended with:
       Long.parseLong(s,i,i+=8,2));}
                       //     A substring of the input `s` from index `i` to `i+8`,
                       //     (and increase `i` by 8 for the next loop iteration)
                       //     Converted from binary-String to integer

```
> 2 votes

# Answer
# Japt, 7 bytes

```
ò8 mÍq.

```

Try it here
> 2 votes

# Answer
# Python 3 (125 bytes)

```
def f(x):
    y=''
    for j in range(4):
        y+=str(int(x[j*8:j*8+8],2))
        if j<4:
            y+="."
    return y

```

Try it online
> 2 votes

# Answer
# k4, ~~18~~ 17 bytes

saved a byte by expressing in composed form instead of as a lambda:

```
("."/:$2/:'4 0N#)

```

original explanation: output is string, quad-dot decimal not supported by k

```
{"."/:$2/:'4 0N#x}

{                } /lambda with implicit arg x
           4 0N#x  /cut x into 4 pieces
       2/:'        /convert each piece to decimal
      $            /stringify
 "."/:             /join with .

```

called on 2 binaries:

```
{"."/:$2/:'4 0N#x}'(10001011111100010111110001111110b;11000000101010000000000111111111b)
("139.241.124.126";"192.168.1.255")

```
> 2 votes

# Answer
## Excel. 96 bytes

```
=BIN2DEC(LEFT(A1,8))&"."&BIN2DEC(MID(A1,9,8))&"."&BIN2DEC(MID(A1,17,8))&"."&BIN2DEC(RIGHT(A1,8))

```
> 2 votes

# Answer
# Perl 5, 30 bytes

```
s/.{8}/oct("0b$&").'.'/ge;chop

```

Try it online!

Search-replaces with regexp that takes eight bits (`0` or `1`) at a time and converts them to their decimal representation with `.` placed after each, but `chop`s off the last `.` char. Using a function named `oct` here seems counter-intuitive since the input string isn't octal. But when the given string starts with `0b` the rest is read as the binary string it is.
> 1 votes

# Answer
# Red, 33 bytes

```
func[n][to 1.1.1 debase/base n 2]

```

Try it online!

Takes the input as strings.
> 1 votes

# Answer
# Python 2, ~~81~~ \\$\cdots\\$ ~~58~~ 55 bytes

```
lambda s:'.'.join(`int(s[i:i+8],2)`for i in(0,8,16,24))

```

Try it online!

Saved 3 bytes thanks to ElPedro!!!

Lambda function that takes a string of 32 `"0"`s and `"1"`s.
> 1 votes

# Answer
# Burlesque, 13 bytes

```
8co{b2}]m'.IC

```

Try it online!

```
8co    #Break into chunks 8 long
{b2}]m #Read each chunk as base-2 and turn to string
'.IC   #Intercalate "." between each and collapse

```
> 1 votes

# Answer
# Stax, 8 bytes

```
Ç∩0&→Ö¡

```

Run and debug it at staxlang.xyz!

### Unpacked (9 bytes) and explanation:

```
8/{|Bm'.*
8/           Split into length-8 chunks. 4M would work just as well.
  {|Bm       Convert each chunk to decimal
      '.*    Join with .

```
> 1 votes

# Answer
# Perl 6, ~~28~~ 27 bytes

*-1 byte thanks to Jo King*

```
{chop S:g/.**8/{:2(~$/)}./}

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~37~~ 34 bytes

```
->b{(-3..0).map{|w|255&b<<w*8}*?.}

```

Try it online!
> 1 votes

# Answer
# CJam, 10 bytes

```
l~8/2fb'.*

```

Try it online!

### Explanation

```
l~    e# Read a line and evaluate it. Pushes list to the stack
8/    e# Split into sublists of 8 elements each. Gives list of sublists
2fb   e# Map "base conversion" with extra parameter 2 over the list of sublists
'.*   e# Join sublists with character ".". Implicitly display

```
> 1 votes

# Answer
# C (clang), ~~66~~ 61 bytes

```
i;g(*m){for(i=32;i--;)*++m+=i%8?*m*2:!printf(".%d"+i/24,*m);}

```

Try it online!

Input as an array of integers (bits)

Adds current number shifted to the next. Every 8 bits it prints instead of adding.

Saved 5 thanks to @gastropner and @ceilingcat
> 1 votes

# Answer
# PowerShell, ~~45~~ 44 bytes

```
$args|%{$r+=+$r+"$_"}
[ipaddress]::Parse($r)

```

Try it online!

---

# PowerShell, 45 bytes

Pure PowerShell. It does not use external libs.

```
($args|%{($r=2*$r%256+"$_")[++$i%8]})-join'.'

```

Try it online!

Unrolled and commented:

```
$bytes = $args|%{           # $args is array on character 48 or 49 (bits)
    $r = 2 * $r             # one bit shift left
                            # the first operand is integer, so Powershell converts the second operand to an integer
    $r = $r % 256           # bitwise and 0xFF
    $digit = "$_"           # convert a char 48, 49 to string "0" or "1" respectively
    $r = $r + $digit        # add a digit
                            # the first operand is integer, so Powershell converts the second operand to an integer
    # now $r is a byte containing 8 bits to the left of the current one

    $index = ++$i % 8       # 1,2,3,4,5,6,7,0, 1,2,3,4,5,6,7,0, ...
    ($r)[$index]            # represent $r as an array; take an element of this array
                            # index 0 will give $r, other indexes will give $null
                            # Powershell outputs non $null values only
                            # Compare to `Wrtie-Output ($r)[$index]`
}
# now $bytes is array of not $null elements
Write-Output ($bytes -join '.')

```
> 1 votes

# Answer
# Python 3, 47 bytes

```
lambda n:".".join(map(str,n.to_bytes(4,"big")))

```

Try it online!
> 1 votes

# Answer
# Forth (gforth), 130 bytes.

Requires a Forth that starts in decimal mode, works with gforth.

```
: p . 8 emit ." ." ;
: d dup 255 and swap ;
: r 8 rshift d ;
: q 32 2 base ! word number drop d r r r drop decimal p p p . ;

```

Try it online!

*Usage:* q 10001011111100010111110001111110 \[enter\]

**Deobfuscated version** (or how I would really do it)

```
\ Forth program to convert a binary IP address to dotted decimal notation.

decimal
: binary   2 base ! ;

\ Get the binary string and convert to a number.
: getbin   32 binary word number drop ;

\ Shift and mask the byte we are interested in. Put all 4 on the stack.
hex
: mask   rshift dup ff and ;
: quad4   dup ff and swap ;
: quad   8 mask swap ;
: 3more   quad quad quad ;

\ Print a quad, backspace over it's trailing space, print a dot.
: .quad   . 8 emit ." ." ;

\ Print all 4 quads in decimal.
: .4quads   decimal .quad .quad .quad . ;

\ Get binary number, chop it up into 4 quads, print in decimal.
: qdot   getbin quad4 3more drop .4quads ;

```
> 1 votes

# Answer
# REXX, 91 bytes

```
PARSE ARG WITH 1 A 9 B 17 C 25 D
SAY X2D(B2X(A))'.'X2D(B2X(B))'.'X2D(B2X(C))'.'X2D(B2X(D))

```

Online REXX interpreter
> 1 votes

# Answer
# , 18 bytes

```
' .'rplc~&":_8#.\]

```

Try it online!

## Old answer

-2 thanks to Kritixi Lithos

```
' .'rplc~&":2#.4 8$]

```

Try it online!

My first answer in a non-esolang! *(kinda)*. The way this answer works is pretty simple. Let's look first at a non-tacit form of this expression:

```
(":#.(4 8 $ n))rplc' .'

```

Assuming that (for instance) n is:

```
n =: 1 0 0 0 1 0 1 1 1 1 1 1 0 0 0 1 0 1 1 1 1 1 0 0 0 1 1 1 1 1 1 0

```

The expression `4 8 $ n` is equal to:

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

```

Then, the `#.` verb is applied over the matrix, yielding the following result:

```
139 241 124 126

```

The resulting list is stringified using `":`, and using `rplc` every space in the string representation of list is swapped to a dot, yielding the final form:

```
139.241.124.126

```
> 1 votes

# Answer
# Julia, ~~58~~ 52 bytes

`x->join(parse.(Int,x[n:n+7] for n=1:8:25;base=2),:.)`

Takes the input string and uses a comprehension to create an array of the 8 bits. Then `parse`s each element (via 'broadcasting' with the `.` into an `Int`. Last step is to join with the period.

Reductions per comments below:

* 4 byte reduction by simplifying the comprehension indexing
* 1 byte reduction in changing the separator from a string to a symbol (which `join` converts into a string upon joining with the integers)
> 1 votes

# Answer
# Vyxal, 45 bitsv2, 5.625 bytes

```
8ẇvB\.j

```

Try it Online!

7 bytes -\> 5.625 bytes.

## Explained

```
8ẇvB\.j
8ẇ       # Split into chunks of length 8
  vB     # Convert each to binary. Pretty sure it should work without the v. Could be a bug
    \.j  # Join on "."s

```

Created with the help of Luminespire.
> 1 votes

# Answer
## Batch, 56 bytes

```
@for /f "tokens=2" %%f in ('ping %1')do @echo %%f&exit/b

```

Takes input as the first command-line argument. Somewhat slow, but `-n1 -w1` can be added to the `ping` command to speed it up a bit.
> 0 votes

# Answer
# GolfScript, 20 bytes

```
8/{1/{~}%2base}%'.'*

```

Try it online!

## Explanation

```
8/                   # Split into size 8 chunks
  {           }%     # For-each over the chunks
   1/                # Split into size-1 chunks
     {~}%            # Convert each from string to number
         2base       # Convert to base 10
                '.'* # Join with dots

```
> 0 votes

# Answer
# \[C (~~gcc~~ clang)\], ~~97~~ ~~85~~ 77 bytes

```
x;f(*s){x=strtoul(s,s,2);printf("%hhu.%hhu.%hhu.%hhu\n",x>>24,x>>16,x>>8,x);}

```

Try it online!

This version takes a string as input. 8 bytes shaved off thanks to JL2210!
> 0 votes

# Answer
# Alchemist, 97 bytes

```
_->3a+7b+i
i+n->i+m
i+0n->j+In_n
j+m->j+2n
j+0m+b->i
j+0m+0b->k+Out_n
k+n->k
k+0n+a->7b+i+Out_"."

```

Try it online!

`a` and `b` count down the bytes and bits remaining, respectively. `i`, `j`, and `k` are phase/step atoms. The current byte is stored in `n`, with temporary storage in `m`.
> 0 votes

# Answer
# Pyth, ~~10~~ 9 bytes

```
j\.iR2cz8

```

Try it online!

Chops input into pieces of length 8 (`cz8`), then maps int(x, 2) over the result (`iR2`). Then just joins those with a dot separator (`j\.`).

-1 by using a more specialized map (`R`) instead of the generic `m`.
> 0 votes

# Answer
# SmileBASIC, 49 bytes

```
INPUT X
RGBREAD X OUT A,B,C,D?A;".";B;".";C;".";D

```

Takes a decimal integer as input

the `RGB` and `RGBREAD` functions were designed to convert between 32 bit ARGB color values and separate 8 bit channels
> 0 votes

# Answer
# Python 3, 44 bytes

Another one using `to_bytes` trick, but this one also uses f-strings.

```
'.'.join(f"{b}"for b in n.to_bytes(4,"big"))

```
> 0 votes

# Answer
# Haskell, 52 bytes

```
s n|(y,x)<-divMod n 256=concat[s y++"."|y>0]++show x

```

Try it online!

Takes input as number. Repeatedly `divMod`s by 256 until the div is zero.
> 0 votes

# Answer
# Perl, 33 bytes

```
$_=join'.',unpack'C4',pack'B*',$_

```

Try it online!

Read in right-to-left order:

1. Encode input using `pack`
2. Extract four unsigned bytes with `unpack`
3. Intercalate `.` separators with `join`
> 0 votes

# Answer
# Ruby `-p`, 34 bytes

Replaces each 8-character subsequence with its decimal conversion plus a dot, then removes the last dot.

```
gsub(/.{8}/){"#{$&.to_i 2}."}
chop

```

Try it online!
> 0 votes

# Answer
# Fortran (GFortran), 58 bytes

```
integer i(4)                 !Declare 4 int array
read('(4B8)'),i              !Read as 4 length 8 binary numbers
print('(3(i0,"."),i0)'),i    !Print as 3 auto-length ints followed by a '.' and then the last int
end

```

Try it online!
> 0 votes

# Answer
# Lua, 82 bytes

```
print(io.read():gsub(("%d"):rep(8),function(n)return'.'..tonumber(n,2)end):sub(2))

```

Try it online!

Takes input from stdin and writes to stdout. Works on Lua 5.0+.

This works by using `string.gsub`'s ability to replace matches using a helper function. The function used here replaces a string of eight binary digits with a `.` followed by the digits in decimal. The `:sub(2)` at the end removes the extraneous `.` at the beginning of the resulting string.

Un-golfed version + extra explanation:

```
print(                                       -- print
    string.sub(                              --  substring
        string.gsub(                         --   replace
            io.read(),                       --    in string
            "%d%d%d%d%d%d%d%d",              --    replace
            function(n)                      --    with
                return                       --     result of
                    '.' ..                   --      concatenate with
                    tonumber(                --      string to number
                        n,                   --       convert this
                        2                    --       with base
                    )
            end
        ),
        2                                    --   starting at character (1-index)
    )
)

```
> 0 votes

# Answer
# Thunno 2, 6 bytes

```
8ẇḂ'.j

```

Try it online!

```
4ẆḂ'.j

```

Try it online!

#### Explanation

```
         # Implicit input
 ẇ       # Split the input into
8        # chunks of length eight
 Ẇ       # Or, split the input into
4        # four equal-sized chunks
  Ḃ      # Then, convert each from binary
   '.j  '# And join the list by "."s
         # Implicit output

```
> 0 votes

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