title: Landmine Number II

text:
# Question
Title: Landmine Number II
## Background

You have again been given the task of calculating the number of landmines in a field. However, we have now travelled into the flatlands.

You must calculate the landmine score given a list/string of numbers (which will be 2D) and the landmine number.

The landmine number tells you where landmines are.

For each digit:

1. if the DIRECTLY ADJACENT digits above, left, right, and below add to the landmine number, add the digit in focus to the landmine score.
2. if the DIRECTLY ADJACENT digits above, left, right, and below multiply to the landmine number, add double the digit in focus to the landmine score.
3. if both 1 and 2 are satisfied, add triple the digit in focus to the landmine number.

Note: The very corner and edge digits cannot have landmines because they are not fully surrounded by other numbers.

## Your Task

* Sample Input: A two dimensional array of numbers, NxN, such that N is \>= 3. Also, the landmine number.
* Output: Return the landmine score.

**Explained Examples**

```
Input => Output
111
111
111

4 => 1

```

There is 1 landmine here. The central 1 has 1+1+1+1 = 4.

```
Input => Output

1448
4441
4114
2114

16 => 12

```

Focusing only on central numbers,

* Top right 4 has 4x4x1x1 = 16, so we add 4x2 = 8.
* Bottom left 1 has 4x4x1x1 = 16, so we add 1x2 = 2.
* Bottom right 1 has 4x1x1x4 = 16, so we add 1x2 = 2.

8+2+2 = 12

```
Input => Output
12312
19173
04832
01010
00100

8 => 42

```

There are 42 landmines here:

* On 9, 2+1+4+1 = 2x1x4x1 = 8, so we add 9x3 = 27.
* On 7, 1+1+3+3 = 8, so we add 7.
* On 8, 1+4+3+0 = 8, so we add 8.
* On central 0, 8x1x1x1 = 8, so we add 0x2 = 0

27+7+8+0 = 42

```

Input => Output
00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000

0 => 0

```

There are 36 central 0s. So, 36x0x3 = 0.

**Test Cases**

```
Input ~> Output

111
111
111

4 ~> 1

1448
4441
4114
2114

16 ~> 12

12312
19173
04832
01010
00100

8 ~> 42

00000000
00000000
00000000
00000000
00000000
00000000
00000000
00000000

0 ~> 0

090
999
090

36 ~> 9

1301
3110
0187
3009

9 ~> 12

48484
28442
84244
28448
48424

256 ~> 68

111111
111111
111111
114111
111111
111111

4 ~> 23

```

This is , so shortest answer wins.

...

**Landmine Number Series**

# Answer
> 4 votes
# , 55 bytes

```
[:+/@,[({.@]*[:I.=)"#.3 3(4&{,](+/,*/)@#~1-2|#\)@,;._3]

```

Attempt This Online!

* Uses J's subarray verb `3 3...;._3`, which automatically extracts the 3x3 tiles
* The rest is figuring out to extract the compass directions from each of those, and then do the needed arithmetic and comparisons with the landmine number

# Answer
> 3 votes
# JavaScript (ES11), 113 bytes

Expects `(n)(matrix)`.

```
n=>m=>m.map((r,y)=>r.map(a=(v,x)=>t+=v*=a+(b=m[y+1]?.[x])+(c=m[y-1]?.[x])+r[++x]==n|2*(a*b*c*r[a=v,x]==n)),t=0)|t

```

Attempt This Online!

### Commented

```
n =>                          // n = target number
m =>                          // m[] = digit matrix
m.map((r, y) =>               // for each row r[] at index y in m[]:
  r.map(a =                   //   initialize a to something NaN'ish
    (v, x) =>                 //   for each value v at index x in r[]:
    t +=                      //     add to t:
      v *=                    //       v multiplied by:
                              //         1 if the sum of ...
        a +                   //           a, the value on the left
        (b = m[y + 1]?.[x]) + //           b, the value below
        (c = m[y - 1]?.[x]) + //           c, the value above
        r[++x]                //           and the value on the right
        == n |                //         is equal to n
        2 * (                 //         2 if the product of:
          a * b * c *         //           a, b, c
          r[a = v, x]         //           and the value on the right
                              //           (copy v into a afterwards)
          == n                //         is equal to n
        )                     //
  ),                          //   end of inner map()
  t = 0                       //   start with t = 0
) | t                         // end of outer map(); return t

```

# Answer
> 3 votes
# Python 3, 125 bytes

```
lambda n,l:sum(e*(2*(a*b*c*d==l)+(a+b+c+d==l))for x,y,z in zip(n,n[1:],n[2:])for a,b,c,d,e in zip(x[1:],z[1:],y,y[2:],y[1:]))

```

Try it online!

The function takes in a 2D list of integers `(n: list[list[int]])` and the landline number `(l: int)`. Magical `zip` stuff happens which assigns `a,b,c,d` to the values adjacent to every "central" coordinate, and `e` to the value of the coordinate in focus.

Explanation by gsitcia:

`_ for x,y,z in zip(n,n[1:],n[2:])` is equivalent to `for i in range(1,len(n)-1): x,y,z=n[i-1],n[i],n[i+1]; _.` `_ for a,b,c,d,e in zip(x[1:],z[1:],y,y[2:],y[1:])` is equivalent to `for j in range(1, len(n[0])-1): a,b,c,d,e = n[i-1][j], n[i+1][j], n[i][j-1], n[i][j+1], n[i][j]; _` both of these work because zip will cut off at the shortest length

*-1 byte thanks to spooky\_simon*

*-50 bytes thanks to gsitcia*

# Answer
> 3 votes
# Excel, 155 bytes

```
=SUM(TOCOL(
        MAP(A1#,
            LAMBDA(a,
                LET(
                    b,OFFSET(a,{-1,0,0,1},{0,-1,1,0}),
                    c,SUBTOTAL(2,b),
                    d,SUBTOTAL(9,b),
                    IF(SUM(c)=4,IF(SUM(d)=Z1,a)+IF(PRODUCT(d)=Z1,2*a))
                )
            )
        ),2
    )
)

```

Matrix is spilled range `A1#`; landmine number in cell `Z1` (or, if necessary, some other cell which does not form part of `A1#`).

# Answer
> 2 votes
# Charcoal, 49 bytes

```
ＷＳ⊞υιＰ⪫υ⸿Ｎθ≔⁰ηＦ⪫υ⸿«Ｆ⌊ＫＶ≧⁺×ＩＫＫ⁺⁼ΣΣＫＶθ⊗⁼ΠΣＫＶθηι»⎚Ｉη

```

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

```
ＷＳ⊞υι

```

Input the field.

```
Ｐ⪫υ⸿

```

Output the field without moving the cursor.

```
Ｎθ

```

Input the target.

```
≔⁰η

```

Start with zero score.

```
Ｆ⪫υ⸿«

```

Loop over the field.

```
Ｆ⌊ＫＶ

```

If there are digits on all four sides, then...

```
≧⁺×ＩＫＫ⁺⁼ΣΣＫＶθ⊗⁼ΠΣＫＶθη

```

... multiply the current digit by the sum of `1` if the digital sum equals the target and `2` if the digital product of those digits equals the target.

```
ι

```

Move to the next digit.

```
»⎚Ｉη

```

Output the final total.

Removing the `Ｆ⌊ＫＶ` test has the effect of only considering those adjacent digits that exist e.g. in the top left corner it would search for the target from the sum and products of the digits to the right and below only.

# Answer
> 2 votes
# Python 3, 174 bytes

```
lambda a,b:sum(a[c][d]*((b==a[c-1][d]+a[c][d-1]+a[c+1][d]+a[c][d+1])+2*(b==a[c-1][d]*a[c][d-1]*a[c+1][d]*a[c][d+1])) for d in range(1,len(a)-1) for c in range(1,len(a[d])-1))

```

Try it online!

If I could condense the doubled calls to a\[c-1\]\[d\], a\[c+1\]\[d\], a\[c\]\[d-1\], and a\[c\]\[d+1\], I could save several bytes.

# Answer
> 2 votes
# 05AB1E, ~~33~~ 28 bytes

```
2Fø€ü3}εε˜ιθDOsPD)QOy˜4è*]˜O

```

-5 bytes thanks to *@ovs*.

Inputs in the order *matrix, landmineNumber*.

Try it online or verify all test cases.

**Explanation:**

```
2Fø€ü3}   # Create all overlapping 3x3 blocks of the first (implicit) input-matrix:
2F    }   #  Loop 2 times:
  ø       #   Zip/transpose; swapping rows/columns
          #   (which will use the implicit first input-matrix in the first iteration)
   €      #   Map over each row:
    ü3    #    Create overlapping triplets
εε        # (Nested) map over each 3x3 block:
  ˜       #   Flatten it to a single nonet-list
   ι      #   Uninterleave it into two parts
    θ     #   Pop and leave just the last list (with the even-indiced values)
     D    #   Duplicate this quadruplet
      O   #   Sum it together
     s    #   Swap so the quadruplet is at the top again
      P   #   Take its product
       D  #   Duplicate this product
        ) #   Wrap all three values into a list: [sum,product,product]
  Q       #   Check for each whether it's equal to the second (implicit) input-integer
   O      #   Sum the checks together
    y˜    #   Push the flattened 3x3 block again
      4è  #   Pop and leave the 0-based 4th integer (the center)
        * #   Multiply it to the earlier sum of checks
]         # Close the nested map
 ˜        # Flatten it to a single list
  O       # Sum this list together
          # (after which it is output implicitly as result)

```

# Answer
> 2 votes
# C (clang), ~~148~~ \\$\cdots\\$ ~~118~~ 117 bytes

```
#define y(z)*a*(a[-1]z+a[1]z+a[n]z+a[-n]==l)
i;j;f(*a,n,l,*s){for(*s=0,a+=j=n-2,i=j*j;i;*s+=y()+2*y(*))a+=i--%j?1:3;}

```

Try it online!

*Saved a whopping ~~12~~ ~~19~~ ~~30~~ 31 bytes thanks to ceilingcat!!!*

# Answer
> 1 votes
# JavaScript (Node.js), 120 bytes

```
x=>k=>x.map((y,i)=>y.map((z,j)=>r+=[a=0,b=1,2,-1].map(d=>{a+=c=(x[i+d%2]||0)[--d%2+j],b*=c})&&z*(a==k|2*(b==k))),r=0)&&r

```

Try it online!

Some of ur test cases seem wrong, 2x1x4x1 = 8 = 2+1+4+1

# Answer
> 1 votes
# Python3, 237 bytes:

```
R=range
def f(n,B):
 t=0
 for x in R(1,len(B)-1):
  for y in R(1,len(B[0])-1):
   a,b,c,d=B[x-1][y],B[x][y-1],B[x][y+1],B[x+1][y]
   j,k=a+b+c+d,a*b*c*d;v=B[x][y]
   if k==n and j==n:t+=v*3
   elif k==n:t+=v*2
   elif j==n:t+=v
 return t

```

Try it online!

# Answer
> 1 votes
# Vyxal `s`, 210 bitsv1, 26.25 bytes

```
żṪ:Ẋ:ƛk□¨V+ƛ¹nÞi;₍Π∑⁰=;¹„¨VÞi*vB

```

Try it Online!

I forgot how this worked like 3 times while writing it. Chances are after I paste in the explanation, it'll be 4 times.

## Explained

