# Question
Title: Find a function with cycles of every length
A function is said to have a *cycle of length n* if there exists an *x* in its domain such that *fn(x) = x* and *fm(x) ≠ x* for *0 \< m \< n*, where the superscript *n* denotes *n*-fold application of *f*. Note that a cycle of length *1* is a fixed point *f(x) = x*.

Your task is to implement a *bijective* function from the integers to themselves, which has exactly one cycle of every positive length *n*. A bijective function is a one-to-one correspondence, i.e. every integer mapped to exactly once. Having exactly one cycle of length *n* means that there are exactly *n* distinct numbers *x* for which *fn(x) = x* and *fm(x) ≠ x* for *0 \< m \< n*.

Here is an example of what such a function might look like around *x = 0*:

```
x     ... -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7 ...
f(x)  ...  2  4  6 -3 -1  1 -4  0 -2  5  7 -7 -6  3 -5 ...

```

This excerpt contains cycles of length *1* to *5*:

```
n   cycle
1    0
2   -2  1
3   -4 -3 -1
4   -5  6  3  7
5   -7  2  5 -6  4
...

```

Note that above I'm using "function" only in the mathematical sense. You may write either a function or a full program in your language of choice, as long as it takes a single (signed) integer as input and returns a single (signed) integer. As usual you may take input via STDIN, command-line argument, function argument etc. and output via STDOUT, function return value or function (out) argument etc.

Of course, many languages don't (easily) support arbitrary-precision integers. It's fine if your implementation only works on the range of your language's native integer type, as long as that covers at least the range *\[-127, 127\]* and that it would work for arbitrary integers if the language's integer type was replaced with arbitrary-precision integers.

Standard rules apply.

# Answer
# Pyth, ~~27~~ 18 bytes

```
_h?gQ0^2Q*.5@,Q-xh

```

Explanation (Pyth initializes `Q` to the input integer):

```
_                       negative of (
                          (
  ?gQ0                      if Q >= 0:
      ^2Q                     2**Q
                            else:
         *.5                  half of
            @        Q          element Q (modulo list length) in
             ,                    the two element list [
              Q                     Q,
                 hQ                 ((Q plus 1)
                x  Q                 XOR Q)
               -    Q               minus Q
                                  ]
 h                        ) plus 1
                        )

```

This has cycles

(−1)
(0, −2)
(1, −3, −4)
(2, −5, −7, −6)
(3, −9, −13, −11, −8)
(4, −17, −25, −21, −15, −10)
(5, −33, −49, −41, −29, −19, −12)
(6, −65, −97, −81, −57, −37, −23, −14)
(7, −129, −193, −161, −113, −73, −45, −27, −16)
(8, −257, −385, −321, −225, −145, −89, −53, −31, −18)
(9, −513, −769, −641, −449, −289, −177, −105, −61, −35, −20)

The cycle of length *n* is given by

(*n* − 2,
−2^(*n* − 2)⋅1 − 1,
−2^(*n* − 3)⋅3 − 1,
−2^(*n* − 4)⋅5 − 1,
…,
−2^2⋅(2·*n* − 7) − 1,
−2^1⋅(2·*n* − 5) − 1,
−2^0⋅(2·*n* − 3) − 1).

Each integer *k* ≥ −1 appears as the first element of the (*k* \+ 2)-cycle. For each integer *k* \< −1, we can uniquely write 1 − *k* = 2^*i* ⋅ (2⋅*j* \+ 1) for some *i*, *j* ≥ 0; then *k* appears as the (*j* \+ 2)th element of the (*i* \+ *j* \+ 2)−cycle.
> 2 votes

# Answer
# MATL, 47 bytes

```
E|G0<-QXJ:tQ*2/0hStJ<f0))Q2MQ)&:J6M-)2/ttk>Eq*k

```

**Try it online!**

### General explanation

*Function 2 below is the same as used in @Sp3000's answer to the related challenge. Thanks to @Agawa001 for noticing.*

The function is the composition of three:

1. Bijection from **Z** (the integers) to **N** (the naturals).
2. Bijection from **N** to **N** with the desired characteristic (one cycle of each length).
3. Inverse of function 1.

Functions 1 and 3 are used because it's easier (I think) to achieve the desired behaviour in **N** than in **Z**.

Function 2 is as follows: upper line is domain, lower line is codomain. Commas are used for clarity:

```
1,  2  3,  4  5  6,  7  8  9  10  ...
1,  3  2,  6  4  5, 10  7  8   9  ...

```

The first block (from upper `1` to lower `1`) is a cycle of length 1. The second (from `2 3` to `3 2`) is a cycle of length 2, etc. In each block, the lower part (image of the function) is the upper part circularly shifted one step to the right.

Function 1 is as follows:

```
 -5  -4  -3  -2  -1   0  +1  +2  +3  +4  ...
+10  +8  +6  +4  +2  +1  +3  +5  +7  +9  ...

```

Function 3 is the same as 1 with the two lines swapped.

### Examples

The image of `3` is `-5`. First `3` is mapped to `7` by function 1; then `7` is mapped to `10` by function 2; then `10` is mapped to -5\` by function 3.

The length-1 cycle is `0`. The length-2 cycle is `-1 1`. The length-3 cycle is `-3 2 -2`, etc.

### Code explained

Functions 1 and 3 are straightforward.

Function 2 works by finding the lower endpoint of the corresponding input block. For example, if the input to this function is `9` it finds `7` (see blocks above). It then picks the upper endpoint, which is `10` in the example. The circular shift of the block is achieved thanks to MATL's 1-based, modular indexing.

```
         % FUNCTION 1
         % Implicit input
E|       % Multiply by two. Absolute value
G0<      % 1 if input is negative, 0 otherwise
-        % Subtract
Q        % Add 1
XJ       % Copy to clipboard J. Used as input to the next function

         % FUNCTION 2
:        % Range [1 2 ... J], where J denotes the input to this function
tQ*      % Duplicate, increment by 1, multiply
2/       % Divide by 2
0hS      % Prepend a 0. This is needed in case J is 0
tJ<f     % Duplicate. Find indices that are less than the input J
0)       % Pick the last index.
)        % Apply as index to obtain input value that ends previous block
Q        % Add 1: start of current block
2M       % Push the two arguments to second-to-last function call
Q)       % Add 1 and use as index: end of current block
&:       % Inclusive binary range: generate input block
J        % Push J (input to function 2)
6M-      % Subtract start of block
)        % Apply as index (1-based, modular). This realizes the shifting

         % FUNCTION 3
2/       % Divide by 2
ttk>     % Duplicate. 1 if decimal part is not 0; 0 otherwise
Eq       % Multiply by 2, add 1
*        % Multiply
k        % Round down
         % Implicit display

```
> 4 votes

# Answer
## Python 2, 55 bytes

```
g=lambda n,k=1:n/k and~g(~n+k*(n>0),k+1)+k*(n>0)or-~n%k

```

---

**59 bytes:**

```
g=lambda n,k=1:n<0and~g(~n,2)or n/k and k+g(n-k,k+2)or-~n%k

```

Creates the cycles

```
[0]
[-1, -2]
[1, 2, 3]
[-3, -4, -5, -6]
[4, 5, 6, 7, 8]
...

```

Modified from my solution on the earlier challenge, which is modified from Sp3000's construction.

The function

```
g=lambda n,k=1:n/k and k+g(n-k,k+2)or-~n%k

```

makes odd-size cycles of non-negative numbers

```
[0]
[1, 2, 3]
[4, 5, 6, 7, 8]
...

```

To find the correct cycle size `k`, shift the input `n` down by `k=1,3,5,7,...` until the result is in the interval `[0,k)`. Cycle this interval with the operation `n->(n+1)%k`, then undo all the subtractions done on the input. This is implemented recursively by `k+g(n-k,k+2)`.

Now, we need the negative to make the even cycles. Note that if we modify `g` to start with `k=2` in `g`, we'd get even-size cycles

```
[0, 1]
[2, 3, 4, 5]
[6, 7, 8, 9, 10, 11]
...

```

These biject to negatives via bit-complement `~`. So, when `n` is negative, we simply evaluate `g(n)` as `~g(~n,2)`.
> 4 votes

# Answer
## Python 3, 146 bytes

For every number greater than 0, there are even loops (len 2,4,6,8...), and less than 0, odd loops (1,3,5,7). 0 maps to 0.

(-3,-2,-1),(0),(1,2),(3,4,5,6)

maps to

(-2,-1,-3),(0),(2,1),(6,3,4,5)

```
f=lambda x:1+2*int(abs(x)**.5)if x<1 else 2*int(x**.5+.5)
x=int(input());n=f(x)
if x>0:b=n*(n-2)/4
else:b=-((n+1)/2)**2
print(b+1+(x-b-2)%n)

```

Edit: @TuukkaX took off 8 bytes from the previous solution. And another 3.
> 2 votes

# Answer
## Matlab(423)

```
function u=f(n),if(~n)u=n;else,x=abs(n);y=factor(x);for o=1:nnz(y),e=prod(nchoosek(y,o)',1);a=log(x)./log(e);b=find(a-fix(a)<exp(-9),1);if ~isempty(b),k=e(b);l=fix(a(b));break;end;end,if(abs(n)==1)k=2;l=0;end,if(k==2)l=l+1;x=x*2;end,e=dec2base(l,k)-48;o=xor(e,circshift(e,[0 1]));g=~o(end);if(~o|nnz(o==1)~=numel(e)-g),u=n*k;else,if((-1)^g==sign(n)),u=sign(n)*k^(base2dec([e(2:end-1) 1]+48,k)-(k==2));else,u=n*k;end,end,end

```
* Non-competing because it breaks a good record of being condidate for the last ranking, whilst I am struggling to shorten it as possible as i can.
* Some nonesensical bugs concerning accuracy in matlab that I couldnt find any way out except making my code sarcatistically big, in other hand the mapping I opt for was in terms of prime facors and n-ary logarithm.

**Execution**

```
 f(2)

 1

 f(1)

 2

 f(-2)

 -4

 f(-4)

 -8

 f(-8)

 -1

 f(0)

 0

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

```

## Explanation

* Knonwing, first off, that any number can be written as product of exponents of primes `N=e1^x1*e2^x2...` from this base i chose to map images of cycles `C` which are extracted from the biggest exponent of the smallest factor (not necessarily prime) that N is a perfect power of.
* in simpler words, let `N=P^x` where P is the smallest perfect root, `x` denotes precisely two essential terms for the cycle : `x=Ʃ(r*P^i)`, a term `P` is the base of cycle as well a perfect root for the main number N, and `k` is the degree of the cycle `C=p^k`, where `i` varies between 1 and k, the coeffecient `r` is incremented by 1 and bounded by P-1 for any following pre-image until all coeffecients are set to r=1, so we move to the start of that cycle.
* To avoid collisions between cycles the choice of exponentiation of primes rather than their products is accurate, because as an example of two cycles of bases `3` and `2` a meetpoint between them can be `3*2`, so this is avoided since a cycle is defined by its degree more than its base , and for the meetpoint there is another cycle of base `6` and degree 1.
* Negative numbers place an exception, as for it, i reserved odd degrees for negative numbers, and even degrees for the rest. How so ?

for any number N embedded within a cycle `P^k`, is written as `P^(a0*P^i0+a1*P^i1+...)`, the amount `(a0*P^i0+a1*P^i1+...)` is transalted in P-ary base as `a0,a1,....` , to clarify this point if (p=2) the sequence must be in binary base. As is known prealably without setting the condition of positive/negative degrees and the (+/-1) exception, a number N is on the edges of a cycle of degree `k` if and only if the sequence `A` is written as `1111..{k+1}..10` or `111..{k}..1` for all bases, otherwise no rotation is needed, thus assigning negative/positive condition for a respective odd/even degrees `k/k'` for both makes an odd sequence written in the form `101..{k}..100`, an even sequence is written in the form `101..{k'}..10` for a beginning edge of a respectively negative/positive number-cycle.

**Example:**

Taking a number `N=2^10`, `x=10=2^1+2^3` , the sequence A is written `A=1010`, this type of sequence symptomizes a finite edge of positive number-cycle, which is `C=2^3`, so the next image is that of beginning edge `A=011` which is `8`, **But**, by standarizing this result to (+/-)1 exception `2^10/2` maps to `8/2` and the previous image mustnt be rotated.

Taking a number `N=-3^9`, `x=9=3^2` , the sequence A is written `A=100`, this type of sequence symptomizes a finite edge of negative number-cycle, which is `C=3^1`, so the next image is that of beginning edge `A=01` which is `3`, But, by adapting this result to negative/positive condition `-3^9` maps to `-3` .
* for the couple `(-/+)1`, i envisaged to intrude it within numbers of cycle-bases `2`, in a guise that an ordinary sequence of cyclic groups `{2,4}{8,16,32,64}..` are made up in another form `{1,2}{4,8,16,32}..`, this prevents any loss of previous elements, and the opeation done is just shifting with popping a new element in.

---

**Results:**

running this little code-sheet to verify the first reasonable ranges of cyclic numbers:

```
for (i=1:6)
index=1;if(max(factor(i))>=5) index=0;end
for ind=0:index
j=f(((-1)^ind)*i); while(((-1)^ind)*i~=j)fprintf('%d ',j);j=f(j);end,fprintf('%d \n',(-1)^ind*i),pause,end,
end

