# Question
Title: Find the rate of change at a point on a polynomial
Given the equation of a polynomial and an x-coordinate find the rate of change of the point at that x-coord on the curve.

A polynomial is in the form: axn \+ axn-1 \+ ... + ax1 \+ a, where a ϵ Q and n ϵ W. For this challenge, n can also be 0 if you don't want to have to deal with special cases (constants) where there is no x.

To find the rate of change at that x-coord, we can get the derivative of the polynomial and plug in the x-coord.

### Input

The polynomial can be taken in any reasonable form, but you must state what that format is explicitly. For example, an array of the form `[..[coefficient, exponent]..]` is acceptable.

### Output

The rate of change of the point at the x-coord given.

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

### Examples

```
[[4, 3], [-2, 4], [5, 10]]   19    ->   16134384838410
                  [[0, 4]]  400    ->   0
           [[4, 0], [5,1]]  -13    ->   5
      [[4.14, 4], [48, 2]]   -3    ->   -735.12
         [[1, 3], [-5, 0]]    5.4  ->   87.48

```

# Answer
> 23 votes
# Mathematica, 6 bytes

```
#'@#2&

```

(Beat **THAT**, ~~MATL~~ and 05AB1E)

The first argument must be a polynomial, with `#` as its variable and with `&` at the end (i.e. a pure function polynomial; e.g. `3 #^2 + # - 7 &`). The second argument is the x-coordinate of the point of interest.

**Explanation**

```
#'

```

Take the derivative of the first argument (`1` is implied).

```
... @#2&

```

Plug in the second argument.

**Usage**

```
#'@#2&[4 #^3 - 2 #^4 + 5 #^10 &, 19] (* The first test case *)

```

> `16134384838410`

# Answer
> 8 votes
# MATL, ~~8~~ 6 bytes

```
yq^**s

```

Input is: array of exponents, number, array of coefficients.

Try it online! Or verify all test cases: ,  , , .

### Explanation

Consider example inputs `[3 4 10]`, `19`, `[4 -2 5]`.

```
y    % Take first two inputs implicitly and duplicate the first
     %   STACK: [3 4 10], 19, [3 4 10]
q    % Subtract 1, element-wise
     %   STACK: [3 4 10], 19, [2 3 9]
^    % Power, element-wise
     %   STACK: [3 4 10], [361 6859 322687697779]
*    % Multiply, element-wise
     %   STACK: [1083 27436 3226876977790]
*    % Take third input implicitly and multiply element-wise
     %   STACK: [4332 -54872 16134384888950]
s    % Sum of array
     %   STACK: 16134384838410

```

# Answer
> 7 votes
# Julia, ~~45~~ ~~42~~ ~~40~~ 37 bytes

```
f(p,x)=sum(i->prod(i)x^abs(i[2]-1),p)

```

This is a function that acceps a vector of tuples and a number and returns a number. The absolute value is to ensure that the exponent isn't negative, which necessary because Julia annoying throws a `DomainError` when raising an integer to a negative exponent.

Try it online! (includes all test cases)

Thanks to Glen O for a couple of corrections and bytes.

# Answer
> 5 votes
# 05AB1E, ~~12~~ 11 bytes

Saved one byte thanks to Adnan.

```
vy¤<²smsP*O

v          For each [coefficient, power] in the input array
 y         Push [coefficient, power]
  ¤<       Compute (power-1)
   ²       Push x value (second input entry)
    sms    Push pow(x, power-1)
       P   Push coefficient * power ( = coefficient of derivative)
        *  Push coefficient * power * pow(x, power-1)
         O Sum everything and implicitly display the result

```

Try it online!

Floating point precision is Python's. I currently swap stack values twice, maybe there is a way to avoid it and save some bytes.

# Answer
> 4 votes
# Python 3, 41 bytes

*6 bytes removed thanks to @AndrasDeak! In fact, this answer is now more his than mine...*

*Thanks also to @1Darco1 for two corrections!*

```
lambda A,x:sum(a*b*x**(b-1) for a,b in A)

```

Anonymous function that accepts a list of lists with coefficients and exponents (same format as described in the challenge) and a number.

Try it here.

# Answer
> 3 votes
# R, 31 bytes

```
function(a,n,x)sum(a*n*x^(n-1))

```

Anonymous function that takes a vector of coefficients `a`, a vector of exponents `n`, and an `x` value.

# Answer
> 2 votes
# MATLAB with Symbolic Math Toolbox, 26 bytes

```
@(p,x)subs(diff(sym(p)),x)

```

This defines an anonymous function. Inputs are:

* a string `p` defining the polynomial, in the format `'4*x^3-2*x^4+5*x^10'`
* a number `x`

Example use:

```
>> f = @(p,x)subs(diff(sym(p)),x)
f =
    @(p,x)subs(diff(sym(p)),x)

>> f('4*x^3-2*x^4+5*x^10', 19)
ans =
16134384838410

```

# Answer
> 2 votes
# Matlab, 27 bytes

This is an anonymous function that accepts a value `x` and a polyonmial `p` in the form of a list of coefficients, e.g. `x^2 + 2` can be represented as `[1,0,2]`.

```
@(x,p)polyval(polyder(p),x)

```

# Answer
> 2 votes
## JavaScript (ES7), 40 bytes

```
(a,n)=>a.reduce((t,c,i)=>t+i*c*n**--i,0)

```

`a` is an array of the coefficients in ascending exponent order with zeros included e.g. *x*³-5 would be represented by `[-5, 0, 0, 1]`.

# Answer
> 2 votes
## R, 31 27 bytes

Unnamed function taking two inputs `p` and `x`. `p` is assumed to be an R-expression of the polynomial (see example below) and `x` is simply the point of evaluation.

```
function(p,x)eval(D(p,"x"))

```

It works by calling the `D` which computes the symbolic derivative w.r.t. `x` and the evaluates the expression at `x`.

**Example output**

Assuming that the function is now named `f` it can be called in the following way:

```
f(expression(4*x^3-2*x^4+5*x^10),19)
f(expression(0*x^4),400)
f(expression(4*x^0+5*x^1),-13)
f(expression(4.14*x^4+48*x^2),-3)
f(expression(1*x^3-5*x^0),5.4)

```

which respectively produces:

```
[1] 1.613438e+13
[1] 0
[1] 5
[1] -735.12
[1] 87.48

```

# Answer
> 2 votes
# C++14, ~~165~~ ~~138~~ ~~133~~ ~~112~~ 110 bytes

Generic Variadic Lambda saves a lot. -2 bytes for `#import` and deleting the space before `<`

```
#import<cmath>
#define A auto
A f(A x){return 0;}A f(A x,A a,A b,A...p){return a*b*std::pow(x,b-1)+f(x,p...);}

```

Ungolfed:

```
#include <cmath>

auto f(auto x){return 0;}

auto f(auto x,auto a,auto b,auto...p){
    return a*b*std::pow(x,b-1)+f(x,p...);
}

```

Usage:

```
int main() {
 std::cout << f(19,4,3,-2,4,5,10) << std::endl;
 std::cout << f(400,0,4) << std::endl;
 std::cout << f(-13,4,0,5,1) << std::endl;
 std::cout << f(-3,4.14,4,48,2) << std::endl;
 std::cout << f(5.4,1,3,-5,0) << std::endl;
}

```

# Answer
> 2 votes
# PARI/GP, 20 bytes

```
a(f,n)=subst(f',x,n)

```

For example, `a(4*x^3-2*x^4+5*x^10,19)` yields `16134384838410`.

# Answer
> 1 votes
# Haskell, 33 bytes

```
f x=sum.map(\[c,e]->c*e*x**(e-1))

```

Usage:

```
> f 5.4 [[1, 3], [-5, 0]]
87.48000000000002

```

# Answer
> 1 votes
## dc, 31 bytes

```
??sx0[snd1-lxr^**ln+z2<r]srlrxp

```

Usage:

```
$ dc -e "??sx0[snd1-lxr^**ln+z2<r]srlrxp"
4.14 4 48 2
_3
-735.12

```

# Answer
> 0 votes
# Dyalog APL, ~~26~~ ~~25~~ 23 bytes

```
{a←⍺⋄+/{×/⍵×a*2⌷⍵-1}¨⍵}

```

Takes polynomial as right argument and value as left argument.

# Answer
> 0 votes
# DASH, 33 bytes

```
@@sum(->@* ^#1- :1#0 1(sS *)#0)#1

```

Usage:

```
(
  (
    @@sum(->@* ^#1- :1#0 1(sS *)#0)#1
  ) [[4;3];[_2;4];[5;10]]
) 19

```

# Explanation

```
@@                             #. Curried 2-arg lambda
                               #. 1st arg -> X, 2nd arg -> Y
  sum                          #. Sum the following list:
    (map @                     #. Map over X
                               #. item list -> [A;B]
      * ^ #1 - :1#0 1(sS *)#0  #. This mess is just A*B*Y^(B-1)
    )#1                        #. X

```

# Answer
> 0 votes
# Scala, 46 bytes

```
s=>i=>s map{case(c,e)=>c*e*math.pow(i,e-1)}sum

```

Usage:

```
val f:(Seq[(Double,Double)]=>Double=>Double)=
  s=>i=>s map{case(c,e)=>c*e*math.pow(i,e-1)}sum
print(f(Seq(4.0 → 3, -2.0 → 4, 5.0 → 10))(19))

```

Explanation:

```
s=>                        //define an anonymous function with a parameter s returning
  i=>                        //an anonymous function taking a paramater i and returning
    s map{                   //map each element of s:
      case(c,e)=>              //unpack the tuple and call the values c and e
        c*e*math.pow(i,e-1)    //calculate the value of the first derivate
    }sum                      //take the sum

```

# Answer
> 0 votes
# Axiom 31 bytes

```
h(q,y)==eval(D(q,x),x,y)::Float

```

results

```
 -> h(4*x^3-2*x^4+5*x^10, 19)
     161343 84838410.0

 -> h(4.14*x^4+48*x^2, -3)
     - 735.12

```

# Answer
> 0 votes
# Casio Basic, 16 bytes

```
diff(a,x)|x=b

```

Input should be the polynomial in terms of `x`. 13 bytes for the code, +3 bytes to enter `a,b` as parameters.

Simply derives expression `a` in respect to `x`, then subs in `x=b`.

# Answer
> 0 votes
## Python 2, 39 bytes

```
lambda p,x:sum(c*e*x**~-e for c,e in p)

```

`lambda` function takes two inputs, `p` and `x`. `p` is the polynomial, given in the example format given in the question. `x` is the x-value at which to find the rate of change.

# Answer
> 0 votes
# Pari/GP, 14 bytes

```
p->x->eval(p')

```

### Usage:

```
? (p->x->eval(p'))(4*x^3 - 2*x^4 + 5*x^10)(19)
%1 = 16134384838410

```

Try it online!

# Answer
> 0 votes
# C, 78 bytes

```
f(int*Q,int*W,int S,int x){return Q[--S]*W[S]*pow(x,W[S]-1)+(S?f(Q,W,S,x):0);}

```

# Answer
> 0 votes
## Clojure, 53 bytes

```
#(apply +(for[[c e]%](apply * c e(repeat(dec e)%2))))

```

The polynomial is expressed as a hash-map, keys being coefficients and values are exponents.

# Answer
> 0 votes
# APL(NARS), 6 chars

```
{⍵⊥⍺}∂

```

For the input of polynom the list

$$ a\_n a\_{n-1} ... a\_1 a\_0 $$

means polynom

$$ a\_n X^n+a\_{n-1} X^{n-1} ... a\_1 X+a\_0 $$

```
      f←{⍵⊥⍺}∂
      5 4 f ¯13
5
      5 0 0 0 0 0 ¯2 4 0 0 0 f 19
1.613438484E13
      0 0 0 0 0 f 400
0
      0 f 400
0
      4.14 0 48 0 0 f ¯3
¯735.12
      1 0 0 ¯5 f 5.4
87.48

```

---
Tags: code-golf, math, calculus
---


title: Calculate 500 digits of e

text:
# Question
Title: Calculate 500 digits of e
Write a program to calculate the first 500 digits of the mathematical constant e, meeting the rules below:

* It cannot include "e", "math.e" or similar e constants, nor may it call a library function to calculate e.
* It must execute in a reasonable time (under 1 minute) on a modern computer.
* The digits are to include the 2 at the start. You do not need to output the `.` if you choose not to.

The shortest program wins.

# Answer
# Python 3.8, 58 bytes

```
x=10**499
print(x+sum((x:=x//i)for i in range(1,253))+128)

```

Try it online!

---

Original version, before it was clearly specified that the decimal point could be omitted:

# Python 3.8, 63 bytes

```
x=10**499
print(f'2.{sum((x:=x//i)for i in range(2,253))+128}')

```

Try it online!
> 15 votes

# Answer
# Vyxal, 11 bytes

```
1∆ȯ1∆ṡ+500Ḟ

```

Try it Online!

Calculates cosh(1)+sinh(1) to 500 decimal places.

```
1∆ȯ         # cosh(1)
      +     # +
   1∆ṡ      # sinh(1)
       500Ḟ # to 500 decimal places

```
> 14 votes

# Answer
# Python 3, 54 bytes

```
n=x=z=499
while~-n:x=(x+10**z)//n;n-=1
print(f'2.{x}')

```

Try it online!

# Python 3, 44 bytes

Outputs *e* without the `.`, courtesy of @xnor.

```
n=x=z=499
while n:x=x//n+10**z;n-=1
print(x)

```

Try it online!
> 10 votes

# Answer
# R, ~~104~~ 90 bytes

Since R doesn't have arbitrary precision arithmetic, and other answers already have used the limit definition and Taylor series of *e*, I use a decimal spigot algorithm to spice things up. I don't usually write loop-based code in R, so there is plenty of room for improvement. (`divmod` would be useful).

-7 bytes thanks to pajonk's better looping, and another -7 because I remembered R's colon operator can go backwards.