```
żṪ:Ẋ:ƛk□¨V+ƛ¹nÞi;₍Π∑⁰=;¹„¨VÞi*vB
żṪ                                # The range [1 ... len(field) - 1]
  :Ẋ                              # Cartesian producted with itself. This generates a list of indices of central numbers
     ƛ                ;           # To each central number index:
      k□¨V+                       #   Add it to ⟨ ⟨ 0 | 1 ⟩ | ⟨ 1 | 0 ⟩ | ⟨ 0 | -1 ⟩ | ⟨ -1 | 0 ⟩ ⟩ to get the numbers above, below, left and right of this number
           ƛ    ;                 #   To each adjacent number index:
            ¹nÞi                  #     Retrieve it from the field
                 ₍Π∑              #   Push a list of [product(adjacents), sum(adjacents)]. Keen readers will notice that I used
                                  #   this in the previous challenge
                    ⁰=            #   And test whether that equals the landmine number. Also in the previous challenge.
                       ¹„         # Push a copy of the field and rotate the stack left so that the central indices are on the top
                         ¨VÞi     # Retrieve the numbers that are central in the field
                             *    # And multiply by the list of checksums.
                              vB  # Convert each from binary.
# The s flag sums the resulting list

 Created with the help of Luminespire at https://vyxal.github.io/Luminespire

```

# Answer
> 1 votes
# Pyth, 37 bytes

```
sm+*yJ@d4qQ*FK%2td*JqQsKsmsM.:Cd3.:E3

```

Try it online!

# Answer
> 1 votes
# Scala, 224 bytes

Port of @Ajax1234's Python answer in Scala.

---

Golfed version. Try it online!

```
def f(n:Int,B:Array[Array[Int]])=(for(x<-1 to B.length-2;y<-1 to B(0).length-2;a=B(x-1)(y);b=B(x)(y-1);c=B(x)(y+1);d=B(x+1)(y);j=a+b+c+d;k=a*b*c*d;v=B(x)(y))yield if(k==n&&j==n)v*3 else if(k==n)v*2 else if(j==n)v else 0).sum

```

Ungolfed version. Try it online!

```
object Main {
  def f(n: Int, B: Array[Array[Int]]): Int = {
    var t = 0
    for (x <- 1 until B.length - 1) {
      for (y <- 1 until B(0).length - 1) {
        val a = B(x - 1)(y)
        val b = B(x)(y - 1)
        val c = B(x)(y + 1)
        val d = B(x + 1)(y)
        val j = a + b + c + d
        val k = a * b * c * d
        val v = B(x)(y)
        if (k == n && j == n) t += v * 3
        else if (k == n) t += v * 2
        else if (j == n) t += v
      }
    }
    t
  }

  def main(args: Array[String]): Unit = {
    val s1 = Array(Array(1, 1, 1), Array(1, 1, 1), Array(1, 1, 1))
    val s2 = Array(Array(1, 4, 4, 8), Array(4, 4, 4, 1), Array(4, 1, 1, 4), Array(2, 1, 1, 4))
    val s3 = Array(Array(1, 2, 3, 1, 2), Array(1, 9, 1, 7, 3), Array(0, 4, 8, 3, 2), Array(0, 1, 0, 1, 0), Array(0, 0, 1, 0, 0))
    val s4 = Array.fill(8)(Array.fill(8)(0))
    val s5 = Array(Array(0, 9, 0), Array(9, 9, 9), Array(0, 9, 0))
    val s6 = Array(Array(4, 8, 4, 8, 4), Array(2, 8, 4, 4, 2), Array(8, 4, 2, 4, 4), Array(2, 8, 4, 4, 8), Array(4, 8, 4, 2, 4))
    val s7 = Array(Array(1, 1, 1, 1, 1, 1), Array(1, 1, 1, 1, 1, 1), Array(1, 1, 1, 1, 1, 1), Array(1, 1, 4, 1, 1, 1), Array(1, 1, 1, 1, 1, 1), Array(1, 1, 1, 1, 1, 1))

    println(f(4, s1))
    println(f(16, s2))
    println(f(8, s3))
    println(f(0, s4))
    println(f(36, s5))
    println(f(256, s6))
    println(f(4, s7))
  }
}

```

---
Tags: code-golf, number
---


title: Simple Boolean Algebra Calculator

text:
# Question
Title: Simple Boolean Algebra Calculator
## Background

Boolean Algebra concerns representing values with letters and simplifying expressions. The following is a chart for the standard notation used:

Above is what actual boolean algebra looks like. For the purposes of this code golf, this is not the syntax that will be used.

## Your Task

Given a string with three characters, return the solution to the expression.

* Input: The string will be a valid expression in boolean algebra. The second character will either be ".", which represents AND, or "+", which represents OR. The first and third characters will be any of 0, 1, or a capital letter. If a capital letter is given, only one letter is ever given. ie. An input will never have two variables, such as A+B.
* Output: Return the evaluation of the expression as a single character.

**Explained Examples**

```
Input => Output
A+1 => 1

```

A + 1 evaluates to 1 because the OR statement is overridden by 1. That is, no matter what value A takes, the presence of 1 means that the statement will always evaluate to 1.

```
Input => Output
B+B => B

```

B + B evaluates to B because the OR statement is dependent on either Bs being true. If both Bs are false, then the output would also be false. So, the statement returns B since whatever value B takes, the output would return that.

```
Input => Output
0.H => 0

```

0 . H evaluates to 0 because the AND statement is overridden by 0. That is, no matter what value H takes, the presence of 0 means that the statement will always evaluate to 0.

```
Input => Output
1.1 => 1

```

1 . 1 evaluates 1 because the AND statement requires both inputs to be 1, and since they are both 1, 1 is returned.

**Examples**

```
Input => Output
A+1 => 1
B+B => B
R+0 => R
1+1 => 1
0+0 => 0

0.0 => 0
Q.Q => Q
0.A => 0
1.C => C
1.1 => 1

```

This is , so shortest answer wins.

Too easy? Try Intermediate Boolean Algebra Calculator.

# Answer
# JavaScript (ES6), 26 bytes

-4 bytes by using the simplified logic suggested by @loopywalt.

```
([x,o,y])=>~x&y!=0^o+1?x:y

```

Try it online!

---

# JavaScript (ES6), 30 bytes

Expects a string of 3 characters.

```
([x,o,y])=>x<1^y<1^o+1^x<y?y:x

```

Try it online!

### 28 bytes

If we can take three separate characters as input:

```
(x,o,y)=>x<1^y<1^o+1^x<y?y:x

```

Try it online!

### Truth table

The table below shows the intermediate results coerced to \\$0\\$ or \\$1\\$, which is implicitly done by the bitwise operators.

Note that `o+1` evaluates to either `0.1` for `.` (coerced to \\$0\\$) or `1` for `+` (coerced to \\$1\\$).

```
 x | y | o | x<1 | y<1 | o+1 | x<y | XOR | use | result
---+---+---+-----+-----+-----+-----+-----+-----+--------
 0 | 0 | . |  1  |  1  |  0  |  0  |  0  |  x  |   0
 0 | 0 | + |  1  |  1  |  1  |  0  |  1  |  y  |   0
 0 | 1 | . |  1  |  0  |  0  |  1  |  0  |  x  |   0
 0 | 1 | + |  1  |  0  |  1  |  1  |  1  |  y  |   1
 0 | A | . |  1  |  0  |  0  |  1  |  0  |  x  |   0
 0 | A | + |  1  |  0  |  1  |  1  |  1  |  y  |   A
 1 | 0 | . |  0  |  1  |  0  |  0  |  1  |  y  |   0
 1 | 0 | + |  0  |  1  |  1  |  0  |  0  |  x  |   1
 1 | 1 | . |  0  |  0  |  0  |  0  |  0  |  x  |   1
 1 | 1 | + |  0  |  0  |  1  |  0  |  1  |  y  |   1
 1 | A | . |  0  |  0  |  0  |  1  |  1  |  y  |   A
 1 | A | + |  0  |  0  |  1  |  1  |  0  |  x  |   1
 A | 0 | . |  0  |  1  |  0  |  0  |  1  |  y  |   0
 A | 0 | + |  0  |  1  |  1  |  0  |  0  |  x  |   A
 A | 1 | . |  0  |  0  |  0  |  0  |  0  |  x  |   A
 A | 1 | + |  0  |  0  |  1  |  0  |  1  |  y  |   1
 A | A | . |  0  |  0  |  0  |  0  |  0  |  x  |   A
 A | A | + |  0  |  0  |  1  |  0  |  1  |  y  |   A
            \_________XOR_________/

```
> 19 votes

# Answer
# Jelly, 9 bytes

```
Ṣ⁼ÞOṂḂṾƲṪ

```

A monadic Link that accepts a list of three characters as specified and yields the resulting character.

**Try it online!**

### How?

Note that `+` and `.` are less than all other possible characters and that their ordinals are odd (\\$43\\$) and even (\\$46\\$), respectively. Also, variables always have ordinals greater than either `0` or `1`.

```
Ṣ⁼ÞOṂḂṾƲṪ - Link: list of characters, S = [a, o, b]
Ṣ         - sort (S) -> [o, min(a,b), max(a,b)]
            ... this places a variable, if present, on the right
       Ʋ  - last four links as a monad - f(S):
   O      -   ordinals
    Ṃ     -   minimum -> 43 (o='+') or 46 (o='.')
     Ḃ    -   mod two ->  1         or  0
      Ṿ   -   uneval  -> '1'        or '0'
  Þ       - sort (the sorted S) by:
 ⁼        -   equals    ('1'        or '0')
            ... i.e. for o='+' (OR) place any '0's at the right
                  or for o='.' (AND) place any '1's at the right
        Ṫ - tail ...get the right-most

```
> 5 votes

# Answer
# Retina 0.8.2, 27 bytes

```
0\+|\+0|1\.|\.1

(\d?)..
$1

```

Try it online! Link includes test cases. Explanation:

```
0\+|\+0|1\.|\.1

```

Rule 1: OR with 0 or AND with 1 returns the other parameter.

```
(\d?)..
$1

```

Rule 2: Return the first parameter if it's a digit. Rule 3: Otherwise, return the second parameter. Examples:

```
0+0 => 0 (by rule 1)    0.0 => 0 (by rule 2)
0+A => A (by rule 1)    0.A => 0 (by rule 2)
0+1 => 1 (by rule 1)    0.1 => 0 (by rule 1)
A+0 => A (by rule 1)    A.0 => 0 (by rule 3)
A+A => A (by rule 3)    A.A => A (by rule 3)
A+1 => 1 (by rule 3)    A.1 => 1 (by rule 1)
1+0 => 1 (by rule 1)    1.0 => 0 (by rule 1)
1+A => 1 (by rule 2)    1.A => A (by rule 1)
1+1 => 1 (by rule 2)    1.1 => 1 (by rule 1)

```
> 4 votes

# Answer
# Python, 36 bytes

```
lambda s:s[-("+."[s>"1"!=s[2]]in s)]

```

Attempt This Online!

#### How?

`s>"1"` due to lexicographic ordering this is the same as `s[0]>"0"` which is the same in both our "dream ordering" and actual string ordering.

`"1"!=s[2]` in standard ordering is `1>s[2]` in dream ordering.

Taken together this comprises the three cases where s\[0\]\>s\[2\] and one equal case which we don't care about.

It remains to xor that with which operator is given.

# Python, 40 bytes (@Jonathan Allan)

```
lambda s:sorted(s)[~("+."["0"in s]in s)]

```

Attempt This Online!

# Python, 41 bytes