```

This leads to this results

```
 2 1
 -2 -4 -8 -1
 1 2
 -4 -8 -1 -2
 9 27 3
 -9 -27 -81 -243 -729 -2187 -6561 -19683 -3
 8 16 32 64 128 256 512 4
 -8 -1 -2 -4
 25 125 625 3125 5
 36 216 1296 7776 46656 6
 -36 -216 -1296 -7776 -46656 -279936 -1679616 -10077696 -60466176 -362797056 -2.176782e+009 -1.306069e+010 ??? Error using ==> factor at 27

```

The last one is segmentation-error but it fits the \[-127,127\] standard signed-integer range.
> 2 votes

# Answer
## Python 3, 110 bytes

*I still have not figured out how to get a lambda in there*

if n is a triangle number \[1,3,6,10,15,21,28,etc...\] then f(n) is the order in the list multiplied by negative one. if the number is negative, give it 1+the next smallest triangle number. else, increment.

Example: 5 is not a triangle number, so add 1.

Next iteration, we have 6. 6 is a triangle number, and it is the 3rd in the list, so out comes -3.

The program gives these lists

length 1:\[0\]

length 2:\[1,-1\]

length 3:\[2,3,-2\]

length 4:\[4,5,6,-3\]

length 5:\[7,8,9,10,-4\]

```
x=int(input())
if x<0:print((x**2+x)/2+1)
else:
 a=((8*x+1)**.5-1)/2
 if a%1:print(x+1)
 else:print(-a)

```

Edit: Thanks again to @TuukkaX for removing excess charcters.
> 2 votes

# Answer
## JavaScript (ES6), 73 bytes

```
f=(n,i=0,j=0,k=0,l=1,m=i<0?-i:~i)=>n-i?f(n,m,k++?j:i,k%=l,l+!k):++k-l?m:j

```

Works by enumerating the sequence (0, -1, 1, -2, 2, -3, 3, ...) until it finds `n`, counting cycles as it goes. `i` contains the current entry; `j` contains the start of the current cycle, `k` the index within the cycle, `l` the length of the current cycle and `m` the next entry in the sequence. Once we find `n` we then take `j` if we're at the end of a cycle or `m` if not.
> 0 votes

---
Tags: code-golf, math, number, permutations
---


title: The lost pawn problem

text:
# Question
Title: The lost pawn problem
# The lost pawn problem

After the chess game ended, a surviving pawn was left behind enemy lines. let's help him find the shortest way back home.

The original problem describes a nXn "chess" board, and a function `f: {1,..,n-1}X{1,..,n}X{-1,0,1} => R+` of weights. the goal is to find the best path from some square in the buttom line, to some other square in the top line, where the possible moves are: left-up,up,right-up, and you may not exit the board.

The problem is relatively easy to solve in O(n^2) using dynamic programming, but this is codegolf, and we don't care about useless stuff like running time complexity...

## The Problem

**input:** a 3-dimentional array (or some other collection of your choice, received through stdin, or as a function argument), corresponding to a regular chess board, exactly in size: 7X8X3 (#linePasses X #rowSize X #movesPerPass) containing non-negative integers. the moves cost **from** some position `(i,j)` where `i` is the row index, and `j` is the column index, are:

* `a[i][j][0]` for the cost to travel up-left to square `(i+1,j-1)`, or graphically: `\`.
* `a[i][j][1]` for the cost to travel up to square `(i+1,j)`, or graphically: `|`.
* `a[i][j][2]` for the cost to travel up-right to square `(i+1,j+1)`, or graphically: `/`.

you may assume it will not contain a path that sums greater than `MAX_INT`.

**output:** an 8X8 ascii output showing the best (shortest, i.e. minimum sum of weights) path (if there is more than 1 optimal result, you may show an arbitrary path of your choice). the path is drawn bottom to top, where in each line, the character corresponding to the pawn's position in the path, is the one it about to make. e.g. if the pawn is about to move up-left from column 3 (to column 2), the you should draw:

```
#?######
##\#####

```

where `?` should be replaced with the next move. final position needs to be drawn as `X`.

### Examples

*input:*

```
[
  [[1,1,1],[1,1,1],[0,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,0,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,1,0],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,1,1],[1,1,0],[1,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,1,1],[1,1,1],[1,0,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,1,1],[1,1,1],[1,0,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]],
  [[1,1,1],[1,1,1],[1,1,1],[0,1,1],[1,1,1],[1,1,1],[1,1,1],[1,1,1]]
]

```

*output:*

```
##X#####
###\####
###|####
###|####
##/#####
#/######
#|######
##\#####

```

*input:*

```
[
  [[41,27,38],[12,83,32],[50,53,35],[46,32,26],[55,89,82],[75,30,87],[2,11,64],[8,55,22]],
  [[56,21,0],[83,25,38],[43,75,63],[56,60,77],[68,55,89],[99,48,67],[94,30,9],[62,62,58]],
  [[23,18,40],[24,47,61],[96,45,72],[71,6,48],[75,63,98],[93,56,51],[23,31,30],[49,34,99]],
  [[20,47,42],[62,79,72],[32,28,44],[68,61,55],[62,39,57],[4,17,49],[97,85,6],[91,18,12]],
  [[51,50,11],[32,39,56],[12,82,23],[33,88,87],[60,55,22],[29,78,14],[70,11,42],[63,94,67]],
  [[75,64,60],[27,79,86],[70,72,56],[55,45,32],[95,67,12],[87,93,98],[81,36,53],[38,22,93]],
  [[31,80,50],[77,71,22],[59,46,86],[64,71,53],[41,19,95],[62,71,22],[92,80,41],[26,74,29]]
]

```

*output:*

```
######X#
#####/##
####/###
#####\##
#####|##
######\#
######|#
#######\

