title: Find a Fixed Point

text:
# Question
Title: Find a Fixed Point
Given an integer \\$x\_1\\$ and some black box function \\$f: ℤ → ℤ\\$ find a fixed point of \\$f\\$ in the sequence defined by \\$x\_{k+1} := f(x\_k)\\$.

### Details

* A value \\$x\\$ is said to be a fixed point of \\$f\\$ if \\$x = f(x)\\$.

For instance if \\$f(x) = \text{round}(\frac{x}{\pi})\\$ and we have a starting point \\$x\_1 = 10\\$ then we get \\$x\_2 = f(x\_1) = f(10) = 3\\$, then \\$x\_3 = f(x\_2) = f(3) = 1\\$, then \\$x\_4 = f(x\_3) = f(1) = 0\\$, and finally \\$x\_5 = f(x\_4) = f(0) = 0\\$ which means the submission should return \\$0\\$.

* You can assume that the generated sequence actually contains a fixed point.
* You can use the native type for integers in place of \\$ℤ\\$.
* You can use any language for which there are defaults for black box functions input in the standard IO meta post. If there are no such default for your language feel free to add one in the sense of the definition of black box functions, and make sure to link your proposals in that definition. Also don't forget to vote on them.

### Examples

```
f(x) = floor(sqrt(abs(x)))
0 -> 0,  all other numbers -> 1

f(x) = c(c(c(x))) where c(x) = x/2 if x is even; 3*x+1 otherwise
all positive numbers should result in 1,2 or 4 (Collatz conjecture)

f(x) = -42
all numbers -> -42

f(x) = 2 - x
1 -> 1

```

# Answer
# Actually, 1 byte

```
Y

```

Try it online!

`Y` is the fixed point function in Actually. In the TIO example, the function is shown being taken as a string, and `£` is used to transform it to a function on the stack. It's also possible to just push the function to the stack like so. These are the only two ways to get a function input in Actually.
> 17 votes

# Answer
# APL (Dyalog), 2 bytes

```
⍣=

```

Try it online!

**NB:** I define `O←⍣=` in the the input section due to a bug in that derived monadic operators can't be defined in the way that TIO likes to define things.

Is an operator that can be used like `(function⍣condition) ⍵`

It applies the `function`, `f`, to  until `(f ⍵) condition ⍵` returns true.

`⍣=` is a derived monadic operator that takes a monadic function, `f`, as its left argument and applies it to its right argument, , until `f ⍵ = ⍵`
> 13 votes

# Answer
## Haskell, 17 bytes

```
until=<<((==)=<<)

```

Try it online!
> 11 votes

# Answer
# MATLAB, 41 bytes

```
function x=g(f,x);while f(x)-x;x=f(x);end

```

There is also this beauty that does not need function files. Unfortunately it is a little bit longer:

```
i=@(p,c)c{2-p}();g=@(g,f,x)i(f(x)==x,{@()x,@()g(g,f,f(x))});q=@(f,x)g(g,f,x)

```

Try it online!
> 10 votes

# Answer
# Mathematica, 11 bytes

```
#2//.x_:>#&

```

Try it online!

# Mathematica, 10 bytes

```
FixedPoint

```

Try it online!
> 7 votes

# Answer
# , ~~36~~ 35 bytes

*thanks to JayCe for golfing down a byte*

```
function(f,x){while(x-(x=f(x)))0;x}

```

Try it online!

Verify the example functions!

R port of flawr's solution.
> 7 votes

# Answer
# Standard ML (MLton), 30 bytes

```
fun& $g=if$ =g$then$else&(g$)g

```

Try it online! Use as `& n blackbox`.

The black box functions are defined as following:

```
fun blackbox1 x = floor(Math.sqrt(Real.fromInt(abs x)))

fun blackbox2 x = c(c(c(x)))
and c x = if x mod 2 = 0 then x div 2 else 3*x+1

fun blackbox3 _ = ~42

fun blackbox4 x = 2-x

```

**Ungolfed version:**

```
fun fixpoint n g = if n = g n then n else fixpoint (g n) g

```
> 7 votes

# Answer
# Python 2, ~~39~~ ~~37~~ 33 bytes

thanks to @Mr.Xcoder for -2 bytes

```
s=lambda k:s(f(k))if k-f(k)else k

```

Try it online!

assumes the black-box function to be named f
> 5 votes

# Answer
# JavaScript (Node.js), ~~25~~ ~~22~~ 21 bytes

thanks Herman Lauenstein for showing me this consensus
thanks to @l4m2 for -1 byte

Assumes the black-box function to be named `f`.

```
g=k=>f(k)-k?g(f(k)):k

```

Try it online!
> 5 votes

# Answer
# Jelly, 3 bytes

```
vÐL

```

Try it online!

Takes the left argument as a string representing a Jelly link (`2_` for instance), and the right argument as an integer

## How it works

```
 ÐL - While the output is unique...
v   -   Evaluate the function with the argument given

```
> 4 votes

# Answer
# Brain-Flak, 24 bytes

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

```

Try it online!

(for the black box function `x -> 2-x` in the example below)

The provided black box function should be a program, that given `x` on the top of the stack, pop `x` and push `f(x)` \- in other word, it should evaluate the function `f` on the value on the top of the stack.

Equivalent Mini-Flak is 26 bytes (thanks to Wheat Wizard for saving 2 bytes):

```
(()){{}(({})( )[{}({})])}{}
             ^ put the function f here

```

(not counting the comments and spaces)

Take the function (inside the `<>`) and a number `x<sub>0</sub>` from input. (note that Brain-Flak is an esoteric language and can't take functional argument as input)

---

Example blackbox functions:

`x -> 2-x`: Try it online!

---

Explanation:

```

(()){{}(({})<f>[({})])}{}   Main program.
                            Implicit input from stdin to stack.
(  )                        Push
 ()                         literal number 1.
                            Now the content of the stack: [1, x<sub>0</sub>]
    {                 }     While stack top ≠ 0:
                            current stack content: [something ≠ 0, x]
     {}                       Pop stack top (something). stack = [x]
       (             )        Push
        ({})                    Stack top = x. Current stack = [x]
             f                  Evaluate f. Current stack = [f(x)]
            < >                   (suppress the value of f(x), avoid adding it)
               [    ]           plus the negative of
                ({})            the top of the stack ( = -f(x) )
                              In conclusion, this change (x) on the stack to
                              (f(x)), and then push (x + -f(x))
                            If it's 0, break loop, else continue.
                       {}   Pop the redundant 0 on the top.
                            Implicit output stack value to stdout.

```
> 4 votes

# Answer
# Swift, ~~47~~ 42 bytes

```
func h(_ n:Int){f(n)==n ?print(n):h(f(n))}

```

Naive approach, assumes that the black box function is named `f`
> 3 votes

# Answer
# APL (Dyalog Unicode), 14 bytes

```
{⍵=⍺⍺⍵:⍵⋄∇⍺⍺⍵}

```

Try it online!

The function at the header is equivalent to `f(x) = floor(sqrt(abs(x)))`

Thanks @Adám for pointing out that the original answer wasn't valid according to PPCG consensus.

### How it works:

```
{⍵=⍺⍺⍵:⍵⋄∇⍺⍺⍵} ⍝ Main 'function' (this is actually an operator)
      :         ⍝ if
 ⍵=⍺⍺⍵          ⍝ the right argument (⍵) = the left function (⍺⍺, which is f) of ⍵
       ⍵        ⍝ return ⍵
        ⋄       ⍝ else
         ∇⍺⍺⍵   ⍝ return this function (∇) with argument f(⍵)

```
> 2 votes

# Answer
# C (gcc), 40 bytes

```
f(n,b)int(*b)(_);{n=n^b(n)?f(b(n),b):n;}

```

Try it online! Note that the flags are not necessary, they are there to aid with testing the fixpoint function defined above.

This is a function that takes an int `n` and a function pointer `b : int → int`. Abusing the fact that writing to the first variable argument sets the `eax` register, which is equivalent to returning. Otherwise, this is pretty standard as far as C golf goes. `n^b(n)` checks for the inequality of `n` and the black box applied to `n`. When unequal, it calls the fixpoint function `f` again recursively with the application and black box as arguments. Otherwise, it returns the fixpoint.

<sup>†Citation needed, I vaguely remember reading this somewhere and google seems to confirm my suspicions</sup>

It declares input with K&R-style parameter typing:

```
f(n, b)
int(*b)(_);
{
    n=n^b(n)?f(b(n),b):n;
}

```

The arcane bit on the second line above declares `b` to be a function pointer that takes an integer parameter—the default type of `_` is assumed to be an integer. Similarly, `n` is assumed to be an integer, and `f` is assumed to return an integer. Hooray for implicit typing?
> 2 votes

# Answer
# Clean, 46 bytes

```
import StdEnv
p x=hd[n\\n<-iterate f x|f n==n]

```

Assumes the function is defined as `f :: !Int -> Int`

It takes the head of the infinite list of applications of `f f f ... x` filtered for those elements where `f el == el`.

Try it online!

If you want to change the function in the TIO, Clean's lambda syntax is:

`\argument = expression`

*(actually it's far more complicated, but thankfully we only need unary functions)*
> 2 votes

# Answer
# Octave, 37 bytes

```
function x=g(f,x);while x-(x=f(x))end

```

Try it online!

Octave has inline assignment but MATLAB doesn't, so this is a golfier Octave port of flawr's solution.

It also ports nicely to R.
> 1 votes

# Answer
# Kotlin, 50 bytes

```
{f,k->var a=k;var b=a+1;while(b!=a){b=a;a=f(a)};a}

```

Try it online!
> 1 votes

# Answer
# Forth (gforth), 36 bytes

This version just assumes `f` is predefined. It's not as cool as the solution below it. Both programs exit with a stack overflow if not found, or a stack underflow if found (after printing the result).

**Try it online**

```
: g dup f over = IF . THEN recurse ;

```

---

## Forth (gforth), 52 bytes

This allows a function's execution token to be passed as a parameter, and is definitely the cooler solution.

```
: g 2dup execute rot over = IF . THEN swap recurse ;

```

**Try it online**

### Explanation:

```
: g             \ x1 f          Define g. Params on the stack. f is on top
2dup execute    \ x1 f x2       duplicate both params, execute f(x1)
rot over        \ f x2 x1 x2    move x1 to top and copy x2 to top
= IF . THEN                     compare, if equal, print
swap recurse ;                  otherwise, recurse

```
> 1 votes

# Answer
# Ruby, ~~31~~ 28 bytes

```
->x,f{x=f[x]until x==f[x];x}

```

Try it online!
> 1 votes

# Answer
## Clojure, ~~45~~ 43 bytes

Well, this is the shortest and ugliest:

```
#(loop[a + b %2](if(= a b)a(recur b(% b))))

```

`+` is there instead of a number so that it is not equal to any value of `x0`.

55 bytes and functional:

```
#(reduce(fn[a b](if(= a b)(reduced a)b))(iterate % %2))