```
lambda s:sorted(s)[s.find("+."["0"in s])]

```

Attempt This Online!

### How?

Ideally, we would like to have an ordering 0 \< variables \< 1. Then we could use `min` and `max` or similar. But in fact "0" \< "1" \< variables.

But, as we are are ranking only 2 values we can instead

* check if "0" is one of them
    + if yes: use normal string ordering
    + if no: use it up-side-down

Actual algorithm step-by-step:

sort input (standard string ordering). This puts the operator in front of the operands, so we need to select index 1 or -1. It so happens that these are the values find will return if we search the original string for either operator (-1 means not found, 1 is the original position of the operator). We choose which operator to test for depending on the above: whether "0" is in the input.
> 4 votes

# Answer
# Python 3.8+,  ~~46~~  45 bytes

```
lambda s:(c:='01'['+'in s])*(c in s)or max(s)

```

An unnamed function that accepts the string and returns a character.

**Try it online!**

### How?

When the operator is `'+'` (OR) we should return `'1'` if a `'1'` is present or a variable if present, otherwise we have `'0+0'` and should return `'0'`.

When the operator is `'.'` (AND) we should return `'0'` if a `'0'` is present or a variable if present, otherwise we have `'1.1'` and should return `'1'`.

The code implements this logic by constructing a character, `c`, which is `'0'` if the operator is `'+'` or `'0'` if the operator is `'.'` \- this is `(c:='01'['+'in s])` \- then repeating that character once if it is present in the input string or zero times (giving `''`) if not - this is `*(c in s)` \- we return this if it is non-empty otherwise we return the variable if present or the repeated, non-matching digit character - this is `or max(s)`.
> 3 votes

# Answer
# Vyxal, 9 bytes

```
sµ?Cg∷=;t

```

Try it Online!

Port of Jonathan Allan's Jelly answer, so upvote that!

```
sµ?Cg∷=;t
s         # Sort
 µ     ;  # Sort by:
  ?Cg     #  Minimum charcode of input
     ∷    #  Modulo two
      =   #  Equals the current item
        t # Last item

```
> 3 votes

# Answer
# x86-64 machine code, 17 bytes

```
66 AD 8A 16 A8 40 74 02 86 C2 9E 10 C4 0F 4A C2 C3

```

Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length of the string (which is always 3 and is ignored) in RDI and its address (as an array of single-byte ASCII characters) in RSI, and returns a value in AL.

In assembly:

```
f:  lodsw           # Load two bytes from the string into AL and AH, advancing the pointer.
    mov dl, [rsi]   # Load the next byte from the string into DL.
    test al, 0x40   # Check bit 6 of AL, which is 1 for letters and 0 for digits.
    jz s0           # Jump if the bit is zero.
    xchg dl, al     # (Otherwise: letters) Exchange DL and AL.
s0:             # At this point, AL must be a digit (as they can't be both letters).
    sahf            # Set flags based on AH (which holds the operation character).
                    # In particular, its low bit goes into CF.
    adc ah, al      # Add AL+CF to AH.
            # AH can be '+', 00101011 in binary, becoming 00101100 after adding CF=1,
            #        or '.', 00101110 in binary, staying  00101110 after adding CF=0.
            # AL can be '0' (00110000) or '1' (00110001).
            # Adding that in produces 010111xy, where x is 0 for '+' and 1 for '.',
            #                                     and y is 0 for '0' and 1 for '1'.
    cmovpe eax, edx # If the sum of the bits in the result is even,
                    #  which is true for (+,0) and (.,1), set EAX to EDX's value,
                    #  so that the other operand becomes the return value.
                    # Otherwise -- for (+,1) and (.,0) -- AL is kept unchanged.
    ret             # Return.

```
> 3 votes

# Answer
# Javascript, ~~130~~ 90 chars

```
s=>([x,y]=s[1]=="+"?'01':'10',t=[s[0],s[2]].sort(),s[0]==x&s[2]==x?x:t.includes(y)?y:t[1])

```

130 -\> 90 Thanks to @Steffan
> 2 votes

# Answer
# Java (JDK), 43 bytes

```
(x,o,y)->x==(o+=~o&4|2)|y==o?o:x==(o^1)?y:x

```

Try it online!

Taken as three characters, returning one character.
> 2 votes

# Answer
# Python3, ~~116~~ ~~103~~ 74 chars

```
lambda s:[[max(s),y:='01'[b:=s[1]<'.']][y in s],x:='10'[b]][s[0]==s[2]==x]

```

116 =\> 103 Thanks to @Unrelated String

103 =\> 74 Thanks to @Steffan, with a radically different answer
> 1 votes

# Answer
# Charcoal, 12 bytes

```
ＦＩ№θ+¿№θιι⌈θ

```

Try it online! Link is to verbose version of code. Explanation: Port of @JonathanAllan's Python answer.

```
ＦＩ№θ+

```

Count the number of `+`s in the input string, then cast that to string and loop over the character (golfy way of reusing the result as a variable).

```
¿№θι

```

If the input contains that digit, then...

```
ι

```

... output the digit, otherwise...

```
⌈θ

```

... output the letter if there is one, otherwise the other digit.
> 1 votes

# Answer
# Ruby, 32 bytes

```
->s{s[s=~/0\+|\+1|1\.|\.0/?2:0]}

```

Try it online!

If the expression contains one of `0+`, `+1`, `1.` or `.0`, then the result is the RHS, otherwise it's the LHS.

### Why?

First, let's discard the case where the first and third character is the same, in that case both are good. We are left with 8 cases to handle:

```
RHS cases:
0+X => X
X+1 => 1
X.0 => 0
1.X => X

LHS casaes:
X+0 => X
1+X => 1
0.X => 0
X.1 => X

```
> 1 votes

# Answer
# MathGolf, 9 bytes

```
s‼╞├$¥░=§

```

Try it online.

**Explanation:**

```
         #  (e.g. input1="R+0";      input2="A.0")
s        # Sort the (implicit) input-string
         #  STACK1: "+0R";           STACK2: ".0A"
 ‼       # Apply the following two commands separately on the same stack:
  ╞      #  Discard the left character
  ├      #  Extract the left character
         #   STACK1: "0R","0R","+";  STACK2: "0A","0A","."
   $     # Convert the top character to its codepoint integer
         #  STACK1: "0R","0R",43;    STACK2: "0A","0A",46
    ¥    # Modulo-2
         #  STACK1: "0R","0R",1;     STACK2: "0A","0A",0
     ░   # Convert it to a string
         #  STACK1: "0R","0R","1";   STACK2: "0A","0A","0"
      =  # Get the index of this character in the string (-1 if not found)
         #  STACK1: "0R",-1;         STACK2: "0A",0
       § # Modular 0-based index it into the string
         #  STACK1: "R";             STACK2: "0"
         # (after which the entire stack joined together is output implicitly as result)

```
> 1 votes

# Answer
# C (gcc), ~~72~~ 65 bytes

*-7 bytes thanks to @ceilingcat*

```
#define f(x)x[2*((*x-x[2]+((*x==49)-(x[2]==49))*91)*(x[1]-44)>0)]

```

Try it online!
> 0 votes

# Answer
# Haskell, 99 bytes

```
c i=fromEnum i+91*fromEnum(i=='1')
f x=toEnum$(if x!!1>'+'then min else max)(c$x!!0)(c$x!!2)`mod`91

```

Try it online!
> 0 votes

# Answer
# 05AB1E, 9 bytes

```
{ΣIÇßÉQ}θ

```

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

Try it online or verify all test cases.

**Explanation:**

```
{        # Sort the characters of the (implicit) input (based on codepoints)
 Σ       # Then (stable-)sort it further by:
  IÇ     #  Push the input as a list of codepoints
    ß    #  Pop and push the minimum
     É   #  Check if this is odd
      Q  #  Check if it's equal to the current character
         #  (a '0' for '+'; and a '1' for '.')
 }θ      # After the sort-by, leave the last character
         # (which is output implicitly as result)

```
> 0 votes

# Answer
# Haskell, 60 bytes

```
f(a:o:b)|a<'1'||b=="1",o<'.'=b|a=='1'||b<"1",o>'+'=b|1>0=[a]

```

Try it online!

Inspired by @G B answer
> 0 votes

# Answer
# T-SQL, 59 bytes

input is a table

```
SELECT iif(a+b+c in(a+'+0',a+'.1','1+'+c,'0.'+c),a,c)FROM @

```

**Try it online**

# T-SQL, 77 bytes

input is char(3) - which is kind of a string in sql

```
PRINT stuff(@,iif(right(@,2)in('+1','.0')or
left(@,2)in('1.','0+'),1,2),2,'')

```

**Try it online**
> 0 votes

# Answer
# GNU sed -r, 33

```
s/0\+|\+0|1\.|\.1//
s/(\d)?../\1/

```

I golfed this myself, *honest*. Though in reality it turns out to be a simple port of @Neil's answer.

Try it online!
> 0 votes

# Answer
# Scala, 108 bytes

Port of @AZTECCO's Haskell answer in Scala.

Golfed version. Try it online!

```
z=>if(z(0)<'1'||z(2)=='1')if(z(1)<'.'||z(0)=='1'&&z(1)>'+'||z(2)<'1')z(2).toString else"1"else z(0).toString

```

Golfed version. Try it online!

```
def f(Z: String): String = {
  val a = Z(0)
  val o = Z(1)
  val b = Z(2)

  if (a < '1' || b == '1') {
    if (o < '.') b.toString
    else if (a == '1' || b < '1') {
      if (o > '+') b.toString
      else "1"
    } else a.toString
  } else a.toString
}

```
> 0 votes

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


title: The Add-Multiply-Add Sequence

text:
# Question
Title: The Add-Multiply-Add Sequence
*(Related)*

Given an integer `n > 1`,
1) Construct the range of numbers `n, n-1, n-2, ... 3, 2, 1` and calculate the sum
2) Take the individual digits of that number and calculate the product
3) Take the individual digits of *that* number and calculate the sum
4) Repeat steps 2 and 3 until you reach a single digit. That digit is the result.

The first twenty terms of the sequence are below:

```
3, 6, 0, 5, 2, 7, 9, 2, 7, 9, 1, 9, 0, 0, 9, 6, 7, 0, 0, 6

```

Note: This sequence is NOT in OEIS.

## I/O and Rules