```

this is , so shortest code wins.

play fair. no loopholes...

## EDIT:

Iv'e written an un-golfed straight forward solution in scala you can look at. There's also a site you can play with scala code on-line: scalafiddle (just copy&paste the gist to scalafiddle, and hit the play button)

# Answer
> 5 votes
## Q: 199 Bytes

```
f:{m::x;n::{@/[+/-1 0 1_\:/:(x;m[y;;|!3]);0 2;(0W,),{x,0W}]};i:*<*|r:{&/n[x;y]}\[8#0;!7];  s:{-1+{*<x}'+n[y;z]}\[();(,8#0),-1_r;!7];j:i,{x+y x}\[i;|s];-1(@[8#"#";;:;]'[j;"X","/|\\"1+s'[|!7;-1_j]]);}

```

**NOTES**

* Q interpreter (kx.com) free for non-commertial use (versions for Windows, Linux, Mac)
* This solution uses inner core of Q (internally named k4), so we need a scripting file with k extension, or interactive interpreter in k mode (\ command at first prompt). By contrast, 'verbose' (legible) version of the language requires script with q extension, and is the default mode at interactive interpreter.

**TEST**

```
f ((1 1 1; 1 1 1; 0 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1)
   (1 1 1; 1 0 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1)
   (1 1 1; 1 1 0; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1)
   (1 1 1; 1 1 1; 1 1 0; 1 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1)
   (1 1 1; 1 1 1; 1 1 1; 1 0 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1)
   (1 1 1; 1 1 1; 1 1 1; 1 0 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1)
   (1 1 1; 1 1 1; 1 1 1; 0 1 1; 1 1 1; 1 1 1; 1 1 1; 1 1 1))

##X#####
###\####
###|####
###|####
##/#####
#/######
#|######
##\#####

f ((41 27 38; 12 83 32; 50 53 35; 46 32 26; 55 89 82; 75 30 87;  2 11 64;  8 55 22)
   (56 21  0; 83 25 38; 43 75 63; 56 60 77; 68 55 89; 99 48 67; 94 30  9; 62 62 58)
   (23 18 40; 24 47 61; 96 45 72; 71  6 48; 75 63 98; 93 56 51; 23 31 30; 49 34 99)
   (20 47 42; 62 79 72; 32 28 44; 68 61 55; 62 39 57;  4 17 49; 97 85  6; 91 18 12)
   (51 50 11; 32 39 56; 12 82 23; 33 88 87; 60 55 22; 29 78 14; 70 11 42; 63 94 67)
   (75 64 60; 27 79 86; 70 72 56; 55 45 32; 95 67 12; 87 93 98; 81 36 53; 38 22 93)
   (31 80 50; 77 71 22; 59 46 86; 64 71 53; 41 19 95; 62 71 22; 92 80 41; 26 74 29))

######X#
#####/##
####/###
#####\##
######\#
######|#
######|#
#######\

```

**EXPLANATION**

For ilustration purpose, we assume second test (matrix ((41 27 38; 12 83 32; ....)

We transform original matrix (m at code level): instead of orginimal matriz with a triplet for each coordinate, we define matrix for left, up, and right displacements. Left matrix contains 7x7 values (we drop first column), Up matrix 7x8, and right matrix 7x7 (we frop last column).

```
left                           up                         right
12 50 46 55 75 2  8       27 83 53 32 89 30 11 55     38 32 35 26 82 87 64
83 43 56 68 99 94 62      21 25 75 60 55 48 30 62     0  38 63 77 89 67 9
24 96 71 75 93 23 49      18 47 45 6  63 56 31 34     40 61 72 48 98 51 30
62 32 68 62 4  97 91      47 79 28 61 39 17 85 18     42 72 44 55 57 49 6
32 12 33 60 29 70 63      50 39 82 88 55 78 11 94     11 56 23 87 22 14 42
27 70 55 95 87 81 38      64 79 72 45 67 93 36 22     60 86 56 32 12 98 53
77 59 64 41 62 92 26      80 71 46 71 19 71 80 74     50 22 86 53 95 22 41

```

To calculate final position we need to evaluate minimum-cost path. We assume initial cost 0 0 0 0 0 0 0 0 (cost to arrive at each column of first row), and iterates with each next row. At each column i, we calculate three values:

* cost of previous i+1 value plus left\[i+1\]. We drop first component of cost (shifts and alineates columns to add) and sum component to component
* cost of previous i value plus up\[i\]. We sum component to component
* cost of previous i-1 value plus right\[i-1\]. We drop last component of cost (shifts and alineates columns to add) and sum component to component

To calculate minimum we complete left cost prepending infinite and right cost appending infinite: with 3 vectors of eight components, calculate minimum component to component. Resulting value is the base cost for new iteration

For first iteration we obtain values (0W is infinite in Q)

```
0W 12 50 46 55 75 2  8
27 83 53 32 89 30 11 55
38 32 35 26 82 87 64 0W

```

and calculates minimum of each column

```
27 12 35 26 55 30 2 8

```

After all iterations, we have the minimum cost to arrive to each square (assuming row 0 at top, 7 at bottom). We are only interested in last column, but i draw all intermediate results for ilustrative purposes

```
0   0   0   0   0   0   0   0
27  12  35  26  55  30  2   8
27  37  78  82  110 78  11  70
45  61  123 88  173 129 34  104
87  123 151 143 212 133 40  122
98  155 163 176 234 147 51  185
158 182 219 208 246 234 87  207
208 204 265 261 265 256 128 233

```

Now we found minimum value at last row (128, at column 6). That's the end of the path (X character in ouput).

We repeat cost calculation again, but now we annotate the direction from we obtain each minimum (wich of the 3 values used to calculate minimum is the selected value).

```
\|/|\///
\\\\\/|/
\\\|//|/
\\|\//|/
\\|//|\/
\\//|\|/
\|/|/|\/

```

We reverse rows, put 'X' at pos 6, and preserves only path that ends at column 6 (the others are substituted by #)

```
######X#
#####/##
####/###
#####\##
######\#
######|#
######|#
#######\

```

---
Tags: code-golf, chess
---


# Question
Title: My "keybore" is key-boring me! Help me find a minimal keystrokes
Credits to @Agawa001 for coming up with this question.

# Explanation

My new "keybore" only has 2 buttons, namely `+` and `-`.

The number in the memory starts at `0`.

Each consecutive press of `+` or `-` will increment/decrement the memory for exactly how many times it has been pressed consecutively.

Therefore, if you press `+` 4 times, first time it adds 1, the second time it adds 2, the third time it adds 3, the fourth time it adds 4, giving you `10` (ten).

Now, if you press `-` 3 times, the first time it subtracts 1, the second time 2, the third time 3, leaving you with `4` (four).

# TL;DR

Given a string of + and -, divide it at each change of character. Then each resulting string of m `+` symbols adds the m-th triangle number, and each string of n `-` symbols subtracts the n-th triangle number.

# Walk-through

Now, if you still do not understand, I will show you how `+++--+--` creates `1`.

```
Program   | Counter | Memory
----------------------------
          |  0      | 0
+         | +1      | 1
++        | +2      | 3
+++       | +3      | 6
+++-      | -1      | 5
+++--     | -2      | 3
+++--+    | +1      | 4
+++--+-   | -1      | 3
+++--+--  | -2      | 1

```

# Task

* You will take a positive integer as input, either as functional argument or from STDIN.
* Then, you will output/print the minimum number of keystrokes needed to create that number using the method above.

# Testcases

Since rearranging the `+` or `-` runs gives the same number, for each such group only the lexicographically earliest sequence is listed.

```
Input | Output | Possible corresponding sequences
-------------------------------------------------
    4 |      5 | -+++-
    6 |      3 | +++
    9 |      5 | ++++-
   11 |      7 | +++-+++
   12 |      7 | +++++--, ++++-++
   19 |      8 | -++++++-
   39 |     12 | +++++++++---
   40 |     13 | +++++++++---+, ++++++++-+++-
   45 |      9 | +++++++++
   97 |     20 | ++++++++++++++--+---, +++++++++++++-++++--, ++++++++++++-++++++-
  361 |     34 | ++++++++++++++++++++++++++-+++-+++

```

# Extra resources

# Scoring

This is . Shortest solution in bytes wins.

# Answer
# MATL, ~~43~~ 29 bytes

```
E:"@TFEqZ^!"@Y'tQ**s]vGE=a?@.

```

This is memory- and time-inefficient. The online compiler can handle up to input `45` only.

Try it online!

Here's a modified version with all test cases up to `40` (it takes almost a minute in the online compiler).

### Explanation

This tests all possible key-press sequences of each length, in order of increasing length, until a valid sequence is found.

```
E:       % Range [1 2 ... 2*N] where N is implicit input. The required sequence length is
         % less than 2*N, so this is enough
"        % For each
  @      %   Push current value: length of sequence
  TFEq   %   Push array [1 -1]
  Z^     %   Cartesian power. Gives all possible sequences of 1, -1 of that length
  !      %   Transpose. Each sequence is now a row
  "      %   For each sequence
    @    %     Push current sequence
    Y'   %     Run-length decoding: Pushes an array of values 1 and -1, and then an
         %     array of run-lengths
    tQ*  %     Duplicate, add 1, multiply. Gives twice the triangular number for each run
    *    %     Multiply element-wise by 1 or -1 to produce correct sign
    s    %     Sum of array. This is the number produced by the current sequence
  ]      %   End for
  v      %   Concatenate all numbers into an array
  GE=a   %   True if any of those numbers equals twice the input
  ?      %   If so
    @    %     Push current sequence length. This is the final result
    .    %     Break loop
         %   End if
         % End for
         % Implicit display

```
> 2 votes

# Answer
# Python 2, 119 bytes

```
def g(n,i=0,s=''):
 c=x=t=0
 for d in s:C=int(d)*2-1;t=(c==C)*t+1;c=C;x+=c*t
 return(x==n)*len(s)or g(n,i+1,bin(i)[3:])

```

Very slow brute-force approach. The third line computes the score of a string `x`; the other lines loop over all possible binary strings until one whose score equals the argument is found.

@Leaky saved three bytes!
> 2 votes

# Answer
# Pyth, 25 bytes

```
ffqyQ.as-Mc*RhdY2{s.pM./T

```

Try it online.

This is extremely inefficient, and runs out of memory for `f(n)` ≥ 11. It calculates `f(22)` = 10 in about 10 seconds on my laptop.

### Explanation

* Starting from 1, loop through numbers `T`. (`f`)
    + Generate all partitions of `T`. (`./T`)
    + Generate all permutations of those. (`.pM`)
    + Flatten the list. (`s`)
    + Uniquify the list. (`{`) This step *could* be removed, but it makes the code much faster.
    + Filter the resulting permutations of partitions: (`f`)
        - Multiply each number `d` of the partition (`*R`) by itself plus one (`hd`). This gives double the number to add/subtract to the result.
        - Chop the list to parts of length 2. (`c``2`)
        - Subtract any second number in those parts from the second number. (`-M`)
        - Sum the results. This gives double the resulting number if the partition permutation was interpreted as number of additions, then subtractions, etc.
        - Take the absolute value. (`.a`) If the result was negative, swapping the additions and subtractions gets the positive result.
        - Check if the result equals double the input. (`qyQ`) In this case the partition permutation is correct, return it.
    + If the filter returned any results, there was a solution of length `T`. Return and print `T`.
> 2 votes

# Answer
# Python, ~~105~~ 100 bytes

Uses an inefficient breadth-first search.

```
def k(n):
 m=t=l=0;h=[]
 while m-n:o=1-2*(t>0);(m,t,l),*h=h+[(m+t-o,t-o,l+1),(m+o,o,l+1)]
 return l

```
* `h` is a list used as a queue
* `m` is the value of the sequence at the head of the list
* `t` is the last number added to `m`
* `l` is the length of the sequence that generated `m`
* `o` is +/-1, the sign is opposite the sign of `t`

Edit: Leaky Nun shaved five bytes.
> 1 votes

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


title: Regex for Finding Radioactive Elements

text:
# Question
Title: Regex for Finding Radioactive Elements
Find the shortest regex that matches all radioactive elements and nothing else in the Periodic Table of Elements.

Radioactive Elements

```
'Technetium','Promethium','Polonium','Astatine','Radon','Francium','Radium','Actinium','Thorium','Protactinium','Uranium','Neptunium','Plutonium','Americium','Curium','Berkelium','Californium','Einsteinium','Fermium','Mendelevium','Nobelium','Lawrencium','Rutherfordium','Dubnium','Seaborgium','Bohrium','Hassium','Meitnerium','Darmstadtium','Roentgenium','Copernicium','Ununtrium','Flerovium','Ununpentium','Livermorium','Ununseptium','Ununoctium'

```

Non-radioactive Elements

```
'Hydrogen','Helium','Lithium','Beryllium','Boron','Carbon','Nitrogen','Oxygen','Fluorine','Neon','Sodium','Magnesium','Aluminium','Silicon','Phosphorus','Sulphur','Chlorine','Argon','Potassium','Calcium','Scandium','Titanium','Vanadium','Chromium','Manganese','Iron','Cobalt','Nickel','Copper','Zinc','Gallium','Germanium','Arsenic','Selenium','Bromine','Krypton','Rubidium','Strontium','Yttrium','Zirconium','Niobium','Molybdenum','Ruthenium','Rhodium','Palladium','Silver','Cadmium','Indium','Tin','Antimony','Tellurium','Iodine','Xenon','Caesium','Barium','Lanthanum','Cerium','Praseodymium','Neodymium','Samarium','Europium','Gadolinium','Terbium','Dysprosium','Holmium','Erbium','Thulium','Ytterbium','Lutetium','Hafnium','Tantalum','Tungsten','Rhenium','Osmium','Iridium','Platinum','Gold','Mercury','Thallium','Lead','Bismuth'

```
* Scored by character count in the regex.
* Use standard Perl regex (just no specialized functions).
* Assume all lower case.
* You only need to count the characters of the regex itself.

Note if you used a program to get you started and maybe post how well it did. I'll post my best attempt as an answer to get started/show an example.

# Answer
### Char count 59

```
e.+[hktv]|oh?r.+m|p...?o|r.*ci|be?.i|^c?u|rad|sta|has|ct|fe

```

Found via a mix of manually selecting good parts and running Peter Norvig's golfer on the remaining items.

Regex101 link
> 3 votes

# Answer
**Char Count 61**

```
lon|ct|oh|^ra|...t.+i|^c?u|or.+u|r.+c.|e..+e|f.?e|^h?as|be*.i

```

~~One~~ 3 characters better than accepted answer!

63-character solution found with Peter Norvig's Regex golf solver. 61-character improvement found by a personal rewrite of that program in Go.
> 10 votes

# Answer
**Char count 64**

```
^(c?u|ra|no)|e.[kht]|[^l][gecv]i|[^c]oh?[rn]iu|f.r|ac|sta|bn|has

```

Should note, used parts of qw3n solution to reduce down my solution. Also used Peter Taylor's suggestion to trim two characters.
> 4 votes

# Answer
**Char count 69**

```
^u|e.[kht]|[^l][gecv]i|[^c]oh?[rn]iu|^cu|f[oe]|a[cds]t|has|nob|rad|du

```

Curium/Cerium are a pain to deal with
> 3 votes

---
Tags: code-golf, regular-expression
---


title: Toggle a string

text:
# Question
Title: Toggle a string
> The challenge involve simply toggling a string within another string.

## Explanation

If the **toggle string** is a substring of the **main string**, remove all instances of the **toggle string** from the **main string**; otherwise, append the **toggle string** at the end of the **main string**.

## Rules

* All string are composed of printable ASCII characters
* The function should take two parameters: the **main string** and the **toggle string**.
* The **main string** can be empty.
* The **toggle string** cannot be empty.
* The result should be a string, which can be empty.
* The shortest answer wins.

## Examples

```
function toggle(main_string, toggle_string){ ... }

toggle('this string has 6 words ', 'now')
=> 'this string has 6 words now'

toggle('this string has 5 words now', ' now')
=> 'this string has 5 words'

```

## Tests cases

```
'','a'          => 'a'
'a','a'         => ''

'b','a'         => 'ba'
'ab','a'        => 'b'

'aba','a'       => 'b'
'ababa', 'aba'  => 'ba'

```

# Answer
# Jelly, 7 bytes

```
œṣȮ⁸e⁹ẋ

```

Try it online!

### How it works

```
œṣȮ⁸e⁹ẋ  Main link. Arguments: s (string), t (toggle string)

œṣ       Split s at occurrences of t.
  Ȯ      Print the result.
   ⁸e    Check if s occurs in the split s. Yields 1 (true) or 0 (false).
     ⁹ẋ  Repeat t that many times.

```
> 5 votes

# Answer
# Java 8, ~~80~~ ~~70~~ ~~65~~ 34 bytes

```
t->m->m==(m=m.replace(t,""))?m+t:m

```

Probably my shortest Java 'codegolf' so far.. xD
with some help from the comments.. ;)

**Explanation:**

Try it online.

```
t->m->                     // Method with two String parameters and String return-type
                           // (NOTE: Takes the toggle `t` and main `m` in reversed order)
  m==(m=m.replace(t,""))?  //  If `m` equals `m` with all `t`-substrings removed:
                           //  (And set `m` to `m` with all `t`-substrings removed)
   m+t                     //   Output this new `m` concatted with `t`
  :                        //  Else:
   m                       //   Output just this new `m`

```
> 11 votes

# Answer
# MATL, 11 bytes

```
yyXf?''YX}h

```

Try it Online!

All test cases

**Explanation**

```
            % Implicitly grab the main string
            % Implicitly grab the toggle string
y           % Copy the main string
y           % Copy the toggle string
Xf          % Check to see if the toggle string is present in the main string
?           % If so
    ''YX    % Replace with an empty string
}           % else
    h       % Horizontally concatenate the two strings
            % Implicit end of if...else
            % Implicitly display the result

```
> 8 votes

# Answer
# Python 3, 38 bytes

```
lambda s,t:(s+t,s.replace(t,""))[t in s]

```
> 6 votes

# Answer
## JavaScript (ES6), ~~39~~ 37 bytes

```
(s,t,u=s.split(t).join``)=>u==s?s+t:u

```
> 4 votes

# Answer
## Pyke, 14 bytes

```
DX{iIXRk:)i!IJ

```

Try it here!

Given that Pyke has no `else` structure, I think this is pretty reasonable score

Explanation:

```
D              -    Duplicate input
 X             -   a,b = ^
  {            -  a in b
   i           - i = ^
    I          - if i:
     XRk:      -  a = b.replace(a,"")
         i!I   - if not i:
            J  -  a = "".join(input)
               - print a

```
> 3 votes

# Answer
# CJam, 9

```
q~:B/2Be]

```

Try it online. Thanks jimmy23013 for chopping off 1 byte :)

**Explanation:**

```
q~     read and evaluate the input (given as 2 quoted strings)
:B     store the toggle string in B
/      split the main string by the toggle string
2Be]   pad the array of pieces to the right with B, up to length 2 (if shorter)

