title: Tips for Golfing in Vyxal 3

text:
# Question
Title: Tips for Golfing in Vyxal 3
*The reason for this question is because I made a deadlineless bounty and I need a tips question to link in the bounty*

Vyxal 3 is the third major version of the Vyxal golfing language. As it is significantly different to Vyxal 2, the tips there don't apply.

Therefore, what tips and tricks do you have for golfing in Vyxal 3? Avoid giving obvious help like "remove whitespace", "limit variable usage", "remove comments" and "don't pad your program with 20000 among us characters".

One tip per answer please.

Literate mode golfing tips are also welcome.

# Answer
# Compress Strings and Numbers

Like Vyxal 2 before it, Vyxal 3 has dictionary string compression and base-based compression. However, in Vyxal 3, dictionary strings use Jelly's sss and base-based compression uses base-252 instead of base-255.

Dictionary compression works on all strings, base string compression only works on strings of lowercase alphabet + space (`[a-z ]`), base number compression only works on positive numbers.

To compress a string using dictionary compression:

```
"Some string" #C

```

To compress a string using base compression:

```
"some lowercase string" #c

```

To compress a number using base compression:

```
69420 #c

```

## Examples

| Original Value | Dictionary Compressed | Base Compressed |
| --- | --- | --- |
| `"hello world"` | `"Ṙ=?”` | `"ᶠ»_Ṃ†ᵘy„` |
| `"Hello, World!"` | `"Ḍᵗ{w<ᵏ”` | NA |
| `69420` | NA | `"ᵇᵡy“` |
> 5 votes

---
Tags: tips, vyxal
---


title: Consecutive 1-Bits are Incremented

text:
# Question
Title: Consecutive 1-Bits are Incremented
Given a pattern (string or array format) of Bits : `[0,1,1,1,0,1,1,0,0,0,1,1,1,1,1,1]`

The tasks is to replace any number of consecutive 1-Bits with an ascending number sequence starting at 1.

**Input**

* Pattern (can be received as an string or array) Example:
    + String: `1001011010110101001`
    + Array: `[1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1]`

**Output**

* Ascending number sequence (can be returned as an string or array) Example:
    + String: `1 0 0 1 0 1 2 0 1 0 1 2 0 1 0 1 0 0 1`
    + Array: `[1, 0, 0, 1, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 0, 1, 0, 0, 1]`

**Rules**

* *(only apply for strings)* Input wont contain spaces between `1` and `0`
* Assume Input `length > 0`
* *(only apply for strings)* Output is separated by space (use any other separator if you need as long as is not a number or a letter from the alphabet)

**Example:**

```
Given [0,1,1,1,0,1,1,0,0,0,1,1,1,1,1,1]
Output [0,1,2,3,0,1,2,0,0,0,1,2,3,4,5,6]

--------------------------------------------------------------------------

Given 0110101111101011011111101011111111
Output 0 1 2 0 1 0 1 2 3 4 5 0 1 0 1 2 0 1 2 3 4 5 6 0 1 0 1 2 3 4 5 6 7 8

---------------------------------------------------------------------------

Given 11111111111101
Output 1 2 3 4 5 6 7 8 9 10 11 12 0 1

```

---

Winning criteria: Codegolf

# Answer
# 05AB1E, 4 bytes

```
γ€ƶ˜

```

Try it online! or as a Test Suit

**Explanation**

```
γ      # split input into groups of consecutive equal elements
 €ƶ    # multiply each number in each sublist by its 1-based index in the sublist
   ˜   # flatten

```
> 20 votes

# Answer
# Haskell, 15 bytes

```
scanl1$(*).succ

```

Try it online!

### Explanation/Ungolfed

`scanl1` iterates from left over a list using a function which takes the last result and the current element generating a new list with the results, leaving empty lists and singletons "unmodified".

`(*).succ` is the equivalent of `\x y-> (x+1)*y`

Using that function together with `scanl1` only works because the increasing sequences (*1,2,3,..*) start with *1* and either have no preceding element (in which case it's the first element in the list which won't be "modified") or they have a leading *0*.
> 19 votes

# Answer
# Husk, ~~5 4~~ 3 bytes

```
ṁ∫g

```

Try it online!

### Explanation

```
ṁ∫g  -- full function, example input: [1,1,1,0,1]
  g  -- group: [[1,1],[0],[1]]
ṁ    -- map the following and concatenate result (example with [1,1,1])
 ∫   -- | cumulative sum: [1,2,3]
     -- : [1,2,3,0,1]

```

**Edit history**

-1 byte by using `scanl1` over `zipWith`

-1 byte by porting Dennis's solution
> 15 votes

# Answer
# Python 2, 36 bytes

```
c=0
for i in input():c=c*i+i;print c

```

Try it online!
> 15 votes

# Answer
# APL (Dyalog Unicode), 5 bytes

```
⊥⍨¨,\

```

Try it online!

### How it works

```
⊥⍨¨,\
   ,\  ⍝ Convert to lists of first n elements
⊥⍨¨    ⍝ Map "Count trailing ones" to each list

```
> 13 votes

# Answer
# JavaScript (ES6), 22 bytes

Takes input as an array.

```
a=>a.map(s=n=>s=n*-~s)

```

Try it online!

The shorter `a=>a.map(n=>a=n*-~a)` (20 bytes) would unfortunately fail on `[1]` because of coercion of singleton arrays to the integer they're holding.
> 11 votes

# Answer
# , 4 bytes

```
#.~\

```

A port of Bubbler's APL solution

Try it online!

# , 8 bytes

```
i.&0@|.\

```

## How?

It's simply the distance to the preceding `0`

```
       \  for each prefix
     |.   reverse it
    @     and
i.&0      find the index of the first 0

```

Try it online!
> 11 votes

# Answer
# Python 2, ~~39~~ 38 bytes

-1 byte thanks to Erik the Outgolfer

```
i=1
for x in input():i*=x;print i;i+=1

```

Try it online!
> 8 votes

# Answer
# Jelly, 4 bytes

```
‘×¥\

```

Try it online!

```
‘×¥\
   \   Accumulate the input with:
  ¥   The dyad
‘      Increment the left element
 ×    Multiply by the second element (1 or 0)
       The result always begins with the first element unchanged

```
> 8 votes

# Answer
# , ~~46~~ 31 bytes

```
function(a)sequence(rle(a)$l)*a

```

Try it online!

`sequence`, which "mainly exists in reverence to the very early history of R", is quite handy here.

```
function(a)                       # function, taking a vector as argument
                    rle(a)$l      # take the lengths of the run-length encoding
           sequence(        )     # and generate the list [1:x for x in lengths]
                             *a   # multiply by a to maintain 0s, and return

```
> 7 votes

# Answer
# Jelly, 4 bytes

```
ŒgÄF

```

Try it online!

### How it works

```
ŒgÄF  Main link. Argument: A (bit array)

Œg    Group adjacent, identical bits.
  Ä   Accumulate; take the cumulative sum of each chunk.
   F  Flatten.

```
> 7 votes

# Answer
# K (oK), ~~11~~ 8 bytes

**Solution:**

```
{y*1+x}\

```

Try it online!

**Explanation:**

Iterate over the list. Increment accumulator, multiply by current item (which resets accumulator if item is 0):

```
{y*1+x}\ / the solution
{     }\ / iterate (\) over lambda function
     x   / accumulator
   1+    / add 1
 y*      / multiply by current item

```
> 6 votes

# Answer
# RAD, 8 bytes

```
(⊢×1+⊣)⍂

```

Try it online!

## How?

* `(⊢×1+⊣)`, if the right argument is `0`, return `0`, otherwise increment the left argument
* , LTR Scan (`(A f B) f C` instead of `A f (B f C)`) , apply this across the array
> 5 votes

# Answer
# TIS, 68 + 33 = 101 bytes

Code (68 bytes):

```
@0
MOV UP ACC
SUB 47
MOV ACC ANY
@1
ADD 1
JRO UP
SUB ACC
MOV ACC ANY

```

Layout (33 bytes):

```
2 1 CC I0 ASCII - O0 NUMERIC - 32

```

Try it online!

Explanation:

```
|    Input 0    |    Input is given in ASCII (`0` is 48, `1` is 49)
+--------+------+
| Node 0 |      |    This node prepares the input data
+--------+      |
| MOV UP ACC    |    Read in a character
| SUB 47        |    Subtract 47 to map [48, 49] to [1, 2]
| MOV ACC ANY   |    Send the 1 or 2 to the next node
|               |    Implicitly wrap back to top of node
+--------+------+
| Node 1 |      |    This node does the incrementing/printing
+--------+      |
| ADD 1         |    Increment counter (starts at zero)
| JRO UP        |    Get value from above, and jump forward that many lines  (skip next line or not)
| SUB ACC       |    Reset counter to zero (if input was zero)
| MOV ACC ANY   |    Send the counter value downward to be printed
|               |    Implicitly wrap back to top of node
+---------------+
|   Output 0    |    Output is space-delimited numeric values

```
> 5 votes

# Answer
# C (gcc), ~~45~~ ~~44~~ 38 bytes

```
f(a,i)int*a;{while(--i)*++a*=-~a[-1];}

```

Try it online!

Save one byte thanks to Toby Speight!

Save 6 bytes by using \*= and a smarter while condition.
> 5 votes

# Answer
# Perl 6, ~~29 24~~ 18 bytes

*-6 bytes thanks to Sean!*

```
*.map:{($+=1)*=$_}

```

Try it online!

The inner function could by `($+=1)*=*`, but then the anonymous variable would persist across function calls. We get by this by wrapping it in an explicit code block.

### Explanation:

```
*.map:               # Map the array to
      {($+=1)    }   # The anonymous variable incremented
             *=$_    # Multiplied by the element

```
> 4 votes

# Answer
# Jelly, 5 bytes

```
ṛȧ+ɗ\

```

Try it online!
> 4 votes

# Answer
# Haskell, 19 bytes

```
scanl1$((*)=<<).(+)

```

Try it online!

**Explanation:** The code is equivalent to `scanl1(\b a->(b+a)*a)`, where `b` is the current bit and `a` is the accumulator. `scanl1` takes a list, instantiates the first list element as accumulator, and folds over the list and collects the intermediate values in a new list.

*Edit: BMO beat me by a few seconds and 4 bytes.*
> 4 votes

# Answer
# Japt, ~~7~~ ~~6~~ 5 bytes

```
åÏ*°X

```

Try it

---

## Explanation

```
åÏ        :Cumulatively reduce
   °X     :  Increment the current total (initially 0)
  *       :  Multiply by the current element

```
> 4 votes

# Answer
# Java 8, ~~55~~ 48 bytes

```
a->{int p=0,i=0;for(int v:a)a[i++]=v<1?p=0:++p;}

```

Modifies the input-array instead of returning a new one to save bytes.

-7 bytes thanks to *@TimSeguine*.

Try it online.

**Explanation:**

```
a->{             // Method with integer-array parameter and no return-type
  int p=0,       //  Previous integer, starting at 0
      i=0;       //  Index-integer, starting at 0
  for(int v:a)   //  Loop over the values of the input-array:
    a[i++]=v<1?  //   If the current value is 0:
          p=0    //    Reset the previous integer to 0
         :       //   Else:
          ++p;}  //    Increase `p` by 1 first with `++p`
                 //    and set the current item to this new value of `p`

```
> 4 votes

