title: Addition on Elliptic Curves

text:
# Question
Title: Addition on Elliptic Curves
*Disclaimer: This does not do any justice on the rich topic of elliptic curves. It is simplified a lot. As elliptic curves recently got a lot of media attention in the context of encryption, I wanted to provide some small insight how "calculating" on an elliptic curve actually works.*

### Introduction

Elliptic curves are sets of points \\$(x,y)\\$ in the plane of the form \\$y^2 = x^3+Ax+B\\$. (Additionally, \\$4A^3+27B^2 ≠ 0\\$ to avoid nasty singularities.) You can consider these curves in any field. If you use the field of real numbers, the curves can be visualized and they look like this:

Source

The special thing about these curves is that they have a *built in* arithmetic operation that is the analogue of addition. You can add and subtract points, and this operation is both associative and commutative (an abelian group).

### How does addition work?

Note: addition of points on elliptic curves is not intuitive. This kind of addition is defined the way it is because it has certain nice properties. It's weird, but it works.

As elliptic curves form a group, there is an *additive identity* that is the equivalent of 0. That is, adding \\$0\\$ to any point will not change the result. This additive identity is the "point" at infinity. All lines on the plane include this point at infinity, so adding it makes no difference.

Let's say that any given line intersects the curve at three points, which may be \\$0\\$, and that the sum of these three points is \\$0\\$. Keeping that in mind, take a look at this image.

Source

