title: Simple Factorial Challenge

text:
# Question
Title: Simple Factorial Challenge
In light of today's date...

A factorial of a number n, is the product of all the numbers from 1 to n inclusive.

## The Challenge

Given an integer n where 0 \<= n \<= 420, find the sum of the digits of n!. It's that simple :P

*Notes: I feel like this challenge isn't too simple, as some languages have a very hard time storing numbers that are fairly large. Also, coding a BigInteger datatype is fairly straightforward, but hard to golf.*

---

## Examples

> Input: 100. Output: 648.
>
> Input: 200. Output: 1404.
>
> Input: 420. Output: 3672.

---

## Scoring

* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

EDIT: Ok, I guess it's actually easy...take a look at the Jelly answer below. Anyways, I guess we all know which one's going to be accepted. But, I'd still like to see some interesting ideas and tricks to this problem!

# Answer
> 4 votes
# Neim, 2 bytes

```

```

Explanation: Factorial ; sum .

This outgolfs 3-byte answers as the sum command is able to implicitly convert to a list.

Try it online!

# Answer
> 5 votes
# (old problem) JavaScript (Node.js), ~~99~~ ~~94~~ ~~92~~ ~~88~~ ~~86~~ ~~83~~ ~~80~~ 78 bytes

```
f=(x,t=[...21+Array(999)])=>x?f(s=x-1,t.map(d=>-s+(s+=(t=~~d*x+t/10|0)%10))):s

```

Try it online!

well, first language without large number support

Thank Arnauld for 4 bytes

```
f = (x, t = ['2', '1', ...','.repeat(998)]) => // init x, t=1
  x ?
    f( // recursive x':=x-1, t'=t*x
      s = x-1, // s init to 0 when x==1, in next recursion just return
      t.map (
        b = // init b to NaN
        d =>
          -s + ( //  to return the added value
            s+= ( // -s + (s + k) == k
              b=
                ~~d*x+b/10 | 0
                // ~~d converts ',' to 0
                // b is initally NaN, after first iteration
                // it's zero, then the last digit sum result with carry
            ) % 10
          )
      )
    )
:
  s // the sum from x==1

```

# Answer
> 4 votes
# Wolfram Language (Mathematica), 24 bytes

```
Total@IntegerDigits[#!]&

```

Try it online!

# Answer
> 4 votes
# Haskell, 42 40 38 bytes

```
f n=sum[read[d]|d<-show$product[1..n]]

```

Try it online!

Thanks to @Laikoni for saving 2 bytes with list comprehension.

# Answer
> 4 votes
# 05AB1E, 3 bytes

```
!SO

```

Try it online!

**Explanation**

```
!     # factorial of input
 S    # split to list of digits
  O   # sum

```

# Answer
> 3 votes
# Attache, 11 bytes

```
Sum@List@`!

```

Try it online!

`Sum`s the `List` of digits in the factorial (`!`) of the input. Anonymous function.

# Answer
> 3 votes
# Pari/GP, 16 bytes

```
n->sumdigits(n!)

```

Try it online!

# Answer
> 3 votes
# , 13 11bytes

```
1#.,.&.":@!

```

Try it online!

## Explanation:

`!` calculate the factorial

`@` and

`,.&.":` convert it to a list of digits (convert to string `":`, ravel `,.` and convert each char back to number)

`1#.` find their sum by base-1 conversion

# Answer
> 3 votes
# Perl 6, 21 bytes

```
{[*](2..$_).comb.sum}

```

Try it

## Expanded:

```
{  # bare block lambda with implicit parameter ｢$_｣

  [*](       # reduce using &infix:« * »

    2 .. $_  # Range starting at 2 (slight optimization over 1)

  ).comb     # split the result into digits
  .sum       # find the sum of those digits
}

```

# Answer
> 3 votes
# \+ gmp, 66 bytes

```
sum(strtoi(el(strsplit(paste(gamma(gmp::as.bigz(scan())+1)),""))))

```

Try it online!

`gmp` is one of the several BigInteger packages available on CRAN.

# Answer
> 3 votes
# Python 2, 51 bytes

```
f=lambda L,p=1:0**L*sum(map(eval,`p`))or f(L-1,p*L)

```

Try it online!

We'd like to write `map(int,`p`)`, but since `repr(p)` might have a trailing `L`, that won't work.

Ordinarily, we'd resort to `map(int,str(p))` and lose three bytes.

Here, can we name our counting-down variable `L`, and write `map(eval,`p`)`. Since `L` is 0 when we compute the result, the digit sum is unaffected.

# Answer
> 2 votes
# Jelly, 3 bytes

```
!DS

```

Try it online!

```
!DS        - main link, taking an integer  e.g. 9
!          - factorial                     -->  362880
 D         - convert to decimal            -->  [3,6,2,8,8,0]
  S        - sum of list                   -->  27

```

# Answer
> 2 votes
# Python 2, ~~52~~ ~~54~~ 52 bytes

```
f=lambda n,r=1:1/n*sum(map(int,str(r)))or f(n-1,n*r)

```

Try it online!

-2 bytes thx to Kirill L.

# Answer
> 2 votes
# Bash + GNU utilities, 36

* 6 bytes saved thanks to @Cowsquack

```
seq -s* $1|bc|sed 's/\B\|\\/+&/g'|bc

```

Try it online!

# Answer
> 2 votes
# Pyt, 2 bytes

Try it online!

Explanation:

```
      Implicit input
!     Factorial
Ś     Sum of digits
      Implicit output

```

# Answer
> 2 votes
# Octave with Symbolic Package, ~~43~~ 42 bytes

```
@(s)sum(char(sym(['factorial(' s 41]))-48)

```

Anonymous function that takes the input as a string and outputs a nubmer.

Try it online!

# Answer
> 1 votes
# Charcoal, 7 bytes

```
ＩΣΠ…¹⊕Ｎ

```

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

```
      Ｎ Input as a number
     ⊕  Increment
    ¹   Literal 1
   …    Range
  Π     Product
 Σ      Sum (of digits)
Ｉ       Cast to string
        Implicitly print

```

`InclusiveRange(1, InputNumber())` also works but the explanation is prettier this way.

# Answer
> 1 votes
# Elixir, 54 bytes

```
fn n->Enum.sum Integer.digits Enum.reduce 1..n,&*/2end

```

Try it online!

Ungolfed:

```
def sum_factorial(n) do
  # factorial
  Enum.reduce(1..n, fn(x, acc) -> x * acc end)
  # sum digits
  |> Integer.digits
  |> Enum.sum

```

# Answer
> 1 votes
# C (gcc), 107 bytes

```
f(x){int a[999]={1},i,c;
for(;x;--x)for(c=i=0;i<999;)c=(a[i]=a[i]*x+c)/10,a[i++]%=10;
for(;i--;)x+=a[i];
i=x;}

```

Try it online!

# Answer
> 1 votes
# Husk, 3 bytes

```
ΣdΠ

```

Try it online!

### Explanation

```
ΣdΠ  Implicit input
  Π  Factorial
 d   Convert to list of digits
Σ    Sum

```

# Answer
> 1 votes
# Ruby, 33 bytes

```
->n{(2..n).inject(:*).digits.sum}

```

Try it online!

# Answer
> 1 votes
# Tcl, 78 bytes

```
proc S n {proc F n {expr $n?($n)*\[F $n-1]:1}
expr [join [split [F $n] ""] +]}

```

Try it online!

# Answer
> 1 votes
# Stax, 4 bytes

```
║▼⌡è

```

Run and debug it at staxlang.xyz!

### Unpacked (5 bytes) and explanation

```
|FE|+
|F       Implicit input. Factorial.
  E      Array of decimal digits.
   |+    Sum of list. Implicit print.

```

# Answer
> 1 votes
**Python**, 75 bytes

```
import math
print(sum(map(int,list(str(math.factorial(int(input())))))))

```

# Answer
> 0 votes
# Java 10, 135 bytes

```
n->{var r=java.math.BigInteger.ONE;for(;!n.equals(r.ZERO);n=n.subtract(r.ONE))r=r.multiply(n);return(r+"").chars().map(c->c-48).sum();}

```

**Explanation:**

Try it online.

```
n->{                         // Method with BigInteger parameter and integer return-type
  var r=java.math.BigInteger.ONE;
                             //  BigInteger, starting at 1
  for(;!n.equals(r.ZERO);    //  Loop as long as `n` is not 0 yet
      n=n.subtract(r.ONE))   //    After every iteration: subtract 1 from `n`
    r=r.multiply(n);         //   Multiply `r` by `n`
  return(r+"").chars()       //  Loop over the characters of `r`
              .map(c->c-48)  //   Convert them to digits
              .sum();}       //   And return the sum of those digits

```

# Answer
> 0 votes
## Ceylon, 98 bytes

```
import ceylon.whole{l=one}Integer q(Integer n)=>sum({0,*product({l,*(l:n)}).string*.offset('0')});

```

Try it online

## Explanation:

This is quite long, because we need to convince the compiler that we are not doing bogus stuff.

```
import ceylon.whole { l = one } // 1

Integer q(Integer n) => // 2
    sum({0,*product({l,*(l:n)}).string *.offset('0')});
//  |   |   |       |    '3' || |    | | |         |||
//  |   |   |       '--4-----'| |    | 7 |         |||
//  |   |   '----5------------' '-6--'   '--8------'||
//  |   |   '----------------9---------------------'||
//  |   '----------------10-------------------------'|
//  '------------------------11----------------------'

```
1. Import the value `one` from the package `ceylon.whole`, and give it locally the name `l` (small L, not the digit `1` – though I choose this alias for its similarity to 1). (This alias import costs two bytes here, but saves two bytes for each of the two usages).
2. Define a function `q` from `Integer` to `Integer`, which maps each parameter `n` to the result of the following expression (calculated in steps 3 to 11). Top-level functions always need a type declaration. For local ones we could replace the return type by `function`, which wouldn't have saved anything here. (For inline functions, we sometimes can omit both types and the keyword, if they can be inferred from context.)
3. This is a short syntax for `measure(one, n)`, which returns either the empty sequence `[]` if `n` is non-positive, or a `Range<Whole>` starting from `one` and having size `n` (i.e. all numbers from 1 to n, assuming n is a positive integer). Type: `[]|Range<Whole>`, which is a subtype of `{Whole*}` (possibly empty iterable of Whole).
4. This is an iterable enumeration, with `one` as the first element and then all the elements of `one:n` (the `*` here expands the iterable). This has type `{Whole+}`, and has the only purpose to make sure the compiler knows it is non-empty. We could have used `[...]` instead of `{...}` for a tuple enumeration (which is non-lazy). No difference here apart from performance. We could have written this `(l:n).follow(l)`, but that is longer.
5. Calculate the product of all those numbers, type `Whole`. `product` needs a non-empty iterable as a parameter to work (as the product of nothing is not defineable in a type-independent way).
6. Get the string representation of the result of step 5. (The `.string` attribute exists for all classes, and `Whole` implements it in the expected way, using decimal digits.) – type `String`, which is also a `{Character*}` (possibly empty iterable of characters).
7. The `*.` operator for iterables applies the the following attribute or method call to each element of the iterable and collects the result in a sequence. It can be seen as syntactic sugar for `.collect(c => c.offset('0'))`. This is non-lazily evaluated, there is also `.map(...)` which is lazy.
8. The `offset` method of `Character` just calculates the difference between the unicode code points, returning an `Integer`. This takes advantage of the fact that the ten decimal digits are sequential starting with `0` in ASCII (and thus unicode).
9. This whole thing has now type `[Integer*]` (possibly empty sequence of integers – because the string is possibly empty for the compiler).
10. Same trick again as step 4, we make it an `{Integer+}` (nonempty iterable) by prepending a `0` (which has no effect on the following sum).
11. Sum it all up.

# Answer
> 0 votes
# CJam, 11 8 bytes

there is in fact a better way to get a list of digits

```
lim!Ab:+

```

Try it online!

Explanation:

```
li          input, convert to integer
  m!        factorial
    Ab      convert to array of digits in base 10
      :+    sum

```

---

Original solution:

```
lim!`1/:i:+

```

Explanation:

```
li              input converted to integer
  m!            factorial
    `           convert to string
     1/         split into pieces of length 1
       :i       convert back to integer
         :+     sum

```

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


title: Digit Product Sequences

text:
# Question
Title: Digit Product Sequences
Here's an interesting sequence discovered by Paul Loomis, a mathematician at Bloomsburg University. From his page on this sequence:

Define
`f(n) = f(n-1) + (the product of the nonzero digits of f(n-1))`
`f(0) = x`, with `x` as any positive integer, written in base 10.

So, starting with `f(0)=1`, you get the following sequence
`1, 2, 4, 8, 16, 22, 26, 38, 62, 74, 102, 104, ...`