```
> 3 votes

# Answer
# Pyth, ~~13~~ ~~11~~ 10 bytes

```
?/Qz:Qzk+z

```

Test suite.

Input format: first string in quotes, second string without quotes.

### This is also 10 bytes:

```
?tJcQzsJ+z

```

Test suite.

### This is 11 bytes:

```
pscQz*!}zQz

```

Test suite.

### Previous 13-byte solution:

```
?:IQzk+Qz:Qzk

```

Test suite.
> 2 votes

# Answer
# Javascript (ECMAScript 6): 47 bytes

```
(a,b)=>(c=a.replace(RegExp(b,'g'),''))!=a?c:a+b

```
> 2 votes

# Answer
## Retina, ~~38~~ 31 bytes

Byte count assumes ISO 8859-1 encoding.

```
(.+)(?=.*¶\1$)
·
1>`·|¶.+

T`·¶

```

The trailing linefeed is significant. Input format is both strings separated with a linefeed.

Try it online! The first line allows running several test cases at once (for the test suite, use `;` to separate the strings and linefeeds to separate test cases; the first line takes care of the conversion).

### Explanation

```
(.+)(?=.*¶\1$)
·

```

In this first step we replace all occurrences of the toggle string in the main string with `·`. We need to insert these markers so that we can determine afterwards if any substitution happened.

```
1>`·|¶.+

```

This is another substitution which removes a `·` marker, or the second line (including the separating linefeed). However, the `1>` is a limit which means that only matches *after* the first are considered. Hence, if the toggle string did not occur in the main string, we won't have inserted any `·`, so the second line will be the first match and won't be removed. Otherwise, we remove the second line along with all but the first marker.

```
T`·¶

```

While this uses a transliteration stage, it's also used simply for removing characters. In particular, we move both `·` and linefeeds. We need the first one, in case there was a match (because then the first `·` will have been left behind by the previous stage) and we need the second one in case there wasn't a match (to join the two lines together and thereby append the toggle string to the main string).
> 2 votes

# Answer
# Python (3.4): ~~55~~ ~~54~~ ~~47~~ 44 Bytes

```
lambda m,t:m.replace(t,'')if t in m else m+t

```

Testing:

```
toggle=lambda m,t:m.replace(t,'')if t in m else m+t
print('', 'a', toggle('','a'))
print('a', 'a', toggle('a','a'))
print('b', 'a', toggle('b','a'))
print('ab', 'a', toggle('ab','a'))
print('aba', 'a', toggle('aba','a'))
print('ababa', 'aba', toggle('ababa','aba'))

```

The Test output

```
 a a
a a
b a ba
ab a b
aba a b
ababa aba ba

```

~~Using a def would be longer because you have to use a return statement, if it were possible without return it would save 2 Bytes~~ Since explicit declaration of the function is not needed (sorry I didn't know that) 7 Bytes were saved.
> 2 votes

# Answer
# Scala, 72 70 bytes

```
def x(m:String,s:String)={val r=m.replaceAll(s,"");if(r==m)m+s else r}

```

Online interpreter: www.tryscala.com
> 2 votes

# Answer
# C#, 63

```
string F(string s,string t)=>s.Contains(t)?s.Replace(t,""):s+t;

```

Better than Java :)

Test code:

```
public static void Main()
{
    Console.WriteLine(F("", "a"));
    Console.WriteLine(F("a", "a"));
    Console.WriteLine(F("b", "a"));
    Console.WriteLine(F("ab", "a"));
    Console.WriteLine(F("aba", "a"));
    Console.WriteLine(F("ababa", "aba"));
    Console.ReadLine();
}

```

Output:

```
a

ba
b
b
ba

```
> 2 votes

# Answer
# Jolf, 12 bytes

```
?=iγρiIE+iIγ

```

Or, if we must include regex-sensitive chars:

```
?=iγρiLeIE+iIγ

```

Try it here!

## Explanation

```
?=iγρiIE+iIγ    if(i === (γ = i.replace(I, E))) alert(i + I); else alert(γ);
  i                i
 =                   ===
    ρ                          .replace( ,  )
     iI                       i         I
       E                                   E
   γ                     (γ =                )
?               if(                           )
        +iI                                     alert(i + I);
                                                              else
           γ                                                       alert(γ);

```
> 2 votes

# Answer
# JavaScript (ES6), 37 Bytes

```
(m,t)=>(w=m.split(t).join``)==m?m+t:w

```

Slightly shorter than @nobe4 's answer by taking advantage of split and join
> 2 votes

# Answer
# Racket, 70 bytes

Pretty straight forward.

```
(λ(s t)((if(string-contains? s t)string-replace string-append)s t""))

```
> 2 votes

# Answer
# Oracle SQL 11.2, 66 bytes

```
SELECT DECODE(:1,s,s||:2,s)FROM(SELECT REPLACE(:1,:2)s FROM DUAL);

```
> 1 votes

# Answer
# Ruby, ~~35~~ ~~37~~ 28 bytes

```
->m,t{m[t]?m.gsub(t,''):m+t}

```

Hooray for string interpolation! It even works in regexes. The rest is simple: if the string in `t` matches to `m`, replace `t` with `''`, else return `m+t`.

**Edit:** Fixed a bug.

**Edit:** I applied Kevin Lau's suggestion, but it appears that I have reached the same algorithm as the one used in Luis Masuelli's answer.
> 1 votes

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

```
s|t=(r=replace(s,t,""))t^(s==r)

```

Try it online!
> 1 votes

# Answer
# Ruby, ~~33 bytes~~ ~~27 bytes (28 if using global subtitution)~~ definitely 28 bytes

```
->u,v{u[v]?u.gsub(v,''):u+v}