* Numbers will get very large quickly, so the solution must be able to handle input numbers up to 100,000 without failure (it's fine if your code can handle past that).
* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

## Examples

```
n     output
1234   9
3005   3
5007   5
9854   8
75849  8
100000 0

```

# Answer
# Python 2, ~~77~~ ~~72~~ ~~71~~ ~~62~~ 60 bytes

```
lambda n:reduce(lambda x,c:eval(c.join(`x`)),'*+'*n,-n*~n/2)

```

*Thanks to @xnor for golfing off 2 bytes!*

Try it online!
> 10 votes

# Answer
# 05AB1E, 7 bytes

```
LOΔSPSO

```

Try it online!

**Exlpanation**

```
L         # push range [1 ... input]
 O        # sum range
  Δ       # loop until top of stack stops changing
   SP     # product of digits
     SO   # sum of digits

```
> 8 votes

# Answer
# Jelly, 8 bytes

```
RSDPDƲÐL

```

Try it online!

Full program (it returns a singleton array containing the result, but the brackets aren't visible in STDOUT).
> 4 votes

# Answer
# MATL, ~~15~~ 13 bytes

In tribute to the Language of the month:

```
:`sV!UpV!Utnq

```

Try it online!

I don't think there's a simpler way to get the digits of a number than to convert the number to a string `V`, then transposing it `!`, and converting this vertical vector back to a numeric one `U`.

Saved 2 bytes thanks to the Creator1 himself! I forgot the implicit end, meaning I could remove `]`, and instead of comparing the number of elements with `1`, I could simply decrement that value and use it as a boolean directly.

So, the explanation goes like this:

```
                 % Grab input n implicitly
:                % Range from 1 ... n inclusive
 `               % Do ... while
  s               % sum the vector
   V!U            % Convert the number to digits
      p           % Take the product of these digits
       V!U        % Convert the product into digits
          t       % Duplicate the result
           n      % Count the number of elements
            q     % Decrement the number of elements
                  % Loop until the number of elements is 1
                 % Implicit end

```

1... of MATL, Luis Mendo.
> 4 votes

# Answer
# JavaScript (ES6), 60 bytes

```
f=(n,k=n*++n/2)=>k>9?f(!n,eval([...k+''].join('*+'[+!n]))):k

```

Try it online!

### Commented

```
f = (                     // f = recursive function taking:
  n,                      //   n = original input
  k = n * ++n / 2         //   k = current value, initialized to sum(i=1..n)(i)
) =>                      //
  k > 9 ?                 // if k has more than 1 digit:
    f(                    //   recursive call to f() with:
      !n,                 //     a logical NOT applied to n
      eval(               //     the result of the expression built by:
        [...k + '']       //       turning k into a list of digits
        .join('*+'[+!n])  //       joining with '*' on even iterations or '+' on odd ones
      )                   //     end of eval()
    )                     //   end of recursive call
  :                       // else:
    k                     //   stop recursion and return the last value

```

---

# Alternate version, 59 bytes (non-competing)

A non-recursive version that only works for **n \< 236172**. (It covers the requested range but does not qualify as a valid generic algorithm.)

```
n=>[...'*+*+'].map(o=>n=eval([...n+''].join(o)),n*=++n/2)|n

```

Try it online!
> 3 votes

# Answer
# Haskell, ~~72~~ 71 63 bytes

```
g=map(read.pure).show
f n=until(<10)(sum.g.product.g)$sum[1..n]

```

Thanks to @BMO for a byte and @nimi for 8 bytes!

Try it online!
> 3 votes

# Answer
# Stax,  ~~14~~   ~~13~~  10 bytes

```
ñu┌↕a√äJ²┐

```

Run and debug it

Was pretty fun to make. I wonder if there is a more concise way to do the comparison at the end.

**Explanation**

```
|+wE:*E|+c9>                 # Full Program Unpacked
|+                           # Create range and sum it
   wE:*                      # Start loop, digitize number, product of digits
       E|+                   # Digitize number, sum digits
          c9>                # Duplicate, check length is = 1
                             # Otherwise loop back to the 'w' character

```

-1 bytes thanks to ovs

-3 bytes thanks to Scrooble
> 2 votes

# Answer
# , ~~152 130~~ 109 bytes

```
function(w,x=w*(w+1)/2,y=prod(d(x)),z=sum(d(y)))"if"(z>9,f(,z),z)
d=function(x)x%/%10^(0:max(0,log10(x)))%%10

```

Try it online!

@Giuseppe found ~~21~~ 42 bytes with various R things I'm not used to yet, along with a way to get the digits of a number without coercing to string and back, and with fewer bytes!

```
# Old
d=function(x)strtoi(el(strsplit(paste(x),"")))
# New
d=function(x)x%/%10^(0:max(0,log10(x)))%%10

```

`options(scipen=9)` ~~is~~ was required for the case of 9854 for the old function, because the first product stage ends up as 80000, which R prints as 8e+05.
> 2 votes

# Answer
# APL (Dyalog Unicode), 16 bytes

-4 thanks to @user

```
f←{⍎¨⍕×/⍎¨⍕+/⍵}⍣≡⍳

```

Try it online!
> 2 votes

# Answer
# Husk, 7 bytes

```
ωöΣdΠdΣ

```

Try it online!
> 1 votes

# Answer
# Pyth, 11 bytes

```
usj*FjGTTsS

```

Try it here!

```
usj*FjGTTsS – Full program. N = The input.
          S – Range. Yield [1, N] ⋂ ℤ.
         s  – Sum.
u           – While no two consecutive iterations yield the same result, do (var: G):
   *FjGT    – Digital product.
 sj     T   – Digital sum.

```
> 1 votes

# Answer
# Gaia, 8 bytes

```
┅⟨Σ₸∨Π⟩°

```

Try it online!

The old explanation (before fixing a bug that is Gaia’s fault IMO :P):

```
┅⟨ΣΠ⟩° – Full program. N = The input.
┅      – Range. Push [1, N] ⋂ ℤ to the stack.
 ⟨  ⟩° – While no two consecutive iterations yield the same result, do:
  Σ    – Sum (or digital sum, when applied to an integer).
   Π   – Digital product.

```

Saved 1 byte thanks to Dennis.
> 1 votes

# Answer
# Japt, ~~16~~ ~~14~~ 13 bytes

```
_ì ×ìx}gN®õ x

```

Try it

---

## Explanation

```
                  :Implicit input of integer U
         ®        :Map
        N         :The array of inputs (which just contains U)
          õ       :  Range [1,U]
            x     :  Reduce by addition
_     }g          :Take the last element of N, run it through the following function and push the result to N
                  : Repeat U times and then return the last element of N
 ì                :  Split to an array of digits
   ×              :  Reduce by multiplication
    ìx            :  Split to an array of digits and reduce by addition

```
> 1 votes

# Answer
# Charcoal, 18 bytes

```
≔Σ…·¹ＮθＷ›θ⁹≔ΣΠθθＩθ

```

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

```
≔Σ…·¹Ｎθ

```

Sum the integers up to the input.

```
 Ｗ›θ⁹≔ΣΠθθ

```

While the result is greater than 9, take the sum of digits of the product of digits.

```
Ｉθ

```

Cast the result to string and implicitly print it.
> 1 votes

# Answer
# Ruby, 57 bytes

```
->n{("*+"*n).chars.reduce(-~n*n/2){|x,y|eval x.digits*y}}

```

Try it online!
> 1 votes

# Answer
## F#, 175 bytes

```
let d n=seq{for i in(string n).ToCharArray() do yield string i|>uint64}
let c n=
 let mutable r=Seq.sum{1UL..n}
 while r>9UL do r<-d r|>Seq.reduce(fun a x->x*a)|>d|>Seq.sum
 r

```

Try it online!

The only caveat to the function is that the input value must be of type `uint64`.

Ungolfed it's a little like this:

```
let d n=seq{for i in(string n).ToCharArray() do yield string i|>uint64}

let c n =
 let mutable r = Seq.sum {1UL..n}
 while r > 9UL do
  r<-d r
  |> Seq.reduce(fun a x->x*a)
  |> d
  |> Seq.sum
 r

```

The function `d n` converts the number `n` into its component digits. It first converts to a string, then gets each character in the string. Each character must then be converted back into a string, otherwise the characters will be converted to their ASCII values instead of their "real" values.

The `c n` function is the main function, with `n` as the initial value. In this function `r` is our running value. The `while` loop does the following:

* Convert `r` into its component digits (`d r`).
* Get the product of all those digits. This uses `Seq.reduce` which takes a function with the accumulated value (`a`) and the next value in the sequence (`x`) and in this case returns the product. The initial value is the first element in the sequence.
* Convert this product value into its component digits (`d`).
* Sum the digits from before, and assign this to `r`.
> 1 votes

# Answer
# Befunge, 136 bytes

```
101p&::*+2/>:82+%01g*01p82+/:#v_$01gv
X      v_v# #:/+82p10+g10%+82: <p100<
v:g10$ >#<#^                 #<^
>82+/#v_.@
      >101p^

```

You can try it here.

While not all interpreters have a large enough cell size, it works with small numbers for pretty much anyone out there. For a larger number of `n` you might need a interpreter like BefunExec.
> 1 votes

# Answer
# Gol\>\<\>, ~~35~~ 33 bytes

```
1AY:P*2,TYMR*YR+:a(?Bt
:a(qlBaSD$

```

Try it online!

-2 bytes by Jo King.

Extensive use of functions and implicit infinite loops.

### Example full program & How it works

```
1AGIE;GN
2AY:P*2,YlMR*YlR+:a(?B8R!
:a(?BaSD$

<main program>
1AG       Register row 1 as function G
   IE;    Take number input; halt on EOF
      GN  Call G and print the result as number
          Repeat indefinitely

<function G>
2AY            Register row 2 as function Y
   :P*2,       Sum of 1 to n
        Y      Call Y (break into digits)
         lMR*  Product
Y              Call Y
 lR+           Sum (an implicit zero is used)
    :a(?B      Return if the result is less than 10
         8R!   Skip initial 8 commands
               Repeat indefinitely

<function Y>
:a(?B      Return if the top is less than 10
     aSD   Divmod by 10; [... n] => [... n/10 n%10]
        $  Swap top two, so the "div" goes to the top

```
> 1 votes

# Answer
# PHP 7, 89 bytes

```
for($a=$argn*-~+$argn/2;$a>9;)$a=array_sum(($s=str_split)(array_product($s($a))));echo$a;

```

Run as pipe with `-r` or try it online.

* PHP always takes input as string, so I have to use `+` to cast to int for `~` to work as wanted.
* Pre-increment would not work: no matter where I put it, it would effect both operands.
* But: It doesn´t matter if the single digit takes place before or after the iteration (additional iterations wouldn´t change a thing); so I can use `for()` instead of `do ... while()`.
* PHP 7 or later is required for the inline assignment of the function name.
Older PHP requires one more byte: `for($s=str_split,$a=...;$a>9;)$a=array_sum($s(...));`
(Not assigning `str_split` to a variable at all would waste another byte.)
> 0 votes

# Answer
# Tcl, 118 bytes

```
proc S n {set r [expr $n*($n+1)/2]
while \$r>9 {set r [expr [join [split [expr [join [split $r ""] *]] ""] +]]}
set r}

```

Try it online!
> 0 votes

# Answer
# PowerShell Core, 91 101 93 bytes

```
Function F($a){$o=$a*($a+1)/2;1,2|%{$o=[char[]]"$([char[]]"$o"-join'*'|iex)"-join'+'|iex};$o}

```

Try it online!

Ungolfed a little...

```
Function F ($a)
{
    $o=$a*($a+1)/2;
    1..2 | % {
        $o = [char[]]"$o"-join '*' | iex;
        $o = [char[]]"$o"-join '+' | iex;
    }
    $o | Write-Output
}

```

First steps were to split the integers into digits -- did this by splitting the integer into an array of stringscharacters. Afterwards, insert the operand, and then evaluate the string as a command. Then, it's a matter of doing the multiple-add cycle until the input is one digit.

`iex` is an alias for `Invoke-Command` which evaluates a string passed into the first param position.

Edit: As requested by @AdmBorkBork, I have added a function header to the byte count. Also, I did a little math and realized that an upper bound on the number of iterations is `< log log 10^6 < log 6 < 2`, so that saved another six bytes.

Edit x2: @AdmBorkBork found a more terse way of converting the integer into a math expression, and then suggested piping it into `iex`. This saved 8 bytes. Thank you!
> 0 votes

# Answer
# Perl 6, 49 bytes

```
{($_*.succ/2,{[+] ([*] .comb).comb}...9>=*).tail}

```

Try it online!
> 0 votes

# Answer
# Perl 5 `-p`, 61 bytes

```
$_*=$_/2+.5;$_=eval((eval s/./$&*/gr.1)=~s/./+$&/gr)while$_>9

```

Try it online!
> 0 votes

# Answer
# Java 8, 129 bytes

```
n->{long r=1,i=n;for(;i>1;r+=i--);for(;r>9;r=(i+"").chars().map(p->p-48).sum(),i=1)for(int s:(r+"").getBytes())i*=s-48;return r;}

```

Try it online.

**Explanation:**

```
n->{            // Method with integer parameter and long return-type
  long r=1,     //  Result-long, starting at 1
       i=n;     //  Temp integer, starting at the input `n`
  for(;i>1;     //  Loop as long as `i` is not 1 yet
      r+=i--);  //   And increase `r` by `i`
  for(;r>9      //  Loop as long as `r` is not a single digit yet
      ;         //    After every iteration:
       r=(i+"").chars().map(p->p-48).sum(),
                //     Set `r` to the sum of digits of `i`
       i=1)     //     And reset `i` to 1
    for(int s:(r+"").getBytes())i*=s-48;
                //    Set `i` to the product of the digits of `r`
  return r;}    //  Return `r` as result

```
> 0 votes

# Answer
# Julia 0.6, 56 bytes

```
f(n,k=(n+1)n÷2)=k>9?f(0,sum(digits(prod(digits(k))))):k

```

Try it online!

Pretty straightforward: calculate `(n+1)n÷2` for sum from 1..n, check if it's a single digit number (`>9`), if it's not, try again with k set to the sum of the digits of the product of the digits of k, else return k.
> 0 votes

# Answer
# J-uby, 38 bytes

This is me resisting forking J-uby to add a bunch of single-character aliases for useful functions.

```
:+|:sum|:!~&((d=:digits)|:/&:*|d|:sum)

```

Attempt This Online!

## Explanation

```
:+ | :sum | :!~ & ((d = :digits) | :/ & :* | d | :sum)

:+ | :sum |                                             # Range 1..n, then sum, then
            :!~ & (                                  )  # Until a fixed point is reached...
                  ((d = :digits) |                      #   Get digits (while saving the function to d for later), then
                                   :/ & :* |            #   Reduce with product, then
                                             d | :sum   #   Get digits, then sum

```
> 0 votes

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


title: Move my liquid to make me equal

text:
# Question
Title: Move my liquid to make me equal
You are given 4 positive integers: volume of the first container (`v1`), volume of the second container (`v2`), volume of the liquid in the first container (`l1`), and volume of the liquid in the second container (`l2`). Your task is to move some of the liquid from container 1 to container 2, making the amount of empty space in the containers equal to each other, outputting how much liquid should be moved.

## An example

Here is an example of some possible input (formatted for the ease of test cases. The input isn't formatted.):

```
8 11
6  5

```

Here, you need to make sure that the differences between the volumes and the containers are equal. Currently the difference is not equal:

```
  8 11
- 6  5
======
   6 2

```

So we need to try to make them equal, by taking some of the values in one container to another container:

```
  8 11
- 4  7
======
  4  4

```

After you have succeeded, output how much liquid you need to take from container 1 to container 2. Therefore the above example should output `2`.

## Test cases

```
15 16
 9  2

```

We move into this state:

```
 15 16
- 5  6
======
 10 10

```

Therefore `4` is the expected result.

## Test case #2

```
16 12
13  1

```

We move into this state:

```
 16 12
- 9  5
======
  7  7

```

Therefore `4` is the expected output.

## Test case #3

```
20 12
10 2

```

Moved:

```
 20 12
-10 2
======
 10 10

```

Therefore `0` is the expected output.

## More test cases

(They don't have explanations as this should be quite clear)

```
12 5
9  0 -> 1

9 11
7  3 -> 3

```

## Rules

* The test cases will be made so that the result is always possible as a positive integer. The result will **never** be a decimal.
* Input can be taken in any convenient and reasonable format.
* Output can be given in any convenient and reasonable format.
* The input string will be made so that a moving is always possible without involving decimals or negative numbers. Also there will not be more liquid than how much a container can hold.
* Of course, this is , so the answer in each language consisting of the fewest number of bytes wins. Happy golfing!
* An extra restriction for the test cases: you can assume that there is always going to be space available in the second container. So a test case like this:

```
10 2
 2 2

```

is not going to be a valid testcase.

# Answer
# JavaScript (ES6) / C#, 21 bytes

```
(v,V,q,Q)=>V-Q-v+q>>1

```

Try it online! (JS)

Try it online! (C#)
> 8 votes

# Answer
# 05AB1E, 3 bytes

```
®β;

```

Try it online!

Input is an array of volumes in the order \[first liquid, first container, second container, second liquid\].

Alternative 3-byter:

```
ÆÆ;

```

Try it online!

Input is a nested array: \[\[first container, first liquid\], \[second container, second liquid\]\].
> 6 votes

# Answer
# Jelly, 3 bytes

```
ISH

```

Try it online!

A monadic link taking as its argument `[[l1, v1], [v2, l2]]` and returning the volume needed to move.

A relatively rare ASCII-only Jelly answer!

## Explanation

```
I   | Increments
 S  | Sum
  H | Half

```
> 4 votes

# Answer
# Keg, ~~14~~ 13 bytes

```
-±¿-¿+½:0<[±]

```

Try it online!

A port of Arnauld's original javascript answer. Takes input in form of:

```
volume1
container1
volume2
container2

```

*-1 byte by utilising implicit input correctly.*
> 2 votes

# Answer
# ~~Perl 6~~ Raku, ~~12~~ 11 bytes

```
(*-*-*+*)/2

```

Try it online!

Edit: I realized that I could take the parameters in any order. Four parameters are: liquid in container 1, liquid in container 2, volume of container 1, volume of container 2.
> 2 votes

# Answer
# Java 8 / CoffeeScript 2, ~~22~~ 21 bytes

```
(V,v,L,l)->v-l-V+L>>1

```

Port of *@Grimmy*'s second 05AB1E answer.
-1 byte by porting @Arnauld's approach, golfing the `(...)/2` I had to `...>>1`.

Try it online in Java 8.
Try it online in CoffeeScript 2.

**Explanation:**

```
(V,v,L,l)->    // Method with four integer parameters and integer return-type
   v-l         //  Calculate the difference between the volume and liquid of container 1
      -V+L     //  Subtract the difference between the volume and liquid of container 2
          >>1  //  Divide that result by 2 (by bit-shifting once towards the right)

```
> 1 votes

# Answer
# Whitespace, 79 bytes

```
[S S S N
_Push_0][S N
S _Dupe_0][T    N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input_vol1][S N
S _Dupe_input_vol1][S N
S _Dupe_input_vol1][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input_liq1][T S S T   _Subtract_vol1-liq1][S N
S _Dupe_vol1-liq1][S N
S _Dupe_vol1-liq1][T    N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input_vol2][S N
S _Dupe_input_vol2][S N
S _Dupe_input_vol2][T   N
T   T   _Read_STDIN_as_integer][T   T   T   _Retrieve_input_liq2][T S S T   _Subtract_vol2-liq2][T  S S T   _Subtract_(vol1-liq1)-(vol2-liq2)][S S S T  S N
_Push_2][T  S T S _Integer_divide_((vol1-liq1)-(vol2-liq2))/2][T    N
S T _Print_as_integer]

```

Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.

Try it online (with raw spaces, tabs and new-lines only).

**Explanation in pseudo-code:**

```
Integer vol1 = STDIN as integer
Integer liq1 = STDIN as integer
Integer vol2 = STDIN as integer
Integer liq2 = STDIN as integer
Integer diff1 = vol1 - liq1
Integer diff2 = vol2 - liq2
Integer diffOfDiff = diff1 - diff2
Integer result = diffOfDiff / 2
Print result as integer to STDOUT

```

Since the integers are guaranteed to be positive, it uses them as heap-address for the next input in line with some duplicates, saving bytes.
> 1 votes

# Answer
# Excel, 16 bytes

```
=(B1-D1-A1+C1)/2

```

Same approach as others
> 1 votes

# Answer
# Python 3, ~~27~~ ~~26~~ 25 bytes

Saved a bytes thanks to meetaig!!!

```
lambda a,b,c,d:b-d-a+c>>1

```

Try it online!
> 1 votes

# Answer
# C (clang), ~~29~~ 28 bytes

Saved a bytes thanks to meetaig!!!

```
#define f(a,b,c,d)b-d-a+c>>1

```

Try it online!
> 1 votes

# Answer
# C (gcc), ~~39~~ 25 bytes

```
f(a,b,c,d){a=b-d-a+c>>1;}

```

Wrote a testing framework for possible future testcases.

Takes as input 4 integers:

* `a`: capacity of first container
* `b`: capacity of second container
* `c`: amount of liquid in first container
* `d`: amount of liquid in second container

Explanation:

```
f(a,b,c,d)

```

Function implicitly returning `int` with four arguments of type `int`.

```
a=

```

A sort of `return` that exploits GCC's code generation when compiling without optimization.

```
b-d-a+c>>1

```

The main algorithm. There's several steps involved here:

* `b-d`: Subtract the amount of liquid in the second container from the capacity in the second container to get the free space in the second container.
* `-a+c`: Subtract the capacity of the first container and add back the amount of liquid in the second container to get the total free space in both.
* `>>1` After that, divide the amount of free space in both by 2 to get the amount of liquid to move from container one to container two. This is a binary right shift and binary is base 2, so it is equivalent to division by 2 but removes the need for parentheses as the operator precedence of `>>` is lower than that of `+` and `-`. The operator precedence for `/` is higher than that of `+` and `-` so it would require extra parentheses.

Try it online!
> 1 votes

# Answer
# AWK, ~~21~~ 20 bytes

```
1,$0=($2-$4-$1+$3)/2

```

Try it online!
> 1 votes

# Answer
# Retina 0.8.2, 19 bytes

```
\d+;?
$*
+`1,1
,
11

```

Try it online! Link includes test cases. Explanation:

```
\d+;?
$*

```

Convert to unary and sum the middle two numbers.

```
+`1,1
,

```

Subtract the outer numbers from that sum.

```
11

```

Divide by 2 and convert to decimal.
> 0 votes

# Answer
# TI-BASIC, ~~26~~ 21 bytes

```
Prompt A,B,C,D:.5abs(A-C-B+D

```

Input is a series of prompts for each value. A = volume1 B = volume2 C = liquid1 D = liquid2

Output is the amount of liquid that needs to be moved from the fuller container to the emptier one.

**Explantion:**

```
Prompt A,B,C,D     ;Prompt the user to input the values
.5abs(A-C-B+D      ;Compute the amount of liquid needed, convert it
                   ;  to a positive number if need be and leave the
                   ;  result in Ans
                   ;Implicit print of Ans

```

**Examples:**

```
prgmCDGF21

A=?15
B=?16
C=?9
D=?2
                   4
prgmCDGF21

A=?11
B=?10
C=?6
D=?7
                   1

```

**Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count.
> 0 votes

# Answer
# Brainf\*ck, 39 bytes

Try it online!

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

```

The input/output are the ASCII values of characters. Using "aaz0" gives "%" as output, as it corresponds to the case

```
97 122

97  48

```

which is solved by moving 37 units of liquid, the % symbol.

Could shave a couple of bytes if the input order could be rearranged, but not sure if that would be acceptable.
> 0 votes

# Answer
# J-uby, 13 bytes

Port of Nick Kennedy's Jelly answer. Takes input in format `[[v1, l1], [l2, v2]]`.

```
+:-**:+|~:/&2

```

Attempt This Online!

## Explanation

```
+:- ** :+ | ~:/ & 2

    **               # Map arguments with...
+:-                  #   Splat pair of elements onto :- (subtract)

       :+ |          # Add, then
            ~:/ & 2  # Divide by 2

```
> 0 votes

---
Tags: code-golf, arithmetic, integer
---


# Question
Title: Tips for improving your score in fastest code challenges
Fastest code is a scoring method on this site where the goal is to write code that is as fast as possible.

From the tag wiki:

> The winner of a fastest-code challenge is determined by the runtime performance of the submissions. For fairness, all submissions should be benchmarked on the same machine, which usually means all submissions have to be tested by the host of the challenge. Alternatively, the submission can be compared to a reference program. For scoring by asymptotic time complexity, use instead.

What general tips do you have for making solutions more competitive at ? One tip per answer, please. Tips should ideally be broadly applicable, not language-specific.

# Answer
# Use a fast hashing algorithm for your hashmap

Your language's default hashing algorithm is not always the fastest.

I'll focus on Rust, because it's the only fast language I'm familiar with. But the same applies to other languages.

## Rust

Rust's default hashing algorithm is SipHash 1-3, which is high-quality, but relatively slow. Since HashDos attacks are not a concern for challenges, you can try the hashing algorithms from the following crates:

* FxHash from `rustc-hash`. This is the hashing algorithm used by the Rust compiler. It is low-quality (so be careful when using it in real-world applications) but extremely fast. It is usually the fastest for small types with a fixed size, like `u32` and `u64`.
* AHash from `ahash`. This hashing algorithm uses the hardware's AES instruction set when available. It is both high-quality and fast. It is usually faster than FxHash for more complex types like `String` and `Vec`.

You should try both and see which one is faster for your use case.

Both crates provide drop-in replacements for `std::collections::HashMap` and `std::collections::HashSet`: `FxHashMap` and `FxHashSet` from `rustc-hash`, and `AHashMap` and `AHashSet` from `ahash`. Please read the documentation for each crate to see how to use them.

The documentation for `ahash` also contains a comparison between common hashing algorithms.

## Other languages

wyhash and xxHash are two fast hashing algorithms I've heard of. They are written in C but ported to many other languages. Please see wyhash's README and this list for xxHash.

There might be other fast hashing algorithms that I'm not aware of.
> 10 votes

# Answer
## Avoid Allocations

Allocating memory is slow. Often you can substantially improve performance by pre-allocating memory. Note that allocation is not just manually calling `malloc` or `new`, but many data structures internally allocate memory.

Consider for example this code:

```
fn main() {
    for i in 0..1000000 {
        let mut a:Vec<u32> = vec![];
        let mut b = 3;
        for i in 0..1000 {
            b+=b/2;
            a.push(b);
        }
        println!("{}",a[999]);
    }
}

```

This uses a `Vec` which will dynamically allocate memory. Multiple times each time the vector grows. On my machine this takes 2854 ms.

You can make this more efficient with static allocations:

```
fn main() {
    for i in 0..1000000 {
        let mut a = [0u32;1000];
        let mut b = 3;
        for i in 0..1000 {
            b+=b/2;
            a[i]=b;
        }
        println!("{}",a[999]);
    }
}

```

This uses a static array of 1000 elements. No allocations needed. This takes 2789ms on my machine. A small difference but a significant one. Difference can be a lot bigger with less optimized data structures.
> 9 votes

# Answer
Here are a couple of tricks I've found that can help:

## Bit Shifting

Instead of dividing (slow) you can *sometimes* replace the operation with a **bit shift**

```
1024 >> 1     // 512

```

This has the same effect as `Math.floor( x / 2.0 )`

## Loop Unrolling

> Loop unrolling, also known as loop unwinding, is a loop transformation technique that attempts to optimize a program's execution speed at the expense of its binary size, which is an approach known as space–time tradeoff. The transformation can be undertaken manually by the programmer or by an optimizing compiler. Wikipedia

```
for (int i=0; i<=5; i++) {
   printf("%d", i);
}

```

becomes:

```
printf("%d", 0);
printf("%d", 1);
printf("%d", 2);
printf("%d", 3);
printf("%d", 4);
printf("%d", 5);

```

## Avoid Division

Similar to the approach with **bit shifting** avoid costly division by using mathmatics:

```
x / 3.0 == 5.5

```

multiply both sides by a factor of 3.0 to remove the division

```
x == 15.5

```

or alternatively instead of using `sqrt()` use `pow()` if applicable

```
Math.sqrt(x) == 5

x == 25

```

## Branch Prediction

> In computer architecture, a branch predictor\[1\]\[2\]\[3\]\[4\]\[5\] is a digital circuit that tries to guess which way a branch (e.g., an if–then–else structure) will go before this is known definitively. The purpose of the branch predictor is to improve the flow in the instruction pipeline. Branch predictors play a critical role in achieving high performance in many modern pipelined microprocessor architectures such as x86. Wikipedia

This one will be highly dependent on the machine you are running your code, as well as if it has been compiled / optimized already, but generally the more homogenous the data or operations are, the faster:

```
function checkIfValueLessThanHalf(value) {
  if (value < 0.5) {
      return true
  } else {
      return false
  }
}

function checkIfValueLessThanHalfOptimized(value) {
    return value < 0.5
}

// random array filled with unsorted numbers
const unsorted = Array(10 ** 6).fill().map((_) => Math.random())

// same array but sorted
const sorted = [...unsorted].sort()

// run method on unsorted data
console.time()
unsorted.filter(checkIfValueLessThanHalf)
console.timeEnd()

// run method on sorted data
console.time()
sorted.filter(checkIfValueLessThanHalfOptimized)
console.timeEnd()
```

The above example isn't necessarily faster (because you need to include the `.sort()` operation, but depending on the data set size and cost of sorting this can change.

*Note: running the code snippet above sequentially may produce different output as the V8 engine is doing optimizations under the hood as well, below are the two different code snippets which can be run in different contexts*:

Try it online! (unsorted & if/else)

Try it online! (sorted & logical return)

Which return roughly `59.859ms` and `35.960ms` respectively for me over several runs.

## Notable Mention

This is one of my favorite examples which was used in Quake which incorporates some ingenious tricks to derive approximations which worked for their use case:

Fast inverse square root method
> 5 votes

# Answer
# Asynchronous execution

### Note: some languages have this behaviour built in, like JavaScript.

Asynchronous programming is useful when you have two expensive operations, since they can be done at the same time. To give a primitive analogy of this:

> You have two tasks:
>
> * Wash clothes in the washing machine.
> * Wash the dishes.
>
> Without asynchronous programming, you would have something like this:
>
> ```
> wash_clothes()
> wash_dishes()
>
> ```
>
> In this example, you would put the clothes in the washing machine, wait for the washing machine to be done, and only then wash the dishes! That's very inefficient, isn't it?
>
> ---
>
> However, with asynchronous programming, you would have something like this:
>
> ```
> await wash_clothes()
> wash_dishes()
>
> ```
>
> In this example, you would put the clothes in the washing machine, and you would wash the dishes while the washing machine is washing the clothes. Much more efficient!

As you can see, it can speed up code execution time.

---

A real world example is scraping from two websites and printing the HTML content of both. Without asynchronous programming, you would have to wait for one request to be finished before doing the other, but with asynchronous programming, you can send a request to the second website before the first website's request is finished!

---

## Edit

Mousetail left a few comments saying that this only works well for IO-focused challenges and that multithreading is often quicker.
> 1 votes

---
Tags: tips, fastest-code
---


title: Parse a Unicode vulgar fraction

text:
# Question
Title: Parse a Unicode vulgar fraction
# Objective

Given a string with single Unicode vulgar fraction, parse it to a rational number.

# Valid inputs

A valid input is one of:

* `¼` U+00BC; one quarter
* `½` U+00BD; one half
* `¾` U+00BE; three quarters
* U+2150; one seventh
* U+2151; one ninth
* U+2152; one tenth
* U+2153; one third
* U+2154; two thirds
* U+2155; one fifth
* U+2156; two fifths
* U+2157; three fifths
* U+2158; four fifths
* U+2159; one sixth
* U+215A; five sixths
* U+215B; one eighth
* U+215C; three eighths
* U+215D; five eighths
* U+215E; seven eighths
* (U+215F; fraction numerator one) followed by ASCII decimal digits (U+0030 – U+0039)
* ASCII decimal digits followed by (U+2044; fraction slash) followed by ASCII decimal digits

There are exceptions. See below.

# Invalid inputs

If the denominator is zero, the parser must fall in an erroneous state. This includes:

* Monadic failing
* Returning an erroneous value
* Throwing an error

# Rules

1. Encoding of the input doesn't matter.
2. Output type and format doesn't matter either. Though native rational number type is preferred, a pair of integers is permitted.
3. Inputs that are neither valid nor invalid fall in *don't care* situation. This includes:

* Whole numbers
    * Improper fractions
    * Reducible fractions
    * Fractions with zero numerator
    * Negative fractions

# Examples

(U+215B) parses to one eighth.

`⅟13` (U+215F U+0031 U+0033) parses to one thirteenth.

`24⁄247` (U+0032 U+0034 U+2044 U+0032 U+0034 U+0037) parses to twenty-four 247ths.

`1⁄7` (U+0031 U+2044 U+0037) parses to one seventh. Note that  and `⅟7` will parse to the same.

`0` (U+0030) falls in *don't care* situation. It's a whole number.

`9⁄8` (U+0039 U+2044 U+0038) falls in *don't care* situation. It's an improper fraction.

`4⁄8` (U+0034 U+2044 U+0038) falls in *don't care* situation. It's reducible to one half.

(U+2189) falls in *don't care* situation. Its numerator is zero.

(U+002D U+00BD) falls in *don't care* situation. It is negative.

`1⁄0` (U+0031 U+2044 U+0030) must make the parser be in erroneous state. Its denominator is zero.

# Ungolfed solution

## Haskell

```
import Control.Monad
import Data.Ratio
import Text.ParserCombinators.ReadP as ReadP
import Text.Read
import Text.Read.Lex

fractionParser :: ReadP Rational
fractionParser = choice [
    char '¼' >> return (1 % 4),
    char '½' >> return (1 % 2),
    char '¾' >> return (3 % 4),
    char '⅐' >> return (1 % 7),
    char '⅑' >> return (1 % 9),
    char '⅒' >> return (1 % 10),
    char '⅓' >> return (1 % 3),
    char '⅔' >> return (2 % 3),
    char '⅕' >> return (1 % 5),
    char '⅖' >> return (2 % 5),
    char '⅗' >> return (3 % 5),
    char '⅘' >> return (4 % 5),
    char '⅙' >> return (1 % 6),
    char '⅚' >> return (5 % 6),
    char '⅛' >> return (1 % 8),
    char '⅜' >> return (3 % 8),
    char '⅝' >> return (5 % 8),
    char '⅞' >> return (7 % 8),
    char '⅟' >> do
        d <- readDecP
        guard (0 /= d)
        return (1 % d),
    do
        n <- readDecP
        char '⁄'
        d <- readDecP
        guard (0 /= d)
        return (n % d)
    ]

```

# Answer
# Raku, 17 bytes

```
{S!\⅟!1/!.EVAL}

```

Try it online!

Returns a rational number type. Raku actually natively supports unicode literals and operators, though it doesn't do , so we need to substitute for that. Also, division by zero won't cause an error, but returns a value that causes an Exception when you try to use or print it.
> 16 votes

# Answer
# PHP, 80 bytes

```
preg_match("~(\d+)/ ?(\d+)~",iconv('','US//TRANSLIT',$argn),$m);echo$m[1]/$m[2];

```

Try it online!

Just letting `iconv` do all the work for us ^^ this time PHP is competitive :O
> 9 votes

# Answer
# JavaScript (ES6),  ~~125 120~~  106 bytes

```
s=>([n,d]=s.split(/\D/),d)?(n||1)/d:'131111121234151357'[i=s.charCodeAt()%63%20]/-~'133689224444557777'[i]

```

Try it online!
> 5 votes

# Answer
# Charcoal, 62 bytes

```
¿№θ⁄⪫⪪θ⁄¦/¿№θ⅟⭆θ⎇κι1/«§”)⧴≦Y�δ↥1≧Ｙ”℅θ/Ｉ⊕§”)¶@≦ＩＧ@℅⁵∧ψ”℅θ

```

Try it online! Link is to verbose version of code. Outputs a pair of integers separated with `/` for convenience. Explanation:

```
¿№θ⁄

```

If the input contains ,

```
⪫⪪θ⁄¦/

```

then replace it with a `/`.

```
¿№θ⅟

```

If the input contains ,

```
⭆θ⎇κι1/

```

then replace it with `1/`.

```
«§”)⧴≦Y�δ↥1≧Ｙ”℅θ/Ｉ⊕§”)¶@≦ＩＧ@℅⁵∧ψ”℅θ