```
C=rep(1,254)
d=2
for(i in 1:500){cat(d)
d=0
for(j in 254:2)C[j]=(t=10*C[j]+d)-(d=t%/%j)*j}

```

Attempt This Online!

Based on *The Calculation of e to Many Significant Digits* by AHJ Sale (1968). The basic idea is to use an \\$m\\$th order Taylor polynomial, extract an integer part and fractional part, multiply the fractional part by 10, and repeat on the fractional part. Here's an example extracting the first decimal digit using 4 terms: (the 0 coefficients are coincidence)

\begin{alignat}{4} \newcommand\pp{\phantom{0}} e &\approx 2 + {} && \biggl\[ &\frac 1 2 \biggl(\pp1 + {} &&\frac 1 3 \biggl(\pp1 + {} &\frac 1 4 (\pp1) \biggr) \biggr) \biggr\]\\ &= 2 + \frac{1}{10} && \biggl\[ &\frac 1 2 \biggl( 10 + {} &&\frac 1 3 \biggl( 10 + {} &\frac 1 4 (10) \biggr) \biggr) \biggr\]\\ &= 2 + \frac{1}{10} && \biggl\[ &\frac 1 2 \biggl( 10 + {} &&\frac 1 3 \biggl( 12 + {} &\frac 1 4 (\pp2) \biggr) \biggr) \biggr\]\\ &= 2 + \frac{1}{10} && \biggl\[ &\frac 1 2 \biggl( 14 + {} &&\frac 1 3 \biggl(\pp0 + {} &\frac 1 4 (\pp2) \biggr) \biggr) \biggr\]\\ &= 2 + \frac{1}{10} && \biggl\[7 + {} &\frac 1 2 \biggl(\pp0 + {} &&\frac 1 3 \biggl(\pp0 + {} &\frac 1 4 (\pp2) \biggr) \biggr) \biggr\] \end{alignat}

Thanks to Steven B. Segletes for helping with MathJax formatting.

I believe the integers involved never exceed \\$10m\\$. The fractional part is always less than 1, so the computed digit can't affect the previous digit. \\$e\\$ is special because the coefficients of the Maclaurin series of \\$e^x\\$ are all 1. Trig functions for \\$\pi\\$ would have larger coefficients or produce negative digits, which would require amending previous digits. For example, here's Newton's arctan formula for \\$\pi\\$:

\begin{align} \frac \pi 2 &\approx 1 + \frac 1 3 \biggl( 1 + \frac 2 5 \biggl( 1 + \frac 3 7 (1) \biggr) \biggr) \\ &= 1 + \frac 1 3 \biggl( 1! + \frac 1 5 \biggl( 2! + \frac 1 7 (3!) \biggr) \biggr) \end{align}

There is no clean way to transform \\$\frac 3 7 (10)\\$ into an integer part while the fractional part is a multiple of \\$\frac 3 7\\$ and less than 1. The solution is modifying the spigot to maintain held *predigits* that are released once we are sure the digits are correct. See *A Spigot Algorithm for the Digits of π* by Rabinowitz and Wagon (1995).

\\$m\\$ can be calculated beforehand from the error of the finite sum using Stirling's approximation. For \\$n+1\\$ correct digits, find least \\$m\\$ satisfying \\$m! \> 10^{n+1}\\$, equivalently $$\frac 1 2 \ln(2\pi m) + m(\ln m - 1) \> (n+1) \ln 10$$

Ungolfed algorithm:

```
n = 500
m = 254
C = rep(1,m)
cat(2)
for(i in 2:n){
  d = 0
  for(j in m:2){
    t = 10*C[j] + d
    d = t %/% j
    C[j] = t - d*j
  }
  cat(d)
}

```
> 8 votes

# Answer
# Wolfram Language (Mathematica), 25 bytes

```
Sum[1/k!,{k,0,∞}]~N~500

```

Try it online!

# Wolfram Language (Mathematica), 29 bytes

```
Limit[(1+1/n)^n,n->∞]~N~500

```

Try it online!
> 7 votes

# Answer
# Python 2, 51 bytes (-2 thanks @xnor)

```
m=p=~2**3333
exec"m=m*m/~p;"*3333
print-m*10**499/p

```

Attempt This Online!

### former Python 2, 53 bytes

```
p=4000
m=2**p+1
exec"m=m*m>>p;"*p
print`m*5**p`[:500]

```

Attempt This Online!

Outputs the digits as a single string, no decimal point.

## How?

Approximately computes \\$(1+1/n)^n\\$ for \\$n=2^{4000}\\$ using repeated squaring.
> 7 votes

# Answer
# Python, 100 bytes

```
from decimal import*
getcontext().prec=500
e=d=Decimal(1)
for x in range(2,254):e+=1/d;d*=x
print(e)

```

Attempt This Online!

-2 bytes thanks to RubenVerg

254 is the lowest number which gives the correct result, but this doesn't get slow until you start looping for thousands of iterations.

This uses the definition:

\\$ \displaystyle e = \sum\_{n=1} ^{\infty} \frac{1}{n!} = \frac{1}{1} + \frac{1}{1 \cdot 2} + \frac{1}{1 \cdot 2 \cdot 3} + \cdots \\$

The only optimization used is to instead of calculating the factorial of each n from 1 to 254, we store the factorial of \\$ n-1 \\$ in the variable `d`, and each iteration multiply d by the loop number `x`.

This uses the Python's decimal library with `getcontext()` in order to calculate the number to 500 digits of precision.
> 5 votes

# Answer
# Charcoal, 23 bytes

```
≔⁰θＦ⊖φ≔÷⁺Ｘχ⁴⁹⁹θ⁻φιθ2.Ｉθ

```

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

```
≔⁰θ

```

Start with a running total of `0`.

```
Ｆ⊖φ≔÷⁺Ｘχ⁴⁹⁹θ⁻φιθ

```

For each integer from `1000` down to `2`, add `10**499` to the running total, then divide by that integer. This is equivalent to summing the reciprocals of the factorials from `2` to `1000` but without any loss of precision.

```
2.Ｉθ

```

Output `e` to `500` digits.

20 bytes to output without the decimal point:

```
≔⁰θＦφ≔⁺Ｘχ⁴⁹⁹÷θ⁻φιθＩθ

```

Try it online! Link is to verbose version of code. Explanation: As above but counts down to `1` and also adds the `10**499` after dividing so that the result includes the `0!` and `1!` terms.
> 5 votes

# Answer
# C, ~~126~~ ~~116~~ 109 bytes

Port of my R answer.

-10 bytes by rearranging loop logic printing leading 2, inspired by pajonk, and some small optimizations.

-7 bytes by using `C` with zeros instead of ones, credit chux - Reinstate Monica. Previously, the initialization of array `C` to 1s is a GNU extension.

```
i=500,d=2,j,t,C[255];main(){while(i--){putchar(d+48);d=0;j=254;while(j-->2)t=10*C[j]+d+10,d=t/j,C[j]=t%j-1;}}

```

Attempt This Online!
> 5 votes

# Answer
# JavaScript (ES11), 45 bytes

*-5 thanks to @l4m2*

A port of Neil's method, as suggested by Neil himself.

```
f=(q=i=999n)=>i?f((q+10n**499n)/-~i--):"2."+q

```

Try it online!
> 4 votes

# Answer
# APL (NARS2000), 20 chars = 40 bytes

```
499⍕+/5 6x○≢⎕FPC←1E4

```

`⎕FPC←1E4` set Floating Point Control to use ten thousand bit floats

count that (gives 1)

`5 6x○` compute sinh and cosh of that (while indicating with `x` that we want extended precision)

`+/` sum

`499⍕` output with 499 decimals, i.e. 500 digits in total
> 4 votes

# Answer
# GolfScript, 29 bytes

```
2 4000:a?:b){.*b/}a*5a?*+500<

```

Try it online!

Ports Albert.Lang's wonderful Python 2 solution to GolfScript. Check that answer for a better understanding of the math.

Code explanation:

```
2 4000:a?:b)
2 4000        # Push 2, 4000 to the stack.
      :a      # Store 4000 in variable a.
        ?     # Power; 2 ^ 4000
         :b   # Store 2 ^ 4000 in variable b.
           )  # Add one.

{.*b/}a*5a?*
{             # Open a block:
 .*           # * Duplicate and multiply (squaring
              #     the top of the stack.)
   b/         # * Integer divide by b.
     }a*      # Run this block a times.
        5a?   # Push 5 ^ a.
           *  # Multiply.

+500<
+      # Append this result to the implicit input,
       #   which is the empty string, therefore
       #   coercing the number to a string.
 500<  # Leave just the first 500 characters of
       #   this string.

```

## GolfScript, 30 bytes

```
"2."128 10 499?{2+/.@+\}251,/;

```

Try it online!

Based on m90's Python solution, since GolfScript has big integers but no floats.
> 4 votes

# Answer
# Jelly, 11 bytes

```
ȷ⁵*;R:\SDḣH

```

Try it online!

A Jelly version of m90’s Python answer. This is a niladic link which returns the first 500 digits of e as a list of decimal digits.

## Explanation

```
ȷ           | 1000
 ⁵*         | 10 ** this
   ;R       | Concatenate to 1..1000
     :\     | Reduce using integer division, collecting intermediate results
       S    | Sum
        D   | Decimal digits
         ḣH | First 500 (since half of 1000 is 500)

```
> 3 votes

# Answer
# Retina, 110 bytes

```

252*
L$`_
$>`,_
^
2.¶
749{`$
;
(_*);(_*)
10*$1$2;
¶(_+),(\1)*(_*);
;$#2*_¶$1,$3
)`^(.*)(¶.*);(_*)
$1$.3$2
1G`

```

Try it online! Too slow to produce 500 digits on TIO so link just produces 108. Explanation: Port of @qwr's R answer.

```

252*
L$`_
$>`,_

```

Generate the working array. (Note: This is an estimate of its size, but increasing it just requires additionally increasing the iteration count of the loop below to compensate.)

```
^
2.¶

```

Start with `2.`.

```
749{`
)`

```

Loop 749 times, which produces 499 digits for some reason.

```
$
;

```

Start another parallel iteration.

```
(_*);(_*)
10*$1$2;

```

Multiply each value by 10 and add the carry from the next element's previous iteration.

```
¶(_+),(\1)*(_*);
;$#2*_¶$1,$3

```

Divmod each value by its index and propagate the carry to the previous element for its next iteration.

```
^(.*)(¶.*);(_*)
$1$.3$2

```

Generate the next digit from the first element.

```
1G`

```

Remove all of the elements leaving just the final decimal expansion.
> 3 votes

# Answer
# APL(NARS), 76 chars

```
Q;r;d;k;v;⎕FPC
r←d←1⋄k←÷10x*501⋄v←0x
r+←d×←÷v+←1⋄→2×⍳k<∣d
⎕FPC←4×501⋄⎕←499⍕r

```

14+21+20+18+3=76

Calculus in rationals, and print with 499 digits after the point (499+1=500) the last digit rounded (but not changed because the 500th digit after the point should be 2\<6)

```
2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320
  0305992181741359662904357290033429526059563073813232862794349076323382988075319525101901157383418793070215408
  9149934884167509244761460668082264800168477411853742345442437107539077744992069551702761838606261331384583000
  7520449338265602976067371132007093287091274437470472306969772093101416928368190255151086574637721112523897844
  250569536967707854499699679468644549059879316368892300987931

```
> 2 votes

# Answer
# WolframAlpha, 26 bytes

```
N[Sum[1/k!,{k,0,∞}],500]

```

Try it on WolframAlpha
> 2 votes

# Answer
# Wolfram Language (Mathematica), 17 bytes

```
Cosh@1+Sinh@1`500

```

Try it online! A direct port of emanresu A's nice answer.
> 2 votes

# Answer
# 05AB1E, 13 bytes

```
₅L₄°šÅ»÷}O₄;£

```

Port of *@NickKennedy*'s Jelly answer, which in turn is based on *@m90*'s Python answer, so make sure to upvote those answers as well.

Outputs the first 500 digits as a single concatted integer.

Try it online.

**Explanation:**"

```
₅L             # Push a list in the range [1,255]
  ₄°š          # Prepend 10**1000
     Å» }      # Cumulative left-reduce, keeping intermediate results
       ÷       #  by doing integer-division
         O     # Sum all those results together
          ₄;   # Push 500 (1000 halved)
            £  # Keep only the first 500 digits
               # (after which this integer is output implicitly as result)

```
> 1 votes

# Answer
# Scala 3, 89 bytes

A port of @m90's Python answer in Scala.

---

Golfed version. Attempt This Online!

```
var x=BigInt(10) pow 499
println(s"2.${(BigInt(0)/:(2 to 252))((s,i) =>s+{x/=i;x})+128}")

```

Ungolfed version. Attempt This Online!

```
object Main {
  def main(args: Array[String]): Unit = {
    var x = BigInt(10).pow(499)
    val result = (for (i <- 2 to 252) yield {
      val div = x / i
      x = div
      div
    }).sum + 128
    println(s"2.$result")
  }
}

```
> 0 votes

# Answer
# SageMath, ~~20~~ 18 Byte

Sehr unkreativ:

```
n(i^(2/i/pi),1664)

```

Alte Antwort:

```
n((-1)^(-i/pi),1664)