# Answer
# Gaia, 5 bytes

```
ẋ+⊣¦_

```

Try it online!

### Explanation

```
ẋ+⊣¦_     Full program
ẋ         Split into chunks of equal adjacent values.
   ¦_     And for each chunk, flattening the result afterwards...
 +⊣       Reduce it cumulatively on + (addition); aka cumulative sums

```

Ugh, I thought SE code fonts were monospace....
> 4 votes

# Answer
# Wolfram Language (Mathematica), 16 bytes

```
FoldList[+###2&]

```

Try it online!
> 4 votes

# Answer
# PowerShell, ~~48~~ ~~40~~ 25 bytes

Thanks Mazzy for -8
Thanks AdmBorkBork for -15

```
$args[0]|%{($i=$_*=++$i)}

```

Try it online!

Takes input as an array numbers. Uses the self-assigning, multiply trick other answers are using and updates everything with a very gross assignment. It then wraps this whole thing in parens to push it to output.
> 4 votes

# Answer
## Shakespeare, 365 bytes

```
I.Ajax,.Ford,.Act I:.Scene I:.[enter Ajax and Ford]Ajax:Open mind!Scene V:.Ford:Am I nicer than the sum of a big red old cute hard cat a big red old cute joy?Ford:If so,you is the sum of thyself a son!Ford:If not,you is zero!Ford:Open heart!Ajax:you is a big red old cute hard cat.Ajax:Speak mind!Ajax:Open mind!Ford:Am I nicer than zero?Ajax:If so, let us Scene V.

```

try it here

## less golfed version

```
I.Ajax,.Ford,.
Act I:.
Scene I:.
[enter Ajax and Ford]
Ajax:Open mind!
Scene V:.
Ford:Am I nicer than the sum of a big red old cute hard cat a big red old cute joy?     <- smallest way to 48 (ascii "0") I could think of
Ford:If so,you is the sum of thyself a son!
Ford:If not,you is zero!
Ford:Open heart!
Ajax:you is a big red old cute hard cat.    <- get value of 32 or space
Ajax:Speak mind!                            <- then output it
Ajax:Open mind!
Ford:Am I nicer than zero?
Ajax:If so, let us Scene V.                 <- loop through inputs

```
> 4 votes

# Answer
# C++, 47 bytes

```
[](int*a,int*b){for(int c=0;a!=b;)c=*a++*=1+c;}

```

A lambda that modifies an array in place, given start and end pointers.

---

Try it online! (requires Javascript)

---

Generic version at 55 bytes (this works for any container with elements of arithmetic type):

```
[](auto a,auto b){for(auto c=*a-*a;a!=b;)c=*a++*=1+c;};

```
> 4 votes

# Answer
# Brachylog, ~~12~~ 10 bytes

```
ḅ{a₀ᵇ+ᵐ}ᵐc

```

Try it online!

*(-2 bytes thanks to @Fatalize.)*

```
ḅ             % split input into "blocks" of equal value
 {     }ᵐ     % map this predicate on each such block:
  a₀ᵇ            % Find all prefixes (initial subsequences) of the block
                 %  Returns them in increasing order of length
     +ᵐ          % Sum the values in each subsequence
                 % This results in each block being replaced by its cumulative sum values
         c    % concatenate the results back into a single array

```

`~c{≤₁a₀ᵇ+ᵐ}ᵐc` is temptingly just out of reach at 13 bytes, but I haven't been able to find a shorter way of doing cumulative sum than the 5 byte `a₀ᵇ+ᵐ`.
> 4 votes

# Answer
# Pyth, 6 bytes

```
m=Z*hZ

```

Try it here!

### How it works

```
m=Z*hZ – Full program. Q = the evaluated input.
m      – For each integer d in Q.
 =Z    – Assign the variable Z (preinitialised to 0) to...
   *hZ – (Z + 1) * d; (d is implicit at the end).

```
> 3 votes

# Answer
Wanted to get an answer in using regular expressions. There is probably an easier solution which I leave as an exercise for the reader.

# PowerShell Core, 86 bytes

```
Filter F{($_-split"(0)(\B|\b)"|?{$_-ne''}|%{$_-replace'(1+)',(1..$_.Length)})-join' '}

```

Try it online!
> 3 votes

# Answer
# C (gcc), ~~57~~ ~~52~~ 51 bytes

```
f(a,l,c,i)int*a;{for(c=i=0;i<l;)a[i++]=c=a[i]*-~c;}

```

Port of Arnauld's JavaScript answer, modifies the array in-place. Try it online here.
> 3 votes

# Answer
# QBasic, 60 bytes

```
INPUT s$
FOR i=1TO LEN(s$)
b=MID$(s$,i)>="1
v=-b*v-b
?v
NEXT

```

Takes the input as a string; gives the output as numbers separated by newlines.

### Explanation

We read the string `s$` and loop `i` from `1` up to its length.

`MID$(s$,i)` gets the substring from character `i` (1-indexed) to the end of the string. If this starts with a `1`, it will be lexicographically `>=` the string `"1"`; if it starts with a `0`, it will not be. So `b` gets `0` if the character at index `i` is `0`, or `-1` if the character is `1`.

Next, we update the current value `v`. If we just read a `0`, we want `v` to become `0`; otherwise, we want to increment `v` by one. In other words, `v = (-b) * (v+1)`; simplifying the math gives the shorter expression seen in the code. Finally, we print `v` and loop.
> 3 votes

# Answer
# Brain-Flak, 60 bytes

```
([]){{}<>(())<>{{}<>({}({}))(<>)}{}([])}{}<>{({}[()]<>)<>}<>

```

Try it online!

# Explanation:

```
([]){  For each element in the input
    {}
    <>(())<>  Push a one to the other stack
    { If the element is one,
       {}<>({}({}))(<>)  Add the one to a copy of the previous number in the series
    }{}  Pop the element
([])}  End loop
{}<>   Pop extra zero
{({}[()]<>)<>}<>   And reverse the output stack, subtracting one from each element

```
> 3 votes

# Answer
## Retina, 14 bytes

```
rv`0|(1)+
$#1¶

```

Try it online!
> 3 votes

# Answer
## Java, 65 bytes

`void a(int[]q){for(int i=1;i<q.length;i++)q[i]+=q[i]>0?q[i-1]:0;}`
> 3 votes

# Answer
# MATL, ~~11~~ 10 bytes

```
0w"@+@*t]x