```

Example:

```
(def f #(...))
(defn collaz [x] (if (even? x) (-> x (/ 2)) (-> x (* 3) (+ 1))))
(f (->> collaz (repeat 3) (apply comp)) 125)
; 1

```
> 1 votes

# Answer
# tinylisp repl, 28 bytes

```
(d P(q((x)(i(e(f x)x)x(P(f x

```

Assumes that the function `f` is predefined.

Try it online! (The example function is `f(x) = (x*2) mod 10`.)

### Ungolfed

```
(load library)
(def P
 (lambda (x)
  (if (equal? (f x) x)
   x
   (P (f x)))))

```

If `f(x)` equals `x`, then `x` is a fixed point; return it. Otherwise, recursively look for a fixed point starting from `f(x)` instead of `x`.
> 1 votes

# Answer
# APL NARS 65 chars

```
r←(f v)n;c
   c←0⋄→B
E: r←∞⋄→0
A: n←r
B: r←f n⋄c+←1⋄→E×⍳c>1e3⋄→A×⍳r≠n

```

v operator would return ∞ (or possibly -oo or Nan) for error, else one value x with x=f(x). In test f=floor(sqrt(abs(x))), f1=2-x, f2=c(c(c(x))) with c=x%2==0?x/2:3\*x+1

```
  f←⌊∘√∘|
  f v 0
0
  f v 9
1
  f1←{2-⍵}
  f1 v 1
1
  f1 v ¯10
∞
  f1 v 2
∞
  c1←{0=2∣⍵:⍵÷2⋄1+3×⍵}
  f2←c1∘c1∘c1
  f2 v 1
1
  f2 v 2
2
  f2 v 7
2
  f2 v 82
4

```
> 1 votes

# Answer
# Java 8, 42 bytes

This takes a `Function<Integer, Integer>` or `IntFunction<Integer>` and an `int` or `Integer` (curried) and returns the fixed point.

```
f->i->{while(i!=(i=f.apply(i)));return i;}

```

Try It Online

Takes advantage of the fact that Java evaluates subexpressions from left to right (so the old `i` is compared to the new), a property which I was unaware of while writing this!
> 1 votes

# Answer
# x86 opcode, 8 bytes

```
fun:
        call    edx          ; 2B
        cmpxchg eax,    ecx  ; 3B, on 8086 use xchg and cmp instead
        jnz     fun          ; 2B
        ret                  ; 1B

```

Take input: `ecx` (value `x<sub>0</sub>`), `edx` (function address, take input from `ecx`, write result to `eax` without modifying the value of `ecx` and `edx`)

# 8086 opcode, 7 bytes (but slow)

```
    xor     cx,     cx
    call    dx
    loop    $-2
    ret

```

If there exists a fixed point, looping 65536 times always drive it there.
Take input: `ax` (initial value `x<sub>0</sub>`), `dx` (function address, take input from `ax`, write output to `ax` without modifying the value of `cx` and `dx`).
Output the fixed point in register `ax`.
> 1 votes

# Answer
# dc, 30 bytes

```
[pq][Smrd3Rd3Rxd3R=mLmlmx]dsmx

```

Try it online!

Takes as input the function in the form of a macro and initial value on the stack(pushed in that order). Prints the fixed point.
> 1 votes

# Answer
# , 3 bytes

```
^:_

```

Try it online!

When a conjunction in J is missing an operand, it becomes an adjective. This program produces an adjective which takes as an argument a verb. `^:` is the *power* or "repeat" verb, and the idiom `f^:_`, that is, `f` repeated infinitely, is J's *limit application*, which exactly solves this challenge:

> An infinite power `n` produces the limit of the application of `u` .
> 1 votes

# Answer
# Perl 5, 18 + 1 (`-p`)

```
$_=f$_ while$_^f$_

```

try it online
> 0 votes

# Answer
# Vyxal, 1 byte

Try it Online!

Builtin lol
> 0 votes

# Answer
# J-uby, 3 bytes

J-uby has a built-in operator for this:

```
:!~

```

Attempt This Online!
> 0 votes

# Answer
# Japt, 14 bytes

```

gOvV
¥W?U:ßW

```

Try it

Japt doesn't have any built-in "repeat until the output is constant" functionality, or the ability to take functions directly as input. This program takes `x` as the first input, and a string defining a Japt function as the second input.

Explanation:

```
/n      # Store first input as U

/n      # Store second input as V

gOvV
 OvV    # Interpret V as Japt code
g       # Apply that function to U
        # Store the result as W

¥W      # Check whether U and W are the same
  ?U    # If they are, output U
    :ßW # Otherwise repeat the program with W and V as the inputs

```

A theoretical alternative would work if the function were assumed to already be stored in V, but there isn't really a good way to actually accomplish that in Japt so it's not really a reasonable input method.
> 0 votes

# Answer
# Japt, 10 bytes

Black-box function is preassigned to variable `V`

```
gU=gV)?ß:U

```

Try it

```
gU=gV)?ß:U     :Implicit input of integer U
g              :Sign of difference with
 U=            :  Reassign to U
   gV          :  Value of U after being passed through V
     )         :End sign
      ?        :If truthy (not 0)
       ß       :  Recursive call with new value of U
        :U     :Else return U

```
> 0 votes

# Answer
# Go, 70 bytes

```
func f(O func(int)int,n int)int{x:=O(n)
for;x!=O(x);x=O(x){}
return x}

```

Attempt This Online!
> 0 votes

---
Tags: code-golf, math, integer, functional-programming
---


title: Is this string valid FEN?

text:
# Question
Title: Is this string valid FEN?
# The challenge

Write a program or function which takes a string input as a function parameter or from stdin and determines if it is a valid FEN string.

# Input

You can assume the input will only ever include the following characters (case sensitive)
`pkqrbnPKQRBN12345678/`
The length of the input will always be a minimum of 1 character and a maximum of 100 characters

# Output

Output should be a truthy/falsey value. These can be any values you wish as long as they are consistent (all truthy results have the same output, all falsey results have the same output). You should have exactly two distinct possible outputs.

# What counts as valid

Lowercase letters represent black pieces, uppercase letters represent white pieces.
You should ensure it is possible in a game of chess for the pieces in the current position to exist.
Each player will always have exactly 1 king (k/K)
Each player may have no more than 8 pawns (p/P)
Each player will usually have no more than 1\* queen (q/Q)
Each player will usually have no more than 2\* rooks (r/R)
Each player will usually have no more than 2\* knights (n/N)
Each player will usually have no more than 2\* bishops (b/B)
* It is legal for a player to 'promote' a pawn to any of these four pieces.
The total of pawns, queens, rooks, knights and bishops for each player will never be more than 15

The total number of pieces plus empty squares (denoted by numbers) should always add up to exactly 8 for each rank. And there should always be exactly 8 ranks, separated by a forward slash.

# Things you can ignore

You do not need to concern yourself with whether or not it is possible to play into the position denoted, or if the position is legal, only that the pieces can exist in the quantities given.
You can ignore further complexities of FEN strings such as player turn, castling rights and en passant.

# This is code golf. Shortest program in bytes wins. Usual loopholes and rules apply.

# Test Cases

**Input** rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR
**Output** True

**Input** 2br2k1/1p2n1q1/p2p2p1/P1bP1pNp/1BP2PnP/1Q1B2P1/8/3NR2K
**Output** True

**Input** r2r2k1/p3q2p/ppR3pr/rP4bp/3p4/5B1P/P4PP1/3Q1RK1
**Output** False
(black has 7 pawns and 4 rooks - impossible)

**Input** 6k1/pp3ppp/4p3/2P3b1/bPP3P1/3K4/P3Q1q1
**Output** False (only 7 ranks)

**Input** 3r1rk1/1pp1bpp1/6p1/pP1npqPn/8/4N2P/P2PP3/1B2BP2/R2QK2R
**Output** False (9 ranks)

**Input** 5n1k/1p3r1qp/p3p3/2p1N2Q/2P1R3/2P5/P2r1PP1/4R1K1
**Output** False (2nd rank has 9 squares/pieces)

**Input** rnbqkbnr/pppppppp/8/35/8/8/PPPPPPPP/RNBQKBNR
**Output** True
Thanks to Feersum and Arnauld for clarifying this case (3+5=8)

# What is FEN?

FEN is a standard notation for recording the position of the pieces on a chess board.
Image credit http://www.chessgames.com

# Answer
> 5 votes
# Retina, 105 bytes

```
[1-8]
$*
^
/
iG`^(/[1KQRBNP]{8}){8}$
G`K
G`k
A`K.*K|k.*k
{2`N

2`B

2`R

1`Q

K

T`L`P
8`P

A`P
}T`l`L
^.

```

Try it online! Link includes test cases. Explanation:

```
[1-8]
$*

```

Expand digits to empty squares, which we denote using `1`s.

```
^
/
iG`^(/[1KQRBNP]{8}){8}$

```

Delete the input if it does not match 8 sets of 8 valid squares joined with `/`s. (An extra `/` is prefixed to simplify the check.)

```
G`K
G`k
A`K.*K|k.*k

```

Delete the input if it has no white or no black king, or if it has two of either.

```
{2`N

2`B

2`R

1`Q

K

```

Delete white's starting pieces, if they are still there.

```
T`L`P

```

Demote any remaining white pieces to pawns.

```
8`P

```

Delete the valid white pawns.

```
A`P

```

Delete the input if there are any white pawns left over.

```
}T`l`L

```

Check again but with the black pieces.

```
^.

```

Output a truthy value unless the line was deleted.

# Answer
> 6 votes
## JavaScript (ES6), ~~168~~ ~~174~~ ... 155

*This answer has been edited an embarrassing number of times. Hopefully, the current version is both reliable and decently golfed.*

---

Returns a boolean.

```
s=>[...s].map(c=>++n%9?+c?n+=--c:a[i='pP/KkQqRrBbNn'.search(c),i&=i>4&a[i]>(i>6)||i]=-~a[i]:x+=c=='/',a=[x=n=0])&&!([p,P,s,k,K]=a,n-71|x-7|s|k*K-1|p>8|P>8)

```

### Formatted and commented

```
s => [...s].map(c =>                  // for each character 'c' in the FEN string 's':
  ++n % 9 ?                           //   if we haven't reached the end of a rank:
    +c ?                              //     if the character is a digit:
      n += --c                        //       advance the board pointer by c - 1 squares
    :                                 //     else:
      a[                              //       update the piece counter array:
        i =                           //         i = piece identifier (0 to 12)
          'pP/KkQqRrBbNn'.search(c),  //             with special case: '/' --> 2
        i &=                          //         we count it as a promoted pawn instead if:
          i > 4 &                     //           it's a Q, R, B or N and we already have
          a[i] > (i > 6) ||           //           2 of them for R, B, N or just 1 for Q
          i                           //           else, we keep the identifier unchanged
      ] = -~a[i]                      //         '-~' allows to increment 'undefined'
  :                                   //   else:
    x += c == '/',                    //     check that the expected '/' is there
  a = [                               //   initialize the piece counter array 'a'
    x =                               //   initialize the '/' counter 'x',
    n = 0 ]                           //   initialize the board pointer 'n'
) &&                                  // end of map()
!(                                    // now it's time to perform all sanity checks:
  [p, P, s, K, k] = a,                //   copy the 5 first entries of 'a' to new variables
  n - 71 |                            //   have we reached exactly the end of the board?
  x - 7 |                             //   have we identified exactly 7 ends of rank?
  s |                                 //   have we encountered any unexpected '/' character?
  k * K - 1 |                         //   do we have exactly one king on each side?
  p > 8 |                             //   no more than 8 black pawns, including promotions?
  P > 8)                              //   no more than 8 white pawns, including promotions?

```

### Test cases

```
let f =

s=>[...s].map(c=>++n%9?+c?n+=--c:a[i='pP/KkQqRrBbNn'.search(c),i&=i>4&a[i]>(i>6)||i]=-~a[i]:x+=c=='/',a=[x=n=0])&&!([p,P,s,k,K]=a,n-71|x-7|s|k*K-1|p>8|P>8)

console.log(f("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR")) // True
console.log(f("2br2k1/1p2n1q1/p2p2p1/P1bP1pNp/1BP2PnP/1Q1B2P1/8/3NR2K")) // True
console.log(f("r2r2k1/p3q2p/ppR3pr/rP4bp/3p4/5B1P/P4PP1/3Q1RK1")) // False (black has 7 pawns and 4 rooks - impossible)
console.log(f("6k1/pp3ppp/4p3/2P3b1/bPP3P1/3K4/P3Q1q1")) // False (only 7 ranks)
console.log(f("3r1rk1/1pp1bpp1/6p1/pP1npqPn/8/4N2P/P2PP3/1B2BP2/R2QK2R")) // False (9 ranks)
console.log(f("5n1k/1p3r1qp/p3p3/2p1N2Q/2P1R3/2P5/P2r1PP1/4R1K1")) // False (2nd rank has 9 squares/pieces)
console.log(f("rnbqkbnr/pppppppp/8/35/8/8/PPPPPPPP/RNBQKBNR")) // True
console.log(f("rnbqkbnr/pppppppp/8/9/7/8/PPPPPPPP/RNBQKBNR")) // False (additional test case suggested by Rick Hitchcock)
console.log(f("rnbqkbnr/pppp/ppp/8/8/8/8/PPPPPPPP/RNBQKBNR")) // False (additional test case)
```

# Answer
> 3 votes
# Python 3, ~~284 259 236 225 247~~ 234 bytes

```
import re
s=input()
t,c=s.split("/"),s.count;P=p=9;o=0
for x in"pqrnb":p-=max(0,c(x)-o);P-=max(0,c(x.upper())-o);o+=o<2
v=8==len(t)and all(8==sum(int(x)for x in re.sub("[A-z]","1",p))for p in t)and p>0<P and c('k')==c('K')==1
print(v)
```

Try it Online!

Try it Online with all of the test cases!

-11 bytes thanks to Mr. Xcoder

-13 bytes thanks to Jonathan Allen

+22 I forgot kings existed.

Semi-ungolfed with some explanation:

```
import re
string = input()
split = string.split("/")
count = string.count # find # of occurences of char in string
pawns = 9 # represents the # of pawns a player has out of the game... plus one, e.g. 1 is all in game, 2 is one out, 0 is invalid
PAWNS = 9 # would be 8, but then I would need >= instead of >
offset = 0 # default for pawns
for char in "pqrnb": # for each pawn, each queen over 1, and each rook/knight/bishop over 2 for each player
    # subtract one from the players 'pawns' var, which must end up 1 or greater to be valid
    # otherwise too many pawns/queens/etc of that player are on the board
    pawns -= max(0,count(char)-offset)
    PAWNS -= max(0,count(char.upper())-offset)
    offset += (offset 0 and PAWNS>0 and \ # make sure each player does not have an invalid number of pawns/q/n/b/r
    count('k')==count('K')==1 # correct # of kings
print(valid)

```

# Answer
> 2 votes
# JavaScript (ES6), ~~181~~ ~~172~~ 174 bytes

```
f=([c,...s],n=1,o={p:0,P:0})=>c?c=='/'&&n%9?0:f(s,n+(+c||1),(o[c]=(o[c]||0)+(/[qrbn]/i.test(c)&&o[c]>1-/q/i.test(c)?!o[c>'a'?'p':'P']++:1),o)):o.p<9&o.P<9&n==72&o.k==1&o.K==1

```

**Ungolfed:**

```
f=
  ([c,...s],                 //c is current character
   n=1,                      //n is current square, range [1-72] (board is 9x8 due to slashes)
   o={p:0,P:0}               //o holds piece counts
  )=>
  c?
    c=='/'&&n%9?0:           //ensure 8 squares per row
    f(s,
      n+(+c||1),             //increment n by the correct number of squares
      (o[c]=(o[c]||0)+(/[qrbn]/i.test(c)&&o[c]>1-/q/i.test(c)?!o[c>'a'?'p':'P']++:1),o)
                             //"depromote" extra queens, rooks, bishops, or knights
     ):
  o.p<9&o.P<9&               //no more than 8 pawns per side (accounting for promotions)
  o.k==1&o.K==1&             //each side has one and only one king
  n==72                      //correct number of squares

```

```
f=([c,...s],n=1,o={p:0,P:0})=>c?c=='/'&&n%9?0:f(s,n+(+c||1),(o[c]=(o[c]||0)+(/[qrbn]/i.test(c)&&o[c]>1-/q/i.test(c)?!o[c>'a'?'p':'P']++:1),o)):o.p<9&o.P<9&n==72&o.k==1&o.K==1

console.log(f('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR')); //true
console.log(f('2br2k1/1p2n1q1/p2p2p1/P1bP1pNp/1BP2PnP/1Q1B2P1/8/3NR2K')) //true
console.log(f('r2r2k1/p3q2p/ppR3pr/rP4bp/3p4/5B1P/P4PP1/3Q1RK1')); //false
console.log(f('6k1/pp3ppp/4p3/2P3b1/bPP3P1/3K4/P3Q1q1')); //false
console.log(f('3r1rk1/1pp1bpp1/6p1/pP1npqPn/8/4N2P/P2PP3/1B2BP2/R2QK2R')); //false
console.log(f('5n1k/1p3r1qp/p3p3/2p1N2Q/2P1R3/2P5/P2r1PP1/4R1K1')); //false
console.log(f('rnbqkbnr/pppppppp/8/35/8/8/PPPPPPPP/RNBQKBNR')); //true
console.log(f('rnbqkbnr/pppppppp/8/35/8/8/PPPPPPPP/RNQQKBNR')); //false, too many queens
```

# Answer
> 2 votes
# PHP, 269 bytes

```
$t=($o=count_chars($a="$argn/"))[47]==8&$o[107]==1&$o[75]==1&9>($w=$u=$o[80])&9>$b=$l=$o[112];foreach([81,82,78,66]as$k=>$v){$z=$k?11:10;$b+=$x=$o[32+$v];$t&=$l+$x<$z;$w+=$x=$o[$v];$t&=$u+$x<$z;}$t&=$b<16&$w<16;for(;$c=$a[$n++];)$c<A?$c>0?$s+=$c:$t&=!$s-=8:++$s;echo$t;

```

Try it online!

# Answer
> 1 votes
# Python 3, 263 bytes

```
s=input()
n=0
for a in s.split('/'):n+=sum([int(c)if c in"123456789"else 1for c in a])
m=lambda k:{c:s.count(c)for c in s}.get(k,0)
p=[m("p"),m("P")]
for c in"rnbqRNGQ":b=c in"qQ";p[c<"Z"]+=m(c)+b-2if m(c)>2-b else 0
print((n==64)&(p[0]<9>p[1])&(m("K")>0<m("k")))

```

Try it online!

Not the smallest Python submission, but I think it still has some promise.

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

```
s=>[a={q:1,Q:1},...s].map(c=>+c?n-=c:a[c=a[c]>1?c<a?'P':'p':c]=-2*!(n--%9)-~a[c],n=72)|!(n|a['/']+7|a.k*a.K-1|a.p>8|a.P>8)

```

Try it online!

# JavaScript (Node.js), 123 bytes

```
s=>[...s].map(c=>+c?n-=c:a[c=a[c]>1?c<a?'P':'p':c]=-2*!(n--%9)-~a[c],a={q:1,Q:1},n=71)&&!(n|a['/']+7|a.k*a.K-1|a.p>8|a.P>8)

```

Try it online!

Arnauld's solution but use `a` as object rather than array. Would see which is shorter

```
s=>[...s].map(
  c=>+c?n-=c:                    // number, skip spaces
  a[c=a[c]>1?c<a?'P':'p':c]=     // if there's two, count on pawn
                                 // promoting to pawn don't make it bad
                                 // promoting to king mean there's 2 king and anyway invalid
                                 // promoting to slash mean there's slash on unintended places, invalid
  -2*!(n--%9)-~a[c],             // subtract on slash position, all 7 chances must belong to slash
  a={q:1,Q:1},                   // an extra queen, so only 1 extra before needing promotion
  n=71                           // board size
)&&!(
  n|                             // length unmatched
  a['/']+7|                      // unintended slash or non-slash
  a.k*a.K-1|                     // incorrect king amount
  a.p>8|                         // Not too many pawns
  a.P>8)

```

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


title: Capture on the Pawn Chessboard

text:
# Question
Title: Capture on the Pawn Chessboard
You should write a program or function which receives a string representing a chessboard with only pawns as input and outputs or returns whether any capture is possible on the board.

Input is in a FEN-like notation describing positions of white and black pawns with no other pieces present. You should decide if there is a pawn which can capture an enemy one.

> Each rank is described, starting with rank 8 and ending with rank 1; within each rank, the contents of each square are described from file "a" through file "h". Each pawn is identified by a single letter (white pawn = "P", black pawn = "p", ). Empty squares are noted using digits 1 through 8 (the number of empty squares), and "/" separates ranks. *(partially taken from Wikipedia)*

For example

```
8/pppppppp/8/8/4P3/8/PPPP1PPP/8

```

describes the board

```
--------

pppppppp

    P

PPPP PPP

--------

```

A white pawn can capture a black one if the black one is positioned diagonally up from it (black is up-left or up-right) and a black pawn can capture a white one if the white one is diagonally below from it (white is down-left or down-right). No other capture move (en passant) should be considered.

## Input

* A FEN-like string consisting of the characters `12345678pP/`.
* The input describes the pawns of a valid chess game position. This means (among other more complex constraints) there will be at most 8 pawns for each side and no pawns on ranks 1 and 8.

## Output

* If there is a possible capture for either side you should output a truthy value and a falsy value otherwise.

## Examples

Inputs with **truthy** output (one per line)

```
8/7p/6P1/8/8/8/8/8
8/8/p7/1P6/3P3p/8/8/8
8/2P5/8/4P1p1/2p2P2/3p4/3p1P2/8
8/P7/8/5P2/2pp4/3P2p1/3pP3/8
8/P7/p7/p1P1P3/1P3p2/8/1p6/8
8/4p1P1/2P2P1P/2p1pPpp/8/6P1/pP1p4/8

```

Inputs with **falsy** output (one per line)

```
8/8/8/8/8/8/8/8
8/7P/6p1/8/8/8/8/8
8/7p/7P/8/8/8/8/8
8/pppppppp/8/8/8/8/PPPPPPPP/8
8/p7/8/1p6/5P2/8/8/8
8/p7/P7/2P1p1p1/2p5/8/PP6/8

```

This is code golf so the shortest entry wins.

# Answer
# Pyth, 25 bytes

```
/smC,>JsXz`M9*LN9dJ,8T"Pp

```

Test suite

Steps:

Transform the input by replacing the digits with the equivalent number of quote marks (`N`). This is saved in `J`. We then slice off the first 8 or 10 characters, and zip the result with the original. Any capturing pair will be transformed into `"Pp"`, so we then find the count of that string in the resultant list. This is the output.

As a bonus, this actually counts the number of captures possible in the input.
> 6 votes

# Answer
# Retina, ~~33~~ 29 bytes

```
T`d`w
)`\d
$0.
_

p.{7}(..)?P

```

To run the code from a single file, use the `-s` flag.

Should be easily beatable by something like Perl where the expansion of digits into strings of spaces (or other characters) doesn't take up 17 bytes.

The output is positive (truthy) if there is a possible capture and zero (falsy) if there isn't.

## Explanation

```
T`d`w
)`\d
$0.

```

This is a loop of two stages. The first one is a transliteration stage which decrements each digit, and turns zeroes to underscores. Why? Because `d` and `w` expand to the following two lines:

```
0123456789
_0123456789AB...YZab...yz

```

If the target set of a transliteration stage is longer than the source set, the extraneous characters are ignored, hence the decrementing behaviour (honestly, it was just luck that I decided to put the underscore in front of the digits when expanding the `w` character class).

Then the second stage is a replacement, which appends a `.` to each digit. That means that for each digit `n`, `n` periods are added before that digit is turned into an underscore.

```
_
<empty>

```

This just gets rid of the underscores.

```
p.{7}(..)?P

```

Finally, we find the matches. Since we're ignoring en passant, captures are only possible if there is a `p` and then a `P` diagonally below it. In the linear string, this simply means that there must be 7 or 9 characters between the two pawns. This matched with `.{7}(..)?` (i.e. match 7 characters and then, optionally, match another two).

Such a match stage returns the number of matches it found.
> 13 votes

# Answer
# Javascript, 272 characters

```
function h(t){b=[[]];for(i=-1;i++<7;){c=0;b.push(l=[]);for(j=-1;j++<7;){o=t.split('/')[i][j];switch(o){case'P':l[c++]=-1;break;case'p':l[c++]=1;break;default:c+=parseInt(o);}}}b.push([]);for(i=1;i<9;i++)for(j=0;j<8;j++)if((p=b[i][j])&&(b[i+p][j-1]||b[i+p][j+1]))return 1;}

```

There's probably a lot of room for improvement.
> 3 votes

# Answer
# Ruby, ~~145 123~~ 46 bytes

```
->b{b.gsub(/\d/){|x|?.*x.to_i}=~/p.{7}(..)?P/}

```

I don't know why I didn't think about this in the first place. It's much shorter and also pretty readable.

Here's the test: http://ideone.com/Gzav8N

---

The old approach:

```
->b{l={}
r=p
b.split(?/).map{|s|c={}
i=0
s.chars.map{|x|n=x.to_i;c[i]=x;i+=n<1?1:n;x==?P&&r||=l[i-2]==?p||l[i]==?p}
l=c}
r}

```

Online test: http://ideone.com/9L01lf, version before golfing: http://ideone.com/CSmqlW

A history of modifications is available here.
> 3 votes

# Answer
## ES6, 64 bytes

An appropriate byte count, if it lasts!

```
f=s=>/p.{7}(..)?P/.test(s.replace(/\d/g,n=>"        ".slice(-n)))

```

I actually thought of this solution without reading the other answers first, but I won't mind if you don't believe me.
> 2 votes

# Answer
# Pip, 21 bytes

```
`p.{7}(..)?P`NaRXDsX_

```

Verify all test cases!

### Explanation

Same regex-based solution as most of the other answers.

```
`p.{7}(..)?P`NaRXDsX_
              a        1st command-line argument
               R       Replace
                XD      regex matching a digit
                  sX_   with space repeated that many times
             N         Count occurrences of
`           `           this regex:
 p                       A black pawn
  .{7}                   followed by any 7 characters
      (..)?              optionally followed by 2 more characters
           P             followed by a white pawn

```
> 2 votes

# Answer
# APL (Dyalog Unicode), 47 bytes

```
'p.{7}(..)?P'{≢⍺ ⎕S⍬⊢⍵}('\d'⎕R{' '⍴⍨⍎⍵.Match})⍞

```

I wanted to make a matrix based matching solution for this, but Martin Ender's Regex ended up being simpler.

Try it online!

## Explanation

```
'p.{7}(..)?P'{≢⍺ ⎕S⍬⊢⍵}('\d'⎕R{' '⍴⍨⍎⍵.Match})⍞
                                              ⍞ String input
                            ⎕R                  Perform Regex replacement
                        '\d'                    match all digits
                              {' '⍴⍨⍎⍵.Match}   Execute match(convert to number), replace with that many spaces
             {≢⍺ ⎕S⍬⊢⍵}                         Tally number of matches of left argument in right
'p.{7}(..)?P'                                   Match two opposite colored pawns 7-9 spaces apart

```
> 2 votes

# Answer
# JavaScript (Node.js), ~~55~~ 51 bytes

```
t=>/p.{7}(..)?P/.test(t.replace(/\d/g,i=>'1e'+i-1))

```

Try it online!

Replace numbers with spaces, then

```
12345678/
 P1234567
p   P1234
56789p
P1234567p ; attempt to make P and p not in neighbor line
       P1 ; and fail
23456789p

```
> 2 votes

# Answer
# Japt v2.0a0, 21 bytes

Adaptation of Neil's solution.

```
r\dÈ°çÃè/p{7ç.}(..)?P

```

Try it (Includes all test cases)
> 1 votes

# Answer
# Perl 5, 30 bytes

29, plus 1 for `-pe` instead of `-e`

```
s/\d/1x$&/ge;$_=/p.{7}(..)?P/

```

A Perl copy of w0lf's Ruby answer.
> 0 votes

# Answer
# PHP, ~~94~~ ~~87~~ 80 bytes

```
for(;$i++<8;)$t[$i]=$s.=" ";echo preg_match("#p.{7}(..)?P#",strtr($argv[1],$t));

```

That loop+`strtr` is a lot shorter than `preg_replace_callback` with `str_pad`.
> 0 votes

# Answer
## Jelly, 88 84 79 72 69 65 64 63 60 bytes

Definitely room for improvement.

```
ØDṖḊ
”_x
e1£¬
1£iÐ€2Ŀ€
x"3Ŀ€;"ÇFṣ”/
w€⁾pPn0
5ĿUŒDÇ
5ĿŒD6ĿoÇS

```
> 0 votes

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


title: Intersection of Two Lines

text:
# Question
Title: Intersection of Two Lines
Given equation of two lines in the format Ax+By=C, determine their intersection point. If they are parallel print 'parallel' without quotes. For input/output format refer sample input/output.

```
Input
1x+1y=1
1x-1y=1

Output
(1.00,0.00)

Input
0x+1y=0
1x+0y=0

Output
(0.00,0.00)

```
1. -1000000 \<= A,B,C \<= 1000000.
2. Note their intersection point may not be integer. Print upto two decimal places.
3. Shortest solution wins.

# Answer
> 3 votes
## Ruby - 119 chars

```
a,b,c,d,e,f=(gets+gets).scan(/-?\d+/).map &:to_f
puts (t=a*e-b*d)==0?'parallel':"(%.2f,%.2f)"%[(e*c-b*f)/t,(a*f-c*d)/t]

```

# Answer
> 3 votes
## Python, 148 146 chars

```
import re
I=raw_input
a,b,p,c,d,q=eval(re.sub('x|y=','.,',I()+','+I()))
D=a*d-b*c
print'(%.2f,%.2f)'%((p*d-q*b)/D,(a*p-c*q)/D)if D else'parallel'

```

# Answer
> 2 votes
## Python+sympy - 161 chars

```
from sympy import*
x,y=symbols('xy')
e=lambda:eval(raw_input().replace('x','*x').replace('y=','*y-'))
r=solve([e(),e()],[x,y])
print r and`r[x],r[y]`or'parallel'

```

**Python+sympy - 143 chars (different output format)**

```
from sympy import*
x,y=symbols('xy')
e=lambda:eval(raw_input().replace('x','*x').replace('y=','*y-'))
print solve([e(),e()],[x,y])or'parallel'

```

output format for 143 char version is slightly different from the spec

```
In:
1x+1y=1
1x-1y=1

Out:
{x: 1, y: 0}

In:
0x+1y=0
1x+0y=0

Out:
{x: 0, y: 0}

```

# Answer
> 2 votes
## sage \- 162 chars

```
x,y=var('x,y')
e=lambda:eval(raw_input().replace('x','*x').replace('y','*y='))
try:r=solve([e(),e()],[x,y])[0];print`r[0].rhs(),r[1].rhs()`
except:print'parallel'

```

# Answer
> 2 votes
## J, 146 132 134 124

```
echo'parallel'"_`(1|.')(',[:(,',',])&(0j2&":)/[:,,.@{:%.}:)@.([:*@|[:-/ .*}:)|:".>{.`(<@}:@;@(1 2&{))`{:(`:0)"1;:;._2(1!:1)3

```

Parsing this is awful.

**Edit**: Realized that my output is basically broken, although it works for the examples given and parallels...

**Edit**: Posting the shorter version I already had.

**Edit**: Fixed without too much pain...

**Edit**: Fixed a weird issue where the program was spread across multiple lines.

Somewhat ungolfed version:

```
words =: ;:;._2(1!:1)3
NB. Leverage J's parser itself to split each line into e.g. ax + by = c
lines =: ".>{.`(<@}:@;@(1 2&{))`{:(`:0)"1 words
NB. Use a 3-part gerund (`) to get boxed strings 'ax';'b';'c', unbox and parse
calc_and_format =: 1|.')(',[:(,',',])&(0j2&":)/[:,,.@{:%.}:
NB. %. (matrix multiply) first two rows (a d/b e) by third row turned (c/f)
NB. And then format laboriously. 0j2&": formats numbers with 2 decimals.
det_nonzero =: [:*@|[:-/ .*}:
NB. 1 if determinant (-/ .*) of (a b/d e) is nonzero (*@|)
echo'parallel'"_`calc_and_format@.det_nonzero|: lines
NB. transpose parsed input to get (a d/b e/c f).
NB. If det_nonzero, call calc_and_format, otherwise constant 'parallel'
NB. Print

```

# Answer
> 2 votes
# OCaml + Batteries, 163 characters

As straightforward as it gets:

```
Scanf.scanf"%fx%fy=%f\n%fx%fy=%f\n"Float.(fun a b c d e
f->Printf.(fun u->if u=0.then printf"parallel"else
printf"(%.2f,%.2f)"((b*f-c*e)/u)((d*c-a*f)/u))(b*d-a*e))

```

**Edit:**

* Initial version, 169
* Use Batteries for delimited overloading of operators, 164
* Lambda binding of `u`, 163

# Answer
> 2 votes
## C-149 bytes

Not much of golfing just the basics.

```
float a,b,c,d,m,n,t;main(){scanf("%fx%fy=%f%fx%fy=%f",&a,&b,&m,&c,&d,&n);t=b*c-a*d;t?printf("(%.2f,%.2f)",(b*n-d*m)/t,(c*m-a*n)/t):puts("parallel");}

```

Here is the ideone link for testing.

Instead of printing 'parallel' an alternative could be to print the orthogonal distance between the lines when they are parallel.

# Answer
> 1 votes
# Vyxal, 10 bytes

```
∆Q:[vt|`ċ₃

```

Try it Online!

8 if the format can be `⟨ ⟨ `x` | xval ⟩ | ⟨ `y` | yval ⟩ ⟩`. Returns fraction representation of all numbers if not integer.

## Explained

```
∆Q:[vt|`ċ₃
∆Q          # Solve the two input equations simultaneously
  :[        # If there's a solution
    vt      #   get the last values of each two item tuple
      |`ċ₃  # else, push the string "parallel"

```

---
Tags: code-golf, geometry
---


# Question
Title: Find random images from http://i.imgur.com/
Imgur is a free image hosting service. Many people use it. Here is an example of an imgur link: https://i.stack.imgur.com/II8CA.png. Write a program that continually outputs random (valid) imgur links. For example, here is some sample output of my progam (not shown because it contains some tricks you will have to figure out yourself):

```
http://i.imgur.com/uFmsA.png
http://i.imgur.com/FlpHS.png
http://i.imgur.com/eAbsZ.png
http://i.imgur.com/lEUsq.png
http://i.imgur.com/RuveH.png
http://i.imgur.com/BoEwB.png
http://i.imgur.com/HVFGQ.png
http://i.imgur.com/PZpMg.png
http://i.imgur.com/DezCY.png

```

Helpful hints:

* When imgur was new, 5-letter links were used.
* When imgur was new, numbers weren't used.
* You can use this to your advantage: only find 5-letter link images with only letters. That is what my program does.
* Also, all images are saved as `.png`.

Requirements:

* Continually output random imgur links
* Links considered sufficiently "random" if 50 are outputted with no repeats
* When visited, links must be an image
* Links must start with `http://i.imgur.com/` and end with `.png`
* Score is amount of characters

I did it in Java (TERRIBLE for golfing) in 452 chars. Not shown here because it contains some tricks you will have to figure out for yourself!)

# Answer
## PHP 5.4, 76 characters

URLs are generated in sequential order using only uppercase letters and never repeat, meeting the letter of the specification.

```
<?for($t=@ZZZZ;$t++;)file($u="http://i.imgur.com/$t.png")[0]>@F&&print"$u
";

```
> 3 votes

# Answer
**HTML (152)**

```
<img src=x
onload=console.log(s);g()
onerror=g=function(){s='http://i.imgur.com/'+Math.random().toString(36).substr(2,6)+'.png';event.target.src=s};g()>

```

This logs all found images on the JavaScript console using `console.log()`. Works in all tested browsers (Firefox, Chrome, IE9, Safari and Opera).

The fun part is that all sorts of funny images are flashing up for the blink of an eye :).

Try it! (jsFiddle wraps this into a more complete HTML page, but browsers also accept the single element.)

Props to the amazing random string method by doubletap!

**Where can I see the JavaScript console and the logged images?**

* *Firefox:* Press Control-Shift-K (Command-Option-K on the Mac). Unselect the Net, CSS and JS buttons there, only select the Logging button.
* *Opera:* Press Control+Shift+i, select the Console tab.
* *Chrome:* Press Control+Shift+i, select the Console tab. On the bottom, select Logs.
* *Safari:* Basically like Chrome, but make sure first that Safari's developer tools are activated. Then press Control+Alt+C (on Windows, not sure on the Mac) instead of Control+Shift+i, select the Console tab. On the bottom, select Logs.
* *IE:* Press F12, select the console tab.
> 5 votes

# Answer
## Perl (93 + 4 = 97)

Using imgur's own random mechanism to get **their** image URLs, which aren't png URLs most of the time:

```
$ perl -Mojo -E 'say+g("http://imgur.com/gallery/random")->dom->at("[rel=image_src]")->attrs("href")for+1..50'
http://i.imgur.com/7cNoA.jpg
...

```

(You need Mojolicious for this.)
> 4 votes

# Answer
# Perl (87)

```
perl -pe's/\W//g;$_="http://i.imgur.com/$_.png\n";$_=""if`curl $_`=~/^</'</dev/urandom

```

Finding images with uppercase, lowercase and digits from 0 up to any characters, some day.
> 3 votes

# Answer
### *Mathematica*, 108

White-space added.

```
While[True,
 Import@# /. _Image :> Print@# &[
  "http://i.imgur.com/" <> "a" ~CharacterRange~ "z" ~RandomChoice~ 5 <> ".png"
 ]
]

```
> 3 votes

# Answer
## Python (~~174~~ ~~158~~ 156)

I want shorter module names in Python. Also an easier method of getting random letters. :)

```
import urllib,random
while 1:a='http://i.imgur.com/%s.png'%''.join(chr(random.randint(65,90))for i in'AAAAA');print('File'not in urllib.urlopen(a).read())*a

```

Explanation:

The modulus operator on a string is the formatting command, in this case it replaces '%s' in the string with 5 random uppercase letters
`a` is the website name (type `str`)
`('File'not in urllib.urlopen(a).read())` is True when 'File' (from 'File not found!') is **not** found in the the HTML of the URL. (type `bool`)
`bool` * `str` = `str` if `bool` = True, so it will only output `a` if 'File' is not found in the HTML code.
> 2 votes

# Answer
# Python, 361 355 334 332 322 314 characters

A little obfuscated, nothing too difficult. May result in unusually high density of cat pictures, you have been warned.

```
import json as j,urllib as o,time as t;a=0
while 1:
 q="i.imgur";y,p=('data','children');r="njj";h="erqqvg.pbz/";u="uggc://"+h+"e/"+r;c=j.loads(o.urlopen(u.decode('rot13')+".json?sorted=new&after=%s"%a).read())[y]
 for s in c[p]:
  f=s[y];w=f['url'].strip('?1')
  if w.find(q)!=-1:print w
 a=c['after'];t.sleep(3)

```

Output:

```
http://i.imgur.com/u3vyMCW.jpg
http://i.imgur.com/zF7rPAf.jpg
http://i.imgur.com/aDTl7OM.jpg
http://i.imgur.com/KONVsYw.jpg
http://i.imgur.com/RVM2pYi.png
http://i.imgur.com/tkMhc9T.jpg
http://i.imgur.com/KxUrZkp.gif
http://i.imgur.com/mnDTovy.jpg
http://i.imgur.com/WpuXbHb.jpg
http://i.imgur.com/qZA3mCR.jpg
http://i.imgur.com/AxMS1Fs.png
http://i.imgur.com/TLSd571.jpg
http://i.imgur.com/VfMhLIQ.jpg
http://i.imgur.com/Wu32582.jpg
http://i.imgur.com/hrmQL2F.jpg
http://i.imgur.com/Clg8N.jpg
http://i.imgur.com/7Wsko.jpg
http://i.imgur.com/Rhb0UNx.jpg
http://i.imgur.com/LAXAf45.gif
http://i.imgur.com/jhOLJ9B.jpg
http://i.imgur.com/FQ9NeAl.jpg
http://i.imgur.com/oqzf6tE.jpg
http://i.imgur.com/rnpXs1A.jpg
http://i.imgur.com/DfUIz6k.jpg
http://i.imgur.com/orfGA5I.jpg
http://i.imgur.com/wBT7JNt.jpg
http://i.imgur.com/RycK1m2.jpg
http://i.imgur.com/7j21FIR.jpg
http://i.imgur.com/z2tVnNC.jpg
http://i.imgur.com/mnsAGuF.jpg
http://i.imgur.com/vIZM1NY.jpg
http://i.imgur.com/JT3XRI4.jpg
http://i.imgur.com/SNpwTmp.jpg
http://i.imgur.com/u9ynLb9.jpg
http://i.imgur.com/DrFWsBP.jpg
http://i.imgur.com/rU6oyup.jpg
http://i.imgur.com/XxBD5nl.jpg
http://i.imgur.com/d09qQzP.jpg
http://i.imgur.com/vvPSbqI.jpg
http://i.imgur.com/1hdfobQ.jpg
http://i.imgur.com/4LLC6Vs.jpg
http://i.imgur.com/RfasxO2.jpg
http://i.imgur.com/BBcpOos.jpg
http://i.imgur.com/zMH8mgG.jpg
http://i.imgur.com/7g8k2Ww.jpg

```
> 2 votes

# Answer
# Bash (129, 121) (117, 109)

I've got two versions: an iterative and an endless recursive one (which will slowly eat up all memory). Both versions check if there actually is a PNG file present (jpg's, gif's and other file types are ignored).

Iterative(old) (129):

```
while true;do u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -s 2>&1|head -c4|grep PNG$ -q&&echo $u;done

```

Recursive(old) (121):

```
:(){ u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -s 2>&1|head -c4|grep PNG$ -q&&echo $u;:;};:

```

**Note**: There might be a compatability issue with grep. My grep manual states that `-s` silents grep's output but it does nothing. However, using `--quiet`, `--silent` or `-q` instead works.

**EDIT:**

Using content headers now after reading https://codegolf.stackexchange.com/a/10499/7195 :)

Iterative (117):

```
while true;do u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -sI|grep image -q&&echo $u;done

```

Recursive (109):

```
:(){ u=http://i.imgur.com/$(tr -dc a-zA-Z</dev/urandom|head -c5).png;curl $u -sI|grep image -q&&echo $u;:;};:

```
> 2 votes

# Answer
## R, 182 characters

```
library(httr);while(0<1){s=paste("http://i.imgur.com/",paste(sample(c(LETTERS,letters),5),collapse=""),".png",sep="");if(HEAD(s)$headers$'content-type'=='text/html')'' else print(s)}

```
> 1 votes

# Answer
# Python, 153 chars

```
import string as s,random as w,requests as r
while 1:
 t='http://i.imgur.com/%s.png'%''.join(w.sample(s.letters,5))
 if'not'not in r.get(t).text:print t

```

While this works, it is bloody slow and might take many seconds before returning any output.

Inspired by @beary605's solution - he saved me a bunch of characters as I was planning to check for image by content-type header.
> 1 votes

# Answer
# Ruby (103 chars)

```
require"open-uri";loop{u="http://i.imgur.com/#{rand(1e9).to_s(36)[0,5]}.png";open u rescue next;puts u}

```
> 1 votes

# Answer
# Bash/command-line tools, 72 chars

Borrowing @memowe's clever technique:

```
curl -sL http://imgur.com/gallery/random|grep e_sr|cut -d\" -f4;exec $0

```

This achieves a continuous loop by re-execing itself within the same process space.
> 1 votes

# Answer
# Jelly, 41 bytes

```
ØẠẊs5Ḣ
“http://i.imgur.com/”;¢;“.png”ṄƲÐḶ

```

How?

```
ØẠẊs5Ḣ  : Helper Link
ØẠ      : Upper and Lowercase Alphabet
  Ẋ     : Shuffle
   s5   : Split Into Lengths of 5
     Ḣ  : Head; pop from front of list
-----------------------------------------------------------------------------------------
“http://i.imgur.com/”;¢;“.png”ṄƲÐḶ  : Main Link
“http://i.imgur.com/”               : String Literal
                      ¢             : Previous link as a nilad.
                        “.png”      : String Literal
                     ; ;            : Concat
                              Ṅ     : Print with a linefeed
                               Ʋ    : Last four links as a monad
                                ÐḶ  : Loop; Repeat until the results are no longer unique.

```

Attempt This Online!
> 1 votes

---
Tags: code-golf, random, internet
---


title: Division between two strings

text:
# Question
Title: Division between two strings
Inverse function of this challenge

> To (properly) multiply an string by an integer, you split the string into characters, repeat each character a number of times equal to the integer, and then stick the characters back together. If the integer is negative, we use its absolute value in the first step, and then reverse the string. If the input is 0, output nothing (anything multiplied by 0 equals nothing).

Now, you are given the multiplied string and the result of multiplication, and your task is to output the multiplied integer.

You can assume such integer exist. If multiple exist, output any of them.

Test cases:

```
abc, cba => -1
abc, aabbcc => 2
abc, ccbbaa => -2
aaa, aaaaaa => 2 or -2
(empty), (empty) => any integer
aaa, aa => undefined behavior
abaa, aaaabbaa => -2
abaa, aabbaaaa => 2
hello, (empty) => 0
a, aaaaaaaaaaa => 11 or -11

```

This is , lowest byte count wins!

# Answer
# JavaScript (ES6), 61 bytes

Expects `(original_string)(other_string)`.

```
a=>b=>b.match([...a].join(`{${q=b.length/a.length|0}}`))?q:-q

```

Try it online!
> 7 votes

# Answer
# , ~~100~~ 98 bytes

```
\(x,y,r=rle(x),s=rle(y))`if`(sum(t<-s$l),`if`(any(r$v!=s$v)|sd(c(a<-t/r$l,a)),-rev(t)/r$l,a)[1],0)

```

Attempt This Online!

Takes input as vectors of characters.
> 6 votes

# Answer
# Japt, ~~16~~ 15 bytes

Takes input in reverse order.

```
ÊzVÊ
*JpNÎÀVmpU

```

Try it

```
ÊzVÊ\n*JpNÎÀVmpU     :Implicit input of strings U=result & V=original
Ê                    :Length of U
 z                   :(Floor) Divided by
  VÊ                 :Length of V
    \n               :Reassign to U
      *              :Multiply U by
       J             :-1
        p            :Raised to the power of
         N           :Array of all inputs
          Î          :First element (original U)
           À         :Is not equal to
            Vm       :Map V
              pU     :Repeat U times

```
> 4 votes

# Answer
# 05AB1E, ~~16~~ 12 bytes

```
gIg÷DI×S¹Êi(

```

Inputs in reversed order as lists of characters.
Will output the positive result for palindromes, where two results are possible.

Try it online or verify all test cases.

**Explanation:**

```
g             # Push the length of the first (implicit) input-list
 Ig           # Push the length of the second input-list
   ÷          # Integer-divide this longer first by the shorter second length
    D         # Duplicate this integer
     I×S      # Repeat each character in the second input-list that many times, and then
              # convert it to a flattened list of characters
        ¹Êi   # If it's NOT equal to the first input-list:
           (  #  Negate it
              # (after which it is output implicitly as result)

```
> 3 votes

# Answer
# , 17 bytes

```
%&#*_1+2*[-:%&##]

```

Try it online!

* `%&#` Scaling factor -- longer length divided by shorter length
* `#]` Use that to duplicate the shorter string elementwise
* `[-:` Does that match the longer string? (will be 0 or 1)
* `_1+2*` Double and subtract 1. This will be -1 if the string was reversed and 1 otherwise.
* `%&#*` Multiply that by the scaling factor from step 1. Sadly repeating the 3 characters `%&#` is shorter than any other approach which re-uses the result, at least that I could find.
> 3 votes

# Answer
# Python, 60 bytes

-17 bytes thanks to `l4m2` and -14 bytes thanks to `friddo`

```
lambda a,b:a and(a==b[::(d:=len(b)//len(a))or 1]or-1)*d or 0

```

Attempt This Online!
> 3 votes

# Answer
# C (GCC), ~~141~~ ~~137~~ 125 bytes

```
f(x,y,d,k,r,i,z)char*x,*y;{for(k=d=!!*y;r=1;(k=-k)>0&&++d){for(i=z=strlen(y);i--;)r&=y[k>0?i:z+~i]==x[i/d];if(r)return d*k;}}

```

Attempt This Online!
> 2 votes

# Answer
# Elm, ~~108~~ 107 bytes

*-1 byte thanks to Wheat Wizard*

```
f a b=if a>[]then let r=l b//l a in if List.concatMap(List.repeat r)a==b then r else-r else 0
l=List.length

```

Takes two lists of chars, the shorter one first. You can try it here. Here's a full test program:

```
import Html exposing (text)

f : List Char -> List Char -> Int
f a b=if a>[]then let r=l b//l a in if List.concatMap(List.repeat r)a==b then r else-r else 0
l=List.length

main =
  f ['a','b','c'] ['c','c','b','b','a','a']
  |> String.fromInt
  |> text

```

### Explanation

* If the shorter list `a` is not empty:
    + Let `r` be the integer quotient of the length of `b` and the length of `a`
    + Multiply `a` by `r` (approach copied from my Elm answer to the string-multiplication question)
    + If the result equals `b`, return `r`
    + If not, assume it's because `a` was reversed and return `-r`
* The only valid case when `a` is empty is both `a` and `b` empty; in this case, any number can be returned; we choose `0`
> 2 votes

# Answer
# Vyxal, 12 bytes

```
ȧ¹•nṠ¬ßṘ⁰=)N

```

Try it Online!

Outputs the smallest integer needed, with preference given to positive integers if there are 2 possible answers.

## Explained

```
ȧ¹•nṠ¬ßṘ⁰=)N
          )N # Find the first integer n (pos or neg) where:
 ¹•          #   the divisor with characters repeated
ȧ            #   abs(n) times
      ßṘ     #   reversed if:
   nṠ¬       #     n is negative
        ⁰=   #   equals the dividend

```
> 1 votes

# Answer
# Haskell, 85 bytes

```
l=length
_#""=0
p#m=let q=l p`div`l m in if p==concatMap(replicate q)m then q else -q

```

Try it online!
> 1 votes

# Answer
# Charcoal, 24 bytes

```
Ｉ∧Ｌη×÷ＬηＬθ∨⁼⭆θ×ι÷ＬηＬθη±¹

```

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

```
   η                        Second input
  Ｌ                         Take the length
 ∧                          Logical And
       η                    Second input
      Ｌ                     Take the length
     ÷                      Integer divided by
         θ                  First input
        Ｌ                   Take the length
    ×                       Multiplied by
             θ              First input
            ⭆               Map over characters and join
               ι            Current character
              ×             Repeated by
                  η         Second input
                 Ｌ          Take the length
                ÷           Integer divided by
                    θ       First input
                   Ｌ        Take the length
           ⁼                Is equal to
                     η      Second input
          ∨                 Logical Or
                       ¹    Literal integer `1`
                      ±     Negated
Ｉ                           Cast to string
                            Implicitly print

```
> 1 votes

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

```
LDns1+:gD0<?z1r(z1(sZAZkz0=Pkw

```

Port of Kevin Cruijssen's 05AB1E answer. Append `0~` to the end if outputting `[]` for 0 isn't allowed.

#### Explanation

```
L         # Push the length of the first (implicit) input-string
 Dn       # Duplicate and negate the top one
   s1+    # Swap and add one to the top one
          # (The range works like Python's in that range(a, b) will give [a..b))
      :   # range of the two items on the stack
       g  # Filter for items where the following is truthy:
D         #   Duplicate the number
 0<?      #   If it's less than 0:
    z1r   #     Push a reversed copy of the second (implicit) input
       (  #   Else:
z1        #     Push the second (implicit) input
  (       #   Endif
   sZA    #   Get the absolute value of the integer
      Zk  #   And uninterleave the string with a length of this integer
z0=       #   Check if each part is equal to the first input
   P      #   Are all of these true?
    k     # End filter
     w    # Keep truthy items only
          # (It was somehow including 0 in the output for all test cases, so I had to discard it)

```

#### Screenshots
> 1 votes

# Answer
# Python 3, 53 bytes

```
lambda x,y:len(y)and[d:=len(y)//len(x),-d][y[::d]!=x]

```

Try it online!
> 1 votes

# Answer
# Nibbles, 8 bytes (16 nibbles)

```
?,%$`%;/,@,$_*~@

```

```
?,%$`%;/,@,$_*~@
       /            # divide
        ,@          #   length of arg2
          ,$        #   by length of arg1
      ;             # and save the result n;
    `%      _       # now get every n-th element of arg2
  %$                # and use this to split arg1
                    # (result will be empty list if they're equal,
                    # or arg1 unchanged if they're unequal);
?,                  # if the length of this is nonzero
             *~@    #   return n multiplied by -1
                    #   otherwise implicitly return n

```
> 1 votes

# Answer
# , 62 bytes

```
\(a,b,`?`=length)`if`(k<-?b,(l=k/?a)*(-1)^any(a!=b[!1:l-1]),0)

```

Attempt This Online!

Test setup stolen from pajonk's R answer.
> 1 votes

---
Tags: code-golf, string, number, arithmetic
---


title: Tips for golfing in Elixir

text:
# Question
Title: Tips for golfing in Elixir
Elixir is a relatively new functional language, which I've taken a deep interest in. I'd like to get general tips about golfing in Elixir and learn techniques that can be applied to code-golf problems that are somewhat specific to Elixir in general.

---

*Based on so many similar questions about Python, Ruby, Javascript, etc. I'll also try to post tips as I learn more about the language.*

# Answer
### Don't use the Pipe operator or parenthesis for calling methods

```
# With Pipe
arg |> M.a |> M.b |> M.c   # 24 Bytes
arg|>M.a|>M.b|>M.c         # 18 Bytes

# With Parenthesis
M.c(M.b(M.a(arg)))         # 18 Bytes

# Only Spaces
M.c M.b M.a arg            # 15 Bytes

```
> 2 votes

# Answer
### String and char arguments don't need spaces

For example, `IO.puts"Hello, World!"` and `IO.puts'cat'` are valid programs.
> 2 votes

# Answer
## Inject code into strings

Instead of concatenating something into a string, like:

```
"prefix"<>code<>"suffix"

```

You can use `#{}` to insert it into the string:

```
"prefix#{code}suffix"

```

This will save 3 bytes.
> 2 votes

# Answer
# Avoid arrow functions where possible

...and use the `&<func>(&1,&2...)` notation. For example:

```
each 0..25,fn x->IO.puts slice(concat(a,a),x,26) # 48 bytes
each 0..25,&IO.puts slice(concat(a,a),&1,26)     # 44 bytes

```
> 2 votes

# Answer
### Map Arguments don't need spaces either

Like LegionMammal978's answer, you can leave out space when passing Map as an argument to a method:

```
IO.inspect%{a: 1,b: 2}

```
> 1 votes

# Answer
# `use Bitwise`

Say you want to import the module `Bitwise`, usually you would do:

```
import Bitwise

```

But there may be an alternative that works in some versions of Elixir:

```
use Bitwise

```

to save 3 bytes!

Even better if your only using a bit wise operator once, you can do:

```
Bitwise.&&&()

```

`&&&` being one of the many bitwise operators useable.
> 1 votes

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


title: Round to nicer numbers

text:
# Question
Title: Round to nicer numbers
The standard way to round numbers is to choose the nearest whole value, if the initial value is exactly halfway between two values, i.e. there is a tie, then you choose the larger one.

However where I work we round in a different way. Everything is measured in powers of two. So wholes, halves, quarters, eights, sixteenths etc. This means our measurements are always a binary fraction. We also round to binary fractions. However when the value is exactly halfway between, instead of rounding up we round to the "nicer" number.

For example if I measure 5/8 but I need to round it to the nearest fourth, both 2/4 and 3/4 are equally close to 5/8, but 2/4 = 1/2 which is a nicer number so we round to 1/2. If I measured 7/8 and needed to round to the nearest fourth I would round up to 8/8 = 1.

To put it concretely if we express every number as \\$x\times2^n\\$ where \\$x\\$ is odd, then we round towards the number with the larger \\$n\\$.

Going back to the example: I measure 5/8 and I need to round it to the nearest fourth. The values I can choose are \\$2/4=1\times2^{-1}\\$ and \\$3/4=3\times 2^{-2}\\$, since -1 is larger than -2 we round towards that.

When both the options are fully reduced fractions you can think of this as rounding towards the fraction with the smaller denominator. However this intuition becomes a little bit strained when the options are whole numbers.

## Challenge

In this challenge you will receive 3 numbers. An odd positive integer \\$x\\$, an integer \\$n\\$ and an integer \\$m\\$. You must round \\$x\times2^n\\$ to the nearest integer multiple of \\$2^m\\$ using the process described, and output the result as a binary fraction. This can be either a native binary fraction or the \\$x\times2^n\\$ format used for the input. The input will always be fully reduced so that the numerator, \\$x\\$, is odd, however you are not required to do so for your output.

This is so the goal is to minimize the size of your source code as measured in bytes.

## Test cases

| \\$x\\$ | \\$n\\$ | \\$m\\$ |  | \\$x\\$ | \\$n\\$ |
| --- | --- | --- | --- | --- | --- |
| 5 | -3 | -2 |  | 1 | -1 |
| 3 | -1 | -3 |  | 3 | -1 |
| 9 | -3 | 0 |  | 1 | 0 |
| 1 | 3 | 4 |  | 0 | 5 |
| 1 | 4 | 4 |  | 1 | 4 |
| 3 | 3 | 4 |  | 1 | 5 |

# Answer
> 9 votes
# Wolfram Language (Mathematica), 18 bytes

```
Round[2^#2#,2^#3]&

```

Try it online!

Returns a binary fraction. By default, the built-in `Round` rounds to even.

# Answer
> 5 votes
# C (GCC), ~~53~~ 51 bytes

*-2 bytes thanks to @ceilingcat*

```
f(x,n,m)int*n,*x;{for(;*n<m;++*n)*x+=*x&(*x/=2)%2;}

```

Attempt This Online!

# Answer
> 4 votes
# , 39 32 bytes

```
((]*%<.@+1r2*2|<.@%)2&^)~(*2&^)/

```

Try it online!

*-7 thanks to the round toward even idea from att's Wolfram answer*

Divide \\$x2^n/2^m\\$, manually round toward even, then multiply back \\$2^m\\$.

# Answer
> 4 votes
# , 29 bytes

```
\(x,n,m)c(round(x*2^n/2^m),m)

```

Attempt This Online!

Based on @att's answer and similar `round` behaviour in R.

Outputs non-reduced answers in `(x,n)` format.

# Answer
> 3 votes
# Rust, ~~55~~ 51 bytes

```
|x,n,m|((n..m).fold(x,|x,_|x/2+(x&1&x/2)),m.max(n))

```

Attempt This Online!

Copied from @matteo\_c's C answer

# Answer
> 2 votes
# Retina 0.8.2, 214 bytes

```
\d+
$*
,(1+),(?!1\1).*
,$1
,(-1+),\1.*
,$1
,(-1+)(1+),\1
,0$2,$1
,-(1+),(1*)
,0$1$2,$2
,(1*),\1(1+)
,0$2,$1$2
+`01
100
\G1(?=.*0)
0
(?=0+,1+(0+))\1
1
^(?=1*0*,1+(0+)\1)(11)*.\1
1$&
(1*)0*,(1+0+,)?(-?)(1*)
$.1,$3$.4

```

Try it online! Link includes test cases. Output is not normalised and input is not required to be normalised either. Explanation:

```
\d+
$*

```

Convert to unary.

```
,(1+),(?!1\1).*
,$1
,(-1+),\1.*
,$1

```

If `n` is greater than `m` then just delete `m`. Most of the rest of the code will then do nothing.

```
,(-1+)(1+),\1
,0$2,$1
,-(1+),(1*)
,0$1$2,$2
,(1*),\1(1+)
,0$2,$1$2

```

Subtract `n` from `m`, adjusting for their signs.

```
+`01
100

```

Calculate `2` to that power.

```
\G1(?=.*0)
0
(?=0+,1+(0+))\1
1

```

Divmod `x` by that.

```
^(?=1*0*,1+(0+)\1)(11)*.\1
1$&

```

If the remainder is at least half (for odd results) or more than half (for even results) then add another `1` to the result.

```
(1*)0*,(1+0+,)?(-?)(1*)
$.1,$3$.4

```

Convert to decimal.

# Answer
> 1 votes
# Charcoal, 31 bytes

```
ＮθＮηＮζ≧×Ｘ²⁻ηζθ≧⁺∧⁻﹪θ²⊘¹⊘¹θＩ⟦⌊θζ

```

Try it online! Link is to verbose version of code. Output is not normalised and input is not required to be normalised either. Explanation:

```
ＮθＮηＮζ

```

Input `x`, `n` and `m`.

```
≧×Ｘ²⁻ηζθ

```

Scale `x` by `2ⁿ⁻ᵐ`.

```
≧⁺∧⁻﹪θ²⊘¹⊘¹θ

```

Prepare to floor `x`, but if its remainder modulo `2` is not `0.5`, add `0.5` so that it gets rounded instead.

```
Ｉ⟦⌊θζ

```

Output `x` and `m`.

# Answer
> 0 votes
# 05AB1E (legacy), 7 bytes

```
o*Io/ò‚

```

Port of *@pajonk*'s R answer, which is based on *@att*'s Wolfram Language answer.

Inputs in the order \\$n,x,m\\$; outputs as pair \\$\[n,x\]\\$. Just like the ported R answer, it does no additional reduction to its simplest form.

Try it online or verify all test cases.

**Explanation:**

Uses the legacy version of 05AB1E (built in Python), where `ò` does banker's rounding. In the new version of 05AB1E (built in Elixir), `ò` seems to be a regular rounding builtin, using the 'away from zero' convention for rounding halves.

```
o        # Take 2 to the power of the first (implicit) input `n`
 *       # Multiply it to the second (implicit) input `x`
  Io     # Push 2 to the power of the third input `m` as well
    /    # Divide the earlier x*2**n by this 2**m
     ò   # Banker's round it to the nearest integer
      ‚  # Pair it with the (implicit) third input `m`
         # (after which this pair is output implicitly as result)

```

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

```
(x,n,m)=>x*2**(n-m)*N/N;N=3e-324

```

Try it online!

Take `x,n,m`, return new `x` and set new `n` to input `m`

# Answer
> 0 votes
# Thunno, \\$ 12 \log\_{256}(96) \approx \\$ 9.88 bytes

```
2@*z22@/ZvZP

```

Attempt This Online!

Port of Kevin Cruijssen's 05AB1E (legacy) answer, which is a port of pajonk's R answer, which is based on att's Mathematica answer.

Thunno is also built in Python so the rounding will work as intended.

```
2@*z22@/ZvZP  # Implicit input
2@            # Raise 2 to the power of the first input, n
  *           # Multiply with the second input, x
   z22@       # Push 2 to the power of the third input, m
       /      # Divide x*2**n by 2**m
        Zv    # Round to the nearest integer
          ZP  # Pair with the third input, m
              # Implicit output

```

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


title: Calculate the area of a regular polygon

text:
# Question
Title: Calculate the area of a regular polygon
## Task

Given an integer, `n`, where `3 <= n < 2^32`, calculate the area of a regular `n`-gon, with an apothem of 1, using the formula `A = n * tan(π / n)`.

> The apothem of a regular polygon is a line segment from the center to the midpoint of one of its sides.

Output the area of this regular polygon as a floating point value showing no fewer than eight decimal places (i.e. `1.24217000`, `3.14159265`).

## Tests

```
In: 3
Out: 5.1961524227

In: 6
Out: 3.4641016151

In: 10
Out: 3.2491969623

In: 20
Out: 3.1676888065

In: 99
Out: 3.1426476062

In: 1697
Out: 3.1415962425

In: 15000
Out: 3.1415926995

```

Note: The output values in the sample cases above each show ten decimal places -- two more than required.

# Answer
> 9 votes
# Mathematica, 16 bytes

```
N[Tan[Pi/#]#,9]&

```

Try it online!

of course mathematica has built-ins for this

```
Area@*RegularPolygon

```

# Answer
> 7 votes
# Actually, 5 bytes

```
╦/Tß*

```

Try it online!

---

# How?

```
╦/Tß*   Full program.

╦       Push Pi.
 /      Divide ^ by the input.
  T     Tangent.
   ß*   Multiply by the input.
        Output implicitly.

```

Alternative: `ß╦/T*`. o\_O Actually actually beats Jelly!!!

# Answer
> 7 votes
# Java (OpenJDK 9), 24 bytes

```
i->i*Math.tan(Math.PI/i)

```

Try it online!

# Answer
> 4 votes
# x87 Machine Code, 11 bytes

```
D9 EB
DA 31
D9 F2
DD D8
DA 09
C3

```

The above bytes of code define a function that calculates the area of a regular n-gon with an apothem of 1. It uses x87 FPU instructions (the classic floating-point unit on the x86 processors) to do this computation.

Following a standard x86 register-based calling convention (in this case, `__fastcall`), the function's argument is a pointer to the integer, passed in the `ECX` register. The function's result is a floating-point value, returned at the top of the x87 floating-point stack (register `ST0`).

**Try it online!**

**Ungolfed assembly mnemonics:**

```
D9 EB  fldpi                  ; load constant PI at top of FPU stack
DA 31  fidiv DWORD PTR [ecx]  ; divide PI by integer input (loaded from pointer
                              ;   in ECX), leaving result at top of FPU stack
D9 F2  fptan                  ; compute tangent of value at top of FPU stack
DD D8  fstp  st0              ; pop junk value (FPTAN pushes 1.0 onto stack)
DA 09  fimul DWORD PTR [ecx]  ; multiply by integer input (again, loaded via ECX)
C3     ret                    ; return control to caller

```

As you can see, this is basically just a straightforward computation of the given formula,
*result = n * tan(π / n)*
Only a couple of interesting things bear pointing out:

* The x87 FPU has a dedicated instruction for loading the constant value PI (`FLDPI`). This was rarely used, even back in the day (and obviously much less so now), but it's shorter in size than embedding a constant into your binary and loading that.
* The x87 FPU instruction to calculate tangent, `FPTAN`, replaces the value of the input register (the top of the FPU stack) with the result, but *also* pushes a constant 1.0 onto the top of the FPU stack. This is done for backwards compatibility with the 8087 (I have no idea why this was done on the 8087; probably a bug). That means we need to pop this unneeded value off of the stack. The fastest and shortest way to do that is a simple `FSTP st0`, like we use here. We could have also done a multiply-and-pop, since multiplying by 1.0 won't change the result, but this is also 2 bytes (so no win in code size), will probably execute more slowly, and may introduce unnecessary indeterminacy into the result.

Although a modern programmer or compiler would use the SSE (and later) instruction set, rather than the aging x87, this would require more code to implement, as there's no single instruction to compute a tangent in these newer ISAs.

# Answer
> 3 votes
# Jelly, 6 bytes

```
ØP÷ÆT×

```

Try it online!

Jelly's π builtin has \>8 decimal places.

# Answer
> 3 votes
# Brachylog, 9 bytes

```
;π/₍*₄;?×

```

Try it online!

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

```
x=>x*Math.tan(Math.PI/x)

```

---

## Try it

```
o.innerText=(f=
x=>x*Math.tan(Math.PI/x)
)(+i.value);oninput=_=>o.innerText=f(+i.value)
```

```
<input id=i min=3 type=number value=3><pre id=o>
```

# Answer
> 3 votes
## Sakura, 4 bytes

```
*ĳ/π

```

This is expanded to `*ĳ/π⓪⓪`, which is

```
*              *
 ĳ     tan(   )
  /         /
   π       π
    ⓪        n
     ⓪          n

```

# Answer
> 3 votes
# , 25 bytes

```
cat((n=scan())*tan(pi/n))

```

Input from stdin, output to stdout.

Try it online!

# Answer
> 2 votes
# Japt, 7 bytes

```
*MtMP/U

```

Test it

---

## Explanation

Just implements the forumla, where `Mt` is tan, `MP` is pi and `U` is the input.

# Answer
> 2 votes
# MATL, 7 bytes

```
YPy/Z,*

```

Try it online!

# Answer
> 2 votes
# Ohm v2, 7 bytes

```
απ/ÆT³*

```

**Try it online!**

---

# How?

```
απ/ÆT³*   Full Program

απ        Push Pi.
  /       Divided by the input.
   ÆT     Tangent.
     ³*   Multiplied by the input.
          Implicitly output.

```

# Answer
> 2 votes
# Perl, 14 + 16 = 30

```
perl -MMath::Trig -ple'$_*=tan(pi/$_)'

```

14 bytes for the program proper, and 16 for the command line switches

# Answer
> 2 votes
# var'aq, 51 bytes

```
'Ij latlh HeHmI' tam boqHa''egh qojmI' boq'egh cha'

```

## Explanation

```
'Ij        - read from STDIN
latlh      - duplicate top of stack
HeHmI'     - push PI onto stack
tam        - swap first 2 elements on stack
boqHa''egh - divide
qojmI'     - take tangent
boq'egh    - multiply
cha'       - print

```

# Answer
> 2 votes
# Common Lisp, 29 bytes

```
(lambda(n)(* n(tan(/ pi n))))

```

Try it online!

# Answer
> 1 votes
# Python 2, 45 bytes

```
from math import*
n=input()
print n*tan(pi/n)

```

Try it online!

# Answer
> 1 votes
# Pyth, 9 bytes

```
*.tc.n0Q2

```

**Test suite.**

---

# How?

```
*.tc.n0Q2    Full program. Q means input.

    .n0      Pi.
   c         Divided by:
       Q     The input.
 .t     2    Tangent.
*        Q   Multiply by the input.
             Output implicitly.

```

# Answer
> 1 votes
# Gaia, 5 bytes

```
₵P÷ṫ×

```

Try it online!

---

# How?

```
₵P÷ṫ×   Full program.

₵P      Push Pi.
  ÷     Divided by the input.
   ṫ    Tangent.
    ×   Multiply by the input.

```

# Answer
> 1 votes
# Swift, 35 bytes

With compiler warnings:

```
import Foundation
{tan(M_PI/$0)*$0}

```

**Try it here!**

Without compiler warnings, **40 bytes**:

```
import Foundation
{tan(Double.pi/$0)*$0}

```

# Answer
> 1 votes
# Excel, 16 bytes

```
=A1*TAN(PI()/A1)

```

# Answer
> 0 votes
# RPNGolf 0.6/0.7, 12 bytes

```
tbp-1mBsdmcc

```

My first post using RPNGolf, my new stack-based language!

This is a full program that reads an integer from standard input and prints the output to standard output (without a trailing newline).

Explanation:

```
tb              # push user input from STDIN as int
  p             # duplicate top of stack
   -1           # push -1
     mB         # pop i, push inverse cosine of i
       s        # swap top two items on the stack
        d       # pop b, pop a, push a/b
         mc     # pop i, push tangent of i
           c    # pop b, pop a, push a*b
# RPNGolf implicity prints the stack upon normal exit

```

# Answer
> 0 votes
# Prolog (SWI), 25 bytes

```
f(X,Y):-X is Y*tan(pi/Y).

```

Try it online!

This is my first submission to codegolf, hope I'm doing alright. Written as a function.

# Answer
> 0 votes
# IBM/Lotus Notes Formula Language, 13 bytes

```
a*@Tan(@Pi/a)

```

Input taken via a field named a on the same form as the field containing the formula. No TIO available so screenshot of all test cases shown below:

# Answer
> 0 votes
# PowerShell, 38 bytes

```
param($n)$n*[math]::tan([math]::pi/$n)

```

Try it online!

Does exactly what it says on the tin, just takes a little longer due to the lengthy `[math]::` .NET calls.

# Answer
> 0 votes
# Ruby, 27 bytes

```
->n{n*Math.tan(Math::PI/n)}

```

Try it online!

# Answer
> 0 votes
# C# (Mono C# compiler), 24 bytes

```

=>n*Math.Tan(Math.PI/n)

```

Try it online!

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

```
n->tan(Pi/n)*n

```

Try it online!

# Answer
> 0 votes
# Factor, 19 bytes

```
[ pi over / tan * ]

```

Try it online!

# Answer
> 0 votes
# 05AB1E, 7 bytes

```
žqI/Å¼*

```

Try it online or verify all test cases.

**Explanation:**

```
žq       # Push PI (3.141592653589793)
  I/     # Divide it by the input
    Å¼   # Get the tangent of this
      *  # Multiply it by the (implicit) input
         # (after which the result is output implicitly)

```

# Answer
> 0 votes
# Pyt, 6 bytes

```
Đπ/⅟ť*

```

Try it online!

```
Đ            implicit input (n); duplicate on stack
 π           push pi
  /          divide n by pi
   ⅟         take the reciprocal
    ť        tan(pi/n)
     *       multiply by n; implicit print

```

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


title: Tips for golfing in ><> (Fish)

text:
# Question
Title: Tips for golfing in ><> (Fish)
Since I've been seeing more \>\<\> submissions floating around lately, I thought it might be a good idea to have a tips page.

Please stick to one tip per post, unless they are closely related.

Official Python interpreter

Official Interpreter on TIO

Online interpreter (some bugs present, but good for most cases)

Another Online Interpreter

# Answer
> 5 votes
# Checking against 0

Using `?!` instead of `0=?` typically saves a byte.

However, just a standard `?` may sometimes be better if you can afford a bit of restructuring

```
?!vA
  B

```

versus

```
?vB
 A

```

# Answer
> 4 votes
# Checking for EOF

When EOF is reached, \>\<\> pushes a -1 onto the stack, which can be checked in one of two ways:

```
:0(?
:1+?

```

For the purposes of checking for EOF, these two are negations, so which one is more beneficial depends on the structure of your program.

# Answer
> 4 votes
# Jump to circumvent starting new lines

Starting a new line sometimes means wasting a lot of leading whitespace on the next line. In such a situation, jumping can be useful.

For instance,

```
[lots of code here]>[loop body]v
                   ^ ......... <

```

can be made to fit on one line like so:

```
[lots of code here][loop body][jump]

```

For a practical example, here's the Hello World program on one line:

```
"!dlroW ,olleH"l?!;oe0.

```

# Answer
> 4 votes
## Using jumps as a conditional

Some times you'll wind up writing programs in \>\<\> that require you to do different things upon receiving different inputs. Usually, you'd use conditionals (`?`) and direction changers to parse this. In some cases, that works fine (especially when there are fewer types of input to handle), but sometimes you end up with something looking like this. (Ignore the fact that this code can be reduced using some other tricks, it's just for demonstration)

```
i:"a"=?v:"b"=?v"c"=?v>
  .00n1< .00n2<.00n3<

```

While this is fine, it does have some whitespace (which I personally never like seeing) and it has a lot of repetition (`=?v` and `.00n`). Instead of that, you could use a jump and different lines as your conditionals. Here's an example:

```
i:"a")$"b")+1+0$.>
v1
v2
v3
<.00n

```

This shaves 10 bytes off. Here's what's happening:

`i:` We duplicate the input once so we can evaluate it twice

`"a")$"b")+` This could be its own sort of tip, but what I'm doing here is checking to see if the input is greater than the character "a" and then if it's greater than the character "b" and adding the result. For "a," this will yield 0, for "b," 1, and for "c," 2.

`1+0$.` This is where the magic happens; we take the result of this previous simplification and add 1 (giving 1 for "a", 2 for "b", 3 for "c"), then push 0 and swap the values. When we reach the jump, this will move to the line corresponding to the value we've assigned to those characters (e.g. line 1 for "a"). N.B. Line 0 is the top of the program.

# Answer
> 3 votes
## Using modulus to simplify input

This might be too simple of a tip, so if it is I'll just replace it or delete it.

Let's say you want to take input of two characters, "a" and "b" and return 1, and 2 for each, respectively. You'd probably use conditionals for this, since it makes the most sense, and I'll be using a more condensed form for this specific example.

```
i:"a")+1+n

```

This checks to see if the input is greater than "a" and adds 1. Since "a" will return 0 and "b" 1, this will give 1 and 2. This does the job pretty well, but in the case of our inputs, we could go even further.

```
i:3%n

```

In mod 3, 97, which is "a"s numerical equivalent, becomes 1, and 98, which is "b"s, becomes 2. For two different numbers, there is guaranteed a mod which gives unique results for both. For more than two, there is a mod that gives unique results, but I don't have the mathematical prowess to find the smallest one in a simple way (e.g. if you have the set {100,101,102,103}, mod 104 would give unique results for each value in it but not in a very helpful fashion). However, in most cases, with input being restricted to a couple alphabetical characters, you can often find a mod that works.

To find the smallest modulus that yields unique results for two numbers, a, and, b, you do as follows. Take the absolute value of the difference of a and b (`|a - b|`) and find the smallest number, n, which does not divide it. e.g. for 97 and 98, `|98 - 97| = 1`, and so 2 would be the smallest mod (but for our test program, this gives 1 for 97 and 0 for 98, so mod 3 is better).

# Answer
> 3 votes
# Writing code that can run two ways

Trampolines (`!`) are very handy when you want your code to be run forwards and backwards (or up and down). These scenarios are somewhat unlikely, but for palindrome or similar challenges this tip could be useful.

Here's an example: I want to run some code once, then loop through the stack discarding values until I reach 0, and then go down. The pointer enters this loop from the `>`. You could use a jump to accomplish this, e.g.

`?!v80.>ao` (let's say I want to print a newline first)

but if the code we want to run once (the code past the `>`) makes the line longer than 16 characters, we no longer can use the jump in three characters. However, this is an example where it is trivial to run forwards and backwards...

`?!v!?<>ao>`

Going forwards, we print a newline and then hit `?!v` which discards the value if it it isn't 0, then because of the trampoline we skip the next `?` and go backwards. The same thing happens and the loop continues until we hit a 0.

This is an oddly specific example, but there are some (perhaps not many) applications.

# Answer
> 3 votes
## Use char codes to store big numbers and use `g` to use them more than once

Typically, you'd encode a large number as a char code, for example if you need `1001` you might write `'ϩ'` In utf-8 this character is encoded as 2 bytes. If you need this number again you can use `[coordinates]g` to get the char code at that position. This saves 1 byte as long as the character is in the 16 by 16 top left square.

For example

```
'ϩ'o'ϩ'o;

```

vs

```
'ϩ'o10go;

```

Same number of characters but 1 byte shorter

# Answer
> 2 votes
# Use the code as infinite length array

You can store values in the source code area with the `g` and `p` commands. For example, you could use the 7th row as a array and access it like this:

`i3g`

This is significantly shorter than if you used the stack:

`i[{:}]`

The stack has a additional disadvantage is you need to compensate for any other data you want on the stack. The code box is always accessible regardless of the state of your stack. You can also easily create multiple arrays, or even a 2-dimentional array this way.

You don't even need to keep the row free, \>\<\> will automatically add rows or columns when you write to them. You can read and write any number, even those not normally valid in source code, like line breaks and floating point numbers. This is a valid program that prints `0.5`:

```
12,00p00gn;

```

Even if there is no character "0.5". This does not seem to work the same for strings.

# Answer
> 2 votes
# Use `i` as a shorthand for `-1` for programs that take no input, or after the input is exhausted

Pusing `-1` is always a bit tricky, requiring `01-` (3 bytes). However, the `i` command pushes `-1` if there is no input. This can save 2 bytes.

For example to invert a number normally requites `0$-` (3 bytes) but if you don't take input you can do `i*` (2 bytes)

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


title: Fewest dice rolling as dice rolling

text:
# Question
Title: Fewest dice rolling as dice rolling
Related

Now you have some dice which you may roll several times. You need a uniform random integer between 1 and \\$n\\$, inclusive. Show a method that rolls the fewest times and behaves as an \\$n\\$-sided dice.

Alternative question: Given a set \\$S\\$ and \\$n\\$, pick the fewest elements from \\$S\\$(each element can be picked multiple times), such that their product is a multiple of \\$n\\$.

Output some unambigious constant or crash (but not infinite loop) if it's impossible.

Test cases:

```
S, n => possible result
{6}, 9 => {6,6}
{2,3}, 12 => {2,2,3}
{2,8}, 4 => {8}
{6}, 1 => {}
{2}, 6 => -1
{12,18}, 216 => {12,18}
{12,18}, 144 => {12,12}
{18}, 144 => {18,18,18,18}

```

Shortest code in each language wins.

# Answer
# JavaScript (ES6), 104 bytes

Expects `(S)(n)`. Returns either a string such as `"2*2*3"` or *false* if there's no solution.

```
(a,N=0)=>F=n=>(g=(b,q=N)=>q&&b.some(s=>eval((o=s)||1)%n<1|g(a.map(v=>s?s+'*'+v:v),q-1)))``?o:N++<n&&F(n)

```

Try it online!
> 4 votes

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

```
s=>g=(t,[p,...r]=[1],...a)=>p%t?!r[t]&&g(t,...a,...s.map(v=>[p*v,...r,v])):r

```

Try it online!

```
s=> // set of dices
  g=(
  t, // target point
  [p, // product of currently selected dices
   ...r // array of currently selected dices
  ]=[1], // initially, we do not select any dices, and the product is 1
  ...a // any other candidate selections
)=>
  p%t? // if current select is invalid
    !r[t]&& // if we already used more than `t` dices
            // we know we cannot get `t` with current set
            // return `false`
    g(t,...a,...s.map(v=>[p*v,...r,v])): // for each candidate dice
                                         // try it recursively
  r // return current selected dices

```

---

# Python 3, 86 bytes

```
f=lambda s,t,p=1,r=[],*a:t<len(r)or p%t and f(s,t,*sum([(p*i,r+[i])for i in s],a))or r

```

Try it online!

Just a port to Python. Or 84 bytes but very slow...
> 4 votes

# Answer
# Pyth, ~~16~~ 11 bytes

```
hf!%*FTQy*E

```

Try it online!

Takes n and S in that order. Outputs a list or throws an index error if there is no solution.

### Explanation

We simply check all possible combinations of elements from \\$S\\$ up to \\$n-1\\$ elements (as well as many other pointless longer ones) and take the shortest one which works. Saved 5 bytes thanks to @Kevin Cruijssen's trick of using the powerset of input list repeated, however this comes at the cost of being even slower. This times out for large \\$n\\$, but can be made much better by adding a logarithm to that range as seen here, at the cost of a few bytes.

```
hf!%*FTQy*EQ    # implicitly add Q
                # implicitly assign Q = eval(input())
         *EQ    # repeat the second eval(input()) Q times
        y       # powerset
 f              # filter on lambda T
    *FT         #   multiply all elements of T (or 1 for empty list)
   %   Q        #   modulo by Q
  !             #   not (will be true for 0)
h               # first element (will be the shortest list, or will raise an index error if there are none)

```
> 3 votes

# Answer
# Vyxal , 12 bytes

```
(⁰n↔≬Π¹Ḋc:[X

```

Try it Online!

Half port of the pyth answer in that it checks all combinations of length 0 to n-1. Returns 0 for invalid, otherwise the list.

## Explained

```
(⁰n↔≬Π¹Ḋc:[X
(             # For N in range(0, n):
 ⁰n↔          #   get all combinations of S of length N
    ≬   c     #   find the first combination where
     Π        #     the product
      ¹Ḋ      #     is divisible by n
         :[X  #   if it's non-empty break from the loop

```
> 3 votes

# Answer
# 05AB1E, 8 bytes

```
иæé.ΔP¹Ö

```

Will output `-1` if no result can be found.

The larger \\$n\times L\_S\\$ (where \\$L\_S\\$ is the length of set \\$S\\$), the slower it is.

Try it online or verify most test cases. (The test cases that time out have been ommitted.)

**Explanation:**

```
и         # Repeat the second (implicit) input-list the first (implicit) input-integer
          # amount of times as single flattened list
 æ        # Get the powerset of this list
  é       # Sort it by length (shortest to longest)
   .Δ     # Find the first list that's truthy for (or -1 if none are):
     P    #  Take the product of the list
      ¹Ö  #  Check whether it's divisible by the first input-integer
          # (after which the found result is output implicitly)

```
> 2 votes

# Answer
# Python, 135 134 bytes

```
lambda s,n:[x for i in range(n)for x in combinations_with_replacement(s,i)if not math.prod(x)%n][0]
from itertools import*
import math

```

Attempt This Online!

Works like the Pyth answer

-1 thanks to @corvus\_192
> 1 votes

# Answer
# Charcoal, 42 bytes

```
¿¬﹪ＸΠθηη«⊞υ⟦⟧Ｗ⬤υ﹪Πκη≔ΣＥυＥθ⁺κ⟦μ⟧υ⭆¹⌊Φυ¬﹪Πλη

```

Attempt This Online! Link is to verbose version of code. Outputs nothing if no solution exists but `[]` for an input of `1`. Explanation:

```
¿¬﹪ＸΠθηη«

```

Check that a solution exists.

```
⊞υ⟦⟧

```

Start with all possible results of length `0`.

```
Ｗ⬤υ﹪Πκη

```

While none of the results work...

```
≔ΣＥυＥθ⁺κ⟦μ⟧υ

```

... form the Cartesian product of the results with the input list.

```
⭆¹⊟Φυ¬﹪Πλη

```

Pretty-print the first working result.
> 1 votes

# Answer
# C (GCC), 150 bytes

```
int*f(s,k,n,p,v,w)int*s,*v,*w;{for(v=calloc(n,4);p=1;){for(w=v;*w;)p*=s[*w++-1];if(p%n<1){for(w=v;*w;)*w++=s[*w-1];return v;}for(w=v;++*w>k;)*w++=0;}}

```

Attempt This Online!

Eventually segfaults if the problem is impossible.

Takes O(|S|n) time if there is a solution, and Ω(|S|n) otherwise. The exponent of such bounds can be lowered to ⌈log2 n⌉ at the cost of more bytes.
> 0 votes

# Answer
# Haskell, 62 bytes

```
s#n=head[o|i<-[0..n],o<-mapM id(s<$[1..i]),mod(product o)n==0]

```

Try it online!

# Haskell, 66 bytes

```
s#n=head[o|i<-[0..n],o<-sequence.replicate i$s,mod(product o)n==0]

```

Try it online!

# Haskell, 91 bytes

```
import Data.List
_#1=[]
s#n=let g=gcd n;m=last(sortOn g s)in m:(filter((1<).g)s#div n(g m))

```

greedily includes the dice with maximum greatest common denominator and recurses down target divided by that common denominator on all dice with common denominator, crashes when depleted of feasible dice, generates some too long solutions.

Try it online!
> 0 votes

---
Tags: code-golf
---