So far, so standard. The interesting property comes into play when you take any *other* integer as the starting point, eventually the sequence converges into a point along the above `x=1` sequence. For example, starting with `x=3` yields
`3, 6, 12, 14, 18, 26, 38, 62, 74, 102, ...`

Here are some more sequences, each shown only until they reach `102`:

```
5, 10, 11, 12, 14, 18, 26, 38, 62, 74, 102, ...
7, 14, 18, 26, 38, 62, 74, 102, ...
9, 18, 26, 38, 62, 74, 102, ...
13, 16, 22, 26, 38, 62, 74, 102, ...
15, 20, 22, 26, 38, 62, 74, 102, ...
17, 24, 32, 38, 62, 74, 102, ...
19, 28, 44, 60, 66, 102, ...

```

He conjectured, and empirically proved up to `x=1,000,000`, that this property (i.e., that all input numbers converge to the same sequence) holds true.

## The Challenge

Given a positive input integer `0 < x < 1,000,000`, output the number where the `f(x)` sequence converges to the `f(1)` sequence. For example, for `x=5`, this would be `26`, since that's the first number in common to both sequences.

```
 x output
 1 1
 5 26
19 102
63 150056

```

## Rules

* If applicable, you can assume that the input/output will fit in your language's native Integer type.
* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
# JavaScript (ES6), ~~81~~ 67 bytes

*Saved 1 byte thanks to @l4m2*

```
f=(n,x=1)=>x<n?f(x,n):x>n?f(+[...n+''].reduce((p,i)=>p*i||p)+n,x):n

```

Try it online!

### Commented

```
f = (n,                   // n = current value for the 1st sequence, initialized to input
        x = 1) =>         // x = current value for the 2nd sequence, initialized to 1
  x < n ?                 // if x is less than n:
    f(x, n)               //   swap the sequences by doing a recursive call to f(x, n)
  :                       // else:
    x > n ?               //   if x is greater than n:
      f(                  //     do a recursive call with the next term of the 1st sequence:
        +[...n + '']      //       coerce n to a string and split it
        .reduce((p, i) => //       for each digit i in n:
          p * i || p      //         multiply p by i, or let p unchanged if i is zero
        ) + n,            //       end of reduce(); add n to the result
        x                 //       let x unchanged
      )                   //     end of recursive call
    :                     //   else:
      n                   //     return n

```
> 5 votes

# Answer
# Jelly, ~~18~~ 14 bytes

```
ḊḢDo1P+Ʋ;µQƑ¿Ḣ

```

Input is a singleton array.

Try it online!

### How it works

```
ḊḢDo1P+Ʋ;µQƑ¿Ḣ  Main link. Argument: [n]

            ¿   While...
          QƑ      all elements of the return value are unique...
         µ          execute the chain to the left.
Ḋ                     Dequeue; remove the first item.
 Ḣ                    Head; extract the first item.
                      This yields the second item of the return value if it has
                      at least two elements, 0 otherwise.
       Ʋ              Combine the links to the left into a chain.
  D                     Take the decimal digits of the second item.
   o1                   Perform logical OR with 1, replacing 0's with 1's.
     P                  Take the product.
      +                 Add the product with the second item.
        ;             Prepend the result to the previous return value.
             Ḣ  Head; extract the first item.

```
> 4 votes

# Answer
# Python 2, ~~111~~ ~~95~~ 93 bytes

Using unpacking in `replace(*'01')` as in @Rod answer
-18 bytes thanks to @Lynn

```
l=[1,input()]
while cmp(*l):l[0]+=eval('*'.join(`l[0]`.replace(*'01')));l.sort()
print l[0]

```

Try it online!
> 2 votes

# Answer
# Python 2, 78 bytes

```
f=lambda a,b=1:a*(a==b)or f(*sorted([a+eval('*'.join(`a`.replace(*'01'))),b]))

```

Try it online!
> 2 votes

# Answer
# Haskell, 65 bytes

```
(!1)
a!b|a>b=b!a|a<b=(a+product[read[d]|d<-show a,d>'0'])!b|1<2=a

```

Try it online!
> 2 votes

# Answer
# Husk, 13 bytes

```
→UΞm¡S+ȯΠf±dΘ

```

Takes input as a singleton list.

Try it online!

# Explanation

```
                 Implicit input, e.g 5
            Θ    Prepend a zero to get  [0,5]
   m             Map the following over [0,5]
    ¡              Iteratatively apply the following function, collecting the return values in a list
           d         Convert to a list of digits
         f±          keep only the truthy ones
       ȯΠ            then take the product
     S+              add that to the original number
                After this map, we have [[0,1,2,4,8,16,22,26,38,62...],[5,10,11,12,14,18,26,38,62,74...]]
  Ξ             Merge the sorted lists:  [0,1,2,4,5,8,10,11,12,14,16,18,22,26,26,38,38,62,62,74...]
 U              Take the longest unique prefix: [0,1,2,4,5,8,10,11,12,14,16,18,22,26]
→               Get the last element and implicitely output: 26

```
> 2 votes

# Answer
# Python 3, ~~126~~ 125 bytes

```
m=[1]
n=[int(input())]
while not{*m}&{*n}:
 for l in m,n:l+=l[-1]+eval('*'.join(str(l[-1]).replace(*'01'))),
print({*m}&{*n})

```

Try it online!

Take the input as string
> 1 votes

# Answer
# Java (JDK 10), 99 bytes

```
n->{for(int x=1;x!=n;n+=(""+n).chars().reduce(1,(a,b)->a*(b>48?b-48:1)))x^=x<n?n^(n=x):0;return n;}

```

Try it online!

Mostly an iterative port of Arnauld's JavaScript answer, so go upvote him!
> 1 votes

# Answer
# Jelly, 23 bytes

```
ð⁹1,Dḟ0P+Ʋ⁸Ð¡€f/©µ1#ṛ®Ḣ

```

Try it online!
> 0 votes

# Answer
# , 50 bytes

tacit style function definition

```
[:{.@(e.~#])/[:(+[:*/@(*#])(#~10)&#:)^:(<453)"0,&1

```

if the argument (say 63) were pasted into a REPL expression it could be 45 e.g.

```
{.(e.~#])/(+[:*/@(*#])(#~10)&#:)^:(<453)"0]1,63

```
* `,&1` append 1 to generate search sequence as well as argument's sequence
* `^:(<453)"0` iterates each until 1mio is reached in 1's sequence
* `+ [: */@(*#]) (#~10)&#:` fork adds to hook which does the product of digits
* `(e.~ # ])/` uses repeat item if exists to get intersection of lists
* `{.` return only the first common value

Try it online!
> 0 votes

# Answer
# , ~~110~~ 86 bytes

```
o=c(1,1:9);o=o%o%o%o%o;o=c(o%o%o)
x=c(1,n);while((x=sort(x))<x[2])x[1]=(x+o[x+1])[1]
x

```

TIO

**previous version 110:**

```
f=function(x){if((x[1]=x[1]+(c((y=(y=c(1,1:9))%o%y%o%y)%o%y))[x[1]+1])==x[2]){x[1]}else{f(sort(x))}}
f(c(1,n))

```

TIO
> 0 votes

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


title: Bots playing a counting game

text:
# Question
Title: Bots playing a counting game
# Introduction

A childhood game designed to help children learn to count in french in Canadian schools is played as follows:

* Students go around the room counting up to 11
* A number greater than 11 cannot be said
* A student can say either 1, 2, or 3 numbers
* If a student says the number 11 then they are removed from the next round and play begins again at 1
* The game continues until there is 1 player remaining

Consider the simple example:

```
Player1 | Player2
01      |
02      |
03      |
        | 04
        | 05
        | 06
07      |
08      |
        | 09
10      |
        | 11
Player 1 wins

```

# The rules

* Design a program which takes in an integer greater than or equal to 2 and less than or equal to 99 (for formatting reasons) and outputs the game played by this number of bots
* Play will begin with bot1 and increase to the highest number bot
* Play will cycle back to the beginning when the final bot is reached
* Bots will randomly output the next 1, 2, or 3 numbers **UNLESS**
    + Outputting 2 or 3 numbers will cause them to lose on that turn.
        - If the count is 8 when it reaches a bot, it should only decide between `9` and `10`
    + Outputting 2 or 3 numbers will cause them to go over 11
* Output numbers and bot numbers should be formatted to take two characters (i.e. you can format numbers to be `01`, `_1`, or whitespace, whatever makes you happy)
* Each column should be 2 characters wide separated by `|` as well as a `|` at the beginning and ends of rows
* Once a bot is out the remainder of their column should be filled by `xx`
* When there is only one bot remaining he is the winner
* The program will announce which bot was the winner in the form of `Bot #N is the winner`
* This is code-golf so shortest byte count wins

# Formatting examples

```
|01|02|03|
|01|  |  |
|02|  |  |
|03|  |  |
|  |04|  |
|  |  |05|
|  |  |06|
|07|  |  |
|  |08|  |
|  |09|  |
|  |10|  |
|  |  |11|
|01|  |xx|
|02|  |xx|
|03|  |xx|
|  |04|xx|
|  |05|xx|
|06|  |xx|
|  |07|xx|
|08|  |xx|
|  |09|xx|
|  |10|xx|
|11|  |xx|
Bot #2 is the winner

```

**Option**

The outputs can get long so you are permitted to output only the final number of the bots turn for example the above output becomes instead:

```
|01|02|03|
|03|  |  |
|  |04|  |
|  |  |06|
|07|  |  |
|  |10|  |
|  |  |11|
|03|  |xx|
|  |05|xx|
|06|  |xx|
|  |07|xx|
|08|  |xx|
|  |10|xx|
|11|  |xx|
Bot #2 is the winner

```

With 5 bots:

```
|01|02|03|04|05|
|01|  |  |  |  |
|  |04|  |  |  |
|  |  |05|  |  |
|  |  |  |07|  |
|  |  |  |  |10|
|11|  |  |  |  |
|xx|01|  |  |  |
|xx|  |03|  |  |
|xx|  |  |06|  |
|xx|  |  |  |09|
|xx|10|  |  |  |
|xx|  |11|  |  |
|xx|  |xx|02|  |
|xx|  |xx|  |03|
|xx|05|xx|  |  |
|xx|  |xx|07|  |
|xx|  |xx|  |08|
|xx|10|xx|  |  |
|xx|  |xx|11|  |
|xx|  |xx|xx|01|
|xx|03|xx|xx|  |
|xx|  |xx|xx|04|
|xx|07|xx|xx|  |
|xx|  |xx|xx|08|
|xx|10|xx|xx|  |
|xx|  |xx|xx|11|
Bot #2 is the winner

```

With 10 players:

```
|01|02|03|04|05|06|07|08|09|10|
|01|  |  |  |  |  |  |  |  |  |
|  |04|  |  |  |  |  |  |  |  |
|  |  |05|  |  |  |  |  |  |  |
|  |  |  |08|  |  |  |  |  |  |
|  |  |  |  |09|  |  |  |  |  |
|  |  |  |  |  |10|  |  |  |  |
|  |  |  |  |  |  |11|  |  |  |
|  |  |  |  |  |  |xx|02|  |  |
|  |  |  |  |  |  |xx|  |04|  |
|  |  |  |  |  |  |xx|  |  |07|
|09|  |  |  |  |  |xx|  |  |  |
|  |10|  |  |  |  |xx|  |  |  |
|  |  |11|  |  |  |xx|  |  |  |
|  |  |xx|01|  |  |xx|  |  |  |
|  |  |xx|  |02|  |xx|  |  |  |
|  |  |xx|  |  |03|xx|  |  |  |
|  |  |xx|  |  |  |xx|04|  |  |
|  |  |xx|  |  |  |xx|  |07|  |
|  |  |xx|  |  |  |xx|  |  |08|
|09|  |xx|  |  |  |xx|  |  |  |
|  |10|xx|  |  |  |xx|  |  |  |
|  |  |xx|11|  |  |xx|  |  |  |
|  |  |xx|xx|02|  |xx|  |  |  |
|  |  |xx|xx|  |03|xx|  |  |  |
|  |  |xx|xx|  |  |xx|05|  |  |
|  |  |xx|xx|  |  |xx|  |08|  |
|  |  |xx|xx|  |  |xx|  |  |09|
|10|  |xx|xx|  |  |xx|  |  |  |
|  |11|xx|xx|  |  |xx|  |  |  |
|  |xx|xx|xx|03|  |xx|  |  |  |
|  |xx|xx|xx|  |05|xx|  |  |  |
|  |xx|xx|xx|  |  |xx|08|  |  |
|  |xx|xx|xx|  |  |xx|  |10|  |
|  |xx|xx|xx|  |  |xx|  |  |11|
|01|xx|xx|xx|  |  |xx|  |  |xx|
|  |xx|xx|xx|03|  |xx|  |  |xx|
|  |xx|xx|xx|  |06|xx|  |  |xx|
|  |xx|xx|xx|  |  |xx|08|  |xx|
|  |xx|xx|xx|  |  |xx|  |09|xx|
|10|xx|xx|xx|  |  |xx|  |  |xx|
|  |xx|xx|xx|11|  |xx|  |  |xx|
|  |xx|xx|xx|xx|03|xx|  |  |xx|
|  |xx|xx|xx|xx|  |xx|05|  |xx|
|  |xx|xx|xx|xx|  |xx|  |06|xx|
|08|xx|xx|xx|xx|  |xx|  |  |xx|
|  |xx|xx|xx|xx|09|xx|  |  |xx|
|  |xx|xx|xx|xx|  |xx|10|  |xx|
|  |xx|xx|xx|xx|  |xx|  |11|xx|
|02|xx|xx|xx|xx|  |xx|  |xx|xx|
|  |xx|xx|xx|xx|05|xx|  |xx|xx|
|  |xx|xx|xx|xx|  |xx|08|xx|xx|
|09|xx|xx|xx|xx|  |xx|  |xx|xx|
|  |xx|xx|xx|xx|10|xx|  |xx|xx|
|  |xx|xx|xx|xx|  |xx|11|xx|xx|
|01|xx|xx|xx|xx|  |xx|xx|xx|xx|
|  |xx|xx|xx|xx|04|xx|xx|xx|xx|
|07|xx|xx|xx|xx|  |xx|xx|xx|xx|
|  |xx|xx|xx|xx|10|xx|xx|xx|xx|
|11|xx|xx|xx|xx|  |xx|xx|xx|xx|
Bot #6 is the winner

```