```

Otherwise look up the ordinal of the input in two compressed strings, one for the numerator, one for the denominator, and then increment the denominator (so that `1/10` can be handled).

Alternative version for 73 bytes:

```
¿№θ⁄«≔Ｉ⪪θ⁄θＩ∕§θ⁰⊟θ»¿№θ⅟«Ｉ∕¹Ｉ✂θ¹»Ｉ∕⊕§”)➙⧴ω⪪B⪪◨ιＹ”℅θ⊕§”)¶@≦ＩＧ@℅⁵∧ψ”℅θ

```

Try it online! Link is to verbose version of code. Output is a decimal fraction. Explanation:

```
¿№θ⁄«≔Ｉ⪪θ⁄θＩ∕§θ⁰⊟θ»

```

Handle the  case by dividing the numerator by the denominator.

```
¿№θ⅟«Ｉ∕¹Ｉ✂θ¹»

```

Handle the  case by taking the reciprocal of the denominator.

```
Ｉ∕⊕§”)➙⧴ω⪪B⪪◨ιＹ”℅θ⊕§”)¶@≦ＩＧ@℅⁵∧ψ”℅θ

```

Look up the decremented numerator and denominator in two compressed strings and divide their increments. (As I need the numerator as an integer anyway, incrementing it actually makes the string more compressible.)
> 5 votes

# Answer
# Groovy, 96 bytes

```
import static java.text.Normalizer.*
def f={s->Eval.me(normalize(s,Form.NFKC).replace("⁄","/"))}