```

Onlinetest

`i^(2/i/pi)` =e : `e^(πi) = -1` =\> `e^(πi/2) = i` =\> `e = i^(2/πi)`

`n(....)` : Kontentiere zu Dezimal

`1664` : Mit einer Genauigkeit von 1664 bit
> -1 votes

---
Tags: code-golf, math, kolmogorov-complexity, restricted-time
---


# Question
Title: Definite integral of polynomial functions
You will need to evaluate the definite integral (bounded by \\$a\\$ and \\$b\\$) of a certain polynomial function that takes the form of:

$$\int\_a^b \left( k\_n x^n + k\_{n-1} x^{n-1} + \cdots + k\_2x^2 + k\_1x + k\_0 \\: \right) dx$$

Normally, this can be done using the fundamental theorem of calculus and power rules. For example:

$$\int\_b^c ax^n dx = a \frac{x^{n+1}} {n+1} \Big|^c\_b = a\left\[ \frac{c^{n+1}} {n+1} - \frac{b^{n+1}} {n+1} \right\]$$

The challenge here is to replicate that process using the shortest amount of code as possible. You will decide the degree your program can solve. Somewhere in your answer, specify how many degrees your program can solve up to. For example:

> My program can solve all polynomials up to the 5th degree. (quintic polynomial)

## Input

Input will be two arrays consisting of bounds and coefficients. For example:

```
bounds = [2, 3]
coefficients = [4, 5, 2, 7]

```

The above input will yield this expression:

$$ \int\_2^3 (4x^3 + 5x^2 + 2x + 7) \mathop{dx} $$

## Output

The output will be a single decimal number rounded to at least 3 decimal places. So the above expression will yield:
```
108.666666666667 // correct
108.6667 // correct
109 // wrong

```

## Constraints

$$ -10^9 \< k\_n, ..., k\_1, k\_0 \< 10^9 $$ $$ 0 \< N \< 30 $$ Integral bounds \\$a, b\\$ satisfy no additional constraints.

## Rules & Scoring

* Standard loopholes apply here as it does anywhere else.
* You may not write a program that only solves a specific integral. Once you pick your degree, that program must work under all constraints up to that degree.
* Your score will be calculated by this equation: `degree of polynomial / num of bytes`, and the highest score wins.
* If your program works for all degrees above 30, set your numerator to be 30, otherwise 29 is the maximum possible numerator.
* Please post a working version of your code on any website so that it can be tested.

# Answer
# Jelly, \\$\frac {30} 7 = 4.29\\$

```
÷J$ŻUḅI

```

Try it online!

Takes the polynomial as a list of coefficients in little-endian format (i.e. the example is `7,2,5,4`). This can handle any (positive) degree you want, but I've limited it at 30 as the question states \\$0 \< N \< 30\\$

+2 bytes and a score of \\$3.33\\$ if the polynomial must be taken in big-endian format

## How it works

```
÷J$ŻUḅI - Main link. Takes coeffs on the left and [a, b] on the right
  $     - To the coeffs:
 J      -   Yield [1, 2, 3, ..., N]
÷       -   Divide each coeff by the orders
   Ż    - Prepend 0
    U   - Reverse
     ḅ  - Calculate as polynomials, with x = a and x = b
      I - Reduce by subtraction