```

Try it online!

*(-1 byte thanks to Giuseppe)*

The obvious "accumulate y(x+y) over the array" approach.

### 16 bytes

```
n:G~f!-tO<YYw(X<

```

Try it online!

Longer, more matrix-y approach: get the overall index, broadcast-subtract the indices of all zeros, and take the difference from the index of the nearest zero.
> 3 votes

# Answer
# Vyxal, 4 bytes

```
Ġv¦f

```

Try it Online!

-6 thanks to Lyxal.

```
Ġ    # Group consecutive identical elements
 v¦  # Take the cumulative sum of each
   f # Flatten the result

```
> 3 votes

# Answer
## Zig, 65 bytes

```
fn f(b:[]u8)[]u8{for(b)|_,i|{if(i>0)b[i]+=b[i-1]*b[i];}return b;}

```

Expanded version

```
fn f(b:[]u8) []u8 {
    // Foreach loop where only index is used.
    for(b) |_,i| {
        // First value is always going to be 0 or 1,
        if(i > 0)
            // b[1] will either be 0 or 1,
            // so this is basically an if statement
            // that we can use to reset the count.
            b[i] += b[i-1] * b[i];
    }
    return b;
 }

```

I would add a *Try it online!*, but their compiler seems to lack some crucial language features. (Language still being in development and all that) And I am not going to attempt to make it compatible through trial and error.

But you can copy paste this into Zig playground (Confirmed to work as of writing this post)

```
const std = @import("std");

fn f(b:[]u8)[]u8{for(b)|_,i|{if(i>0)b[i]+=b[i-1]*b[i];}return b;}

pub fn main() anyerror!void {
    var bits = [_]u8{0,1,1,1,0,1,1,0,0,0,1,1,1,1,1,1};
    var array = f(bits[0..]);

    try std.io.getStdOut().writer().print("{any}\n", .{array});
}

```
> 3 votes

# Answer
# Thunno, \\$ 6 \log\_{256}(96) \approx \\$ 4.94 bytes

```
zy.z(S

```

Attempt This Online!

#### Explanation

```
zy      # Group by consecutive
  .     # Apply to each:
   z(   #  Cumulative sums
     S  # Flatten

```
> 3 votes

# Answer
# K (ngn/k), ~~11~~ 9 bytes

```
(*/+\|,)\

```

Try it online!

-2 bytes thanks to ovs
> 3 votes

# Answer
# Jelly, 6 bytes

```
ŒgJ€F×

```

Try it online!
> 2 votes

# Answer
# Retina 0.8.2, 15 bytes

```
.(?<=(1*))
$.1

```

Try it online! Link includes test cases. Alternative version, also 15 bytes:

```
.(?<=(1)*)
$#1

```

Try it online! Link includes test cases Explanation:

```
.

```

Match the 0s and 1s.

```
(?<=(1*))
(?<=(1)*)

```

Count the number of 1s from the current digit backwards. The first one counts by capturing the run of 1s as a subtring, while the second one counts the number of times the 1 was captured.

```
$.1
$#1

```

Replace the digit with the number of 1s, either via the length of the capture or by the number of captures as appropriate.
> 2 votes

# Answer
# Pyth, 9 bytes

```
t.u*YhNQZ

```

Verify all the test cases

```
t.u*YhNQZ   Implicit: Q=eval(input())

 .u    QZ   Cumulative reduce over Q, starting value 0
     hN       Increment the current value
   *Y         Multiply by the next value
t           Remove 1st element of list, implicit print

```
> 2 votes

# Answer
# racket, 107 bytes

```
(λ(i)(let c((x i)(z 0))(if(empty? x)'()(if(= (car x)1)(cons(+ 1 z)(c(cdr x)(+ 1 z)))(cons 0(c(cdr x)0))))))

```
> 2 votes

# Answer
# Brain-Flak, 78 bytes

```
(<>)<>([]){{}{{}<>(({})())<>}([]){{}(<>)<>}{}([])}{}<>([]){{}({}<>)<>([])}<>{}

```

Try it online!

Readable version:

```
(<>)<>
([])

{

    {}

    {
        {}<>(({})())<>
    }

    ([])
    {

        {}(<>)<>
    }

    {}

    ([])

}{}<>

([])

{
    {}({}<>)<>([])
}<>{}

```
> 2 votes

# Answer
# C (gcc), 52 51 bytes

Thanks to ceilingcat for the suggestion.

```
c;f(char*i){for(;*i;printf("%d ",c=~c*(48-*i++)));}

```

Try it online!
> 2 votes

# Answer
# Julia 0.6, 28 bytes

```
t->(x=0;[(x=(x+y)y)for y=t])

```

Try it online!
> 2 votes

# Answer
# C++, ~~46~~ ~~45~~ 41 bytes

Generic lambda, any int container.

```
[](auto&a){int p=0;for(int&i:a)p=i*=p+i;}

```

Saved a byte with the `*=` operator, saved 4 bytes by removing unneeded braces and parenthesis.

Note: The `p+i` part can be replaced with `p+1` or `++p`, I'm not sure why I did `p+i` but it wouldn't save any bytes to change it.

Old:

```
[](auto&a){int p=0;for(int&i:a){p=i=i*(p+i);}}

```
> 2 votes

# Answer
# Arturo, 22 bytes

```
$=>[0map&=>[<=&*<=1+]]

```

Try it

```
$=>[        ; a function, assign input to &
    0       ; push 0
    map&=>[ ; map over input, assign current elt to &
        1+  ; increment tos
        <=  ; dup
        &*  ; multiply by current elt
        <=  ; dup
    ]       ; end map
]           ; end function

```
> 2 votes

# Answer
# TI-Basic, 25 bytes

```
Prompt B
For(I,1,dim(⁻B
⁻B(I)(Ans+1
Disp Ans
End

```

Input is taken as a list. Output is as numbers separated by newlines.
> 2 votes

# Answer
# Nibbles, 2.5 bytes (5 nibbles)

```
=\$+*

```

```
=\$+*       # full function
=\$+*$@$    # (with implicit arguments shown):
=\          # scan from left over
  $         # input
            # with function:
   +        #   add
       $    #   each element
            #   to
    *       #   product of
     $      #   each element
            #   and
      @     #   result so far

```
> 2 votes

# Answer
# BQN, 6 bytes

```
(×+⊢)`

```

Try it at BQN online!

### Explanation

Port of Dominic van Essen's Nibbles answer.

```
(×+⊢)`
(    )`  Left scan on this function:
  +       Add
   ⊢      each element to
 ×        the product of the element and the previous intermediate value

```
> 2 votes

# Answer
# KamilaLisp v0.2, 14 (APL SBCS)

```
$(⍀.←[+ * #1])

```

Equivalent to `$(scanl1[+ * #1])`.
> 2 votes

# Answer
# Thunno 2 `S`, 4 bytes

```
ġıż×

```

Attempt This Online!

#### Explanation

```
ġıż×  # Implicit input
ġ     # Group consecutive items
 ı    # Map over this list of lists:
  ż   #  Push [1..length] without popping
   ×  #  Multiply the two lists elementwise
      # Implicit output, summed (flattened)

```
> 2 votes

# Answer
# Python 2, ~~52~~ 46 bytes

```
f=lambda x,y=1:x and[y*x[0]]+f(x[1:],y*x[0]+1)

```

Saved 6 bytes thanks to Jo King and Rod!
> 1 votes

# Answer
# Perl 5 `-p`, ~~22~~ 20 bytes

*-2 bytes thanks to @DomHastings*

```
s/./$i=$&*++$i.$"/ge

```

Try it online!

**Method:**

Replace each character with itself multiplied by the incremented value of `$i`, then store that value back in `$i`. Thus, `$i` starts at 0 (`undef`) and gets reset to 0 every time the character in the bit string is a 0.

Finally, append a space to the result of the above step to make the output format correct.
> 1 votes

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

---

**Golfed** Try it online!

```
a=>{for(int i=1;i<a.Length;i++)if(a[i-1]>0&a[i]>0)a[i]=a[i-1]+1;return a;};

```

---

**Ungolfed**

```
a => {
    for( int i = 1; i < a.Length; i++ )
        if( a[ i - 1 ] > 0 & a[ i ] > 0 )
            a[ i ] = a[ i - 1 ] + 1;

    return a;
};

```

---

**Full code**

```
using System;

namespace Namespace {
    class Program {
        static void Main( String[] args ) {
            Func<Int32[], Int32[]> f = a => {
                for( int i = 1; i < a.Length; i++ )
                    if( a[ i - 1 ] > 0 & a[ i ] > 0 )
                        a[ i ] = a[ i - 1 ] + 1;

                return a;
            };

            List<Int32[]>
                testCases = new List<Int32[]>() {
                    new Int32[] { 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1 },
                    new Int32[] { 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1 },
                    new Int32[] { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1 },
                };

            foreach( Int32[] testCase in testCases ) {
                Console.WriteLine( $"{{ {String.Join(", ", testCase)} }}\n{f( testCase )}" );
            }

            Console.ReadLine();
        }
    }
}

```

---

**Releases**

* **v1.0** \- `75 bytes` \- Initial solution.

---

**Notes**

* None
> 1 votes

# Answer
# Dodos, 152 bytes

```
	_ b _ F >
b
	dab
t
	dot
(
	t b
	t
X
	X dip
<
	b X (
/
	<
	< b
0
	t 0 b
>

	0
.
	dip <
	< b
	t b
x
	x .
H
	b b x >
	b
G
	t H /
	b b
F
	<
	F G
_
	_ b
	<

```

Try it online!
> 1 votes

# Answer
# Python 2.7, 217 Bytes

```
def f(d):
    c = 0
    r = []
    for e in d:
        if e == 1:
            r.append(1 + c)
            c += 1
        else:
            c = 0
            r.append(0)
    return r

```

I'm new so.
> 1 votes

# Answer
# Kotlin, 73 bytes

```
var i=0
readLine()?.forEach{(it-48).toInt().let{c->i=i*c+c;print("$i ")}}

```

Try it online!
> 1 votes

# Answer
# Lua, ~~63~~ 54 bytes

```
function f(j)for i=2,#j do j[i]=j[i]*(j[i-1]+1)end end
```

Written by Jo King. Try it online!

---

### Explanation

```
function f(j) -- declares the function 'f' that will receive a variable 'j' (we know it's a table)
  for i=2,#j do -- from 2 to the number of elements in j
    j[i]=j[i]*(j[i-1]+1) -- change the current element of j to itself
              (j[i-1]+1) -- multiplied by the one before it plus one
  end
end

```

Original (invalid) in expanded form:

```
for i=2,#input do -- a loop that goes from 2 to the number of elements in the input table
  if input[i] == 0 then -- if the element at 'i' is 0
    input[i] = 0 -- then keep it as 0
  else
    input[i] = input[i-1]+1 -- change it to the element that comes before + 1
  end
end

```

Feel free to ask or suggest anything!
> 1 votes

# Answer
# C++ (gcc), 37 bytes

```
[](auto&a){for(int&i:a)i*=*(&i-1)+1;}

```

Try it online!

---

A lambda function which works with any int container supporting range-based for loops.
> 1 votes

# Answer
# Z80Golf, 12 bytes

```
00000000: cd03 8030 0176 b928 0180 47d5            ...0.v.(..G.

```

Try it online! or Run test cases.

I/O format is byte values.

### Disassembly

```
start:
  call $8003    ; cd 03 80 ; a = getchar()
  jr nc, skip   ; 30 01    ; if not EOF, skip
  halt          ; 76       ; terminate program
skip:
  cp c          ; b9       ; compare a and 0
  jr z, skip2   ; 28 01    ; if a == 0, skip
  add b         ; 80       ; a += b
skip2:
  ld b, a       ; 47       ; b = a
  push de       ; d5       ; call putchar with return address 0

```

The final `push de` pushes the address 0 to the stack, so when `putchar` returns, PC goes back to the start of the program.
> 1 votes

# Answer
# C# (.NET Core), 74 70 bytes

```
a=>{int i=0;var s="";foreach(var c in a)s+=(i=c/49*-~i)+" ";return s;}

```

Try it online!

*-4 bytes: changed format of* `foreach` *loop (thanks to recursive)*

Ungolfed:

```
a => {
    int i = 0;              // initialize i to 0
    var s = "";             // initialize s
    foreach(var c in a)     // for each character in a
        s +=                    // append to s:
            ( i =                   // i, where i is:
                c / 49                  // ascii representation of c divided by 49 (identifies 0 or 1)
                    * -~i )             // multiplied by the negative bitwise complement of i (essentially, one more than current i)
            + " ";                      // a space
    return s;               // output s to console
}

```
> 1 votes

# Answer
# Clojure, 62 bytes

```
#(map-indexed(fn[i n](*(+(.indexOf(reverse(take i %))0)1)n))%)

```

Use as follows:

```
(println #(...) [0 1 1 1 0 1])

```

where `#(...)` is the answer (anonymous function).
> 1 votes

# Answer
# Forth (gforth), 48 bytes

```
: f 0 tuck do 1+ over i + c@ '0 - * dup . loop ;

```

Try it online!

### Code Explanation

```
: f                \ start a new word definition
  0 tuck           \ set up a loop and also stick a 0 on the stack to use as a counter
  do               \ loop from 0 to string-length - 1
    1+             \ add 1 to counter
    over i +       \ get the address of the next character
    c@             \ get the ascii value for that character
    '0 -           \ subtract ascii 0 (48) from the value
    *              \ multiply counter by the result (change counter to 0 if char is '0')
    dup .          \ print the current sequence
  loop             \ end the loop
;                  \ end word definition

```
> 1 votes

# Answer
# Google Sheets, 37 bytes

```
=SCAN(,array,LAMBDA(a,c,--IF(c,a+1)))

```
> 1 votes

# Answer
# Nekomata, 4 bytes

```
ĉᵐ∫j

```

Attempt This Online!

A port of @Dennis's Jelly answer.

```
ĉᵐ∫j
ĉ       Split into runs of equal elements
 ᵐ      Map over each run:
  ∫         Cumsum
   j    Join

```
> 1 votes

# Answer
# PHP, 41 bytes

```
while(~$c=$argv[++$i])echo$k=++$k*$c," ";

```

takes input from command line arguments; prints string.

Run with `-r`.
> 0 votes

# Answer
# Scheme, ~~91~~ 61 bytes

```
(lambda(l)(define x 0)(map(lambda(n)(set! x(* n(+ 1 x)))x)l))

```

Try it online!
> 0 votes

# Answer
# Uiua, 6 bytes

```
\(×+1)

```

Try it!

```
\(×+1)
\(   )  # scan by
   +1   # increment
  ×     # multiply

```
> 0 votes

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


title: Electron Configuration

text:
# Question
Title: Electron Configuration
> In atomic physics and quantum chemistry, the **electron configuration** is the distribution of electrons of an atom in atomic orbitals. For example, the electron configuration of the neon atom is *1s2 2s2 2p6* (From Wikipedia)

## Challenge

Your challenge is to take a number representing the atomic number of an element and output the electron configuration of that element as defined by the Aufbau principle.

Iron (26) has the electron configuration `1s<sup>2</sup> 2s<sup>2</sup> 2p<sup>6</sup> 3s<sup>2</sup> 3p<sup>6</sup> 3d<sup>6</sup> 4s<sup>2</sup>`. However, superscripts are unnecessary; the output for Iron (26) should be along the lines of `1s2 2s2 2p6 3s2 3p6 3d6 4s2`.

## Specification

* You do not have to handle any inputs outside of the range `1 <= n <= 118`.
* Your output should look something like the test cases, but you may use any non-digit character/characters (aside from `s`, `p`, `d`, and `f`) to delimit the different orbitals.
* You must return/print a string containing the orbital names/values/delimiters; you cannot simply return/print an array.
* You do not need to handle any exceptions to the Aufbau principle; where there are exceptions, printing the "incorrect" configuration is fine.

Examples:

```
Input -> Valid output            -> Invalid output
16    -> 1s2 2s2 2p6 3s2 3p4     -> 1s22s22p63s23p4
16    -> 1s2, 2s2, 2p6, 3s2, 3p4 -> [[1, 2], [2, 2], [2, 6], [3, 2], [3, 4]]
17    -> 1s2+2s2+2p6+3s2+3p5     -> 1s2s2s2s2p6p3s2s3p5

```

Here is a list of all the electronic orbitals. The maximum values they can contain are below the name:

```
name: 1s 2s 2p 3s 3p 3d 4s 4p 4d 5s 5p 4f 5d 6s 6p 5f 6d 7s 7p
max:  2  2  6  2  6  10 2  6  10 2  6  14 10 2  6  14 10 2  6

```

## Test Cases

```
Input -> Output
1     -> 1s1
2     -> 1s2
16    -> 1s2 2s2 2p6 3s2 3p4
50    -> 1s2 2s2 2p6 3s2 3p6 3d10 4s2 4p6 4d10 5s2 5p2
115   -> 1s2 2s2 2p6 3s2 3p6 3d10 4s2 4p6 4d10 5s2 5p6 4f14 5d10 6s2 6p6 5f14 6d10 7s2 7p3

```

Here is a complete list and a reference implementation of sorts (Try it online!)

This is , the shortest code wins!

# Answer
# Jelly, ~~63 62 56~~ 55 bytes

```
ḊFµi@€QḤ’Ḥ
“ŒµḊuÆẓƙỊ’D,“çƥ÷£ḟ’ṃ“spdf”¤µxÇZ
¢ḣŒg'µQ€żL€K

```

Try it online!

Thanks to user202729 for saving 6 bytes with base decompression!

**Explanation**

First I construct the list `[[1,2,2,3,3,3,4,4,4,5,5,4,5,6,6,5,6,7,7],'sspspdspdspfdspfdsp']` with the code `“ŒµḊuÆẓƙỊ’D,“çƥ÷£ḟ’ṃ“spdf”¤` in the second link.

* `“ŒµḊuÆẓƙỊ’` is the number `1223334445545665677` compressed into base 250. `D` gives turns this into a list of digits.
* `“çƥ÷£ḟ’ṃ“spdf”` changes the base 250 number `“çƥ÷£ḟ’` into base 4 and indexes it into the string `“spdf”` yielding `'sspspdspdspfdspfdsp'`. This was contributed by user202729.

The list is then take to the fist link by `Ç`. The first link does the following:

```
ḊFµQiÐ€µḤ’Ḥ
ḊF           Dequeue then flatten yields 'sspspd...'. Ṫ doesn't work because it modifies the input.
  µ          New monadic link
   Q         Unique elements → 'spdf'
    iÐ€      The index of each of 'sspspd...' into the string 'spdf' → [1,1,2,1,2,3...]
       µ     New monadic link. This prevents Ḥ from acting on the right argument of iÐ€.
        Ḥ’Ḥ  Takes [1,1,2,1...] and computes 2(2l+1) → [2,2,6,2,6,10...]

```

Now back to the second link. With  we repeat each of the elements in each sublist of `[[1,2,2,3...7],['sspspd...p']]` by the numbers in our new list `[2,2,6...]`. This yields `[[1,1,2,2,2,2...],['sssspp...']]`. `Z` zips the two sublist which yields `[[1,'s'],[1,'s'],[2,'s']...]`.

Now to the main link. `¢` calls the second link which yields the final list of tuples described above. Assume the input to the program is 5 as an example.

```
¢ḣŒg'µQ€żL€K
¢             Calls the second link as a nilad which yields the final list of tuples described above
 ḣ            Takes the first 5 tuples → [[1,'s'],[1,'s'],[2,'s'],[2,'s'],[2,'p']]
  Œg'         Group together runs of equal elements → [[[1,'s'],[1,'s']],[[2,'s'],[2,'s']],[[2,'p']]]
     µ        New monadic link
      Q€      Unique elements of each of these runs
         L€   Length of each of these runs
        ż     Zip these together → [[[1,'s'],2],[[2,'s'],2],[[2,'p'],1]]
           K  Join this list with spaces → 1s2 2s2 2p1

```
> 2 votes

# Answer
# Python 2, ~~129~~ 128 bytes

-1 byte thanks to notjagan

```
n=input()
d='spdf'.find
s='sspspdspdspfdspfdsp'
i=0
while n>0:c=s[i];t=d(c)*4+2;print`s[:i].count(c)-~d(c)`+c,min(t,n);n-=t;i+=1

```

Try it online!
> 7 votes

# Answer
# Imperative Tampio, 930 bytes

```
Yöllä on ilot.Olkoon oma ilo uusi yö, jonka iloja ovat ilo"1s",ilo"2s",ilo"2p",ilo"3s",ilo"3p",ilo"3d",ilo"4s",ilo"4p",ilo"4d",ilo"5s",ilo"5p",ilo"4f",ilo"5d",ilo"6s",ilo"6p",ilo"5f",ilo"6d",ilo"7s"ja ilo"7p".Olkoon iso yö uusi yö, jonka iloja ovat 2,2,6,2,6,10,2,6,10,2,6,14,10,2,6,14,10,2 ja 6.Kun iso luku juo ison ilon,iso ilo näyttää oman yön,missä oma yö on oman ilon ensimmäinen ilo ja ujo ilo on ison yön ensimmäinen ilo,jos iso luku on suurempi kuin ujo ilo,niin iso ilo näyttää ujon ilon,iso ilo näyttää ilon" ",oman ilon iloiksi asetetaan oman ilon ilot toisesta alkaen,ison yön iloiksi asetetaan ison yön ilot toisesta alkaen ja iso luku vähennettynä ujolla ilolla juo ison ilon ja,jos iso luku on pienempi tai yhtä suuri kuin ujo ilo,niin iso ilo näyttää ison luvun.Olkoon oma muuttuja uusi muuttuja.Kun iso sivu avautuu,omaan muuttujaan luetaan luku ja oman muuttujan arvo juo ison sivun.

```

> Yöllä **on** ilot.**Olkoon** oma ilo **uusi** yö, **jonka** iloja **ovat** **ilo**`"1s"`,**ilo**`"2s"`,**ilo**`"2p"`,**ilo**`"3s"`,**ilo**`"3p"`,**ilo**`"3d"`,**ilo**`"4s"`,**ilo**`"4p"`,**ilo**`"4d"`,**ilo**`"5s"`,**ilo**`"5p"`,**ilo**`"4f"`,**ilo**`"5d"`,**ilo**`"6s"`,**ilo**`"6p"`,**ilo**`"5f"`,**ilo**`"6d"`,**ilo**`"7s"`**ja** **ilo**`"7p"`.**Olkoon** iso yö **uusi** yö, **jonka** iloja **ovat** `2`,`2`,`6`,`2`,`6`,`10`,`2`,`6`,`10`,`2`,`6`,`14`,`10`,`2`,`6`,`14`,`10`,`2` **ja** `6`.**Kun** iso luku *juo* ison ilon,iso ilo *näyttää* oman yön,**missä** oma yö **on** oman ilon `ensimmäinen` ilo **ja** ujo ilo **on** ison yön `ensimmäinen` ilo,**jos** iso luku **on** **suurempi** **kuin** ujo ilo,**niin** iso ilo *näyttää* ujon ilon,iso ilo *näyttää* **ilon**`" "`,oman ilon iloiksi *asetetaan* oman ilon ilot `toisesta` **alkaen**,ison yön iloiksi *asetetaan* ison yön ilot `toisesta` **alkaen** **ja** iso luku **vähennettynä** ujolla ilolla *juo* ison ilon **ja**,**jos** iso luku **on** **pienempi** **tai** **yhtä** **suuri** **kuin** ujo ilo,**niin** iso ilo *näyttää* ison luvun.**Olkoon** oma muuttuja **uusi** muuttuja.**Kun** iso sivu *avautuu*,omaan muuttujaan *luetaan* *luku* **ja** oman muuttujan arvo *juo* ison sivun.

Online version

It is a very straightforward implementation. In the golfed version I simply replaced the words with short words like `ilo`, , `iso`, `oma`, etc.

Ungolfed:

> Listalla **on** alkiot.
>
> **Olkoon** lyhyt orbitaalilista **uusi** lista, **jonka** alkioita **ovat** **orbitaali** `"1s"`, **orbitaali** `"2s"`, **orbitaali** `"2p"`, **orbitaali** `"3s"`, **orbitaali** `"3p"`, **orbitaali** `"3d"`, **orbitaali** `"4s"`, **orbitaali** `"4p"`, **orbitaali** `"4d"`, **orbitaali** `"5s"`, **orbitaali** `"5p"`, **orbitaali** `"4f"`, **orbitaali** `"5d"`, **orbitaali** `"6s"`, **orbitaali** `"6p"`, **orbitaali** `"5f"`, **orbitaali** `"6d"`, **orbitaali** `"7s"` **ja** **orbitaali** `"7p"`.
>
> **Olkoon** lyhyt maksimilista **uusi** lista, **jonka** alkioita **ovat** `2`, `2`, `6`, `2`, `6`, `10`, `2`, `6`, `10`, `2`, `6`, `14`, `10`, `2`, `6`, `14`, `10`, `2` **ja** `6`.
>
> **Kun** *jaetaan* *orbitaaleille* pienehkö elektronimäärä nykyisellä sivulla,
>
> * nykyinen sivu *näyttää* nykyisen orbitaalin, **missä** nykyinen orbitaali **on** lyhyen orbitaalilistan `ensimmäinen` alkio **ja** nykyinen maksimi **on** lyhyen maksimilistan `ensimmäinen` alkio,
> * **jos** pienehkö elektronimäärä **on** **suurempi** **kuin** nykyinen maksimi, **niin**
>
> + nykyinen sivu *näyttää* nykyisen maksimin,
>     + nykyinen sivu *näyttää* **välin** `" "`,
>     + lyhyen orbitaalilistan alkioiksi *asetetaan* lyhyen orbitaalilistan alkiot `toisesta` **alkaen**,
>     + lyhyen maksimilistan alkioiksi *asetetaan* lyhyen maksimilistan alkiot `toisesta` **alkaen**
>     + **ja** *jaetaan* *orbitaaleille* pienehkö elektronimäärä **vähennettynä** nykyisellä maksimilla nykyisellä sivulla,
> * **ja**, **jos** pienehkö elektronimäärä **on** **pienempi** **tai** **yhtä** **suuri** **kuin** nykyinen maksimi,
>     + **niin** nykyinen sivu *näyttää* pienehkön elektronimäärän.
>
> **Olkoon** mukava muuttuja **uusi** muuttuja.
>
> **Kun** nykyinen sivu *avautuu*,
>
> * mukavaan muuttujaan *luetaan* *luku*
> * **ja** *jaetaan* *orbitaaleille* mukavan muuttujan arvo nykyisellä sivulla.

Online version

Translation:

> A list **has** items.
>
> **Let** the short orbital list **be** a new list, its items **are** the orbital `"1s"`, the orbital `"2s"`, the orbital `"2p"`, the orbital `"3s"`, the orbital `"3p"`, the orbital `"3d"`, the orbital `"4s"`, the orbital `"4p"`, the orbital `"4d"`, the orbital `"5s"`, the orbital `"5p"`, the orbital `"4f"`, the orbital `"5d"`, the orbital `"6s"`, the orbital `"6p"`, the orbital `"5f"`, the orbital `"6d"`, the orbital `"7s"` **and** the orbital `"7p"`.
>
> **Let** the short maximum list **be** a new list, its items **are** 2, 2, 6, 2, 6, 10, 2, 6, 10, 2, 6, 14, 10, 2, 6, 14, 10, 2 and 6.
>
> **When** a small number of electrons *is divided to the orbitals* at the current page,
>
> * the current page *shows* the current orbital, **where** the current orbital **is** the first item in the short orbital list **and** the current maximum **is** the first element in the short maximum list,
> * **if** the small number of electrons **is greater than** the current maximum,
>     + the current page *shows* the current maximum,
>     + the current page *shows* the space `" "`,
>     + the elements of the short orbital list *are set to be* the elements of the short orbital list **beginning from** the second,
>     + the elements of the short maximum list *are set to be* the elements of the short maximum list **beginning from** the second
>     + **and** the small number of electrons **subtracted by** one *is divided to the orbitals* at the current page,
> * **and**, **if** the small number of electrons **is less than or equal to** the current maximum,
>     + the current page *shows* the small number or electrons.
>
> **Let** the nice variable **be** a new variable.
>
> **When** the current page *opens*,
>
> * *a number is read to* the nice variable
> * **and** the value of the nice variable *is divided to the orbitals* at the current page.

The translation is approximate, I had to change the word order to make the English more natural.
> 7 votes

# Answer
# Charcoal, 72 bytes

```
Ｎθ≔”{⊞″I⌀⁼C$Pπ3”α≔⁰ιＷ›θ⁰«§”o⧴∨c▷⎇_'l|”ι§αι≔⁺×⁴⌕spdf§αι²εＩ⌊⟦εθ⟧→≔⊕ιι≔⁻θεθ

```

Try it online!

Here you have the verbose version.
> 5 votes

# Answer
# JavaScript (ES6), 102 bytes

```
n=>'0010120120132013201'.replace(/./g,k=>n?++p[m=k*4+2,n-=e=m>n?n:m,k]+'spdf'[k]+e+' ':'',p=[0,1,2,3])

```

### Test cases

```
let f =

n=>'0010120120132013201'.replace(/./g,k=>n?++p[m=k*4+2,n-=e=m>n?n:m,k]+'spdf'[k]+e+' ':'',p=[0,1,2,3])

console.log(f(  1)) // -> 1s1
console.log(f(  2)) // -> 1s2
console.log(f( 16)) // -> 1s2 2s2 2p6 3s2 3p4
console.log(f( 50)) // -> 1s2 2s2 2p6 3s2 3p6 3d10 4s2 4p6 4d10 5s2 5p2
console.log(f(115)) // -> 1s2 2s2 2p6 3s2 3p6 3d10 4s2 4p6 4d10 5s2 5p6 4f14 5d10 6s2 6p6 5f14 6d10 7s2 7p3
```

### Formatted and commented

```
n =>                          // given the atomic number n
  '0010120120132013201'       // list of azimuthal quantum numbers
  .replace(/./g, k =>         // replace each character k in the above string with:
    n ?                       //   if n does not equal 0:
      ++p[                    //     ++p[k] = updated principal quantum number
        m = k * 4 + 2,        //       m = maximum number of electrons
        n -=                  //       subtract from n:
          e = m > n ? n : m,  //         e = min(m, n) = number of electrons
        k                     //       index actually used to access the p[] array
      ] +                     //     followed by:
      'spdf'[k] +             //     the label
      e + ' '                 //     and the number of electrons
    :                         //   else:
      '',                     //     an empty string
    p = [0, 1, 2, 3]          //   initial list of principal quantum numbers
  )                           // end of replace()

```
> 4 votes

# Answer
# Swift, ~~177~~ ~~175~~ 156 bytes

Loosly based on @Arnauld's Javascript answer

```
func f(n:Int){var i=n,a=0,b=[0,1,2,3];[0,0,1,0,1,2,0,1,2,0,1,3,2,0,1,3,2,0,1].map{a=$0*4+2;b[$0]+=1;i>0 ?print(b[$0],"spdf".map{$0}[$0],min(a,i)):();i-=a}}

```

Try it online!

## Without the spaces in the electron groups, ~~190~~ ~~187~~ 169 bytes:

```
func f(n:Int){var i=n,a=0,b=[0,1,2,3];[0,0,1,0,1,2,0,1,2,0,1,3,2,0,1,3,2,0,1].map{a=$0*4+2;b[$0]+=1;i>0 ?print(b[$0],"spdf".map{$0}[$0],min(a,i),separator:""):();i-=a}}

```

Try it online!
> 2 votes

# Answer
# Wolfram Language (Mathematica), ~~43~~ 42 bytes

```
#~ElementData~"FullElectronConfiguration"&

```

-1 byte thanks to ovs.

This does not work with Try it online!, so I've provided a screenshot instead. Note that this correctly shows the exceptions, such as `4s1 3d5` for chromium (Z=24), which occurs because half-filled and fully-filled orbitals are energetically favorable (thus slightly advantaging `4s1 3d5` over `4s2 3d4`); and `5s1 4d7` for ruthenium (Z=44):

In order to get the full electron configuration, it is necessary to use the "FullElectronConfiguration" option; the "ElectronConfigurationString" option will instead provide the electron configuration using "core notation" shorthand. E.g., for Z = 16, core notation is:

where `[Ne]` means "the electron configuration for Ne", i.e., `1s2 2s2 2p6`
> 2 votes

# Answer
# C (gcc), ~~260~~ ~~187~~ ~~167~~ ~~156~~ ~~152~~ ~~147~~ ~~143~~ 138 bytes

```
i,*m;f(e){for(m=L"...",i=0;e>0;printf("%.2s%d ","1s2s2p3s3p3d4s4p4d5s5p4f5d6s6p5f6d7s7p"+i++*2,(e-=*m)<0?*m+e:*m++));}

```

Try it online! Golfed from the reference implementation.

StackExchange removes unprintables, so the value of `m` is replaced with `"..."`.

Here is a reversible hexdump of the program, since it uses unprintables in a string, which replaces the integer array `{2,2,6,2,6,10,2,6,10,2,6,14,10,2,6,14,10,2,6}` with the literal byte values of the integers.

```
00000000: 692c 2a6d 3b66 2865 297b 666f 7228 6d3d  i,*m;f(e){for(m=
00000010: 4c22 0202 0602 065c 6e02 065c 6e02 060e  L".....\n..\n...
00000020: 5c6e 0206 0e5c 6e02 0622 2c69 3d30 3b65  \n...\n..",i=0;e
00000030: 3e30 3b70 7269 6e74 6628 2225 2e32 7325  >0;printf("%.2s%
00000040: 6420 222c 2231 7332 7332 7033 7333 7033  d ","1s2s2p3s3p3
00000050: 6434 7334 7034 6435 7335 7034 6635 6436  d4s4p4d5s5p4f5d6
00000060: 7336 7035 6636 6437 7337 7022 2b69 2b2b  s6p5f6d7s7p"+i++
00000070: 2a32 2c28 652d 3d2a 6d29 3c30 3f2a 6d2b  *2,(e-=*m)<0?*m+
00000080: 653a 2a6d 2b2b 2929 3b7d                 e:*m++));}

```

Alternatively, you could just copy the code from the TIO link.
> 1 votes

# Answer
# Clarion, 388 bytes

```
PROGRAM
  Map
  End
o CString('sspspdspdspfdspfdsp')
n CString('1223334445545665677')
m CString('2 2 6 2 6 102 6 102 6 14102 6 14102 6 ')
r CString(129)
Code
  e#=Command('ATOM'); Loop i#=1 To 19
  If e#>m[(i#*2)-1:(i#*2)] Then r=r&n[i#]&o[i#]&Clip(m[(i#*2)-1:(i#*2)])&' '
  e#-=m[(i#*2)-1:(i#*2)]; Cycle.;If e# < m[(i#*2)-1:(i#*2)] Then r=r&n[i#]&o[i#]&e#;Break.;End;Message(r)

```

Loosely based on @Rod's Python answer
> 1 votes

# Answer
# Scala, 173 bytes

A port of @Endenite's Swift answer in Scala.

173 bytes. It can be golfed much more.

---

Golfed version. Try it online!

```
n=>{var(i,a,b)=(n,0,Array(0,1,2,3));Seq(0,0,1,0,1,2,0,1,2,0,1,3,2,0,1,3,2,0,1).map{x=>a=x*4+2;b(x)+=1;if(i>0){println(b(x).toString+"spdf"(x)+math.min(a,i).toString)};i-=a}}

```

Ungolfed version. Try it online!

```
object Main {
  def f(n: Int): Unit = {
    var i = n
    var a = 0
    var b = Array(0, 1, 2, 3)
    List(0, 0, 1, 0, 1, 2, 0, 1, 2, 0, 1, 3, 2, 0, 1, 3, 2, 0, 1).map { x =>
      a = x * 4 + 2
      b(x) += 1
      if (i > 0) {
        println(b(x).toString + "spdf"(x) + math.min(a, i).toString)
      }
      i -= a
    }
  }

  def main(args: Array[String]): Unit = {
    f(16)
  }
}

```
> 0 votes

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


title: Tips for golfing in Retina

text:
# Question
Title: Tips for golfing in Retina
What general tips do you have for golfing in Retina? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Retina (e.g. "remove comments" is not an answer). Please post one tip per answer.

For reference, the online compiler is here.

@Sp3000 pointed out there is also Tips for Regex Golf. Answers here should focus specifically on Retina features and not on general regex golfing tips.

# Answer
> 4 votes
## Combine loops if possible

In non-trivial computations you'll often find yourself using several loops to process data:

```
+`stage1
+`stage2
+`stage3

```

So this runs `stage1` until the output converges, then `stage2` until the output converges and then `stage3` until the output converges.

However, it's always worth examining the stages in detail. Sometimes it's possible to run the loop in an interleaved fashion as `stage1, stage2, stage3, stage1, stage2, stage3, ...` instead (this depends a lot on what the stages actually do, but sometimes they make completely orthogonal changes or work well as a pipeline). In this case you can save bytes by wrapping them in a single loop:

```
{`stage1
stage2
}`stage3

```

If `stage1` is the first stage or `stage3` is the last stage of the program you can then even omit on of those parentheses as well (which means this can already save bytes for a loop of two stages).

A recent use of this technique can be seen in this answer.

# Answer
> 3 votes
## Splitting strings into chunks of equal length `n`

As in most "normal" languages TMTOWTDI (there's more than one way to do it). I'm assuming here that the input doesn't contain linefeeds, and that "splitting" means splitting it into lines. But there are two quite different goals: if the length of the string isn't a multiple of the chunk length, do you want to keep the incomplete trailing chunk or do you want to discard it?

### Keeping an incomplete trailing chunk

In general, there are three ways to go about the splitting in Retina. I'm presenting all three approaches here, because they might make a bigger difference when you try to adapt them to a related problem. You can use a replacement and append a linefeed to each match:

```
.{n}
$&¶

```

That's 8 bytes (or a bit less if `n = 2` or `n = 3` because then you can use `..` or `...` respectively). This has one issue though: it appends an additional linefeed if the string length *is* a multiple of the chunk length.

You can also use a split stage, and make use of the fact that captures are retained in the split:

```
S_`(.{n})

```

The `_` option removes the empty lines that would otherwise result from covering the entire string with matches. This is 9 bytes, but it doesn't add a trailing linefeed. For `n = 3` it's 8 bytes and for `n = 2` it's 7 bytes. Note that you can save one byte overall if the empty lines don't matter (e.g. because you'll only be processing non-empty lines and getting rid of linefeeds later anyway): then you can remove the `_`.

The third option is to use a match. With the `!` option we can print all the matches. However, to include the trailing chunk, we need to allow for a variable match length:

```
M!`.{1,n}

```

This is also 9 bytes, and also won't include a trailing linefeed. This also becomes 8 bytes for `n = 3` by doing `..?.?`. However note that it reduces to *6* bytes for `n = 2` because now we only need `..?`. Also note that the `M` can be dropped if this is the last stage in your program, saving one byte in any case.

### Discarding an incomplete trailing chunk

This gets really long if you try to do it with a replacement, because you need to replace the trailing chunk with nothing (if it exists) and also with a split. So we can safely ignore those. Interestingly, for the match approach it's the opposite: it gets shorter:

```
M!`.{n}

```

That's 7 bytes, or less for `n = 2`, `n = 3`. Again, note that you can omit the `M` if this is the last stage in the code.

If you do want a trailing linefeed here, you can get that by append `|$` to the regex.

### Bonus: overlapping chunks

Remember that `M` has the `&` option which returns overlapping matches (which is normally not possible with regex). This allows you to get all overlapping chunks (substrings) of a string of a given length:

```
M!&`.{n}

```

# Answer
> 3 votes
## Horizontal or Vertical Mirroring in Retina 0.8.2

If the amount of mirroring is a constant, then it's easy enough: duplicate the string, then reverse the appropriate half. For instance, suppose the buffer is known to contain 10 characters, and you want to mirror them about the last character:

```
saippuakiv

```

The following program would then achieve that:

```
.$
$&$`
10>O$^`.

```

Try it online! Explanation: The first stage copies the first 9 characters to the end of the line, then the second stage reverses the characters after the first 10. Note that the second stage consists of two lines but the second (empty) line may be omitted if it's the last stage.

If you want to mirror to the left, then you can prepend the suffix and sort the first 9 characters instead.

```
^.
$'$&
9O$^`.

```

Try it online! (Mirrors `vikauppias` to the left.)

Similarly, you can mirror a fixed number of lines. Suppose for instance you wanted a mirror copy of all three lines:

```
| | | | |
=~=~=~=~=
#########

```

The following program would then achieve that:

```
$
¶$`
3>O$^`

```

Try it online! Explanation: The first stage duplicates the entire buffer, while the second stage reverses the lines after the first three.

If you want to mirror up, then remove the `>`, so the first `3` lines are reversed instead.

If the amount of mirroring is a variable, then it might still be possible, but you would need to use .NET balancing groups to ensure that only the characters or lines that need to be reversed are processed by the `O` command.

## Horizontal Mirroring in Retina 1

Horizontal mirroring is straightforward in Retina 1: simply use the `$^` function to reverse a substitution. For instance, to horizontally mirror `saippuakiv` as above:

```
.$
$&$^$`

```

Try it online! Explanation: The reversed prefix of the input is appended to it, thus mirroring the input. (The code would be even simpler if the last character could be duplicated as well.)

## Vertical Mirroring of Horizontally Mirrored Text in Retina 1

If you are mirroring horizontally mirrored text, then a very similar approach will allow you to vertically mirror the whole text.

```
$
¶$^$`

```

Try it online! Explanation: The whole buffer is duplicated, but the second copy is reversed. This only works because the horizontal mirroring turns the string reversal into a line reversal.

Both of these examples are readily adapted to mirror to the left or up.

If the text is not already horizontally mirrored then you will need to adapt the Retina 0.8.2 examples (note that the limits syntax changes so that `3>` is now `3,` and `3` is now `,2`). You can use the `V` command instead to avoid the second line of the stage: `3,V0^` instead of `3,O$^` (the `0` is needed to avoid reversing the characters of the lines).

# Answer
> 2 votes
## Arithmetic in Retina 1

In Retina you need to do your arithmetic in unary. However, Retina 1 makes things slightly easier for you in certain cases, principally because of two constructs:

* The repetition operator `*` accepts an expression as its RHS, whereas the `$*` operator in Retina 0.8.2 only accepted a character as its RHS
* Retina 1 now includes a `$(...)` grouping construct, which accepts the length modifier `$.(...)`

It thus becomes possible to perform some arithmetic operations in both unary or decimal, depending on which is convenient. In particular, the group length construct `$.(...)` calculates the sum of the lengths of its contents, taking any products using arbitrary precision integers, so it's not limited in value.

### Addition

This is straightforward.

* Convert any decimal numbers to unary using `*_`
* Concatenate the numbers to give a unary result
* Group the sum using `$(...)` if you intend to multiply it or `$.(...)` to convert it to decimal

2-argument examples:

* Unary + Unary = Unary: `$1$2`
* Unary + Unary = Decimal: `$.($1$2)`
* Unary + Decimal = Unary: `$1$2*_`
* Unary + Decimal = Decimal: `$.($1$2*)` (see below)
* Decimal + Decimal = Unary: `$1*_$2*_`
* Decimal + Decimal = Decimal: `$.($1*_$2*)`

### Multiplication

Note that `*` normally takes one decimal and one unary parameter and returns a unary result.

* If the numbers are all decimal, add an extra unary parameter of 1
* Convert all but one number to decimal using the length modifier
* Take the product to give a unary result
* Convert the product to decimal by enclosing in `$.(...)` if desired

2-argument examples:

* Unary * Unary = Unary: `$.1*$2`
* Unary * Unary = Decimal: `$.($.1*$2)`
* Decimal * Unary = Unary: `$1*$2`
* Decimal * Unary = Decimal: `$.($1*$2)`
* Decimal * Decimal = Unary: `$1*$2*_`
* Decimal * Decimal = Decimal: `$.($1*$2*)` (see below)

A Retina replacement string to take the cube of a matched decimal number would be `$.(***` (see below).

### Further savings

* Only the first non-negative integer contained in the the LHS of a `*` operator is significant; there is no limit on junk characters (including `-`s). In particular this makes it easier to use `$&`.
* If the LHS of a `*` is indeed `$&`, then it is not necessary at the start of a `$(` construct or replacement string or after another `*`. Example: `$.(*__)`
* The `_` after a `*` is not necessary at the end of a `$(` construct or replacement string. Example: `$.($1*_$2*)`
* It is not necessary to close your `$(` constructs if they end at the end of the replacement string. Example: `$.($1$2`
* When adding the constant values 1 or 2 it is shorter to express them in unary.

# Answer
> 1 votes
## Using balancing groups to capture the same count twice.

Occasionally you need to capture a balancing group twice, such as to match the substring `nice` when the letters are equally spaced in the input. The naive approach is to capture the characters between `n` and `i` twice, and then use balancing groups to ensure that the same number of character exist between `i` and `c` and `c` and `e`, like this:

```
n((.))*i(?<-1>.)*(?(1)^)c(?<-2>.)*(?(2)^)e

```

However, you can capture into capture group `2` while popping from capture group `1`, allowing you to then pop the same count from capture group `2` later, saving a byte:

```
n(.)*i(?<2-1>.)*(?(1)^)c(?<-2>.)*(?(2)^)e

```

(Normally you would use `(?!)` to force the match to fail if the count is too low but obviously in code golf we just use the shortest regex that we know will fail; `^` usually works.)

# Answer
> 1 votes
## Actualising a transliteration pattern in Retina 0.8.2

In Retina 1, it's easy to produce the contents of a transliteration pattern, here the 64 characters used by MIME Base-64:

```

    64*
    Y`\_`Lld+/

```

Try it online! Explanation: The first stage inserts 64 `_`s, and the second stage cyclically transliterates `_`s to the 64 base 64 characters in turn. You can also cyclically extend the string should you want, say, 10 copies of each of the digits; just cyclically translate 100 `_`s into digits.

But it turns out not to be that difficult in Retina 0.8.2. Here is the required program:

```
T`Lld+/`_o
}`$
/

```

Try it online! Explanation: Each pass through the loop, the characters in the string get transliterated through the contents of the pattern, with the first character of the pattern being deleted, and a new copy of the last character is appended.

The loop becomes idempotent when the buffer equals the contents of the pattern, as then the deletion of the first character and the append of the last character is balanced by the transliteration of the intervening characters.

You can generate a prefix of a pattern by using the appropriate ending character in the append stage.

The code as shown is designed to be used to produce input as part of a larger program, which is why it does not begin with a loop block; it would need an extra `{` if it was embedded within a larger program. If the code actually appears at the end, or it is the desired program, then you can go on to remove the trailing loop block instead, saving a byte.

Note that when embedded within a larger program the code will normally delete any other copies of the output pattern present within the work buffer while appending a copy of the output pattern. You may be able to avoid the deletion by use of a suitable pattern to restrict the scope of the transliteration. It is also possible to adapt the code to prefix rather than append the desired output.

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


title: Sort list by types

text:
# Question
Title: Sort list by types
# Rules

You will receive as input a list that contains integers and strings. Your task is to move all of the strings to the end of the list and all of the integers to the beginning of the list.

This is so the answer with the least number of bytes wins.

# Answer
> 11 votes
# Python 3, 24 bytes

```
lambda l:l.sort(key=dir)

```

Try it online!

Sorts in place, modifying the input list. It so happens that the `dir` of a number is smaller than that of a string because the `__abs__` method that numbers have comes alphabetically first.

```
>> dir(1)
['__abs__', '__add__', '__and__', ...]
>> dir('a')
['__add__', '__class__', '__contains__', ...]

```

The only built-in to use as a key that would be shorter than `dir` is `id`, but it seems to puts strings before numbers, and I don't know if its behavior is consistent.

---

# Python 2, 6 bytes

```
sorted

```

Try it online!

Python 2 allows comparing different types, and conveniently numbers come before strings.

# Answer
> 7 votes
# 05AB1E, 1 byte

05AB1E does this *exactly* as specified.

```
{

```

Try it online!

Or, verify all test cases (so far)

# Explanation

Even if the answer is a one-byte answer, I still feel like typing the explanation.

```
Implicit input as a list
{ Sort the list (numbers go before the strings)

```

# Answer
> 5 votes
# APL (Dyalog Extended), 1 byte

Try it online!

# Answer
> 3 votes
# Wolfram Language (Mathematica), 4 bytes

```
Sort

```

Try it online!

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

```
a=>a.sort((a,b)=>!b.big-!a.big)

```

Try it online!

### How?

The deprecated but still widely supported method `.big()` is defined for Strings and undefined for Numbers. Hence the sorting criterion `!b.big-!a.big` which is either \\$-1\\$, \\$0\\$ or \\$1\\$.

# Answer
> 3 votes
# Ruby, ~~30~~ 24 bytes

```
->l{l.sort_by &:methods}

```

Try it online!

# Answer
> 2 votes
# Python 3, 33 bytes

```
L.sort(key=lambda x:str(type(x)))

```

Try it online!

And in fact this is how I'd write it in live code too, probably...

# Answer
> 2 votes
# Red, 23 bytes

```
func[x][reverse sort x]

```

Try it online!

# Answer
> 2 votes
# Java 8, ~~43~~ 41 bytes

```
L->{L.sort((i,j)->i==i.toString()?1:-1);}

```

-2 bytes thanks to *@Neil*.

Input as a `List` of `Object`s, with `String` and `Integer` items.

Try it online.

**Explanation:**

```
L->{                    // Method with Object-List parameter and no return-type
  L.sort(               //  Sort the List by:
    (i,j)->             //   For every pair of items `i,j`:
      i==i.toString()?  //    If `i` is a String (by checking whether `i` and the builtin
                        //    String-conversion of `i` reference the same instance):
       1                //     Put it after item `j`
      :                 //    Else:
       -1);}            //     Put it before item `j`

```

# Answer
> 2 votes
# ~~Perl 6~~ Raku, ~~15~~ 14 bytes

-1 thanks to Jo King.

```
*.sort(*~~Str)

```

Try it online!

This is an anonymous WhateverCode function nested within another. I didn't know I could do that.

# Answer
> 1 votes
# Python 3, 78 bytes

```
lambda x:[*filter(lambda _:type(_)==int,x)]+[*filter(lambda _:type(_)==str,x)]

```

Try it online!

# Answer
> 1 votes
# Japt, 2 bytes

```
ñy

```

Test it here

# Answer
> 1 votes
# PHP, 20 bytes

```
fn(&$a)=>sort($a,2);

```

Try it online!

# Answer
> 1 votes
# Bash \+ GNU utilities, 36 bytes

```
p=egrep\ ^-?[0-9]+$
tee a|$p
$p -v<a

```

Try it online!

A value is considered to be an integer if: (1) the first character is either a digit or a minus sign; (2) any other characters are all digits; and (3) at least one digit is present. Any value that is not an integer is considered to be a string.

# Answer
> 1 votes
# , 26 bytes

```
function(L)sort(unlist(L))

```

Straightforward: `unlist` then `sort` the list `L`. Works because digits sort before alphabetic letters, be them upper or lower case.

Try it online!

# Answer
> 1 votes
# C (gcc), 117 bytes

```
f(a,l,p,c)struct{int*s,i;}*a,*p;{for(c=l,p=a;c--;p++)p->s?:printf("%d ",p->i);for(;l--;a++)a->s&&printf("%s ",a->s);}

```

C does not have lists of combined strings and integers so instead I use an array of structures; if the string is `NULL` (which a real string never will be), then print the integer instead. Of course, go over the list an print the integers first, then the strings.

Stable sort.

Try it online!

# Answer
> 1 votes
# T-SQL, 35 bytes

Decimals will be placed in the integer section

```
DECLARE @ table(a varchar(99))
INSERT @ values('1'),('a'),('abc'),('1'),('d'),('84753')

SELECT*FROM @ ORDER BY-isnumeric(a)

```

# Answer
> 1 votes
# Burlesque, 2 bytes

```
><

```

Try it online!

# Answer
> 1 votes
# Pyth, 8 bytes

```
o$dir(N)

```

I don't know what it is about python eval that makes me feel like I'm bending the rules, but I like it :)

Try it online!

# Answer
> 1 votes
# Retina 0.8.2, 24 bytes

```
O$^m`^(-?[0-9]+$)?.*$
$1

```

Try it online! Explanation:

```
m`^(-?[0-9]+$)?.*$

```

Match each line, capturing it if it's an integer.

```
O$
$1

```

Sort the matches by the captured integer, as a string. This sorts non-integers to the beginning as nothing was captured which results in the empty string in the substitution.

```
^

```

Reverse the list after sorting.

# Answer
> 1 votes
# Charcoal, 15 bytes

```
Ｆ²ΦＥθ⭆¹κ⁼ι⁼κ§θλ

```

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

```
Ｆ²

```

Make two passes over the input items.

```
Ｅθ⭆¹κ

```

Stringify all the input items...

```
Φ...⁼ι⁼κ§θλ

```

... and filter on those elements that are not or are unchanged under stringification respectively.

# Answer
> 1 votes
# Batch, 320 Bytes

```
@ECHO OFF
Setlocal EnableDelayedExpansion
Set /P S=Str:
FOR %%B IN (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z) DO (
IF "!L!"=="" (Set L=!S:%%B= !) Else (Set L=!L:%%B= !)
)
FOR %%C IN (0,1,2,3,4,5,6,7,8,9) DO (
IF "!R!"=="" (Set R=!S:%%C= !) Else (Set R=!R:%%C= !)
)
Set S=%L: =%%R: =%
ECHO(%S%
pause

```

# Answer
> 1 votes
# Kotlin, 41 bytes

Expects and returns a `List<Any>`. The order of ints and strings in the returned list should be stable.

```
{it.partition{it is Int}.let{(a,b)->a+b}}

```

Try it online!

# Answer
> 1 votes
# Fig, \\$4\log\_{256}(96)\approx\\$ 3.292 bytes

```
^'#s

```

See the README to see how to run this

```
^'#s # Expects the list as input
^'   # Sort the input using the following function as a key:
  #s # Is string?

```

# Answer
> 0 votes
# Factor, 29 bytes

```
[ [ real? 0 1 ? ] sort-with ]

```

Try it online!

Is it a real number? Then sort it as though it were 0. Otherwise, sort it as though it were 1.

# Answer
> 0 votes
# Uiua, 3 bytes

```
⊏⍏.

```

Try it!

This is the default behavior of sorting a boxed list in Uiua.

```
⊏⍏.
  .  # duplicate
 ⍏   # rise (grade up)
⊏    # select

```

# Answer
> 0 votes
# Scala 3, 75 bytes

Golfed version. Attempt This Online!

```
_.sortWith{case(i:String,j:Any)=>2<1;case(i:Any,j:String)=>2>1;case _=>2>1}

```

Ungolfed version. Attempt This Online!

```
object Main {
  trait N {
    def c(L: List[Any]): List[Any]
  }

  val n: N = (L: List[Any]) => {
    L.sortWith {
      case (i: String, j: Any) => false
      case (i: Any, j: String) => true
      case _ => true
    }
  }

  def main(args: Array[String]): Unit = {
    test(1, 4, "2", "c", 6)
    test("a", 1, "b", 2, "c", 3, "1", "2", "3")
  }

  def test(a: Any*): Unit = {
    var list = a.toList
    prettyPrint(list)
    print(": ")
    list = n.c(list)
    prettyPrint(list)
    println()
  }

  def prettyPrint(list: List[Any]): Unit = {
    print("[")
    for (i <- list.indices) {
      val o = list(i)
      o match {
        case s: String => print("\"" + s + "\"")
        case _ => print(o)
      }
      if (i < list.size - 1) print(",")
    }
    print("]")
  }
}

```

---
Tags: code-golf
---


title: Make an inversedict

text:
# Question
Title: Make an inversedict
## Input

A dictionary with string keys and string values.

## Output

The 'inversedict' of this dictionary.

## How to make an inversedict

An inversedict is a dictionary with string keys and **string array** values. The keys are the values from the original dictionary, and the values are the keys from the original dictionary with that value from the original dictionary.

## An example

```
Input
["Clyde": "blue", "Sarah": "blue", "Fred": "green"]
Output
["blue": ["Clyde", "Sarah"], "green": ["Fred"]]

```

## This is , so shortest code in bytes wins!

# Answer
# Mathematica, 28 bytes

```
Merge[Reverse/@Normal@#,#&]&

```

The input is an `Association`, the output is an `Association` too.

**Explanation**

```
Normal@#

```

Convert the input `Association` to a `List` of `Rule`s.

```
Reverse/@ ...

```

Reverse the `Rule`s.

```
Merge[ ... ,#&]

```

`Merge` all `Rule`s, grouping duplicates with a `List` and then with the identity operation. Creates an `Association`.

**Usage**

```
Merge[Reverse/@Normal@#,#&]&[
 <|"Clyde" -> "blue", "Sarah" -> "blue", "Fred" -> "green"|>
]

```

> `<|"blue" -> {"Clyde", "Sarah"}, "green" -> {"Fred"}|>`
> 4 votes

# Answer
## Python 2, 54 bytes

```
lambda i:{i[k]:[a for a in i if i[a]==i[k]]for k in i}

```

**Usage:**

```
f=lambda i:{i[k]:[a for a in i if i[a]==i[k]]for k in i}
print f({"Clyde": "blue", "Sarah": "blue", "Fred": "green"})

```

Gives

```
{'blue': ['Sarah', 'Clyde'], 'green': ['Fred']}

```
> 4 votes

# Answer
# Brachylog, 10 bytes

```
tᵍ⟨ttʰhᵐ⟩ᵐ

```

Try it online!

Takes input as a list of `[key, value]` pairs through the input variable, and outputs a list of `[value, [keys]]` pairs through the output variable.

```
 ᵍ            Group the elements of
              the input
t             by their last elements.
         ᵐ    For each group,
   t          its last element
  ⟨     ⟩     paired with
      hᵐ      the first element of every element
     ʰ        with the first element of the pair being replaced by
    t         its last element
         ᵐ    is the corresponding element of
              the output.

```

...such an eloquent explanation...
> 3 votes

# Answer
# Pyth, 10 bytes

```
uXeHG]hHQH

```

Try it online!

```
uXeHG]hHQH   Implicit: Q=eval(input()), H={} (empty dictionary)
u       Q    Reduce elements of Q...
         H   ... starting with an empty dictionary...
             ... current value is G, next value is H:
 X  G          Add to G...
  eH           ... with key as last element of H (i.e. value from original input dictionary)...
     ]hH       ... value as first element of H, wrapped in a list
               This adds a new single-element list if the key is not alrady present, or concatenates values if it is

```
> 2 votes

# Answer
# Rust, 127 bytes

```
use std::collections::HashMap as H;|m:H<String,String>|{let mut n=H::new();for(k,v)in m{n.entry(v).or_insert(vec![]).push(k)}n}

```

Try it online!
> 2 votes

# Answer
# Japt, ~~9~~ 7 bytes

Input is as a 2D-array: `[[key,value],[key,value],...]`.
Output is as a 3D-array: `[[value,[key,key,...]],[value,[key,key,...]],...]`.

If we can ouput the pairs in reverse order then the `Ô` can be removed, an the `v` replaced with `o` to save a byte.

```
üÌ®ÕÔvÎ

```

Try it

```
üÌ®ÕÔvÎ     :Implicit input of array
ü           :Group and sort by
 Ì          :  Last element of each
  ®         :Map
   Õ        :  Transpose
    Ô       :  Reverse
     v      :  Modify first element
      Î     :    Get first element

```

If output *must* be a 2D-array then:

## ~~10~~ 8 bytes

```
üÌc_ÕÔvÎ

```

Try it

The `_`, essentially, serves the same purpose as the `®` above and the `c` flattens the array by one level afterwards.
> 2 votes

# Answer
# Lua, 82 Bytes

```
function(t)g={}for k,v in pairs(t)do g[v]=g[v]or{}g[v][#g[v]+1]=k end return g end

```

An anonymous function which takes a table as an input and outputs the inverse dict.

## Commented and Ungolfed.

```
function(t)                     #Anonymous Function.
    g={}                        #Define the output array.
    for k,v in pairs(t) do      #For each value in the input by key value pairs.
        g[v]= g[v] or {}        #Set the value of the output dictionary with the key v, to either itself, or a new table if it's null.
        g[v] [#g[v]+1] = k      #Set a new value (#g[v]+1 is the key that is +1 the count, lua is 1 indexed) to the key.
    end                         #This loop will append values with the same 'key', instead of set. However, makes all output in table form.
    return g                    #Output g
end                             #End

```
> 1 votes

# Answer
# JavaScript (ES6), 57 bytes

```
d=>eval("r={};for(i in d)(r[j=d[i]]=r[j]||[]).push(i);r")

```

Input and output are as Objects, e.g. `{"Clyde": "blue", "Sarah": "blue", "Fred": "green"}`
> 1 votes

# Answer
## C#6, 136 bytes

```
using System.Collections.Generic;using System.Linq;ILookup<string,string>F(Dictionary<string,string>d)=>d.ToLookup(x=>x.Value,x=>x.Key);

```

repl.it demo

Seriously, do I really need to ungolf this? Just create an `ILookup` with input value as output key and input key as output value.
> 1 votes

# Answer
# C++17, 158 bytes

```
#import<string>
#import<map>
#import<vector>
[](auto m){std::map<std::string,std::vector<std::string>>n;for(auto x:m)n[x.second].push_back(x.first);return n;}

```

Ungolfed and usage:

```
#include<iostream>
#include<string>
#include<map>
#include<vector>

auto f=
[](auto m){
 std::map<std::string,std::vector<std::string>>n;  //using namespace is equally long
 for(auto x:m)
  n[x.second].push_back(x.first);
 return n;
}
;

using namespace std;

int main(){
 map<string,string> m={
  {"a","x"},{"b","x"},{"c","y"}
 };
 auto n = f(m);
 for (auto x:n){
  cout << x.first << ": ";
  for (auto y:x.second)
   cout << y << ", ";
  cout << "\n";
 }
 cout << "\n";
}

```
> 1 votes

# Answer
# Factor, 27 bytes

```
[ [ last ] collect-key-by ]

```
> 1 votes

# Answer
# 05AB1E, 10 (or 9) bytes

```
.¡θ}εø`н‚R

```

Input as `[[key,value],[key,value],...]`; output as `[[value,[keys]],[value,[keys]],...]`.

Try it online.

If it's allowed to output as `[[[keys],value],[[keys],value],...]` instead, it can be 1 byte less by removing the trailing `R`:
Try it online.

**Explanation:**

```
.¡ }        # Group the pairs of the (implicit) input-list by:
  θ         #  Their last item
    ε       # Then map over each group of pairs:
     ø      #  Zip/transpose; swapping rows/columns
      `     #  Pop and push the list of keys and list of values separately to the stack
       н    #  Pop and leave just the first item of the values-list
        ‚   #  Pair it with the keys-list
         R  #  (optional: Reverse the [[keys],value] pair to [value,[keys]])
            # (after which the result is output implicitly)

```
> 1 votes

# Answer
# JavaScript, 47 bytes

Input as a 2D array, output as an object.

```
a=>a.map(([k,v])=>i[v]=[...i[v]||[],k],i={})&&i

```

Try it online!
> 1 votes

# Answer
# Jelly, 8 bytes

```
ZQż¹ƙɗ@/

```

Try it online!

Input as a list of `[key, value]` pairs, output as a list of `[value, keys]` pairs.

```
Z   ɗ@/    With the keys on the right and the values on the left:
  ż        Zip
 Q         the unique values with
   ¹ƙ      the keys grouped by value, in order of the value's first appearance.

```
> 1 votes

# Answer
# Nibbles, 6 bytes

```
.=~$@~/.$@$.

```

Attempt This Online!

Takes and outputs a list of pairs.

```
.  Map
=~  group by
$    [input]
@    [second element]
~   pair
/    fold
.     map
$      [the group]
@      [second element]
$     [value]
.    map
      [the group]
      [first element]

```

**5 bytes** if we allow the output to be in the format `[(values, key)]` rather than `[(key, values)]`:

```
.=~$@~`'$/

```

Attempt This Online!
> 1 votes

# Answer
# Uiua, 11 bytes

```
∵⊂⊝:⊕□⊛,⍘⊟⍉

```

Try it!

```
∵⊂⊝:⊕□⊛,⍘⊟⍉
          ⍉  # transpose
        ⍘⊟   # uncouple
       ,     # over
      ⊛      # classify
    ⊕□       # group by box
   :         # flip
  ⊝          # deduplicate
∵⊂           # zip

```
> 1 votes

# Answer
# Perl, 36 bytes

This is an anonymous function which takes a hash (not hash reference) as an argument, and returns a hash (not a hash reference) as its result. (A "hash" is Perl's name for a dictionary.) Although the language has dictionaries, it doesn't have sets; thus, for the values of the inverse dictionary (which are logically sets), I used the common Perl representation of a set as a hash, in which the keys are the set elements and the values are irrelevant.

Here's the program itself:

```
sub{my%t;$t{+pop}{+pop}++while@_;%t}

```

Here's how I tested it:

```
use Data::Dumper;
$f = sub{my%t;$t{+pop}{+pop}++while@_;%t};
my %test = qw/sky blue sea blue grass green/;
print Dumper({&$f(%test)});

```

The dump of the resulting hash is:

```
$VAR1 = {
          'blue' => {
                      'sky' => 1,
                      'sea' => 1
                    },
          'green' => {
                       'grass' => 1
                     }
        };

```

which is the expected value.
> 0 votes

# Answer
## Haskell, 55 bytes

```
foldl(\l(k,v)->maybe(v,[k])((,)v.(k:))(lookup v l):l)[]

```

This uses the good old association list as the data structure, which means that the output list may contain multiple elements with the same key, where only the first one is valid. However, I exploit the fact that the keys in the input list are all distinct.

Usage example:

```
*Main> foldl(\l(k,v)->maybe(v,[k])((,)v.(k:))(lookup v l):l)[] [("Clyde","blue"),("Sarah","blue"),("Fred","green")]
[("green",["Fred"]),("blue",["Sarah","Clyde"]),("blue",["Clyde"])]

```

How it works:

```
foldl(   )[]                    -- starting with the empty list, reduce the
                                -- input list
    \l (k,v)->                  -- with via a lambda function that takes a list l
                                -- (the output list so far) and a key-value-pair
                                -- (k,v) from the input list and returns the next
                                -- version of the output list, which is made by:
                          :l    -- prepend to the existing list
      maybe   (lookup v l)      -- if v is already a key in the output
           (,)v.(k:)            --     prepend k to the list for v
                                --     (this leaves the current pair in places and
                                --     adds the updated version to the front)
         (v,[k])                -- else a new pair with v and k flipped
                                --     and k put into a singleton list

```
> 0 votes

# Answer
## Racket 208 bytes

```
(let p((l2(remove-duplicates(map(λ(x)(list-ref x 1))ll)))(ol'()))(cond[(empty? l2)(reverse ol)][
(p(rest l2)(cons(cons(first l2)(for/list((i ll)#:when(equal?(first l2)(list-ref i 1)))(list-ref i 0)))ol))]))

```

Ungolfed:

```
(define (f ll)
  (define l2 (remove-duplicates (map (λ (x) (list-ref x 1)) ll)))
  (let loop ((l2 l2)
             (ol '()))
    (cond
      [(empty? l2) (reverse ol)]
      [else
       (define tl (for/list ((i ll) #:when (equal? (first l2) (list-ref i 1)))
                    (list-ref i 0)))
       (loop (rest l2) (cons (cons (first l2) tl) ol))
       ])))

```

Testing:

```
(f '[("Clyde" "blue") ("Sarah" "blue") ("Fred" "green")])

```

Output:

```
'(("blue" "Clyde" "Sarah") ("green" "Fred"))

```
> 0 votes

# Answer
## R, 79 69 bytes

```
function(l)setNames(lapply(u,function(x)names(l)[l==x]),u<-unique(l))

```

R does not have a dictionary by default but the closest approximation to a dictionary is an object of class `list`. It's basically a generic vector allowing for multiple data types where each value (can basically be any R-object) is allowed to have a name/key.

**Example**

A list with keys/names can be created as e.g.:

```
l <- list(Clyde="blue", Sarah="blue", Fred="green")

```

Which if printed returns:

```
$Clyde
[1] "blue"

$Sarah
[1] "blue"

$Fred
[1] "green"

```

Calling the function now returns:

```
$blue
[1] "Clyde" "Sarah"

$green
[1] "Fred"

```
> 0 votes

# Answer
# Groovy, ~~56~~ 53 bytes

```
{m=[:];it.each{k,v->if(!m."$v"){x=m."$v"=[]};x<<k};m}

```

## Testing

```
({m=[:];it.each{k,v->if(!m."$v"){x=m."$v"=[]};x<<k};m})(["Clyde": "blue", "Sarah": "blue", "Fred": "green"])

```

**Output**

```
[blue:[Clyde, Sarah], green:[Fred]]

```
> 0 votes

# Answer
# Java 7, ~~211~~ 205 bytes

golfed:

```
Map<String,List<String>>i(Map<String,String>m){Map<String,List<String>>r=new HashMap<>();for(String k:m.keySet()){String s=m.get(k);if(r.get(s)==null)r.put(s, new ArrayList<>());r.get(s).add(k);}return r;}

```

ungolfed:

```
public static Map<String, List<String>> i(Map<String, String> m)
{
    Map<String, List<String>> r = new HashMap<>();
    for (String k : m.keySet())
    {
        String s = m.get(k);
        if (r.get(s) == null)
            r.put(s, new ArrayList<>());
        r.get(s).add(k);
    }
    return r;
}

```

Test it online!

Java ... the worst golfing language.
> 0 votes

# Answer
# Go, 107 bytes

```
type S=string
func f(m map[S]S)map[S][]S{O:=make(map[S][]S)
for k,v:=range m{O[v]=append(O[v],k)}
return O}

```

Attempt This Online!
> 0 votes

# Answer
# Raku, 28 bytes

```
{push my Array%: .antipairs}

```

Try it online!

Raku hashes have an `antipairs` method that returns a list of the value-key pairs, and a `push` method that adds any number of key-value pairs, accumulating values associated with duplicated keys into arrays. So this answer could *almost* be just:

```
{push {}: .antipairs}

```

...but unfortunately the `push` method *doesn't* create an array value unless there actually is a duplicated key. In the provided example, it would associate the key `"green"` with the string `"Fred"`, not the array `["Fred"]`. So I address that by declaring that the anonymous returned hash has values of type `Array`.
> 0 votes

# Answer
# Scala 3, 47 bytes

```
_.groupBy(_._2).map{case(k,v)=>k->v.keys.toSeq}

```

Attempt This Online!
> 0 votes

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