```

Try it online!

Uses Unicode Normalization to replace the digits with ASCII digits. Then replaces the fraction slash by an ASCII slash and evaluates the resulting string.
> 4 votes

# Answer
# Python 3, ~~78~~ 76 bytes

```
lambda s:eval(normalize('NFKC',s).replace(*'⁄/'))
from unicodedata import*

```

Try it online!

A lazy built-in solution in Python.

2 bytes saved by dingledooper.
> 4 votes

# Answer
# 05AB1E, ~~90~~ ~~88~~ 65 bytes

```
gi•QλÖìʒ¨ù·'á!÷€āW•2ô2ÝƵ∞+14ÝŽX=+«çIkè`>/ëćÇŽX€åizë\ŽW&ç¡`D_iõEë/

```

Try it online or verify all test cases.

**Explanation:**

```
gi                       # If the length of the (implicit) input is 1:
  •QλÖìʒ¨ù·'á!÷€āW•     '#  Push compressed integer 131133161819122214243444155517375777
                   2ô    #  Split it into parts of size 2:
                         #   [13,11,33,16,18,19,12,22,14,24,34,44,15,55,17,37,57,77]
  2Ý                     #  Push list [0,1,2]
    Ƶ∞                   #  Push compressed integer 188
      +                  #  Add it to each value
       14Ý               #  Push list [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]
          ŽX=            #  Push compressed integer 8528
             +           #  Add it to each value
              «          #  Merge the two lists together
               ç         #  Convert each to a character:
                         #   ["¼","½","¾","⅐","⅑","⅒","⅓","⅔","⅕","⅖","⅗","⅘","⅙","⅚","⅛","⅜","⅝","⅞"
                Ik       #  Get the index of the input in this list
                  è      #  Use it to index into the list we created earlier
                   `     #  Pop and push both digits separated to the stack
                    >    #  Increase the denominator by 1
                     /   #  And divide them by one another
 ë                       # Else (the length is not 1):
  ć                      #  Extract the first character of the (implicit) input
   Ç                     #  Convert it to a unicode integer-list
    ŽX€                  #  Push compressed integer 8543
       åi                #  If it's in the list (thus the first character was '⅟'):
         z               #   Push 1 divided by the remaining value
        ë                #  Else (the first character is not '⅟'):
         \               #   Discard the partial input
          ŽW&            #   Push compressed integer 8260
             ç           #   Convert it to a character "⁄"
              ¡          #   Split the (implicit) input by "⁄"
               `         #   Push both values separated to the stack
                D_i      #   If the top value (the denominator) is 0:
                   õE    #    Loop "" amount of times, resulting in an error
                  ë      #   Else:
                   /     #    Divide the two values by one another
                         # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand how all the compressed integers work.