Now, the natural question is, what is \\$P+Q\\$? Well, if \\$P+Q+R = 0\\$, then \\$P+Q = -R\\$ (alternatively written as \\$R'\\$). Where is \\$-R\\$? It is where \\$R + (-R) = 0\\$, which is on the other side of the x-axis from \\$R\\$ so that the line through them is vertical, intersecting only \\$R\\$, \\$-R\\$, and \\$0\\$. You can see this in the first part of this image:

Source

Another thing you can see in these images is that the sum of a point with itself means the line is tangent to the curve.

### How to find intersections of lines and elliptic curves

**In the case of two distinct points**

Generally there is exactly one line through two points \\$P=(x\_0,y\_0), Q=(x\_1,y\_1)\\$. Assuming it is not vertical and the two points are distinct, we can write it as \\$y = mx+q\\$. When we want to find the points of intersection with the elliptic curve we can just write

$$0 = x^3+Ax+B-y^2 = x^3+Ax+B-(mx+q)^2$$

which is a third degree polynomial. These are generally not that easy to solve, but we already know two zeros of this polynomial: The two \\$x\\$-coordinates \\$x\_0, x\_1\\$ of the two points we want to add!

That way we factor out the linear factors \\$(x-x\_0)\\$ and \\$(x-x\_1)\\$ and are left with a third linear factor whose root is the \\$x\\$-coordinate of the point \\$R\\$. (\\$-R\\$ too because of the symmetry. Note that if \\$R = (x\_2,y\_2)\\$ then \\$-R = (x\_2,-y\_2)\\$. The \\$-\\$ is from the group; it is not a vectorial minus.)

**In the case of adding one point \\$P\\$ to itself**

In this case we have to calculate the tangent of the curve at \\$P=(x\_0,y\_0)\\$. We can directly write \\$m\\$ and \\$q\\$ in terms of \\$A,B,x\_0\\$ and \\$y\_0\\$:

$$m = \frac{3x\_0^2+A}{2y\_0}$$

$$q = \frac{-x\_0^3+Ax\_0+2B}{2y\_0}$$

We get the equation \\$y = mx+q\\$ and can proceed the same way as in the paragraph above.

### A complete case tree

This is a complete list of how to handle all those cases:

Let \\$P,Q\\$ be points on the elliptic curve (including the "infinity" point \\$0\\$)

* If \\$P = 0\\$ or \\$Q = 0\\$, then \\$P+Q = Q\\$ or \\$P+Q = P\\$, respectively
* Else \\$P ≠ 0\\$ and \\$Q ≠ 0\\$, so let \\$P = (x\_0,y\_0)\\$ and \\$Q = (x\_1,y\_1)\\$:
    + If \\$P = -Q\\$ (that means \\$x\_0 = x\_1\\$ and \\$y\_0 = -y\_1\\$) then \\$P+Q = 0\\$
    + Else \\$P ≠ -Q\\$
        - If \\$x\_0 = x\_1\\$ then we have \\$P=Q\\$ and we calculate the tangent (see section above) in order to get \\$R\\$. Then \\$P+Q = P+P = 2P = -R\\$
        - Else: We can construct a line of the form \\$y = mx+q\\$ through those two points (see section above) in order to calculate \\$R\\$. Then \\$P+Q=-R\\$

### Finite fields

For this challenge we will only consider fields of size \\$p\\$ where \\$p\\$ is prime (and because of some details \\$p ≠ 2, p ≠ 3\\$). This has the advantage that you can simply calculate \\$\bmod p\\$. The arithmetic in other fields is much more complicated.

This in this example we set \\$p = 5\\$ and all equalities here are congruences \\$\bmod 5\\$.

```
2+4 ≡ 6 ≡ 1
2-4 ≡ -2 ≡ 3
2*4 ≡ 8 ≡ 3
2/4 ≡ 2*4 ≡ 3 because 4*4 ≡ 16 ≡ 1, therefore 1/4 ≡ 4

```

# Challenge

Given the parameters \\$A,B\\$ of an elliptic curve, a prime field characteristic \\$p\\$ and two points \\$P,Q\\$ on the elliptic curve, return their sum.

* You can assume that the parameters \\$A,B\\$ actually describe an elliptic curve, that means that \\$4A^3+27B^2 ≠ 0\\$.
* You can assume that \\$P,Q\\$ are actually points on the elliptic curve or the \\$0\\$-point.
* You can assume that \\$p ≠ 2,3\\$ is prime.

### Test Cases

I made a (not very elegant) implementation in MATLAB/Octave, that you can use for your own test cases: ideone.com I hope it is correct. It did at least reproduce a few calculations I made by hand.

Note the trivial test cases that work for all curves we consider here:

* Adding zero: \\$P+0 = P\\$
* Adding the inverse: \\$(x,y) + (x,-y) = 0\\$

---

For \\$p = 7, A = 0, B = 5\\$ the two points \\$P = (3,2)\\$ and \\$Q = (6,2)\\$ are on the elliptic curve. Then following holds:

```
2*Q = Q+Q = P
2*P = P+P = (5,2)
3*P = P+P+P = (5,2)+P = (6,5)
4*P = P+P+P+P = (5,2)+(5,2) = (6,5)+(5,2) = Q

```

All the points on the elliptic curve are \\$(3,2),(5,2),(6,2),(3,5),(5,5),(6,5),0\\$

---

For \\$p = 13, A = 3, B = 8\\$ we get

```
(1,8)+(9,7) = (2,10)
(2,3)+(12,11) = (9,7)
2*(9,6) = (9,7)
3*(9,6) = 0

```

---

For \\$p = 17, A = 2, B = 2\\$ and \\$P=(5,1)\\$ we get

```
2*P = (6,3)
3*P = (10,6)
4*P = (3,1)
5*P = (9,16)
6*P = (16,13)
7*P = (0,6)
8*P = (13,7)
9*P = (7,6)
10*P = (7,11)

```

---

If you are really ambitious, take

```
p = 1550031797834347859248576414813139942411
A = 1009296542191532464076260367525816293976
x0 = 1317953763239595888465524145589872695690
y0 = 434829348619031278460656303481105428081
x1 = 1247392211317907151303247721489640699240
y1 = 207534858442090452193999571026315995117

```

and try to find a natural number \\$n\\$ such that \\$n\times(x\_0,y\_0) = (x\_1,y\_1)\\$. Further information here.

# Appendix

First of all a big THANK YOU to @El'endiaStarman for reviewing and editing my draft!

### Why elliptic curves?

Well it might appear like some kind of arbitrary equation, but it is not, it is quite general: Generally we consider those geometric "shapes" in the projective plane (that is where the "infinity" is coming from. There we consider all homogeneous polynomials of third degree. (Those of lower or higher degree would be too difficult or just trivial to examine.) After applying some restrictions in order to get the nice properties we want, and after dehomogenizing those polynomials (projecting into one of three affine planes) we end up with equations like \\$y^2+axy+by = x^3+cx^2+dx+e\\$ This is an elliptic curve in the long Weierstrass form. These are basically the same curves as we considered, but just somewhat skewed. With a linear coordinate transform, you can easily make a short Weierstras equation out of that. example, which still hold all the interesting properties.

### Why did we exclude \\$p=2,3\\$?

This has to do with the fact that for the short Weierstrass form we need the restriction \\$4A^3+27B^2 ≠ 0\\$ in order to avoid singularities (more on that below). In a field of characteristic 2 we have \\$4 = 0\\$ and in a field of characteristic 3 we have \\$27 = 0\\$, this makes it impossible to have curves in short Weierstrass form for those kinds of fields.

### What are singularities?

If the equation \\$4A^3+27B^2=0\\$ holds, we have singularities like following: As you see at those points you cannot find a derivative and therefore no tangent, which "kills" the operation. You might look at the equations \\$y^2 = x^3\\$ or \\$y^2 = x^3-3x+2\\$

### Why are they called *elliptic curves* anyway?

The reason is that equations of this shape pop up in elliptic integrals, e.g. which are what you get when you want to caclulate the e.g. the arclength of an ellipse. A short slideshow about the origin of the name.

### What do they have to do with cryptography?

There are ways to compute \\$nP = P+P+...+P\\$ very efficiently. This can be used for example in the Diffie Hellman key exchange. The modular arithmetic can be replaced by the addition on torsion subgroups, these are just the points on the curve that have finite order. (That means that \\$mP = 0\\$ for some \\$m\\$, which is basically just calculating \\$\bmod m\\$ ).

# Answer
# Pyth, ~~105~~ 100 bytes

```
A,@Q3eQ?qGZH?qHZG?&=YqhHhGqeG%_eHhQZ_m%dhQ,-*J?Y*+*3^hG2@Q1^*2eG-hQ2*-eGeH^-hGhH-hQ2-hGK--^J2hGhHeGK

```

Input is expected as `(p, A, P, Q)`, where `P` and `Q` are the two points of the form `(x, y)` or, if they are the special `0` point, just as `0`. You can try it out online here. The last two examples show how the special `0` works.

In order to save a few bytes, I only use `mod p` on the final answer. This means that it does things like `x0^p` a few times without doing modular exponentiation, so it might be very slow.

It works by following roughly the same logic as this Python function:

```
def add_ellip(p, A, P, Q): # points are in format (x, y)
    z = 0 # representing special 0 point

    if (P == z):
        return Q
    if (Q == z):
        return P

    if P[0] == Q[0]:
        if (P == (Q[0], -Q[1] % p)):
            return z
        else:
            m = ((3*pow(P[0], 2, p) + A)*pow(2*P[1], p-2, p)) % p
    else:
        m = (P[1] - Q[1])*pow(P[0] - Q[0], p-2, p) % p

    x = (pow(m, 2, p) - P[0] - Q[0]) % p
    y = (m*(P[0] - x) - P[1]) % p
    return (x, y)

```

This is heavily reliant on the fact that the modular multiplicative inverse of `x` is equal to `x^(p-2) mod p` if `p` is prime. Thus we are able to compute `m`, the slope of the line, by finding the modular multiplicative inverse of the denominator and multiplying it by numerator. Pretty handy. The Python function should calculate larger problems a little more efficiently because of the use of `pow`.

I also used the shortcuts shown on the Wikipedia page on this subject. It's quite interesting I only end up using `A` once, and `B` not at all.

Also just for fun:

```
def pow2floor(x):
    p = 1
    x >>= 1
    while (x > 0):
        x >>= 1
        p <<= 1
    return p

def multi_nP(p, A, n, P):
    d = {}

    def rec_helper(n, P):
        if (n == 0):
            return (0, 0)
        elif (n == 1):
            return P
        elif (n in d):
            return d[n]
        else:
            p2f = pow2floor(n)
            remainder = n - p2f

            lower_half = rec_helper(p2f//2, P)
            d[p2f//2] = lower_half
            nP = add_ellip(p, A, lower_half, lower_half)

            if (remainder):
                nP = add_ellip(p, A, nP, rec_helper(remainder, P))

            d[n] = nP
            return nP

    return rec_helper(n, P)

```

The `multi_nP` function computes `n*P` for a given integer `n` and point `P`. It uses a recursive strategy by splitting `n` into two parts `p2f` and `remainder` such that `p2f + remainder = n` and that `p2f = 2^k`. Then we call the function again on those parts, adding the result with `add_ellip`. I also used basic dynamic programming approach by saving already computed values in the dict `d`.

The next function would theoretically solve the bonus question using the same strategy:

```
def find_nPQ(p, A, P, Q): # P is input point, Q is what we're looking for
    d = {}
    found_Q = False

    def rec_helper(n, P):
        if (n == 0):
            return (0, 0)
        elif (n == 1):
            return P
        elif (n in d):
            return d[n]
        else:
            p2f = pow2floor(n)
            remainder = n - p2f

            lower_half = rec_helper(p2f//2, P)
            d[p2f//2] = lower_half

            nP = add_ellip(p, A, lower_half, lower_half)

            if (remainder):
                nP = add_ellip(p, A, nP, rec_helper(remainder, P))

            d[n] = nP
            return nP

    for x in range(p):
        xP = rec_helper(x, P)
        if (xP == Q):
            return x

```

Unfortunately, it runs nowhere near quickly enough to compute it. I'm guessing there might be much more efficient ways to do this, especially if we don't have to iterate through every possibly value for `n`.
> 5 votes

# Answer
# Python 3, ~~193~~ 191 bytes

A solution based on Rhyzomatic's Pyth answer and their Python logic. In particular. I liked how they found the third root of a monic cubic polynomial `x^3 + bx^2 + cx + d` when you have two roots `x_1` and `x_2` by noting that `b == x_1 + x_2 + x_3` and subtracting accordingly. I plan to add an explanation, golf this, and perhaps transpile it into Ruby, if Ruby turns out to be shorter.

```
def e(p,A,B,P,Q):
 if P==0:return Q
 if Q==0:return P
 f,g=P;j,k=Q
 if f==j:
  if g==-k%p:return 0
  m=(3*f*f+A)*pow(2*j,p-2)
 else:m=(g-k)*pow(f-j,p-2)
 x=m*m-f-j;y=m*(f-x)-g;return(x%p,y%p)

```

**Ungolfing:**

```
def elliptic_curve_addition(p, A, B, P, Q):
    if P == 0:
        return Q
    if Q == 0:
        return P
    f,q = P
    j,k = Q
    if f==j:
        if g == (-k) % p:
            return 0
        m = (3 * f**2 + A) * pow(2*j, p-2)
    else:
        m = (g-k) * pow(f-j, p-2)
    x = m**2 - f - j
    y = m * (f-x) - g
    return (x%p, y%p)

```
> 3 votes

# Answer
# Wolfram Language(Mathematica), 254 bytes.

254 bytes, **it can be golfed more**.

Modified from @user293787's answer on MSE.

---

Golfed version. Try it online!

```
Needs["FiniteFields`"];
f[A_,B_,p_,P:{xp_, yp_},Q:{xq_,yq_}]:=Module[{k=GF[p][{#}]&},xP=k@xp;yP=k@yp;xQ=k@xq;yQ=k@yq;a=k@A;If[And[xP===xQ,yP===-yQ],Infinity,With[{s=If[xP===xQ,(3*xP^2+a)/(2*yP),(yP-yQ)/(xP-xQ)]},With[{xR=s^2-xP-xQ},{xR,-yP-s*(xR-xP)}]]]]

```

Ungolfed vesrion. Try it online!

```
Clear["Global`*"];
add[a_][P : {xP_, yP_}, Q : {xQ_, yQ_}] :=
  If[And[xP === xQ, yP === -yQ], Infinity,
   With[{s = If[xP === xQ, (3*xP^2 + a)/(2*yP), (yP - yQ)/(xP - xQ)]},
     With[{xR = s^2 - xP - xQ}, {xR, -yP - s*(xR - xP)}]]];

Needs["FiniteFields`"];
f[a_, b_, p_, P : {xP_, yP_}, Q : {xQ_, yQ_}] :=
  Module[{kk = GF[p][{#}] &
    },
   aa = kk[a];
   bb = kk[b];
   PP = {kk[xP], kk[yP]};
   QQ = {kk[xQ], kk[yQ]};
   e[{x_, y_}] := y^2 - (x^3 + aa*x + bb);
   {PAddQ = add[aa][PP, QQ], e[PAddQ]}
   ];

params = {{0, 5, 7, {6, 2}, {6, 2}}, {0, 5, 7, {3, 2}, {3, 2}}, {0, 5,
     7, {5, 2}, {3, 2}}, {0, 5, 7, {5, 2}, {5, 2}}, {3, 8,
    13, {1, 8}, {9, 7}}, {3, 8, 13, {2, 3}, {12, 11}}, {3, 8,
    13, {9, 6}, {9, 6}}, {3, 8, 13, {9, 7}, {9, 6}}, {2, 2,
    17, {5, 1}, {5, 1}}, {2, 2, 17, {6, 3}, {5, 1}}, {2, 2,
    17, {10, 6}, {5, 1}}, {2, 2, 17, {3, 1}, {5, 1}}, {2, 2,
    17, {9, 16}, {5, 1}}, {2, 2, 17, {16, 13}, {5, 1}}, {2, 2,
    17, {0, 6}, {5, 1}}, {2, 2, 17, {13, 7}, {5, 1}}, {2, 2,
    17, {7, 6}, {5, 1}}};

Do[Print[params[[i]], " -> ", f @@ params[[i]]], {i, Length[params]}]

```
> 2 votes

# Answer
# PARI/GP, 46 bytes

```
f(a,b,p,P,Q)=elladd(ellinit(Mod([a,b],p)),P,Q)
```

Attempt This Online!

Using built-ins. The zero point is represented by `[0]`.

---

# PARI/GP, 114 bytes

```
f(a,b,p,P,Q)=if(!#P,Q,!#Q,P,[x,y]=Mod(P,p);[x,-y]-[w,z]=Q,m=if(d=x-w,(y-z)/d,(3*x^2+a)/2/y);[t=m^2-x-w,m*x-m*t-y])
```

Attempt This Online!

A port of @Rhyzomatic's Pyth answer. The zero point is represented by `0`.
> 1 votes

---
Tags: code-golf, math, geometry, number-theory, abstract-algebra
---


title: Golf Me a World Clock

text:
# Question
Title: Golf Me a World Clock
### Task

Write a program or function that takes as input a time in UTC, and outputs the equivalent time in **5 different cities** around the world. The cities displayed are up to the programmer, but the **time must be different** in each city.

To prevent golfers from using overly obscure city names, the city names used must appear on this list: World Cities\*, which corresponds to the list of cities and times found here.

As usual, Standard loopholes are forbidden, including fetching data from an external source.

\*The times provided in the pastebin use daylight time and assume that the time is 0:30 UTC.

### Example

Given as input 12:30AM, your output might be:

```
Athens: 3:30AM
London: 1:30AM
New York: 8:30PM
Seoul: 9:30AM
Beijing: 8:30AM

```

### Input

You may take input in any reasonable format. You can choose to take the time as 24-hour time, or 12-hour time with `AM` and `PM`. Specify the input format in your answer.

### Output

Output may also be in either 12-hour or 24-hour time. The city-time pairs may be in any order and any reasonable format, so long as it is possible to associate each city with the corresponding time.

Daylight Savings Time can safely be ignored (ie. you can either use the offsets from the pastebin above, or you can assume that all times are in daylight time, or alternatively all in standard time)

### Scoring

This is . Happy golfing!

# Answer
> 26 votes
# Python 2, ~~80~~ ~~79~~ 77 bytes

-1 byte thanks to Surculose Sputum.

24-hour time, input as `hours, minutes`.

```
h,m=input();i=h
exec"print'ALCADcaamucgimbroraaasoni'[i-h::5],i%24,m;i+=1;"*5

```

Try it online!

Example output for `0, 30` (12:30AM):

```
Accra 0 30
Lagos 1 30
Cairo 2 30
Amman 3 30
Dubai 4 30

```

# Answer
> 16 votes
# Python 2, ~~71~~ 65 bytes

*Save 2 bytes using @dingle dooper's printing through `input()` trick!*

```
t=input('Accra Lagos Rome Kyiv Dubai ')
exec"print t%24,;t+=1;"*5

```

Try it online!

Takes input as a complex number (e.g `01:30` is inputted as \\$1+30i\\$), and prints out the list of cities, then the corresponding times. Uses 24-hour time.

# Answer
> 7 votes
# Bash \+ Core utilities, ~~79~~ ~~78~~ 72 bytes

```
for c in Amman Dubai Kabul Dhaka Seoul;{ TZ=Asia/$c date +$c\ %R -d$1Z;}

```

Try it online!

Input is passed as an argument, and output is on stdout. Both are in 24-hour time.

# Answer
> 6 votes
# Google Sheets, ~~82~~ ~~77~~ 80 bytes

*Saved 5 bytes by finding a shorter list of city names that are all off by 1 hour.*
*Added 3 bytes thanks to Surculose Sputum pointing out that I was referencing the wrong list.*

```
=ArrayFormula(Split("Lagos,Rome,Kyiv,Dubai,Kabul",",")&Mod(A1+Column(A:E),24)&B1

```

Sheets will automatically add the trailing parentheses. Hours are input in `A1` and minutes in `B1`.

`Split(~)` gives us the list of city names.
`A1+Column(A:E)` iterates the input time by ones.
`Mod(~,24)` accounts for when the clock rolls to the next day.
`Split(~)&Mod(~)&B1` tacks on the minutes.
`ArrayFormula(~)` makes the whole thing work on arrays instead of just the first value.

There aren't any delimiters between the city name and the time because pretty costs bytes. It's fairly easy to distinguish between the end of the name and the start of the time, though, since none of the city names have numbers in them.

# Answer
> 4 votes
# Befunge-93, 238 bytes

```
&&\" arccA",,,,,,:.\:.\" nammA",,,,,,3+:345*+`!v v    <
>    v v          `+*543:+3,,,,,,"Dhaka "\.:\.:_#<83*-^
^-*38>#_         :.\:.\" luoeS",,,,,,3+:345*+`!v v    <
>    v v          `+*543:+3 ,,,,,"Suva " \.:\.:_#<83*-^
^-*38>#_:.\:.@

```

Try it online!

Reads the hour and minutes from the input. For each city, except the first, it adds 3 to the hour, then checks whether it exceeds 23. If it does, it makes a small loop to subtract 24. The rest is just printing strings, moving the PC around and swapping the hours/minute to/from the top of the stack.

# Answer
> 4 votes
# 05AB1E, 25 bytes

Thanks to Kevin Cruijssen for shaving off 7 bytes.

```
”Accra‡¸«ÄçªâÈ”#ε¹N+24%²»

```

Try it online!

# 05AB1E, 32 bytes

Just another port of Surculose Sputum's answer. It produces quite an ugly output, due to joining by newlines.

```
”Accra Lagos«Ä KyivâÈ”#ε¹N+24%²»

```

Try it online!

# Explanation (for both)

```
”...”           Compressed string with the cities
     #          Space-split
      ε         Map:
                    Implicit current city pushed
       ¹            First input:
        N+              Add by the iteration counter
          24%       Modulo by 24
             ²      Append the second input
              »     Join the whole stack by newlines.

```

# Answer
> 3 votes
# , 43 40 bytes

```
{`Accra`Cork`Rome`Doha`Dubai!x+60*til 5}

```

No Tio unfortunately for q

q has built in time types that you can perform arithmetic with, so simple enough

```
Example:
q){`Accra`Cork`Rome`Doha`Dubai!x+60*til 5}00:30
Accra| 00:30
Cork | 01:30
Rome | 02:30
Doha | 03:30
Dubai| 04:30

```

# Answer
> 3 votes
# Vyxal, 26 bytes

```
5ɾ+₆+24%$S+`∴∷₇›†↵ƈ…±↑`5/Y

```

Try It Online!

Takes in `<hour>` `<minute>`, outputs an interleaved list of `<time>|<city>`.

My first Vyxal answer... it took me an embarrassingly long time to figure out how to properly deal with input.

# Answer
> 2 votes
# Bash, <sup>~~118~~ \\$\cdots\\$ ~~76~~</sup> 75 bytes

Saved a byte thanks to Duncan!!!
Saved a whopping ~~18~~ ~~39~~ ~~41~~ 42 bytes thanks to David G.!!!

```
for d in Accra Lagos Rome Kyiv Dubai;do date -d$1Z+$((i++))hour +$d%R;done&

```

Try it online!

Input passed as command line argument.
Outputs to stdout.
Uses 24-hour time format.

# Answer
> 2 votes
# C (gcc), 92 bytes

```
i;f(h,m){for(i=0;i<5;)printf("%s %d:%d;","AccraLagosRome.Kyiv.Dubai"+6*i++,(h+i)%24,m);}

```

Try it online!

Port of Bash, didn't check map

# C (gcc), 94 bytes

```
i;f(h,m){for(i=0;i<15;i+=3)printf("%s %d:%d;","AccraAmmanDhakaSeoulSuva"+2*i,(h+i)%24,m);}

```

Try it online!

Port of Python solution, didn't check map

# Answer
> 2 votes
# Jelly, 23 bytes

```
+Ɱ5%24;€⁹“F=ẓŒMdƲEṢ$Ṛ.»

```

A full program accepting two arguments, hours then minutes, which prints in an ugly format. Uses `Algiers Amsterdam Amman Dubai Islamabad` since they are the alphabetically earliest allowed cities with DST offsets of `1-5` hours from UTC.

**Try it online!**

### How?

```
+Ɱ5%24;€⁹“F=ẓŒMdƲEṢ$Ṛ.» - Main Link: hour, H; minute M
 Ɱ5                     - map across [1..5] with:
+                       -   addittion (to H)
   %24                  - modulo by 24
        ⁹               - chain's right argument, M
      ;€                - concatenate to each
         “F=ẓŒMdƲEṢ$Ṛ.» - compressed string "Algiers Amsterdam Amman Dubai Islamabad"
                        -   (this new niladic chain forces the previous result to be printed)
                        - implicit print

```

# Answer
> 1 votes
# Charcoal, 38 bytes

```
Ｅ⪪”↶+∧e-|GT⊘"↘w⌊⎇*↔ＪAN·”⁵⪫⟦ι﹪⁺Ｉθκ²⁴η⟧

```

Try it online! Link is to verbose version of code. Port of @SurculoseSputum's Python answer. Takes input as separate hours and minutes and uses the 24 hour clock. Explanation:

```
  ...               Compressed string of five cities
 ⪪   ⁵              Split into substrings of length 5
Ｅ                   Map over each substring
        ι           Current substring
           Ｉθ       Input hours as a number
          ⁺  κ      Plus current index
         ﹪    ²⁴    Modulo literal 24
                η   Input minutes
      ⪫⟦         ⟧  Joined with spaces
                    Implicitly print on separate lines

```

# Answer
> 1 votes
# JavaScript, 98 bytes

```
((h,m)=>['Accra','Lagos','Rome','Kyiv','Dubai'].map((e,i)=>console.log(e+' '+(h+i)%24+':'+m+';')))

```

Try it online!

Get the original idea from the C and so the Python guys.

# Answer
> 1 votes
# PHP 5.4+, 96 bytes

Yes, it's a fat boy :(
But was fun to write it!

```
foreach([Accra,Lagos,Cairo,Doha,Dubai]as$k=>$v)echo"\n$v ",date(H_i,strtotime("$argn {$k}hour"));

```

Run this with `php -r` (produces warnings).

The input format is flexible, as long as it can be interpreted by `strtotime()`.
You can input hours in 12-hour or 24-hour formats, being displayed in 24-hour format.

The cities chosen were picked because they are NOT in DST at the time of this answer:

# Answer
> 1 votes
# JavaScript (V8), 81 bytes

```
(h,m)=>'Accra-Lagos-Rome-Kyiv-Dubai'.split`-`.map(e=>console.log(e,h++%24+':'+m))

```

Try it online!

# Answer
> 1 votes
# JavaScript, 65 bytes

Input `f(h)(m)`. Outputs an array of arrays: `[[City, mm, ss], ...]`.

```
h=>m=>`Accra
Lagos
Rome
Kyiv
Dubai`.split`
`.map(c=>[c,h++%24,m])

```

Try it online!

---

# JavaScript, 66 bytes

Prettier. Outputs a string with `City,mm,ss` separated by newlines.

```
h=>m=>`Accra
Lagos
Rome
Kyiv
Dubai`.replace(/.+/g,M=>[M,h++%24,m])

```

Try it online!

---

# JavaScript, 64 bytes

Uglier. Outputs a string without delimiters: `Citymm,ssCitymm,ss...`.

```
h=>m=>`Accra Lagos Rome Kyiv Dubai `.replace(/ /g,_=>[h++%24,m])

```

Try it online!

# Answer
> 0 votes
# , 33 bytes

Just realized that my language is such a bad language. It doesn't even support dumping the stack...

```
☻|▓■°u:"≡∟◘Σ≡☺╖ⁿ╩]┼ε╝╣╗à_∙▬Cô\K←û

```

Uncompressed:

```
"3@374Ry<+o;<r>YwI+eA78P`5a(c0[+24mc1[{M

```

## Explanation

```
"3@374Ry<+o;<r>YwI+eA78P`                % Compressed string containing the cities
                         5             M % In the range 1..5:
                          a              %    The current counter,
                           (             %    Decremented,
                            c0[+         %    Is added to the hours
                                24m      %    And modulo'd by 24
                                   c1[   %    Push the minutes
                                      {  %    Pair the two items

```

# Answer
> 0 votes
# C# (Visual C# Interactive Compiler), 119 bytes

Input: `hh:mm`
Output: `h:mm`

```
t=>String.Concat("Accra,Lagos,Rome,Kyiv,Dubai".Split(',').Select((c,i)=>c+$":{(int.Parse(t[0..2])+i)%24}:{t[3..5]}\n"))

```

Try it online!

# Answer
> 0 votes
# Perl 5, 548 bytes

Golfed vesrion, try it online!

```
use strict;use warnings;my %time_offsets = ('Athens' => 3,'Beijing' => 8,'London' => 1,'New York' => -4,'Seoul' => 9);my $input = '12:30 AM';my ($hour, $minute, $ampm) = $input =~ /^(\d{1,2}):(\d{2}) (AM|PM)$/;if ($ampm eq 'PM' && $hour != 12) {$hour += 12;} elsif ($ampm eq 'AM' && $hour == 12) {$hour = 0;}my %city_times;while (my ($city, $offset) = each %time_offsets) {my $local_hour = ($hour + $offset) % 24;$city_times{$city} = sprintf("%02d:%02d", $local_hour, $minute);}while (my ($city, $time) = each %city_times) {print "$city: $time\n";}

```

Ungolfed vesrion

```
use strict;
use warnings;

my %time_offsets = (
    'Athens' => 3,
    'Beijing' => 8,
    'London' => 1,
    'New York' => -4,
    'Seoul' => 9,
);

my $input = '12:30 AM';  # Replace with input from user

# Extract hour, minute, and AM/PM from input
my ($hour, $minute, $ampm) = $input =~ /^(\d{1,2}):(\d{2}) (AM|PM)$/;

# Convert 12-hour time to 24-hour time
if ($ampm eq 'PM' && $hour != 12) {
    $hour += 12;
} elsif ($ampm eq 'AM' && $hour == 12) {
    $hour = 0;
}

# Calculate time in each city
my %city_times;
while (my ($city, $offset) = each %time_offsets) {
    my $local_hour = ($hour + $offset) % 24;
    $city_times{$city} = sprintf("%02d:%02d", $local_hour, $minute);
}

# Output city times
while (my ($city, $time) = each %city_times) {
    print "$city: $time\n";
}

```

# Answer
> 0 votes
# PowerShell, 123 bytes

Input can be in 12 or 24 hour format `i.e. hh:mm OR hh:mm AM/PM`

```
param($i)0..4|%{"{0}: {1}"-f("Accra","Lagos","Cairo","Amman","Dubai")[$_],([datetime]$i).AddHours($_).ToString("hh:mm tt")}

```

Try it online!

---
Tags: code-golf
---


title: String Comparison

text:
# Question
Title: String Comparison
You are given two strings \\$a\\$ and \\$b\\$ consisting of characters from a to z in lowercase. Let \\$n\\$ be the length of \\$a\\$. Let \\$m\\$ be the length of \\$b\\$. Let \\$a'\\$ be the string \\$a\\$ repeated \\$m\\$ times. Let \\$b'\\$ be the string \\$b\\$ repeated \\$n\\$ times. Check whether \\$a'\\$ is lexicographically less than \\$b'\\$.

Test cases:

```
a b ---> true
ac a ---> false
bekcka kwnfoe ---> true
beztbest bestbe ---> false
mcjaf mc ---> true
akboe uenvi ---> true

```

Shortest code wins.

Hint: there's a 13-byte JavaScript solution. Beat that!

Competitive answers use the `a+b<b+a` approach. A proof of this approach can be found at https://codeforces.com/blog/entry/91381?#comment-808323

# Answer
# Jelly, 3 bytes

Let's give these strings some oo`ṁÞƑ` :)

```
ṁÞƑ

```

A monadic Link that accepts a pair of lists of characters, \\$\[b, a\]\\$, and yields `0` when \\$a'=a\times n\\$ is lexicographically less than \\$b'=b\times m\\$ where \\$\times\\$ is "repeat" or `1` if not.

i.e. takes the strings in reverse order and results in the negative.

**Try it online!** Or see the test-suite.

### How?

We actually only need to check the first up to \\$m+n\\$ characters of the two augmented strings. This gets these by moulding each string like the input pair, e.g. `['ab', 'xyz']` gives `['ab', 'aba']` and `['xy', 'zxy']`. There is no need to flatten these before comparing them since their relative sort order is unaffected due to them having the same shape as each other.

```
ṁÞƑ - Link: pair of strings, X = [b, a]
  Ƒ - is X invariant under?:
 Þ  -   sort (the elements, e, of) X by:
ṁ   -     (e) mould like (X)

```

### Worked Example

```
a = 'abcdefgh' -> n = 8
b = 'pqrst' -> m = 5
X = [b, a] = ['pqrst', 'abcdefgh']
b ṁ X = ['pqrst', 'pqrstpqr']
  ...this is the first n+m=13 characters of b',
         'pqrstpqrstpqrstpqrstpqrstpqrstpqrstpqrst', split after m = 5 characters
a ṁ X = ['abcde', 'fghabcde']
  ...this is the first n+m=13 characters of a',
         'abcdefghabcdefghabcdefghabcdefghabcdefgh', split after m = 5 characters
(a ṁ X) < (b ṁ X) so the sorting, `ṁÞ`, reverses X
checking for invariance with `ṁÞƑ` therefore gives 0 indicating that a' < b'

```
> 7 votes

# Answer
# Python, 18 bytes

```
lambda a,b:a+b<b+a

```

Attempt This Online!

### How?

\\$a+b \lesseqqgtr b+a \quad\Leftrightarrow\quad a+a+b \lesseqqgtr a+b+a \lesseqqgtr b+a+a \quad\cdots\quad\Leftrightarrow\quad m\times a+b \lesseqqgtr b+ m\times a \quad\Leftrightarrow\quad m\times a+b+b \lesseqqgtr b+m\times a+b \lesseqqgtr b+b+ m\times a \quad\cdots\quad\Leftrightarrow\quad m\times a+n\times b \lesseqqgtr n\times b+ m\times a \quad\Leftrightarrow\quad m\times a \lesseqqgtr n\times b\\$
> 14 votes

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

```
a=>b=>a+b<b+a

```

Try it online!

Probably the 13 byte JS solution mentioned in the challenge. Ports loopy walt's Python answer.
> 6 votes

# Answer
# Wolfram Language(Mathematica), 31 bytes

```
f=AlphabeticOrder[#<>#2,#2<>#]&

```

Try it online!
> 5 votes

# Answer
# Vyxal, 4 bytes

```
₌Jp>

```

Try it Online!

A port of python is one byte shorter because of the niceness of parallel apply.

## Explained

```
₌Jp>
₌  >  # check whether
J    # the joining of the two strings
  >  # is greater than
 p   # the prepending of the two strings

```

For a more straightforward approach:

## Vyxal, 5 bytes

```
@Ṙ*ƒ<

```

Try it Online!

Takes input as a list of strings.

## Explained

```
@Ṙ*ƒ<
@     # vectorised lengths
 Ṙ*   # reverse that, and pairwise repeat the input strings that many times
   ƒ< # reduce by lexographic less than

```
> 4 votes

# Answer
# Julia 1.0, 11 bytes

```
a\b=a*b<b*a

```

Try it online!

Another port of loopy walt's Python answer.
> 4 votes

# Answer
# Go, 36 bytes

```
func(a,b string)bool{return a+b<b+a}

```

Attempt This Online!

Port of Loopy's Python answer.

### Go, 81 bytes

```
import."strings"
func f(a,b string)bool{return Repeat(a,len(b))<Repeat(b,len(a))}

```

Attempt This Online!

A more literal interpretation of the question.
> 4 votes

# Answer
# Arturo, 18 bytes

```
$[a b]-><a++b b++a

```

Try it

Port of loopy walt's Python answer.
> 3 votes

# Answer
# Charcoal, 7 bytes

```
‹⁺θη⁺ηθ

```

Try it online! Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` if `a'<b'`, nothing if not. Explanation: Another port of @loopywalt's Python answer.

```
  θ     First string
 ⁺      Concatenated with
   η    Second string
‹       Is less than
     η  Second string
    ⁺   Concatenated with
      θ First string
        Implicitly print

```

There are four cases:

* One of `a` and `b` is a repetition of the other. In this case, `a'=b'`, but `a+b=b+a`, so the result is correct.
* One of `a` and `b` is the prefix of the other, but the other is a prefix of its repetition. In this case the tie between `a'` and `b'` can always be broken before the length of `a+b`. Suppose `a` is a prefix of `b` is a prefix of `a'`, then `a+b` is also a prefix of `a'`, and `b+a` is a prefix of `b'`, so the result is correct.
* One of `a` and `b` is the prefix of the other. In this case the tie between `a'` and `b'` can always be broken before the length of the longer of `a` and `b`. Suppose `a` is a prefix of `b`, then `a+b` contains enough copies of `a` to break the tie with `b`, so the result is correct.
* Otherwise, `a` and `b` break the tie anyway before the length of the shorter of the two, so again the result is correct.

6 bytes by using JSON input:

```
‹ΣθΣ⮌θ

```

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

```
  θ     Input pair
 Σ      Joined
‹       Is less than
     θ  Input pair
    ⮌   Reversed
   Σ    Joined
        Implicitly print

```

9 bytes for the naïve version:

```
‹×θＬη×ηＬθ

```

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

```
  θ         First input
 ×          Repeated by
    η       Second input
   Ｌ        Length
‹           Is less than
      η     Second input
     ×      Repeated by
        θ   First input
       Ｌ    Length
            Implicitly print

```
> 3 votes

# Answer
# 05AB1E (legacy), ~~6~~ 5 bytes

```
Â‚J`‹

```

-1 byte porting *@loopyWalt*'s Python answer, so make sure to upvote that answer well!

Try it online or verify all test cases.

**Original straight-forward 6 bytes answer:**

```
€gR×`‹

```

Try it online or verify all test cases.

**Explanation:**

Uses the legacy version of 05AB1E, built in Python, which allows for comparisons on strings.

```
Â       # Bifurcate the (implicit) input-pair; short for Duplicate & Reverse copy
 ‚      # Pair the pair with its reversed pair
  J     # Join each inner pair together to a string
   `    # Pop and push the strings to the stack
    ‹   # Check if the first is smaller than the second
        # (after which the result is output implicitly)

€g      # Get the length of each inner string of the (implicit) input-pair
  R     # Reverse this pair
   ×    # Repeat the strings in the (implicit) input-pair that many times
    `‹  # Same as above
        # (after which the result is output implicitly)

```

---

# 05AB1E, 5 bytes

Porting @JonathanAllan's Jelly answer gives an alternative 5 bytes answer, which only works in the new version of 05AB1E.

```
Σδ∍}Q

```

Try it online or verify all test cases.

**Explanation:**

```
Σ       # Sort the (implicit) input-pair by:
 δ      #  Map over the (implicit) input-pair with the current string as argument:
  ∍     #   Extend/shorten the current string of the map to the same length as the
        #   current string of the sort-by
}       # After the sort-by:
 Q      # Check if the sorted pair is equal to the (implicit) input-pair
        # (after which the result is output implicitly)

```
> 3 votes

# Answer
# C (gcc), 82 bytes

```
t;*p;*q;f(a,b){for(t=3,p=a,q=b;*p==*q&&t;!*++p?--t,p=b:0)!*++q?--t,q=a:0;t=*p<*q;}

```

Try it online!

*Based on loopy walt's Python answer*
> 3 votes

# Answer
# Excel, 12 bytes

```
=A1&B1<B1&A1

```

Input is in the cells `A1` and `B1`. Excel uses `&` for concatenation.
> 3 votes

# Answer
# Ruby, 35 b-bwytes =￣ω￣=

`lambda{|a, b|"#{a}#{b}"<"#{b}#{a}"}`

Yiff yiff, this is a furrendly conversion of the python tail wag!
> 3 votes

# Answer
# Thunno `D`, \\$ 8 \log\_{256}(96) \approx \\$ 6.58 bytes

```
rZP.JAu<

```

Attempt This Online! or verify all test cases

Direct port of Kevin Cruijssen's 05AB1E answer, which is a port of loopy walt's Python answer.

#### Explanation

```
rZP.JAu<  # Implicit input
rZP       # Pair with reverse
   .J     # Join each inner list
     Au   # Dump onto stack
       <  # Check if less than
          # Implicit output

```
> 2 votes

# Answer
# Retina 0.8.2, 32 bytes

```
¶
$'¶$'$`¶$`
O`.+¶
M`(.+)¶\1$
^0

```

Try it online! Explanation: Based on @loopywalt's Python answer.

```
¶
$'¶$'$`¶$`

```

Create a list of `a+b`, `b+a`, `a+b`.

```
O`.+¶

```

Sort the first two elements of the list.

```
M`(.+)¶\1$
^0

```

Check that the last two elements are different.
> 2 votes

# Answer
# Pyth, 5 bytes

```
<sQs_

```

Try it online!

Port of @loopyWalt's python answer. Takes the input as a list of two strings `[a,b]`.

### Explanation

```
<sQs_Q    # implicitly add Q
          # implicitly assign Q = eval(input())
<         # lexicographically compare
 sQ       # sum of Q
   s_Q    # sum of the reversal of Q

```
> 2 votes

# Answer
# Haskell \+ hgl, 10 bytes

```
gt.*cx*^Rv

```

Attempt This Online!

Takes the input as a list with two values. I don't like this format so I also solved it with a good io format:

# Haskell \+ hgl, 14 bytes

```
ap<gt<<fmp*^mp

```

Attempt This Online!

Honorable mention to:

```
ap~<l2 gt<<F$mp

```

which is 1 byte longer.

# Haskell \+ hgl, 13 bytes

```
gt.*Uc mp*^Sw

```

Attempt This Online!

This uses a tuple with two values. It's a compromise between the two formats and is *slightly* shorter than the longer of the two.

# Haskell \+ hgl, 9 bytes

```
cb cx*^Rv

```

Attempt This Online!

This outputs a comparison (3 values) instead of a boolean (2 values). This is shorter than the first answer, however the output format isn't officially permitted in the challenge (although I haven't got a "No" yet).

I actually prefer this format since it's generally more modular and fits in with the systems available in hgl (part of why this is shorter). The 14 byte answer can also be made to use this format by replacing `gt` with `cp`, but it makes no difference to the byte count.

# Reflection

The 10 byte and 9 byte answers are pretty tight. The 10 byte answer (and the 13 byte answer) could potentially be shorter if `on gt` were given a 2 byte name (`cb` is the 2 byte name of `on cp` and the reason the 9 byte answer is shorter), however it's a bit hard to justify that. A 3 byte name might be useful anyway.

However I am really concerned with improving the 14 byte answer. The other answers are in my opinion an abuse of the format. This is a very simple challenge and if I were to encounter this challenge as a part of a larger challenge there's no way I would get the input in such a format. I'd get it in a format much more similar to what the 14 byte answer expects. The issue that blows up the size of that answer is that in order to thread through two separate arguments, both of which are used twice requires a good deal of glue. All the other answers benefit from only taking one input, making their glue much simpler.

So what's missing? Well, I have trouble coming up with a good reusable way to combine any of the existing parts. `on gt` doesn't actually help in this one unlike the other ones. And it's hard to make a version of `on` that actually does help. However there are pretty much two salient functions here `gt` and `mp`. All the glue is just a way to combine two functions, so maybe all of it should just be one function.

```
gt+^$mp

```

This would actually make things shorter (a lot shorter) and since it does combine two arguments it seems plausible that it could be reused at some point in the future. It's not a slam-dunk, it's not a clear hole in the language, but it's about the best I can do in this case.
> 2 votes

# Answer
# Japt, 5 bytes

Takes input as an array.

```
¬<UÔ¬

```

Try it (Includes all test cases)
> 1 votes

# Answer
# Factor, 36 bytes

```
[ 2dup append -rot prepend before? ]

```

Try it online!

```
         ! "ac" "a"
2dup     ! "ac" "a" "ac" "a"
append   ! "ac" "a" "aca"
-rot     ! "aca" "ac" "a"
prepend  ! "aca" "aac"
before?  ! f

```
> 1 votes

# Answer
# C (gcc) `-m32`, 78 bytes

This is a comparison function, it outputs \\$a + b \lesseqqgtr b + a\\$, where \\$+\\$ is string concatenation.

```
f(a,n,b,m){int c[4][n+m];wcscmp(wcscat(wcscpy(c),b),wcscat(wcscpy(c+2,b),a));}

```

Try it online!
> 0 votes

---
Tags: code-golf, string, decision-problem
---


title: Zahlen auf Deutsch! (Numbers in German)

text:
# Question
Title: Zahlen auf Deutsch! (Numbers in German)
Your task is to write a program that receives a base 10 number from 0 to 99 and outputs the German name of that number with non-ASCII characters replaced with ASCII equivalents.

## German number names

```
0 -> null
1 -> eins
2 -> zwei
3 -> drei
4 -> vier
5 -> fuenf
6 -> sechs
7 -> sieben
8 -> acht
9 -> neun
10 -> zehn
11 -> elf
12 -> zwoelf
13 -> dreizehn
14 -> vierzehn
15 -> fuenfzehn
16 -> sechzehn
17 -> siebzehn
18 -> achtzehn
19 -> neunzehn
20 -> zwanzig
21 -> einundzwanzig
22 -> zweiundzwanzig
23 -> dreiundzwanzig
24 -> vierundwanzig
30 -> dreissig
31 -> einunddreissig
40 -> vierzig
41 -> einundvierzig
50 -> fuenfzig
60 -> sechzig
70 -> siebzig
80 -> achtzig
90 -> neunzig

```

TL;DR - 0-12 are irregular, 13-19 are mostly just the number plus zehn, multiples of ten are mostly the number plus zig, and other numbers are the number, und, and then the multiple of ten. There are some irregularities, though.

## Rules

* This is code golf, so the lowest byte count wins.
* Standard loopholes apply.
* Any standard input/output methods are allowed.
* You may use any case you want, as long as it's consistent across different runs.

## Test Cases

```
3 -> drei
12 -> zwoelf
14 -> vierzehn
16 -> sechzehn
30 -> dreissig
52 -> zweiundfuenfzig
90 -> neunzig

```

# Answer
> 9 votes
# JavaScript (ES6), 213 bytes

```
f=(n,m=8,u=n%10)=>n<20?`null ein5 zw26 drei vier fuenf sech7 sieb89 acht neun zehn elf zwoelf`.replace(/\d/g,n=>['enasisn'[(m^n)%10]]).split` `[~~n]||f(u,0)+'zehn':(u?f(u,2)+'und':'')+f(n/=10,0)+(n^3?'zig':'ssig')

```

Try it online! (test cases)
Try it online! (all values from 0 to 99)

### How?

`eins`, `zwei`, `sechs` and `sieben` have different forms when they're used as prefixes. To support these alternate forms, some letters are encoded as decimal digits:

```
ein5 zw26 sech7 sieb89

```

Given a digit \\$n\\$ and a parameter \\$m\\$, the correct letter is obtained with:

```
[ 'enasisn'[(m ^ n) % 10] ]
// 0123456

```

The outer brackets are used to coerce the result to an empty string if it's undefined.

We use:

* \\$m=0\\$ for a prefix of `zehn` or `zig`
* \\$m=2\\$ for a prefix of `und`
* \\$m=8\\$ for the regular form

This gives the following table:

```
 m | n | m^n | %10 | letter
---+---+-----+-----+-----------------
 0 | 5 |  5  |  5  | 's' -> eins (1)
 0 | 2 |  2  |  2  | 'a' \_ zwan (2)
 0 | 6 |  6  |  6  | 'n' /
 0 | 7 |  7  |  7  |  -  -> sech
 0 | 8 |  8  |  8  |  -  \_ sieb
 0 | 9 |  9  |  9  |  -  /
---+---+-----+-----+-----------------
 2 | 5 |  7  |  7  |  -  -> ein
 2 | 2 |  0  |  0  | 'e' \_ zwei
 2 | 6 |  4  |  4  | 'i' /
 2 | 7 |  5  |  5  | 's' -> sechs
 2 | 8 | 10  |  0  | 'e' \_ sieben
 2 | 9 | 11  |  1  | 'n' /
---+---+-----+-----+-----------------
 8 | 5 | 13  |  3  | 's' -> eins
 8 | 2 | 10  |  0  | 'e' \_ zwei
 8 | 6 | 14  |  4  | 'i' /
 8 | 7 | 15  |  5  | 's' -> sechs
 8 | 8 |  0  |  0  | 'e' \_ sieben
 8 | 9 |  1  |  1  | 'n' /

```

*(1) Not used*
*(2) Used for -zig only*

# Answer
> 4 votes
# Retina 0.8.2, ~~162~~ 157 bytes

```
12
zwo11
11
elf
(\d)(.)
$2und$1zig
3z
3ss
0?und1.+
zehn
0und

0
null
1
eins
su
u
2
zwei
eiz
anz
3
drei
4
vier
5
fuenf
6
sechs
7
sieben
8
acht
9
neun
sz|enz
z

```

Try it online! Link is to test suite that automatically generates the results for `0-99`. Explanation:

```
12
zwo11
11
elf

```

Process `12` and `11` first.

```
(\d)(.)
$2und$1zig

```

For two digit inputs, switch the digits, insert `und`, and suffix `zig`.

```
3z
3ss

```

Except `dreizig` becomes `dreissig`.

```
0?und1.+
zehn

```

`nullundeinzig` becomes `zehn`, as does `undeinzig` when a suffix of any other digit.

```
0und

0
null

```

Delete a `nullund` prefix but a lone `0` becomes `null`.

```
1
eins
su
u

```

`1` becomes `eins` unless it's a prefix in which case it's only `ein`.

```
2
zwei
eiz
anz

```

`2` becomes `zwei` except before `zig` in which case it becomes `zwan`.

```
3
drei
4
vier
5
fuenf
6
sechs
7
sieben
8
acht
9
neun

```

Translate the remaining digits.

```
sz|enz
z

```

Fix up `sechszehn`, `siebenzehn`, `sechszig` and `siebenzig` to `sechzehn`, `siebzehn`, `sechzig` and `siebzig`.

Edit: Saved 4 bytes thanks to @Arnauld.

# Answer
> 3 votes
# Python \+ num2words, ~~54 107 104~~ 91 bytes

```
lambda n:num2words(n,0,'de').translate({252:'ue',246:'oe',223:'ss'})
from num2words import*

```

+53 bytes because we have to replace non-ASCII with ASCII equivalents.
-3 thanks to *@CreativeName*
-13 thanks to *@Neil*

# Answer
> 2 votes
# Charcoal, 127 bytes

```
≔Ｅ⪪”&⌈⪪γ,‴\Π↶QＢσＰc�⁸QＤι,ÀH⁸²V≧τ⁼θＣUH↶⊙↨Ｈ⊖Ｏ³j⪫JＷＸ<⸿Ｄη″β↓”p⪪ιqζＮθ≔﹪θχη¿‹θ¹³⁺⌈§ζθ×s⁼θ¹¿‹θ²⁰⁺⌊§ζη⌈§ζχ«∧η⁺⌈§ζηund⌊§ζ÷θχ⎇⁼³÷θχss¦z¦ig

```

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

```
≔Ｅ⪪”...”p⪪ιqζ

```

Split a compressed string on `p` and then split each substring on `q` (for the numbers `2`, `6` and `7`).

```
Ｎθ≔﹪θχη

```

Input the number in base `10` and take the remainder modulo `10`.

```
¿‹θ¹³

```

If the number is less than `13`, then...

```
⁺⌈§ζθ×s⁼θ¹

```

... output the maximum of the two substrings for that number, plus an extra `s` if the number is `1`.

```
¿‹θ²⁰

```

Otherwise, if the number is less than `20`, then...

```
⁺⌊§ζη⌈§ζχ

```

... output the minimum of the two substrings for that number modulo `10`, plus the substring for `10` (although I could have just used the string literal at this point).

```
«

```

Otherwise:

```
∧η⁺⌈§ζηund

```

If the remainder modulo `10` is not zero, then output the maximum of the two substrings for that number, plus the literal string `und`.

```
⌊§ζ÷θχ

```

Output the minimum of the two substrings for the number integer divided by `10`. This outputs `zwan` for `20-29`, `sech` for `60-69`, and `sieb` for `70-79`.

```
⎇⁼³÷θχss¦z¦ig

```

Output `ssig` if the number is in the range `30-39` otherwise output `zig`.

It looks as if the alternate forms are just the first four letters of the regular form, but this only works if you use the original accented characters, which Charcoal can't compress anyway, and working around the cases of `15` and `50-59` just takes too many bytes.

# Answer
> 2 votes
# Mathematica, 427 bytes

Golfed version, try it online!

```
Module[{o,t},o={"null","eins","zwei","drei","vier","fuenf","sechs","sieben","acht","neun"};t={"","","zwanzig","dreissig","vierzig","fuenfzig","sechzig","siebzig","achtzig","neunzig"};Which[0<=n<10,o[[n+1]],10<=n<20,StringJoin[{"zehn","elf","zwoelf","dreizehn","vierzehn","fuenfzehn","sechzehn","siebzehn","achtzehn","neunzehn"}[[n-9]]],20<=n<100,StringJoin[{If[Mod[n,10]!=0,o[[Mod[n,10]+1]]<>"und",""],t[[Quotient[n,10]+1]]}]]]

```

Ungolfed version

```
germanNumber[n_Integer] := Module[{ones, tens},
  ones = {"null", "eins", "zwei", "drei", "vier", "fuenf", "sechs", "sieben", "acht", "neun"};
  tens = {"", "", "zwanzig", "dreissig", "vierzig", "fuenfzig", "sechzig", "siebzig", "achtzig", "neunzig"};

  Which[
   0 <= n < 10, ones[[n + 1]],
   10 <= n < 20, StringJoin[{"zehn", "elf", "zwoelf", "dreizehn", "vierzehn", "fuenfzehn", "sechzehn", "siebzehn", "achtzehn", "neunzehn"}[[n - 9]]],
   20 <= n < 100, StringJoin[{If[Mod[n, 10] != 0, ones[[Mod[n, 10] + 1]] <> "und", ""], tens[[Quotient[n, 10] + 1]]}]
   ]
  ]

```

# Answer
> 1 votes
# 05AB1E, 108 bytes

```
'¡Ö.•вß³á∍>jO5:+VÍÏnтågÏÇ&õL1δç´#₄’WH‹fÈ7Pm•#D9ÝÁè©ć«¦¦®¦¦¦.•8WÏ•š…zig«„iz…iss:.•j(}•3ô'z:®¦ć¨š…und«õšδì)˜Iè

```

Try it online or verify the entire list.

**Explanation:**

```
'¡Ö          '# Push dictionary string "null"
.•вß³á∍>jO5:+VÍÏnтågÏÇ&õL1δç´#₄’WH‹fÈ7Pm•
              # Push compressed string
              #  "eins zwei drei vier fuenf sechs sieben acht neun zehn elf zwoelf"
  #           # Split it on spaces to a list
D             # Duplicate this list
 9Ý           # Push a list in the range [0,9]
   Á          # Rotate it to [9,0,1,2,3,4,5,6,7,8]
    è         # 0-based index each in the copy:  ["zehn","eins","zwei","drei","vier",
              #  "fuenf","sechs","sieben","acht","neun"]
     ©        # Store this list in variable `®` (without popping)
      ć       # Extract head; push first item and remainder-list separately
       «      # Append this "zehn" to each item in the remainder-list
        ¦¦    # Remove the first two items ("einszehn" and "zeizehn")
®             # Push list `®` again
 ¦¦¦          # Remove the first three items ("zehn", "eins", and "zei")
    .•8WÏ•š   # Prepend "zwan" to the list
…zig«         # Append "zig" to each item in the list
 „iz…iss:     # Replace all "iz" with "iss"
 .•j(}•       # Push compressed string "enzsz"
       3ô     # Split it into parts of size 3: ["enz","sz"]
         'z: '# Replace both with "z"
              # (with `®¦¦¦.•8WÏ•š…zig«„iz…iss:.•j(}•3ô'z:` we've pushed list
              #  ["zwanzig","dreissig","vierzig","fuenfzig","sechzig","siebzig",
              #  "achtzig","neunzig"])
®¦            # Push list `®`, and remove the first item "zehn"
  ć           # Extract head "eins"
   ¨          # Remove its last letter "s"
    š         # Prepend "ein" back to the list
     …und«    # Append "und" to each item in the list
          õš  # Prepend an empty string "" to the list
δ             # Apply double-vectorized on the two lists:
 ì            #  Prepend
)             # Wrap everything on the stack into a list
 ˜            # Flatten it
  Iè          # Use the input to 0-based index into it
              # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (sections *How to use the dictionary?* and *How to compress strings not part of the dictionary?*) to understand why `'¡Ö` is `"null"`; `.•вß³á∍>jO5:+VÍÏnтågÏÇ&õL1δç´#₄’WH‹fÈ7Pm•` is `"eins zwei drei vier fuenf sechs sieben acht neun zehn elf zwoelf"`; `.•8WÏ•` is `"zwan"`; and `.•j(}•` is `"enzsz"`.

# Answer
> 1 votes
# Haskell, 341 bytes

```
n 0="null"
n 1="eins"
n 10="zehn"
n 11="elf"
n 2="zwei"
n 12="zwoelf"
n 20="zwanzig"
n 3="drei"
n 30="dreissig"
n 4="vier"
n 5="fuenf"
n 6="sechs"
n 16="sechzehn"
n 60="sechzig"
n 7="sieben"
n 17="siebzehn"
n 70="siebzig"
n 8="acht"
n 9="neun"
n t|t<20=n(t-10)++"zehn"
n t|mod t 10==0=n(div t 10)++"zig"
n t=n(mod t 10)++"und"++n(t-mod t 10)

```

Try it online!

---
Tags: code-golf, string, number, natural-language
---


# Question
Title: Replace 0s In a String With Their Consecutive Counts
# Challenge

Given a string of any length which contains only digits from `0` to `9`, replace each consecutive run of the digit `0` with its length.

## Test Cases

1. `1234500362000440``1234523623441`
2. `123450036200044``123452362344`
3. `000000000000``12`
4. `0123456789``1123456789`
5. `1234567890``1234567891`
6. `123456789``123456789`
7. `010203004050``11121324151`

## Note

The shortest answer in bytes wins as per rules

# Answer
# Retina 0.8.2, 6 bytes

```
0+
$.&

```

Try it online! Link includes test cases. Explanation: Unary to decimal conversion.
> 14 votes

# Answer
# JavaScript, 31 bytes

```
s=>s.replace(/0+/g,x=>x.length)

```

Try it online!
> 11 votes

# Answer
# Pip, 7 bytes

-1 byte by jezza\_99 / DLosc

```
aR+X0#_

```

Wow pip is really good at regex

Try It Online!

```
aR+X0#_
aR+X0     Replace all occurrences of (regexified zero with a +)
     #_   with it's length

```
> 10 votes

# Answer
# Japt, 7 bytes

```
r+iT Èl

```

Try it here

```
r+iT Èl     :Implicit input of string
r           :Replace
 +i         :  "+" prepended with
   T        :    0, giving the RegEx /0+/g
     È      :  Pass each match through a function
      l     :    Length

```
> 9 votes

# Answer
# QuadR, 5 bytes

```
0+
⍵L

```

Try it online!

`0+` Replace any runs of zeros

`⍵L` with the match Length
> 8 votes

# Answer
# Vyxal `s`, 7 bytes

```
ĠṠƛ0cßL

```

Try it Online!

## Explained

```
ĠṠƛ0cßL
Ġ       # Group on consecutive items
 Ṡ      # join each into a single string
  ƛ     # To each group:
   0c   #   if it contains 0:
     ßL #     push the length of the string
        # the s flag joins into a single string

```

An alternate 8 byter that uses regex match replacement

```
‛0+$⁽Løṙ

```

Try it Online!

## Explained

```
‛0+$⁽Løṙ
‛0+       # The string "0+"
   $      # pushed under the input
    ⁽L    # a function object that returns the length of its argument
      øṙ  # replace instances of runs of 0 with their length

```
> 6 votes

# Answer
# Python 3, ~~91~~ 90 bytes

```
lambda x:''.join(l>"0"and l or f'{len([*g])}'for l,g in groupby(x))
from itertools import*

```

Try it online!

*-1 byte thanks to The Thonnu*

I use the `itertools` module's `groupby` function to group consecutively.
> 6 votes

# Answer
# \>\<\>, 55 bytes

```
i:'0'= ?v>:0(?;o
='0':i<1<\n$v?
      \+1~  /

```

Try it
> 6 votes

# Answer
# 05AB1E, 7 bytes

```
0ÃηRāR:

```

Try it online!

* -6 thanks to Kevin Cruijssen

#### Explanation

```
0ÃηRāR:   # Implicit input
0Ã        # List intersection with [0]
  ηR      # Reversed prefixes
    āR    # Reversed length range
      :   # Infinite replacement

```

Previous 13 byte answer

```
.γ}εD0.åig}}J   # Implicit input
.γ}             # Group by consecutive items
   ε       }    # For each group:
    D           #  Duplicate the group
     0.åi }     #  If 0 is in the group:
         g      #   Push its length
            J   # Join everything into a single string

```
> 6 votes

# Answer
# , ~~64~~ ~~58~~ 57 bytes

*Edit: -1 byte thanks to @Dominic van Essen*.

```
\(x){regmatches(x,t)=Map(attr,t<-gregexpr("0+",x),"m")
x}

```

Attempt This Online!

`R` has some weird string manipulation functions...
> 5 votes

# Answer
# Raku, 18 bytes

```
{S:g[0+]=$/.chars}

```

Try it online!
> 4 votes

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

```
s/0+/length$&/eg

```

Try it online!
> 4 votes

# Answer
# Vim, 28 bytes

`:s/0\+/\=len(submatch(0))/g` `Enter`

Try it online!

We cannot use `0*` because it matches the empty string between digits.
> 4 votes

# Answer
# Retina 0.8.2, 8 bytes

```
(0+)
$.1

```

Try it online!

### How it works

Match runs of zeros (`0+`), capture each match in a group (`( )`), replace it with the length of the most recent capture (`$.1`).
> 3 votes

# Answer
# \>\<\>, 28 bytes

```
0i:"0"=?v{:?n}ol?!
~1+00.  >

```

Try it online!
> 3 votes

# Answer
# C (gcc), 70 bytes

```
n;f(char*a){*a-48?n=!printf(n?"%d":"%c",n?:*a++),*a&&f(a):f(a+!!++n);}

```

Try it online!

# C (gcc), 62 bytes by c--

```
n;f(int*a){*a-48?n=!printf(n?"%d":a++,n),*a&&f(a):f(a+!!++n);}

```

Try it online!
> 3 votes

# Answer
# Ruby, 16 bytes

```
gsub /0+/,&:size

```

Attempt This Online!
> 3 votes

# Answer
# Python, ~~62~~ 57 bytes

```
lambda n:re.sub("0+",lambda s:str(len(s[0])),n)
import re

```

Attempt This Online!

-5 bytes thanks to @xnor

Regex solution, port of @mathcat's Pip answer
> 3 votes

# Answer
# Excel VBA, ~~100~~ 77 bytes

Saved 23 bytes thanks to a translation by Taylor Raine

```
For i=2^15-1To 1Step-1:[B1]=i:[A1]=[Substitute(A1,Rept(0,B1),B1)]:Next:[B1]="

```

Input is in the cell `A1` of the active sheet. Output is in the same cell. The code is run from the immediate window in VBA. The only clever bit is that Excel only allows 32,767 characters in a cell and counting down from there is less bytes than counting down from the length of the input.
> 3 votes

# Answer
# Bash - ~~181~~ 158 chars

*Edit 1: I used this trick for the `for` loop, remove whitespace, condence an `if` statement*

```
n=0;for ((i=0;i<${#1};i++));{ c="${1:$i:1}";if [ $c = '0' ]; then ((n++)); else [ $n -ne 0 ] && { echo -n $n;n=0;};echo -n $c;fi;};[ $n -ne 0 ] && echo -n $n

```

## Explanation

```
# a counter of how far into a sequence of zeros we are
# this is zero if we're not in a 'zero-sequence'
n=0

# iterate over all the characters
# $1 is the first function argument ($0 would be the script name)
for (( i=0; i<${#1}; i++ )); do
    # get the current char
    c="${1:$i:1}"

    # if it is a zero, then increment the counter
    if [ $c = '0' ]; then
        ((n++));
    # if it is NOT a zero
    else
        # if a zero sequence is over (given that the counter is
        # not equal to zero and the current char isn't zero)
        if [ $n -ne 0 ]; then
            # print the number of zeros in the sequence,
            # and reset the counter to zero
            echo -n $n;
            n=0;
        fi;
    echo -n $c;
    fi
done
# check if there was a zero sequence terminating the string,
# as we wouldn't otherwise check as there wouldn't be a non-zero
# char initiating the check
if [ $n -ne 0 ]; then echo -n $n; fi

```

I referred to this SO answer for how to iterate over a string in Bash and this AU answer for a short way to increment a variable
> 3 votes

# Answer
# K (ngn/k), 25 bytes

```
{,/$(.'x)|#'x:(&~=':x)_x}

```

Try it online!

* `x:(&~=':x)_x` split the input where it changes, and reassign to `x`
* `(.'x)|#'x` take the maximum of the chunk of input (converted to its corresponding integer) and its count
* `,/$` convert to strings and flatten (and implicitly return)
> 3 votes

# Answer
# Julia 1.0, 27 bytes

```
!x=replace(x,r"0+"=>length)

```

Try it online!
> 2 votes

# Answer
# Jelly, 8 bytes

```
Œgċ”0ȯƊ€

```

A full program that accepts a string of digit characters and prints the result.

**Try it online!**

### How?

```
Œgċ”0ȯƊ€ - Main Link: list of characters, S
Œg       - group runs
       € - for each group:
      Ɗ  -   last three links as a monad - f(group):
   ”0    -     literal '0' character
  ċ      -     count occurrences
     ȯ   -     logical OR (group)
         - implicit, smashing print

```
> 2 votes

# Answer
# Husk, 8 bytes

```
ṁ?IosLig

```

Try it online!
> 2 votes

# Answer
# Factor, 42 bytes

```
[ R/ 0+/ [ length >dec ] re-replace-with ]

```

Try it online!
> 2 votes

# Answer
# Zsh `--extendedglob`, 24 bytes

```
<<<${1//(#m)0##/$#MATCH}

```

Try it Online!
> 2 votes

# Answer
# Brachylog, 11 bytes

```
ḅ{ị0&lṫ|}ᵐc

```

Try it online!

### Explanation

I was hoping for some automatic number -\> string conversion, but no dice.

```
ḅ{ị0&lṫ|}ᵐc
ḅ            Break the input string into blocks of identical characters
 {      }ᵐ   Map this predicate to each block:
  ị            Convert to integer
   0           Assert that the result is zero
    &l         If so, get the length of the block
      ṫ        and convert to string
       |       If that failed (because the number wasn't zero), return the block unchanged
          c  Concatenate the results together into a single string

```
> 2 votes

# Answer
# Java, 88 bytes

```
s->java.util.regex.Pattern.compile("0+").matcher(s).replaceAll(r->r.group().length()+"")

```

Try it online!
> 2 votes

# Answer
# \>\<\>, ~~23~~ 18 bytes

```
\&l:?n&o]
\i:'0'-?

```

Try it online!
> 2 votes

# Answer
# PHP, ~~110~~ ~~96~~ ~~94~~ 86 bytes

```
try{for(;;)if(!~~$c=fgetc(STDIN))$x++;else{echo$x?:"",$c;$x=0;}}finally{echo$x?$x:"";}

```

Try it online!

Takes input via STDIN, outputs via STDOUT.
> 2 votes

# Answer
# Java 19, 156 ~~161~~ ~~162~~ bytes

```
interface A{static void main(String[] a){var i=0;var s="";for(var c:a[0].toCharArray())if(c==48)i++;else{s+=i>0?i+""+c:c;i=0;}System.out.print(i>0?s+i:s);}}

```

## Without Java's golfing tax, 113 bytes

```
var i=0;var s="";for(var c:a[0].toCharArray())if(c==48)i++;else{s+=i>0?i+""+c:c;i=0;}System.out.print(i>0?s+i:s);

```

Try it online!

Edit: replaced `'0'` with `48` as suggested in the comments. Thanks!

Edit: String concatentation is shorter than doing `var o=System.out;`
> 2 votes

# Answer
# SNOBOL4 (CSNOBOL4), 86 bytes

```
	I =INPUT
R	I ARB . L SPAN(0) . X REM . I	:F(O)
	O =O L SIZE(X)	:(R)
O	OUTPUT =O I
END

```

Try it online!

```
	I =INPUT				;* read input
R	I 					;* Match in I:
	  ARB . L				;*	ARBitrary characters (save as Left part of string) up to
		  SPAN(0) . X			;*	1 or more 0s (save as X)
			      REM . I		;*	REMaining characters (save as I)
					:F(O)	;* On no match, goto O
	O =O L SIZE(X)	:(R)			;* Append L and # of 0s to O and goto R
O	OUTPUT =O I				;* Output O and any remaining characters of I that didn't match
END

```
> 1 votes

# Answer
# Charcoal, 20 bytes

```
⭆⪪⁻⪫⪪ＳＩ⁰_0_×_²_∨№ι0ι

```

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

```
     Ｓ                  Input string
    ⪪                   Split on
       ⁰                Literal integer `0`
      Ｉ                 Cast to string
   ⪫                    Join with
        _0_             Literal string `_0_`
  ⁻                     Remove matching substrings
            _           Literal string `_`
           ×            Repeated
             ²          Twice
 ⪪                      Split on
              _         Literal string `_`
⭆                       Map over pieces and join
                №       Count of
                  0     Literal string `0`
                 ι      In current piece
               ∨        Logical Or
                   ι    Current piece

```

String separators are only needed between consecutive strings so the code has been tweaked to avoid them to reduce the byte count. `⭆Ｓ∨Ｉι_0_` also works instead of `⪫⪪ＳＩ⁰_0_` for the same byte count.
> 1 votes

# Answer
# Dart (2.18.4), 63 bytes

```
r(s)=>s.replaceAllMapped(RegExp('0+'),(m)=>'${m.end-m.start}');

```

```
String replaceZerosWithTheirConsecutiveCounts(String src) {
  return src.replaceAllMapped(
    RegExp('0+'),
    (Match match) => '${match.end - match.start}',
  );
}

```
> 1 votes

# Answer
# , 16 bytes

```
'0+'":@#rxapply]

```

Attempt This Online!

Fairly simple regex solution:

```
'0+' ":@#rxapply ]
'0+'     rxapply ]    apply to all relevant patterns in the input
        #             length
     ":@              casted to string

```

# , 47 bytes

```
' '-.~[:,(1,2~:/\'0'&=)([`(":@#)@.('0'&e.));.1]

```

Attempt This Online!

Horrendously long non-regex solution. This is the only way I could really think of approaching this, since, afaik, J doesn't have a builtin for grouping according to a boolean matrix or similar.
> 1 votes

# Answer
# Bash `--extglob`, 57 bytes

```
j=$1;for w in ${1//[1-9]/ };{ j=${j/+(0)/${#w}};}
echo $j

```

Try it Online!
> 1 votes

# Answer
# Pyth, 11 bytes

```
sm`|vedhdr8

```

Try it online!

### Explanation

```
sm`|vedhdr8Q    # implicitly add Q to the end
                # implicitly assign Q = eval(input())
         r8Q    # length encode Q
s               # concatenate together
 m              # map over lambda d
  `             # convert to string
   |            # short circuiting or
    ved         # evaluate the second element of d
       hd       # or take the first element of d

```
> 1 votes

# Answer
# Lua 68 bytes

```
s=io.read("*a")for i=#s,1,-1 do s=s:gsub(("0"):rep(i),i)end print(s)

```
> 1 votes

# Answer
# Python 3, ~~120~~ 119 bytes

```
def f(s):
    c=0;r=''
    for d in s:
        if d=='0':c+=1
        else:r+=f'{c if c!=0 else""}'+d;c=0
    return r+f'{c if c!=0 else""}'

```

Try it online!
> 1 votes

# Answer
# Arturo, 55 bytes

```
$=>[chunk&=>[&]|map'g->(`0`=g\0)?->size g->join g|join]

```

Try it

```
$=>[                   ; a function, assign input to &
    chunk&=>[&]        ; split input into blocks of equal, contiguous chars
    |                  ; then
    map'g->            ; map over each block and assign current elt to g
        (`0`=g\0)?     ; is the first element of g the character `0`?
        ->size g       ; then map g to the length of g
        ->join g       ; otherwise, map g to its joined string
    |                  ; then
    join               ; join the block of strings and numbers to a string
]                      ; end function

```
> 1 votes

# Answer
# PowerShell, 94 bytes

```
$r='';$_|sls '0+|[1-9]+'-a|% m*|%{$v=$_.value;('$r+=$v','$r+=$_.length')[$v-match"0+"]|iex};$r

```

**Ungolfed**

```
$args|%{

    # empty string to append to
    $r=''

    # '0+|[1-9]+' will match full string but split by zeroes and non-zeroes
    $_ | sls '0+|[1-9]+' -a | % m*| %{

        # value is the matched string
        $v=$_.value

        # true = 1; false = 0; shorter than an if statement
        # iex will execute the command in quotes
        ('$r+=$v','$r+=$_.length')[$v-match"0+"] | iex
    }

    # prints the results
    $r
}

```

Try it online!
> 1 votes

# Answer
# Nibbles, ~~7~~ 6 bytes (12 nibbles)

```
+.`=$$?`r$@,

```

```
  `=$           # chunk the input by
     $          # itself,
 .              # now map over each chunk:
      ?         #   if
       `r$      #   its value as an integer is nonzero
          @     #     return itself
                #   otherwise
           ,    #     return its length
+               # finally, join it all together

```
> 0 votes

# Answer
# Mathematica (13.1) 54 bytes

```
StringReplace[string,x:"0"..:>ToString@StringLength@x]

```
> 0 votes

# Answer
# Haskell, 76 bytes

```
import Data.List
r s=concat[case t!!0 of '0'->show$length t;_->t|t<-group s]

```

Try it online!
> 0 votes

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

Solution without using regexp

```
s=>s.split(0).map(c=>c?(a?a:"")+(a=1,c):(++a,""),a=0).join``+(--a?a:"")

```

Try it online!
> 0 votes

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


# Question
Title: Distance between the Sun and the nth planet
## Challenge

Predict the distance between the Sun and the nth planet when using **any formula** that gives the same result as the Titius–Bode law: `d=(3*2^n+4)/10`.

**BUT WAIT**... there is one restriction:

* Your source code can not include any of the Titius–Bode law's digits
* So, your program can not contain the characters `0`, `1`, `2`, `3`, or `4`

## Input

`n` a non-negative integer value:

* For Mercury `n` is -∞ no need to handle this case.
* `n=0` for Venus
* `n=1` for Earth
* `n=2` for Mars, and so on ...

## Output

Distance in astronomical unit between the Sun and the nth planet (decimal with at least one decimal place).

## Titius–Bode law

Distance in astronomical unit between the Sun and the nth planet is estimated by `d=(3*2^n+4)/10`.

## Example

```
0          --> 0.7
1          --> 1.0 or 1
11         --> 614.8

```

## Rules

* The input and output can be given in any convenient format.
* No need to handle **invalid input values**
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# 05AB1E, 7 bytes

```
oxOÌÌT/

```

Try it online!

**Explanation**

```
o          # push 2^input
 x         # pop a and push a, 2*a
  O        # sum stack
   ÌÌ      # add 2 twice
     T/    # divide by 10

```
> 11 votes

# Answer
# C (gcc), 22 bytes

```
-Df(x)=((6<<x)+8.)/''

```

Try it online!
> 11 votes

# Answer
# Haskell, ~~29~~ ~~28~~ ~~27~~ 25 bytes

```
s=9-7
d n=(6*s^n+8)/5/s/s

```

~~Nothing special, I'm afraid.~~ All allowed digits exactly once!

Try it online!
> 5 votes

# Answer
# JavaScript (Node.js), ~~20~~ 19 bytes

```
n=>((6<<n)+8)/5/~-5

```

Try it online!
> 5 votes

# Answer
# JavaScript (ES6), 20 bytes

*Saved 2 bytes thanks to @l4m2*

Does not support Mercury.

```
n=>(5-9-(9-6<<n))/~9

```

Try it online!

---

# JavaScript (ES7), 27 bytes

Supports Mercury.

```
n=>(k=5,--k+--k*--k**n)/-~9

```

Try it online!
> 4 votes

# Answer
# Java 8, ~~20~~ 18 bytes

```
n->((6<<n)+8f)/''

```

Port of l4m2's C answer, thanks to Kevin Cruijssen. Try it online here.

# Java 8, ~~30~~ 24 bytes

```
n->(9-5+(9-6<<n))/(5f+5)

```

My original approach; admittedly, it's not very creative. Try it online here.

Thanks to Kevin Cruijssen for golfing 6 bytes.
> 4 votes

# Answer
# Jelly,  ~~14~~  8 bytes

-3 thanks to miles (use of `æ«`, bit-shift) ..and -3 more by golfing from there

```
6æ«+8H÷⁵

```

**Try it online!**

### How?

```
6æ«+8H÷⁵ - Link: number, N (including -inf)
6        - literal six
 æ«      - bit-shift = 6*(2^N)
   +8    - add eight = 6*(2^N)+8
     H   - halve = 3*(2^N)+4
       ⁵ - literal ten
      ÷  - divide = (3*(2^N)+4)/10

```
> 4 votes

# Answer
# dc, ~~18~~ 17 bytes

```
zzrkr^zz+*8z/+A/p

```

Try it online!

Assuming *n* is all that's on the stack, we get the stack depth twice to push `1` and `2` onto the stack. Reverse these and use the `1` to set our precision (`k`). Reverse so that our stack is now `2 n`, exponentiate (`^`). Use `z` to get stack depth twice, again pushing `1` and `2` onto the stack. Add them (`+`) to get `3`, multiply (`*`) by our previous result. Push `8`, get the stack depth with `z` to push `2`, divide these (`/`) to push `4`. Add this (`+`) to the previous result, and divide by 10 (`A/`). Finally, `p`rint.

Knocked off a byte using `8z/` instead of `zF+v` to make a `4`.
> 3 votes

# Answer
# Retina 0.8.2, ~~54~~ ~~42~~ 35 bytes

```
.+
@@@$&$*_@@@@
+`@_
_@@
M`@
.$
.$&

```

Try it online! Link includes test cases. Edit: Saved 12 bytes thanks to @Leo. Explanation:

```
.
@@@$&$*_@@@@

```

Generate a pseudo-binary number using `@` as 1 and `_` as `*2`, having `3` as the first digit and `4` as the last digit, thus representing `3*2^n+4`.

```
+`@_
_@@

```

Convert to unary.

```
M`@

```

Convert to decimal.

```
.$
.$&

```

Divide by 10.
> 3 votes

# Answer
# Google Sheets, ~~27~~ ~~26~~ ~~25~~ 23 bytes

```
~~=((8-5)*(7-5)^A5+9-5)/(5+5)~~
~~=(9^.5*(7-5)^A5+9-5)/(5+5)~~
~~=(9^.5*(7-5)^A5+9-5)*.7/7~~
=(7-5)^A5*(.8-.5)+.9-.5

```

Take input from cell A5.

For a no-digit version (except the A5 is unavoidable),

```
=(code("")*code("")^a5+code(""))/code("

```

(there is a trailing newline)
> 3 votes

# Answer
# Whispers v2, 325 bytes

```
> 8
> 8
> 8
> 8
> 9
> 6
> Input
>> 5-6
>> 5-55
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 8
> 7
>> 9+9
>> 9*7
>> 55-56
>> 57⋅58
> 8
> 8
> 8
> 8
> 8
>> 58+55
>> 59+56
>> 66÷65
>> Output 67

```

Try it online!

Let me outline the problem with using Whispers:

Whispers is a single-expression, line-based programming language. Each line consists of a single mathematical expression. However, if the line starts with `>>`, the numbers used have different values to what they would normally express.

When a line begins with `>` (such as `> 8`) the value returned is the number shown, so that example would return `8` when referenced. `Input` returns an evaluated line from STDIN.

However, when the line starts with `>>`, such as `>> 5-6`, the numbers are interpreted as line references, i.e. the above line would call line `5`, then line `6`, then subtract the results.

Let's create a program that half-sticks to the rules first. This program doesn't use `0`, `1`, `2`, `3`, or `4` to represent those numbers, but does use them as line references. This 'half' solution is 96 bytes:

```
> 6
> 9
> Input
>> 2-1
>> 1=1
>> 4-5
>> 6*3
>> 7⋅4
>> 6+6
>> 8+9
>> 2+5
>> 10÷11
>> Output 12

```

Try it online!

Unfortunately, the challenge disallows the *characters* `0`, `1`, `2`, `3`, and `4` from appearing in the program, irregardless of what they represent. So, to work around this, we have to use line references with only the numbers `5`, `6`, `7`, `8` and `9` in their digits. This has the consequence that we cannot use any lines between `10` and `54`, which is what the massive chain of `> 8` are. In fact, all lines that represent a forbidden line reference has `> 8`, just for consistency.

So, let's remove those lines, but pretend they're still there, we just can't see them:

```
> 9
> 6
> Input
>> 5-6
>> 5-55
> 7
>> 9+9
>> 9*7
>> 55-56
>> 57⋅58
>> 58+55
>> 59+56
>> 66÷65
>> Output 67

```

Which is a very similar structure to the 'half' solution. Here's how this shortened solution works, with an input `11`:

```
> 9		; Line  5: Yield 9
> 6		; Line  6: Yield 6
> Input		; Line  7: Yield a line of input (11)
>> 5-6		; Line  8: Yield 3 	-	9 - 6
>> 5-55		; Line  9: Yield 2	-	9 - 7
⋮
> 7		; Line 55: Yield 7
>> 9+9		; Line 56: Yield 4	-	2 + 2
>> 9*7		; Line 57: Yield 2048 	-	2 ^ 11
>> 55-56	; Line 58: Yield 3	-	7 - 4
>> 57⋅58	; Line 59: Yield 6144	-	2048 ⋅ 3
⋮
>> 58+55	; Line 65: Yield 10	-	3 + 7
>> 59+56	; Line 66: Yield 6148	-	6144 + 4
>> 66÷65	; Line 67: Yield 614.8	-	6148 ÷ 10
>> Output 67	; Line 68: Output 614.8

```
> 3 votes

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

```
l$:?!vll-+$:+!
:*lrl<;n,a+l

```

Try it online!

Some heavy abuse of the stack length command (`l`) command here. Luckily, most of the numbers needed are in ascending order. Takes input through the `-v` flag
> 3 votes

# Answer
# Raku, 13 bytes

```
³+<*/Ⅹ+⅖

```

Try it online!

This formula uses Unicode characters with the right numeric values to stand in for the forbidden characters.

* ³ - SUPERSCRIPT THREE - value = 3
* Ⅹ - ROMAN NUMERAL TEN - value = 10
* ⅖ - VULGAR FRACTION TWO FIFTHS - value = 0.4
> 3 votes

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

```
lambda n:((6-9<<n)-~-5)/~9

```

Try it online!

---

# Python 2, ~~38~~ ~~34~~ ~~31~~ ~~28~~ 27 bytes

```
lambda n:((6-9<<n)-9.+5)/~9

```

Try it online!

---

Saved:

* -4 bytes, thanks to Giuseppe
* -1 byte, thanks to Jonathan Allan
> 2 votes

# Answer
# Symbolic Python, ~~69~~ 56 bytes

```
___=_==_
__=-~___
_=__**~-_*-~__+___+___**-___
_/=__-~__

```

Try it online! Implements `(3*2^(n-1)+2)/5`

### How?

```
# Input is stored in _ initially

___=_==_         # ___ = True (=1)
__=-~___         # __  = -~1 = 1 + 1 = 2
_=__**~-_*-~__+___+___**-___
# _ = 2**~-_ * -~2 + 1 + 1**-1 = 2**(n-1) * 3 + 1 + 1.0 = 3 * 2**(n-1) + 2.0
_/=__-~__        # _   = _ / (2 -~ 2) = _ / (2 + -~2) = _ / (2 + 2+1) = _ / 5

# Implicit output of _

```
> 2 votes

# Answer
# Mathics, 34 bytes

```
d[n_]:=((9-6)*(8-6)^n+(9-5))/(5+5)

```

Try it here!

My first time golfing in Mathics, so there's probably a bit more optimizing to be done.
> 2 votes

# Answer
# Jelly, ~~14~~ 12 bytes

```
‘⁺
¢*+Ḥ$Ç⁺÷⁵

```

Try it online!

About time for an explanation

## How it works

```
‘⁺        - Helper link. Can be called monadically, or niladically.
          - When called niladically, `0` is the left argument.
 ⁺        - Perform the previous command twice:
‘         -   Increment the left argument

¢*+Ḥ$Ç⁺÷⁵ - Main link. 1 argument: n
¢*        - Yield 2<sup>n</sup>
    $     - Perform the next two commands on 2<sup>n</sup>:
   Ḥ      -   Halve.           Yields 2<sup>n-1</sup>
  +       -   Add to 2<sup>n</sup>.       Yields 3⋅2<sup>n</sup>
     Ç    - Add 2.             Yields 3⋅2<sup>n</sup> + 2
      ⁺   - Add 2 again.       Yields 3⋅2<sup>n</sup> + 4
        ⁵ - Yield 10
       ÷  - Divide by 10.      Yields (3⋅2<sup>n</sup> + 4)/10

```
> 2 votes

# Answer
# Stax, 7 bytes

```
â╬╫▓♠âε

```

Run and debug it

PackedStax source encoding makes the character restrictions trivial. Unpacked, ungolfed, and commented this is the same program.

```
|2  2 to the power
3*  multiply by 3
4+  add 4
A/  divide by 10

```

Run this one
> 2 votes

# Answer
# BRASCA, 29 bytes

```
ig$}}:a$^A}:a*A}+:l/ml%mn'.on

```

Try it!

BRASCA only supports whole integers, so I had to spend a couple bytes to at least get one decimal, to pass the test cases.

## Explanation

```
                               - Implicit input
ig                             - Turn 0-9 into the actual numbers and concatenate
  $}}:a$^                      -    2^n
         A}:a*                 - (3*
              A}+              -       +4)
                 :l/           -          /10
                    ml%mn'.on  - Get the first decimal, and print the number.

```
> 2 votes

# Answer
# MathGolf, 8 bytes

```
ó∙☻√ΓΣ♂/

```

Try it online.

Actually the same amount of bytes as the straight-forward approach without :

```
ó3*4+♀√/

```

Try it online.

**Explanation:**

```
ó         # Take 2 to the power of the (implicit) input-integer
 ∙        # Triplicate it
  ☻       # Push 16
   √      # Take the square-root of that: 4.0
    Γ     # Wrap the four values on the stack into a list
     Σ    # Sum this list together
      ♂/  # Divide it by 10
          # (after which the entire stack is output implicitly as result)

ó         # Take 2 to the power of the (implicit) input-integer
 3*       # Multiply it by 3
   4+     # Add 4
     ♀√/  # Divide it by the square-root of 100 (10.0),
          # since `/` will be integer-division if both arguments are integers
          # (after which the entire stack is output implicitly as result)

```
> 2 votes

# Answer
# C# .NET, 18 bytes

```
n=>((6<<n)+8f)/''

```

`''` is an unprintable ASCII character with value `20`.

Port of *@l4m2*'s C answer.

Try it online.
> 1 votes

# Answer
# Ruby, 25 bytes

```
->n{6-5.6+6%5.7*(9-7)**n}

```

Try it online!

Output ±ε due to float imprecision.
> 1 votes

# Answer
# Whispers v2, 91 bytes

```
> Input
>> 9*56
>> 57⋅8
>> 58+7
>> 59÷6
> 5
>> ≺6
>> ≺7
>> ≺8
>> 5÷9
>> Output 65

```

Try it online!
> 1 votes

# Answer
# PowerShell, 38 bytes

```
(.9-.6)*[math]::pow(8-6,"$args")+.9-.5

```

Try it online!

-11 bytes thanks to @mazzy
> 1 votes

# Answer
# Lua, 55 bytes

```
o=#" "t=o+o function x(m)return((o+t)*t^m+t^t)/(5*t)end

```

Try it online!
> 1 votes

# Answer
# Scala, 41 bytes

A port of @O.O.Balance's answer.

Try it online!

```
val d:Int=>Float=n=>(9-5+(9-6<<n))/(5f+5)

```
> 1 votes

# Answer
# Stax, 8 bytes

```
à╙i;?«°☻

```

Run and debug it

I think this is a little bit unfair because the original code contains digits, but PackedStax doesn't... here's what it unpacks to:

# Stax, 9 bytes

```
|23*4+A:_

```

Run and debug it

```
|23*4+A:_
|2        # 2**n
  3*      # *3
    4+    # +4
      A:_ # float divided by 10

```
> 1 votes

# Answer
# Vyxal, 6 bytes

```
ET⇧⇧₀/

```

Try it Online!

!= `0`

## Explained

```
ET⇧⇧₀/
E      # 2 ** n
 T     # * 3
  ⇧⇧   # + 2 + 2
    ₀/ # divided by 10

```
> 1 votes

# Answer
# Thunno 2, 8 bytes

```
ODḌ+ƙƙT/

```

Port of Emigna's 05AB1E answer.

#### Explanation

```
ODḌ+ƙƙT/  # Implicit input
O         # Push 2 ** input
 DḌ       # Duplicate and double
   +      # Add (triple)
    ƙƙ    # Add 2 twice (add 4)
      T/  # Divide by ten
          # Implicit output

```

---

**Screenshot:**
> 1 votes

# Answer
# Pip, 13 bytes

```
U(U Ea*@PI)/t

```

Contains no digits at all. Attempt This Online!

### Explanation

Uses a slightly modified formula:

$$\frac{3\cdot(2^n+1)+1}{10}$$

```
U(U Ea*@PI)/t
     a         ; Command-line input
    E          ; 2 to that power
  U            ; Increment
      *        ; Times
       @PI     ; the first character of pi
U(        )    ; Increment that result
           /t  ; Divide by 10

```
> 1 votes

# Answer
# x86 machine code, ~~21~~ 20 bytes

```
6a 03                   push   0x3
58                      pop    eax
d3 e0                   shl    eax,cl
04 04                   add    al,0x4
50                      push   eax
db 04 24                fild   DWORD PTR [esp]
6a 0a                   push   0xa
de 74 24 00             fidiv  WORD PTR [esp+0x0]
58                      pop    eax
58                      pop    eax
c3                      ret

```

Pretty straightforward, except for two little details:

1. It's enough to add 4 to `al` \- adding it to `eax` is 1 byte longer
2. `[esp+0x0]` \- explicit displacement equal to 0 is needed to avoid the forbidden byte `0x34` (ASCII `4`) in the instruction's encoding; thanks to l4m2 for the idea!
> 0 votes

---
Tags: code-golf, math, restricted-source
---


title: String Concatenate

text:
# Question
Title: String Concatenate
You are given a string \\$s\\$ of characters from a to z. Your task is to count how many unique strings of length \\$n\\$ you can make by concatenating multiple prefixes of the string \\$s\\$ together.

Since the result can be superlative you can either choose to output the whole result, the result mod \\$2^{32}\\$ or the result mod \\$2^{64}\\$.

This is , shortest code wins.

Tests:

```
aaaaa 8 -> 1
abcdef 10 -> 492
aerodynamics 10 -> 507
disbelief 10 -> 511

```

# Answer
# Jelly, 9 bytes

```
¹ƤṗF€ḣ€QL

```

Try It Online!

This is very slow, so it will not run well for any of the test cases provided.

## Explanation

```
¹ƤṗF€ḣ€QL  Main Link: word as left argument, number as right argument
¹Ƥ         get prefixes of the word
  ṗ        cartesian power
   F€      flatten (join into one string) each list of prefixes
     ḣ€    take the first N characters of each string
       Q   deduplicate
        L  count the number of strings

```
> 5 votes

# Answer
# Nekomata, 10 bytes

```
rJᵐ#rj@au#

```

Attempt This Online!

```
rJᵐ#rj@au#
rJᵐ#         Ordered integer partition
    r        Range each
     j       Concatenate
      @      Nth (vectorized)
       au#   Count unique results

```
> 8 votes

# Answer
# JavaScript (ES12), 53 bytes

Expects `(s)(n)`, where `s` is given as an array of characters.

```
s=>g=(n,q=t=0)=>s.map(c=>q[n]?g[q]||=++t:g(n,q+=c))|t

```

Attempt This Online!

### Commented

```
s =>         // outer function taking s[] = input string
g = (        // inner recursive function taking:
  n,         //   n = target length
  q =        //   q = generated string (initially set to 0, then
             //       coerced to "0something")
  t = 0      //   t = output counter (defined in the global scope)
) =>         // NB: g is also used as an object to store all
             //     generated strings
s.map(c =>   // for each character c in s[]:
  q[n] ?     //   if q[n] is defined (target length reached):
    g[q] ||= //     unless g[q] is already defined,
      ++t    //     set it to a truthy value and increment t
  :          //   else:
    g(       //     do a recursive call:
      n,     //       pass n unchanged
      q += c //       append c to q
    )        //     end of recursive call
)            // end of map()
| t          // return t

```
> 7 votes

# Answer
# Python, 96 bytes

```
f=lambda s,n,j=0:n<2or sum(f(s,n-(j:=j+1))*all(s.find(s[k:j])for k in range(1,j))for c in s[:n])

```

Attempt This Online!

## How?

Does the recursion

\\$f(n) = \sum\_{j=1\ldots\min(n,|s|)}x(j)f(n-j)\\$

where

\\$x(n):=\begin{cases}0 & \text{if } s\[:n\] \text{ has a proper prefix equaling a suffix} \\\\ 1 & \text{else}\end{cases}\\$

is there to avoid double counting.
> 6 votes

# Answer
# Wolfram Language (Mathematica), 100 bytes

```
(a=#1;n=#2;Length[Union@@Map[a[[;;#]]&,Permutations/@IntegerPartitions[n,All,Range@Length@a],{3}]])&

```

Try it online!
Based on idea, that lengths of all prefixes in valid combination is integer partition of given number.
Very fast, but may be golfed more, I'll try!
Needs input as array of chars and number.
> 5 votes

# Answer
# 05AB1E, 9 bytes

```
ηIиæJIùÙg

```

Try it online. (Extremely slow, so no test suite. It'll even time out for all provided test cases..)

Or alternatively, a port of *@hyper-neutrino♦*'s Jelly answer is **9 bytes** as well:

```
ηIãJIδ∍Ùg

```

Try it online. (Faster than my approach above, but still extremely slow, so again no test suite.)

**Explanation:**

```
η          # Get the prefixes of the first (implicit) input-string
 Iи        # Repeat this list the second input-integer amount of times as flattened list
   æ       # Get the powerset of this
    J      # Join each inner list together to a string
     Iù    # Only keep strings of a length equal to the second input-integer
       Ù   # Uniquify this list of strings
        g  # Pop and push the length to get the amount of unique strings
           # (which is output implicitly as result)

η          # Get the prefixed of the first (implicit) input-string
 Iã        # Get the cartesian power with the second input-integer
   J       # Join each inner list together to a string
     δ     # Map over each inner string:
    I ∍    #  Extend or shorten it to a length of the second input-integer
       Ùg  # Same as above (including implicit output)

```
> 4 votes

# Answer
# Thunno 2 `L`, 11 bytes

```
ƒọʠ€Jæl¹=;U

```

Port of Kevin Cruijssen's 05AB1E answer.

Warning: this is very slow. It manages to complete the test case in the screenshot in ~10s on my computer.

#### Explanation

```
ƒọʠ€Jæl¹=;U  # Implicit input
ƒ            # Prefixes of the first input
 ọ           # Repeated second input number of times
  ʠ          # Powerset of this list
   €J        # Join each inner list
     æ   ;   # Filtered by:
      l      #  Pop and push the length
       ¹=    #  Equals the second input?
          U  # Uniquify this list
             # L flag gets the length
             # Implicit output

```

---

Thunno 2 isn't on ATO yet, so here's a screenshot of the local interpreter:
> 4 votes

# Answer
# Haskell, 125 bytes

```
import Data.List.Ordered
s#n=length(m!!n)where m=map(\n->nubSort$take n(cycle s):[p++q|l<-[1..n-1],p<-m!!l,q<-m!!(n-l)])[0..]

```

Try it online!
> 4 votes

# Answer
# Python, ~~120~~ 118 bytes

*-2 bytes thanks to @The Thonnu*

```
def g(s,n):a={0};f=lambda n,l="":n and[f(n-i,l+s[:i])for i in range(1,1+min(n,len(s)))]or a.add(l);f(n);return~-len(a)

```

Attempt This Online!
> 3 votes

# Answer
# Charcoal, 30 bytes

```
Ｎθ⊞υωＦυＦ⁻Ｅθ…⁺ι…ηθ⊕κυ⊞υκＩ№ＥυＬιθ

```

Try it online! Link is to verbose version of code. Takes `n` as the first input and `s` as the second input. Explanation:

```
Ｎθ

```

Input `n`.

```
⊞υωＦυ

```

Start a breadth-first search of concatenations of prefixes with the empty string.

```
Ｆ⁻Ｅθ…⁺ι…ηθ⊕κυ

```

For each concatenation so far, extend it up to the desired length with a cyclic prefix of the input string, then take each prefix of the result that has not yet been discovered.

```
⊞υκ

```

Push each new discovery to the list so that it can be processed on a later iteration.

```
Ｉ№ＥυＬιθ

```

Count how many strings were of the desired length.

For example, with an input of `10` and `abcdef`, the first pass produces the strings `a`, `ab`, `abc`, `abcd`, `abcde`, `abcdef`, `abcdefa`, `abcdefab`, `abcdefabc` and `abcdefabcd`. This is golfier than only producing the first six strings and waiting until `abcdef` is processed to produce the remaining four.
> 2 votes

# Answer
# Scala, 183 bytes

Modified from @97.100.97.109's answer.

---

Golfed version, try it online!

```
def g(s:String,n:Int)={val a=mutable.Set[String]("");def f(n:Int,l:String=""):Unit=if(n>0)(1 to math.min(n,s.length)).foreach(i=>f(n-i,l+s.substring(0,i)))else a.add(l);f(n);a.size-1}

```

Ungolfed version

```
import scala.collection.mutable

object Main {
  def g(s: String, n: Int): Int = {
    val a = mutable.Set[String]("")

    def f(n: Int, l: String = ""): Unit =
      if (n > 0) (1 to math.min(n, s.length)).foreach(i => f(n - i, l + s.substring(0, i)))
      else a.add(l)

    f(n)
    a.size - 1
  }

  def main(args: Array[String]): Unit = {
    println(g("aaaa", 8))
    println(g("abcdef", 10))
    println(g("aerodynamics", 10))
    println(g("disbelief", 10))
  }
}

```
> 2 votes

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


title: Gambling with an Alien

text:
# Question
Title: Gambling with an Alien
You met a 4-th dimensional being who challenged you to a game of dice. The rules are simple: each player rolls 3 6-sided dice and takes the sum of each combination of 2 dice. The player with the highest sum wins. If the first-highest sum is a tie, consider the second-highest sum, and so on.

Your opponent's dice look normal, but you think they might have more than 6 sides! **Your goal is to find out if the alien rolled a number higher than 6.**

Your input is a set of 3 integers, separated by at least one character (space or otherwise). Input must not be hard coded.

```
// All valid inputs
6 7 9
6, 7, 9
(6, 7, 9)

```

Your output is a string representing if the alien cheated. Any output is allowed, as long as two distinct values exist for cheating/valid. Appended whitespace is permitted.

```
"" // (U+1F600) Valid set of dice
"" // (U+1F620) Invalid set of dice

```

Examples:

```
<-: 8 11 9
->:        // Dice can be found to be 3, 5, and 6, which are all on 6-side die

```

```
<-: 9 11 6
->:        // Dice can be found to be 2, 7, and 4, which means the alien cheated!

```

Assumptions:

* Input will be 3 integers, 2-12
* Input numbers can be in any order
* Die values will be positive integers
* Alien only cheated if they rolled greater than 6

Write a program or function that takes inputs, returns or prints outputs.

Fewest bytes wins!

# Answer
# Husk, 8 bytes

```
¬>6-▼¹½Σ

```

Try it online!

Outputs `1` for normal dice, `0` if the alien cheated.

Checks whether half (`½`) of the sum (`Σ`) minus (`-`) the smallest () element is not (`¬`) greater than 6 (`>6`).
> 13 votes

# Answer
# , 28 bytes

```
function(x)sum(x/2)-min(x)>6

```

Try it online!

Same approach as my Husk answer.
> 7 votes

# Answer
# Haskell, 20 bytes

```
f l=any(<sum l/2-6)l

```

Try it online!

Inspired by *@DominicVanEssen* R answer.
Tells if it's a cheater (the alien.. not Dominic).
> 7 votes

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

```
f=(a,b,c)=>a>b|a>c?f(b,c,a):b+c-a<13

```

Try it online!

Like the hypot one
> 5 votes

# Answer
# C (gcc) (-O0), 73 bytes

```
#define g(a,b) if(a>b)a^=b^=a^=b;
f(a,b,c){g(a,b)g(b,c)g(a,b)a=b+c-a<13;}

```

Try it online!

Not the prettiest solution

# C (gcc) (-O0), 38 bytes, shamelessly copy this beautiful answer.

```
f(a,b,c){a=a>b|a>c?f(b,c,a):b+c-a<13;}

```

Try it online!

*-2 bytes thanks to AZTECCO*
> 5 votes

# Answer
# JavaScript (ES6), 35 bytes

Expects `([a,b,c])`. Returns *true* for cheating or *false* for valid.

```
A=>A.some(x=>eval(A.join`+`)/2>x+6)

```

Try it online!
> 5 votes

# Answer
# 05AB1E, ~~7~~ 6 bytes

```
O;αà6›

```

Inspired by *@DominicVanEssen*'s R answer.
Takes a list `[a,b,c]` as input, and outputs `1`/`0` for cheating/valid respectively.

Try it online or verify all test cases.

**Explanation:**

```
O       # Sum the three values in the (implicit) input-list
        #  e.g. [8,11,9] → 28
        #  e.g. [9,11,6] → 26
 ;      # Halve it
        #  → 14
        #  → 13
  α     # Take the absolute difference of this sum with each value in the
        # (implicit) input-list
        #  → [6,3,5]
        #  → [4,2,7]
   à    # Pop and push its maximum
        #  → 6
        #  → 7
    6›  # Check if this is larger than 6
        #  → 0
        #  → 1
        # (after which this is output implicitly as result)

```
> 4 votes

# Answer
# MATL, 10 bytes

```
2/sGX<-IE>

```

Try it out / Test three cases

Port of @Dominic van Essen's answers. 1 = You cheating alien! 0 = Never had a moment of doubt.

`4-sGX<E-F>` Try it online! is another 10 byter.

## MATL, 11 bytes

```
.5IXy-iY*7<

```

Try it out / Test three cases

Outputs truthy (all 1s) for no cheating, falsy (some 0s) for cheating.

For given input \[a, b, c\], the system of linear equations is : \\$ d\_2 + d\_3 = a \\$ , \\$ d\_1 + d\_3 = b \\$ , \\$ d\_1 + d\_2 = c \\$

Or in matrix form: \\$ \begin{bmatrix} 0 & 1 & 1 \\ 1 & 0 & 1 \\ 1 & 1 & 0 \end{bmatrix}\begin{bmatrix} d\_1 \\ d\_2 \\ d\_3 \end{bmatrix} = \begin{bmatrix} a \\ b \\ c \end{bmatrix} \\$

The solution - the set of dice values - is the inverse of the matrix on the left, multiplied by the input. This inverse is equal to \\$ 0.5 - I\_3 \\$ (where \\$I\_3\\$ is the 3x3 identity matrix).

`.5IXy-` computes this inverse, `iY*` multiplies that by the input, `7<` checks if all of the resulting dice values are less than 7 (and hence valid).
> 4 votes

# Answer
# Retina 0.8.2, 34 bytes

```
\d+
$*
O`1+
^
12$*
(1+)(1+),\1,\2$

```

Try it online! Link includes test cases. Outputs `1` for normal dice, `0` if the alien cheated. Explanation:

```
\d+
$*

```

Convert to unary.

```
O`1+

```

Sort into order.

```
^
12$*

```

Add 12 to the smallest value.

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

```

The sum should then equal or exceed the sum of the other two values.
> 3 votes

# Answer
# Vyxal, 7 bytes

```
∑½?g-6≤

```

Try it Online!

Port of @Dominic van Essen's Husk answer. `1` if the dice are normal, `0` if the alien used tesseracts for its dice.

```
∑½?g-6≤ # Takes list as input
∑       # Sum of the list
 ½      # Halved..
    -   # Minus...
  ?g    # Smallest element of the input
     6≤ # Is less than or equal to 6?

```
> 2 votes

# Answer
# , ~~20~~ 11 bytes

```
12<+/-2*<./

```

-9 bytes thanks @Bubbler

Try it online!
> 2 votes

# Answer
# Python 3.8 (pre-release),~~38~~ ~~28~~ 27 bytes

**Latest Answer**

```
lambda *a:sum(a)/2-min(a)>6

```

Try it online!

**Old Answer**

```
lambda x,y,z:max(x-y+z,x+y-z,y+z-x)>12

```

Try it online!

**Output** : Gives `True` when cheated and `False` when not.

Thank you Aetol for the suggestion of using `a+b+c-2*min(a,b,c)>12` instead of `max(x-y+z,x+y-z,y+z-x)>12`

This R answer gave the nice `sum(a)/2-min(a)>6` Idea
> 2 votes

# Answer
# , 28 bytes

```
function(x)any(sum(x)/2>6+x)

```

Try it online!

Alternate and equally-golfy solution porting this python answer -- the naive port would be something like `sum(x)-2*x>12` which is a byte longer.
> 2 votes

# Answer
# Julia 1.0, 23 bytes

```
x->sum(x/2)-min(x...)>6

```

Try it online!

Port of @Dominic van Essen's answers. Output is the answer to the question "Did the alien cheat?"

### Julia 1.2 or above, with `using LinearAlgebra`, 23 bytes

```
x->any((.5 .-I(3))x.>6)

```

(doesn't work on TIO since it only has Julia 1.0)

**18 bytes** without the `any` call, if output can be all 0s for no cheating, at least one 1 for cheating alien.

Find the dice values by solving the system of linear equations via matrices, and check if any are greater than 6. (More explanation in my MATL answer).
> 2 votes

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

## Code

```
lambda v:sum(v)/2-min(v)>6

```

Outputs `True` for cheated and `False` for valid.

Try it online!

## Explanation

Let \\$a\\$, \\$b\\$ and \\$c\\$ be the three dice rolls, where \\$a\\$ is the highest roll. Therefore, if \\$a \> 6\\$, the alien cheated, and otherwise they did not.

The sum of the numbers is \\$2a + 2b + 2c\\$. The minimum of the numbers is \\$b + c\\$. Therefore, `sum(v)/2-min(v)` is \\$(2a + 2b + 2c)/2 - (b + c)\\$ which is \\$a\\$. If this is greater than \\$6\\$, the alien cheated.
> 2 votes

# Answer
# Pyth, ~~22~~ ~~18~~ 11 bytes

```
L>-/sb2hSb6

```

Port of @Lecdi's Python 3 solution.

```
L>-/sb2hSb6
L             # lambda b:
    sb        # sum(b)
   /  2       # sum(b) / 2
       hSb    # min(b)
  -           # sum(b)/2 - min(b)
 >        6   # sum(b)/2 - min(b) > 6

```

Try it online!
> 2 votes

# Answer
# Charcoal, 8 bytes

```
›Σθ⊗⁺⁶⌊θ

```

Try it online! Link is to verbose version of code. Takes input as an array and outputs `-` if the alien cheated, nothing if it didn't. Explanation: Inspired by @DominicvanEssen's answers.

```
  θ         Input array
 Σ          Summed
›           Is greater than
       θ    Input array
      ⌊     Minimum
    ⁺       Plus
     ⁶      Literal integer `6`
   ⊗        Doubled
            Implicitly print

```
> 1 votes

# Answer
# Ruby, 21 bytes

```
->*s{s.sum/2-s.min<7}

```

Try it online!
> 1 votes

# Answer
# Etch, 47 bytes

`s=:get;:split" ";:intify;;:out:sum s;/2-:min s;>6;`

A straightforward point of this Husk answer.
> 1 votes

# Answer
# BQN, 9 bytes

```
¯12>-˜´∘∨

```

Try it at BQN online REPL

Outputs `0` if the dice are 6-sided, `1` if the alien is cheating.

We calculate the highest die roll using a single `fold` (or `reduce` in some languages) of a "minus" operation across the 3 sums-of-2-rolls in increasing order.
Consider initial die rolls of `s`, `m` and `l`, where `l` is the (possibly non-unique) largest, and `s` is the smallest. Then, the sums-of-2-rolls, in increasing order, are: `s+m`, `s+l`, `m+l`.
Folding "minus" across this yields `(s+m minus s+l) minus m+l` = `m-l - (m+l)` = `-2l`. So we just need to check whether the result is less than minus 12: if it is, then `l` was greater than 6 and the alien was cheating.

```
         ∨   # sort the input
        ∘    # and use that to
     -˜´     # fold 'subtracted from' from the right
¯12>         # and check whether it's less than minus 12

```

This comes out 1 byte shorter than the "subtract the lowest value from half the sum of the input" approach (`12<+´-2×⌊´` = 10 bytes in BQN: try it)
> 1 votes

# Answer
# Scala, 35 bytes

Try it online!

```
def f(x:Seq[Int])=x.sum/2.0-x.min>6

```
> 1 votes

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