# Answer
# JavaScript (Node.js), 269 245 240 233 232 231 bytes

* thanks to @Kevin Cruijssen for reducing by 1 byte

```
N=>{for(S=d=[],D=n=i=0;D<N-1;){for(R=n>8?1:(n>7?2:3)*Math.random()+1|0;R--;)S+="|"+[...Array(N)].map((x,I)=>i^I?d[I]?"xx":"  ":++n>9?n:"0"+n).join`|`+`|
`
for(n>10&&(d[i]=++D,n=0);d[i=++i%N];);}return S+`Bot #${i+1} is the winner`}

```

Try it online!
> 2 votes

# Answer
# Python 2, ~~295~~ ~~291~~ 290 bytes

```
from random import*
n=input()
r=range(n)
p=r[:]
b=[1]*n;s='%02d'
def P(l):print'|%s|'%'|'.join(l)
P(s%-~j for j in r)
x=0
while sum(b)>1:i=p.pop(0);g=choice(range(x+1,11)[:3]or[11]);P([2*'x '[b[j]],s%g][j==i]for j in r);x=g%11;b[i]=g<11;p+=[i]*b[i]
print'Bot #%d is the winner'%-~b.index(1)

```

Try it online!

* -1 byte, thanks to Kevin Cruijssen
> 4 votes

# Answer
# C (clang), ~~288~~ ~~283~~ ~~282~~ 266 bytes

```
f(n){int i,j,p[99]={},m,k,x;for(i=j=k=0;k<n;printf("|%02d",k++));for(puts("|"),m=n;x=i>7?10-i:3,i=x?clock()%x-~i:0,m>1;){for(k=~0;++k<n;printf(p[k]?"|xx":k-j?"|  ":"|%02d",i?i:11));puts("|"),!i&&m--*p[j]++;do j++,j%=n;while(p[j]);}printf("Bot #%d is the winner",j);}

```

Try it online!

Bots are 0 indexed.

Following will do 1-indexed for+2 bytes

```
f(n){int i,j,p[99]={},m,k,x;for(i=j=k=0;k<n;printf("|%02d",++k));for(puts("|"),m=n;x=i>7?10-i:3,i=x?clock()%x-~i:0,m>1;){for(k=~0;++k<n;printf(p[k]?"|xx":k-j?"|  ":"|%02d",i?i:11));puts("|"),!i&&m--*p[j]++;do j++,j%=n;while(p[j]);}printf("Bot #%d is the winner",j+1);}

```
> 2 votes

# Answer
# VBA (Excel), 551 bytes

`CellA1` as input and output in immediate window.

```
Sub k()
Z = [A1] - 1
ReDim p(Z)
For b = 0 To Z
p(b) = "  "
Next
Do Until i = Z
Do Until a >= 11
Randomize
a = a + CInt(IIf(a > 8, 1, IIf(a > 7, 1 + Rnd, 1 + (Rnd * 2))))
Do Until p(d) = a
p(y) = IIf(p(y) = "xx", p(y), a)
d = y
y = IIf(y = Z, 0, y + 1)
Loop
For b = 0 To Z
c = c & IIf(p(b) < 10, 0 & p(b), p(b)) & "|"
g = IIf(p(b) = "  ", b, g)
p(b) = IIf(p(b) = "xx", "xx", "  ")
Next
Debug.Print "|" & c
Application.Wait Now + #12:00:01 AM#
DoEvents
c = ""
Loop
p(d) = "xx"
i = i + 1
a = 0
Loop
Debug.Print "Bot #" & g + 1 & " is the winner."
End Sub

```
> 1 votes

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


# Question
Title: Compare char to other chars in javascript
In my answer, I have this code:

```
s.match(/[AEIOU]/)

```

This seems too verbose to check if a string is one of `A`, `E`, `I`, `O`, or `U`.

I tried:

```
"AEIOU".includes(s)

```

But that's 1 byte longer. Can I do this in a shorter way?

# Answer
> 6 votes
Try `/[AEIOU]/.test(s)`

Body must be at least 30 characters; you entered 21

# Answer
> 4 votes
If `s` is a literal and not a variable, you can do the following:

```
/[AEIOU]/.test`A`
"AEIOU".includes`A`
~"AEIOU".indexOf`A`

```

which is shorter than

```
/[AEIOU]/.test("A")
"AEIOU".includes("A")
~"AEIOU".indexOf("A")

```

# Answer
> 2 votes
`s.match`[AEIOU]`` goes well.....

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


title: Find out my number neighbors

text:
# Question
Title: Find out my number neighbors
The input consists of *i* rows with neighbors information. Each *i*th row contains 4 values, representing the neighbor of *i* to the **North**, **East**, **South** and **West** directions, respectively. So each value represents a neighbor at the given direction of the *i*th row, starting from row 1, and can go up to 65,535 rows. The *0* value indicates no neighbor to that direction.

For instance, if the first row is "0 2 3 10" it means that the *i* neighbor has three other neighbors: no one to the north, neighbor *2* to the east, neighbor *3* to the south and neighbor *10* to the west.

You need to output the array of neighbors, starting from the value which is most to the northwest. Each neighbor will be displayed only once, at its position relative to others. Let's see some examples:

Input:

```
0 0 0 0

```

No neighbors (empty case), output:

```
1

```

Input:

```
0 2 0 0
0 0 0 1

```

1 has neighbor 2 to the east. 2 has neighbor 1 to the west

Output:

```
1 2

```

Input:

```
0 2 0 0
0 0 3 1
2 0 0 0

```

1 has neighbor 2 to the east. 2 has neighbor 1 to the west and 3 to the south. 3 has neighbor 2 to the north

Output:

```
1 2
  3

```

Input:

```
2 0 0 0
0 0 1 0

```

Output:

```
2
1

```

Input:

```
0 2 3 0
0 0 4 1
1 4 0 0
2 0 0 3

```

Output:

```
1 2
3 4

```

**Rules:**

* Test cases are separated by one **empty line**. Output of different test cases must also be separated by one empty line.
* The output graph is **always** connected. You are not going to have 1 neighbor to 2 only, along with 3 neighbor to 4 only (isolated from 1-2 component).
* **All entries are valid.** Example of invalid entries:
    + Entries containing letters or any symbol different than spaces, line breaks and digits (0-9).
    + the *i*th row containing the *i*th value (because one can't be its own neighbor).
    + a negative value or value higher than 65,535.
    + Less than four values in a row.
    + More than four values in a row.
    + The same neighbor pointing to two different directions (ex: 0 1 1 0).

Standard loopholes apply, and the shortest answer in bytes wins.

# Answer
# Python 2, 152 bytes

```
l=input()
def f(x,y,n):
 if m[x][y]<n:m[x][y]=n;[f(i%3-1+x,i/3-1+y,h)for h,i in zip(l[n-1],[3,7,5,1])]
e=len(l)
m=eval(`[[0]*e*2]*e*2`)
f(e,e,1)
print m

```

Try it online!

The input order is `NESW`
`f` is a recursive function to populate the houses
> 2 votes

# Answer
* still golfing :)

# JavaScript (Node.js), 135 bytes

```
R=>R.map((t,y)=>r.map((T,Y)=>T.map((X,I)=>X==y+1?[-1,1,1,-1].map((x,i)=>t[i]?(r[a=Y+x*-~i%2]=r[a]||[])[I+x*i%2]=t[i]:0):0)),r=[[1]])&&r

```

Try it online!

### \_______________________________________________________________

Second approach

# JavaScript (Node.js), 130 bytes

```
f=(R,x=0,y=0,c=1,r=[[]])=>[-1,1,1,-1].map((d,i)=>(t=R[c-1][i])&&!(r[Y=y+d*-~i%2]=r[Y]||[])[X=x+d*i%2]?f(R,X,Y,t,r):0,r[y][x]=c)&&r

```

Try it online!
> 2 votes

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


title: Uptime Progress Bar

text:
# Question
Title: Uptime Progress Bar
Write a program which parses the output of `uptime` and generates an anatomically suggestive progress bar (as shown) with a length equal to the current uptime in days:

```
$ uptime
23:01  up 34 days,  7:30, 5 users, load averages: 0.23 0.27 0.24
$ uptime|<command>
8==================================D

```

(34 days = 34 equal signs)

Shortest answer wins.

# Answer
> 6 votes
# Ruby, 39

No input required (by shelling out):

```
`w`=~/up (\d*)/;puts '8'+'='*$1.to_i+'D'

```

Or from stdin (40 chars):

```
gets=~/up (\d*)/;puts '8'+'='*$1.to_i+'D'

```

# Answer
> 5 votes
## Bash, 71 characters

```
a=`uptime` a=${a#*p } a=${a%% *};while((a--));do p==$p;done;echo I${p}I

```

I'm not that much into exposing my ~~gen~~uptimes on the internet, so I'm drawing a fence instead. It's the same character count. Think of resetting `p` between calls.

Pure bash, 71 characters including `uptime`.

```
$ uptime
 23:35:12 up 159 days,  4:15, 15 users,  load average: 1.07, 0.63, 0.38

```

Well, well, well... mine's bigger than yours.

# Answer
> 5 votes
## Perl - 26 24 characters

```
/p (\d+)/;say+8,"="x$1,D

```

Ran like so:

```
$ uptime
 04:52:39 up 17 days, 11:27,  3 users,  load average: 0.21, 0.07, 0.02
$ uptime | perl -nE '/p (\d+)/;say+8,"="x$1,D'
8=================D

```

*edit*: Unquoted the final 'D' - thanks **J B**

# Answer
> 4 votes
**Perl, 17 characters**
Now with say:

```
say+8,"="x$F[2],D

```

Yields

```
uptime | perl -naE 'say+8,"="x$F[2],D'

```

was:

```
print"8"."="x$F[2]."D"

```

Yields

```
]# uptime | perl -anle 'print"8"."="x$F[2]."D"'
8=========================D

```

(I can't "say", sadly)

# Answer
> 4 votes
## Haskell, 88 characters

As is often the case, Haskell doesn't offer the most extreme golfability of some other languages, but does allow an elegant expression of the mathematical structures underlying the problem. Building on their seminal work in this field, I aim to introduce a Haskell implementation of the Holkins-Krahulik Approximation operator. Briefly, the operator ignores both its inputs and returns a phallus-printing function parameterized by shaft length.

```
_⁑≈≈≈⊃_=(\n->concat["8",take n$repeat '=',"D"])
main=interact$(0⁑≈≈≈⊃1).read.(!!2).words

```

# Answer
> 3 votes
## 57 characters

```
python -c "print'8'+'='*int(raw_input().split()[2])+'D'"

```

# Answer
> 3 votes
## 35 characters

```
awk '{printf"#%"$3"sp",p}'|tr \  \*

```

so,

```
uptime
12:27μμ  up 111 days,  2:36, 1 user, load averages: 0,07 0,03 0,00
uptime | awk '{printf"#%"$3"sp",p}'|tr ' ' '*'

#***************************************************************************************************************p

```

**Edit**: was

```
printf "#%`awk '{print $3}'`sp"|tr ' ' '*'