> 3 votes

# Answer
# Retina 0.8.2, 136 bytes

```
T`¼-¾⅐-⅟`L
B
1/2
D
1/7
E
1/9
F
1/10
G|H
$&3
A|C
$&4
[I-L]
$&5
M|N
$&6
[O-R]
$&8
[AGIMOS]
1/
H|J
2/
[CKP]
3/
L
4/
N|Q
5/
R
7/
⁄
/

```

Try it online! Link includes test cases. Explanation: By transliterating the UTF-8 characters to uppercase letters we can avoid massive UTF-8 encoding penalties which would otherwise make the shortest solution a series of replacements one for each fraction character (154 bytes in total). Instead I can squeeze out a few bytes by sharing replacements between fractions with the same denominator and then again with the numerator, particularly with fifths and eighths.
> 3 votes

# Answer
# Python 3, ~~273~~ \\$\cdots\\$ ~~248~~ 240 bytes

Saved 8 bytes thanks to pppery!!!

```
lambda s:{'¼':1/4,'½':.5,'¾':3/4,'⅐':1/7,'⅑':1/9,'⅒':.1,'⅓':1/3,'⅔':2/3,'⅕':.2,'⅖':.4,'⅗':.6,'⅘':.8,'⅙':1/6,'⅚':5/6,'⅛':1/8,'⅜':3/8,'⅝':5/8,'⅞':7/8}.get(s[0])or eval(s.replace('⁄','/').replace('⅟','1/'))

```

Try it online!

A straight-up mapping of Unicode vulgar fractions to their values ( (U+2189) falls into the *"don't care"* situation so throws an exception) or failing that, replaces  (U+215F) with `1/` (ASCII 49 + ASCII 47) and  (U+2044) with `/` (ASCII 47) and does an `eval`. So either returns the value (for valid input) or throws an exception (for invalid input).
> 3 votes

# Answer
# Python 3, ~~153~~ 151 bytes

```
lambda s:F(s.translate({8260:47,8543:"1/"}))if s[1:]else F(numeric(s)).limit_denominator()
from fractions import Fraction as F
from unicodedata import*

```

Try it online!

---

A not-so-lazy Python solution that returns the correct rational number as a `fraction.Fraction` instead of its floating point approximation.

## Explanation

We need to distinguish between two cases:

### Case 1: input length ≠ 1

```
Fraction( s.translate({ 8260: 47, 8543: "1/" }) )

```

Replace a couple of codepoints

* 826010 (U+2044, ) → 4710 (U+002F, `/`)
* 854310 (U+215F, ) → `1/`

and parse the result as a `Fraction`.

### Case 2: input length = 1

```
Fraction(unicodedata.numeric(s)).limit_denominator(10)

```

Convert the input codepoint into its floating point representation using `unicodedata.numeric` and subsequently as a `Fraction`. Unfortunately the intermediate representation as a floating point value loses some precision and we need to approximate the intended value using `Fraction.limit_denominator` and the knowledge of the largest occurring denominator 1,000,000 (actually 10 but the function’s default argument value is good enough).

Unfortunately we cannot merge the code paths for conversion to `Fraction` of both cases since the denominator limitation will return incorrect results for large denominators in case 1.
> 2 votes

# Answer
Perl5:

```
perl -CiIO -Mutf8 -MUnicode::Normalize -pe '$_=NFKD$_'

```
> 1 votes

# Answer
# C (gcc) with `-funsigned-char`, 317 239 234 bytes

Thanks to ceilingcat for the changes!

To save some size, I preload the numerator with `1` (the denominator will usually be set to `0` on test failures so that the function will return an invalid value: generally `NAN` or `INF`, but some of the "don't care" inputs give other values.) I then look for the common cases and return the result.

It's a somewhat brute-forced function, given that I'm not using any character classification or normalization to assist: I decode the first byte to determine whether I'm looking at a precomposed fraction or not, and then apply rules from what is found.

```
#define S(x)strtol(x,&s,0)*!
n,d;float f(char*s){n=1;d=*s<58?n=S(s)0,*s|s[1]?s+=3,S(s)*s:0:*s-194?d=0[s+=2]-144,d<1?7:d<2?9:d<3?10:d<5?n=d-2,3:d<9?n=d-4,5:d<11?n=4*d-35,6:d<15?n=2*d-21,8:S(++s)*s:*++s<191?n=*s-187,4:0;return(n+.0)/d;}

```

Try it online!
> 1 votes

# Answer
# Ruby, 49 bytes

Prints a representation of a Ruby Rational type.

```
$_=eval $_.unicode_normalize(:nfkc).sub ?⁄,"r/"

```

Attempt This Online!
> 1 votes

---
Tags: code-golf, parsing, rational-numbers, unicode
---


title: Reverse Conway's Game of Life

text:
# Question
Title: Reverse Conway's Game of Life
Conway's Game of Life is a cellular automaton "played" on an infinite grid, filled with cells that are either alive or dead. Once given an initial state, the board evolves indefinitely according to the following rules:

* Any live cell with 2 or 3 living neighbours lives to the next state
* Any dead cell with exactly 3 living neighbours becomes a living cell
* Any other cell becomes a dead cell

---

# The Challenge

Given a state of the game, find the previous state.

## Rules

* All inputs are assumed to have a preceding state, that is, your code need not handle Gardens of Eden.
* There will be multiple solutions, output any of them.
* You may take input in any reasonable format. Standard I/O Rules apply.

## Test cases