```
> 9 votes

# Answer
# , \\$\frac{30}{12}\approx2.5\\$

```
[:-/[-p..p.[

```

Try it online!

*-1 thanks to Bubbler*

* `p..` Integral of a polynomial. Returns a list representing the solution polynomial.
* `p.` Evaluate polynomial at given bounds.
* `[-` Subtract from constant terms (makes both values negative).
* `-/` And subtract negative ending bound answer from negative starting bound answer.
> 5 votes

# Answer
# Factor, \\$\frac{30}{56}\approx0.5357\\$

```
[ [ 1 + 3dup nip v^n first2 - swap / * ] map-index sum ]

```

Try it online!

Takes the bounds and coefficients in reverse, e.g. `{ 3 2 } { 7 2 5 4 }`, and returns a rational number, e.g. `108+2/3`.

To take the inputs as given and return a float, add a `reverse`, a `neg`, and a `>float` to get 75 bytes:

# Factor, \\$\frac{30}{75}=0.4\\$

```
[ reverse [ 1 + 3dup nip v^n first2 - swap / * ] map-index sum neg >float ]

```

Try it online!
> 3 votes

# Answer
# Charcoal, \\$ \frac {30} {20} = 1.5 \\$

```
ＵＭθ∕ι⁻Ｌθκ⊞θ⁰Ｉ⁻↨θζ↨θη

```

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

```
ＵＭθ∕ι⁻Ｌθκ

```

Divide each element of the polynomial by the 1-indexed reverse index.

```
⊞θ⁰

```

Append a zero.

```
Ｉ⁻↨θζ↨θη

```

Calculate the value at each bound and take the difference.
> 3 votes

# Answer
# Wolfram Language (Mathematica), ~~30/32=0.9375~~ \\$\frac{30}{31}\approx0.9677\\$

```
c(a=0;c^++a.{-1,1}/a&/@#).#&

```

Try it online!

Accepts coefficients in ascending (lower to higher exponent) order. Input `[{a, b}][coeff]`.

---

some 32-byters:

```
FromDigits[#,]~Integrate~{,##2}&

```

Try it online! Integrates using `Null` as the variable.

```
#2-#&@@Sum[i/++a#2^a,{i,a=0;#}]&

```

Try it online!
> 3 votes

# Answer
# APL (Dyalog Unicode), \\$\frac{30}{20}=1.5\\$

```
{-/⌽⊥∘(0,⍨⍵÷⌽⍳≢⍵)¨⍺}

```

Try it online!

Takes the bounds on the left and the coefficients on the right. This is a great place to use APL's ⊥, which can evaluate polynomials (although appending a zero is necessary because we want to use n+1 and not n).
> 2 votes

# Answer
# 05AB1E, \\$\frac{30}{8} = 3.75\\$

```
āR/0ªIβÆ

```

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

First input is the list of coefficients; second is a pair of \\$\[b,a\]\\$ bounds.

Try it online.

**Explanation:**

```
ā         # Push a list in the range [1, (implicit) coefficients-length]
 R        # Reverse this range to [length,1]
  /       # Divide the coefficients by the ranged list (at the same postitions)
   0ª     # Append a 0 at the end of this list
     Iβ   # Convert this list to base-b and base-a using the second input-pair
       Æ  # And reduce that pair by subtracting
          # (after which the result is output implicitly)

```
> 2 votes

# Answer
# SageMath, \\$\frac{30}{67}\approx 0.44776\\$

```
lambda c,b:RR(integrate(sum(a*x**e for e,a in enumerate(c)),[x]+b))

```

Try it online!

Inputs the coefficients (from the constant to the highest degree) and bounds as lists.

Can surely work for much higher degrees of a polynomial but got tired waiting for it to finish \\$10000\\$.
Works quite quickly for degree of \\$3000\\$.
> 1 votes

# Answer
# JavaScript, score: \\$\frac{30}{71}\approx 0.42\\$

```
n=>k=>(x=y=>k.reduce((a,b,c)=>a+b*y**(z=k.length-c)/z,0))(n[1])-x(n[0])

```

Demonstration:

```
f=n=>k=>(x=y=>k.reduce((a,b,c)=>a+b*y**(z=k.length-c)/z,0))(n[1])-x(n[0]);
// test case
console.log(f([2,3])([4,5,2,7]));
// large polynomial of degree 30
console.log(f([3,5])(new Array(31).fill(1) /*shortcut*/));
```

## How it works

Constructs a function dynamically which calls reduce on the coefficients array. Then invokes it on both bounds and takes the difference.
> 1 votes

# Answer
# C (gcc) (`-lm`), score: \\$\frac{30}{90}= 0.\bar3\\$

Sums the bounds for each term in descending order. Due to quirks with `-O0`, I was able to write this function without the usual return or explicit value assignment at the end of the function.

```
double f(b,t,n,i,j)int*b,*t;{for(double s=i=0;j=n-i;)s+=t[i++]*(pow(b[1],j)-pow(*b,j))/j;}

```

Try it online!
> 1 votes

# Answer
# , 55 bytes, score: \\$\frac{30}{55}=0.\overline{54}\\$

```
function(b,k)diff(outer(b,a<-rev(seq(!k)),"^")%*%(k/a))

```

Try it online!

If we could take the coefficients in ascending order of degree, this would be 5 bytes shorter and get a score of \\$0.6\\$ instead, by removing the `rev()`.
> 1 votes

# Answer
# Scala, \\$\frac{30}{88}\approx0.3409\\$

```
p=>_.:\(.0)((x,r)=>p.reverse.zipWithIndex.map{case(k,n)=>k*math.pow(x,n+1)/(n+1)}.sum-r)

```

Try it in Scastie

The question's IO format actually works out quiet well here (although I could save 8 bytes by taking the coefficients in reverse to avoid `.reverse`).
> 0 votes

# Answer
# APL(NARS), 14 chars

```
a←⎕⋄-/{⍵⊥a}∫¨⎕

```

For the input of polynom the list

$$ a\_n a\_{n-1} ... a\_1 a\_0 $$

means polynom

$$ a\_n X^n+a\_{n-1} X^{n-1} ... a\_1 X+a\_0 $$

test:

```
    a←⎕⋄-/{⍵⊥a}∫¨⎕
⎕:
      4 5 2 7
⎕:
      3 2
108.6666667

```
> 0 votes

---
Tags: math, code-challenge, polynomials, calculus
---


title: Counting Collinear Points

text:
# Question
Title: Counting Collinear Points
Given two points \\$(x\_1, y\_1)\\$ and \\$(x\_2, y\_2)\\$ with integer coordinates, calculate the number of integer points (excluding the given points) that lie on the straight line segment joining these two points. Use any maths formula you like, such as

$$gcd(|x\_2 - x\_1|, |y\_2 - y\_1|) - 1$$

**Input**

Four integer coordinates of the two points: \\$x\_1, y\_1, x\_2, y\_2\\$.

**Output**

Number of integer points between the two given points.

# Test Cases

| Integer Coordinates | In-between Points |
| --- | --- |
| (5,10),(10,5) | 4 |
| (-8,5),(0,5) | 7 |
| (-3,-3),(2,2) | 4 |

# Answer
> 4 votes
# Desmos, 17 bytes

```
f(A,B)=gcd(A-B)-1

```

Takes input as two two-element lists.

This uses the formula as stated in the question, but it seems like `gcd` is always positive even with negative numbers, so I don't need to take the absolute difference, but rather just regular difference.

Try It On Desmos!

# Answer
> 7 votes
# Vyxal, 3 bytes

```
εġ‹

```

Try it Online!

Port of Jonathan Allan's Jelly answer.

```
ε   # Absolute difference - [|x1-x2|,|y1-y2|]
 ġ  # gcd of that list
  ‹ # decrement

```

# Answer
> 5 votes
# Jelly, 4 bytes

```
ạg/’

```

A dyadic Link that accepts a point as a pair on each side and yields the count.

**Try it online!**

### How?

Implements the provided greatest common divisor formula.

```
ạg/’ - Link: pair of integers [x1, x2]; pair of integers [y1, y2]
ạ    - absolute difference (vectorises) -> [|x1-y1|, |x2-y2|]
  /  - reduce by:
 g   -   greatest common divisor -> GCD(|x1-y1|, |x2-y2|)
   ’ - decrement -> GCD(|x1-y1|, |x2-y2|) - 1

```

# Answer
> 4 votes
# Nekomata, 4 bytes

```
≈đG←

```

Attempt This Online!

Takes input as two pairs of numbers, e.g. `[-8,5] [0,5]`.

```
≈đG←
≈       Absolute difference (vectorized)
 đ      Unpair; get the two elements of a pair
  G     GCD
   ←    Decrement

```

---

> I wonder how an approach that defines the solution to be an integer point on the line, and using `-n` for the final result. (I haven't really tried to learn Nekomata yet and somehow doubt it would be shorter for this problem, but seems interesting) – noodle man

The shortest I can get using this approach is 10 bytes:

# Nekomata \+ `-n`, 10 bytes

```
≈:Ṁᵉ{~Z*}¦

```

Attempt This Online!

```
≈:Ṁᵉ{~Z*}¦      Take [-8,5] [0,5] as an example
≈           Absolute difference (vectorized)
                [-8,5] [0,5] -> [8,0]
 :          Duplicate
                [8,0] -> [8,0] [8,0]
  Ṁ         Maximum
                [8,0] [8,0] -> [8,0] 8
   ᵉ{       Apply the following block and then push the original top of stack
     ~Z       Choose any integer in [1,n)
                [8,0] 8 -> [8,0] 1 or [8,0] 2 or ... or [8,0] 7
       *      Multiply
                [8,0] 1 -> [8,0]
                [8,0] 2 -> [16,0]
                ...
                [8,0] 7 -> [56,0]
        }   End the block (ᵉ pushes the original top of stack)
                [8,0] -> [8,0] 8
                [16,0] -> [16,0] 8
                ...
                [56,0] -> [56,0] 8
         ¦  Divide and check if the result is an integer
                [8,0] 8 -> [1,0]
                [16,0] 8 -> [2,0]
                ...
                [56,0] 8 -> [7,0]

```

`-n` counts the number of solutions, so the output is `7`.

# Answer
> 3 votes
# Charcoal, 28 bytes

```
ＮθＮη≧⁻Ｎθ≔∨⁻ηＮθηＩＬΦ↔η∧ι¬﹪×ιθη

```

Try it online! Link is to verbose version of code. Explanation: No vectorised difference or gcd, so I have to do things the hard way.

```
ＮθＮη

```

Input the first co-ordinate.

```
≧⁻Ｎθ≔∨⁻ηＮθη

```

Subtract the second co-ordinate, but if it is horizontal then make it diagonal, which has the same number of intermediate points.

```
ＩＬΦ↔θ∧ι¬﹪×ιηθ

```

Generate a list of intermediate y-coordinates and see how many x-coordinates are integers.

# Answer
> 3 votes
# APL(Dyalog Unicode), 7 bytes SBCS

```
¯1+∨/⍤-

```

Try it on APLgolf!

A tacit function which takes vectors on the left and right and returns an integer. I believe this solution also works in any dimension, not just 2D. It takes the difference of the points, GCD all of the differences, and adds -1.

# Answer
> 2 votes
# Uiua, 12 bytes SBCS

```
-1;⍢⊃◿∘±°⊟⌵-

```

Try it!

```
-1;⍢⊃◿∘±°⊟⌵-
           -  # difference
          ⌵   # absolute value
        °⊟    # uncouple pair to stack
  ;⍢⊃◿∘±      # GCD
-1            # decrement

```

# Answer
> 2 votes
# Retina 0.8.2, 97 bytes

```
,(.+),(.+),
,$2¶$1,
%O`[^,]+
\d+
$*
-(1+),(1+)
$1$2
(1+),-?\1|[^1¶]

mO^`^.*
^(1(1*))\1*¶\1*$
$.2

```

Try it online! Link includes test cases. Explanation:

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

```

Exchange the first y-coordinate with the second x-coordinate and split the coordinates onto separate lines.

```
%O`[^,]+

```

Ensure that if either coordinate is negative then the first one is.

```
\d+
$*

```

Convert to unary.

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

```

If the co-ordinates have different signs then add their absolute values together.

```
(1+),-?\1|[^1¶]

```

Otherwise take the absolute difference.

```
mO^`^.*

```

Sort them descending in case the first difference is zero.

```
^(1(1*))\1*¶\1*$
$.2

```

Calculate the decremented GCD.

# Answer
> 2 votes
# , 62 bytes

```
\(x,y)max((y=1:max(z<-abs(x-y)))[!z[1]%%y&!z[2]%%y|!all(z)])-1

```

Attempt This Online!

Base R has no built in for GCD.

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

```
(p,q,r,s)=>(g=r=>s?g(s,s=r%s):r*r)(r-p,s-=q)**.5-1

```

Try it online!

Basically based on the formula in the question. Calculate

$$ \sqrt{\left(\text{gcd}(x\_2-x\_1,y\_2-y\_1)\right)^2}-1 $$

where \\$\text{gcd}\\$ is defined as

$$ \text{gcd}(x,y)=\begin{cases} x & y=0 \\ \text{gcd}(y,x \bmod y) & \text{otherwise} \end{cases} $$

# Answer
> 1 votes
# APL(NARS), 9 chars

```
¯1+∨/∣⎕-⎕

```

test&how use:

```
      ¯1+∨/∣⎕-⎕
⎕:
      ¯8 5
⎕:
      0 5
7
~

      ¯1+∨/∣⎕-⎕
⎕:
      5 10
⎕:
      10 5
4
~

```

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

*-5 bytes, thanks to @ceilingcat*

```
g(a,b){return b?g(b,a%b):abs(a);}main(x,y,a,b){scanf("%d%d%d%d",&x,&y,&a,&b);printf("%u",g(x-a,y-b)-1);}

```

Try it online!

---
Tags: code-golf, math, integer, geometry
---


# Question
Title: Print "abracadabra" with 7 different alterations
*Abracadabra* is a magic word. To make it even more magical, let's make several *alterations* to how it may be written:

1. Change the casing for any subset of characters; for example: `aBrAcAdAbRa`
2. Append an exclamation mark to it: `abracadabra!`
3. Change each occurrence of `a` into a different vowel: `ybrycydybry`
4. Change any single consonant letter into a different consonant which doesn't appear in the original word: `abracadakra` (don't change all occurrences of `b` into `k`, only one!)
5. Change the foreground colour, but not background colour
6. Change the background colour, but not foreground colour
7. Use fullwidth characters: `ａｂｒａｃａｄａｂｒａ` (don't cheat by inserting spaces!)

Output the variants to the screen (or printer) in 8 different lines of text. One variant (not necessarily the first one) should be "base", while all others should differ from it in a single aspect, as described above.

The output may be the same each time your code is run; alternatively, it may be different each time (depending on random numbers or unpredictable values in memory).

If your system can't support some of these alterations (for example, no support for colours on a black-and-white screen; no full-width characters on ASCII-only terminals), use the following replacement alterations:

* Text in inverted colours
* Blinking text
* Different font
* Different font size

But please use these only if your system really doesn't support the original alterations!

# Answer
> 1 votes
# Retina 0.8.2, 98 bytes

```

M¶M¶M!¶M¶M¶␛[5mM␛[25m¶␛[7mM␛[27m¶M
M
abracadabra
2=`c
C
T`a`y`!¶.+
4=`c
k
T`l`ａ-ｒ`.+$

```

Try it online!  characters above are actual ESC characters in the link, but they don't work in a post. Byte count shows as 86 bytes because link assumes SBCS but this is actually UTF-8. Fifth and sixth lines of output are blinking and inverse video. Explanation:

```

M¶M¶M!¶M¶M¶␛[5mM␛[25m¶␛[7mM␛[27m¶M
M
abracadabra

```

Insert the basic text, but with lines 3, 6 and 7 already altered.

```
2=`c
C

```

Uppercase a letter in line 2.

```
T`a`y`!¶.+

```

Change the vowels in line 4.

```
3=`c
k

```

Change a consonant in line 5.

```
T`l`ａ-ｒ`.+$

```

Use full width characters in line 8.

# Answer
> 1 votes
# Python 3.8 (pre-release), ~~263~~ ~~247~~ ~~205~~ ~~202~~ ~~186~~ 165 bytes

```
p=print;p(s:='abracadabra');p(s+'!')
for j in 0,1,2,3:p(''.join((chr(ord(c)+(j>2)*65248),'Dyk '[j])[c=='dac '[j]]for c in s))
for j in 3,4:p(f'\033[{j}4m{s}\033[0m')

```

Try it online!

Not a very good Python solution, but worth the try. Outputs

1. base case: `abracadabra`
2. exclamation mark appended: `abracadabra!`
3. case swapped: `abracaDabra` (`d` replaced with `D`)
4. vowels replaced: `ybrycydybry` (`a` replaced with `y`)
5. single consonant replaced: `abrakadabra` (`c` replaced with `k`)
6. width filled: `ａｂｒａｃａｄａｂｒａ`
7. with blue foreground: `abracadabra`
8. with blue blackground: `abracadabra`

**How it works?**

The first line sets an alias for `print` and executes steps 1 and 2.

The second line groups \\$4\\$ steps: 3, 4, 5 and 6.

Therefore, \\$0 \leq j \lt 4\\$: for step 3, \\$j=0\\$; for step 4, \\$j=1\\$; and so on.

Note that for steps 3, 4 and 5, a single letter is replaced by another single letter. This allows us to do

```
[c,'Dyk '[j]][c=='dac '[j]]

```

Also note that for step 6, ASCII character `a` is 65248 characters apart from :

```
chr(ord(c)+65248)

```

Since they're different types of replacement, we can filter it using

```
(j>2)*65248

```

where it'll be evaluated to 65248 only for \\$j=3\\$ (step 6).

Since this conditional is not lazy-evaluated, we must add a space after `Dyk` and `dac` for considering the case where \\$j=3\\$.

The third line handles the colors.

**Changes**

*-16 bytes* by reducing the lambdas to a curry.

*-42 bytes* by assuming that "change the casing" means "change the case of any letter" as other answers did.

*-3 bytes* by inlining the `j > 2` condition

*-16 bytes* by using f-strings instead of `print(..., sep='')`

*-21 bytes* by inlining the lambdas and using a generator comprehension

# Answer
> 1 votes
# JavaScript (ES6), 114 bytes

*-2 thanks to Kevin Cruijssen (and another -4 from there)*

Includes the unprintable character `\x1b`.

```
_=>`ab*
Ab*
ab*!
obrocodobro
ak*
ab*
ab*
ａｂｒａｃａｄａｂｒａ`.split`*`.join`racadabra`

```

Try it online!

### Output

# Answer
> 1 votes
# 05AB1E, 61 bytes

```
.•ÒÔt_º°•D©™®'!«®žOÂ‡®'f1ǝ₆41‚ε®27çDr"[ÿmÿÿ[0m"«}`®Ç65248+çJ»

```

Alteration options in the same order as the challenge description.

Try it online.

I misunderstood the challenge at first and thought the alternations were cumulative, which is actually shorter in 05AB1E (**52 bytes \- non-competing**):

```
.•ÒÔt_º°•='!«=žOÂ‡=™='f1ǝ=Ç65248+çJ=₆41‚vy…[ÿm27çìì=

```

(Cumulative) alteration options in the order 2,3,1,4,7,5,6.

Try it online.

**Explanation:**

```
.•ÒÔt_º°•       # Push compressed string "abracadabra"
         ©      # Store it in variable `®` (without popping)
D               # Duplicate it
 ™              # Titlecase the copy
®               # Push base-string `®` again
 '!«           '# Append "!"
®               # Push base-string `®` again
 žO             # Push vowels builtin "aeiouy"
   Â            # Bifurcate it (short for Duplicate & Reverse copy): "yuoiea"
    ‡           # Transliterate all characters (so "a"s become "y"s)
®               # Push base-string `®` again
    ǝ           # Insert
 'f            '# an "f"
   1            # at 0-based index 1
®               # Push base-string `®` again
 Ç              # Convert it to a list of codepoint integers
  65248+        # Add 65248 to each
        ç       # Convert each integer back to a character
         J      # Join it back together to a string
₆41‚            # Push pair [36,41]
    ε           # Map over them:
                #  (implicitly push the current integer)
     ®          #  Push base-string `®` again
      27ç       #  Push 27, and convert it to a character with this codepoint (␛)
         Dr     #  Duplicate, then reverse the four items on the stack
     "[ÿmÿÿ[0m" #  Push this string, replacing the `ÿ` one by one with the values
     «          #  Append it to the remaining ␛
    }`          # After the map: pop and push both strings to the stack
      »         # Join all strings on the stack by newlines
                # (after which the result is output implicitly)

```

The cumulative program is pretty similar, except uses `=` (print with trailing newline without popping the string). And the `␛[0m` to reset the colors aren't necessary.

See this 05AB1E tip of mine (section *How to compress strings not part of the dictionary?*) to understand why `.•ÒÔt_º°•` is `"abracadabra"`.

---
Tags: code-golf
---


# Question
Title: Heart plus diamond is spade-and-club: table puzzle
I found this YouTube video with a table on it showing some card suits with ampersands. You might not understand what it is about, but I still want to make a challenge about it.

The input is two suits, being one of the following:

```
heart
diamond
spade
club

```

You can do anything for any other input.

Then the output is their 'game sum':

1. If both suits are red (heart/diamond), then:
    * Up to one heart promotes to a spade
    * Up to one diamond demotes to a club
2. Output in order of priority (spade \> heart \> diamond \> club).

Leading and trailing whitespace is allowed.

Example input:

```
spade
heart

```

Example output:

```
spade and heart

```

Use any language. This is code-golf, so shortest code in bytes wins.

# Answer
> 3 votes
# Retina 0.8.2, 58 bytes

```
O^`
h.+¶[hd]
spade $&
[td]¶d.+
$& club
( .+)?¶(.+ )?
 and

```

Try it online! Takes input on separate lines but link is to test suite that splits on  `+`  for convenience. Explanation:

```
O^`

```

Sort in reverse order.

```
h.+¶[hd]
spade $&

```

Prefix `spade` if `heart` is followed by either `heart` or `diamond`.

```
[td]¶d.+
$& club

```

Suffix `club` if either `heart` or `diamond` are followed by `diamond`.

```
( .+)?¶(.+ )?
 and

```

Keep only the first and last words and join them with `and`.

# Answer
> 3 votes
# 05AB1E, 33 bytes

```
„‰áš¸#©¢O<i®“spade†Ú“#.;}{R„ €ƒÀý

```

Input as a pair of strings.

Try it online or verify all test cases.

**Explanation:**

```
„‰áš¸                 # Push dictionary string "heart diamond"
     #                # Split it on spaces: ["heart","diamond"]
      ©               # Store this pair in variable `®` (without popping)
       ¢              # Count how many times each occurs in the (implicit) input-pair
        O             # Sum those counts together
         <i           # If it's 2:
                      # (this is only truthy for the following four pairs: dd,dh,hd,hh)
           ®          #  Push ["heart","diamond"] again from variable `®`
           “spade†Ú“  #  Push dictionary string "spade club"
                    # #  Split it on spaces as well: ["spade","club"]
           .;         #  Replace the first "heart" with "spade" and first "diamond"
                      #  with "club" in the (implicit) input-pair
          }           # Close the if-statement
                      # (the implicit else uses the implicit input-pair)
           {R         # Sort the pair in descending order (sort + reverse)
             „ €ƒ     # Push dictionary string "  and"
                 À    # Rotate it once to the left to " and "
                  ý   # Join the pair with " and " as delimiter
                      # (after which the result is output implicitly)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `„‰áš¸` is `"heart diamond"`; `“spade†Ú“` is `"spade club"`; and `„ €ƒ` is `" and"`.

# Answer
> 2 votes
# JavaScript (ES6), 80 bytes

*-6 thanks to @tsh*

Inspired by Neil's method.

Expects `([a, b])`.

```
c=>(/[dt],h/.test([b,a]=c.sort())?"spade":a)+" and "+(/d,[dh]/.test(c)?"club":b)

```

Try it online!

### Commented

```
c =>           // c[] = input array
(              //
  /[dt],h/     // if a is "heart" and b is
  .test(       // either "heart" or "diamond",
    [b, a] =   // where a and b are sorted such
      c.sort() // that a > b:
  ) ?          //
    "spade"    //   use "spade" as the left output
  :            // else:
    a          //   use a
) +            //
" and " +      // append " and "
(              //
  /d,[dh]/     // if b is "diamond" and a is
  .test(c) ?   // either "diamond" or "heart":
    "club"     //   use "club" as the right output
  :            // else:
    b          //   use b
)              //

```

# Answer
> 2 votes
# Jelly, 34 bytes

```
ṢṚµĖ41,3ḥⱮỊẸoḂƲȧ"ȯ"“ɓ¤PⱮ»Ḳ¤j“ and

```

A full program that takes a single list of two strings and prints the result to STDOUT.

*Thanks to @JonathanAllan for suggesting a technique that ultimately saved a byte!*

## Alternative Jelly, 35 bytes

```
ṢṚµOḢ€ọ2¬Ẹo_J$ƲḂȧ"ȯ"“ɓ¤PⱮ»Ḳ¤j“ and

```

A full program that takes a single list of two strings and prints the result to STDOUT.

*Thanks to @JonathanAllan for pointing out a bug!*

This works because of the following pattern:

```
╔═══════════════════════════╦════╦═════╦═════╦═════╗
║ First character           ║ c  ║ d   ║ h   ║ s   ║
╠═══════════════════════════╬════╬═════╬═════╬═════╣
║ Codepoint                 ║ 99 ║ 100 ║ 104 ║ 115 ║
╠═══════════════════════════╬════╬═════╬═════╬═════╣
║ ọ2                        ║ 0  ║ 2   ║ 3   ║ 0   ║
╠═══════════════════════════╬════╬═════╬═════╬═════╣
║ Subtract 1, or not, mod 2 ║ 1  ║ 1   ║ 0   ║ 1   ║
╠═══════════════════════════╬════╬═════╬═════╬═════╣
║ Subtract 2, or not, mod 2 ║ 1  ║ 0   ║ 1   ║ 1   ║
╚═══════════════════════════╩════╩═════╩═════╩═════╝

```

## Explanation

```
Ṣ                                    | Sort
 Ṛ                                   | Reverse
  µ                                  | Start a new monadic chain
   O                                 | Convert to codepoints
    Ḣ€                               | Head of each
      ọ2                             | Number of times divisible by 2
              Ʋ                      | Following as a monad:
        ¬Ẹ                           | - Any non-zero
          o_J$                       | - Or (the result of ọ2 from before minus the indices)
               Ḃ                     | Mod 2
                ȧ"                   | And zipped (with the reverse sorted input)
                  ȯ"“ɓ¤PⱮ»Ḳ¤         | Or zipped with "spade club" split at spaces
                            j“ and   | Join with " and " (the last ” is implicit)

```

# Answer
> 1 votes
# Charcoal, ~~52~~ 49 bytes

```
Ｆ²⊞υＳ⪫Ｅ⌈⟦υ⮌υ⟧⎇›⁼§hdκ§ι⁰⊙sc№Συλ§⪪spadeclub⁵κι and

```

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

```
Ｆ²⊞υＳ

```

Input the two strings.

```
Ｅ⌈⟦υ⮌υ⟧⎇›⁼§hdκ§ι⁰⊙sc№Συλ§⪪spadeclub⁵κι and

```

Sort them in descending order, then unless one the two strings contains `s` or `c`, change the first string from `heart` to `spade` and the second from `diamond` to `club`, then join the results with `and`.

# Answer
> 1 votes
# Perl 5 `-n`, 77 bytes

```
$,=" and ";/[dt] [dh]/&&s/heart/spade/+s/diamond/club/;say reverse sort/\S+/g

```

Try it online!

# Answer
> 0 votes
# Uiua, ~~76~~ 72 bytes

```
$"_ and _"⍜(⊟∩□|⊏⍖.)(∘|(⊙⊙;|⊙;)≍,,∩(("club"|"spade")=@h⊢),)×∩(∊:"hd"⊢),,

```

Test pad

Naïve solution to the problem (if anyone can golf this more, comment please)

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


# Question
Title: Displaying Inky the ghost from Pac-Man using ANSI escape codes
# Challenge

Display Inky the ghost from Pac-Man using only ANSI escape codes.

Here's a text representation of the image

```
B B B B B C C C C B B B B B
B B B C C C C C C C C B B B
B B C C C C C C C C C C B B
B C W W C C C C W W C C C B
B W W W W C C W W W W C C B
B E E W W C C E E W W C C B
C E E W W C C E E W W C C C
C C W W C C C C W W C C C C
C C C C C C C C C C C C C C
C C C C C C C C C C C C C C
C C C C C C C C C C C C C C
C C B C C C B B C C C B C C
C B B B C C B B C C B B B C

```

| Code | ANSI Escape Code | Background Color |
| --- | --- | --- |
| B | "\x1b\[40m" | Black |
| C | "\x1b\[46m" | Cyan |
| W | "\x1b\[47m" | White |
| E | "\x1b\[44m" | Blue |

# ANSI Intro

This C example shows the use of ANSI escape codes to print

# Disclaimer

No Inky's were harmed in the making of this challenge.

# Answer
# JavaScript (ES6), 146 bytes

NB: The actual code contains the unprintable character `\x1b`.

```
f=(x=n=0)=>n<195?(x>13?`
`:`\x1b[4${"6074"[[5301,4781,4097,p=2731,p,2861,130,,,,,748,2458][y=n/15|0]*3>>x&1|7800/"52225"[y-3]>>x&2]}m `)+f(++n%15):""

```

Try it online!

Or 148 bytes to restore a black background.

### Output

### Encoding

| y | black/blue layer | decimal | / 3 | white/blue layer | decimal |
| --- | --- | --- | --- | --- | --- |
| 0 | 11111000011111 | 15903 | 5301 | 00000000000000 | 0 |
| 1 | 11100000000111 | 14343 | 4781 | 00000000000000 | 0 |
| 2 | 11000000000011 | 12291 | 4097 | 00000000000000 | 0 |
| 3 | 10000000000001 | 8193 | 2731 | 00001100001100 | 780 |
| 4 | 10000000000001 | 8193 | 2731 | 00011110011110 | 1950 |
| 5 | 10000110000111 | 8583 | 2861 | 00011110011110 | 1950 |
| 6 | 00000110000110 | 390 | 130 | 00011110011110 | 1950 |
| 7 | 00000000000000 | 0 | 0 | 00001100001100 | 780 |
| 8 | 00000000000000 | 0 | 0 | 00000000000000 | 0 |
| 9 | 00000000000000 | 0 | 0 | 00000000000000 | 0 |
| 10 | 00000000000000 | 0 | 0 | 00000000000000 | 0 |
| 11 | 00100011000100 | 2244 | 748 | 00000000000000 | 0 |
| 12 | 01110011001110 | 7374 | 2458 | 00000000000000 | 0 |
> 5 votes

# Answer
# C (gcc), 151 bytes

*-3 thanks to @vengy*
*-28 thanks to @ceilingcat*

Essentially a port of my JS answer.

```
n;y;main(x){for(;n<195;printf(x>13?"\n":"[4%cm ","6074"[L"㸟㠇〃  ↇƆ\0\0\0\0ࣄ᳎"[y=n++/15]>>x&1|(y>2&y<8)*7800/(~y&3?2:5)>>x&2]))x=n%15;}

```

Try it online!

### Output
> 2 votes

# Answer
# C (gcc), 147 bytes

```
i=182;main(){for(;i--;)printf("\e[4%cm %s","0674"[3&"ATPATQETQUUUUUUUUUUUUUUUeVeVUzWzGe~e~PiZiJTiUiATUUE@TUU@@PU"[i/3]>>i%3*2],i%14?"":"\e[0m\n");}

```

Try it online!

-4B from ceilingcat

Port like

Assumes that after `...TUU@@PU` there are 2 null bytes
> 2 votes

# Answer
# Commodore C64, using PETSCII graphics, ~392 BASIC bytes

The simplest way to do this is to use the reverse character mode to print out white spaces, but changing the colours as necessary. These are Control characters in Commodore BASIC, similar to escaped characters in a C or PHP string. We will use a string array `B$`, and then a `FOR/NEXT` loop to output to the C64 screen. All colours in this listing are accessed by the control (often referred to as `CTRL`) key, by pressing the following key combinations:

```
{BLACK} is CTRL + 1
{WHITE} is CRTL + 2
{CYAN} is CTRL + 4
{BLUE} is CRTL + 7
{REVERSE ON} is CTRL + 9

```

To make the listing clearer and easier to type in, `{SPACE x 5}` indicates 5 spaces following the control character, as looking at the listing in Commodore BASIC might not be very clear.

Here is the listing:

```
0DIMB$(12):B$(.)="{BLACK}{SPACE x 5}{CYAN}{SPACE x 4}{BLACK}{SPACE x 5}":B$(1)="{BLACK}{SPACE x 3}{CYAN}{SPACE x 8}{BLACK}{SPACE x 3}"
1B$(2)="{BLACK}{SPACE x 2}{CYAN}{SPACE x 10}{BLACK}{SPACE x 2}":B$(3)="{BLACK}{SPACE}{CYAN}{SPACE}{WHITE}{SPACE x 2}{CYAN}{SPACE x 4}{WHITE}{SPACE x 2}{CYAN}{SPACE x 3}{BLACK}{SPACE}"
2B$(4)="{BLACK}{SPACE}{WHITE}{SPACE x 4}{CYAN}{SPACE x 2}{WHITE}{SPACE x 4}{CYAN}{SPACE x 2}{BLACK}{SPACE}":B$(5)="{BLACK}{SPACE}{BLUE}{SPACE x 2}{WHITE}{SPACE x 2}{CYAN}{SPACE x 2}{BLUE}{SPACE x 2}{WHITE}{SPACE x 2}{CYAN}{SPACE x 2}{BLACK}{SPACE}"
3B$(6)="{CYAN}{SPACE}{BLUE}{SPACE x 2}{WHITE}{SPACE x 2}{CYAN}{SPACE x 2}{BLUE}{SPACE x 2}{WHITE}{SPACE x 2}{CYAN}{SPACE x 3}":B$(7)="{CYAN}{SPACE x 2}{WHITE}{SPACE x 2}{CYAN}{SPACE x 4}{WHITE}{SPACE x 2}{CYAN}{SPACE x 4}"
4B$(8)="{CYAN}{SPACE x 14}":B$(9}=B$(8):B$(10)=B$(8):B$(11)="{CYAN}{SPACE x 2}{BLACK}{SPACE}{CYAN}{SPACE x 3}{BLACK}{SPACE x 2}{CYAN}{SPACE x 3}{BLACK}{SPACE}{CYAN}{SPACE x 2}"
5B$(12)="{CYAN}{SPACE}{BLACK}{SPACE x 3}{CYAN}{SPACE x 2}{BLACK}{SPACE x 2}{CYAN}{SPACE x 2}{BLACK}{SPACE x 3}{CYAN}{SPACE}":FORI=.TO12:PRINT"{REVERSE ON}"B$(I):NEXT

```

Some notes: be careful when entering line 4 as it is 80 characters in length (the maximum number of characters in a logical C64 line). Cursor up so that the flashing cursor is over one of the characters on the line and press the return key. Or, enter this into a Commodore C128, which allows for 160 characters in a logical line; this will work in C64 or C128 mode. I typed this in again from the listing above to check that the number of spaces and control characters are correct, and it seems fine. Best viewed with `POKE 53280, 0: POKE 53281, 0: RUN`.

By using C128 BASIC, and with the 160 PETSCII character per logical line, this can be crunched further as you will be able to reduce the line numbers. Some bytes could also be saved by removing some of the control characters, for instance, where `B$(0)` ends with `{BLACK}` there is no need to start `B$(1)` with `{BLACK}`. I will try to crunch this further to save some more bytes.

And here is how things look on a C64 (at least a C64 emulator):
> 2 votes

# Answer
# Perl 5 \+ `-p0513`, 132 bytes

```
s!!5.2B8.4B5.5B3.CLBCLB2.2MB2MB2.,MB,MB.@/L@/L2BM2BM24B.B<.B<B<2.B2.B3..!;s/\d+(.)/$1x$&/ge;s/./ord$&/ge;s/.{14}\K/
/g;s/./.[4$&m /g
```

Try it online!

## Explanation

The string of random numbers and symbols is an RLE string that contains the data for all the background colours (only the last digit, as the first digit's always `4`), this is stored in `$_` via the `s///`ubstitution operator. This is decoded to repeated runs of characters and each of those characters is replaced with its `ord`inal value, split into run of `14` characters and has the ANSI escape code string wrapped around each value.
> 2 votes

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

```
f=(x=182)=>x?`\x1B[4${'0674'[3&Buffer('ATPATQETQUUUUUUUUUUUUUUUeVeVUzWzGe~e~PiZiJTiUiATUUE@TUU@@PU')[--x/3|0]>>x%3*2]}m `+(x%14?'':`\x1b[0m
`)+f(x):''

```

Try it online!

Hardcode

Arnauld's solution spill color and mine don't. Removing this difference mine is shorter, but Arnauld usen't Buffer

I don't use char `\x1B` since otherwise it's better encode 4 pos in a char
> 1 votes

# Answer
# C (gcc, msvc), 228 bytes

```
#include<stdio.h>
j,i[]={89391445,88080405,83886085,77597185,111684225,132660865,65552000,10488320,0,0,0,4214800,22040660};main(){for(;j<182;j++)printf("\x1B[4%cm%s","6074"[(i[j/14]>>(2*(13-j%14)))&3],j%14==13?" \x1b[0m\n":" ");}

```

NB: The actual code contains the unprintable `ESC` character `\x1b`.

Try it online!

# Output

Windows Command Prompt:

Linux (Ubuntu) Terminal:
> 1 votes

---
Tags: code-golf, graphical-output
---


title: Matrices Generated Using Rectangles

text:
# Question
Title: Matrices Generated Using Rectangles
Input is an r by c matrix of non-negative integers (you may input r and c as other parameters if this helps with golf). This may be inputted as a 2D array or, if you prefer, a 1D array (though taking in r this time is necessary). Strings separated by spaces to distinguish rows and newlines to distinguish columns are also fine (below, the test cases have multiple spaces to distinguish rows for clarity -- you do not have to do this).

Consider a matrix of zeros. A *move* consists of replacing a rectangle of numbers with a rectangle of some *positive* integer (not zero). For example, these are all valid first moves:

```
0 0 0 0
0 2 0 0
0 0 0 0
0 0 0 0

0 3 0 0
0 3 0 0
0 3 0 0
0 3 0 0

1 1 1 0
1 1 1 0
0 0 0 0
0 0 0 0

```

These are *not* valid first moves:

```
0 0 0 0
0 2 0 0
0 0 0 0
0 2 0 0

0 1 0 0
0 2 0 0
0 0 0 0
0 0 0 0

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

```

**Make *golfed* code to answer the following the question:**

Given an r by c matrix, what is the smallest possible number of turns taken to construct this?

### Test Cases:

```
1 1 1 1
1 2 2 2
1 2 3 3
1 2 3 4
1 2 3 4
> 4

1  2  3  4  5
6  7  8  9  10
11 12 13 14 15
> 15

3 3 3 3 3 3
3 2 2 2 2 3
3 2 1 1 2 3
3 2 1 1 2 3
3 2 2 2 2 3
3 3 3 3 3 3
> 3

1 1 1 1 1 1
1 2 2 2 2 1
1 2 0 0 2 1
1 2 0 0 2 1
1 2 2 2 2 1
1 1 1 1 1 1
> 8

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
> 0

1 1 1 1
1 3 3 1
2 3 3 2
2 2 2 4
> 4

```

# Answer
# Python 2, 333 bytes

```
lambda g,l=len:min(i for i in r(l(g)*l(g[0])+1)if g in o(l(g[0]),l(g),[[0]*l(g[0])for _ in" "*l(g)],set(sum(g,[])),i))
o=lambda w,h,g,s,I:I and sum([o(w,h,n,s,I-1)for n in[[[x<=j<=X<[]>Y>=i>=y and S or E for j,E in e(R)]for i,R in e(g)]for x in r(w)for X in r(x,w)for y in r(h)for Y in r(y,h)for S in s]],[])or[g]
r=range
e=enumerate

```

Try it online!

This only works in theory, because in practice, it takes way too long if you have more than about 5 elements in the grid.

Since this is , I apologize for the inefficiency, but efficiency would require more thought and FAR more bytes.

This code does the same thing at the cost of 5 bytes, but short-circuits, meaning that a larger grid with a small answer may finish somewhat earlier... the difference in viable search space is negligible, but just in case you wanted to test it a bit more.

The reason this is so slow is because it looks from \\$0\\$ up to \\$W\times H\\$, generating every possible \\$W\times H\\$ grid that can be achieved with the elements of the grid with that many steps being used.
> 3 votes

# Answer
# Python3, 1288 bytes

Long, but crunches the test cases in under a second.

```
R=range
E=enumerate
M=[(1,0),(-1,0),(0,-1),(0,1)]
def D(b):
 for x,j in E(b):
  for y,_ in E(j):
   for X in R(x,len(b)):
    for Y in R(y,len(b[0])):yield[(u,i)for u in R(x,X+1)for i in R(y,Y+1)]
def r(b):
 S={(x,y)for x,j in E(b)for y,_ in E(j)if _ not in['0']}
 W={*S}
 while S:
  x,y=[(x,y)for x,y in S if b[x][y]!='-'][0];S=S-{(x,y)};d,s={x:[y]},[(x,y)]
  V=b[x][y]
  q=[(x,y)]
  while q:
   x,y=q.pop(0)
   F=1
   for X,Y in M:
    J,K=x+X,y+Y
    if(J,K)in S and(b[J][K]==V or'-'==b[J][K]):F=0;q+=[(J,K)];S=S-{(J,K)};d={**d,J:sorted(d.get(J,[])+[K])};s=s+[(J,K)]
   if all(b==d[min(d)]for b in d.values()):yield s
def Z(B,s,i):
 B=eval(str(B))
 for x,y in s:B[x][y]=i
 return B
V=lambda W,c,S,U:(W==-1 or c+1<W)and all(C>c for C,u in S if u==U)
def f(b):
 q,S=[(b,0)],[(0,b)]
 L=[i for i in D(b) if i]
 W=-1
 while q:
  B,c=q.pop()
  if all(not({*i}-{'-','0'})for i in B):W=c if W==-1 else min(W,c);continue
  H=[*r(B)]
  for i in H:
   U=Z(B,i,'-')
   if V(W,c,S,U):
    q+=[(U,c+1)];S+=[(c,U)]
    if len({sum(B[x][y]!='-'for x,y in j)for j in H})==1:break
  U=Z(B,max([i for i in L if len(T:={B[x][y]for x,y in i})<3 and{'-'}!=T and'0'not in T and(len(T)==1 or'-'in T)],key=lambda X:sum(B[x][y]not in{'-','0'}for x,y in X)),'-')
  if V(W,c,S,U):q+=[(U,c+1)];S+=[(c,U)]
 return W

```

Try it online!
> 2 votes

---
Tags: code-golf, matrix
---


title: Enumerate a Cell Notation

text:
# Question
Title: Enumerate a Cell Notation
So we're all hopefully familiar with Spreadsheet 'A1' cell notation.

It's simply an alphanumeric representation of the positioning of said cell within a grid. The letter(s) represent the column positioning of the cell, and the number represents the row.

The 'letter' part can consist of 1 or more letters from the 26 letter English alphabet, all of which must be capital letters. These map to numbers through the use of 26-adic bijective numeration. The 'number' part can consist of any positive, non-zero integer.

---

The challenge, write a program that given the A1 notation of any cell as a single string, can output a string containing the column position represented as a number, followed by a space and then the row number.

Sample Input/Outputs below:

```
A1
>>1 1
B10
>>2 10
AC4
>>29 4
AAC753
>>705 753
F123
>>6 123
GL93
>>194 93

```

This is my first challenge, hence the relative simplicity and potential poorness of the criteria.

**EDIT**: String must be letters followed by numbers and the winning criteria is the shortest code length (if that can be a thing)

**EDIT**: Related to this but does the reverse process with a different starting index. Some may argue that this fact makes the linked puzzle more interesting.

# Answer
> 4 votes
# 05AB1E, ~~12~~ 11 bytes

```
áÇ64-₂βð¹þJ

```

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

# Answer
> 20 votes
# Microsoft Excel, 43 Bytes.

```
=COLUMN(INDIRECT(A1))&" "&ROW(INDIRECT(A1))

```

I couldn't help myself, I just had to use the right tool for the job. Takes input on A1.

## Test Cases

# Answer
> 11 votes
## Microsoft Excel, 40 bytes

**Brasilian Portuguese language version.**

```
=COL(INDIRETO(A1))&" "&LIN(INDIRETO(A1))

```

Translated (and therefore golfed) version of ATaco's solution.

# Answer
> 7 votes
# Python 2, ~~94~~ ~~91~~ 73 bytes

-3 bytes thanks to Jonathan Allan
-18 bytes thanks to tsh

```
s=input().strip
a=s(`3**39`);t=0
for n in a:t=t*26+ord(n)-64
print t,s(a)

```

Try it online!

This abuses the way that `.strip` works, removing all digits wtih `a=s(`3**39`)` where ``3**39`` is just a shorter way to generate the digits from `0` to `9`, this will store only the chars on `a` that will be used to strip the chars from the numbers on `s(a)`

# Answer
> 6 votes
# Google Sheets, 43 bytes

```
=COLUMN(INDIRECT(A1))&" "&ROW(INDIRECT(A1))

```

Try it online!

`A1` is the input cell. Hopefully the above link works, I've never tried code golf with Google Sheets before.

# Answer
> 5 votes
# JavaScript, 72 bytes

```
x=>x.replace(/\D+/,s=>[...s].reduce((n,v)=>n*26+parseInt(v,36)-9,0)+' ')

```

# Answer
> 2 votes
# Proton, 113 bytes

```
k=>{b=(s=k.strip)('0123456789');str(sum(map((a=>26**a[1][0]*(ord(a[1][1])-64)),enumerate(b[to by-1]))))+' '+s(b)}

```

Try it online!

-19 bytes borrowing Rod's algorithm (*note to self: add listcomps*)

# Answer
> 2 votes
# Dyalog APL, 44 bytes

```
(26⊥¯65+⎕AV⍳(a~⎕D)),⎕A~⍨a←⍞

```

Try it online!

# Answer
> 1 votes
# Pyth - 31 bytes

First attempt, very naive.

```
jd,s*V.u*26NQ1_hMxLGr-QK@`UTQZK

```

Try it online here.

# Answer
> 1 votes
# Jelly,  ~~16~~  15 bytes

```
ØAɓi@€ḟ0ḅ26,⁸Kḟ

```

A full program accepting the string as an argument and printing the result

**Try it online!**

### How?

```
ØAɓi@€ḟ0ḅ26,⁸Kḟ - Main link: list of characters, ref  e.g. "AAC753"
ØA              - uppercase alphabet yield               = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  ɓ             - dyadic chain separation, call that B and place it on the right
   i@€          - first index for €ach (swap arguments)    [1,1,3,0,0,0]
      ḟ0        - filter discard zeros                     [1,1,3]
        ḅ26     - convert from base 26 to integer           705
            ⁸   - chain's left argument (ref)              "AAC753"
           ,    - pair                                     [705,['A','A','C','7','5','3']]
             K  - join with spaces                         [705,' ','A','A','C','7','5','3']
              ḟ - filter discard those in right (B)        [705,' ','7','5','3']
                - implicit print                        >>>705 753

```

Note: conversion from a list of numbers using the base conversion atom  allows places to be outside of the expected range, so conversion from, say, `[2,26,1]` (`"BZA"`) using `ḅ26` is calculated as **2×262+26×261+1×260=2029** even though the "expected" representation would have been `[3,0,1]`.

# Answer
> 1 votes
# Perl 5, 35 + 1 (-p) = 36 bytes

```
map$r=$r*26-64+ord,/\D/g;s/\D*/$r /

```

Try it online!

The `map` statement treats the column like a base26 number and converts it to decimal. The substitution replaces the letters with the numbers. The input and output are implicit in the `-p` flag.

# Answer
> 1 votes
## Mathematica, 108 bytes

```
StringReplace[c:LetterCharacter..~~r:DigitCharacter..:>ToString@FromDigits[ToCharacterCode@c-64,26]<>" "<>r]

```

Operator form of `StringReplace` which takes the alphabetic part `c` of the string, converts it to a list of character codes, subtracts `64` from each code point, interprets the result as a base `26` integer, converts that integer to a `String`, then `StringJoin`s a space followed by the numeric part `r`.

Using a regex (also `108` bytes):

```
StringReplace[RegularExpression["([A-Z]+)(.+)"]:>ToString@FromDigits[ToCharacterCode@"$1"-64,26]<>" "<>"$2"]

```

# Answer
> 1 votes
# Mathematica, ~~77~~ ~~72~~ ~~69~~ 68 bytes

```
#/.{a__,b__?DigitQ}:>{f=FromDigits;f[LetterNumber@{a},26],f[b<>""]}&

```

Takes a list of characters.

Try it on Wolfram Sandbox

### Usage

```
#/.{a__,b__?DigitQ}:>{f=FromDigits;f[LetterNumber@{a},26],f[b<>""]}&[{"G", "L", "9", "3"}]

```

> `{194, 93}`

or

```
#/.{a__,b__?DigitQ}:>{f=FromDigits;f[LetterNumber@{a},26],f[b<>""]}&[Characters["GL93"]]

```

> `{194, 93}`

### Explanation

```
#/.

```

In the input replace...

```
{a__,b__?DigitQ}

```

A list containing two sequences `a` and `b` (with 1 or more elements), where `b` consists of digit characters only... (Mathematica uses lazy pattern matching, so no check is required for `a`)

```
:>

```

into...

```
f=FromDigits;

```

Set `f` to digit-to-integer conversion function.

```
LetterNumber@{a}

```

Convert `a` to letter numbers (a -\> 1, b -\> 2, etc).

```
{f[ ... ,26],f[b<>""]}

```

Convert the above from base-26 to decimal, and convert `b` to decimal.

# Answer
> 1 votes
# Ruby, ~~50~~ 48+1 = ~~51~~ 49 bytes

Uses the `-p` flag. -2 bytes from `m-chrzan`.

```
sub(/\D+/){i=0;$&.bytes{|b|i=26*i+b-64};"#{i} "}

```

Try it online!

# Answer
> 1 votes
# Ruby, ~~64~~ ~~61~~ 59 bytes

```
->s{s.sub(/\D+/){"#{$&.bytes.reduce(0){|t,b|t*26+b-64}} "}}

```

Saved 2 bytes thanks to Value Ink.

# Answer
> 1 votes
# Excel-VBA Immediate window, ~~44~~ 45 Bytes (~~36~~ 35)

```
Set v=Range([A1]):?trim(v.Column &" "&v.Row);

```

1 byte added to suppress the trailing newline

---

Or for 35 with leading whitespace

```
Set v=Range([A1]):?v.Column""&v.Row

```

1 byte saved thanks to @TaylorScott!

Both take input from cell A1, output to the VBE Immediate window

# Answer
> 1 votes
# Haskell, 67 bytes

```
(\(l,n)->show(foldl(\a->(a*26-64+).fromEnum)0l)++" "++n).span(>'9')

```

Try it online.

# Answer
> 1 votes
# Retina, 85 bytes

```
[A-Z]
$&
[T-Z]
2$&
[J-S]
1$&
T`_L`ddd
\d+
$*
{`\G1(?=.* .* )
26$*
}` (.* )
$1
1+
$.&

```

Try it online! Explanation:

```
[A-Z]
$&

```

Separate the letters from each other and the final number.

```
[T-Z]
2$&
[J-S]
1$&
T`_L`ddd

```

Convert the letters to decimal.

```
\d+
$*

```

Convert everything to unary.

```
{`\G1(?=.* .* )
26$*
}` (.* )
$1

```

While there are at least three numbers, multiply the first by 26 and add it to the second.

```
1+
$.&

```

Convert everything to decimal.

# Answer
> 1 votes
# \>\<\>, 42 Bytes

```
0i88*-:0(?\$2d**+!
$n88*+48*o\
oi:0(?;   >

```

**Try It Online**

### Explanation:

```
0i88*-:0(?\$2d**+! Read in the Letters part of the input
0                  Push an initial 0 to the stack
 i                 Read a character of input
  88*-             Subtract 64 to get from the ascii code to its value ('A'=1,'B'=2 etc.)
      :0(?\        If the value is less than 0, break out of this loop
           $2d**   Multiply our accumulator by 26
                +  Add our new number to the accumulator
                 ! don't add a new zero to the stack

```

The above loop will read in the first number of the numbers part (eg. '3' in "AB34") before breaking, and will have already subtracted 64 from it, so the next bit of code has to deal with that

```
$n88*+48*o\        Output a space, and prepare to output the first number we read in during the previous loop
          \        Loop round to the left end of this line
$n                 Output the value of the letters part as a number
  88*+             Add the 64 we subtracted from the first number
      48*o         Output a space
          \        Enter the next loop

```

This loop starts by outputting a character which will either be the 1st character read in by the first loop, or the character read in by the previous iteration of this loop.

```
oi:0(?;   >        Output the numbers part, by just echoing it
          >        Loop round to the start of the line
o                  Output the character
 i                 Read in the next character
  :0(?;            If the value read in was less than 0, terminate

```

# Answer
> 1 votes
## Lua, 127 Bytes

Some nice string manipulations going there, I'm using some function that are usually never used while golfing in lua :D. The best way to golf this would be to find an other way to iterate over the column part of the input while being able to retain the position of each letter. I didn't ^^'.

Try it online!

```
I=...l=I:gsub("%d",""):reverse()r=0
for i=1,#l
do
r=r+(l:sub(i,i):byte()-64)*math.pow(26,i-1)end
print(r.." "..I:gsub("%a",""))

```

### Explanation

```
I=...                       -- shorthand for the input
l=I:gsub("%d","")           -- shorthand for the column part
   :reverse()               -- letters are put in reverse order to calculate their weight
r=0                         -- column number
for i=1,#l                  -- iterate over the letters of the input
do
  r=r+                      -- add to the column number
      (l:sub(i,i):byte()-64)-- the byte value of the current letter minus 64 (A=1 this way)
      *math.pow(26,i-1)     -- then apply its weight in base 26
end
print(r                     -- output the column number
        .." "               -- a space
        ..I:gsub("%a",""))  -- and the row number

```

# Answer
> 1 votes
# Vyxal , 9 bytes

```
⌊ẆhøA₄β?⌊

```

Try it Online!

whoa

# Answer
> 0 votes
# JavaScript (Node.js), 67 bytes

```
x=>(a=0,b=x.replace(/\D/g,u=>(a=a*26+parseInt(u,36)-9,'')),a+' '+b)

```

Try it online!

Lots of code formatting

---
Tags: code-golf, alphabet
---


# Question
Title: Implement a typeface based on a 3x3 bitmap matrix
## Input

A single-character string containing an uppercase or a lowercase letter from the English alphabet.

Alternatively, you may handle only uppercase or only lowercase letters as input.

## Output

This 3x3 typeface of the input letter (source), with two distinct, printable ASCII characters of your choice (excluding tabs and newlines) to represent the black and white pixels. They also must be consistent: if a character is used to represent a black pixel for an input, that same character can't be used to represent a white pixel for another input.

You may alternatively create a string or list of characters of length 11 (12 if a trailing newline is present) and output that.

In this demonstration, the selected characters will be `.` for black and  for white:

```
A
 .
...
. .

B
..
...
...

C
...
.
...

D
..
. .
..

E
...
..
...

F
...
..
.

G
..
. .
...

H
. .
...
. .

I
...
 .
...

J
  .
. .
...

K
. .
..
. .

L
.
.
...

M
...
...
. .

N
...
. .
. .

O
...
. .
...

P
...
...
.

Q
...
...
  .

R
...
.
.

S
 ..
 .
..

T
...
 .
 .

U
. .
. .
...

V
. .
. .
 .

W
. .
...
...

X
. .
 .
. .

Y
. .
 .
 .

Z
..
 .
 ..

```

While a trailing newline is optional, the intermediate newline is required.

This is , so try to create your solution with fewest bytes possible. It also uses the standard I/O defined by the community.

---

Very thanks to @emanresuA for helping me on The Nineteenth Byte.

Sandbox

# Answer
> 5 votes
# Jelly, 42 bytes

```
ḢOị“©Ịı)ḍ6*,ÐÄÄ<Ụ,+ɼɲ4øeọṅịḲ{§*/ṡƑ’Bs9¤s3Y

```

A full program that accepts a single character string in upper case and prints the typeface for that character using `1`s, `0`s and newlines.

**Try it online!**

### How?

I don't think there is any pattern to exploit here so this is just a simple compression. (Trying to cater for `A`, `J`, and `S` being the only characters with no ink in the top left pixel is more expensive for example).

```
ḢOị“...’Bs9¤s3Y - Main Link: list of characters  e.g. "A"
Ḣ               - head                                'A'
 O              - ordinal -> Ord                      65 (N.B. 65 % 26 = 13)
           ¤    - nilad followed by links as a nilad
   “...’        -   a big number
        B       -   convert to binary
                         -> flat list of pixel values of O, P, Q, ..., Z, A, B, ..., N
                                               (indices: 1  2  3      12 13 14  ... 26(0))
         s9     -   split into chunks of length nine -> 26 binary lists
  ị             - {Ord} index into {that}             [0,1,0,1,1,1,1,0,1]
                    (1-indexed and modular)
            s3  - split into chunks of length three   [[0,1,0],[1,1,1],[1,0,1]]
              Y - join with newline characters        [0,1,0,'\n',1,1,1,'\n',1,0,1]
                - implicit, smashing print

```

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

Expects the ASCII code of an upper case letter. Returns a string of 0's (white) and 1's (black).

```
c=>`876
543
210`.replace(/./g,n=>parseInt("DDEED5CAAA99B5CDBDDBAD3A8E"[c%=26]+"PR41GYY72NHE79FJYZWZL33D75"[c],36)>>n&1)

```

Try it online!

NB: In order to have each typeface encoded as two characters, we can actually use any base in \\$\[23\dots36\]\\$ (because \\$\log\_{23}2^9\approx1.99\\$, while \\$\log\_{22}2^9\>2\\$).

# Answer
> 3 votes
# JavaScript (Node.js), 95 bytes

```
c=>`2i2owi3ukgacum8
193s0cuufnghmk0
004zspr9y5072pg`.replace(/.{5}/g,n=>parseInt(n,36)>>c%26&1)

```

Try it online!

Inverse view of Arnauld

Generator

# JavaScript (Node.js), 94 bytes

```
c=>`05mo1jcsjkjz8ej
zffuo1yte4zibec
vkdfk5502pbswtk`.replace(/.{5}/g,n=>parseInt(n,36)>>c-1&1)

```

Try it online!

Use 32-bit fact

# Answer
> 3 votes
# Charcoal, 43 bytes

```
⪪§⪪”{∨&×⊞ΦＶＲvRμΣ⧴ＷςCＺ¦±✳Ｚ“…⎚\`ＡW⦃$z↶c(�”⁹℅Ｓ³

```

Try it online! Link is to verbose version of code. Takes the input letter in upper case. Explanation:

```
   ”...”        Compressed bitmap of `.`s and spaces
  ⪪     ⁹       Split into groups of length 9
 §       ℅Ｓ     Cyclically index by the ordinal of the input letter
⪪          ³    Split into 3 lines
                Implicitly print

```

The compressed string starts with the bitmap for `N` as its ordinal is `78` which is a multiple of `26`.

# Answer
> 1 votes
# Python 3.8, 176 bytes

The function takes as input only uppercase letters.

```
def g(c):
 o=bin([-233,25,65,8,81,78,9,-41,49,-311,-49,-127,87,71,73,86,83,62,-208,44,-55,-60,-39,-81,-84,-19][ord(c)-65]+422)[2:].zfill(9)
 return o[:3]+'\n'+o[3:6]+'\n'+o[6:]

```

Try it online!

---

# Python 3.8, 231 bytes (letters and numbers)

The function handles both uppercase letters and numbers.

```
def g(c):
 o=bin([85,-3,-7,69,-33,-196,-91,47,-155,95,-221,37,77,20,93,90,21,-29,61,-299,-37,-115,99,83,85,98,95,74,-196,56,-43,-48,-27,-69,-72,-7][ord(c)-(48 if c<'A'else 55)]+410)[2:].zfill(9)
 return o[:3]+'\n'+o[3:6]+'\n'+o[6:]

```

Try it online!

---

Commented code (letters and numbers)

```
def g(input_char):

    # each character pixmap is encoded using '1' for filled and '0' for gaps, excluding newlines
    # resulting in a binary string ('0' -> '111101111')
    # the binary string is converted into a decimal value
    # the decimal value is offset by 410 to reduce the length of the pixmap list

    # pixmap of characters '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    pixmap = [85,-3,-7,69,-33,-196,-91,47,-155,95,-221,37,77,20,93,90,21,-29,61,-299,-37,-115,99,83,85,98,95,74,-196,56,-43,-48,-27,-69,-72,-7]

    # select the pixmap corresponding to the character
    # using the ascii value
    char_pixmap = pixmap[ord(input_char) - (48 if input_char < 'A' else 55)]

    # account for the offset
    char_pixmap += 410

    # build the binary string representing the pixmap for the characters
    # '1' for filled, '0' for gaps
    output = bin(char_pixmap)[2:].zfill(9)

    # insert newlines
    return output[:3] + '\n' + output[3:6] + '\n' + output[6:]

```

---
Tags: code-golf, printable-ascii
---


title: Snow Blow My Driveway!

text:
# Question
Title: Snow Blow My Driveway!
There has recently been a big snow, and my driveway needs snow-blowing. If the snow-blower goes over some area that it has already snow-blowed, then that area will have snow blown onto it and need to be blown again. And of course, the snow-blower cannot start in the middle of the driveway, it needs to start from my garage, where it is stored.

**More formally:**

Your program takes a standard form of input as a string or multidimensional array that looks like the following:

```
XXXXOOOOXXXX
X          X
X          X
XXXXXXXXXXXX

```

`X` represents an area that cannot be snow-blowed, `O` represents an area where the snow-blower can be deployed, and empty spaces represent areas where there is snow. You can chose different values if you wish.

Your program must output something like the following:

```
XXXX*%OOXXXX
Xv<<<^<<<<<X
X>>>>>>>>>^X
XXXXXXXXXXXX

```

The snow-blower starts at the `*`. The `*` always points to the nearest non-garage space. The `<`,`>`,`v`, and `^` all represent pointers of where the next direction is. They point the snow-blower where to go. Once a pointer points to the `%`, the blower has re-arrived into the garage, and the whole driveway should be clear.

The snow blower must go over the whole driveway. The snowblower's path can never overlap itself. Impossible input must not be given.

Because I don't want to be outside any longer than I need to be, and not need to spend a lot of time typing, the program should be as short as possible. Shortest code wins!

**Test Cases:**

These test cases may have multiple correct answers. I have provided possible solutions below each test case.

Test case 1: The one given in the example.

Test case 2:

```
XOOOOOX
X     X
X     X
X     XXXXXXXX
X            X
X            X
XXXXXXXXXXXXXX

X*OOO%X
Xv>>>^X
Xv^<<<X
Xv>>>^XXXXXXXX
Xv^<<<<<<<<<<X
X>>>>>>>>>>>^X
XXXXXXXXXXXXXX

```

Test case 3:

```
XOOOOX
X    X
X    X
X  XXX
X    X
X    X
XXXXXX

XOO%*X
X>>^vX
X^v<<X
X^vXXX
X^>>vX
X^<<<X
XXXXXX

```

Test case 4:

```
XXXXXXXXXXXXX
O           X
O    X      X
O    X      X
O           X
XXXXXXXXXXXXX

XXXXXXXXXXXXX
*>>>>>>>>>>vX
Ov<v<Xv<<<<<X
Ov^v^X>>>>>vX
%<^<^<<<<<<<X
XXXXXXXXXXXXX

```

# Answer
> 4 votes
# JavaScript (ES6), ~~346~~ ~~310~~ ~~299~~ ~~298~~ ~~297~~ ~~296~~ 283 bytes

```
f=(a,y=0,x=0)=>(a[y][x]?a[y][x]=='O'&&(a[y][x]='*',(g=w=>(w=a[y])&&w[x]&&(w[x]<'!'?g(w[x]='v',y++)||g(w[x++]='>',y--)||g(w[--x]='^',y--)||g(w[x--]='<',y++)||+(w[++x]=' '):w[x]=='O'&&!/ /.test(a)?w[x]='%':0))(y++)||g(y-=2)||g(y++,x++)||g(x-=2)||+(a[y][++x]='O'))||f(a,y,x+1):f(a,y+1))
```

```
<textarea id="tests">XXXXOOOOXXXX
X          X
X          X
XXXXXXXXXXXX

XOOOOOX
X     X
X     X
X     XXXXXXXX
X            X
X            X
XXXXXXXXXXXXXX

XOOOOX
X    X
X    X
X  XXX
X    X
X    X
XXXXXX

XXXXXXXXXXXXX
O           X
O    X      X
O    X      X
O           X
XXXXXXXXXXXXX</textarea><br><button onclick="for(test of document.getElementById('tests').value.split('\n\n')){console.log(test);arr=test.split('\n').map(line=>line.split(''));f(arr);console.log(arr.map(line=>line.join('')).join('\n'))}">Run</button>
```

Quite hacky in some places, but I wanted to get the code out there. Input as a 2D character array, output by modifying said array.

### Ungolfed version

This is the same exact algorithm, save for some truthy/falsy magic with `+' '` being `NaN` being falsy (and some more), some golf variables and using `if`s instead of `?:`, `||` and `&&`.

```
f = (a, y = 0, x = 0) => {         // main function
  if (!a[y][x])                    // check for end of line
    return f(a, y + 1);            // end of line, recursively check next
  if (a[y][x] == 'O') {            // check for valid start position
    a[y][x] = '*';                 // set the start position
    function g() {                 // pathfinder function
      if (!a[y] || !a[y][x])       // check for out of bounds
        return 0;
      if (a[y][x] == ' ') {        // check for snow
        a[y][x] = 'v';             // set current cell to 'down'
        y++;                       // move position down
        if (g()) return 1;         // see if a valid route is found from there
        y--;                       // if not, reset position and try again
        a[y][x] = '>';             // repeat for other directions
        x++;
        if (g()) return 1;
        x--;
        a[y][x] = '^';
        y--;
        if (g()) return 1;
        y++;
        a[y][x] = '<';
        x--;
        if (g()) return 1;
        x++;
        a[y][x] = ' ';             // no route found, reset cell to snow
        return 0;
      }
      if (a[y][x] == 'O'           // check for valid exit
          && !/ /.test(a)) {       // and that no snow is left
        a[y][x] = '%';             // set the exit
        return 1;
      }
    }
    y++;                           // move a cell down from the start position
    if (g()) return 1;             // see if a valid route starts there
    y -= 2;                        // repeat for other directions
    if (g()) return 1;
    y++; x++;
    if (g()) return 1;
    x -= 2;
    if (g()) return 1;
    x++;
    a[y][x] = 'O';                 // no route found, continue on
  }
  return f(a, y, x + 1);           // check the next cell
}

```

# Answer
> 0 votes
# Python3, 737 bytes

```
E=enumerate
G=['v','^','>','<']
O=lambda x,y,D,M=1:[(*t,D[t],m)for(X,Y),m in zip([(1,0),(-1,0),(0,1),(0,-1)],G)if(M==1 or[m in G[:2],m in G[2:]][M in G[:2]])and(t:=(x+X,y+Y))in D]
def f(b):
 d={(x,y):v for x,j in E(b)for y,v in E(j)}
 q=[({**d,i:'*'},*i)for i in d if'O'==d[i]][:1]
 while q:
  D,x,y=q.pop(0)
  u,F={},1
  Q=[]
  for X,Y,v,m in O(x,y,D):
   u[v]=(m,(X,Y))
   if' '==v and{V for J,K,V,_ in O(X,Y,D,m)if(J,K)not in[(X,Y),(x,y)]}&{'O','X',*G}:Q+=[({**D,(X,Y):m},X,Y)];F=0
  if F:
   if' 'not in D.values()and'O'in u:
    D={**D,u['O'][1]:'%'}
    for x,y in D:b[x][y]=D[(x,y)]
    return b
   elif' 'in u:Q+=[({**D,u[' '][1]:u[' '][0]},*u[' '][1])]
  if not all(' 'not in[V for *_,V,_ in O(*i,D)]for i in D if'O'==D[i]):q+=Q

```

Try it online!

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


title: Tips for golfing in Rust

text:
# Question
Title: Tips for golfing in Rust
While Rust is very, very rarely competitive in code golfing competitions (Java is often shorter), it can still be fun to golf in. What are some tricks for making Rust code shorter?

Please post only one tip in each answer.

# Answer
## Use closures instead of functions

A closure:

```
|n|n+1

```

is shorter than a function:

```
fn f(n:i32)->i32{n+1}

```

---

Closures longer than one statement need braces but are still far shorter than a function.
> 24 votes

# Answer
# Converting `&str` to `String`

Never do these:

```
s.to_string()  // 13 bytes
s.to_owned()   // 12 bytes

```

This is always shorter:

```
s.repeat(1)    // 11 bytes

```

If `s` is a string literal:

```
format!(s)     // 10 bytes

```

For example: use `format!("")` instead of `String::new()` to save 2 bytes.

If type inference works:

```
s.into()       // 8 bytes

```
> 20 votes

# Answer
# Avoid .iter().enumerate()

Let's say you have some x that implements the IntoIterator Trait and you need to call a function f that takes the index of an element and a reference to it. The standard way of doing this is

```
x.iter().enumerate().map(f)

```

instead you can do

```
(0..).zip(x).map(f)

```

and save yourself not only the unusually long enumerate but also the call to iter!
> 16 votes

# Answer
If you need many mutable variables, it can waste a lot of space declaring them and initializing them, since each requires the mut keyword and you can't do anything like a=b=c=0. A solution then is to declare a mutable array

```
let mut a=[0;5];

```

You spend 3 extra bytes each time you use them vs. a normal variable:

```
a[0]+=1;

```

but it can often still be worth it.

Using tuples for the same trick is often an even better option:

```
let mut t=(1,4,"this", 0.5, 'c');

```

This has the advantage of saving a byte on each use vs. the array:

```
t.0=2

```

It also lets them be of different types. On the downside, it requires more characters to initialize.
> 15 votes

# Answer
# Use `@` to define multiple variables to the same value

`@` is meant to define an alias for pattern matching (like destructuring an array but also getting the original array at the same time). But it works with plain variables too.

```
let a=2;let b=2; // 16 bytes
let(a,b)=(2,2);  // 15 bytes
let a@b=2;       // 10 bytes

```

It works in destructuring too:

```
let a=1;let b=1;let c=2;let d=2; // 32 bytes
let(a,b,c,d)=(1,1,2,2);          // 23 bytes
let(a@b,c@d)=(1,2);              // 19 bytes

```
> 14 votes

# Answer
When using string formatting for example with `print!()`, one can use both numbered and unnumbered formatters to save one byte per item to format:

Best shown with an example:

```
fn main() {
    print!(
        "{}{}{}. Yes, {0}{}{2}. All you other{1}{2}s are just imitating.",
        "I'm", " Slim", " Shady", " the real",
    );
}

```

Which outputs:

> ```
> I'm Slim Shady. Yes, I'm the real Shady. All you other Slim Shadys are just imitating.
>
> ```

So the unnumbered formatters will get assigned to the items in order, this allows you to skip the index on them. Note that you can only use one unnumbered formatter per item to format, after that it will get used up.
> 11 votes

# Answer
# Skipping trailing semicolons

In functions returning `()`, where the last expression is also of type `()`, you don't need the trailing `;`:

```
fn main(){print!("Hello, world!")}

```
> 9 votes

# Answer
# Replace all `filter_map` with `flat_map`

It works because:

* `filter_map` takes a `FnMut(Self::Item) -> Option<B>`
* `flat_map` takes a `FnMut(Self::Item) -> impl IntoIterator`
* `Option` implements `IntoIterator`, which will return an iterator with one item for `Some` and empty iterator for `None`
> 9 votes

# Answer
When working with strings with newlines in them, you save one byte if you use a literal line break in the source code vs having a `\n` in the string and/or using `println`.

```
print!("Hello
World!
");

```

is 2 bytes less than:

```
println!("Hello\nWorld!");

```
> 8 votes

# Answer
# Do-while loops

Rust does not have a C-style do-while loop:

```
do{do_work();}while(condition);

```

But blocks are also expressions in Rust, so you can write:

```
while{do_work();condition}{}

```
> 8 votes

# Answer
# Reading lines

After considering various things, I think that is generally the shortest way to retrieve a line. The line has a newline, it can be removed by trimming (`.trim()`) or if that cannot be done by slicing.

```
let y=&mut"".into();std::io::stdin().read_line(y);

```

For multiple lines, `lines` iterator can be used, the iterated line doesn't end in newline then. A glob import is needed to import `BufRead`, needed for `lines` to be available for `StdinLock<'_>` type.

```
use std::io::*;let y=stdin();y.lock().lines()

```
> 7 votes

# Answer
When using whole number floating point numbers, you can omit the trailing `.0` to save one byte.

```
let a=1.

```

is 1 byte less than:

```
let a=1.0

```
> 7 votes

# Answer
# Use `..=`

Replace all `..i+1` with `..=i` to save 1 byte, works on both array index `a[i..=i]` and range `(0..=n)`
> 7 votes

# Answer
# Use closure parameter to define variable instead of `let`

```
{let(a,b)=(A,B);X}

```

can be replaced by

```
(|a,b|X)(A,B)

```

to save 5 bytes if the type of `a` and `b` can be inferred, it usually works when they are integers or are passed to another function directly in `X`.

This works well on 2 or more variables, but for a single variable, this could still save 2 bytes if it allows you to get rid of the `{}`.
> 6 votes

# Answer
# Declare multiple variables using pattern matching

(Somewhat of an extension of https://codegolf.stackexchange.com/a/99124/97519)

Using multiple `let` statements:

```
let a=x;let b=y;
let a=x;let b=y;let c=z;

```

Using a tuple match saves 1 char for 2 variables and 3 more chars for ever variable after:

```
let(a,b)=(x,y);
let(a,b,c)=(x,y,z);

```

Similarly, you can use array patterns for initializing multiple mutable variables to the same value (this works with immutable variables too but is pretty useless):

```
let[mut a,mut b]=[x;2];

```
> 6 votes

# Answer
# Prefer todo! over panic!

`todo!` is shorter than `panic!` by 1 byte, so prefer to use it if you need to panic and exit the program. It's also shorter than `print!` by a byte, so it can shorten your program if you can output to stderr instead of stdout.

```
todo!("optional message for stderr")

```
> 6 votes

# Answer
Use the `?` operator to unwrap infallible results. `?` is used for error propagation in conjunction with the result and option types, and per this meta post returning them with infallible results is a standard output method. For example, the following code summing the value of a string when interpreted in base a and b, with `?`:

```
|s,a,b|Ok(i32::from_str_radix(s,a)?+i32::from_str_radix(s,b)?)

```

and without:

```
|s,a,b|i32::from_str_radix(s,a).unwrap()+i32::from_str_radix(s,b).unwrap()

```

As you can see, with `?` it is much shorter, and it works with options as well, although often for smaller gains.
> 4 votes

# Answer
# `if let` can sometimes be shorter than `match`

Using `match`:

```
match a{M(v)=>expr,_=>other}

```

Using `if let` costs 2 bytes if there are only 2 branches and 1 is wildcard:

```
if let M(v)=a{expr}else{other}

```

More effective when your `match` needed `{}` anyways, like if the types don't match. For example:

```
match a{M(v)=>{expr;}_=>{other;}}

```

vs.:

```
if let M(v)=a{expr;}else{other;}

```

saves 1 byte.
> 4 votes

# Answer
# Loops are sometimes shorter than iterators

Even with the extra curly braces, in some cases it can be shorter to declare a mutable variable and use a loop instead of using `Iterator` methods.

For example, to do something with every third element of a slice and then return the last index:

```
|n:&[_]|{let mut i=0;while i<n.len(){println!("{}",n[i]);i+=3}i-3}

```

```
|n:&[_]|(0..=n.len()/3).map(|i|{println!("{}",n[i*3]);i*3}).last().unwrap()

```
> 3 votes

# Answer
# `(0..).scan` can be shorter than `std::iter::successors`

If you want to make endless sequences that are based on previous state:

```
std::iter::successors(Some(a),|x,_|Some(/*something*/))

```

This will be shorter by a character:

```
(0..).scan(a,|x,_|{let y=*x;*x=/*something*/;Some(y)})

```

If you don't mind dropping the first case, it can be even shorter:

```
(0..).scan(a,|x,_|{*x=/*something*/;Some(*x)})

```
> 3 votes

# Answer
# Get the nth element of a `String` or `&str` slice

In rust you can't directly index a string or slice. If you want to build a string from indexes of another string you would typically do this:

```
s.chars().nth(n).unwrap() // char
s.bytes().nth(n).unwrap() // u8

```

Shorter is this, but it will depend `s` so won't work if `s` is generated from a expression:

```
s.as_bytes()[n]as char // char, supports only single byte characters
s.as_bytes()[n] // u8

```

However, if you are ok with a `&str` (like if you want to collect into a `String` or concatenate with a existing `String`). This also supports only single byte characters.

```
&s[n..][..1] // &str
&s[n..=n] // &str, if `n` is a single variable or sufficiently short expression

```

If your expression is a literal you can use byte string instead to index it directly:

```
b"hello world"[n] // u8
b"hello world"[n]as char // char

```
> 3 votes

# Answer
# `scan` and `fold` on `Iterator`s can be used for stateful iteration

If your closure consists of variable declarations and iterating over something while keeping an internal state, you might be able to save some bytes by using `scan` or `fold` instead of a `for` loop:

```
|i:&str|{let(mut a,mut b,mut c)=(1,2,0);for x in i.chars(){/*AAA*/;/*BBB*/;c=/*CCC*/}c}

```

`scan` is good for handling many mutable variables, at the cost of some operations (such as assignment) requiring dereferencing with `*` and needing to collect the final value using a method like `last`:

```
|i:&str|i.chars().scan((1,2),|(a,b),x|{/*AAA*/;/*BBB*/;Some(/*CCC*/)}).last()

```

`fold` can also be used in a similar manner by passing values in the accumulator:

```
|i:&str|i.chars().fold((1,2,3),|(a,b,c),x|(/*AAA*/,/*BBB*/,/*CCC*/)).2

```
> 2 votes

# Answer
## Using slice patterns to get both an array and variables with the same value

It is a common trick to use array slicing to compactly assign many variables to the same value:

```
let[a,b,c]=[0;3]
// vs
let(a,b,c)=(0,0,0)
// or
let a=0;let b=0;let c=0;

```

I've never really seen this used on arrays, even though it also saves bytes there:

```
let[a,..@b]=[0;99]; // store "the rest" of the slice in b
// vs
let(a,b)=(0,[0;98]);
// or
let a=0;let b=[0;98];

```

Saves just one byte so may not be worth it if it increases the array size by one byte.

It works for mutable variables too:

```
let[mut v,mut u@..]=[0;99];
// vs
let(mut u,mut v)=(0,[0;98]);

```
> 1 votes

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