```

**Edit 2**: J B's comment (use `\` instead of `''`)

# Answer
> 3 votes
## Windows PowerShell, 28

```
"8$('='*(-split$input)[2])D"

```

At least

```
echo 23:01  up 34 days,  7:30, 5 users, load averages: 0.23 0.27 0.24|powershell -file uptime.ps1

```

yields the correct output, so it should be able to handle `uptime`'s output. I cannot test, though, since GNUWin32 includes a broken `uptime` that tries to read from a non-existant file (Note to people porting Unix tools: Don't try to assume that Windows is a Unix and adheres to the same principles or conventions; there is no file containing the boot time on Windows).

# Answer
> 3 votes
## Common Lisp, 84 characters

```
(defun p(s)(write 8)(loop repeat(read-from-string(subseq s 9))do(write'=))(write'D))

```

This takes the uptime string as input. It seems like there ought to be a shorter solution mapping #'write over a list, but if so I can't come up with it.

# Answer
> 3 votes
## GolfScript (24 characters)

```
' '/{(;}3*(\;~'='*8\'D'

```

## Haskell (73 characters)

```
main=getLine>>=putStr.('8':).(++"D").(`take`repeat '=').read.(!!2).words

```

## C (131 characters)

```
#define r(a);read(0,x,a),
#define p ;putchar(
x[9];main(i){for(r(1)i<3;i+=*x==32)r(9)0
p'8');for(i=atoi((int)x+2);i--p'='))p'D');}

```

# Answer
> 2 votes
## PHP, 62 characters

```
<?$d=split(" ",`uptime`);echo 8;while($d[3]--)echo"=";echo"D";

```

No input required, it shells out.

# Answer
> 2 votes
## Python (42)

```
print('8'+int(input().split()[2])*"="+'D')

```

*Note: Python 3 used for reducing total character count.*

# Answer
> 2 votes
# Python, 65 Bytes

```
import sys
print '8'+'='*int(sys.stdin.readline().split()[2])+'D'

```

test:

```
echo '23:01  up 34 days,  7:30, 5 users, load averages: 0.23 0.27 0.24'|./time.py
8==================================D

```

# Answer
> 1 votes
## PHP, 61

```
<?$n=split(' ',$argv[1]);$v=8;while($n[2]--)$v.'=';echo"$vD";

```

# Answer
> 1 votes
### Common Lisp, 57 characters

(excluding implementation/OS-specific shebang)

```
#!/opt/local/bin/sbcl --script
(do()((eql(read-char)#\p)(format t"8~v,,,'=<~>D"(read))))

```

Based on an attempt to satisfy Dr. Pain's answer's wish for a shorter way to write a repeated character. This one can be used in a pipeline as shown in the question.

(The format string specifies to right-justify the empty string (between `~<` and `~>`), in a field of width specified by an argument, padded using the `=` character.)

# Answer
> 1 votes
# K, 35

```
-1"8",(("I"$(" "\:0:0)@3)#"="),"D";

```

.

```
$ uptime
17:21:47 up 242 days,  7:22, 35 users,  load average: 0.33, 0.34, 0.44
$ uptime | q t.k
8============================================================================ ...

```

# Answer
> 0 votes
## Bash 67 chars

```
read t u d w
echo -e '\t'|expand -t $d|sed 's/^/8/;s/ /=/g;s/$/B/;'

```

invocation to the letter of the assignment:

```
uptime | ./cg1570uptime-bar.sh

```

Much shorter

### just 54 chars:

with this variation:

```
echo -e '\t'|expand -t $3|sed 's/^/8/;s/ /=/g;s/$/B/;'

```

invocation, not 100% in accordance with the rules:

```
./cg1570uptime-bar.sh $(uptime)

```

output in both times:

```
uptime && uptime | ./cg1570uptime-bar.sh
06:29:53 up 16 days, 21:03, 10 users,  load average: 1.29, 1.34, 1.23
8================B

```

Non-everyday tricks:

```
 read t u d w

```

reads 06:29:53=t, up=u, 16=d rest...=w
without w, everything to the end would be put into $d.

expand is normally used to translate a tab into an amount of blanks and takes a parameter if you don't like 8.

Grabbing the 3rd parameter with $3 in `echo -e '\t'|expand -t $3|sed 's/ /=/g'` is even shorter, but needs an invocation, not fitting to the words of the rules.

# Answer
> 0 votes
### bash/zenity 38 short version, 68 longer version

```
read c o d e
zenity --scale --value=$d --max-value=497 --text=uptime

```

The short version ends after $d, the longer takes into account that we know a max-value and like to have helpful text:

# Answer
> 0 votes
# Gema, 24 characters

```
<D> d=8@repeat{$1;=}D;?=

```

Sample run:

```
bash-4.4$ uptime
 18:35:31 up 13 days,  7:53, 16 users,  load average: 0.31, 0.85, 1.24

bash-4.4$ uptime | gema '<D> d=8@repeat{$1;=}D;?='
8=============D

```

# Answer
> 0 votes
# AutoHotkey, 39 bytes

```
d:=A_TickCount//=8.64e+7
Send 8{= %d%}D

```

No input. Result is sent to active window.
The built-in `A_TickCount` is the number of milliseconds since the computer was rebooted.

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


title: Help me redirecting

text:
# Question
Title: Help me redirecting
Your task is to automatically complete URLs like the address bar in most browsers is doing. We will use the following (simplified) rules:

* If the input string starts with `http://`, `ftp://` or `https://`, return the string unchanged.
* Otherwise, if the input string contains a dot `.`, e.g. `in.put` then the HTTP is assumed and `http://` is prepended: `http://in.put`.
* Otherwise `ftp://` is prepended, e.g. `ftp://input` when the input string was `input`.

## Input

Any string which must not necessarily be a valid URL.

## Output

The string modified according to the above rules.

## Test Cases

```
dan-pc -> ftp://dan-pc
https://localhost/ -> https://localhost/
ftp://foo -> ftp://foo
http://foo -> http://foo
f.oo -> http://f.oo
derp.me -> http://derp.me
another.one/ ->http://another.one/
// -> ftp:////
a://b -> ftp://a://b

```

*This is code golf, shortest code wins. Good Luck!*

# Answer
> 3 votes
# R, 98 bytes

```
x=scan()
cat(`if`(grepl("^(https?|ftp)://",x),"",`if`(grepl("\\.",x),"http://","ftp://")),x,sep="")

```

Try it online!

# Answer
> 2 votes
# Perl 5 `-p`, 38 bytes

```
m%://%||s%.*\.%http://$&%||s%^%ftp://%

```

Try it online!

# Answer
> 2 votes
# Ruby, ~~63~~ ~~56~~ 55 bytes

```
->a{a[%r*(https?|ftp)://*]?a:"#{a[?.]?'ht':?f}tp://"+a}

```

Try it online!

# Answer
> 2 votes
# Swift, ~~147~~ 133 bytes

Thanks to Herman L for saving 14 bytes.

Sadly, `NSRegularExpression` would've taken away lots of precious bytes.

```
import Foundation;let s=readLine()!,h=["http://","https://","ftp://"];print(h.contains{s.hasPrefix($0)} ?s:h[s.contains(".") ?0:2]+s)

```

**Prettyfied:**

```
import Foundation

let s = readLine()!, h = ["http://","https://","ftp://"]
print(h.contains{ s.hasPrefix($0) } ? s :h[s.contains(".") ? 0 : 2] + s)

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~87~~ 85 bytes

```
lambda s:re.match('(https?|ftp)://',s)and s or['f','ht']['.'in s]+'tp://'+s
import re

```

Try it online!

-2 bytes thx to Titus and wastl

# Answer
> 1 votes
# JavaScript, 64 bytes

```
x=>x.match`^(https?|ftp)://`?x:`${/\./.test(x)?'ht':'f'}tp://`+x

```

# JavaScript, ~~51~~ 50 bytes, Real life assumption

```
x=>x.match`//`?x:`${/\./.test(x)?'ht':'f'}tp://`+x

```

Thank tsh for 1 byte

# Answer
> 1 votes
# JavaScript (Firefox 52), 41 bytes

```
s=>new URL(s,/\./.test(s)?'http:':'ftp:')

```

If a string is required for output, add 3 bytes `+''` at the end. (Notice this solution may add a trailing `/` at the end of domain name since they are the same URL)

```
f=
s=>new URL(s,/\./.test(s)?'http:':'ftp:')

t=s=>console.log(`${s} -> ${f(s)}`)

t('example.com')
t('example')
t('http://example')
t('https://example')
t('ftp://example')
t('http://example.com')
t('https://example.com')
t('ftp://example.com')
```

It seems this only works on Firefox 52 ESR but not Firefox 60 or Chrome 65. So sad.

# Answer
> 1 votes
# Java 8, ~~74~~ 72 bytes

```
s->s.matches("(https?|ftp)://.*")?s:(s.contains(".")?"ht":"f")+"tp://"+s

```

-2 bytes thanks to *@HermanLauenstein*.

Try it online.

**Explanation:**

```
s->                   // Method with String as both parameter and return-type
  s.matches("(https?|ftp)://.*")?
                      //  If the input starts with one of
                      //  "http://", "https://", or "ftp://"
   s                  //   Return it as is
  :                   //  Else:
   (s.contains(".")?  //   If it contains a dot
     "ht"             //    Start with "ht"
    :                 //   Else:
     "f")             //    Start with "f"
   +"tp://"+s         //   And append "tp://" and the input-String

```

# Answer
> 1 votes
# PHP, 59 bytes

```
<?=strpos($s=$argn,':')?$s:(strpos($s,'.')?ht:f)."tp://$s";

```

To run all the tests:

```
cat <<EOF | php -nF <filename>
dan-pc
https://localhost/
ftp://foo
http://foo
f.oo
derp.me
another.one/
EOF

```

(Put a newline before the `<?=` for formatting, not required for one line of input)

Or just one at a time:

```
echo '<input>' | php -nF <filename>

```

Or Try it online!

# Answer
> 1 votes
# Retina, 64 bytes

```
^(?!(https?|ftp)://)(?=.*\.)
http://
^(?!(https?|ftp)://)
ftp://

```

Try it online!

# Answer
> 1 votes
# GolfScript, ~~58~~ 55 bytes

```
.'://':a/.,(\0=['https'.4<'ftp']:l?)*{}{.'.'?)!)l=a@}if

```

Try it online!

This is my first GolfScript program, so I expect there is a lot room for golfing.

Explanation:

```
.'://':a/.,(\0=['https'.4<'ftp']:l?)*{}{.'.'?)!)l=a@}if Full program, implicit input
.                                                       Copy input
 '://':a                                                Push '://', and assign it to a
        /.                                              Split input at '://' and copy
          ,(                                            Push length of the result - 1 (<==> '://' in input)
            \0=                                         Pull up the array and get the first element
               ['https'.4<'ftp']:l                      Push [ 'https', 'http', 'ftp' ] and assign it to l
                                  ?)                    Test if first element is in that array
                                    *{}{            }if If at least one of those values is false
                                        .'.'?)          Push whether the input contains a dot
                                              !)        Logical not and increment:
                                                              '.' in input -> 1
                                                           no '.' in input -> 2
                                                l=      Get that element of l ([ 'https', 'http', 'ftp' ])
                                                  a@    Append a ('://') and input
                                                        Implicit output

```

# Answer
> 1 votes
# Pyth, 58 bytesSBCS

```
J"://"I:Q."(|e<UGÐÌ@ãy!'"ZQ.?I}\.Q++"http"JQ.?++"ftp"J