```
> 1 votes

# Answer
# Perl, ~~37~~ 30 bytes

```
{$_=shift;s/\Q@_//g?$_:"$_@_"}

```

Regular expressions inside the toggle string are not evaluate because of the quoting with `\Q`...`\E`.

`sub F` and `\E` are removed according to the comment by msh210.

It is not entirely free of side effects because of setting `$_`. Using a local variable will cost six additional bytes:

```
{my$a=shift;$a=~s/\Q@_//g?$a:"$a@_"}

```

On the other hand, with switched input parameters two bytes can be saved by using `pop` instead of `shift` (28 bytes):

```
{$_=pop;s/\Q@_//g?$_:"$_@_"}

```

Test file:

```
#!/usr/bin/env perl

sub F{$_=shift;s/\Q@_//g?$_:"$_@_"}

sub test ($$$) {
  my ($m, $t, $r) = @_;
  my $result = F($m, $t);
  print "F('$m', '$t') -> '$result' ",
    ($result eq $r ? '=OK=' : '<ERROR>'), " '$r'\n";
}
test '', 'a', 'a';
test 'a', 'a', '';
test 'b', 'a', 'ba';
test 'ab', 'a', 'b';
test 'aba', 'a', 'b';
test 'ababa', 'aba', 'ba';
test 'ababa', 'a*', 'ababaa*';
test 'foobar', '.', 'foobar.';
__END__

```

Test result:

```
F('', 'a') -> 'a' =OK= 'a'
F('a', 'a') -> '' =OK= ''
F('b', 'a') -> 'ba' =OK= 'ba'
F('ab', 'a') -> 'b' =OK= 'b'
F('aba', 'a') -> 'b' =OK= 'b'
F('ababa', 'aba') -> 'ba' =OK= 'ba'
F('ababa', 'a*') -> 'ababaa*' =OK= 'ababaa*'
F('foobar', '.') -> 'foobar.' =OK= 'foobar.'

```
> 1 votes

# Answer
# C# (58 bytes)

`string F(string s,string t)=>s==(s=s.Replace(t,""))?s+t:s;`

It uses an inline assignment to shave a few bytes off
> 1 votes

# Answer
# bash + sed, 28 bytes

```
sed "s/$2//g;t;s/$/$2/"<<<$1

```

The script lives in a toggle-string.bash file, which we call with `bash toggle-string.bash mainstring togglestring`.

`s/$2//g` removes the toggle string from the main string

`t` jumps to the end if the previous substitution was successful (ie. the main string contained the toggle string)

`/$/$2/` adds the toggle string at the end (`$`), if we didn't jump to the end

bash is required for the herestring
> 1 votes

# Answer
## PowerShell v2+, 47 bytes

```
param($a,$b)(($c=$a-replace$b),"$a$b")[$c-eq$a]

```

Takes input `$a,$b` and then uses a pseudo-ternary `(... , ...)[...]` statement to perform an if/else. The inner parts are evaluated first to form an array of two elements. The 0th is `$a` with all occurrences of `$b` `-replace`d with nothing, which is stored into `$c`. The 1st is just a string concatenation of `$a` and `$b`.

If `$c` is `-eq`ual to `$a`, meaning that `$b` wasn't found, that's Boolean `$true` or `1`, and so the 1st element of the array (the concatenation) is chosen. Else, it's Boolean `$false`, so we output `$c`, the 0th element.

Note that `-replace` is greedy, so it will replace from the left first, meaning the `ababa / aba` test case will properly return `ba`.
> 0 votes

# Answer
# Java 8, 65 bytes

```
BinaryOperator<String>l=(m,t)->m.contains(t)?m.replace(t,""):m+t;

```

The same logic as the Java 7 solution, written with a lambda.

Try it here
> 0 votes

# Answer
**TSQL, 143 129 121 Bytes**

```
DECLARE @1 VARCHAR(10)='',@2 VARCHAR(10)='a'SELECT CASE WHEN @1 LIKE'%'+@2+'%'THEN REPLACE(@1,@2,'')ELSE CONCAT(@1,@2)END

```

Readable:

```
   DECLARE @1 VARCHAR(10) = ''
    , @2 VARCHAR(10) = 'a'

SELECT CASE WHEN @1 LIKE '%' + @2 + '%'
            THEN REPLACE(@1, @2, '')
            ELSE CONCAT (@1, @2)
            END

```

`**`Live Demo`**`

**114 Bytes** with strictly 1 character input

```
DECLARE @1 CHAR(1) = 'a'
    , @2 CHAR(1) = '.'

SELECT CASE WHEN @1 LIKE '%' + @2 + '%'
            THEN REPLACE(@1, @2, '')
            ELSE CONCAT (@1, @2) END

```
> 0 votes

# Answer
# Mathematica, 45 bytes

```
If[StringContainsQ@##,StringDelete@##,#<>#2]&

```

Anonymous function that takes the main string and the toggle string (in that order) and returns the result. Explanation:

```
                                            &  Anonymous function returning...

If[StringContainsQ@##,               ,     ]    if its first argument contains
                                                its second argument, then...
                      StringDelete@##            its first argument with its
                                                 second argument removed, else...
                                      #<>#2      its second argument appended to
                                                 its first argument.

```
> 0 votes

# Answer
# TSQL(Sqlserver 2012), 49 bytes

```
DECLARE @ VARCHAR(10) = 'hello',@x VARCHAR(10) = 'o'

PRINT IIF(@ LIKE'%'+@x+'%',REPLACE(@,@x,''),@+@x)

```

Try it online!
> 0 votes

# Answer
# k (23 bytes)

```
{$[#x ss y;,/y\:x;x,y]}

```

Examples:

```
k){$[#x ss y;,/y\:x;x,y]}["aba";"a"]
,"b"
k){$[#x ss y;,/y\:x;x,y]}["this string has 6 words ";"now"]
"this string has 6 words now"
k){$[#x ss y;,/y\:x;x,y]}["this string has 5 words now";"now"]
"this string has 5 words "
k){$[#x ss y;,/y\:x;x,y]}["ababa";"ba"]
,"a"
k){$[#x ss y;,/y\:x;x,y]}["";"a"]
,"a"

```
> 0 votes

# Answer
## Kotlin, 61 Bytes

```
{m:String,t:String->var n=m.replace(t,"");if(m==n)m+t else n}

```

This is would be shorter if assignment was an expression in Kotlin,and parameters were mutable,and there was a ternary conditional operator, sadly this isn't the case :(

Try it Online!

### UnGolfed

```
fun t(m:String, t:String):String{
    var n=m.replace(t, "")
    return if(m==n)m+t else n
}

```
> 0 votes

# Answer
# Rust, 84 bytes

```
fn toggle(a:&str,b:&str)->String{let mut r=a.replace(b,"");if&r==a{r.push_str(b)}r}

```

Try it on play.rust-lang.org.
> 0 votes

# Answer
# PHP 65

```
function f($s,$v){return($m=str_replace($v,'',$s))==$s?$s.$v:$m;}

```

Inspired from Kevin Cruijssen's java example.
> 0 votes

# Answer
# PHP, 73 chars

`<?$s=$argv[1];$t=$argv[2];echo!strpos($s,$t)?$s.$t:str_replace($t,'',$s);`

Longer than the other php answer, but uninspired and fully working as a standalone in the console.
> 0 votes

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


title: Collide against walls

text:
# Question
Title: Collide against walls
## Statement

Given an input like this `35 15 0 0 10` that matches the following constrains:

* `Width` in characters of the grid (5-50)
* `Height` in characters of the grid (5-25)
* Initial `X` position of the ball (0-(`Width`-1)
* Initial `Y` position of the ball (0-(`Height`-1)
* Number of movements to simulate

Generate a grid that shows the trajectory of the ball, knowing it's direction is initially `DR` (down-right) and that colliding with a wall will reverse the increment being applied to that axis. In other words, if we are going `DR` and hit the bottom we will now be going `UR` until we collide again.

The trajectory is not affected by passing twice over the same point since it's not the game snake, it's the trajectory of an object in 2d.

The input will be a string such as the one above and the output should be similar to this, not caring about which characters represent the wall, trajectory or ball, as long as they're consistent.

### Points

Your score is the length of your submission, in characters.

### Winners by language

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

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

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

# Answer
# MATL, ~~35~~ 34 characters

```
Z"42Gi:qi!+lGqE!/tYo-KM!*|QYoZ}X](

```

**Try it online!**

### Explanation

This takes care of the reflections using the formulas

```
nx = 2*(Nx-1)
px = abs(t/nx-round(t/nx))*nx

```

where `t` is a time variable that increases in steps of `1`, `Nx` is the maximum size along the `x` direction and `px` is the computed `x` position. Analogous formulas are used for the `y` coordinate.

A char matrix of spaces is initially created, and then it is filled with character `*` at the computed `x` and `y` positions.

```
Z"     % Implicitly take [width height]. Push char matrix of spaces with that size
42     % Push 42. ASCII for character `*`
G      % Push first input again, that is, [width height]
i      % Take number of movements, M
:q     % Range [0 1 ... M-1]
i!     % Take initial position [x y]. Transpose into column vector
+      % Add element-wise with broadcast. Gives 2-row vector
lG     % Push first input, [width height]
qE!    % Transform into column vector [2*width-2; 2*height-2]
/      % Divide element-wise with broadcast
tYo    % Duplicate. Round to closest integer
-      % Subtract
KM!    % Push [2*width-2; 2*height-2] again
*      % Multiply element-wise with broadcast
|      % Absolute value
Q      % Add 1
Yo     % Round to closest integer
Z}     % Separate 2-row array into two row arrays. These contain row and column
       % indices, respectively, of the ball positions
X]     % Convert row and colummn indices to linear index
(      % Assign 42 to those positions of the matrix of spaces

```
> 4 votes

# Answer
## Python 180 ~~172~~ ~~171~~ ~~163~~ 145 Bytes

### (-2 Bytes with Python3)

```
def r(m,n,x,y,t):
 s=([' ']*m+['\n'])*n;a=b=1
 for c in'o'*(t-1)+'x':s[x+y*m+y],x,y=c,x+a,y+b;a*=2*(0<x<m-1)-1;b*=2*(0<y<n-1)-1
 print''.join(s)

```

To save 2 more bytes with Python3 (thanks to shooqie) replace second line with

```
 s=[*' '*m,'\n']*n

```

Had to use a list of characters because python does not support string item assignement. The `x+y*m+y` part is from `x+y*(m+1)` because of the '\n' add each line end

Edit1: right after posting, saw how to get rid of the overwriting 'x'

Edit2: space after print

Edit3: using `<` and `>` instead `==`, also tabs for 2nd indentation

Edit4: Replaced the if statements with assignements, daisy-chaining less-than and placing the loop in one line (thanks to RootTwo)
> 2 votes

# Answer
# JavaScript, ~~293~~ 279

Nothing too clever going on here.

EDIT: Saved 14 characters by initialising the 2D array differently.

```
p=prompt().split(' ')
a=[];for(i=0;i++<p[1];)a.push(new Array(~~p[0]).fill(' '))
x=~~p[2];y=~~p[3]
d=e=1
for(i=0;i++<p[4];){a[y][x]=i==p[4]?'x':'o'
if(x<1&&d<0||x>p[0]-2&&d>0)d*=-1
if(y<1&&e<0||y>p[1]-2&&e>0)e*=-1
x+=d;y+=e}o=''
for(i=0;i++<p[1];)o+=a[i-1].join('')+'\n'
alert(o)
```
> 1 votes

# Answer
# R, 156 bytes/chars

As an unnamed function. It's quite long but I quite like the method. There's probably a better way to do the 1 to w to 1 vector.

```
function(w,h,x,y,i)cat(c(' ','o')[1:(w*h)%in%(rep(c(c(1:w),c((w-1):2)),i)[x:((i=i-1)+x)+1]+(rep(c(c(1:h),c((h-1):2)),i)*w-w)[y:(i+y)+1])*1+1],fill=w,sep='')

```

Brief explanation of function internals

```
cat(                                                 # output to STDOUT
  c(' ','o')                                         # vector of characters
    [1:(w*h)%in%(                                    # number of characters in the board
      rep(c(c(1:w),c((w-1):2)),i)[x:((i=i-1)+x)+1]+  # oscillating vector of x to w to 1 to x
      (rep(c(c(1:h),c((h-1):2)),i)*w-w)[y:(i+y)+1]   # similar to above but in steps of w
    *1+1]                                            # cause a vector of 1 or 2 to pick char
  ,fill=w,sep='')                                    # print width of w, no separator

```

Like the other current answers this doesn't output the border, but I will add one if required.
> 1 votes

# Answer
# Javascript ES6 ~~202~~ ~~181~~ 177 chars

```
(w,h,x,y,s)=>(a=(r=Array)(h).fill().map(_=>r(w).fill` `),eval("for(vx=vy=1;s--;x+=vx,y+=vy,a){a[y][x]=0;if(!x||x==w-1)vx*=-1;if(!y||y==h-1)vy*=-1;}"),a.map(r=>r.join``).join`
`)

```

~~Not very golfed, I take a another look at it once I get home.~~
> 1 votes

# Answer
## C++11, 355 Bytes

Takes input string as command line arguments

```
#include <iostream>
#define A(n,i) int n=atoi(a[i]);
int main(int,char**a) {
A(w,1)A(h,2)A(x,3)A(y,4)A(n,5)
int d=1,r=1;
auto b=new int64_t[h];
while(--n>1){
b[y]|=1<<x;
if(r)x++;else x--;
if(d)y++;else y--;
if(x==0||x==w-1)r=!r;
if(y==0||y==h-1)d=!d;
}
for(int i=0;i<h;++i){
for(int j=0;j<w;++j){
std::cout<<(x==j&&y==i?'x':b[i]&(1<<j)?'o':' ');
}
std::cout<<'\n';
}
}

```

Don't worry about the newlines, they are already removed from the count.

Storing the rows as 64-Bit integer is okay since maximum width is 50.
> 1 votes

# Answer
## Q, 94 Bytes (kx.com)

`{[w;h;i;j;n]./[(1+h,w)#" ";+{z#y_+\0,-1 1@{x=2*_x%2}'&(-_-(z+y)%x)#x}.'(h,j,n;w,i,n);:;"*"]}.`

Defines a lambda with parameters w (width), h (height), i (initial x), j (initial y), and n (number of movements).

Lambda is delimited with `{}`

Final `.` (after `}`) allows to use a sequence as argument. Standard function invocation is `f[arg;arg;..;arg]`, but we can also invoque as `f . sequence`. An integer sequence is `v v .. v`, so we can invoque as `f . w h i j n`. If we define `f:{..}.` we can invoque as `f w h i j n` (as required by the question)

Solution uses 'K mode' of Q. K is the functional inner core of Q (Q is more readable, verbose and with a lot of additional libraries, but K is compact). To execute in K mode we must use scripts with k extension (vs q extension for q mode). Interactive interpreter starts in Q mode (-\> q) prompt). We can load code from k script, and execute test directly on interactive interpreter (even in q mode, as shown in test). There is also a k mode at interactive interpreter level, but it's not worth in this case.

**TEST**

NOTE.- to avoid display cluttering, we assume f name associated to lambda (f:{..}.)

```
q)f 35 15 0 0 49
"*                             *     "
" *                           * *    "
"  *                         *   *   "
"   *                       *     *  "
"    *                     *       * "
"     *                   *         *"
"      *                 *         * "
"       *               *         *  "
"        *             *         *   "
"         *           *         *    "
"          *         *         *     "
"           *       *         *      "
"            *     *   *     *       "
"             *   *     *   *        "
"              * *       * *         "
"               *         *          "
q)f 35 15 4 2 49
"                                *   "
"                               * *  "
"    *                         *   * "
"     *                       *     *"
"      *                     *     * "
"       *                   *     *  "
"        *                 *     *   "
"         *               *     *    "
"          *             *     *     "
"           *           *     *      "
"            *     *   *     *       "
"             *     * *     *        "
"              *     *     *         "
"               *   * *   *          "
"                * *   * *           "
"                 *     *            "

```

**EXPLANATION**

We define a lambda for 1D movement that accepts args \[max;init;n\] (legal positions 0..max-1, initial pos init, n movements) and returns a sequence of positions (after computing rebounds). Later apply that lambda to y and x axes (with args \[h;j;n\] and \[w;i;n\] respectively).

* Initially assume starting at 0 pos. We calculate number of rebounds to accomplish n movements, and generate a sequence with repeated increasing numbers (0 0 ...0; 1 1 .. 1; 2 2 .. 2; ..).
* Each subsequence has w items, so there are rebounds just between subsequences. For each number determine if is even, and sustitutes even results by 1 and even results by -1. (1 1 .. 1; -1 -1 .. -1; 1 1 .. 1; ..)
* We join subsequences and calculate accumulated sums starting with 0 -\> 0 1 2 3 .. 35 34 33 32 .. 0 1 2 ..
* finally we drop starting i movements and take exactly n movements

Last, we define a (h x w) char matrix filled with blanks, and for each position (resulting of applying 1D lambda on y and x) we replace character with "\*"
> 0 votes

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


title: Stack Exchanging

text:
# Question
Title: Stack Exchanging
# Problem

Say you have N stacks named S1 through SN, where each Sk (k = 1 to N) contains N copies of the number k.

For example, when N = 3 the stacks looks like this:

```
1  2  3  <- top of stack
1  2  3
1  2  3  <- bottom of stack
=======
1  2  3  <- stack index

```

Here there are 3 stacks indexed as 1, 2, and 3, and each one contains N instances of its own index.

The goal is to rearrange the N stacks such that each of them identically contains the numbers 1 through N in order from top to bottom.

e.g. for N = 3 the goal is to rearrange the stacks into:

```
1  1  1
2  2  2
3  3  3
=======
1  2  3

```

The only action you can perform with the stacks is **taking the top number from one of the stacks (popping) then immediately placing it on top of a different stack (pushing)**. This is subject to these stipulations:

* **A number can only be pushed onto a stack if it is less than or equal to the top number on that stack.**

+ e.g. a `1` can be pushed onto a stack with a `1`, `2`, or `3` at the top, but a `2` can only be pushed onto a stack with a `2` or `3` (or higher) at the top.
    + This has the effect that stacks are always monotonically increasing from top to bottom.
* Any nonempty stack may be popped from, and, assuming the previous bullet is satisfied, any stack may be pushed to.
* Any number may be pushed onto an empty stack.
* Stacks have no maximum height limit.
* Stacks cannot be created or destroyed, there are always N of them.

This challenge is about deciding which pops and pushes to do in order to complete the stack exchange, not necessarily in the fewest moves, but in a surefire way.

(Practicing with a deck of cards is a good way to get a feel for the problem.)

# Challenge

Write a program or function that takes in a positive integer N, guaranteed to be 3 or above. Print or return a string that denotes all the pop-push actions required to rearrange the stacks from the initial state:

```
1  2  3  4  5
1  2  3  4  5
1  2  3  4  5
1  2  3  4  5
1  2  3  4  5
=============
1  2  3  4  5

```

(N = 5 case)

To the final state:

```
1  1  1  1  1
2  2  2  2  2
3  3  3  3  3
4  4  4  4  4
5  5  5  5  5
=============
1  2  3  4  5

```

Every line in your output must contain two numbers separated by a space. The first number is the index of the stack to pop from and the second number is the index of the stack to push to. Performing the actions of all the lines in order should arrange the stacks correctly without breaking any rules.

For example, here is a potential valid output for the N = 3 case:

```
1 2  [move the top number on stack 1 to the top of stack 2]
1 2  [repeat]
1 2  [repeat]
3 1  [move the top number on stack 3 to the top of stack 1]
2 3  [etc.]
2 3
2 3
2 1
2 1
2 1
3 1
3 1
3 1
3 2
1 2
1 2
1 2
1 3
2 3
2 3
2 3
1 2
3 2
3 1

```

### Notes

* **Your output does *not* need to be optimal**, only correct. i.e. you do not need to minimize the number of pops and pushes.

+ So it would be alright if, say, some move were repeatedly made and immediately reversed.
    + Popping and pushing to the same stack in one move, e.g. `2 2`, is allowed as well (though of course pointless).
* Your output *does* need to be deterministic and finite.
* Remember that stacks have 1-based indexing. 0-based indexing is not allowed.
* N greater than 9 should of course work just as well as single digit N.
* If desired you may use any two distinct, non-digit printable ASCII characters in place of spaces and newlines. A trailing newline (or newline substitute) in the output is fine.

# Scoring

The shortest code in bytes wins. Tiebreaker is higher voted answer.

Valueless brownie points if you can show your algorithm is optimal.

# Answer
# Pyth ~~96~~ 94 bytes

```
Mt*Q+++bGdHM|%+y_GHQQg1 2++Qd1g2 3g2 1g3 1++Qd2Vr3QgNtN++QdN;g1QVStQVStQI<NHgnNHnNtH)++nN0dnNH

```

Try it here

## How does it work?

This explanation will be using N=5.

### Part 1: Create the bottom layer on every stack

The reason why this is needs a separate piece of code is because every stack needs to be used: the first 4 need a 5 to be put beneath them, and the last stack must provide the 5s. This means that we can't just move all the 4s somewhere, put a 5 there, and move the 4s back.

Visualization: (parentheses mean what will be moved)

```
     _
11111 |
22222 |_ Can't move 4s here, not monotonically increasing
33333_|
(44444)------------??? Where to put the 4s?
55555 <- Must supply the 5 that will be moved

```

Instead, to do this first exchange, we will first move all the 1s over to to the second stack, move a 5 to the first stack (which is now empty), move the 1s to the third stack, move the 2s to the first stack, move the 1s back to the first stack, and finally move a 5 to the second stack.

```
(11111)-----.
2222211111<-'
===============================
5<---------.
2222211111 : (from stack 5)
===============================
5
22222(11111)-.
3333311111<--'
===============================
522222<-.
(22222)-'
3333311111
===============================
52222211111<-.
             |
33333(11111)-'
===============================
52222211111
5<-----.
33333  |
44444  |
555(5)-'

```

Now that we have a free space to move stacks into (stack 2, which only contains a 5 that is placed in the right spot), we can move all the 3s to stack 2 and place a 5 in stack 3. We can then repeat the same thing for stack 4, and now we get all the 5s in the right place! And just one more thing: we will move all the 1s to stack 5 so that we get a nice setup for the next stack exchange.

```
522222(11111)-.
533333        |
544444        |
5             |
511111<-------'

```

## Part 2: Do everything else :)

This is much easier now, because now we will always have a free stack to move other numbers we need to juggle around into. So, first we figure out where the 4 is. A bit of examination will show that it will always be 1 up from where it started, or 2 above the last stack. Now, we just keep going down the stacks, placing a 4 in the stack if it's free, or moving the other numbers up 1 stack if it's not. Now we have all the 4s in place.

```
522222<------.
533333<----. |
544444-.-.-'-'
5<-----' |
511111<--'
===============================
5433333
54
54
5411111
5422222

```

Now, we realize that the 3s are 2 stacks above where the 4s where. This means that we can do the exact same thing we did with the 4s! And as it turns out, we can keep doing this as long as we wrap the stack index around to the other side.

```
5433333-'wrap around 543
54                   543
54                   54311111
5411111 .----------->54322222
5422222 |2 stacks up 543

```

And so, we can keep doing this until we have exchanged all the stacks.

## Code explanation:

### First of all: The (important) predefined variables.

```
Q: Evaluated input.
b: The newline character, '\n'
d: A space, ' '

```

### There are 2 lambda definitions.

```
M           | g(G)(H), used for moving Q numbers at a time.
            | We will call these Q numbers a "(number) block"
 t          | Tail, used to remove beginning newline
  *Q        | Repeat the following Q times
    +++bGdH | '\n' + G + ' ' + H. Just a whole bunch of concatenating.
            |
M           | n(G)(H), used for figuring out which stacks to move from
 |       Q  | If the following code is 0 (false), then use Q instead
  %     Q   | Mod Q
   +   H    | Add H
    y       | Multiply by 2
     _G     | Negate (remember in the explanation part 2? Always 2 stacks above?)

```

### The stack exchanging: part 1

```
g1 2                       | Move the 1 block to stack 2
    ++Qd1                  | Move a Q to stack 1
         g2 3              | Move the 1 block to stack 3
             g2 1          | Move the 2 block to stack 1
                 g3 1      | Move the 1 block back to stack 1
                     ++Qd2 | Move a Q to stack 2
 v---Code-continuation---' |I don't have enough room!!!
Vr3Q                       | For N in range(3, Q)
    gNtN                   | Move the number block in stack N up 1
        ++QdN              | Move a Q to stack N
             ;g1Q          | End for loop; move the 1 block to the last stack

```

### The stack exchanging: part 2

```
VStQ                           | For N in [1, 2, ..., Q - 1]
    VStQ                       | For H in [1, 2, ..., Q - 1]
        I<NH                   | If N < H
            g                  | Number block move
             nNH               |  (find number block)
                nNtH           |  (find the previous stack)
                    )          | End "For H"
                     ++nN0dnNH | Find start, move number to next location down

```

I already know I'm not getting brownie points, cuz I can see many more efficient and more complicated methods :(
> 9 votes

---
Tags: code-golf, number, data-structures
---


title: Shortest way to reverse a number

text:
# Question
Title: Shortest way to reverse a number
Write a function (or equivalent subprogram) to accept a single integer valued argument and return a (similarly typed) value found by reversing the order of the base-10 digits of the argument.

For example given 76543 return 34567

# Answer
# HTML 21 7 chars (1 char if I'm cheeky...)

```
n

```

replace `n` with your number
> 86 votes

# Answer
Python

`int(str(76543)[::-1])`

**EDIT:**

Shorter solution as suggested by @gnibbler:

```
int(`76543`[::-1])

```

or, if above is unclear:

```
x=76543
int(`x`[::-1])

```
> 33 votes

# Answer
**Universal (language *agnostic/independent*)**

If you want to use **only numbers** (avoid converting the number to string) and **don't** want to use some **specific** library (to be universal for any language):

```
x = 76543 # or whatever is your number
y = 0
while x > 0:
    y *= 10
    y += ( x %10 )
    x /= 10 # int division

```

This is python, but it could be done in any language, because it's just a math method.
> 28 votes

# Answer
## Perl 6

```
+$n.flip

```

or:

```
$n.flip

```

for dynamically typed code.

Numbers got string methods due to language design.
> 13 votes

# Answer
# J - 6 characters + variable

```
".|.":y

```

Where y is your value.
> 10 votes

# Answer
## APL (3)

```
⍎⌽⍕

```

Usage:

```
⍎⌽⍕12345 => 54321

```
> 10 votes

# Answer
# PHP, 9 chars

```
(int)strrev(123);

```

To do it short where `N` is a constant:

```
strrev(N)

```
> 8 votes

# Answer
# Vim

17 chars
```
:se ri<CR>C<C-R>"

```
> 8 votes

# Answer
# Befunge (3 characters)

Complete runnable program:

```
N.@

```

Where `N` is your number. Rules say "accept *a single integer* valued argument"; In Befunge you can only enter integers from 0 to 9.
> 8 votes

# Answer
### Language-independent/mathematics

Inspired by Kiril Kirov's answer above. I got curious about the mathematical properties of reversing a number, so I decided to investigate a bit.

Turns out if you plot the difference `n - rev(n)` for natural numbers `n` in some base `r`, you get patterns like this (`(n - rev(n)) / (r - 1)`, for `r=10`, wrapped at `r` columns, red denotes negative number):

This sequence could be generated as such (pseudocode):

```
for i=1 to r:
  output 0

for m=0, 1, …
  for k=1 to (r-1):
    for d=1 to r^m:
      for i=0 to (r-1):
        output (r-1) * (r+1)^m * (k - i)

```

If you store these values in a list/array, then `n - arr[n]` would get you the reversed form of `n`. Now, to "mathematically golf" this, we'd ideally want a closed-form expression that gives us the n:th value in the sequence, so that we could have a closed-form expression for solving the entire task. Unfortunately, I haven't been able to find such an expression... but it *looks* like it should be possible. :(

So yeah, not so much a code-golf as a mathematical curiosity, but if there is a closed-form expression of the above sequence it might actually be useful in proper PL golf submissions.
> 8 votes

# Answer
# Haskell, ~~28~~ 24 characters

```
f=read.reverse.show.(+0)

```
> 7 votes

# Answer
# Ruby (14)

```
x = 13456
x.to_s.reverse

```
> 6 votes

# Answer
**Scala - 33 Chars**

```
def r(a:Int)=(a+"").reverse.toInt

```
> 6 votes

# Answer
## Python 3+

### Function form: 28 characters

```
r=lambda i:int(str(i)[::-1])

```

### (Sub)program form: 25 characters

```
print(input()[::-1])

```

I consider some of the other Python examples to be cheating, or at least cheap, due to using hardcoded input and/or not fully satisfying the requirements.
> 6 votes

# Answer
It is possible to convert a number a string, then reverse the string and then convert that string back to number. This kind of feature is probably available in all language. If you are looking for a more mathematical method then this might help:

```
int n = 76543;
int r = 0;

while (n > 0) {
    r *= 10;
    r += n % 10;
    n /= 10;
}

```
> 5 votes

# Answer
## Golfscript, 5 chars

```
`-1%~

```

This takes an argument on the stack and leaves the result on the stack. I'm exploiting the "subprogram" option in the spec: if you insist on a function, that's four chars more leaving it on the stack:

```
{`-1%~}:r

```
> 5 votes

# Answer
In shell scripting :

```
  echo "your number"|rev

```

Hope this was useful :)
> 5 votes

# Answer
Kinda late but

## APL, 3

```
⍎⌽⍞

```

If you insists on a function

```
⍎∘⌽∘⍕

```
> 3 votes

# Answer
# Mathematica, 14 bytes

```
IntegerReverse

```

This is not competing, because this function was only added in last week's 10.3 release, but for completeness I thought I'd add the only ever (I think?) built-in for this task.
> 3 votes

# Answer
Depends on what you mean by short (javascript):

```
alert(String(123).split('').reverse().join('')),

```
> 2 votes

# Answer
You could do the following in Java. Note that this converts to String and back and is not a mathematical solution.

```
public class test {
    public static int reverseInt(int i) {
        return Integer.valueOf((new StringBuffer(String.valueOf(i))).reverse().toString());
    }

    public static void main(String[] args) {
        int i = 1234;
        System.out.println("reverse("+i+") -> " + reverseInt(i));
    }
}

```
> 2 votes

# Answer
# Lua

Numbers and strings are interchangeable, so this is trivial

```
string.reverse(12345)

```
> 2 votes

# Answer
This one *ACTUALLY* takes an input, unlike some of the rest:

```
print`input()`[::-1]

```

Python btw.
> 2 votes

# Answer
## Actionscript

43 characters. num as the parameter to the function:

```
num.toString().split('').reverse().join('')

```
> 2 votes

# Answer
# Groovy

```
r={"$it".reverse() as BigDecimal}

assert r(1234) == 4321
assert r(345678987654567898765) == 567898765456789876543
assert r(345346457.24654654) == 45645642.754643543

```
> 2 votes

# Answer
# Perl, 11 chars

The `p` flag is needed for this to work, included in the count.

Usage:

```
$ echo 76543 | perl -pE '$_=reverse'

```
> 2 votes

# Answer
# Clojure (42 chars)

```
#(->> % str reverse(apply str)read-string)

```

Example usage:

```
(#(->> % str reverse(apply str)read-string) 98321)

```

returns 12389
> 2 votes

# Answer
# Common Lisp - 60 chars

```
(first(list(parse-integer(reverse(write-to-string '4279)))))

```

will get you 9724.
> 2 votes

# Answer
# K, 3 bytes:

```
.|$

```

Evaluate (`.`) the reverse (`|`) of casting to a string (`$`).

Usage example:

```
  .|$76543
34567

```
> 2 votes

# Answer
# rs, 20 bytes

```
#
+#(.*)(.)/\2#\1
#/

```

Technically, this doesn't count (rs was created earlier this year), but I didn't see any other regex-based answers, and I thought this was neat.

Live demo.

## Explanation:

```
#

```

Insert a pound character at the beginning of the string. This is used as a marker.

```
+#(.*)(.)/\2#\1

```

Continuously prepend the last character of the main string to the area before the marker until there are no characters left.

```
#/

```

Remove the marker.
> 2 votes

# Answer
## mIRC 4.45 (35 Bytes)

```
$regsubex(12,/(.)/g,$mid(\A,-\n,1))

```
> 2 votes

# Answer
this is AS3 code, so you may need to make slight changes

```
function reverseData ( inData:String ):* {
    var ar1 = inData.split(''); //Takes string value, split each digit into an array

    var ar2 = ar1.reverse(); //Inverses the array direction
    /* //OR (if not supported) [not AS3]
    var ar2 = new Array();
    for( var i:int = (ar1.length - 1); i > 0; i++ ) {
        ar2.push( ar1[i] );
    }
    */

    var result = ar2.join();
    return result;
}

```

It should work for a string equavalent (that should be easy to typecast)

For a javascript example...

```
function flip( inData ) {
    return ( parseInt( (inData + '').split('').reverse().join('') ) );
}

alert( flip(123) );

```
> 1 votes

# Answer
## C#

```
int reversed = Convert.ToInt32(String.Join<char>(null, 76543.ToString().Reverse()));

```
> 1 votes

# Answer
# Perl (19 chars)

Simple:

`$x=reverse (98765);`
> 1 votes

# Answer
**k4 - 6 characters**

```
"I"$|$

```

Examples:

```
  "I"$|$76543
34567
  "I"$|$98765
56789

```

Explanation from right to left: ("I"$ = cast to integer)(| = reverse)($ = convert to string)
> 1 votes

# Answer
# Java

```
""+new StringBuilder(""+i).reverse();

```
> 1 votes

# Answer
## in Q (20 characters)

```
f:{"I"$reverse -3!x}

```

Sample Usage:

```
q)f 89478237
73287498

```

Use the k version of reverse (wrapped in parentheses) to make it shorter

```
{"I"$(|:) -3!x}

```

also just define it as a lambda to take 2 chars off for a total of 15
> 1 votes

# Answer
## Bash (15)

```
read a;rev<<<$a

```

As a number of other entries do, '01234' becomes '43210' and '2340' becomes '0432'; i.e. in Python terms it does `print reverse(raw_input())`. If behaviour like `print int(reverse(str(int(raw_input()))))` is expected, it is a bit longer:

### Takes care of trailing zeroes (36)

```
read a;sed s.^0*..\;s.0*$..<<<$a|rev

```
> 1 votes

# Answer
# ruby (26)

The existing ruby answer wasn't a function/lambda, so here goes:

```
f=->i{i.to_s.reverse.to_i}

```
> 1 votes

# Answer
**BaCon**

```
PRINT REVERSE$(STR$(76543))

```

Replace 76543 with any number.
> 1 votes

# Answer
## Brainfuck, 11

```
>,[>,]<[.<]

```
> 1 votes

# Answer
# Pyth (3 chars)

Try it here

```
v_z

```
> 1 votes

# Answer
# TI-BASIC, ~~35~~ ~~32~~ 31 (or 28) bytes

Takes input from the calculator's answer variable, which is whatever was last evaluated (like `_` in the interactive python shell).

```
fPart(.1int(Ans10^(seq(A,A,~int(log(Ans+.5)),not(Ans
sum(Ans10^(cumSum(1 or Ans

```

`10^(` is `2ND``LOG` and `~` is `( - )`, next to ENTER. Everything else can be found in the `2ND``0` catalog.

---

If the program doesn't have to handle the possibility of 0 as input, it can be reduced to 28 bytes by changing `~int(log(Ans+.5)),not(Ans` to `~int(log(Ans)),0`.
Credit goes partially to Thomas Kwa for helping to golf this.
> 1 votes

# Answer
# ES6 Javascript, 31 bytes

```
x=>[...x+''].reverse().join('')

```
> 1 votes

# Answer
C++:

```
int reverse(int number, int number1, int number2){std::vector<int> v; v.push_back(number); v.push_back(number1); v.push_back(number2); std::cout << v[2] << v[1] << v[0]; return 0;}

```
> 1 votes

# Answer
**Scheme, 75 characters**

```
(string->number(list->string(reverse(string->list(number->string 76543)))))

```
> 0 votes

# Answer
# k3, 4 chars

```
0$|$

0$|$76543 \-> gives 34567

```

See also the K4 solution here. The only difference (saving two chars) is that `0$` converts to int.
> 0 votes

# Answer
## PHP, 37

```
<?function f($n){return strrev($n);}

```

## C, 44

```
x;m(n){for(;n;x=x*10+n%10,n/=10);return x;}

```
> 0 votes

# Answer
**R (35 characters)**

```
> cat(rev(strsplit("12345","")[[1]]))
5 4 3 2 1

```

With help from my friends in R chat.
> 0 votes

# Answer
## Game Maker Language, 44

Replace 12345 with whatever number or variable you want:

```
n=12345while(n>0){r=r*10+(n mod 10)n div 10}

```

If you want to prompt for user input, use this **56** character long code instead:

```
n=get_string('','')while(n>0){r=r*10+(n mod 10)n div 10}

```

In both pieces of code, the reverse number is stored in `r`
> 0 votes

# Answer
## Haskell, ~~61~~,23

Using the string reversing technique. `digitToInt` is available from the `Data.Char` library, and of course this code would be shorter if we'd be able to assume if `Data.Char` already was available.

```
-- original version 61 chars
foldl1((+).(*)10).map(Data.Char.digitToInt)$reverse$show 1234

--bonus foldonly version, 67 chars
foldl1((+).(*)10).foldl(flip((:).Data.Char.digitToInt))[]$show 1234

--FireFly's suggestion: 23 chars. Note that read's return type is `a`
-- so you might want to tack on a +1 on ghci etc so `Int` can be derived.
read.reverse.show$1234

```
> 0 votes

# Answer
**Groovy 32**

```
def r(n){print ((n+"").reverse())}

```
> 0 votes

# Answer
# Rebol, 29

```
f: func[n][do reverse mold n]

```

Usage example in Rebol console:

```
>> f 76543
== 34567

```

If you only wanted this to work on integer input then....

```
f: func [n [integer!]] [do reverse mold n]

```
> 0 votes

# Answer
# TI-BASIC, 58 54

```
Input N:0:While N>0:Ans+E3fpart(N,10:N/10→N:End:Ans

```

**Usage**

```
prgmREVERSE
?598028
          820895
            Done

```
> 0 votes

# Answer
**POWERSHELL, 25**

```
-join(Read-Host)[-1..-9]

```

a longer version to take arbitrary input , 36

```
-join($a=Read-Host)[-1..-$a.length]

```

usage

```
PS C:\> -join(Read-Host)[-1..-9]
123456789
987654321
PS C:\>

```
> 0 votes

# Answer
# Julia, 23

```
r(x)=int(reverse("$x"))

```

**$** interpolates an argument (or the result of a function) into a string, denoted by the double quotes. **int()** automatically deletes leading zeroes.

Example:

```
julia> x=1234567890;r(x)
987654321

```

or

```
julia> r(1234567890)
987654321

```
> 0 votes

# Answer
# C# - 58

I think we need more C#

```
int.Parse(string.Concat(Enumerable.Reverse(x.ToString())))

```
> 0 votes

# Answer
## Burlesque, 2 bytes

Certain built-ins treat numbers as list of digits. The reverse built-in for example treats integers as a list of digits and thus reverses integers.

```
blsq ) 76543<-
34567

```

(For characters `<-` switches case).
> 0 votes

# Answer
# MATL, 3 bytes (non-competing)

```
VPU

```

This uses release 10.1.0 of the language/compiler, which is the current version at the time of writing.

**Try it online!**

### Explanation

```
V   % implicitly input a number and convert to string
P   % flip
U   % convert to number and implicitly display

```
> 0 votes

# Answer
# Python 2, 26 bytes

```
print int(`input()`[::-1])

```
> 0 votes

# Answer
# Python 3, 33 bytes

I decided to make a function instead of hardcoding it.

```
def r(n):print(int(str(n)[::-1]))

```

The code is pretty self-explanatory.

Usage: `r(12345)`
> 0 votes

# Answer
# Oracle SQL 11.2, ~~35~~ 34 bytes

```
SELECT 0+REVERSE(:1||'')FROM DUAL;

```
> 0 votes

# Answer
# JavaScript (ES6) 35

`a=b=>b.split("").reverse().join("")`
> -1 votes

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


title: Fairly rank values

text:
# Question
Title: Fairly rank values
# Task

Given an input list of integers **x1…xn**, compute a list of ranks **r1…rn** (a permutation of **{1…n}**) so that **xr1 ≤ xr2 ≤ … ≤ xrn**. Then, for each **xi**, replace its rank by the arithmetic mean of the ranks of all values in **x** that are equal to **xi**. (That is, whenever there is a tie between equal values in **x**, fairly redistribute the ranks among all of them.) Output the modified list of ranks **r’1…r’n**.

(For statistics geeks: such a ranking of observations is used in the Mann–Whitney *U* test (method two, step 1.))

# Example

Given an input list **\[3, -6, 3, 3, 14, 3\]**, the first list of ranks would be **\[2, 1, 3, 4, 6, 5\]**, which would sort the list into **\[-6, 3, 3, 3, 3, 14\]**. Then, the ranks for all **3**s in the input list are evened out into **(2 + 3 + 4 + 5) ÷ 4 = 3.5**. The final output is **\[3.5, 1, 3.5, 3.5, 6, 3.5\]**.

# Test cases

```
[4, 1, 4] -> [2.5, 1.0, 2.5]
[5, 14, 14, 14, 14, 5, 14] -> [1.5, 5.0, 5.0, 5.0, 5.0, 1.5, 5.0]
[9, 9, -5, -5, 13, -5, 13, 9, 9, 13] -> [5.5, 5.5, 2.0, 2.0, 9.0, 2.0, 9.0, 5.5, 5.5, 9.0]
[13, 16, 2, -5, -5, -5, 13, 16, -5, -5] -> [7.5, 9.5, 6.0, 3.0, 3.0, 3.0, 7.5, 9.5, 3.0, 3.0]

```

# Rules

This is , so the shortest code in bytes wins.

# Answer
# Jelly, ~~10~~ 8 bytes

```
ð_'Ṡ‘S‘H

```

*Saved 2 bytes by using the `cmp` trick from @xnor's answer.*

Try it online! or verify all test cases.

### How it works

```
ð_'Ṡ‘S‘H  Main link. Left argument: A (list of values)

ð         Make the chain dyadic, setting the right argument to A.
 _'       Spawned subtraction; compute the matrix of differences.
   Ṡ      Apply the sign function to each difference.
    ‘     Increment.
     S    Sum across columns.
      ‘   Increment.
       H  Halve.

```
> 7 votes

# Answer
# Pyth, 12

```
m+l<#dQ.OS/Q

```

Test Suite

For each value this computes the arithmetic mean of `[1..frequency]` and adds the count of values less than the current one.

This works because for each value we would compute:

```
(1 / frequency) * sum (i = 1..frequency) i + count_less

```

which we can simplify to:

```
(1 / frequency) * [ frequency * (frequency + 1) / 2 + count_less * frequency ]

```

and again to:

```
(frequency + 1) / 2 + count_less

```

However, in Pyth it was golfier to compute the first summand by using the mean builtin, rather than this other formula.
> 6 votes

# Answer
## Python 2, 51 bytes

```
lambda l:[-~sum(1+cmp(y,x)for x in l)/2.for y in l]

```

For each element `y`, the `cmp` expression gives 2 points for each smaller `x` and 1 point for each equal `x`. This sum is rescaled into the right range by adding 1 and halving. The `2.` is needed to avoid integer division.

**Python 3, 52 bytes**

Python 3 lacks `cmp`, requiring a Boolean expression (+2 bytes), but it has float division (-1 byte).

```
lambda l:[-~sum((y>x)+(y>=x)for x in l)/2for y in l]

```
> 4 votes

# Answer
# MATL, 14 bytes

```
7#utG&S&S2XQw)

```

Try it online! Or verify all test cases (slightly modified version of the code; each result is on a different line).

```
      % Implicit input. Example: [5 14 14 14 14 5 14]
7#u   % Replace each value by a unique, integer label. Example: [1; 2; 2; 2; 2; 1; 2]
t     % Duplicate
G&S   % Push input again. Sort and get indices of the sorting. Example: [1 6 2 3 4 5 7]
&S    % Sort and get the indices, again. This gives the ranks. Example: [1 3 4 5 6 2 7]
2XQ   % Compute mean of ranks for equal values of the integer label. Example: [1.5; 5]
w     % Swap top two elements in stack
)     % Index the means with the integer labels. Example: [1.5; 5; 5; 5; 5; 1.5; 5]
      % Implicit display

```
> 3 votes

# Answer
# 05AB1E, 13 bytes

Code:

```
v¹y‹O¹yQO>;+ˆ

```

Uses the **CP-1252** encoding. Try it online!.
> 3 votes

# Answer
# R, ~~17~~ 12 bytes

Takes the input from STDIN outputs to STDOUT. If the output is flexible then we can ditch the `cat()`.

```
rank(scan())

```

Fairly simple, uses the builtin rank that defaults to average for a tie breaker.

In use:

```
> rank(scan())
1: 5 14 14 14 14 5 14
8:
Read 7 items
[1] 1.5 5.0 5.0 5.0 5.0 1.5 5.0
> rank(scan())
1: 3 -6 3 3 14 3
7:
Read 6 items
[1] 3.5 1.0 3.5 3.5 6.0 3.5
>

```
> 3 votes

# Answer
# J, 18 bytes

```
1-:@+1+/"1@:+*@-/~

```

Based on Dennis' solution using xnor's method.

Using a straight-forward approach requires **24 bytes** for me.

```
(i.~~.){](+/%#)/.1+/:@/:

```

## Usage

```
   f =: 1-:@+1+/"1@:+*@-/~
   f 3 _6 3 3 14 3
3.5 1 3.5 3.5 6 3.5
   f 4 1 4
2.5 1 2.5
   f 5 14 14 14 14 5 14
1.5 5 5 5 5 1.5 5
   f 9 9 _5 _5 13 _5 13 9 9 13
5.5 5.5 2 2 9 2 9 5.5 5.5 9
   f 13 16 2 _5 _5 _5 13 16 _5 _5
7.5 9.5 6 3 3 3 7.5 9.5 3 3

```
> 2 votes

# Answer
## Actually, 18 bytes

```
;╗`╝╜"╛-su"£MΣu½`M

```

Try it online!

This is essentially a port of xnor's Python solution.

Explanation:

```
;╗`╝╜"╛-su"£MΣu½`M
;╗                  push a copy of input to reg0
  `             `M  for x in input:
   ╝                  push x to reg1
    ╜                 push input from reg0
     "    "£M         for y in input:
      ╛                 push x from reg0
       -s               cmp(y,x) (sgn(y-x))
         u              add 1
             Σu½      sum, add 1, half

```
> 1 votes

# Answer
# Julia, 30 bytes

```
!x=-~sum((x.>x')+(x.>=x'),2)/2

```

This uses an approach from @xnor's answer. Julia has `cmp`, but it doesn't vectorize.

Try it online!
> 1 votes

# Answer
# APL, 17 chars

```
(y+.×⍋X)÷+/y←∘.=⍨X

```

Assuming the list is stored in `X`.

## Explanation:

Note that APL evaluates expressions from right to left. Then:

* `∘.=⍨X` = `X∘.=X` where `∘.=` is the outer product using `=` as dyadic function. (Where you normally would multiply. So the mathematical outer product may be written as `∘.×`.)
* The resulting matrix is stored in `y` and `y` is directly folded using `+` to give a vector of the number of equal objects for each rank (lets call it `z←+/y`).
* `⍋X` returns the ranks of `X`
* `y+.×⍋X` gives the inner product of our matrix y with this vector.
* The result is divided (component wise) by `z`.
> 1 votes

# Answer
## JavaScript (ES6), ~~49~~ 48 bytes

```
a=>a.map(n=>a.reduce((r,m)=>r+(n>m)+(n>=m),1)/2)

```

Edit: Saved 1 byte by reformulating the expression so it now looks like @xnor's Python 3 answer.
> 0 votes

---
Tags: code-golf, sorting
---


title: Help My Brother Work on his Tan(gent)!

text:
# Question
Title: Help My Brother Work on his Tan(gent)!
*This challenge is entirely fictional. There is no time limit for this challenge.*

My little brother is terrible with computers! He saved up all of his money to buy a new one, and within half an hour the hard drive was wiped and the only software left is a lousy BF interpreter. The worst part of it is, he has a huge Geometry test tomorrow and needs help!

# The Challenge

There's no way I'm going to let him touch my machine, so I'm going to need a fast way to write BF programs that solve his problem. He's learning about finding the area of regular polygons, and writing a new BF program for every calculation is a massive task. I need a fast way to generate BF programs! That's where you come in...

# The Input

Your program or function will receive an integer `2 < N <= 100` which shall represent the number of sides of a regular polygon. You may receive input from function arguments, command line arguments, STDIN, or your language's closest alternative. If necessary, you may additionally require trailing or leading whitespace.

# The Output

Your program should generate a separate BF program that takes input of a single positive integer `0 < a <= 10^10` that shall represent the length of the apothem of a regular polygon. When run, the BF program should output the area of a polygon with `N` sides and an apothem of `a`. More specifically:

* Assume that the BF interpreter is set up such that `,` takes a number as input and `.` outputs a value as a number, not a character. An input of `12` does not translate to the characters `'1' '2'` in memory, rather the literal number `12`. Similarly, when a value of `48` is output, it outputs `'48'`, not the character `'0'`.
* Assume also that each value on the tape of the BF program may contain an infinitely large **integer** -- the value will never wrap to 0.
* Assume that the tape of the BF spans infinitely to the right, but has no negative indices. The pointer starts at `0`.
* My brother is as careless with numbers as he is with computers. As such, the BF code should output the area **rounded to the nearest integer**.

# The Rules

In a separate and unrelated incident, my brother downloaded so much garbage onto my primary programming machine that I have virtually no hard drive space left. As such, your original program **may not exceed 512 bytes**.

Your score in this challenge is the length of all BF programs generated by your program for values of `N` from `3` to `100` inclusive.

Standard loopholes are disallowed.

# Answer
## Python, 23938 score

```
from math import*
def apothem(n):
 c=int(n*tan(pi/n)/2*10)

 s=',>' + '+'*c
 m=">[-]>[-]<<[>>+<<-]>>[<<<[>+>+<<-]>>[<<+>>-]>-]<<"*2
 p=">>[-]<[-]<+++++<[-]++++++++++"
 d=">[>+<-]>[<<[>>>+>+<<<<-]>>>>[<<<<+>>>>-]<[>+<<-[>>[-]>+<<<-]>>>[<<<+>>>-]<[<-[<<->>[-]]+>-]<-]<<+>]"
 o="<."
 print s+m+p+d+o

```
* the area of a regular polygon is *nsa/2* width *n* given in Python and *a* later in BF. *s* is the sidelength of the polygon, which can be computed from *a* and *n*
* `c` is a constant, such that the area is *(aac+5)/10*, so only this formula must be coded into BF. *c* is between 15 and 25.
* `s` is the starting point for the BF code: read the apothem and write `c`
* `m` does *c=ca* twice, so in the cell formaly holding *c* there is *aac*
* `p` prepares for the final operation, clearing temporary cells, adding *5* to *aac* and setting the first cell to *10*
* `d` division
* `o` output

This is my first writing in BF, so all algorithms are from this page.
> 4 votes

---
Tags: geometry, brainfuck, metagolf
---