```
> input
: output

> [(2, 2)]
: [(1, 1), (2, 2), (3, 3)]
> [(2, 2), (2, 4), (3, 3), (3, 4), (4, 3)]
: [(1, 3), (2, 4), (3, 2), (3, 3), (3, 4)]
> [(2, 2), (2, 3), (2, 4)]
: [(1, 3), (2, 3), (3, 3)]
> [(2, 2), (2, 3), (2, 4), (3, 2), (3, 4), (4, 2), (4, 3), (4, 4)]
: [(1, 3), (2, 3), (3, 2), (3, 4), (4, 3), (5, 3)]
> [(3, 2), (3, 3), (3, 4), (4, 2), (4, 3), (5, 2), (5, 3), (5, 4)]
: [(2, 2), (2, 5), (3, 5), (4, 2), (4, 3), (5, 3), (5, 4)]
> [(2, 4), (2, 5), (4, 2), (4, 5), (5, 2), (5, 3), (5, 4)]
: [(2, 4), (2, 5), (3, 4), (3, 5), (4, 2), (4, 3), (4, 4), (5, 3)]
> [(1, 13), (1, 14), (1, 19), (1, 20), (2, 13), (2, 19), (3, 8), (3, 9), (3, 15), (3, 21), (3, 29), (3, 30), (4, 7), (4, 9), (4, 14), (4, 15), (4, 20), (4, 21), (4, 26), (4, 27), (4, 30), (5, 3), (5, 4), (5, 6), (5, 9), (5, 11), (5, 12), (5, 15), (5, 17), (5, 18), (5, 21), (5, 23), (5, 24), (5, 27), (5, 29), (6, 3), (6, 5), (6, 6), (6, 8), (6, 11), (6, 12), (6, 14), (6, 17), (6, 18), (6, 20), (6, 23), (6, 24), (6, 26), (6, 29), (6, 30), (7, 8), (7, 9), (7, 14), (7, 15), (7, 20), (7, 21), (7, 26), (7, 27), (7, 31), (8, 4), (8, 5), (8, 7), (8, 10), (8, 11), (8, 13), (8, 16), (8, 17), (8, 19), (8, 22), (8, 23), (8, 25), (8, 28), (8, 29), (8, 32), (9, 4), (9, 6), (9, 7), (9, 10), (9, 12), (9, 13), (9, 16), (9, 18), (9, 19), (9, 22), (9, 24), (9, 25), (9, 28), (9, 30), (9, 31), (9, 32), (10, 8), (10, 9), (10, 14), (10, 15), (10, 20), (10, 21), (10, 26), (10, 27), (11, 5), (11, 6), (11, 9), (11, 11), (11, 12), (11, 15), (11, 17), (11, 18), (11, 21), (11, 23), (11, 24), (11, 27), (11, 29), (11, 30), (12, 5), (12, 6), (12, 8), (12, 11), (12, 12), (12, 14), (12, 17), (12, 18), (12, 20), (12, 23), (12, 24), (12, 26), (12, 29), (12, 30), (13, 8), (13, 9), (13, 14), (13, 15), (13, 20), (13, 21), (13, 26), (13, 27), (13, 33), (13, 34), (14, 3), (14, 4), (14, 5), (14, 7), (14, 10), (14, 11), (14, 13), (14, 16), (14, 17), (14, 19), (14, 22), (14, 23), (14, 25), (14, 28), (14, 29), (14, 31), (14, 34), (15, 1), (15, 4), (15, 6), (15, 7), (15, 10), (15, 12), (15, 13), (15, 16), (15, 18), (15, 19), (15, 22), (15, 24), (15, 25), (15, 28), (15, 30), (15, 31), (15, 32), (16, 1), (16, 2), (16, 8), (16, 9), (16, 14), (16, 15), (16, 20), (16, 21), (16, 26), (16, 27), (17, 5), (17, 6), (17, 9), (17, 11), (17, 12), (17, 15), (17, 17), (17, 18), (17, 21), (17, 23), (17, 24), (17, 27), (17, 29), (17, 30), (18, 5), (18, 6), (18, 8), (18, 11), (18, 12), (18, 14), (18, 17), (18, 18), (18, 20), (18, 23), (18, 24), (18, 26), (18, 29), (18, 30), (19, 8), (19, 9), (19, 14), (19, 15), (19, 20), (19, 21), (19, 26), (19, 27), (20, 3), (20, 4), (20, 5), (20, 7), (20, 10), (20, 11), (20, 13), (20, 16), (20, 17), (20, 19), (20, 22), (20, 23), (20, 25), (20, 28), (20, 29), (20, 31), (21, 3), (21, 6), (21, 7), (21, 10), (21, 12), (21, 13), (21, 16), (21, 18), (21, 19), (21, 22), (21, 24), (21, 25), (21, 28), (21, 30), (21, 31), (22, 4), (22, 8), (22, 9), (22, 14), (22, 15), (22, 20), (22, 21), (22, 26), (22, 27), (23, 5), (23, 6), (23, 9), (23, 11), (23, 12), (23, 15), (23, 17), (23, 18), (23, 21), (23, 23), (23, 24), (23, 27), (23, 29), (23, 30), (23, 32), (24, 6), (24, 8), (24, 11), (24, 12), (24, 14), (24, 17), (24, 18), (24, 20), (24, 23), (24, 24), (24, 26), (24, 29), (24, 31), (24, 32), (25, 5), (25, 8), (25, 9), (25, 14), (25, 15), (25, 20), (25, 21), (25, 26), (25, 28), (26, 5), (26, 6), (26, 14), (26, 20), (26, 26), (26, 27), (27, 16), (27, 22), (28, 15), (28, 16), (28, 21), (28, 22)]
: [(1, 13), (1, 14), (1, 19), (1, 20), (2, 13), (2, 19), (3, 8), (3, 9), (3, 15), (3, 21), (3, 29), (3, 30), (4, 7), (4, 9), (4, 14), (4, 15), (4, 20), (4, 21), (4, 26), (4, 27), (4, 30), (5, 3), (5, 4), (5, 6), (5, 9), (5, 11), (5, 12), (5, 15), (5, 17), (5, 18), (5, 21), (5, 23), (5, 24), (5, 27), (5, 29), (6, 3), (6, 5), (6, 6), (6, 8), (6, 11), (6, 12), (6, 14), (6, 17), (6, 18), (6, 20), (6, 23), (6, 24), (6, 26), (6, 29), (6, 30), (7, 8), (7, 9), (7, 14), (7, 15), (7, 20), (7, 21), (7, 26), (7, 27), (7, 31), (8, 4), (8, 5), (8, 7), (8, 10), (8, 11), (8, 13), (8, 16), (8, 17), (8, 19), (8, 22), (8, 23), (8, 25), (8, 28), (8, 29), (8, 32), (9, 4), (9, 6), (9, 7), (9, 10), (9, 12), (9, 13), (9, 16), (9, 18), (9, 19), (9, 22), (9, 24), (9, 25), (9, 28), (9, 30), (9, 31), (9, 32), (10, 8), (10, 9), (10, 14), (10, 15), (10, 20), (10, 21), (10, 26), (10, 27), (11, 5), (11, 6), (11, 9), (11, 11), (11, 12), (11, 15), (11, 17), (11, 18), (11, 21), (11, 23), (11, 24), (11, 27), (11, 29), (11, 30), (12, 5), (12, 6), (12, 8), (12, 11), (12, 12), (12, 14), (12, 17), (12, 18), (12, 20), (12, 23), (12, 24), (12, 26), (12, 29), (12, 30), (13, 8), (13, 9), (13, 14), (13, 15), (13, 20), (13, 21), (13, 26), (13, 27), (13, 33), (13, 34), (14, 3), (14, 4), (14, 5), (14, 7), (14, 10), (14, 11), (14, 13), (14, 16), (14, 17), (14, 19), (14, 22), (14, 23), (14, 25), (14, 28), (14, 29), (14, 31), (14, 34), (15, 1), (15, 4), (15, 6), (15, 7), (15, 10), (15, 12), (15, 13), (15, 16), (15, 18), (15, 19), (15, 22), (15, 24), (15, 25), (15, 28), (15, 30), (15, 31), (15, 32), (16, 1), (16, 2), (16, 8), (16, 9), (16, 14), (16, 15), (16, 20), (16, 21), (16, 26), (16, 27), (17, 5), (17, 6), (17, 9), (17, 11), (17, 12), (17, 15), (17, 17), (17, 18), (17, 21), (17, 23), (17, 24), (17, 27), (17, 29), (17, 30), (18, 5), (18, 6), (18, 8), (18, 11), (18, 12), (18, 14), (18, 17), (18, 18), (18, 20), (18, 23), (18, 24), (18, 26), (18, 29), (18, 30), (19, 8), (19, 9), (19, 14), (19, 15), (19, 20), (19, 21), (19, 26), (19, 27), (20, 3), (20, 4), (20, 5), (20, 7), (20, 10), (20, 11), (20, 13), (20, 16), (20, 17), (20, 19), (20, 22), (20, 23), (20, 25), (20, 28), (20, 29), (20, 31), (21, 3), (21, 6), (21, 7), (21, 10), (21, 12), (21, 13), (21, 16), (21, 18), (21, 19), (21, 22), (21, 24), (21, 25), (21, 28), (21, 30), (21, 31), (22, 4), (22, 8), (22, 9), (22, 14), (22, 15), (22, 20), (22, 21), (22, 26), (22, 27), (23, 5), (23, 6), (23, 9), (23, 11), (23, 12), (23, 15), (23, 17), (23, 18), (23, 21), (23, 23), (23, 24), (23, 27), (23, 29), (23, 30), (23, 32), (24, 6), (24, 8), (24, 11), (24, 12), (24, 14), (24, 17), (24, 18), (24, 20), (24, 23), (24, 24), (24, 26), (24, 29), (24, 31), (24, 32), (25, 5), (25, 8), (25, 9), (25, 14), (25, 15), (25, 20), (25, 21), (25, 26), (25, 28), (26, 5), (26, 6), (26, 14), (26, 20), (26, 26), (26, 27), (27, 16), (27, 22), (28, 15), (28, 16), (28, 21), (28, 22)]

```

*Visualize test cases (possible output followed by input)*

This is , shortest answer in bytes wins.

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

```
f=(x,u=[],i=0,j=0,...L)=>u.find(g=([x,y])=>(t[[k%3+x-1,(k/3|0)%3+y-1]]+=[k%9==4],++k%9?t[[x,y]].length%5-3:g(v)),k=t=[])||Object.keys(t).filter(i=>t[i][22]&&!t[i][28]).sort()!=x.sort()+''?f(x,...L,u,i+1,j,u,i,j+1,[...u,[i,j]],i,j):u

```

Nothing to Try it online!

```
f=(x,u=[],i=0,j=0,...L)=>                       // Init case
u.find(g=v=>(                                   // [i,j] exist?
  t[[k%3+v[0]-1,(k/3|0)%3+v[1]-1]]+=[k%9==4],   // neighbors +=5('false'), self +=4('true')
  ++k%9?t[[x,y]].length%5-3:g(v)                // Repeat 9 times then return if dup
),k=t=[])||
Object.keys(t).filter(                          // 0    5   10   15   20   25 28
  i=>t[i][22]&&!t[i][28]                        // undefinedfalsefalsefalsetrue
                                                // falsefalsetrue | falsefalsefalse | falsefalsefalsetrue
).sort()!=x.sort()+''?
f(x,...L,u,i+1,j,u,i,j+1,[...u,[i,j]],i,j)      // Try next, push with next [i,j] and version with [i,j] pushed
:u

```
> 2 votes

---
Tags: code-golf, cellular-automata, game-of-life
---