```

**Test suite**

### Code contains unprintable characters, and as such does not display properly on Stack Exchange. The link provided contains these characters and is the correct version of the program.

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


title: The Third Flak!

text:
# Question
Title: The Third Flak!
**This challenge was posted as part of the April 2018 LotM challenge**

---

Brain-Flak is a turing-tarpit language which has gained quite a lot of fame here on PPCG. The memory of the language is composed by two stacks, but a "hidden" third stack was discovered by Wh~~e~~at Wizard, leading to some interesting new ways of thinking Brain-Flak programs.

So, what about giving that poor hidden third stack more visibility? Let's create a language where the third stack has the recognition it deserves! Here I present you **Third-Flak**.

# The language

In Third-Flak there is only one stack, called the third stack. Operators work on the third stack in the same way they do in Brain-Flak, but here there are no `[]`,`{}`,`<>` nilads and no `{...}` monad (so the only admissible characters in a Third-Flak program are `()[]<>`). Here is what each operator does (examples will be given representing the third stack with a list where the last element is the top of the stack):

* `()` is the only two-characters operator in Third-Flak. It increases the top of the third stack by 1. Example: `[1,2,3]``[1,2,4]`
* `(`,`[`,`<`: all opening parentheses that are not covered by the previous case push a `0` to the third stack. Example: `[1,2,3]``[1,2,3,0]`
* `)` pops two elements from the third stack and pushes back their sum. Example: `[1,2,3]``[1,5]`
* `]` pops two elements from the third stack and pushes back the result of subtracting the first from the second. Example: `[1,2,3]``[1,-1]`
* `>` pops an element from the third stack. Example `[1,2,3]``[1,2]`

And here are the other rules of the language:

* At the beginning of execution the third stack contains only a single 0.
* It is forbidden to have empty `[]` or `<>` inside a program (they would be noops anyway if following the semantics of Third-Flak, but they actually have a different meaning in Brain-Flak that is not possible to recreate here).
* Parentheses always need to be balanced, except for the fact that trailing closing parentheses at the end of the program can be missing. As an example, `[()<(()` is a valid Third-Flak program (and the third stack at the end of the program would be `[1,0,1]`).
* A program can only contain the six allowed characters `()[]<>`. Programs are guaranteed to be non-empty.

Note: it is implied by the previous rules that you won't have to deal with situations where you need to pop from an empty stack.

# The challenge

Simple, write an interpreter for Third-Flak. Your program must take as input a Third-Flak program and return as output the state of the third stack at the end of the program.

Your output format is flexible as long as it is possible to unambiguously read from it the state of the third stack and the same number is always encoded in the same way (This is just a way of saying that any output format that's not a blatant way to try to cheat is fine).

Your output choice may restrict the range of numbers you can manage as long as this does not trivialize the challenge (since this would be a default loophole).

# Test cases

For each test case the first line is the input, and the second line the output stack represented as a space separated list of numbers where the top of the stack is the last element.

```
[()<(()
0 1 0 1

[((((()()()()()))
0 0 0 5

((([()][()][()])))
-3

[<<(((()()()())(((((
0 0 0 0 0 4 0 0 0 0 0

[()]<(([()])><[()]
-1 0 -1

(())(()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(()()()()())(())(())(())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(()()()()())(())(())(())(())(())(())(()())(())(())(())(()())(()()()())(())(()()()()())(()())(()())(()())(()()())(())(()())(())(()()()()())(()())(()()()()())(())(())(())(())(())(()())(())(())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(()())(()())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(()()())(()())(())(()()()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(())(())(())(()()())(())(())(()()())(())(())(()()())(())(()()()()())(()())(()()()()())(()()())(())(()()())(())(())(())(()())(()()())(()())(())(()()()()())(()())(())(()()())(())(()()()()())(())(())(())(()()())(())(())(())(()())(())(()())(()()()())(())(())(()()()()())(()())(()())(())(()()())(())(())(())(())(()()())(()())(())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()())(())(()()()()())(()()()()())(())(()()())(())(())(()())(())(()()()()())(())(()()()()())(())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(()()()()())(())(()()()()())(())(())(())(()())(())(()()()()())(())(())(()())(())(()())(())(()())(()())(()())(()())(())(()()()()())(()())(())(()()()()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(())(()()())(())(())(())(()())(()()()())(())(())(()())(())(()()()()())(())(())(()()()()())(())(())(()()()()())(())(())(()())(())(()())(())(()())(())(()())(())(()())(()())(()())(()())(()())(()())(())(()()())(())(())(()())(())(()()()()())(()())(()()()()())(()()())(())(())(()())(())(())(()()()()())(()()()())(()())(()())(()()())(())(()())(())(()()()()())(()())(()()()()())(())(())(())(()()()())(()()()())(()()
718 2

```

# Answer
> 20 votes
# Brain-Flak, 276 bytes

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

```

Try it online!

You had to know this was coming.

# Answer
> 4 votes
# Python 3, ~~145 144 132 122 116 109~~ 104 bytes

*-7 bytes thanks to Leo!*

*And - 5 thanks to Lynn!*

```
s=[0]
for i in input().replace('()',' '):s+=i in']>) 'and(i<'!'or(2-ord(i)%5)*s.pop())+s.pop(),
print(s)

```

Try it online!

~~Pretty standard implementation.~~ Not so readable now though. I'm disappointed I couldn't figure out a shorter way to check between start and end brackets though.

Some attempts at one-liners:

* 124 bytes (anonymous function):

```
lambda c:[s.append(i in']>) 'and(i<'!'or~-']>)'.index(i)*s.pop())+s.pop())or s for s in[[0]]for i in c.replace('()',' ')][0]

```
* 115 bytes (full program):

```
s=[0];[s.append(i in']>) 'and(i<'!'or~-']>)'.index(i)*s.pop())+s.pop())for i in input().replace('()',' ')];print(s)

```

Append is annoyingly longer than plain assignment

# Answer
> 4 votes
# Retina 0.8.2, ~~64~~ ~~48~~ 46 bytes

```
\(\)
_
[([<]
¶
+1`¶(.*)\)|(.*)¶\2]|¶.*>
$1
%`_

```

Try it online! Outputs the stack from bottom to top. Only works with non-negative integers, and the last test case is too slow, so the link only includes three test cases. Explanation: The stack implicitly precedes the program, so it starts off as the empty string, which represents a single zero. The `()` nilad is turned into a `_` which is used to count in unary, while the other open brackets are turned into newlines which push a zero on to the stack as they are encountered. The close brackets are then processed one at a time so that the stack will be correct; the `)` deletes the previous newline, adding the top two elements together, the `]` deletes the top element and matches it from the previous element on the stack thus subtracting it, and the `>` just deletes the top element. Finally the stack is converted to decimal. Edit: Saved 2 bytes thanks to @Leo.

# Answer
> 2 votes
# Ruby, ~~98~~ 91 bytes

```
->s{a=[i=0];s.chars{|c|a<<("([<"[c]?s[i,2]["()"]?1:0:a.pop*~-"]>)".index(c)+a.pop);i+=1};a}

```

Try it online!

My initial code worked similarly in spirit to Jo King's Python answer, so that before looping through the source chars we replaced all `()` substrings by another character, as a distinct operator.

However, at least in Ruby, it turned out golfier not to do this, but rather go for a slightly more cumbersome approach. Here, we maintain an additional indexer `i` keeping track of our position in the source string, and whenever an opening bracket is encountered, we do a lookahead checking if our current+next chars `s[i,2]` form the `()` operator. In that case we push 1 instead of 0 on top of the stack, and let the closing `)` do its job in the next step.

# Answer
> 1 votes
# , ~~182~~ 177 bytes

```
function(P){for(k in utf8ToInt(gsub("\\(\\)",7,P))%%8){if(k%in%0:4)F=c(0,F)
if(k==7)F[1]=F[1]+1
if(k==1)F=c(F[2]+F[3],F[-3:0])
if(k==5)F=c(F[2]-F[1],F[-2:0])
if(k==6)F=F[-1]}
F}

```

Try it online!

Returns the stack, where the top of the stack is first and the bottom of the stack is last.

Swaps `()` with `7` and then computes the code points mod 8 to get distinct numeric values, which are easier and golfier to work with than strings.

It's golfier to work with the beginning of a vector in R, so we construct the stack that way.

Then it sees a `)`, or when `k==1`, it adds an extra zero to the top of the stack since it's golfier to add it and remove it.

# Answer
> 1 votes
# 05AB1E, 25 bytes

```
Î„()1:v"0+0\0->"žuykè.V})

```

Try it online!

**Explanation**

```
Î                           # initialize the stack with 0 and the input
 „()1:                      # replace any occurrence of "()" in the input with 1
      v                }    # for each char y in this string
                žuyk        # get its index in the string "()[]<>{}"
       "0+0\0->"    è       # use this to index into the string "0+0\0->"
                     .V     # eval
                        )   # wrap the stack in a list

```

# Answer
> 1 votes
# SOGL V0.12, 34 bytes

```
0,Ƨ() Iŗ{"(<[”č0ŗΖ)+ŗ ] -ŗΖ>Xŗ!!}⁰

```

Try it Here!

# Answer
> 1 votes
# CJam, 29 bytes

```
0q")]>([<""+-;U"er"U+"/')*~]p

```

Try it online!

```
0q                              Push 0, input
  ")]>([<""+-;U"er              Translate )]>([< to +-;UUU
                  "U+"/')*      Replace U+ by )
                          ~     Eval as CJam code
                           ]p   Wrap and pretty-print stack

```

# Answer
> 1 votes
## Ceylon, ~~285~~ 266 bytes

```
function f(variable String c){variable Integer[]s=[0];value o=>[s[0]else nothing,s=s.rest][0];void u(Integer i)=>s=[i,*s];while(c!=""){if(c[0:2]=="()"){u(1);c=c.rest;}switch(c[0])case(')'){u(o+o);}case(']'){u(-o+o);}case('>'){noop(o);}else{u(0);}c=c.rest;}return s;}

```

Try it online!

(Saved 19 bytes due to a suggestion by Leo.)

Formatted and commented:

```
// Interpreter for ThirdFlak
// Question:    https://codegolf.stackexchange.com/q/163242/2338
// This answer: https://codegolf.stackexchange.com/a/163403/2338
//
// This function takes the code as a string, and returns the value
// of the stack as a sequence of Integers.
function f(variable String c) {
    // stack, in the beginning just a single 0.
    // Top element of the stack is the first, because push + pop is easier this way.
    variable Integer[] s = [0];
    // pop – used like an Integer variable (not a function – this saves the `()`), but has side effects.
    value o =>
        // `s[0]` is the first element of the stack. We tell the compiler
        // that it is non-null (otherwise we'll get an error at run time)
        // using the `else nothing`. `s.rest` is `s` without its first element.
        // Both together are wrapped into a 2-tuple, of which we then take just
        // the first element, to have both together in an expression instead
        // the longer way using an accessor block with a temporary variable and a return.
        // value o {
        //   value r = s[0] else nothing;
        //   s = s.rest;
        //   return r;
        // }
        [s[0] else nothing, s = s.rest][0];
    // push
    void u(Integer i) =>
        // a tuple enumeration, using the spread argument.
        s = [i, *s];
    // the main loop
    while (c != "") {
        if (c[0:2] == "()") {
            // »`()` is the only two-characters operator in Third-Flak. It increases the top of the third stack by 1.«
            // As `)` alone adds the two top elements together, we can just push a one here, and let the handling for `)` do the rest.
            u(1);
            c = c.rest;
        }
        switch (c[0])
        case (')') {
            // »`)` pops two elements from the third stack and pushes back their sum.«
            u(o + o);
        }
        case (']') {
            // »`]` pops two elements from the third stack and pushes back the result of subtracting the first from the second.«
            // As the o written first is the first one, we can't write this as a subtraction.
            u(-o + o);
        }
        case ('>') {
            // »`>` pops an element from the third stack.«
            // `o;` alone is not a valid statement, so we pass it to the `noop` function.
            noop(o);
        }
        else {
            // all other valid code characters are `(`, `[`, `<`, which all just push a 0.
            u(0);
        }
        c = c.rest;
    }
    return s;
}

```

Try it online!

---
Tags: code-golf, brain-flak
---


title: Getting the Vowel Square

text:
# Question
Title: Getting the Vowel Square
**Challenge**

You will create a function which takes a matrix filled with letters from the alphabet and determine if a `2x2` square composed of vowels exists.

* If a 2x2 square of vowels is found, your function should return the top-left position (row-column) of the square.
* If no 2x2 square of vowels exists, then return the string `"not found"`.
* If there are multiple squares of vowels, return the one that is at the most top-left position in the whole matrix.

**Rules**

* Matrix must be at least `2x2`
* Matrix can only contain letters from the alphabet
* Input can be a String, where each line is separated by `\n`, `,`, `.`, `\t` (`\n` means `line break` and `\t` TAB) or an array of strings.
* Vowels are `a e i o u`.

**Example**

Given `["abcd", "eikr", "oufj"]`

```
a   b   c   d
e   i   k   r
o   u   f   j

```

Output: `1-0`

---

Given `["gg", "ff"]`

```
g   g
f   f

```

Output `not found`

---

**Test Cases**

**Given `["asd", "qie", "euo"]`**

```
a s d
q i e
e u o

```

Output: `1-1`

**Given `["aqrst", "ukaei", "ffooo"]`**

```
a   q   r   s   t
u   k   a   e   i
f   f   o   o   o

```

Output: `1-2`

**Given `["ghsdfhsd", "sdfgsdff", "sdfgsdfg"]`**

```
g   h   s   d   f   h   s   d
s   d   f   g   s   d   f   f
s   d   f   g   s   d   f   g

```

Output: `"not found"`

* Consider the examples as test cases as well

## Update

* If you are going to use 1-based index, please clarify it in your answer.

---

This is , so the shortest answer in bytes win.

# Answer
> 7 votes
# Python 2, 121 bytes

```
import re
s=input()
w=s.find(',')
v='[aeiou]'*2
m=re.search(v+'.'*~-w+v,s)
print m and divmod(m.start(),-~w)or'not found'

```

Try it online!

I feel like I don't get to use `divmod` often in Python, haha.

Takes input like `"aqrst,ukaei,ffooo"`.

## Explanation

We compute the width **w** of the matrix by finding the position of the first `,`: in this case, that's 5.

Then, we build the regex `[aeiou][aeiou]....[aeiou][aeiou]` with **(w − 1)** dots: to match vowels on the next row, we skip (one row − 2 letters + 1 comma) = **(w − 1)** characters we don't care about.

To turn `m.start()` back into coordinates, we `divmod` by **(w + 1)** (minding the comma).

# Answer
> 6 votes
# JavaScript (ES6), ~~89~~ 88 bytes

*Saved 1 byte thanks to @RickHitchcock*

Takes input as a comma-separated string.

```
s=>~(k=s.search((v='[aeiou]{2}')+`.{${(w=s.search`,`+1)-2}}`+v))?[k/w|0,k%w]:'not found'

```

Try it online!

# Answer
> 4 votes
# Python 3, ~~143~~ ~~132~~ ~~130~~ 129 bytes

* Thanks to musicman523 for golfing eleven bytes; golfed `{m[y][x],m[y][x+1],m[y+1][x],m[y+1][x+1]}` to `{*(m[y][x:x+2]+m[y+1][x:x+2])}`.
* Thanks to ovs, golfed `{...}<={*"aeiou"}` to `{...}<{*"aeiou"}`; using the fact that five vowels do not fit into four cells.

```
lambda m:([(y,x)for y in range(len(m)-1)for x in range(len(m[y])-1)if{*(m[y][x:x+2]+m[y+1][x:x+2])}<{*"aeiou"}]+["not found"])[0]

```

Try it online!

# Answer
> 4 votes
# Java 8, 156 bytes

```
m->{for(int i=0,j;++i<m.length;)for(j=0;++j<m[i].length;)if((m[i][j]+m[i][j-1]+m[i-1][j]+m[i-1][j-1]).matches("[aeiou]+"))return i+"-"+j;return"not found";}

```

1-indexed output.

Try it online.

```
m->{                           // Method with String-matrix input and String return-type
  for(int i=0,j;++i<m.length;) //  Loop over the rows, skipping the first
    for(j=0;++j<m[i].length;)  //   Inner loop over the columns, skipping the first
      if((m[i][j]+m[i][j-1]+m[i-1][j]+m[i-1][j-1])
                               //    If four characters in a square appended to each other,
         .matches("[aeiou]+")) //    are only vowels
        return i+"-"+j;        //     Return the 1-indexed output
  return"not found";}          //  Return "not found"

```

# Answer
> 2 votes
# Jelly, 26 bytes

```
e€€ØcaƝ⁺€T€µT,FZḢȯ“¤Ø#"ȯ"»

```

Indexing is 1-based.

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 82 bytes

```
(.*¶)*?(.)*?[aeiou]{2}.*¶(?>(?<-2>(.))*)[aeiou]{2}(.|¶)*
$#1-$#3
^[^-]*$
not found

```

Try it online! Explanation:

```
(.*¶)*?

```

Match an optional number of rows which are stacked into capture group 1.

```
(.)*?

```

Match an optional number of columns which are stacked into capture group 2.

```
[aeiou]{2}

```

Match two vowels.

```
.*¶

```

Match the rest of the line.

```
(?>(?<-2>(.))*)

```

Match an equal number of columns on the next line, which are stacked into capture group 3, as the matching empties the capture group 2 stack.

```
[aeiou]{2}

```

Match two more vowels.

```
(.|¶)*

```

Match the rest of the input.

```
$#1-$#3

```

If there's a match, replace the entire input with the number of rows and columns matched.

```
^[^-]*$
not found

```

If the input doesn't yet contain a `-` then the match must have failed.

# Answer
> 1 votes
# Jelly, 35 bytes

```
FḟØcṆ
ZÇ€T,€
ṡ€2ṡ2ç"JṖFḣ2Uȯ“¤Ø#"ȯ"»

```

Try it online! (comes with test-suite)

Way too long, but I guess it'll improve. Uses 1-based indexing.

# Answer
> 1 votes
# APL+WIN, 73 bytes

Prompts for character matrix input:

```
z←,(,r)/(⍴r)⊤(⍳⍴,r←<⍀<\(2^/m,0)×2^⌿(m←⎕∊'aeiou')⍪0)⋄z,(~×⍴z)↑⊂'not found'

```

# Answer
> 1 votes
# Python 2, 134 bytes

```
f=lambda m,i=0,y=0:m[i+1:]and(m[i][y+1:]and(set(m[i][y:y+2]+m[i+1][y:y+2])<set('aeiou')and(i,y)or f(m,i,y+1))or f(m,i+1))or'not found'

```

Try it online!

# Answer
> 1 votes
# Haskell, ~~146~~ 140 bytes

```
l x=[0..length x-2]
h x|p<-(!!).(x!!)=([show(i,j)|i<-l x,j<-l(x!!0),all(`elem`"aeiou")[p i j,p(i+1)j,p i$j+1,p(i+1)$j+1]]++["not found"])!!0

```

Try it online!

### Explanation

This just generates a list of possible indices, nothing special:

```
l x=[0..length x-2]

```

This is just a little helper, that allows quickly accessing the element at `(i,j)` with `p i j` (due to operator precedence it's shorter not to use an operator):

```
    p<-(!!).(x!!)

```

This generates a list with all the indices (as strings...) of 2x2 sub-matrices that consist of vowels in order:

```
h x|             = [show(i,j)|i<-l x,j<-l(x!!0),all(`elem`"aeiou")[p i j,p(i+1)j,p i$j+1,p(i+1)$j+1]]

```

Now we just need to append the `"not found"` string:

```
                  (                                                                                ++["not found"])

```

This way we can simply retrieve the first element in this list (since it's generated in order and in case of no such indices, there's always the `"not found"` string):

```
                                                                                !!0

```

# Answer
> 1 votes
# , 61 bytes

```
[:'not found'"_`($#:t)@.(#@,~:t=.4:i.~,)2 2+/@,;.3'aoeiu'e.~]

```

Try it online!

## Explanation:

```
   ] a =. 'asd','qie',:'euo'   Let `a` be the first test case
asd
qie
euo
  'aoeiu'e.~] a        creates an equality table between the input and the vowels
1 0 0
0 1 1
1 1 1

2 2<;.3'aoeiu'e.~] a      2 2 u ,. 3 x splits the table into 2x2 overlapping windows
┌───┬───┬─┐
│1 0│0 0│0│
│0 1│1 1│1│
├───┼───┼─┤
│0 1│1 1│1│
│1 1│1 1│1│
├───┼───┼─┤
│1 1│1 1│1│
└───┴───┴─┘

```

I need to check if all the 4 chars are vowels, so I add the numbers (reduce with addition `+/` the flattened list):

```
    2 2+/@,;.3'aoeiu'e.~] a
2 2 1
3 4 2
2 2 1
   (t=.4:i.~,)2 2+/@,;.3'aoeiu'e.~] a   flattens the list, finds the first
4                                        occurence of 4 in it and saves it in `t`

```

If 4 is not found J returns the length of the list. That's why I compare the result with the length of the flattened list:

```
   (#@,~:t=.4:i.~,)2 2+/@,;.3'aoeiu'e.~] a    (0 means not found; 1 - found)
0

u`v@.y     '@.' is 'agenda' - checks the value of y and uses it as an index to the
train of verbs on the left. 0 > u; 1 -> v and so on.

```

If `0`, it simply returns 'not found'
If `1`, finds the position by converting the index to a pair of numbers in a number system denoted by the size of the input `$#:t`:

```
  3 3#:4          (t is the index of 4, #: convert to antibase, the base is
1 1               the shape of the table, $)

```

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


title: Area of an ASCII polygon

text:
# Question
Title: Area of an ASCII polygon
You should write a program or function which receives a string representing an ascii-art polygon as input and outputs ot returns the area of the polygon.

The input is a string consisting of the characters `_ / \ L V space` and `newline` defining a simple polygon (which means no extra segments, no self-touch and no self-intersect).

The area of a single character cell is `2`

* `_` splits the cell into sizes `0` and `2`
* `\` splits the cell into sizes `1` and `1`
* `/` splits the cell into sizes `1` and `1`
* `L` splits the cell into sizes `0` and `2`
* `V` splits the cell into sizes `1` and `1` (The two sides of the `V` will always be on the same side of the polygon so they are treated together in the listing.)

Every character connects the two corners of its character cell which you expect (e.g. top left and top right in case of `V`).

An example with area of 7 (`1+2+1` in the second row and `1+1+1` in the third one):

```
 _
/ \
V\/

```

## Input

* Input will form a rectangle, i.e. there will be the same number of characters between newlines.
* There can be extra whitespace on any side of the polygon.
* Trailing newline is optional.

## Output

* A single positive integer, the area of the polygon.

## Examples

Outputs are after the last row of their inputs.

```
  _
  V

1

/L
\/

3

    /VV\
    L  /
     L/
14

  ____/\
  \    /
/\/   /
\____/

32

   /V\
  /   \__
  \     /
/\/   /V
L____/

45

```

This is code-golf so the shortest entry wins.

# Answer
> 5 votes
# CJam, ~~48 43~~ 29 bytes

```
qN-{i_9%2%U!^:U;J%D%1U2*?}%:+

```

*Update*: Golfed a lot using maths and the state\*2 trick from orlp's answer.

**How it works (Outdated, updating soon)**

We split the input on newline and then for each part we maintain a counter of occurrences of boundary characters `L\/`. This counter % 2 will tell us which of the two partitions amounts to choose for all of the characters. Then we find the index of each character in the string `L _`. `\/V` will give `-1` referring to the last element in an array. After getting the index, we use `4558Zb2/` to create the array `[[2 0] [0 2] [0 2] [1 1]]` and then choose the correct of the count using the counter.

```
qN/0f{                                  }      e# Split the input on newline and for each
      \{                             }/        e# swap the 0 to back and for each char in
                                               e# the line, run this loop
        _"L _"#                                e# Copy the char and get index of it in
                                               e# this string "L _"
               4558Zb                          e# This is basically 4558 3base
                                               e# which comes to be [2 0 0 2 0 2 1 1]
                     2/=                       e# Group into pairs of 2 and choose the
                                               e# correct one.
                        2$=                    e# Based on the counter, choose the correct
                                               e# partition amount
                           @@"\/L"&,+          e# Increment the counter if the char is one
                                               e# of \, / and L
                                       ;       e# Pop the counter after each line loop
                                         :+    e# Sum all the numbers to get area

```

Try it online here

# Answer
> 22 votes
# Pyth, 47 46 45 36 30

```
FNs.zx=Z}N"\/L"aY|}N"\/V"yZ;sY

```

Explanation:

```
FNs.z            For every character in input, except newlines...
  x=Z}N"\/L"     Swap state if /, \, or L.
  aY|}N"\/V"yZ;  Append 1 if /, \, or V, else 2 times the state to Y.
sY               Sum Y and print.

```

We have two states, "in the polygon", and "out of the polygon". The following characters each do the following when reading them from top-left to bottom-right:

```
/ \     swap state, add one to area
V                   add one to area
_ space             if in polygon, add two to area
L       swap state, if in polygon, add two to area

```

Note that "add one to area" and "if in polygon, add two to area" are mutually exclusive.

# Answer
> 14 votes
# Retina, 293 + 15 = 308 ~~314~~ ~~385~~ bytes

```
;`\s
_
;`\\
/
;`.+
o$0iio
;+`(o(?=/.*(i)|L.*(ii)|V.*(io)|_)|i(?=/.*(io)|L.*(o)|_.*(ii)|V.*(i))).
$1$2$3$4$5$6$7$8
;`o
<empty>
;`ii$
#:0123456789
;+`^(?=i)(i*)\1{9}(?=#.*(0)|i#.*(1)|ii#.*(2)|iii#.*(3)|iiii#.*(4)|iiiii#.*(5)|iiiiii#.*(6)|iiiiiii#.*(7)|iiiiiiii#.*(8)|iiiiiiiii#.*(9))
$1#$2$3$4$5$6$7$8$9$10$11
:.*|\D
<empty>

```

Each line goes in a separate file, so I've added 13 to the byte count. Alternatively, you can put that all in a single file as is and use the `-s` flag. The `<empty>` stand for actually empty files or lines.

Unfortunately, I need 187 bytes just to convert the result from unary to decimal. I guess I really should implement this some time soon.

## Explanation

Retina is a regex-based language (which I wrote exactly for being able to do stuff like this with regex). Each pair of files/lines defines a replacement stage, with the first line being the pattern and the second line the replacement string. Patterns can be preceded by a ```-delimited configuration string, which may contain the usual regex modifiers, as well as some Retina-specific options. For the above program, the relevant options are `;`, which suppresses output of that stage and `+`, which applies the replacement in a loop until the result stops changing.

The idea of the solution is to count each line separately, because we can always decide by the characters already encountered whether we're inside or outside the polygon. This also means I can join the entire thing into a single line, because going the beginning and end of a line are always outside the polygon. We can also note that `_` and space are completely identical for a line sweep algorithm, as well as `\` and `/`. So as a first step I replace all newlines and spaces by `_` and all `\` by `/` to simplify some code later on.

I'm keeping track of the current inside/outside state with the characters `i` and `o`, while also using the `i`s to tally the area. To do so I start by prepending an `o` to the joined line to mark that we're outside the polygon. I'm also adding an `iio` to the very end of the input, which I'll use as a lookup to generate new characters.

Then, the first large replacement simply replaces an `i` or `o` followed by one of `/V_L` with the next set of characters, thereby flooding and tallying the entire thing. The replacement table looks as follows, where the columns correspond to the last character in that line and the rows to the next character (where `S` is for space and `<>` for an empty string). I've included all characters of the input to show the equivalences I've already made use of:

```
     i     o

/    io    i
\    io    i
L    o     ii
V    i     io
_    ii    <>
S    ii    <>

```

Note that the final character then always indicates whether *after* the character we're inside or outside the polygon, while the number of `i`s corresponds to the area that needs to be added to the polygon. As an example here are the results of the first four iterations on the last example input (this was generated by an old version which actually flooded each line separately, but the principle is still the same):

```
o   /V\
o  /   \___
o  L     _/
o/\/   /V
oL__ _/
o   V

o  /V\
o /   \___
o L     _/
oi\/   /V
oii__ _/
o  V

o /V\
o/   \___
oL     _/
oiio/   /V
oiiii_ _/
o V

o/V\
oi   \___
oii     _/
oiioi   /V
oiiiiii _/
oV

oiV\
oiii  \___
oiiii    _/
oiioiii  /V
oiiiiiiii_/
oio

```

Lastly, I just get rid of all the `o`s and the line breaks by removing everything that matches `[^i]`, and the remainder is the decimal-to-unary conversion which is rather boring.

# Answer
> 4 votes
# GNU sed, 290 + 1

The + 1 is to account for the `-r` switch passed to sed. Comments and additional whitespace not counted in the score.

I haven't looked in great detail, but I think this is probably similar to Martin's Retina answer:

```
:                      # label to start processing next (or first) line
s/[0-9]//g             # remove the count of colons from previous lines
H                      # append the current line to the hold space
g                      # copy the hold space to the pattern space
y^_\\^ /^              # Replace '_' with ' ' and replace '\' with '/'
s/(\n| +$)//g          # strip newlines and trailing space
:o                     # start of "outside loop"
s/(^|:) *V/\1:/        # replace leading spaces and "V" with ":"
to                     #   if the above matches, stay outside
s/(^|:) *[|/]/\1:/     # replace leading spaces and "|" or "/" with ":"
ti                     #   if the above matches, go inside
s/(^|:) *L/\1::/       # replace leading spaces and "L" with "::"
:i                     # start of "inside" loop
s/: /:::/              # replace space with "::"
ti                     #   if the above matches, stay inside
s/:V/::/               # replace "V" with ":"
ti                     #   if the above matches, stay inside
s/:[|/]/::/            # replace "|" or "/" with ":"
to                     #    if the above matches, go outside
s/:L/:/                # remove "L"
to                     #    if the above matches, go outside
h                      # copy current string of colons to hold buffer
:b                     # start of colon count loop
s/:{10}/</g            # standard sed "arithmetic" to get string length
s/<([0-9]*)$/<0\1/
s/:{9}/9/
s/:{8}/8/
s/:{7}/7/
s/:{6}/6/
s/:{5}/5/
s/::::/4/
s/:::/3/
s/::/2/
s/:/1/
s/</:/g
tb                     # once arithmetic done, pattern buffer contains string length
N                      # append newline and next line to pattern buffer
b                      # loop back to process next line

```

### Overview

* Replace each unit of area with a colon `:`
* Count the number of colons

### Notes

* `sed` is line oriented so needs some work to process multiple lines at once. The `N` command does this by appending a newline then the next line to the current pattern space. The difficulty with `N` is that once it gets to the input stream EOF, it quits `sed` completely without any option to do further processing. To get around this, we count the current set of colons at the end of each line, just before reading in the next line.

### Output:

```
$ echo '   /V\
  /   \__
  \     /
/\/   /V
L____/' |sed -rf polyarea.sed
45
$

```

# Answer
> 4 votes
# Perl, ~~65~~ 58 bytes

```
map{map{$b^=2*y,/\\L,,;$a+=y,/\\V,,||$b}split//}<>;print$a

```
* Toggle $b between 0 and 2 upon seeing / \ or L.
* Add 1 to $a upon seeing / \ or V.
* Add $b to $a upon seeing anything else.

# Answer
> 3 votes
# C, 93 ~~96 108~~ bytes

*Edit:* Took into account suggestions in the comments, converted the while into a single-statement for loop, and removed the "i" variable entirely.

```
int s,t;main(c,v)char**v;{for(;c=*v[1]++;t+=s+(c>46^!(c%19)^s))s^=c>13^c%9>4;printf("%d",t);}

```

*Original post:*

This looked like a fun and simple enough problem to finally get me to create an account here.

```
main(c,v)char**v;{int i,t,s;i=t=s=0;while(c=v[1][i++]){s^=c>13^c%9>4;t+=s+(c>46^!(c%19)^s);}printf("%d",t);}

```

The polygon text should be passed as the first command-line argument; this should work with or without any amount of newlines / whitespace.

This just reads in the polygon one character at a time, s switches whether currently in or outside of the polygon on '/', 'L', or '\\', and t increases by 1 on '/', 'V', and '\\', or by 2 if inside / 0 if outside on 'L', '\_', space and newline.

This is my first time trying my hand at any sort of "golfing" (or C, to the extent it differs from C++), so any criticisms are appreciated!

# Answer
> 3 votes
# POSIX sed, 245 244

POSIX sed, no extensions or extended regexps. Input is limited to the maximum hold space size of sed - POSIX mandates at least 8192; GNU manages more. This version assumes that there will be no blank lines before or after the shape; an extra 10 bytes of code, indicated in the expansion, can accommodate that if it's a requirement (original question doesn't specify).

```
H
/^\([L\\]_*\/\|V\| \)*$/!d
x
s/[_ ]/  /g
s/^/!/
s/$/!/
:g
s/\([^V]\)V/V\1/
tg
y/V/ /
s/L/!  /g
s,[/\\], ! ,g
s/![^!]*!//g
:d
/ /{
s/     /v/g
s/vv/x/g
/[ v]/!s/\b/0/2
s/  /b/g
s/bb/4/
s/b /3/
s/v /6/
s/vb/7/
s/v3/8/
s/v4/9/
y/ bvx/125 /
td
}

```

## Expanded and annotated

```
#!/bin/sed -f

# If leading blank lines may exist, then delete them
# (and add 8 bytes to score)
#/^ *$/d

# Collect input into hold space until we reach the end of the figure
# The end is where all pieces look like \___/ or V
H
/^\([L\\]_*\/\|V\| \)*$/!d

x

# Space and underscore each count as two units
s/[_ ]/  /g

# Add an edge at the beginning and end, so we can delete matching pairs
s/^/!/
s/$/!/
# Move all the V's to the beginning and convert each
# to a single unit of area
:gather
s/\([^V]\)V/V\1/
tgather
y/V/ /

# L is a boundary to left of cell; / and \ in middle
s/L/!  /g
s,[/\\], ! ,g

# Strip out all the bits of outer region
s/![^!]*!//g

# Now, we have a space for each unit of area, and no other characters
# remaining (spaces are convenient because we will use \b to match
# where they end).  To count the spaces, we use roman numerals v and x
# to match five and ten, respectively.  We also match two (and call
# that 'b').  At the end of the loop, tens are turned back into spaces
# again.
:digit
/ /{
s/     /v/g
s/vv/x/g
/[ v]/!s/\b/0/2
s/  /b/g
s/bb/4/
s/b /3/
s/v /6/
s/vb/7/
s/v3/8/
s/v4/9/
y/ bvx/125 /
tdigit
}

# If trailing blank lines may exist, then stop now
# (and add 2 bytes to score)
#q

```

# Answer
> 1 votes
# C, 84 bytes

```
a;i;f(char*s){for(;*s;a+=strchr("\\/V",*s++)?1:i+i)i^=!strchr("\nV_ ",*s);return a;}

```

We switch sides whenever we see `\`, `/` or `L`; we always add one for `\\`, `/` or `V`, but add 2 (if inside) or 0 (if outside) for space, newline, `L` or `_`.

The variables `a` and `i` are assumed to be zero on entry - they must be reset if the function is to be called more than once.

### Ungolfed:

```
int a;                          /* total area */
int i;                          /* which side; 0=outside */
int f(char*s)
{
    while (*s) {
        i ^= !strchr("\nV_ ",*s);
        a += strchr("\\/V",*s++) ? 1 : i+i;
    }
    return a;
}

```

### Test program:

```
#include <stdio.h>
int main()
{
    char* s;
    s = "  _  \n"
        "  V  \n";
    printf("%s\n%d\n", s, f(s));
    a=i=0;

    s = "/L\n"
        "\\/\n";
    printf("%s\n%d\n", s, f(s));
    a=i=0;

    s = "    /VV\\\n"
        "    L  /\n"
        "     L/";
    printf("%s\n%d\n", s, f(s));
    a=i=0;

    s = "  ____/\\ \n"
        "  \\    /\n"
        "/\\/   /\n"
        "\\____/";
    printf("%s\n%d\n", s, f(s));
    a=i=0;

    s = "   /V\\\n"
        "  /   \\__ \n"
        "  \\     /\n"
        "/\\/   /V\n"
        "L____/";
    printf("%s\n%d\n", s, f(s));
    a=i=0;

    return 0;
}

```

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


title: ??? Question Marks?

text:
# Question
Title: ??? Question Marks?
**Challenge**

Create a function that takes an string as a parameter. (Easy as far)

This string will contain

* Single digit numbers
* Letters from the alphabet
* Question marks (Of course)

Your function will check if there are exactly `3 question marks` between every pair of two numbers that add up to 10 or more. If so, then your function should return `truthy`, otherwise it should return `falsey`.

If there are not any two numbers that add up to 10 or more in the string, your function should return false.

**Rules**

* Input must be a string
* Output must be `truthy` or `falsey` value
* If string contains only one number or none return `falsey`
* If string contains odd amount of single digits, ignore the last one (left to right)

**Example**

Given: `"arrb6???4xxbl5???eee5"`

Your function must output `true` because there are exactly `3 question marks` between `6` and `4`, and `3 question marks` between `5` and `5` at the end of the string

---

Given: `"a4sd???9dst8?3r"`

Your function must output `false` because there is just a `single question mark` between `8` and `3`

**Test Cases**

**Input:** `"aa6?9"`

**Output:** `false`

---

**Input:** `"acc?7??sss?3rr1??????5"`

**Output:** `true`

---

**Input:** `"sdty5???xcd8s3"`

**Output:** `true`

---

**Input:** `"sthfer5dfs"`

**Output:** `false`

---

## Update (Some clarification points)

* Once you use a number to pair with other, you can not use it again.
* You only can pair consecutive numbers (left to right). Example `"as4f???6sda3?3d"` the pairs are `4-6` and `3-3`

---

This is , so the shortest answer in bytes win.

# Answer
> 1 votes
# Python 3, 148 bytes

```
def f(a):q=[a.group(1).count("?")==3for a in re.finditer("(?=((\d+)\D+(\d+)))",a)if 10==sum(map(int,a.groups()[1:]))];return any(q)*all(q)
import re

```

Try it online!

# Answer
> 0 votes
# Python 2, 126 bytes

`all*any` idea is by @HyperNeutrino, checkout his answer

```
def f(n):r=[sum(map(int,g[0::2]))>9for g in re.findall('(\d)(.*?)(\d)',n)if 3==g[1].count('?')];return all(r)*any(r)
import re

```

Try it online!

---

# Python 2, 125 bytes

Ouputs `[]` for false and `[True]` for true

```
def f(n):r=[sum(map(int,g[0::2]))>9for g in re.findall('(\d)(.*?)(\d)',n)if 3==g[1].count('?')];return r[:1]*all(r)
import re

```

Try it online!

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


title: Minimal Triangles

text:
# Question
Title: Minimal Triangles
Make an upside down triangle of **positive** integers. Every number in the triangle must be **distinct**. Each number is the **summation** of its two parents (similar to how Pascal's triangle is constructed, but upside-down). Construct it in such a way that the bottom number is **minimized**.

For example, for input `n = 4`, here is a possible solution:

```
4  1  2  7
 5  3  9
  8  12
   20

```

A reversal of the top numbers, such as `7 2 1 4`, would also work.

For input `n = 5`, here is a possible solution:

```
7  2  1  4  6
  9  3  5 10
   12  8 15
     20 23
       43

```

The solution for `n = 2` is rather boring:

```
1 2
 3

```

The sequence of bottom numbers is described in OEIS A028307.

### Challenge

Given an input integer `n > 0` describing how many elements are in the first row, output the corresponding minimal triangle as explained above. Output can be as ASCII-art of the triangle, a list-of-lists or matrix, to STDOUT as one row per line, etc.

## Rules

* If applicable, you can assume that the input/output will fit in your language's native Integer type.
* The input and output can be given by any convenient method.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

# Answer
> 4 votes
# Jelly, 20 bytes

```
!*ṗµ+ƝÐĿ€FQƑ$Ðf-ị$ÞḢ

```

Try it online!

It's trivial to prove that there exists a solution which all elements on the first row are in range `[1,n!<sup>n</sup>]`.

Be careful as this computes an array of 10'077'696 3-element arrays for `n=3`.

---

Proof:

Let `x` be on the `k`th layer (`1 ≤ k ≤ n`, and there are `a` numbers to the left of `x`. Let `b<sub>0</sub>, b<sub>1</sub>, ..., b<sub>n-1</sub>` be the numbers on the first line.

Then:

`x = b<sub>a</sub> × (k-1 choose 0) + b<sub>a+1</sub> × (k-1 choose 1) + ... + b<sub>a+k-1</sub> × (k-1 choose k-1)`

It can be proven that all of the coefficients are non-negative and less than `n!` (except when `n=1`, in that case the algorithm gives correct result anyway), and two different numbers have two different set of coefficients.

So if the first line are chosen to be the powers of `n!` with exponent `0,1,2,...,n-1`, the value of each cell uniquely determines the set of coefficients, and thus is unique.

---

# Jelly, 19 bytes

```
!*r1œcµ_ƝÐĿ€FQƑ$ÐfṪ

```

Try it online!

Output format: Columns, upside down.

# Answer
> 1 votes
# Python 2, ~~251~~ ~~239~~ 230 bytes

-9 bytes thanks to @Mr.Xcoder

Outputs list of lines of triangle, bottom to top.

```
def F(s,d):
 if-~d==len(s):
	u=sum(s,[])
	if len(u)==len(set(u)):print s;g
 else:
	for j in range(s[d][0]):
	 s[d+1]=[j]
	 for i in s[d]:j=i-j;s[d+1]+=j,
	 if min(s[d+1])>=0:F(s,d+1)
i,I=1,input()
while i:F(eval(`[[i]]*I`),0);i+=1

```

Try it online!

Bruteforce-ish solution.
For all i in \[1 .. \] generate all possbile triangles starting from the bottom, until one with all different numbers is found.

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


title: Implement Tyrant Sort

text:
# Question
Title: Implement Tyrant Sort
## TL;DR

* Record (left-right)/length for each pair of consecutive elements. If they're 0 or negative, don't record it.
* Once this is done, take these actions. Don't update quotients:
    + Increment right and decrement left for (0, .3)
    + Remove from the array at \>=.3
    + Print both elements for \>.5
* Print the remaining array. Have some separator for executed and remaining.

Now, onto the challenge…

This is the sorting algorithm that has a worst-case of ***GLORIOUS LINEAR TIME***, and where any who dare oppose its ***INFINITE WISDOM*** will be promptly ***EXECUTED*** for their ***HEINOUS CRIME OF HIGH TREASON***.

The ***FEARLESS LEADER*** has tasked you with the ***HONORABLE MISSION*** of writing a program or function that takes in an array of integers and sorts it using the following sorting algorithm:

1. Iterate through your array, enlightening each element with the ***GLORIOUS*** presence of their ***FEARLESS LEADER***.
2. Have your ***SECRET POLICE*** check on every pair of 2 consecutive elements to make sure they are ***PROPERLY LOYAL TO THEIR NATION***. If they're not ordered correctly, record the difference between the numbers, divided by the length of the array. This is their dissent quotient.
3. At the end of your ***GLORIOUS TOUR***, go through the list and ***RAIN FEARLESS LEADER'S DIVINE PUNISHMENT*** on all of the ***TREASONOUS DISSENTERS*** as follows:
    * For a dissent quotient of less than .3, they merely need ~~brainwashing~~ a reminder of the ***INFINITE GLORY OF THE FEARLESS LEADER***. Decrement the left element and increment the right element. Don't change any dissent quotients.
    * For a dissent quotient of .3-.5 (inclusive), they are ***TRAITORS*** and should be sent to ***PRISON CAMPS***. Remove them from the array.
    * For a dissent quotient greater than .5, they are ***ODIOUS REBEL SCUM***. They should be ***PUBLICLY EXECUTED*** as an example for any other ***TREASONOUS HERETICS*** they might have allied with. Remove them from the array and send it to the national news source, The STDOUT Times.
4. Your array is now ***COMPLETELY AND FOREVER*** sorted. Send it to The STDOUT Times so they can sing of your ***GLORIOUS VICTORY***.

As ***MANDATORY VIEWING*** to those who are too ***FOOLISH*** to understand the ***INFINITE GLORY*** of this algorithm, it will be used to sort the following array:

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

```
* 1 and 8 are ordered correctly.
* 8 and 6 aren't ordered right, so the dissent quotient of .2 is recorded for both of them.
* 6 and 0 are another pair of dissenters. This dissent quotient is .6.
* 0 and 4 are ordered correctly.
* 4 and 9 are ordered correctly.
* 9 and 3 have a dissent quotient of .6.
* 3 and 5 are ordered correctly.
* 5 and 7 are ordered correctly.
* 7 and 2 have a dissent quotient of .5.

So, you take the following actions in the name of the ***FEARLESS LEADER***:

* Decrement 8 to 7, and increment 6 to 7.
* Remove 0 and the new 7, and ***EXECUTE THEM***.
* Follow with 9 and 3.
* Haul the original 7 and the 2 to the re-education camps and remove them.

This should be your press release, done in STDOUT or whatever's convenient:

```
Executions: 7, 0, 9, 3
[1, 7, 4, 5]

```

As you can see, the resulting array is ***COMPLETELY AND FOREVER SORTED***. Attempting to suggest that it isn't sorted constitutes ***HIGH TREASON***.

Now, as a ***GLORIOUS DEMONSTRATION*** of the ***UNENDING RESOURCES*** given by the ***FEARLESS LEADER***, he has provided you with his ***INFINITE WISDOM*** in generating test cases:

```
import random

len=random.randint(2,20)
arr=list(range(len))
random.shuffle(arr)
print(arr)

dissent=[(arr[i]-arr[i+1])/len for i in range(len-1)]
dissent.append(0) # Barrier between front and back of the array.
executions=[]
for i in range(len-1):
    if dissent[i] > 0:
        if dissent[i] < 0.3:
            arr[i] -= 1
            arr[i+1] += 1
        elif dissent[i] > 0.5:
            if dissent[i-1] <= 0.5:
                executions.append(arr[i])
            executions.append(arr[i+1])

print([arr[i] for i in range(len) if dissent[i] < 0.3 and dissent[i-1] < 0.3])
print(executions)

```

Try it Online \- hit the run button to use, otherwise you're just getting what the last person got.

In the interest of stare desecis, the ***FEARLESS LEADER*** has also provided an edge case example:

```
Input                  Output
3,2,1,4,4,1,2,3,4,5    2,2,2,4,2,3,4,5

```

(There are no executions in this example.)

Finally, you should treat the bytes in your program as key supporters and minimize them. The shortest program in bytes will win the ***ETERNAL FAVOR OF THE FEARLESS LEADER***.

## Credit where it's due

The concept for this was inspired by Lazy Drop Sort, and the writing style used was largely taken from Psychotic Dictatorships—go visit them if you enjoyed the parody aspect of this.

Additional credit goes to everyone who voted on this in the Sandbox early on. The +8 it attained was my motivation to rewrite it to avoid duplication.

# Answer
# Ruby, ~~146~~ 135 bytes

```
->l{e=[];i=0;l.inject{|j,k|q=(j-k)*10.0/l.size;b,c=l[i],l[i+=1];q>5&&e<<b<<c;q>0&&(l[i-1],l[i]=q<3?[b&&b-1,c&&c+1]:p);k};[l-a=[a],e-a]}

```

Try it online!
> 2 votes

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


title: Checkers Checker

text:
# Question
Title: Checkers Checker
The goal of this challenge is to determine if a move is a legal English Checkers move.

This challenge will use an 8x8 board. A moved piece should be treated as a man (not a king) that can only move diagonally forward. The board will have 0 or more black pieces and 1 or more white piece. One white piece will be currently moving. The white piece can "jump" over one black piece diagonally in front of it if the square directly behind it is empty. It is possible to take a further jump from that position if there is another black piece in either direction diagonally in front of it. Capture is mandatory, so it is illegal to not take a jump that is available. However, it is not mandatory to take a path that maximizes the number of jumps. Basically, this means that if you make a jump and there is another possible jump from the ending position then that move is illegal. Piece positions use the following numbering scheme:

---

### Rules

Inputs:

* A list of numbers that represent black pieces.
* A list of numbers that represent white pieces.
* A starting position for the white piece
* The ending position for the white piece

Output:

* A truthy value if the move is valid, otherwise a falsey value

You can assume a white piece will always occupy the starting position.

If convenient, you can assume that the first white piece in the white piece list will contain the starting position instead of accepting input 3.

Standard code golf rules. Fewest bytes wins.

---

### Test Cases

To illustrate, O is the starting position, X is the ending position, B are black pieces, and W are white pieces

```
Black pieces: []
White pieces: [5]
Move: (5, 1)
Output: True

Single move no jump
 X _ _ _
O _ _ _

B: [6]
W: [9]
M: (9, 2)
O: True

Single jump
 _ X _ _
_ B _ _
 O _ _ _

B: [2, 6]
M: (9, 2)
O: False

Illegal ending position on top of black piece
 _ X _ _
_ B _ _
 O _ _ _

B: [7, 14]
W: [17]
M: (17, 3)
O: True

Double jump
 _ _ X _
_ _ B _
 _ _ _ _
_ B _ _
 O _ _ _

B: [7, 14]
M: (17, 10)
O: False

Illegal jump, must take the next jump as well
 _ _ _ _
_ _ B _
 _ X _ _
_ B _ _
 O _ _ _

B: [4]
W: [8]
M: (8, 3)
O: False

Illegal jump across the board
 _ _ _ X
B _ _ _
 O _ _ _

B: [6, 7]
W: [6]
M: (10, 1)
O: True

Split decision p1
 X _ _ _
_ B B _
 _ O _ _

B: [6, 7]
M: (10, 3)
O: True

Split decision p2
 _ _ X _
_ B B _
 _ O _ _

B: [2]
W: [1]
M: (1, 3)
O: False

Sideways Jump
 O B X _

B: [6]
W: [1]
M: (1, 10)
O: False

Backwards Jump
 O _ _ _
_ B _ _
 _ X _ _

B: [6]
W: [9, 2]
M: (9, 2)
O: False

Illegal ending position on top of white piece
 _ X _ _
_ B _ _
 O _ _ _

B: []
W: [9, 6]
M: (9, 2)
O: False

Illegal jump over white piece
 _ X _ _
_ W _ _
 O _ _ _

B: [8, 15, 23, 24]
W: [27]
M: (27, 4)
O: True

Split decision long path
 _ _ _ X
_ _ _ B
 _ _ _ _
_ _ B _
 _ _ _ _
_ _ B B
 _ _ W _

B: [8, 15, 23, 24]
W: [27]
M: (27, 20)
O: True

Split decision short path
 _ _ _ _
_ _ _ B
 _ _ _ _
_ _ B _
 _ _ _ X
_ _ B B
 _ _ W _

```

# Answer
That was challenging :) * fixed bugs (added bytes)

# JavaScript (Node.js), 197 193 191 185 181 186 bytes

```
f=(B,W,S,E,F=1)=>g(S).filter((x,i)=>B[I="includes"](x)&!B[I](t=g(x)[i])&!W[I](t)&&t>0?F+=f(B,W,t,E):0)[0]?F>1:g(S)[I](E)
g=S=>[S--,!(y=~-(e=S-3)/4%2|0)||S%4^3?y?e+1:e:0,S%4||y?y?e:e-1:0]

```

Try it online!
> 1 votes

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