# Question
Title: Generate the k-ary necklaces of length n
The set of necklaces is the set of strings, where two strings are considered to be the same necklace if you can rotate one into the other. Your program will take nonnegative integers `k` and `n`, and generate a list of the `k`-ary (fixed) necklaces of length `n`.

Necklaces will be represented by any representative string. So the necklace corresponding to the strings {ABC, BCA, CAB} can represented as `ABC`, `BCA`, *or* `CAB`.

The program will output a list of strings, such that each necklace is represented by *exactly one* string in the list. So for instance, outputting `ABC` and `BCA` would not be valid, since the same necklace was represented twice.

Some other details:

* Your program may choose which `k` characters to use for the alphabet. If you prefer, you can instead choose `k` distinct values of any type, and have your program output lists (or some other sequence type) of those `k` values. (This might in fact be necessary if `k` is greater than the number of characters avaible in your language.) For example, if `k=3`, you could use {A,B,C}, {&, H, (}, or even {10, 11, 12} as your alphabet. The only restriction is that elements of your alphabet may not contain whitespace.
* You may output any representative for each necklace. So for the necklace {ABC, BCA, CAB}, you may output `ABC`, `BCA`, or `CAB`. There is no "preferred" representative.

This is , so the shortest program wins!

---

Also, here is a useful test to see if your program is working. Given `k` and `n`, the list your program outputs have the length listed here. Here is an OEIS sequence corresponding to `k`=2.

Also, here are some examples and counterexamples. Note that these are not test cases, because any input has both an infinite number of correct and incorrect outputs. I will give inputs in the form `(k,n)`.

Examples:

* `(2,2)`: `[AA, BB, AB]`
* `(2,2)`: `[AA, BA, BB]`
* `(2,2)`: `[[1,0], [0,0], [1,1]]`
* `(3,2)`: `[AA, BB, CC, AB, BC, AC]`
* `(2,3)`: `[AAA, BBB, AAB, ABB]`
* `(3,3)`: `[AAA, BBB, CCC, AAB, AAC, ABB, ABC, ACB, ACC, BBC, BCC]`
* `(0,n)`: `[]` (for positive integers n)
* `(k,0)`: `[[]]` (for nonnegative integers k)
* `(k,n)`: Search "necklaces with k colors and n beads" on wolfram alpha (for positive integers k and n)

Counterexamples:

* `(2,2)`: `[AA, BB, AB, BA]`
* `(2,2)`: `[AA, BB]`
* `(3,3)`: `[AAA, BBB, CCC, AAB, AAC, ABB, ABC, ACC, BBC, BCC]`
* `(3,3)`: `[AAA, BBB, CCC, AAB, BAA, AAC, ABB, ABC, ACB, ACC, BBC, BCC]`
* `(k,n)`: Any list whose length is different from this (for positive integers n)
* `(3,3)`: `[AAA, BBB, CCC, AAB, BAA, AAC, ABB, ABC, ACC, BBC, BCC]`

# Answer
# Jelly, 8 bytes

```
ṗṙJṂȯƲ€Q

```

A dyadic Link accepting the alphabet size, `k`, on the left and the necklace length, `n`, on the right which yields a list of the necklaces using the positive integers up to `k` as the alphabet.

**Try it online!**

### How?

```
ṗṙJṂȯƲ€Q - Link: integer k, integer n
ṗ        - Cartesian power of [1,2,...,k] with n
         -   i.e. all n-length lists using alphabet [1,2,...,k]
     Ʋ€  - last four links as a monad for €ach list, L:
  J      -   range of length - i.e. [1,2,...,n]
 ṙ       -   rotate left by each of those values - i.e. get all rotations
   Ṃ     -   minimum
    ȯ    -   logical OR with L (since the minimum of an empty list is 0 not [])
      Q  - unique values the resulting list

```
> 3 votes

# Answer
# Python 2, 105 bytes

```
lambda k,n:{min(i[j:]+i[:j]for j in range(n or 1))for i in product(*[range(k)]*n)}
from itertools import*

```

Try it online!

Returns a set of tuples.
> 2 votes

# Answer
# JavaScript (ES7),  ~~123 116 115~~  113 bytes

Takes input as `(k)(n)`. Each necklace is represented as an array of integers.

```
k=>g=(n,x=k**n,o=[])=>x--?g(n,x,o.some(a=>~(a+[,a]).search(b),b=[...Array(n)].map(_=>x/k**--n%k|0))?o:[b,...o]):o

```

Try it online!
> 1 votes

# Answer
# Japt, 27 bytes

```
?UÆVoÃrï ®c £ZéYÃn gÃâ:[[]]

```

Try it online!

Outputs with numbers starting from 0 for the values. Inputs in reversed order (`n` then `k`). The `r` throws a fit for `n = 0` so I had to add an significant special-case.

Explanation:

```
?                     :[[]]    #Special case: return [[]] if n is 0
 UÆ  Ã                         #Get n rows of:
   Vo                          # The numbers [0..k-1]
      rï                       #Get all possible lists containing one number from each row...
         ®          Ã          #For each of those lists:
          c                    # Fix the formatting
            £ZéYÃ              # Get every possible rotation
                 n g           # Choose the "minimum" one
                     â         #Remove duplicate lists

```
> 0 votes

# Answer
# Charcoal, 37 bytes

```
Ｎθ≔Ｘθ…⁰⊕Ｎη≔⊟ηζ¿ηＩＥΦζ⁼κ⌊﹪÷×ι⊕ζηζ﹪÷ιηθ¶

```

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

```
Ｎθ≔Ｘθ…⁰⊕Ｎη≔⊟ηζ

```

Input `k` and `n` and calculate the powers of `k` from `1` to `n`, but then keep `kⁿ` separately.

```
¿η...¶

```

If `n` is zero then just print a newline. (I could special-case `0` in the algorithm which would only cost two bytes but the resulting array only contains an empty array and Charcoal optimises that away on output, so you can't tell that the empty array is there.)

```
Φζ⁼κ⌊﹪÷×ι⊕ζηζ

```

For all the numbers from `0` to `kⁿ`, multiply them all by `kⁿ+1`, then divide by the above powers of `k`, then take the modulus of all of them by `kⁿ`. Keep only those numbers which equal the minimum of the resulting set.

```
ＩＥ...﹪÷ιηθ

```

Convert the numbers to reversed base `k` padded to length `n` for output using Charcoal's default output which is each element on its own line and each necklace double-spaced from the next necklace.
> 0 votes

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


title: Finding Not-Quite-Prime Numbers

text:
# Question
Title: Finding Not-Quite-Prime Numbers
Your challenge, should you chose to accept it, is to code-golf a function that returns true or false (or some similar meaningful representation of yes and no) if a number meets the following criteria:

1. The integer itself is a prime number OR
2. Either of its neighbor integers are prime

For example:
An input of `7` would return True.
An input of `8` would also return True.
An input of `15` would return False. (Neither 14, 15, or 16 are prime)

The input must be able to return correctly for numbers between 2^0 and 2^20 inclusive, so there's no need to worry about sign issues or integer overflows.

# Answer
> 11 votes
# J, 17

```
*/<:$&q:(<:,],>:)

```

Returns booleans encoded as process return codes: zero for true, nonzero for false. Sample use:

```
   */<:$&q:(<:,],>:) 7
0
   */<:$&q:(<:,],>:) 8
0
   */<:$&q:(<:,],>:) 15
3

```

# Answer
> 9 votes
## Haskell, 47 characters

```
f n=any(\k->all((>0).mod k)[2..k-1])[n-1..n+1]

```

# Answer
> 6 votes
## Python 85 80

```
def f(n):g=lambda n:all(n%i!=0for i in range(2,n));return g(n)or g(n-1)or g(n+1)

```

First time on Code Golf so there's probably some tricks I'm missing.

# Answer
> 5 votes
Not a real contender in code shortness by any means, but still submitting since determining primeness *by regular expression* is twisted in many ways!

## Python (2.x), 85 characters

```
import re
f=lambda n:any(not re.match(r"^1?$|^(11+?)\1+$","1"*x)for x in[n,n-1,n+1])

```

# Answer
> 4 votes
# Ruby (55, or 50 as lambda)

```
def f q;(q-1..q+1).any?{|n|(2..n-1).all?{|d|n%d>0}};end

```

or as lambda (use `g[23]` to call it)

```
g=->q{(q-1..q+1).any?{|n|(2..n-1).all?{|d|n%d>0}}}

```

# Coffeescript (53)

```
p=(q)->[q-1..q+1].some (n)->[2..n-1].every (d)->n%d>0

```

# Answer
> 3 votes
The boring **Mathematica, 35** solution!

```
PrimeQ[n-1]||PrimeQ[n]||PrimeQ[n+1]

```

# Answer
> 3 votes
## C, 112 82 72 characters

Following Ilmari Karonen's comment, saved 30 chars by removing `main`, now `P` returns true/false. Also replaced loop with recursion, and some more tweaks.

```
p(n,q){return++q==n||n%q&&p(n,q);}P(n){return p(-~n,1)|p(n,1)|p(~-n,1);}

```

Original version:

```
p(n,q,r){for(r=0,q=2;q<n;)r|=!(n%q++);return!r;}
main(int n,int**m){putchar(48|p(n=atoi(*++m))|p(n-1)|p(n+1));}

```

# Answer
> 3 votes
# Mathematica, 24 bytes

Don't know why this old post showed up in my list today, but I realized Mathematica is competitive here.

```
Or@@PrimeQ/@{#-1,#,#+1}&

```

Unnamed function taking an integer argument and returning `True` or `False`. Direct implementation.

# Answer
> 3 votes
# Stax, 6 bytes

```
Ç▀<╝ºΩ

```

Run and debug it

Explanation (unpacked):

```
;v:Pv<! Full program, implicit input  Example: 7
;v      Copy input and decrement               7 6
  :P    Next prime                             7 7
    v   Decrement                              7 6
     <! Check if input is >= result            1

```

# Answer
> 2 votes
## JavaScript (71 73 80)

```
n=prompt(r=0);for(j=n-2;p=j++<=n;r|=p)for(i=1;++i<j;)p=j%i?p:0;alert(r)

```

Demo: http://jsfiddle.net/ydsxJ/3/

**Edit 1:** Change `for(i=2;i<j;i++)` to `for(i=1;++i<j;)` (thanks `@minitech`). Convert `if` statement to ternary. Moved `r|=p` and `p=1` into outer `for` to eliminate inner braces. Saved 7 characters.

**Edit 2:** Combine `p=1` and `j++<=n` to `p=j++<=n`, save 2 chars (thanks `@ugoren`).

# Answer
> 2 votes
# Regex (ECMAScript), 20 bytes

`^x?x?(?!(x+)(x\1)+$)`

Try it online!

The above version does not correctly handle zero, but that only takes 1 extra byte:

`^x?x?(?!(x+)(x\1)+$)x`

As an added bonus, here's a version that gives a return match of `1` for one less than a prime, `2` for prime, and `3` for one more than a prime:

`^x?x??(?!(x+)(x\1)+$)x`

Try it online!

# Answer
> 1 votes
# C#, 96

It returns -1,0,1 for true, anything else is false.

Any suggestions to make it shorter would be wonderful!

```
int p(int q){var r=q-1;for(var i=2;i<r&r<q+2;i++){if(i==r-1)break;if(r%i==0)r+=i=1;}return r-q;}

```

Expanded form:

```
int p(int q){
    var r=q-1;
    for(var i=2;i<r&r<q+2;i++){
        if(i==r-1)break;
        if(r%i==0)r+=i=1;
    }
    return r-q;
}

```

# Answer
> 1 votes
## GolfScript: 26

```
)0\{.:i,{i\%!},,2=@|\(}3*;

```

Explanation: The innermost block `{.:i,{i\%!},,2=@|\(}` determines if the top of the stack is prime by checking if there are exactly 2 factors less than the top of the stack. It then disjuncts this with the second item on the stack, which holds the state of whether a prime has been seen yet. Finally, it decrements the number on the top of the stack.

Start by incrementing the input, initializing the prime-seen state, and repeat the block 3 times. Since this will decrement twice, but we started by incrementing, this will cover `n+1` and `n-1`.

# Answer
> 1 votes
# C#, 87 97 chars

```
bool p(int q){return new[]{q-1,q,q+1}.Any(x=>Enumerable.Range(2,Math.Abs(x-2)).All(y=>x%y!=0));}

```

# Answer
> 1 votes
# CJam, 12 bytes

CJam is much younger than this challenge, so this answer is not eligible for the green checkmark (which should be updated to randomra's answer anyway). However, golfing this was actually quite fun - I started at 17 bytes and then changed my approach completely three times, saving one or two bytes each time.

```
{(3,f+:mp:|}

```

This is a block, the closest equivalent to a function in CJam, which expects the input on the stack, and leaves a 1 (truthy) or 0 (falsy) on the stack.

Test it here.

Here is how it works:

```
(3,f+:mp:|
(          "Decrement the input N.";
 3,        "Push an array [0 1 2].";
   f+      "Add each of those to N-1, to get [N-1 N N+1].";
     :mp   "Test each each element for primality, yielding 0 or 1.";
        :| "Fold bitwise OR onto the list, which gives 1 if any of them was 1.";

```

# Answer
> 1 votes
## F#, 68 bytes

```
let p n=Seq.forall(fun x->n%x>0){2..n-1}
let m n=p(n-1)||p n||p(n+1)

```

Try it online!

This is why I love code golf. I'm still very green with F# but I learn so much about how the language works and what it can do from these kinds of challenges.

# Answer
> 1 votes
# APL (Dyalog Classic), 20 bytes

```
0∊¯1 0 1∘+∊(∘.×⍨1↓⍳)

```

Try it online!

# Answer
> 1 votes
# Retina, 22 bytes

```
$
1
^1?1?(?!(11+)\1+$)

```

Try it online!

Takes unary as input

# Answer
> 1 votes
# Java 8, 83 bytes

```
n->n==1|p(n-1)+p(n)+p(n+1)>0int p(int n){for(int i=2;i<n;n=n%i++<1?0:n);return--n;}

```

Returns `true` / `false` as truthy/falsey values.

Try it online.

**Explanation:**"

```
n->                    // Method with integer parameter and boolean return-type
  n==1                 //  Return whether the input is 1 (edge-case)
  |p(n-1)+p(n)+p(n+1)>0//  Or if the sum of `n-1`, `n`, and `n+1` in method `p(n)` is not 0

int p(int n){          // Separated method with integer as both parameter and return-type
  for(int i=2;i<n;     //  Loop `i` in the range [2, `n`)
    n=n%i++<1?         //   If `n` is divisible by `i`
       0               //    Change `n` to 0
      :                //   Else:
       n);             //    Leave `n` as is
                       //  (After the loop `n` is either 0, 1, or unchanged,
                       //   if it's unchanged it's a prime, otherwise not)
  return--n;}          //  Return `n` minus 1

```

So `int p(int n)` will result in `-1` for `n=0` and non-primes, and will result in `n-1` for `n=1` or primes. Since `p(0)+p(1)+p(2)` will become `-1+0+1 = 0` and would return false (even though `2` is a prime), the `n=1` is an edge case using this approach.

---

A single loop without separated method would be **85 bytes**:

```
n->{int f=0,j=2,i,t;for(;j-->-1;f=t>1?1:f)for(t=n+j,i=2;i<t;t=t%i++<1?0:t);return f;}

```

Returns `1` / `0` as truthy/falsey values.

Try it online.

**Explanation:**

```
n->{              // Method with integer as both parameter and return-type
  int f=0,        //  Result-integer, starting at 0 (false)
      j=2,i,      //  Index integers
      t;          //  Temp integer
  for(;j-->-1;    //  Loop `j` downwards in range (2, -1]
      f=          //    After every iteration: Change `f` to:
        t>1?      //     If `t` is larger than 1 (`t` is a prime):
         1        //      Change `f` to 1 (true)
        :         //     Else:
         f)       //      Leave `f` the same
    for(t=n+j,    //   Set `t` to `n+j`
        i=2;i<t;  //   Inner loop `i` in the range [2, t)
      t=t%i++<1?  //    If `t` is divisible by `i`:
         0        //     Change `t` to 0
        :         //    Else:
         t);      //     Leave `t` the same
                  //   (If `t` is still the same after this inner loop, it's a prime;
                  //   if it's 0 or 1 instead, it's not a prime)
  return f;}      //  Return the result-integer (either 1/0 for true/false respectively)

```

# Answer
> 1 votes
# Japt, 7 bytes

```
´Uô2 dj
´Uô2    // Given the range [U-1..U+1],
     dj // sing "Daddy DJ", uh, I mean, check if any are a prime.

```

Try it online!

# Answer
> 1 votes
# Jelly, 5 bytes

```
‘r’ẒẸ

```

Try it online!

### How it works

```
‘r’ẒẸ    Monadic main link. Input: integer n
‘r’      Generate range n-1..n+1
   ẒẸ    Is any of them a prime?

```

# Answer
> 0 votes
## C++

```
k=3;cin>>i;i--;
while(k)
{l[k]=0;
  for(j=2;j<i;j++)
   if(!(i%j))
     l[k]++;
  k--;
  i++;
}
if(!l[1]|!l[2]|!l[3])
     cout<<"1";
else cout<<"0";

```

# Answer
> 0 votes
# Q, 43 chars 36

```
~~{any min each a mod 2_'til each a:x+-1 0 1}~~
```

```
{any(min')a mod 2_'(til')a:x+-1 0 1}

```

# Answer
> 0 votes
## R, 68 chars

```
f=function(n){library(gmp);i=isprime;ifelse(i(n-1)|i(n)|i(n+1),1,0)}

```

Usage (1 for TRUE, 0 for FALSE):

```
f(7)
[1] 1
f(8)
[1] 1
f(15)
[1] 0

```

# Answer
> 0 votes
## J, 16 chars

```
   (_2&<@-4 p:]-2:)

   (_2&<@-4 p:]-2:) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
1 1 1 1 1 1 1 1 0 1 1 1 1 1 0 1 1 1 1

```

# Answer
> 0 votes
**Python, ~~69~~ 67 chars**

```
any(all(i%j for j in range(2,i))for i in range(input()-1,8**7)[:3])

```

`8**7 > 2**20` while being slightly shorter to write

# Answer
> 0 votes
# Ruby, 47 chars but very readable

```
require'Prime'
f=->x{[x-1,x,x+1].any? &:prime?}

```

# Answer
> 0 votes
**C++ 97**

ugoren seems to have beat me to the clever solution. So he's a shortish version on the loop three times approach:

```
P(int k){int j=1;for(int i=2;i<k;){j=k%i++&&j;}return j;}
a(int b){return P(b)|P(b+1)|P(b-1);}

```

# Answer
> 0 votes
# Forth (gforth), 104 bytes

```
: p dup 1 > if 1 over 2 ?do over i mod 0> * loop else 0 then nip ;
: f dup 1- p over 1+ p rot p + + 0< ;

```

Try it online!

## Explanation

Prime check (p)

```
dup 1 > if          \ if number to check if greater than 1
   1 over 2 ?do     \ place a 1 on the stack to act as a boolean and loop from 2 to n
      over i  mod   \ take the modulo of n and i
      0> *          \ check if greater than 0 (not a divisor) and multiply result by boolean
   loop             \ end the loop, result will be -1 if no divisor was found (prime)
else                \ if n is less than 2
   0                \ put 0 on the stack (not prime)
then                \ end the loop
nip                 \ drop n from the stack

```

Main Function (f)

```
dup 1- p             \ get n-1 and check if prime
over 1+ p            \ get n+1 and check if prime
rot p                \ rotate stack to put n on top and check if prime
+ + 0<               \ add the three results and check if less than 0 (at least 1 was prime)

```

# Answer
> 0 votes
# Julia 0.4, 23 bytes

```
n->any(isprime,n-1:n+1)

```

Try it online!

# Answer
> 0 votes
# APL(NARS) 13 chars, 26 bytes

```
{∨/0π⍵+¯1..1}

```

Here {0π⍵} is the function says if its argument it is a prime (return 1\[true\], else it return 0\[false\]), that function can have argument both one scalar integer or one list of integers as the above case... test:

```
  f←{∨/0π⍵+¯1..1}
  f¨1 2 7 8 14 15 16 (2*20)
1 1 1 1 1 0 1 0

```

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


title: A Turtle Finds a Portal

text:
# Question
Title: A Turtle Finds a Portal
The turtle wants to move along the grid to get to his food. He wants to know how many moves it will take for him to get there.

As well since he is slow he has teleporters set up around his domain that he will utilize if it shortens his path. Or avoid them if it lengthens his path.

## *Meet the turtle*

The turtle lives on a grid $$\begin{matrix} X&X&X&X&X\\ X&X&X&X&X\\ X&X&&X&X\\ X&X&X&X&X\\ X&X&X&X&X\\ \end{matrix}$$ The turtle can move to any adjacent square... $$\begin{matrix} X&X&X&X&X\\ X&\nwarrow&\uparrow&\nearrow&X\\ X&\leftarrow&&\rightarrow&X\\ X&\swarrow&\downarrow&\searrow&X\\ X&X&X&X&X\\ \end{matrix}$$

However, the turtle cannot move to a square with a mountain $$\begin{matrix} X&&X&X&X\\ X&\nwarrow&\uparrow&\nearrow&X\\ X&&&\rightarrow&X\\ X&&\downarrow&\searrow&X\\ X&&X&X&X\\ \end{matrix}$$

The Turtle wants to eat his Strawberry, and would like to know how long it will take to get to his Strawberry $$\begin{matrix} X&&\\ &&X\\ X&&X\\ X&X&X\\ \end{matrix}$$ This example would take the turtle \\$5\\$ turns $$\begin{matrix} X&&\\ \downarrow&&\uparrow\\ \searrow&&\uparrow\\ X&\nearrow&X\\ \end{matrix}$$ Luckily, the Turtle found a teleporter! There are two teleports on the grid that map to each other. Stepping on the teleporter immediately moves the turtle to the corresponding teleporter. Teleporters are very unstable and after using them once, they disapear and are no longer useable. $$\begin{matrix} &&\\ &&\\ X&&X\\ X&X&X\\ \end{matrix}$$ It is now faster for the turtle to move up twice. Now the turtles shortest path is \\$2\\$ $$\begin{matrix} &&\\ \uparrow&&\uparrow\\ X&&X\\ X&X&X\\ \end{matrix}$$

## The challenge

Given an initial grid configuration output the number of moves it will take the turtle to reach his strawberry.

## Rules

* You may assume that the input grid has a solution
* Each grid will only have one `strawberry` and two `portals` and one `turtle`
* The input grid may be entered in any convenient format
* You should treat `teleporters` are single use items
* The turn that the turtle moves onto a `teleporter` square he is already on the corresponding `teleporter`. He never moves onto a `teleporter` and stays there for a move
* The shortest path does not need to make use of the portal
* The turtle cannot pass into mountain tiles
* You may use any ASCII character or integer to represent `mountains`, `turtle`, `empty grid square`, `strawberry`
* You may use either the same character or two different ASCII characters or integers to represent the `teleporter` pairs
* A grid can have more than one path with the same shortest path length
* This is

## Clarifications to Rules

* You should treat `teleporters` are single use items.

**Reasoning**: It was pointed out that the case of: $$\begin{matrix} &X&&X&\\ &&&&&\\ &X&X&X&X \end{matrix}$$

Could be only solved by entering and exiting the portals twice. At the time of making this clarification both solutions acted by assuming they were either single use, or there was no reason to try previously used squares. To avoid breaking their hard-worked solutions, this seemed the best way account for this set up. Therefore, this would be considered an invalid grid.

## Test Cases formatted as lists

```
[ ['T', 'X', 'X', 'S', 'X'], ['X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X'] ] --> 3
[ ['T', 'M', 'X', 'S', 'X'], ['X', 'M', 'X', 'X', 'X'], ['O', 'X', 'X', 'X', 'O'] ] --> 4
[ ['T', 'M', 'X', 'S', 'O'], ['O', 'M', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X'] ] --> 2
[ ['T', 'M', 'X', 'S', 'X'], ['O', 'M', 'X', 'X', 'X'], ['O', 'X', 'X', 'X', 'X'] ] --> 4
[ ['T', 'M', 'S', 'X', 'O'], ['X', 'M', 'M', 'M', 'M'], ['X', 'X', 'X', 'X', 'O'] ] --> 7
[ ['T', 'X', 'X', 'S', 'X'], ['O', 'M', 'M', 'M', 'X'], ['X', 'X', 'O', 'X', 'X'] ] --> 3

```

## Test Cases formatted for humans

```
T X X S X
X X X X X
X X X X X --> 3

T M X S X
X M X X X
O X X X O --> 4

T M X S O
O M X X X
X X X X X --> 2

T M X S X
O M X X X
O X X X X --> 4

T M S X O
X M M M M
X X X X O --> 7

T X X S X
O M M M X
X X O X X --> 3

```

**Credits**

Design and structure via: *Hungry mouse by Arnauld*

Proposed Challenges Edit Advice: *Kamil-drakari*, *beefster*

General Edit Advice: *okx* *nedla2004* *mbomb007*

# Answer
> 13 votes
# JavaScript (ES7),  ~~140 139~~  138 bytes

Takes input as a matrix of integers with the following mapping:

* \\$-1\\$ = (any portal)
* \\$0\\$ = \\$X\\$ (empty)
* \\$1\\$ = (mountain)
* \\$2\\$ = (turtle)
* \\$3\\$ = (strawberry)

```
m=>(R=g=(t,X,Y,i)=>m.map((r,y)=>r.map((v,x)=>r[(u=0,t?v-t:(x-X)**2+(y-Y)**2<3?v-3?~v?v:u--:R=R<i?R:i:1)||g(u,x,y,u-~i,r[x]=1),x]=v)))(2)|R

```

Try it online!

### How?

The main recursive search function \\$g\\$ is able to either look for a specific tile \\$t\\$ on the board (if it's called with \\$t\ne 0\\$) or for any tile at \\$(x,y)\\$ which can be reached from the current position \\$(X,Y)\\$.

It keeps track of the length of the current path in \\$i\\$ and updates the best result \\$R\\$ to \\$\min(R,i)\\$ whenever the turtle finds the strawberry.

It is first called with \\$t=2\\$ to find the starting position of the turtle.

It calls itself with \\$t=-1\\$ if a portal is reached, so that the turtle is teleported to the other portal. We do not increment \\$i\\$ during such an iteration.

Each visited tile is temporarily set to a mountain to prevent the turtle from moving twice on the same tile in the same path. If we get trapped in a dead-end, the recursion simply stops without updating \\$R\\$.

### Commented

```
m => (                        // m[] = input matrix
  R =                         // initialize R to a non-numeric value
  g = (t, X, Y, i) =>         // g = recursive search function taking t = expected tile,
                              //     (X, Y) = current coordinates, i = path length
    m.map((r, y) =>           // for each row r[] at position y in m[]:
      r.map((v, x) =>         //   for each tile v at position x in r[]:
        r[                    //     this statement will eventually restore r[x] to v
          ( u = 0,            //     u = next tile to look for, or 0 if none
            t ?               //     if we're looking for a specific tile:
              v - t           //       test whether we've found it
            :                 //     else:
              (x - X) ** 2 +  //       compute the squared Euclidean distance between
              (y - Y) ** 2    //       (x, y) and (X, Y)
              < 3 ?           //       if it's less than 3 (i.e. reachable from (X, Y)):
                v - 3 ?       //         if v is not equal to 3:
                  ~v ?        //           if v is not equal to -1:
                    v         //             test if v = 0
                  :           //           else (v = -1):
                    u--       //             set u = -1 to find the other portal
                :             //         else (v = 3):
                  R = R < i ? //           we've found the strawberry: set R = min(R, i)
                      R : i   //
              :               //       else (this tile can't be reached):
                1             //         yield 1
          ) ||                //     if the above result is falsy:
          g(                  //       do a recursive call:
            u,                //         t = u
            x, y,             //         move to (x, y)
            u - ~i,           //         unless u is set to -1, increment i
            r[x] = 1          //         set this tile to a mountain
          ),                  //       end of recursive call
          x                   //     restore r[x] ...
        ] = v                 //     ... to v
    ))                        // end of both map() loops
)(2) | R                      // initial call to g with t = 2; return R

```

# Answer
> 5 votes
# Python 2, ~~441~~ ~~431~~ 341 bytes

```
from itertools import*
G=input()
W=len(G[0])
H=len(G)
A=[0]*5
E=enumerate
for y,r in E(G):
 for x,C in E(r):A[C]=[x,y]
for L in count():
 for M in product(*[zip('UDLR'*2,'LRDU    ')]*L):
  x,y=A[0]
  for m in M:
    x+='R'in m;x-='L'in m;y+='D'in m;y-='U'in m
    if(x,y)==A[3]:x,y=A[2]
    if 1-(W>x>-1<y<H)or G[y][x]>3:break
  if[x,y]==A[1]:exit(L)

```

Try it online!

Input as lists, but using numbers instead of characters (thanks to Quintec) and a seperate value for the destination of the teleporter. Those large indentations should be tab characters if Stack Exchange removes them. Any tips or ideas especially welcome, as I feel that this could get ~~**much**~~ somewhat shorter.

The table for characters used in the challenge to the numbers used for my program is below, but you can also use this program.

```
Challenge | My program
T         | 0
S         | 1
E         | 2
O         | 3
M         | 4
X         | -1

```

-10 bytes thanks to Quintec by changing the input from using characters to numbers.

-A lot of bytes thanks to Jonathan Frech, ElPedro, and Jonathan Allan.

# Answer
> 2 votes
# Python 2, 391 ~~397~~ ~~403~~ ~~422~~ bytes

```
M=input()
from networkx import*
a=b=c=d=0
N,h,w,S=[-1,0,1],len(M),len(M[0]),[]
for i in range(h):
 for j in range(w):
  I,m=(i,j),M[i][j]
  if m>7:c,d=a,b;a,b=I
  if m<0:Z=I
  if m==5:F=I
  S+=[I+I]
S+=[(a,b,c,d),(c,d,a,b)]
print len(shortest_path(from_edgelist([((A+p,B+q),(C,D))for A,B,C,D in S for p,q in[(p,q)for p in N for q in N]if-1<A+p<h and-1<B+q<w and M[C][D]*M[A+p][B+q]]),Z,F))-1

```

Try it online!

The problem is translated into a graph and the solution is to find the shortest path form the turtle to the strawberry.

```
Challenge | This code
T         | -1
S         |  5
O         |  8
M         |  0
X         |  1

```

---
Tags: code-golf, grid, path-finding
---


title: Date Multiplying Challenge

text:
# Question
Title: Date Multiplying Challenge
(Inspired by last week's Riddler on FiveThirtyEight.com. Sandbox post.)

Given a year between 2001 and 2099, calculate and return the number of days during that calendar year where `mm * dd = yy` (where `yy` is the **2-digit** year).

2018, for example, has 5:

* January 18th (1 * 18 = 18)
* February 9th (2 * 9 = 18)
* March 6th (3 * 6 = 18)
* June 3rd (6 * 3 = 18)
* September 2nd (9 * 2 = 18)

Input can be a 2 or 4-digit numeric year.

Output should be an integer. Optional trailing space or return is fine.

# Complete input/output list:

```
Input = Output
 2001 = 1     2021 = 3     2041 = 0     2061 = 0     2081 = 2
 2002 = 2     2022 = 3     2042 = 4     2062 = 0     2082 = 0
 2003 = 2     2023 = 1     2043 = 0     2063 = 3     2083 = 0
 2004 = 3     2024 = 7     2044 = 3     2064 = 2     2084 = 5
 2005 = 2     2025 = 2     2045 = 3     2065 = 1     2085 = 1
 2006 = 4     2026 = 2     2046 = 1     2066 = 3     2086 = 0
 2007 = 2     2027 = 3     2047 = 0     2067 = 0     2087 = 1
 2008 = 4     2028 = 4     2048 = 6     2068 = 1     2088 = 3
 2009 = 3     2029 = 1     2049 = 1     2069 = 1     2089 = 0
 2010 = 4     2030 = 6     2050 = 3     2070 = 3     2090 = 5
 2011 = 2     2031 = 1     2051 = 1     2071 = 0     2091 = 1
 2012 = 6     2032 = 3     2052 = 2     2072 = 6     2092 = 1
 2013 = 1     2033 = 2     2053 = 0     2073 = 0     2093 = 1
 2014 = 3     2034 = 1     2054 = 4     2074 = 0     2094 = 0
 2015 = 3     2035 = 2     2055 = 2     2075 = 2     2095 = 1
 2016 = 4     2036 = 6     2056 = 4     2076 = 1     2096 = 4
 2017 = 1     2037 = 0     2057 = 1     2077 = 2     2097 = 0
 2018 = 5     2038 = 1     2058 = 0     2078 = 2     2098 = 1
 2019 = 1     2039 = 1     2059 = 0     2079 = 0     2099 = 2
 2020 = 5     2040 = 5     2060 = 6     2080 = 4

```

This is a challenge, lowest byte count in each language wins.

Pre-calculating and simply looking up the answers is normally excluded per our loophole rules, but I'm explicitly allowing it for this challenge. It allows for some interesting alternate strategies, although its not likely a ~~98~~ 99-item lookup list is going to be shortest.

# Answer
> 14 votes
# Excel, 48 bytes

Hooray! Finally something Excel is actually good at.

```
=COUNT(VALUE(ROW(1:12)&"/"&A1/ROW(1:12)&"/"&A1))

```

Takes input from A1 in the form of an integer 1-99 representing the year, and outputs to wherever you enter this formula. It's an array formula, so use Ctrl-Shift-Enter instead of Enter to enter it.

This takes advantage of the fact that `COUNT` ignores errors, so any errors that are caused by either the month not dividing the year (leading Excel to parse something like `2/12.5/25` or by the date not being valid, like `2/29/58`, are just silently ignored.

# Answer
> 6 votes
# Python 2, 44 bytes

```
[k/32%13*(k%32)for k in range(96,509)].count

```

Try it online!

An anonymous function given as a method object. Produces all products of `(month, day)` pairs `(m, d)` as encoded by `k=32*m+d` with `0≤m≤12`, `0≤d≤31`, wrapping around. Eliminates Feb 29-31 by excluding them from the range.

# Answer
> 5 votes
# Java (JDK 10), 65 bytes

```
y->{int m=13,c=0;for(;m-->1;)if(y%m<1&y/m<29+m%2*3)c++;return c;}

```

Try it online!

# Credits

# Answer
> 4 votes
# PowerShell, 94 bytes

```
param($a)for($x=Date 1/1/$a;$x-le(Date 12/9/$a);$x=$x.AddDays(1)){$z+=$x.Month*$x.Day-eq$a};$z

```

Try it online!

Takes input as a two-digit year, then constructs a `for` loop from `1/1/year` to `12/9/year` (because 12/10 and beyond will never count and this saves a byte). Each iteration, we increment `$z` iff the `.Month` times the `.Day` is equal to our input year. Outside the loop, `$z` is left on the pipeline and output is implicit.

*Edit - this is culture dependent. The above code works for `en-us`. The date format may need to change for other cultures.*

# Answer
> 4 votes
# JavaScript (Node.js), ~~48~~ ~~44~~ 43 bytes

```
F=(x,h)=>h>12?0:F(x,-~h)+(x/h<3*h%6+28>x%h)

```

Try it online!

# JavaScript (Node.js), ~~59~~ 58 bytes

```
x=>[a=0,...'030101001010'].map((k,m)=>x%m|x/m>31-k||a++)|a

```

Try it online!

# Answer
> 4 votes
# Ruby, ~~46~~ 42 bytes

```
->y{(1..12).count{|j|y%j<1&&y/j<29+j%2*3}}

```

Try it online!

# Answer
> 3 votes
# JavaScript, ~~91~~ ~~85~~ ~~82~~ ~~81~~ 77 bytes

Takes input as a 2-digit string (or a 1 or 2 digit integer).

Takes advantage of the fact that `new Date` will rollover to the next month, and continue doing so, if you pass it a day value that exceeds the number of days in the month you pass to it so, on the first iteration, it tries to construct the date `yyyy-01-345` which becomes `yyyy-12-11`, or `yyyy-12-10` on leap years. We don't need to check dates after that as `12*11+` results in a 3-digit number.

```
y=>(g=d=>d&&([,M,D]=new Date(y,0,d).toJSON().split(/\D/),D*M==y)+g(--d))(345)

```

3 bytes saved thanks to Arnauld.

---

## Test It

```
f=
y=>(g=d=>d&&([,M,D]=new Date(y,0,d).toJSON().split(/\D/),D*M==y)+g(--d))(345)
o.innerText=[...Array(99)].map((_,x)=>(2001+x++)+` = `+f(x)).join`\n`
```

```
pre{column-count:5;width:480px;}
```

```
<pre id=o></pre>
```

# Answer
> 3 votes
# Jelly, 15 bytes

```
31x12_2¦3RĖP€Fċ

```

Try it online!

Take a number in range `[0,100[` as input.

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

I was curious to know how hardcoding would compare to an iterative computation. It's definitely longer (see @Shaggy's answer), but not *awfully* longer.

*Edit*: It is, however, much longer than a more direct formula (see @l4m2 answer).

Takes input as an integer in **\[1..99\]**.

```
n=>(k=parseInt('8ijkskercdtbnqcejh6954r1eb2kc06oa3936gh2k0d83d984h'[n>>1],36),n&1?k>>3:k&7)

```

Try it online!

### How?

Odd years have significantly less chance of having **mm * dd = yy** than even years. More concretely, odd years have **0** to **3** matches, while even years have **0** to **7** matches. This allows us to code each pair of years with just 5 bits, which can conveniently be represented as a single character in base 36.

# Answer
> 3 votes
# Bash + GNU utilities, 57

* 1 byte saved thanks to @SophiaLechner

```
seq -f1/1/$1+%gday 0 365|date -f- +%m*%d-%y|bc|grep -c ^0

```

Note that the `seq` command always produces a list of 366 dates - for non-leap years January 1st of the next year will be included. However in the date range 2001..2099, MM\*DD will never be YY for January 1st of the next year for any of these years, so this extra day won't affect the result.

Try it online!

# Answer
> 3 votes
# Python 2 and , ~~55~~ 52 bytes

```
lambda y:sum(y%i<(y/i<29+i%2*3)for i in range(1,13))

```

Try it online!

# Answer
> 3 votes
# Perl 6, 40 bytes

```
{+grep {$_%%$^m&&29+$m%2*3>$_/$m},1..12}

```

Try it online!

# Answer
> 3 votes
# T-SQL, ~~123~~ 121 bytes

Per our IO rules, input is taken via pre-existing table **t** with an integer field **y**, which contains a 2-digit year.

```
WITH c AS(SELECT 1m UNION ALL SELECT m+1FROM c WHERE m<12)
SELECT SUM(ISDATE(CONCAT(m,'/',y/m,'/',y)))FROM c,t WHERE y%m=0

```

Line break is for readability only. Inspired largely by Sophia's Excel solution.

* The top line generates a 12-item number table **c** which is joined to the input table **t**.
* If that passes I mash together a date candidate using `CONCAT()`, which does implicit `varchar` datatype conversions. Otherwise I'd have to do a bunch of `CAST` or `CONVERT` statements.
* Found the perfect evaluation function `ISDATE()`, which returns 1 for valid dates and 0 for invalid dates.
* Wrap it in a SUM and I'm done.
* **EDIT**: Moved the integer division check (`y%m=0`) into the `WHERE` clause to save 2 bytes, thanks @RazvanSocol.

Unfortunately, it's not much shorter than the lookup table version (using the string from osdavison's version):

# T-SQL lookup, 129 bytes

```
SELECT SUBSTRING('122324243426133415153317223416132126011504033106131204241006003213011306002122042005101305111014012',y,1)FROM t

```

**EDIT**: Leaving my original above, but we can save a few bytes by using a couple of new functions:

* `STRING_SPLIT` is available in MS SQL 2016 and above.
* `CONCAT_WS` is available in MS SQL 2017 and above.
* As above, replaced `IIF` with `WHERE`

# MS-SQL 2017, ~~121~~ 118 bytes

```
SELECT SUM(ISDATE(CONCAT_WS('/',value,y/value,y)))
FROM t,STRING_SPLIT('1-2-3-4-5-6-7-8-9-10-11-12','-')
WHERE y%value=0

```

# MS-SQL 2017, extra cheaty edition: 109 bytes

```
SELECT SUM(ISDATE(CONCAT_WS('/',number,y/number,y)))
FROM t,spt_values WHERE number>0AND y%number=0AND'P'=TYPE

```

Requires you to be in the `master` database, which contains a system table `spt_values` that (when filtered by `TYPE='P'`), gives you counting numbers from 0 to 2048.

# Answer
> 3 votes
# Julia 0.6, 49 44 42 bytes

```
y->sum(y/i∈1:28+3(i%2⊻i÷8)for i=1:12)

```

Try it online!

*-5 bytes inspired by Asone Tuhid's Ruby answer.*
*-2 bytes replacing count with sum*

### Explanation:

For each month `i` from 1 to 12, calculate `y/i`, and check if it's one of that month's days. Months with 31 days are 1, 3, 5, 7, 8, 10, 12 - so they're odd below 8 and even at and above 8. So either `i%2` or `i÷8` (which is 0 for i\<8 and 1 for i\>=8 here) should be 1, but not both - so we XOR them. If the xor result is true, we check dates `1:28+3` i.e. `1:31`, otherwise we check just dates `1:28`.

`1:28` is sufficient for the rest of the months (this improvement inspired by Asone Tuhid's Ruby answer) because:

* for February, the only possibility would have been `2*29 = 58`, but `2058` is not a leap year, so we can assume Feb always has 28 days.
* the other months with 30 days are month 4 and above - for which `i*29` (and `i*30`) would be above 100, which can be ignored.

Finally, we count out the number of times `y/i` belongs in this list of days (by using boolean `sum` here), and return that.

# Answer
> 2 votes
# Python 2, ~~89~~ ~~84~~ ~~68~~ 58 bytes

```
f=lambda y,d=62:d-59and((d/31+1)*(d%31+1)==y)+f(y,-~d%372)

```

Try it online!

# Answer
> 2 votes
# Excel, 83 bytes

```
{=SUM(IF(MONTH(DATE(A1,1,0)+ROW(1:366))*DAY(DATE(A1,1,0)+ROW(1:366))=A1-2000,1,0))}

```

Input is in cell `A1` in the format `yyyy`. This is an array formula and is entered with `Ctrl`+`Shift`+`Enter` to get the curly brackets `{}`. It is fairly straightforward and without any cleverness.

When in an array formula, `DATE(A1,1,0)+ROW(1:366)` gives us an array of 366 date values. On non-leap years, this will include Jan 1 of the next year but that is not a problem because `1*1=1` and would only count as a false positive if the next year is `2001` but, since the required year range is `2001 - 2099`, it will never arise as an issue.

If you shorted that bit into simply `~`, the formula because much easier to follow:

```
{=SUM(IF(MONTH(~)*DAY(~)=A1-2000,1,0))}

```

---

I tried using `COUNTIF()` instead of `SUM(IF())` but Excel wouldn't even let me enter it as an array formula, much less give me a result. I *did* find a **Google Sheets** solution using `CountIf()` but the same method otherwise that turned out to be 91 bytes, mostly because it uses `ArrayFormula()` instead of simply `{ }`.

```
=CountIf(ArrayFormula(Month(Date(A1,1,0)+Row(1:366))*Day(Date(A1,1,0)+Row(1:366))),A1-2000)

```

# Answer
> 2 votes
# Python 3, 158 ~~162~~ ~~215~~ ~~241~~ bytes

Removed 4 Thanks to Stephen for golfing the conditionals.

Removed 53 thanks Stephen for pointing out the white space

Removed 26 thanks to the link provided by caird

I'm pretty new at this. Couldn't think of how to do this without having the days in a month be described.

```
r=range
def n(Y):
 a,b,c=31,30,0
 for x in r(12):
  for y in r([a,(28if Y%4else 29),a,b,a,b,a,a,b,a,b,a][x]):
   if(x+1)*(y+1)==int(str(Y)[2:]):c+=1
 return c

```

Try it online!

# Answer
> 2 votes
# Forth (gforth), 60 59 bytes

```
: f 0 13 1 do over i /mod swap 32 i 2 = 3 * + 0 d< - loop ;

```

Try it online!

This version takes advantage of the fact that there can't be more than 1 matching day per month, and that the year has to be divisible by the month for it to match.

### Explanation

Iterates over the months, checks if year is divisible by month, and if the quotient is \< 31 (28 for Feb) Months after March can't match for days greater than 25, so we can just assume all months (other than Feb) have 31 days for the purpose of the puzzle.

### Code Explanation

```
: f                   \ start new word definition
  0                   \ set up counter
  13 1 do             \ start a counted loop from 1 to 12
    over i /mod       \ get the quotient and remainder of dividing year by month
    swap              \ default order is remainder-quotient, but we want to swap them
    32 i 2= 3 * +     \ we want to compare to 32 days unless month is Feb
    0 d<=             \ treat the 4 numbers on the stack as 2 double-length numbers
                      \ and compare [1]
    -                 \ subtract result from counter (-1 is true in Forth)
  loop                \ end loop
;                     \ end word definition

```

\[1\] - Forth has the concept of double length numbers, which are stored on the stack as two single-length numbers (of the form x y, where the value of the double = `y * 2^(l) + x`where l is the size in bits of a single in the forth implementation you're working with).

In this case, I compared the quotient and remainder to 32 (or 29) 0. If the remainder was greater than 0 (year not divisble by month), the first double would be automatically bigger than 32 (or 29) 0 and the result would be false. If the remainder is 0, then it resolves to effectively a regular check of quotient \<= 32 (or 29)

# Forth (gforth), 61 bytes

```
: f 0 13 1 do i 2 = 3 * 32 + 1 do over i j * = - loop loop ;

```

Try it online!

Saved some bytes by realizing that only February matters in terms of having the correct number of days in the month

# Explanation

Forth (at least gforth) comparisons return -1 for true and 0 for false

```
0                     \ place 0 on top of the stack to use as a counter
13 1 do               \ begin the outer loop from 1 to 12
  i 2 = 3 *           \ if i is 2 place -3 on top of the stack, otherwise 0
  32 + 1 do           \ begin the inner loop from 1 to 31 (or 28)
    over              \ copy the year from stack position 2 and place it on top of the stack
    i j * = -         \ multiply month and day compare to year, subtract result from counter
  loop                \ end the inner loop
loop                  \ end the outer loop

```

# Answer
> 2 votes
# Retina 0.8.2, 55 bytes

```
..
$*
(?<=^(1{1,12}))(?=(?(?<=^11$)\1{0,27}|\1{0,30})$)

```

Try it online! Takes a two-digit year; add 1 byte to support 4-digit years. Explanation: The first stage simply converts to unary. The second stage starts by matching 1 to 12 characters before the match position, representing the month, and then attempts to look ahead for a whole number of repetitions of that month. However, the lookahead contains a conditional, which chooses between up to 27 or 30 further repetitions depending on the month. The count of match positions is then the desired result.

# Answer
> 2 votes
# C (gcc), ~~65~~ ~~60~~ 59 bytes

```
d(a,t,e){for(t=0,e=13;e-->1;)t+=a%e<1&a/e<(e-2?32:29);a=t;}

```

Port of user202729's Java answer. Try it online here. Thanks to Jonathan Frech for golfing 1 byte.

# Answer
> 2 votes
# , ~~22~~ 122 bytes

```
x=scan();substr("122324243426133415153317223416132126011504033106131204241006003213011306002122042005101305111014012",x,x)

```

Try it online!

Decided to go with a lookup table approach. Input year needs to be 2 digits.

# Answer
> 2 votes
# , 29 bytes

```
1#.(,x*i."+29+3*2~:x=.i.13)=]

```

Try it online!

### How it works

```
1#.(,x*i."+29+3*2~:x=.i.13)=]    Input: year (2-digit, 1..99)
                   x=.i.13       array of 0..12; assign to x
                2~:              1 1 0 1 .. 1
              3*                 3 3 0 3 .. 3
           29+                   32 32 29 32 .. 32
       i."+                      for each item of above, generate a row 0 .. n
    ,x*                          each row times 0 .. 12 and flatten
                           =]    1 for each item == input, 0 otherwise
1#.                              sum

```

Tried hard to get under 2 times Jelly solution :)

### Side note

If someone really wants to hardcode the 99-digit data, here's a bit of information:

Divide the 99-digit into chunks of 2 digits. Then the first digit is `<4` and the second `<8`, which means five bits can encode two numbers. Then the entire data can be encoded in 250 bits, or 32 bytes.

# Answer
> 1 votes
# Java (JDK 10), ~~79~~ ~~72~~ 70 bytes

```
y->{int a=0,m=13;for(;m-->1;)a+=y%m<1&&y/m<(m==2?29:32)?1:0;return a;}

```

Try it online!

# Answer
> 1 votes
# Haskell, ~~61~~ 51 bytes

```
f y=sum[1|i<-[96..508],mod(div i 32)13*mod i 32==y]

```

Try it online!

Inspired by xnor's Python 2 answer and Laikoni.

# Answer
> 1 votes
# JavaScript (Node.js), 108 bytes

```
a=>'0122324243426133415153317223416132126011504033106131204241006003213011306002122042005101305111014012'[a]

```

```
f=a=>'0122324243426133415153317223416132126011504033106131204241006003213011306002122042005101305111014012'[a]
o.innerText=[...Array(99)].map((_,x)=>(2001+x++)+` = `+f(x)).join`\n`
```

```
pre{column-count:5;width:480px;}
```

```
<pre id=o></pre>
```

# Answer
> 1 votes
# Perl 5, 68 bytes

```
//;map$\+=$'%++$m==0&&$'/$m<$_,32,29,32,31,32,31,32,32,31,32,31,32}{

```

Try it online!

# Answer
> 1 votes
# Python 3, 132 bytes

This is really quite long of a program but I thought it might be of interest.

All the values are between 0-7 so I encode each number with 3 bits in a long binary string. I tried pasting a raw binary string into my python program but I couldn't get it to work, so I settled on base64 in the file.

I used the following string as a lookup table (ending 7 used for padding): `01223242434261334151533172234161321260115040331061312042410060032130113060021220420051013051110140127`

The program takes this string and decodes it as a number, then uses bit shifting to extract the result.

```
import base64
lambda n:int.from_bytes(base64.b64decode(b'pNRRxYtw01s9Jw4tFYE0QNkYsoRQgYBosEsYBFIRAUgsUkgwFQM='),'big')>>(6306-3*n)&7

```

# 66 bytes + 37 byte file = 103 bytes

This reads a binary file called `e` and avoids using base64.

```
lambda n:int.from_bytes(open('e','rb').read(),'big')>>(6306-3*n)&7

```

Here is a hexdump of the read file (without padding):

```
00000000  a4 d4 51 c5 8b 70 d3 5b  3d 27 0e 2d 15 81 34 40  |..Q..p.[='.-..4@|
00000010  d9 18 b2 84 50 81 80 68  b0 4b 18 04 52 11 01 48  |....P..h.K..R..H|
00000020  2c 52 48 30 0a                                    |,RH0.|

```

# Answer
> 1 votes
# Oracle SQL, 115 bytes

```
select count(decode(sign(decode(l,2,29,32)-y/l),1,1))from t,
xmltable('1to 12'columns l int path'.')where mod(y,l)=0

```

We may note that it does not really matter how many days in April (and later months), since 100/4 \< 28. Also it's not necessary to check whether year is leap or not. We just have to specify that there are 28 days in February (not 29 because that validation will be executed only for 2058 which is not leap) otherwise it may be just 31 for any month.

**Other approaches**

# Oracle SQL (12c Release 2 and later), 151 bytes

```
select count(to_date(y/l||'-'||l||'-1' default '' on conversion error,'dd-mm-y'))from t,
(select level l from dual connect by level<=12)where mod(y,l)=0

```

# Oracle SQL (12c Release 2 and later), 137 bytes

```
select sum(validate_conversion(y/l||'-'||l||'-1'as date,'dd-mm-y'))from t,
(select level l from dual connect by level<=12)where mod(y,l)=0

```

*Both solution could have been 8 bytes shorter if we replace `(select level l from dual connect by level<=12)` with `xmltable('1to 12'columns l int path'.')` but Oracle throws an exception because of the bug (tested on versions 12.2.0.1.0, 18.3.0.0.0).*

```
SQL> select count(to_date(y/l||'-'||l||'-1' default '' on conversion error,'dd-mm-y'))from t,
  2  xmltable('1to 12'columns l int path'.')where mod(y,l)=0
  3  /
select count(to_date(y/l||'-'||l||'-1' default '' on conversion error,'dd-mm-y'))from t,
*
ERROR at line 1:
ORA-00932: inconsistent datatypes: expected DATE got DATE

SQL> select sum(validate_conversion(y/l||'-'||l||'-1'as date,'dd-mm-y'))from t,
  2  xmltable('1to 12'columns l int path'.')where mod(y,l)=0
  3  /
select sum(validate_conversion(y/l||'-'||l||'-1'as date,'dd-mm-y'))from t,
*
ERROR at line 1:
ORA-43909: invalid input data type

```

The only case in both solution when year does matter is 2058 which is non-leap so literal '-1' was used to specify non-leap year.

# Oracle SQL, 128 bytes

```
select count(d)from t,(select date'1-1-1'+level-1 d from dual connect by level<365)
where to_char(d(+),'mm')*to_char(d(+),'dd')=y

```

# Oracle SQL, 126 bytes

```
select substr('122324243426133415153317223416132126011504033106131204241006003213011306002122042005101305111014012',y,1)from t

```

**Update**

# Oracle SQL, 110 bytes

```
select-sum(least(sign(y/l-decode(l,2,29,32)),0))from t,
xmltable('1to 12'columns l int path'.')where mod(y,l)=0

```

# Oracle SQL, 108 bytes

```
select sum(decode(sign(decode(l,2,29,32)-y/l)*mod(y+1,l),1,1))from t,
xmltable('1to 12'columns l int path'.')

```

# Spark SQL, 137 bytes

```
select count(cast(regexp_replace(concat_ws('-','2001',l,y/l),'.0$','')as date))
from(select explode(array(1,2,3,4,5,6,7,8,9,10,11,12))l),t

```

# Spark 2.3+ SQL, 126 bytes

(`replace` function becomes available)

```
select count(cast(replace(concat_ws('-','2001',l,y/l),'.0')as date))
from(select explode(array(1,2,3,4,5,6,7,8,9,10,11,12))l),t

```

# Answer
> 1 votes
# PHP, 73 bytes

Using pipe input and `php -nR`:

```
for(;++$m<13;$d=1)while($d<25+($m-2?$m>4?:7:4))$c+=$argn==$m*$d++;echo$c;

```

Try it online!

# PHP, 76 bytes

Using command line arg input `php dm.php 18`:

```
for(;++$m<13;$d=1)while($d<25+($m-2?$m>4?:7:4))$c+=$argv[1]==$m*$d++;echo$c;

```

Try it online!

Iterative approach. Since the only leap year to look at is 2 * 29 = 58, and 2058 is not a leap year there's no need to consider leap year in the Feb days. And since wraparound is not a concern -- from April on, any day greater than 25 will exceed 100 we just say the rest of the months only have 25 days.

Input is 2 digit year via command line (-10 bytes as program, thx to suggestion from @Titus).

*OR:*

# PHP, 101 bytes

```
$y=$argv[1];for($d=strtotime("$y-1");date(Y,$d)==$y;$d+=86400)eval(date("$\x+=j*n=='y';",$d));echo$x;

```

Try it online!

Still iterative but using PHP's timestamp functions. Accepts year as four digit number. Thx to @Titus for suggestion of using `strtotime()` instead of `mktime()`.

# Answer
> 0 votes
# Japt `-x`, 18 bytes

Takes input as an integer in the range `1-99`.

```
346Ç=ÐUTZ)f *ÒZÎ¥U

```

Try it

As with my JS solution, takes advantage of the fact that JavaScript's `Date` will rollover to the next month, and continue doing so, if you pass it a day value that exceeds the number of days in the month you pass to it so, on the first iteration, `ÐUTZ` tries to construct the date `yyyy-01-345` which becomes `yyyy-12-11`, or `yyyy-12-10` on leap years. We don't need to check dates after day 345 that as `12*11+` results in a 3-digit number.

```
346Ç=ÐUTZ)f *ÒZÎ¥U     :Implicit input of integer U
346Ç                   :Map each Z in the range [0,346)
    =                  :  Reassign to Z
     ÐUTZ              :    new Date(U,0,Z) - months are 0-indexed in JS
         )             :  End reassignment
          f            :  Get the day of the month
            *Ò         :  Multiply by the negation of bitwise NOT of
              ZÎ       :  Get 0-based month of Z
                ¥U     :  Test for equality with U
                       :Implicitly reduce by adition and output

```

# Answer
> 0 votes
# PHP, ~~74~~ 70 bytes

```
while(++$m<13)for($d=$m<5?$m-2?31:28:25;$d;)$n+=$d--*$m==$argn;echo$n;

```

accepts two-digit years only.

I adopted gwaugh´s considerations and golfed them; my 1st approach was longer than his (92 bytes):

```
for($y=$argn%100;++$m<13;)for($d=$m-2?30+($m+$m/8)%2:29-($y%4>0);$d;)$n+=$d--*$m==$y;echo$n;

```

`%100` allows to use 4-digit years.

---

Run as pipe with `-nR` or try them online.

---
Tags: code-golf, date
---


title: Score a single dart

text:
# Question
Title: Score a single dart
# Introduction

Write a program or function that, given the coordinates of where a dart lands on a dartboard, return the score of that dart. Dart coordinates are given as two integers, `x,y` measured from the center of the dartboard, with millimeter precision.

## How to score a dart

Darts is a game played by throwing a dart at a circular board. The dart board is divided into 20 equally sized "wedges". Starting from the top and going clockwise, the sections have values of 20,1,18,4,13,6,10,15,2,17,3,19,7,16,8,11,14,9,12,5. If your dart lands in the black or white parts of any of the wedges, you score the value indicated on the outside of that wedge.
.

However, if your dart lands in the outer green/red ring of the dartboard, you score double the points indicated on the outside of the wedge that you hit. Likewise, hitting the inner green/red ring (the one in between the two white/black sections), you score triple the number indicated on the outside of the wedge. If your dart hits the innermost circle (the red bulls-eye) you instead score 50 points and finally, if your dart hits the second-innermost circle (the green ring around the bulls-eye), you score 25 points.

The dimensions of the rings, measured from the center of the dartboard, are as follows:

```
Bullseye (50): [0mm-6mm)
25:            [6mm-16mm)
Inner Single:  [16mm-99mm)
Triple:        [99mm-107mm)
Outer Single:  [107mm-162mm)
Double:        [162mm-170mm)
Miss (0):       170mm+

```

Note 1: Pictures provided are for illustration purposes only, and are not to scale.
Note 2: Measurements given are approximate, and may not be accurate to a real dartboard.
Note 3: All measurements given are `[inclusive-exclusive)`. For the purposes of this challenge, we're not going to worry about darts hitting the wire and bouncing off. If the dart lands "on the wire" with one of the radial lines, then it is up to the answerer to decide whether to break the tie clockwise or counter-clockwise. Tie breaking direction must be consistent, and indicated.
Note 4: Dartboard is hung in the standard way with the middle of the 20 section being directly above the bullseye, and the 3 section directly below the bullseye.

# Input

Two integers representing the `x,y` coordinates of where the dart landed, measured in millimeters, relative to the center of the dartboard.

# Output

A single integer, for the number of points that would be awarded to a dart that landed at the given coordinates.

# Sample

```
0,0     -> 50
2,101   -> 60
-163,-1 -> 22
6,18    ->  1
-6,18   ->  5
45,-169 ->  0
22, 22  ->  4 (if tie-broken clock-wise)
            18(if tie-broken counter-clockwise)
-150,0  ->  11
-150,-1 ->  11

```

## Scoring

. Fewest bytes in your source code wins.

Standard loopholes forbidden.

# Answer
> 19 votes
# JavaScript (ES7), 137 bytes

Takes the coordinates in currying syntax `(x)(y)`. Uses counterclockwise tie-break.

```
x=>y=>(r=(x*x+y*y)**.5)<6?50:r<16?25:(r<99?1:r<107?3:r<162||r<170&&2)*parseInt('b8g7j3h2fa6d4i1k5c9eb'[Math.atan2(y,x)*3.1831+10.5|0],36)

```

Try it online!

### How?

We translate the input Cartesian coordinates \\$(x,y)\\$ into polar coordinates \\$(r,\theta)\\$ with:

$$r=\sqrt{x^2+y^2}$$ $$\theta=\arctan\_2(y,x)$$

We use \\$r\\$ to determine whether the dart is located over the *Bullseye*, *25*, *Inner Single*, *Triple*, *Outer Single*, *Double* or if the shot is a *Miss*.

If we're located over a *Single*, *Double* or *Triple*, we use \\$\theta\\$ to determine in which sector \\$s\\$ we are with:

$$s=\left\lfloor\frac{\theta+\pi}{2\pi}\times20+\frac{1}{2}\right\rfloor=\left\lfloor\theta\times\frac{10}{\pi}+10+\frac{1}{2}\right\rfloor$$

For a \\$340\times340\\$ area, we need 4 decimal places of \\$10/\pi\\$ to get enough precision, which gives:

$$\frac{10}{\pi}\approx3.1831$$

The base scores are stored counterclockwise in a base-36 encoded string of 21 entries, starting and ending at \\$11\\$:

$$11,8,16,7,19,3,17,2,15,10,6,13,4,18,1,20,5,12,9,14,11$$

We need to repeat \\$11\\$ because half of this sector belongs to the first slice (where \\$\theta\\$ is close to \\$-\pi\\$), while the other half belongs to the last slice (where \\$\theta\\$ is close to \\$+\pi\\$).

### Graphical output

The following ES6 code snippet draws the dartboard using the same logic as in the golfed code.

```
for(ctx = c.getContext('2d'), y = -180; y < 180; y++) {
  for(x = -180; x < 180; x++) {
    r = Math.pow(x * x + y * y, 0.5);
    s = Math.atan2(y, x) * 3.1831 + 10.5 | 0;

    ctx.fillStyle = [ '#000', '#fff', '#be3628', '#487f45', '#bbb', '#ddd' ][
      r < 6 ? 2 : r < 16 ? 3 :
      (r < 99 ? 1 : r < 107 ? 3 : r < 162 ? 1 : r < 170 ? 3 : 4) ^ (s & 1)
    ];
    ctx.fillRect(x + 180, y + 180, 1, 1);
  }
}
```

```
<canvas id=c width=360 height=360 style="width:360px;height:360px" />
```

# Answer
> 8 votes
## JavaScript (ES6) + SVG(HTML5), ~~53 + 523~~ 51 + ~~519~~ 507 = ~~576~~ ~~570~~ 558 bytes

```
document.write`<svg width=345 height=345>`;i=b=Math.PI/10;s=Math.sin(a=-b/2);c=Math.cos(a);f=(r,f,n)=>document.write(`<path d=M172,172L${[172+r*s,172+r*c]}A${[r,r,0,0,1,172+r*t,172+r*d]}z fill=#${f} n=${n} />`);g=(q,r,m,n,i)=>f(q,i?474:`b32`,n*m)+f(r,i?`fff`:`000`,n);[3,17,2,15,10,6,13,4,18,1,20,5,12,9,14,11,8,16,7,19].map(n=>{t=s;d=c;s=Math.sin(a+=b);c=Math.cos(a);g(170,162,2,n,i=!i);g(107,99,3,n,i);});document.write`<circle cx=172 cy=172 r=16 fill=#474 n=25 /><circle cx=172 cy=172 r=6 fill=#b32 n=50`
```

```
<body onclick=alert(+event.target.getAttribute`n`)>
```

Input is via mouse click, output via `alert`. Edit: Saved 12 bytes by using slightly more approximate colours as suggested by @Arnauld.

# Answer
> 7 votes
# Intel 8086/8087 assembly, ~~180~~ ~~144~~ ~~142~~ 138 bytes

This uses the 8087 math co-processor for all of the trig and floating-point arithmetic. All calculations are done in hardware with 80-bit floating-point precision.

```
df06 b101 d8c8 df06 af01 d8c8 dec1 d9fa df1e b301 8b16 b301
33c0 81fa aa00 7c03 eb53 9083 fa06 7d05 b032 eb49 9083 fa10
7d05 b019 eb3f 90df 06b7 01df 06b5 01d9 f3df 06b1 01dd d2d9
ebde f9de c9de c1df 1eb3 01a1 b301 bb9c 01d7 83fa 6b7d 0a83
fa63 7c05 b303 eb09 9081 faa2 007c 04b3 02f6 e30b 0810 0713
0311 020f 0a06 0d04 1201 1405 0c09 0e0b 0a00

```

Written as a MASM MACRO (basically a function), takes X and Y as coordinates and returns the calculated score in AX. The tie is broken clockwise.

```
MAX_BULL EQU 6
MAX_25   EQU 16
MIN_3X   EQU 99
MAX_3X   EQU 107
MIN_2X   EQU 162
MAX_2X   EQU 170

; cartesian coordinates to radius
; ST = sqrt( X^2 + Y^2 )
; input: X,Y (mem16,mem16)
; output: Radius (mem16)
FCRAD   MACRO X, Y, R
    FILD  Y         ; ST[] = Y
    FMUL  ST,ST     ; ST = y^2
    FILD  X         ; ST[] = X
    FMUL  ST,ST     ; ST = x^2
    FADD            ; ST = ST + ST1
    FSQRT           ; ST = SQRT(ST)
    FISTP R         ; R = ROUND(ST)
        ENDM

; cartesian coordinates to sector #
; input: X,Y (mem16,mem16)
; output: Sector (mem16)
FCSEC   MACRO X, Y, S
    FILD  Y         ; ST[] = Y
    FILD  X         ; ST[] = X
    FPATAN          ; ST = atan2(Y,X)
    FILD  CTEN      ; ST[] = 10
    FST   ST(2)     ; ST(2) = 10
    FLDPI           ; ST[] = pi
    FDIV            ; ST = 10 / pi
    FMUL            ; ST = A * ST
    FADD            ; ST = ST + 10
    FISTP S         ; S = ROUND(ST)
        ENDM

; score the dart throw
; input: X / Y coordinates (mem16)
; output: Score (AX)
SCORE   MACRO X, Y
        LOCAL IS_BULL, IS_25, IS_3X, IS_2X, MUL_SCORE, DONE
    FCRAD X, Y, FDW         ; FDW = radius(X,Y)
    MOV  DX, FDW            ; DX = FDW = radius
    XOR  AX, AX             ; score is initially 0
    CMP  DX, MAX_2X         ; >= 170 (miss)
    JL   IS_BULL            ; if not, check for bullseye
    JMP  DONE
IS_BULL:
    CMP  DX, MAX_BULL       ; < 6 (inner bullseye)
    JGE  IS_25              ; if not, check for 25
    MOV  AL, 50             ; score is 50
    JMP  DONE
IS_25:
    CMP  DX, MAX_25         ; < 16 (outer bullseye)
    JGE  IS_3X              ; if not, check for triple
    MOV  AL, 25             ; score is 25
    JMP  DONE
IS_3X:
    FCSEC X, Y, FDW         ; FDW = sector(X,Y)
    MOV  AX, FDW            ; load sector # into AX
    MOV  BX, OFFSET SCR     ; load base score table
    XLAT                    ; put base score into AL
    CMP  DX, MAX_3X         ; < 107 (triple upper bounds)
    JGE  IS_2X              ; if not, check for double
    CMP  DX, MIN_3X         ; >= 99 (triple lower bounds)
    JL   IS_2X              ; if not, check for double
    MOV  BL, 3              ; this is triple score
    JMP  MUL_SCORE          ; go forth and multiply
IS_2X:
    CMP  DX, MIN_2X         ; >= 162 (double lower bounds) (> 170 already checked)
    JL   DONE               ; if not, single score
    MOV  BL, 2              ; this is double score
MUL_SCORE:
    MUL  BL                 ; multiply score either 2x or 3x
DONE:
    ENDM

; DATA (place in appropriate segment)
SCR     DB  11,8,16,7,19,3,17,2,15,10,6  ; score table
        DB  13,4,18,1,20,5,12,9,14,11
CTEN    DW  10      ; constant 10 to load into FPU
FDW     DW  ?       ; temp DW variable for CPU/FPU data transfer

```

An example test program for PC DOS. Download it here DARTTEST.COM.

```
INCLUDE DART.ASM            ; the above file
INCLUDE INDEC.ASM           ; generic I/O routines - input int
INCLUDE OUTDEC.ASM          ; generic I/O routines - output int

    FINIT                   ; reset 8087

    MOV  AH, 2              ; display "X" prompt
    MOV  DL, 'X'
    INT  21H
    CALL INDEC              ; read decimal for X into AX
    MOV  X, AX

    MOV  AH, 2              ; display "Y" prompt
    MOV  DL, 'Y'
    INT  21H
    CALL INDEC              ; read decimal for Y into AX
    MOV  Y, AX

    SCORE X, Y              ; AX = SCORE( X, Y )

    CALL OUTDEC             ; display score

X   DW  ?
Y   DW  ?

```

## Output

Example usage of above test program. Actual IBM PC with 8087, DOSBox or your favorite emulator required.

```
A>DARTTEST.COM
X: 0
Y: 0
50
A>DARTTEST.COM
X: 2
Y: 101
60
A>DARTTEST.COM
X: -163
Y: -1
22
A>DARTTEST.COM
X: 6
Y: 18
1
A>DARTTEST.COM
X: -6
Y: 18
5
A>DARTTEST.COM
X: 45
Y: -169
0
A>DARTTEST.COM
X: 22
Y: 22
4
A>DARTTEST.COM
X: -150
Y: 0
11
A>DARTTEST.COM
X: -150
Y: 0
11
A>DARTTEST.COM
X: -150
Y: -1
11
A>DARTTEST.COM
X: -7
Y: -6
25
A>DARTTEST.COM
X: -90
Y: 138
24

```

\*Edits:

* -36 bytes by removing truncate-rounding statement and 10.5 constant. Tie now broken clockwise.
* -2 bytes by removing no longer necessary FRNDINT
* -4 bytes, FMUL use same source/destination

# Answer
> 6 votes
# Jelly, 56 bytes

```
æA/Æ°_9:18ị“!@umÞẓẓS’Œ?¤
ḅıA<“©Ñckɱȥ‘TṂị“2ı¢¤¢£¡‘¹×>3$?Ç

```

A monadic link accepting the pair as a list `[x,y]` which yields the score.
Uses clockwise tie-breaking.

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

N.B. a dyadic version is also 56 bytes

### How?

```
æA/Æ°_9:18ị“!@umÞẓẓS’Œ?¤ - Link 1, segment score: pair [x, y]
  /                      - reduce by:
æA                       -   arc tangent
   Æ°                    - convert from radians to degrees
     _9                  - subtract 9 (align 0 with boundary between 1 & 20)
       :18               - integer divide by 18 (yields a segment index from 0 to 19)
                       ¤ - nilad followed by link(s) as a nilad:
           “!@umÞẓẓS’    -   base 250 number = 2091180117530057584
                     Œ?  -   shortest permutation of natural numbers [1..N] which
                         -   would reside at that index in a list of all permutations of
                         -   those same numbers ordered lexicographically.
                         -   = [18,4,13,6,10,15,2,17,3,19,7,16,8,11,14,9,12,5,20,1]
          ị              - index into (yields the score associated with the segment)

ḅıA<“©Ñckɱȥ‘TṂị“2ı¢¤¢£¡‘¹×>3$?Ç - Main Link: segment score: pair [x, y]
 ı                              - √(-1)
ḅ                               - convert from base = x+iy
  A                             - absolute value = √(x²+y²)
    “©Ñckɱȥ‘                    - code-page index list = [6,16,99,107,162,170]
                                - (i.e. the radial boundaries)
            T                   - list of truthy indexes
             Ṃ                  - minimal value (0 if empty)
               “2ı¢¤¢£¡‘        - code-page index list = [50,25,1,3,1,2,0]
              ị                 - index into
                                - (i.e. get an override score (>3) OR a multiplier (<=3))
                              Ç - call last Link (1) as a monad (get the segment score)
                             ?  - if...
                            $   - ...condition: last two links as a monad:
                          >     -      (override OR multiplier) greater than?
                           3    -      three
                        ¹       - ...then: identity (keep override as is)
                         ×      - ...else: multiply (by multiplier)

```

# Answer
> 4 votes
# TI-Basic (TI-84 Plus CE), ~~147~~ 146 bytes

```
Prompt X,Y
abs(X+iY→R
int(<sub>E</sub>-12+11.5+10π<sup>-1</sup>R▸Pθ(X,Y→θ
{11,8,16,7,19,3,17,2,15,10,6,13,4,18,1,20,5,12,9,14,11
25((R<6)+(R<16))+Ans(θ)(R≥16 and R<170)(1+(R≥162)+2(R≥99 and R<107

```

Prompts for X and Y on separate lines.

Tie-breaks counter-clockwise.

TI-Basic is a tokenized language; all tokens used here are one byte.

Explanation:

```
Prompt X,Y
# 5 bytes, Prompt for X and Y
abs(X+iY→R
# 8 bytes, store distance from origin in R
int(<sub>E</sub>-12+11.5+10π<sup>-1</sup>R▸Pθ(X,Y→θ
# 22 bytes, store index in list of point values by polar angle in θ
{11,8,16,7,19,3,17,2,15,10,6,13,4,18,1,20,5,12,9,14,11
# 55 bytes, list of point values
25((R<6)+(R<16))+Ans(θ)(R≥16 and R<170)(1+(R≥162)+2(R≥99 and R<107
# ~~57~~ 56 bytes, calculate the score

```

Utilizes the fact that TI-Basic boolean comparisons return 0 or 1 by adding them up and multiplying by point values.

# Answer
> 3 votes
# T-SQL, ~~392 374~~ 366 bytes

```
UPDATE t SET x=1WHERE x=0
SELECT TOP 1IIF(r<16,f,b*f)
FROM(SELECT r=SQRT(x*x+y*y),w=FLOOR(10*ATN2(y,x)/PI()+.5)FROM t)p,
(VALUES(10,11),(9,14),(8,9),(7,12),(6,5),(5,20),(4,1),(3,18),(2,4),(1,13),(0,6),
   (-1,10),(-2,15),(-3,2),(-4,17),(-5,3),(-6,19),(-7,7),(-8,16),(-9,8),(-10,11))s(a,b),
(VALUES(6,50),(16,25),(99,1),(107,3),(162,1),(170,2),(999,0))d(e,f)
WHERE a=w AND r<e

```

Line breaks are for readability. The initial `UPDATE` takes care of the `x=y=0` problem that would otherwise throw an error with `ATN2()`, but doesn't change the score.

Input is taken via pre-existing table *t*, per our IO guidelines. Due to using `TOP 1`, this table should contain only a single row.

Basically I'm joining 3 tables:

* **Table p**: The *x* and *y* from input table **t** are converted to polar *r* and a "wedge" value *w* representing a number from -11 to positive 11, for the scoring wedge the dart fell into. "Tie breaker" is counter-clockwise. (I tried `ROUND()`, which was slightly shorter, but it gave an inconsistent tie breaker.)
* **Table s**: This is a lookup table to convert a "wedge" value *a* into a score *b*.
* **Table d**: This is a lookup table the returns the score calculation based on the distance from the center. *e* is the distance and joins to *r*, and returns only a single row based on the `TOP 1`. The value *f* is either a fixed score (for a bulls-eye) or a multiplier for the wedge score.

**EDIT**: Dropped the `ORDER BY`, it seems to work properly without it, at least on SQL 2017. I also dropped the `AND y=0` on the update condition; I tested for all integer `y` values, changing `x=0` to `x=1` never changes the score.

**EDIT 2**: Removed column *g* from table **d**, replaced it with an `IIF()` statement that either returns `f` directly (for a bulls-eye), or `f*b`, saved 8 bytes. Also removed the space after `TOP 1`.

# Answer
> 2 votes
# Haskell, 198 bytes

```
p=pure
a#b=(!!(sum[1|k<-a,k<=b]))
a!b=([6,16,99,107,162,170]#(sqrt$a*a+b*b))[p 50,p 25,id,(*3),id,(*2),p 0]$([pi/20,3*pi/20..6]#(pi+atan2 b a))[11,8,16,7,19,3,17,2,15,10,6,13,4,18,1,20,5,12,9,14,11]

```

Tie breaks counter-clockwise. `(#)` is a lookup function. The polar angle is used to index from the list of numbers, starting at the `atan2` cutoff point at 11. The distance is used to index from the list of functions `[const 50, const 25, id, (*3), id, (*2), const 0]` and at last this function is applied to the number we previously got.

Try it online!

# Answer
> 1 votes
# Perl 5 `-MMath::Trig':pi' -MMath::Trig':radial' -apl`, 166 bytes

```
($d,$a)=cartesian_to_cylindrical@F;$_=(1+($d>161||$d<6)+($d<107&&$d>98)*2)*($d<170)*($d<16?25:("6 134 181 205 129 14118 167 193 172 1510"=~/../g)[($a/pi*10+41/2)%20])

```

Try it online!

Takes the two coordinates space separated on STDIN. Tie-breaking is anticlockwise.

---
Tags: code-golf, game
---


title: Borderless table

text:
# Question
Title: Borderless table
In this challenge you are going to place letters from the alphabet in a Cartesian plane and output the result as a text.

Your input will consist in a list of list with 3 parameters:

* X coordinate
* Y coordinate
* String

**How?**

We know that a Cartesian plane contain 2 axes \\$(X, Y)\\$ and 4 quadrants where the signs of the \\$(X,Y)\\$ coordinates are \\$(+,+)\\$, \\$(−,+)\\$, \\$(−,−)\\$, and \\$(+,−)\\$. For example

Consider the following 3 by 3 matrix as a Cartesian plane

\begin{matrix} (-1,1) & (0,1) & (1,1) \\ (-1,0) & (0,0) & (1,0) \\ (-1,-1) & (0,-1) & (1,-1) \end{matrix}

If we are given in the input something like `[[-1,1,L],[0,1,F]]` our matrix will look something similar to

\begin{matrix} L & F & (1,1) \\ (-1,0) & (0,0) & (1,0) \\ (-1,-1) & (0,-1) & (1,-1) \end{matrix}

And the final output `LF`

In addition to that there are some points we need to follow in order to get the correct output:

* When a X,Y coord is repeated, you will need to concatenate the strings. Example: assume in (-1,1) the string `F` is placed and you need to place the string `a` in the same point. You concatenate both strings resulting in `Fa` and that is the value that will go in (-1,1).
* Your output need to be consistent to the matrix. Example imagine this as your final result:

\begin{matrix} Ma & r & ie \\ i & s & (1,0) \\ cute & (0,-1) & (1,-1) \end{matrix}

You must output

```
Ma  rie
i   s
cute

```

**Why?**

You can view this as a table where the columns are the values of the x-axis and the rows the y-axis.

```
        Column 1    |   Column 2    |   Column 3
        ----------------------------------------
Row 1   |  "Ma"     |      "r"      |     "ie"
Row 2   |  "i"      |      "s"      |
Row 3   |  "cute"   |               |

```

All columns values must have the same length

```
        Column 1    |   Column 2    |   Column 3
        ----------------------------------------
Row 1   |  "Ma  "   |      "r"      |     "ie"
Row 2   |  "i   "   |      "s"      |
Row 3   |  "cute"   |               |

```

Finnaly we output the result

```
Ma  rie
i   s
cute

```

---

**Test Cases**

```
Input
------------
[[3, 3, "c"]
[4, 1, "un"]
[5, 3, "e"]
[4, 3, "od"]
[4, 2, "lf"]
[1, 2, "go"]
[2, 1, "i"]
[2, 1, "s f"]]

Output
--------------
      code
go     lf
  is f un

```

---

```
Input
--------------
[[0, 0, 's'],
[-1,1, 'M'],
[0, 1, 'r'],
[-1,1, 'a'],
[1, 1, 'i'],
[-1, 0, 'i'],
[1, 1, 'e'],
[-1,- 1, 'c'],
[-1,- 1, 'u'],
[-1, -1, 'te']]

Output.
----------------
Ma  rie
i   s
cute

```

---

**Notes**

* This is supposed to be
* You can wrap the coordinates in a single list e.g `[[3, 3], "c"]`
* You can take the input in any reasonable format
* You can assume there wont be any number or empty spaces only in the input. e.g. There can be something like `a a` but never `1` or `" "` or `1a` or `1 1`

# Answer
> 9 votes
# JavaScript (ES8),  ~~186 180~~  179 bytes

*Saved 1 byte thanks to @Shaggy*

```
a=>(g=d=>a.some(([x,y,s])=>(w[x+=d]>(l=((r=o[y=d-y]=o[y]||[])[x]=[r[x]]+s).length)||(w[x]=l),x|y)<0,w=[o=[]])?g(-~d):o.map(r=>w.map((w,x)=>(r[x]||'').padEnd(w)).join``).join`
`)``

```

Try it online!

### Negative indices in JS (or the lack of them)

Given an array `A[]`, it's perfectly legal in JS to do something like `A[-1] = 5`. However, this will **not** save the value in the array itself. Instead, it will implicitly coerce this negative index to a string (`"-1"`) and set the corresponding *property* in the **surrounding object** of the array.

The bad news is that properties are not iterable with methods such as `map()`:

```
a = [];
a[1] = 3;
a[-1] = 5;
a.map((v, i) => console.log(v + ' is stored at index ' + i))

```

Try it online!

The above code will only display `3 is stored at index 1`.

A possible workaround would be:

```
a = [];
a[1] = 3;
a[-1] = 5;
Object.keys(a).map(k => console.log(a[k] + ' is stored with key ' + k))

```

Try it online!

But:

* This is not very golf-friendly.
* The keys are not sorted in numerical order.

### What we do here

We definitely want to work with positive values of both \\$x\\$ and \\$y\\$ in order to avoid the problems described above.

We could do a first pass on the data, looking for the minimum value of \\$x\\$ and the minimum value of \\$y\\$. But that would be quite lengthy.

Here's what we do instead:

* we start with \\$d=0\\$
* we process an iteration where \\$x\\$ is replaced with \\$x+d\\$ and \\$y\\$ is replaced with \\$d-y\\$
* if we have either \\$x\<0\\$ or \\$y\<0\\$ for any entry, we abort and recursively start another attempt with \\$d+1\\$

# Answer
> 6 votes
# APL (Dyalog Unicode), 39 bytesSBCS

Anonymous infix lambda taking\* lists of coordinates and strings as left and right arguments.

```
{⊃,/↑¨↓⌽m⊣m[c],←⍵⊣m←(⊃⌈/c←1+⍺-⌊/⍺)⍴⊂''}

```

Try it online!

`{``}` "dfn"; left (coordinates) and right (strings) arguments are  and :

`⊂''` enclosed empty string, so use as fill for an array

`(``)⍴` cyclically **r**eshape into an array of the following dimensions:

`⌊/⍺` the lowest value along each axis of the coordinates

`⍺-` subtract that from all the coordinates

`1+` add that to one (since we want the inclusive range)

`c←` store in `c` (for **c**oordinates)

`⌈/` the highest value along each axis of those

unpack to use as dimensions

`m←` store in `m` (for **m**atrix)

`⍵⊣` discard that in favour of the strings

`m[c],←` append those to `m` at the coordinates `c`

`m⊣` discard those in favour of the amended `m`

mirror

split into list of lists of strings

`↑¨` mix each list of strings into a character matrix, padding with spaces

`,/` reduce by horizontal concatenation

unpack (since reduction reduces rank from 1 to 0)

---

* If taking a single argument of interwoven coordinates and strings is required, it will be 5 bytes longer.

# Answer
> 5 votes
# Python 2, ~~188~~ ~~185~~ 181 bytes

```
s=sorted;d={};k={}
for x,y,c in input():d[x]=d.get(x,{});k[~y]=d[x][y]=d[x].get(y,'')+c
for y in s(k):print''.join('%*s'%(-max(map(len,d[x].values())),d[x].get(~y,''))for x in s(d))

```

Try it online!

# Answer
> 4 votes
# 05AB1E, ~~45~~ 44 bytes

```
WsàŸãεUõIvyнXQiyθ«]IZsß->ôεíDéθgjí}øRJʒðKĀ}»

```

Takes the input-coordinates as an inner list.

Try it online or verify all test cases.

**Explanation:**

```
Wsà           # Get the minimum and maximum of the (implicit) input-list
   Ÿ          # Create a list in the range [min, max]
    ã         # Create each possible pair by taking the cartesian product with itself
ε             # Map each coordinate to:
 U            #  Pop and store the coordinate in variable `X`
 õ            #  Push an empty string ""
  Iv          #  Loop `y` over the input-items:
    yн        #   Get the coordinates of item `y`
      XQi     #   If it's equal to variable `X`:
         yθ   #    Get the string of item `y`
           «  #    Concat it to the (non-)empty string
]             # Close the if-statement, loop, and map
 IZsß         # Get the maximum and minimum of the input-list
     -        # Subtract them from each other
      >       # And increase it by 1
       ô      # Split the list into parts of this size
ε             # Map each part to:
 í            #  Reverse each inner string
  Déθg        #  Get the length of the longest inner string
      j       #  Prepend spaces to each item up to that length
       í      #  And reverse every item back again
              #  (so the spaces are trailing instead of leading)
}ø            # After the map: zip/transpose; swapping rows/columns
  R           # Reverse the entire list
   J          # Join each inner list together to a single string
ʒðKĀ}         # Remove all strings consisting only of spaces
     »        # Join the strings by newlines (and output implicitly)

```

# Answer
> 3 votes
# Perl 5 `-p00` `-MList::Util=max`, 148 bytes

```
s/(\S+) (\S+) (.*)
/$a{$1}=max$a{$1},length($h{$2}{$1}.=$3);''/ge;for$y(sort{$b-$a}keys%h){map{printf"%-$a{$_}s",$h{$y}{$_}}sort{$a-$b}keys%a;say""}

```

TIO

How

* `s/(\S+) (\S+) (.*)
/` ... `;''/ge;`, substitution flags `/g` loop `/e` eval, replacement evaluates to empty clearing line input/default variable
* `$a{$1}=max$a{$1},length($h{$2}{$1}.=$3)`, autovivifies a map %h of map whose first level keys `y` second level `x` and concatenate string `$3` to the value, get the length and autovivifies a second map %a whose keys `x` and value the max of length over the column (`x`)
* `for$y(sort{$b-$a}keys%h){` ... `;say""}`, for row indices `$y` in keys of `%h` sorted numerically reverse, `say""` at the end to print a newline
* `map{` ... `}sort{$a-$b}keys%a`, for column index `$_` in keys %a sorted numerically
* `printf"%-$a{$_}s",$h{$y}{$_}`, print string aligned to the left with column width

# Answer
> 3 votes
# Charcoal, 60 bytes

```
≔Ｅθ§ι¹η≔Ｅθ§ι⁰ζＦ…·⌊ζ⌈ζ«≔Ｅ…·⌊η⌈η⭆θ⎇∧⁼ι§μ⁰⁼κ§μ¹§μ²ωε⮌εＭ⌈ＥεＬκ±Ｌε

```

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

```
≔Ｅθ§ι¹η≔Ｅθ§ι⁰ζ

```

Extract the coordinates from the input.

```
Ｆ…·⌊ζ⌈ζ«

```

Loop over the x-coordinates.

```
≔Ｅ…·⌊η⌈η⭆θ⎇∧⁼ι§μ⁰⁼κ§μ¹§μ²ωε

```

Loop over the y-coordinates, extracting and concatenating all of the strings at the given coordinates.

```
⮌ε

```

Print the strings in reverse order as the y-coordinates are reversed compared to Charcoal's coordinate system.

```
Ｍ⌈ＥεＬκ±Ｌε

```

Move to the start of the next column.

# Answer
> 3 votes
# Clean, ~~212~~ 206 bytes

```
import StdEnv,StdLib
? =minList
m=maxList
c=flatten
$a#(x,y,z)=unzip3 a
=flatlines(map c(transpose[[ljustify(m(map length l))k\\l<-[reverse[c[s\\(u,v,s)<-a|u==i&&v==j]\\j<-[?y..m y]]],k<-l]\\i<-[?x..m x]]))

```

Try it online!

---
Tags: code-golf, string, array, matrix, generation
---


# Question
Title: Radiation hardened cyclic quine polyglot
## Challenge

Write two programs that:

* run in two different programming languages.
    + These may not be two versions of one language.
* when one program is run, it outputs the second program, and vice versa.
* The two programs must be different (no polyglots).

Here's the catch though:

* The programs must be radiation hardened.
    + This means that when any set of \\$n\\$ (defined below) characters is removed from either of the two programs, their functionality is unaffected.
    + \\$n\\$ is defined as the number of characters that may be omitted with your program's functionality unaffected.
    + \\$n\\$ must be at least \\$1\\$.

## Rules

* Standard loopholes are disallowed.
* Your programs must be proper cyclic quines. They may not read their own source code.
* Scoring is performed as follows:
    + Your score is \\$\frac{S\_1+S\_2}n\\$
    + where \\$S\_1\\$ and \\$S\_2\\$ are the size of your first and second programs respectively…
    + and \\$n\\$ is as defined above.
* This is a , lowest score wins.

## Reward

As this challenge is difficult to answer, I will be giving a bounty to the first person to answer.

# Answer
> 5 votes
# Gol\>\<\> and \>\<\>, (117 bytes + 117 bytes)/1 = 234

### Gol\>\<\>

```
\\<<'3d*}}}}~}:r0<}!o::! ?>~~a<o>Hr~Kl a}}:?%2l}}}ss2"<<\\
\\<<'3d*}}}}~}:r0<}!o::! ?>~~a<o>Hr~Kl a}}:?%2l}}}ss2"<<\\

```

Try it online!

### \>\<\>

```
\\<<"2ss}}}l2%?:}}a lK~rH>o<a~~>? !::o!}<0r:}~}}}}*d3'<<\\
\\<<"2ss}}}l2%?:}}a lK~rH>o<a~~>? !::o!}<0r:}~}}}}*d3'<<\\

```

Try it online!

Verification!

These two programs are the same, just reversed. They both follow the same general code structure.

### Explanation (Gol\>\<\> on top, \>\<\> on the bottom)

```
\\<<                           <<\\  Transition to the copy of the code that is not radiated
\\<<                           <<\\

                              "    Wrapping string literal over the rest of the code
                              '

                           ss2     Push the string character
                           *3d

                        }}}        Rotate the "<<\" to the correct end of the stack
                        }}}

                 }}:?%2l           Use the extra \ to replace a possible irradiated copy
                    }~}:

       ~     lK                    Duplicate the code
        ~~>? !::o!}<0r             Print a copy of the code in reverse

                a                  Push a newline
       a
    Hr                             Reverse, print the rest of stack and terminate
    >o<                            Print the rest of the stack and terminate

```

---
Tags: code-challenge, quine, radiation-hardening
---