title: Quineoid Triple - A(B) = C

text:
# Question
Title: Quineoid Triple - A(B) = C
Write three different programs such that when any one program is provided as input to one of the other two, you get the source of the remaining program as output. More explicitly, given programs \\$A\\$, \\$B\\$, and \\$C\\$, where \\$f(g)\\$ denotes the output obtained from inputting the text of program \\$g\\$ into program \\$f\\$, ***all*** of the following must hold:

* \\$ A(B) = C \\$
* \\$ A(C) = B \\$
* \\$ B(A) = C \\$
* \\$ B(C) = A \\$
* \\$ C(A) = B \\$
* \\$ C(B) = A \\$

# Rules and Scoring

* This is , so the shortest program length total, in bytes wins.
* Standard quine rules apply.
* Each program must be at least one byte different from the other two
* Each program can be in any language. Any number of them may share languages or each may use a different language.
* Use any convenient IO format as long as each program uses a consistent convention.
    + Functions are allowed, as this counts as "any convenient IO".
* The result of feeding a program its own source code is undefined
* The result of feeding anything other than program text of either of the other two programs is undefined.

# Answer
> 9 votes
## JavaScript + Python 3 + Bash, 938 bytes

### JavaScript, 465 bytes

```
a=3-2-1//True;a=str(a);alert,eval,prompt=print,exec,input;String=JSON=__builtins__;JSON.stringify=repr;JSON.fromCharCode=chr
s=String.fromCharCode;j=JSON.stringify;r="t='tr '+s(48)+s(49)+' '+s(49)+s(48)";eval(r);d="alert([t,'a=3-2-'+a+'//True;a=str(a);alert,eval,prompt=print,exec,input;String=JSON=__builtins__;JSON.stringify=repr;JSON.fromCharCode=chr\\ns=String.fromCharCode;j=JSON.stringify;r='+j(r)+';eval(r);d='+j(d)+';eval(d)'][+(prompt()[2]<s(33))])";eval(d)

```

### Python 3, 465 bytes

```
a=3-2-0//True;a=str(a);alert,eval,prompt=print,exec,input;String=JSON=__builtins__;JSON.stringify=repr;JSON.fromCharCode=chr
s=String.fromCharCode;j=JSON.stringify;r="t='tr '+s(48)+s(49)+' '+s(49)+s(48)";eval(r);d="alert([t,'a=3-2-'+a+'//True;a=str(a);alert,eval,prompt=print,exec,input;String=JSON=__builtins__;JSON.stringify=repr;JSON.fromCharCode=chr\\ns=String.fromCharCode;j=JSON.stringify;r='+j(r)+';eval(r);d='+j(d)+';eval(d)'][+(prompt()[2]<s(33))])";eval(d)

```

### Bash, 8 bytes

```
tr 01 10

```

## TIO links

Javascript(Bash)

Javascript(Python)

Python(Bash)

Python(Javascript)

Bash(Javascript)

Bash(Python)

For some reason, TIO doesn't understand Javascript's `alert` function, but you can try it in your browser console.

## Explanation:

The JavaScript and Python codes are 1 byte apart. The only difference is that the JS code starts with `a=3-2-1` where the Python code has `a=3-2-0`. This is a polyglot pseudo-quine. The output is *almost* identical to the source code, but if the source code has a `1` in that statement, the output has a `0`, and vice versa. This is because the pseudo-quine puts the current value of `a` into the string that describes how `a` is initialized.

In other words, the JavaScript code constructs the Python code and vice versa, and it's completely arbitrary which one is considered JavaScript and which is considered Python. Both programs are valid in either language.

Here's the JS/Python code without the quine construction, and with spaces and line breaks to make it more readable:

```
a=3-2-1//True; a=str(a); alert,eval,prompt=print,exec,input; String=JSON=__builtins__; JSON.stringify=repr; JSON.fromCharCode=chr
s=String.fromCharCode;
j=JSON.stringify;
r="t='tr '+s(48)+s(49)+' '+s(49)+s(48)";
eval(r);
d="alert([t, <pseudo-quine>][+(prompt()[2]<s(33))])";
eval(d)

```

The JavaScript version ignores all the redefinitions after `//` on the top line, and redefines the verbose `String.fromCharCode` and `JSON.stringify` functions to single characters. It then constructs the string `tr 01 10` and the pseudo-quine and puts both in a list. To access the list, it checks whether the third character in the input is less than `!` and casts the result to an integer with `+(bool)`. If the input is `tr 01 10` (or anything else with a space as the third character), this check is true and it prints the pseudo-quine. If the input is the Python code, this condition is false, and it prints `tr 01 10`.

The Python logic is identical, but it renames some functions and creates dummy `JSON` and `String` namespaces for compatibility with JavaScript. It also casts `a` to a string so Python won't complain about concatenation. The redefinitions are possible because `//` is a comment in JavaScript, but floor division in Python. `a//True` is the same as `a//1`, but I'm avoiding the use of `1` and `0` everywhere except the first statement.

Finally, `tr 01 10` simply changes `0` to `1` and vice versa. This has the same effect as running the JS/Python code with the other version as input.

I initially chose Python and Javascript because they have a lot of overlapping syntax and `//` made it easy to add compatibility logic, but I ended up having to redefine more functions than I expected. There's probably a better pair of languages for this approach (maybe Python and Ruby?). I guess I could have cheated by using Python 2 and 3 as my "different languages", but that's hardly the most interesting approach :)

# Answer
> 10 votes
# C, ~~243~~ ~~240~~ ~~180~~ ~~132~~ 57 bytes

```
f(int*v){ v[4]^=1;}

```

```
f(int*v){ v[4]^=2;}

```

```
f(int*v){ v[4]^=3;}

```

Try it online:

The input program can be passed as a `char*` to the function `f`, and is implicitly converted to an `int*`.

-60 bytes thanks to @Neil
-48 bytes thanks to @Bubbler
-72 bytes thanks to @AZTECCO

# Answer
> 10 votes
# Pyth, 5 + 5 + 5 = 15 bytes

```
CxCz1

```

```
CxCz2

```

```
CxCx3

```

Try A(B), A(C), B(A), B(C), C(A), C(B) online!

## Explanation

```
CxCz_
  Cz    # convert input from base-256 to int
 x  _   # xor 1, 2 or 3 based on program
C       # convert from int to base-256

```

# Answer
> 10 votes
# brainfuck, 33+34+35=102 bytes

Perhaps one of a few answers that has the length of the 3 programs not equal. (\*)

```
+␀>>,<,[<+>,]<-----[+>>.<<].,[.,]
++␀>>,<,[<+>,]<-----[+>>.<<].,[.,]
+++␀>>,<,[<+>,]<-----[+>>.<<].,[.,]

```

Try it online!

The ␀ () represents a null character.

Alternatives:

* `+␀>,>,[<<+>>,]<<-----[+>.<].,[.,]`
* `-␀>,>,[<<->>,]<<+++++[->.<].,[.,]`

(\*): The only one at the time of posting. BF is the only used language that doesn't have integer literal.

---

Explanation:

```
+             Set a cell (call this cell 1) to X (depends on the current program, may be 1, 2 or 3)
<NUL>         No operation
>,            Read the first byte of the input (must be a "+") and store it in cell 2
>,[<<+>>,]    Increment cell 1 by (-1+(the number of remaining "+" in the input until the <NUL>))
                (use cell 3 as temporary storage)
<<-----       Decrement cell 1 by 5
[+>.<]        Print (-(that many)) (cell 2) (must be +)
.             Print a NUL byte
,[.,]         Copies the rest of the input to the output

```

# Answer
> 3 votes
# Charcoal, 42 bytes

```
≔0η⭆θ⎇⊖κι⁻⁻³ηι
≔1η⭆θ⎇⊖κι⁻⁻³ηι
≔2η⭆θ⎇⊖κι⁻⁻³ηι

```

Try it online! Link shows `A` passed `B` and printing `C`. Explanation:

```
≔0η

```

Store either `0`, `1` or `2` in a variable as appropriate.

```
⭆θ

```

Map over the parameter.

```
⎇⊖κι

```

Leave all characters except the second unchanged.

```
⁻⁻³ηι

```

Subtract the variable and the second character from 3.

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

```
(⍕3-0+⍎)@5
(⍕3-1+⍎)@5
(⍕3-2+⍎)@5

```

Try it online!

Three functions that change the 5th character (from the left, 1-based) from the input string. Link shows that all six requirements (`f(g)≡h` etc.) are satisfied.

```
(⍕3-n+⍎)@5  ⍝ All functions share the same format
(      )@5  ⍝ Apply to the 5th character only...
      ⍎       ⍝ Eval the character; m←0 or 1 or 2
  3-n+        ⍝ 3-(n+m)
 ⍕            ⍝ Stringify the above

```

# Answer
> 3 votes
# JavaScript (ES6), 75 bytes (3 x 25)

Uses the same approach as most other answers.

```
// f1
s=>s.replace(/\d/,x=>x^1)

// f2
s=>s.replace(/\d/,x=>x^2)

// f3
s=>s.replace(/\d/,x=>x^3)

```

Try it online!

# Answer
> 3 votes
**Python 3, 3\*51 = 153 bytes Try it online!**

```
x=input();print(x.replace(x[-4],str(int(x[-4])^1)))
x=input();print(x.replace(x[-4],str(int(x[-4])^2)))
x=input();print(x.replace(x[-4],str(int(x[-4])^3)))

```

Adapted @aidan0626 answer, got the same length

---

Although, this would return the actual function if in/out would be functions instead of programs.

```
def a(x):return b if x==c else c
def b(x):return c if x==a else a
def c(x):return a if x==b else b

```

works for inputs like c(c(c(b(a(c(a)))))) -\> b

# Answer
> 2 votes
# Raku, 11+11+11=~~45~~ 33 bytes

```
{S{\d}+^=1}
{S{\d}+^=2}
{S{\d}+^=3}

```

Try it online!

Xors the first digit in the input with the current program's index.

# Answer
> 2 votes
# , 72 51 bytes

```
0&(3-+)&.".@{.,}.
1&(3-+)&.".@{.,}.
2&(3-+)&.".@{.,}.

```

Try it online!

*-21 bytes thanks to Bubbler!*

## original

# , 72 bytes

```
a=.(0{3":@-0+8".@{])`8:`]}~
b=.(0{3":@-1+8".@{])`8:`]}~
c=.(0{3":@-2+8".@{])`8:`]}~

```

Try it online!

*Heavily inspired by Bubbler's clever answer.*

*Note: -11 off stated TIO score for the `a=.`, `b=.`, `c=.` pieces, and line breaks*

# Answer
> 2 votes
# Japt, 3\*3 = 9 bytes

Uses the convenient I/O format of an array of characters.

```
o^1

```

Try it

# Answer
> 1 votes
# Python 2, ~~186~~ 153 bytes

-33 bytes thanks to @Neil

```
x=raw_input();print x.replace(x[48],`int(x[48])^1`)
x=raw_input();print x.replace(x[48],`int(x[48])^2`)
x=raw_input();print x.replace(x[48],`int(x[48])^3`)

```

Example

Takes input from the user using `raw_input()` and changes the number after the `^` symbol and prints it out

# Answer
> 1 votes
# Japt v2.0a0, 6 + 6 + 6 = 18 bytes

```
d\d_^1

```

```
d\d_^2

```

```
d\d_^3

```

Try it

## Explanation

```
d\d_^?
d       // Replace occurrences
 \d     // of a digit
   _^?  // with the digit xor 1, 2 or 3 based on program

```

# Answer
> 1 votes
# PHP, 30 * 3 = 90 bytes

```
$argn[9]=1^$argn[9];echo$argn;
$argn[9]=2^$argn[9];echo$argn;
$argn[9]=3^$argn[9];echo$argn;

```

Try it online!

Uses the XOR approach, because he's the space sheriff

# Answer
> 1 votes
# Befunge-98, 3 * ~~15~~ 14 = ~~45~~ 42 bytes

*-1 * 3 bytes thanks to @Jo King!*

```
0'c\~+-#;,#@~;
1'c\~+-#;,#@~;
2'c\~+-#;,#@~;

```

Try it online!

Uses the subtraction method.

### Explanation

```
X'c\~+-#;,#@~;
X               # Push X (the number of the program, either 0, 1, or 2)
 'c             # Push 99
   \            # Swap 99 and X
    ~           # Get the first character of the input (which is 48+Y, where Y is the number of the second program)
     +          # Add (the stack now looks like [99, 48+X+Y])
      -         # Subtract 48+X+Y from 99, leaving 51-X-Y
       #;       # (skipped)
                # (begin loop)
         ,      # First iteration: Output 51-X-Y, the first character of the third program
          #@    # (skipped)
            ~   # Get the next character of the input
        ;    ;  # Jump to the start of the loop
         ,      # Output the character unchanged
                # (repeat)
            ~   # On EOF, reverse direction
           @    # End the program

```

# Answer
> 0 votes
# Python 2, 123 bytes

```
lambda x:x.replace(x[-4],`int(x[-4])^1`)#
lambda x:x.replace(x[-4],`int(x[-4])^2`)#
lambda x:x.replace(x[-4],`int(x[-4])^3`)#

```

Try it online!

Note that the comment at the end is required since otherwise the index will have to be either `-3` or `37` instead of `-4` which will mess things up when replacing 3

# Answer
> 0 votes
# Lua, 64\*3=192 bytes

```
print(((...):gsub('%d',load"return ('').char((...):byte()~1)")))

```

Try it online! (includes test cases)

Other two programs:

```
print(((...):gsub('%d',load"return ('').char((...):byte()~2)")))
print(((...):gsub('%d',load"return ('').char((...):byte()~3)")))

```

Use xor like many other programs

---
Tags: code-golf, source-layout
---


title: Lumberjaxe Code Golf

text:
# Question
Title: Lumberjaxe Code Golf
Tom the lumberjack is going to do his daily routine: chop trees. After all, it's his job to do so. His boss has ordered him to chop trees in a straight line marked with a special tape to identify them, so he knows which trees he is going to have to chop. However, Tom quickly realizes he has a problem. His axe will only chop so much wood before breaking, and he forgot to bring a spare with him. Plus, the trees are different sizes. A small tree, marked with an `i`, will take 2 swings of the axe to chop, and a large tree, marked with an `|` will take 4 swings. Can Tom chop all of the assigned trees?

**The Objective**

Given two inputs, a string that determines the sequence of small and large trees and an integer that determines the durability of the axe, create a program that determines not only if Tom's axe will break or not, but also determine how many of each tree type he chopped down. It's , so the shortest code in bytes wins!

**Example**

Input 1 example:`i||iii|` This input string determines the sequence of trees.

Input 2 example:`50` This input integer determines the durability of the axe.

The outputs for this particular example will be a boolean and a string as follows(True means Tom's axe broke): `False` `4 small, 3 big`

# Answer
# 05AB1E, 20 bytes

-5 bytes thanks to Kevin Cruijssen.

```
ηʒÇ3%·ÌO@}θD¹Ês{γ€g‚

```

Try it online!

## Explanation

```
η                    Prefixes of the input. ["i", "i|", "i||", "i||i", "i||ii", "i||iii", "i||iii|"]
 ʒ                   Filter:
  Ç                      Ord codes. E.g. "i||i" -> [105, 124, 124, 105]
   3%                    Mod 3.          ->        [0, 1, 1, 0]
     ·                   Double.         ->        [0, 2, 2, 0]
      Ì                  Add 2.          ->        [2, 4, 4, 2]
       O                 Sum the prefix. ->        12
        @}               Does it exceed
                       the second input? -> 50 >= 12 -> 1

          θ              The last item of the filtered prefixes: "i||iii|"
           D             Duplicate.
            ¹Ê           Is it not equal to the first inupt?     "i||iii|" != "i||iii|" -> 0
              s          Swap the other copy up.                 "i||iii|"
               {         Sort.                                   "iiii|||"
                γ        Group by consecutive equal items.       ["iiii","|||"]
                 €g      Map: length.                            [3, 4]
                   ‚     Pair.                                   [0, [3, 4]]

```
> 5 votes

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

Takes input as `(b)(n)`, where `b` is a Buffer (using the characters described in the challenge) and `n` is the durability of the axe.

Returns a Boolean value and 2 integers as `[ broken, [ small, big ]]`.

```
b=>n=>[b.some(c=>(n-=6&c+1)<0||!++a[c%3],a=[0,0]),a]

```

Try it online!

### How?

Given an ASCII code `c`, we use `6 & (c + 1)` to get the number of swings needed to chop the tree, and `c % 3` to get an index into the tree-counting array `a[]` (0 for *small*, 1 for *big*).

```
 char. | c = ASCII code | 6 & (c + 1) | c % 3
-------+----------------+-------------+-------
  'i'  |       105      |      2      |   0
  '|'  |       124      |      4      |   1

```
> 7 votes

# Answer
# , 37 34 33 bytes

```
(](-:;+/@#:@])(>:2*+/\)#])' i'i.]

```

Try it online!

*-1 byte thanks to Bubbler*

Converts small to 1, big to 2. Now create a filter by doubling and scan summing, and apply filter to find entries less than or equal to the left input. Take just those entries, convert to binary, and sum to get the `<num big>, <num small>` part of the answer. Check if the filtered list equals the unfiltered list to get the "chops down all trees?" part of the answer.
> 4 votes

# Answer
# , 63 bytes

using characters exactly as described in challenge (or only **54 bytes** using 0,1 to represent small & big trees, and outputting 0,1 to represent FALSE/TRUE axe breaking).

```
function(a,t)list(sum(c<-2+2*(t<"i"))>a,table(t[cumsum(c)<=a]))

```

Try it online!
> 4 votes

# Answer
# Python 2, ~~103~~ \\$\cdots\\$ ~~82~~ 80 bytes

Saved ~~4~~ ~~6~~ ~~9~~ 11 bytes thanks to ovs!!!

```
f=lambda s,n:n<sum(6&ord(t)%6for t in s)and f('<'+s[:-1],n)or map(s.count,"<i|")

```

Try it online!

Inputs a string of trees \\$s\\$ (as `i`s and `|`s) and an axe durability \\$n\\$.
Outputs a list of `[axe broken, small trees, large trees]` where `axe broken` is truthy if Tom's axe broke (or falsy otherwise) followed by the number of trees cut down.

**How**

If \\$c\\$ is either `i`, `|` or `<` then: $$ \text{6&ord(c)%6} = \left\\{ \begin{array}{ll} 2 \text{ if c is 'i'}\\ 4 \text{ if c is '|'}\\ 0 \text{ if c is '\<'} \end{array} \right. $$

this is summed for all the trees in \\$s\\$ to calculate its needed durability. If it's too much for Tom's axe then we repeatedly try again without the last tree and set Tom's axe as broken by inserting a `<` into \\$s\\$, making that count truthy. When Tom's axe us strong enough we return what happened to his axe along with the number of each tree still in \\$s\\$.
> 4 votes

# Answer
# Keg, 32 bytes

```
0:&®s?⑷¦i2⑹|\|4©s⑨®s±™⑸¿⅀0=⑻©s(.

```

Try it online!

Takes input as trees, durability and outputs big, small and whether or not the axe breaks.

Somehow, Keg beat pyth.
> 3 votes

# Answer
# Jelly, 14 bytes

I'm assuming, for now, that the "boolean" part of the output may be given as a Truthy/Falsey value.

```
Og©2ḤÄ’<a®‘ċⱮ3

```

A dyadic Link accepting the trees (a list of characters) on the left and the axe durability (an integer) on the right which yields a list of three integers, `[is_broken, small_trees, big_trees]` (Note that non-zero integers are Truthy in Jelly while `0` is Falsey).

**Try it online!**

### How?

```
Og©2ḤÄ’<a®‘ċⱮ3 - Link: list of characters, T; integer, D   e.g. "|i|iii"; 14
O              - Ordinals (T)                                   [124,105,124,105,105,105]
  ©            - copy this to the register and yield it:
 g 2           -   greatest common divisor with two             [2,1,2,1,1,1]
    Ḥ          - double                                         [4,2,4,2,2,2]
     Ä         - cumulative sums                                [4,6,10,12,14,16]
      ’        - decrement                                      [3,5,9,11,13,15]
       <       - less than (D)?                                 [1,1,1,1,1,0]
        a      - logical AND with:
         ®     -   recall the value from the register           [2,1,2,1,1,0]
          ‘    - increment                                      [3,2,3,2,2,1]
            Ɱ3 - map across 3 with: (i.e. for right in [1,2,3])
           ċ   -   count occurrences                            [1,3,2]

```
> 2 votes

# Answer
# Python 3.8, 109 bytes

```
f=lambda l,n,a=0,b=0:f(l[1:],m,a+1-j,b+j)if l and(m:=n-((j:='i|'.index(l[0]))+1)*2)>=0 else[l!=''and m<0,a,b]

```

Try it online!
> 2 votes

# Answer
# Retina 0.8.2, 55 bytes

```
\d+
$*
(11)+1?(?<-1>(i)|(?<-1>(\|)))*($)?.*
$#4 $#3 $#2

```

Try it online! Takes input as \[durability\]\[trees\] without a separator and outputs \[complete\] \[big\] \[small\]. Explanation:

```
\d+
$*

```

Convert the durability to unary.

```
(11)+1?

```

Capture half the durability as `$#1`.

```
(?<-1>(i)|(?<-1>(\|)))*

```

Count the trees as they are matched, and decrement the remaining durability appropriately depending on the size of tree.

```
($)?.*

```

Determine whether the all of the trees were chopped down.

```
$#4 $#3 $#2

```

Output the desired results.
> 1 votes

# Answer
# Desmos, 73+31+8+8 = ~~125~~ 120 bytes

-5 bytes from finding a new builtin, which cost a few bytes but allowed three functions to be collapsed into one.

```
l(g)=\sum_{m=1}^{t.length}\left\{2*\sum_{n=1}^m t[n]<=d:g[t[m]],0\right\}
\left\{d-total(t)*2<0:1\right\}
l([1,0])
l([0,1])

```

(each line is an individual function, line breaks are not used and don't count towards bytes)

Try it online

Desmos is absolutely the wrong choice of language for this problem.

Input is taken as a variable `t` holding the trees as an array of 1s and 2s, representing 2s and 4s (as accepted in the comments, Desmos doesn't even support strings anyways) / small and large trees and a variable `d` holding the durability. Output is in the second function (will it break, undefined for no and 1 for yes) and third and fourth functions (short and tall trees chopped respectively.

Explanation:

```
l(g)=\sum_{m=1}^{t.length}\left\{2*\sum_{n=1}^m t[n]<=d:g[t[m]],0\right\}

```

Calculates the amount of trees of a certain type chopped. It goes through each tree, checks if it has enough durability to chop it with the inner `sum`, and if so, adds a 1 or a 0 depending on the tree type, based on a lookup array `g` passed to it.

```
\left\{d-total(t)*2<0:1\right\}

```

Simple calculation to check if the durability available is less than what's required. Fun fact: Desmos can't properly output truthy or falsey values! It does support true and false, as you can see if you plug in `\left\{3>2:1,0\right\}` (where 3\>2 evaluates to true, causing 1 to be output instead of 0), but you can't actually get then to print. Plug in `3>2` and you don't get any output. Additionally, try to use values we might traditionally think of as truthy or falsey in those same formulas, and you get an error! For this reason, it's possible that this isn't technically a truthy/falsey output based on this, but that definition allows for the occasional exception, which I think this fits under. I think we can all agree that 1 is truthy and undefined is falsey, so that's what I've gone with here. A looser definition (for example, any positive number is truthy and 0, undefined, and negatives are falsey) would likely allow for this line to be shorter.

```
l([1,0])

```

Calculate `1` (short) trees chopped with a 1 in position 1.

```
l([0,1])

```

Calculate `2` (tall) trees chopped with a 1 in position 2.
> 1 votes

---
Tags: code-golf, sequence
---


title: Arbitrary Clock Time Calculator

text:
# Question
Title: Arbitrary Clock Time Calculator
Create a routine to calculate the position of each unit of a clock with an arbitrary number of units (minutes, hours, half-days, days, years, parsecs, quarter-quells, etc), where each unit can be equally sub-divided into an arbitrary number of sub-units; *after* `n` base units have elapsed.

Basically, figure out what a clock would show after `n` seconds given user defined lengths for minutes, hours, days, etc.

For example, after 86,400 seconds on a clock that has 60 seconds in a minute, 60 minutes in an hour, 12 hours per half day, 2 half days per day, and 365 days in a year; you get the following:

`clockFunction(86400,[60,60,12,2,365]) = 0,0,0,0,1` (Standard Clock)

`clockFunction(86400,[60,60,12,2]) = 0,0,0,0` (Standard Clock - Rolling Over)

`clockFunction(7430201,[100,100,10,10,3,12]) = 1,2,3,4,1,2` (French Republican Calendar \[sec / min, min / hr, hrs / day, days / wk, wks / mo, mo / yr\])

`clockFunction(2443332,[60,60,24,365]) = 12,42,6,28` (Standard Clock - Donnie Darko)

`clockFunction(63570500940,[60,60,12,2,365,10000]) = 0, 29, 4, 1, 294, 2015` (Standard Clock - Back to the Future)

Shortest code that works wins!

Clarifications:

* All Units are integer
* All Units are greater than 0

# Answer
# Dyalog APL, ~~9~~ ~~7~~ 5 bytes

```
⌽⊤⍨∘⌽

```

This is a dyadic function train that expects seconds and lengths as left and right arguments. It is equivalent to the following, train-less function:

```
{⌽⍺⊤⍨⌽⍵}

```

Verify all test cases at once on TryAPL.

### How it works

```
    ⌽ Reverse the right argument...
   ∘    and...
 ⊤⍨     perform mixed base encoding on the left argument with those bases.
⌽     Reverse the order of the result.

```
> 6 votes

# Answer
# CJam, 10 bytes

```
{{md\}%W<}

```

Verify all test cases at once in the CJam interpreter.

### How it works

```
{        }  Define a code block:
 {   }%     For each unit length:
  md          Perform modular division with the topmost integers on the stack.
    \         Swap quotient and residue.
            Collect the results in an array.
       W<   Discard the last quotient.

```
> 3 votes

# Answer
# Javascript ES6, 34 bytes

```
F=(q,a)=>a.map(u=>[q%u|0,q/=u][0])

```

Explanation:

```
F=(q,a)=>a.map(u=>
  // For each unit
  [
    q%u|0, // floored remainder of q / u
    q/=u // set q to quotient of q / u
  ][0] // return remainder
)

```
> 3 votes

# Answer
# C – 166 ~~176~~ bytes

The *Back to the Future* test case necessitated using `long long` types! The output format is not consistent in the specs, sometimes there are spaces after the comma, sometimes not, I assumed this meant the space was discretionary. ~~Handles units of zero by outputting `-1`.~~

```
#include<stdlib.h>
#include<stdio.h>
int main(int c,char**v){long long x=atoll(*++v),m;while(--c>1){m=atoll(*++v);printf("%lld%c",x%m,c>2?',':'\n');x/=m;}return 0;}

```

To use, save as `units.c`, compile via `gcc -o units units.c`, and run on the command line as follows:

```
$ ./units 63570500940 60 60 12 2 365 10000
0,29,4,1,294,2015

```

Depending on compiler options, you may be able to remove `int`  and `return 0;` for 153 bytes.
> 2 votes

# Answer
# MATLAB, 66

```
function a=d(t,L);a=[];for s=L;a=[a mod(t,s)];t=floor(t/s);end;end

```

And an explanation

```
function a=d(t,L)
    a=[];
    for s=L %For each of the input blocks
       a=[a mod(t,s)]; %Append the number in this block
       t=floor(t/s); %And divide by the size of this block ignoring the remainder
    end
end

```

It's a pretty standard approach. I'll see if I can reduce the length.

It also works with **Octave**, so you can try it here.
> 0 votes

# Answer
# Wolfram Language (Mathematica), 47 bytes

```
#~NumberDecompose~Reverse@FoldList[Times,1,#2]&

```

Try it online!
> 0 votes

# Answer
# \>\<\>, 12 bytes

```
:{:}%:nao-{,

```

Expect (units...,seconds) on the stack.

\>\<\> has the oddball property of supporting floating point division but not integer division, so the verbous stack shifting `{}` and copying `:` here is in order to subtract the remainder before performing division.
> 0 votes

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


# Question
Title: Number chopping: Split a number into its digits
# Number Splitting

## Instructions

Oh no, my numbers have stuck together! Luckily, we can split them apart with code.

Your code should be a function that takes an integer input from stdin or as an argument. You must split the number into single digits, keeping the order and possible duplicates of these digits. The output should be an array and it may be returned from the function or from stdout. Other forms of output may be discussed. The array elements may be a string or number.

## Examples

```
345 -> [3, 4, 5]
12218 -> [1, 2, 2, 1, 8]

```

## Scoring

This is code golf, so shortest code wins.

# Answer
> 2 votes
# JavaScript, 12 bytes

-3 bytes if we can take input as a string.

```
n=>[...n+""]

```

Try it online!

# Answer
> 4 votes
# Japt, 1 byte

Trivial challenges get trivial solutions.

```
ì

```

Try it

# Answer
> 3 votes
# Wolfram Language (Mathematica), 13 bytes

```
IntegerDigits

```

Try it online!

# Answer
> 2 votes
# Retina 0.8.2, 4 bytes

```
\B
,

```

Try it online! Explanation: Simply inserts a `,` between each pair of digits. Alternatively, if a newline-delimited list is acceptable, then for 3 bytes:

```
!`.

```

Try it online! Explanation: Simply lists each digit separately. Alternatively, to produce the example output, then for 13 bytes:

```
\B
,
^
[
$
]

```

Try it online! Link includes test cases. Alternatively, this can be done in Retina 1 for 12 bytes:

```
[[|", "]]L`.

```

Try it online! Link includes test cases.

# Answer
> 2 votes
# Arn, 1 byte

Mmm. I have absolutely no idea how I found this...

```
\

```

Try it!

# Explained

```
  _  The current input (implicit)
 \   Map/Fold by this:
_    The current item of the input, overloaded by \

     Thus, Map/Fold yields a list of the items of the input string.

```

# Arn, 2 bytes

```
<i

```

Try it!

# Explained

Unpacked: `:!"`

```
_      Input indicator (implicit)
 :!    Split by
   "   The empty string
    "  Trailing quote mark (implicit)

```

# Answer
> 1 votes
# Assembly (MIPS, SPIM), 106 bytes

Outputs the digits space-separated.

```
.data
.text
main:li $v0,12
syscall
move $a0,$v0
beq $a0,10,e
li $v0,11
syscall
li $a0,32
syscall
b main
e:

```

Try it online!

# Assembly (MIPS, SPIM), 160 bytes

This outputs in a format looking like a list of digits.

```
.data
.text
main:li $a0,91
li $v0,11
syscall
l:li $v0,12
syscall
move $a0,$v0
beq $a0,10,e
li $v0,11
syscall
li $a0,44
syscall
b l
e:li $a0,93
li $v0,11
syscall

```

Try it online!

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

Prompts for integer:

```
⍎¨⍕⎕

```

Try it online! Courtesy of Dyalog Classic

# Answer
> 0 votes
# Javascript(ES6), 38 bytes

Just to kick this off.

```
a=(w)=>{return w.toString().split("")}

```

## Output:

345 -\> \["3", "4", "5"\] 12218 -\> \["1", "2", "2", "1", "8"\]

# Answer
> 0 votes
# Python 2, 18 bytes

```
lambda x:list(`x`)

```

# Python 3, 21 bytes

```
lambda x:list(str(x))

```

# Answer
> 0 votes
# Python 3: ~~28~~ 20 bytes

Try it Online - lambda function

Try it Online - normal function def

Tried it with lambda function (20 bytes) instead of normal function definition

```
x=lambda n:[*str(n)]

```

My earlier response with normal def function - 28 bytes

```
def x(n):*x,=str(n);return x

```

Calling the function as follows:

```
print(x(345))
print(x(12218))

```

Output:

```
['3', '4', '5']
['1', '2', '2', '1', '8']

```

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

Returns a string representation of the integer.

```
f(i){int*s;asprintf(&s,"%d",i);i=s;}

```

Try it online!

# Answer
> 0 votes
# Pyth, 3 bytes

```
jQT

```

Try it online!

Explanation: Takes the integer input (Q) and converts it into base 10 (T) and returns the individual digits in a list.

---

# Pyth, 3 bytes

```
cz1

```

Try it online!

Unlike the above one, this one takes input as a string and returns an array of the characters of the string. Still 3 bytes. :\<)

# Answer
> 0 votes
# Jelly, 1 byte

Another trivial solution.

```
D

```

Try it online!

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


title: Spiral Permutation Sequence

text:
# Question
Title: Spiral Permutation Sequence
We can roll up the natural numbers in a rectangular spiral:

```
 17--16--15--14--13
  |               |
 18   5---4---3  12
  |   |       |   |
 19   6   1---2  11
  |   |           |
 20   7---8---9--10
  |
 21--22--23--24--25

```

But now that we have them on a rectangular grid we can unwind the spiral in a different order, e.g. going clockwise, starting north:

```
 17  16--15--14--13
  |   |           |
 18   5   4---3  12
  |   |   |   |   |
 19   6   1   2  11
  |   |       |   |
 20   7---8---9  10
  |               |
 21--22--23--24--25

```

The resulting sequence is clearly a permutation of the natural numbers:

```
1, 4, 3, 2, 9, 8, 7, 6, 5, 16, 15, 14, 13, 12, 11, 10, 25, 24, 23, 22, 21, 20, 19, 18, 17, ...

```

Your task is to compute this sequence. (OEIS A020703, but spoiler warning: it contains another interesting definition and several formulae that you might want to figure out yourself.)

**Fun fact:** all 8 possible unwinding orders have their own OEIS entry.

## The Challenge

Given a positive integer `n`, return the `n`th element of the above sequence.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.

Standard rules apply.

## Test Cases

```
1       1
2       4
3       3
4       2
5       9
6       8
7       7
8       6
9       5
100     82
111     111
633     669
1000    986
5000    4942
9802    10000
10000   9802

```

For a complete list up to and including `n = 11131` see the b-file on OEIS.

# Answer
> 6 votes
# Jelly, ~~11~~ 10 bytes

```
’Æ½ð²+ḷ‘Ḥ_

```

Another Jelly answer on my phone.

```
’Æ½ð²+ḷ‘Ḥ_   A monadic hook:
’Æ½          Helper link. Input: n
’             n-1
 Æ½            Atop integer square root. Call this m.
   ð         Start a new dyadic link. Inputs: m, n
    ²+ḷ‘Ḥ_    Main link:
    ²+ḷ       Square m, add it to itself,
       ‘      and add one.
        Ḥ     Double the result
         _    and subtract n.

```

Try it here.

# Answer
> 8 votes
# Japt, ~~20~~ ~~19~~ 16 bytes

```
V=U¬c)²-V *2-U+2

```

Test it online!

Based on the observation that

> F(N) = ceil(N^.5) * (ceil(N^.5)-1) - N + 2

Or, rather, that

> F(N) = the first square greater than or equal to N, minus its square root, minus N, plus 2.

I don't know if this explanation is on the OEIS page, as I haven't looked at it yet.

# Answer
> 5 votes
# Julia, 28 bytes

```
n->2((m=isqrt(n-1))^2+m+1)-n

```

This is a lambda function that accepts an integer and returns an integer. To call it, assign it to a variable.

We define *m* to be the largest integer such that *m*2*n*-1, i.e. the integer square root of *n*-1 (`isqrt`). We can then simplify the OEIS expression 2 (*m* \+ 1) *m* \- *n* \+ 2 down to simply 2 (*m*2 \+ *m* \+ 1) - *n*.

Try it online

# Answer
> 4 votes
# CJam, 14 bytes

```
qi_(mQ7Ybb2*\-

```

Using Alex's approach: `2*(m^2+m+1)-n` where `m = isqrt(n-1)`.

# Answer
> 2 votes
## ES7, ~~31~~ ~~28~~ 26 bytes

```
n=>(m=--n**.5|0)*++m*2-~-n

```

I had independently discovered Alex's formula but I can't prove it because I wasn't near a computer at the time.

Edit: Saved 3 bytes partly thanks to @ETHproductions. Saved a further 2 bytes.

# Answer
> 2 votes
# APL (Dyalog Extended), ~~25~~ ~~19~~ 14 bytes

```
{2⊥⍨3⍴⌊√⍵-1}-⊢

```

-6 bytes from Adám.

-5 bytes from Bubbler.

Try it online!

A direct implementation of the last function mentioned on the OEIS page:

\\$a(n)=2×\Big(\big\lfloor\sqrt{n-1}\big\rfloor+1\Big)×\big\lfloor\sqrt{n-1}\big\rfloor-n+2\\$

## Explanation:

```
{(2-⍵)+2×(1+⌊√⍵-1)×⌊√⍵-1} ⍵ → n
                   ⌊√⍵-1  floor of root of n-1
         (1+⌊√⍵-1)×       times 1 + floor of root of n-1
       2×                 times 2
 (2-⍵)                    plus 2-n

```

Try it online!

# Answer
> 1 votes
# Pyth, 21 bytes

```
K2-h+^.E@QKK^t.E@QKKQ

```

Try it online!

Nothing fancy going on. Same method as in the JAPT answer.

# Answer
> 1 votes
# MATL, ~~16~~ 13 bytes

```
qX^Y[tQ*Q2*G-

```

Based on Lynn's CJam answer.

**Try it online!** (`Y[` has been replaced by `k` according to changes in the language)

```
q       % input n. Subtract 1
X^      % square root
Y[      % floor
tQ      % duplicate and add 1
*       % multiply
Q       % add 1
2*      % multiply by 2
G-      % subtract n

```

---

This uses a different approach than other answers (**16 bytes**):

```
6Y3iQG2\+YLt!G=)

```

It explicitly generates the two spiral matrices (actually, vertically flipped versions of them, but that doesn't affect the output). The first one is

```
17    16    15    14    13
18     5     4     3    12
19     6     1     2    11
20     7     8     9    10
21    22    23    24    25

```

and the second one traces the modified path:

```
25    10    11    12    13
24     9     2     3    14
23     8     1     4    15
22     7     6     5    16
21    20    19    18    17

```

To find the `n`-th number of the sequence it suffices to find `n` in the second matrix and pick the corresponding number in the first. The matrices need to be big enough so that `n` appears, and should have *odd* size so that the origin (number `1`) is in the same position in both.

**Try it online** too! (`6Y3` has been moved according to changes in the language)

```
6Y3      % 'spiral' string
i        % input n
QG2\+    % round up to an odd number large enough
YL       % generate spiral matrix of that size: first matrix
t!       % duplicate and transpose: second matrix
G=       % logical index that locates n in the second matrix
)        % use that index into first matrix

```

# Answer
> 1 votes
# Brachylog, 20 bytes

```
-1$r$[I*I+I+1=*2-?=.

```

This uses the same technique as pretty much all other answers.

### Explanation

```
-1                   § Build the expression Input - 1
  $r                 § Square root of Input - 1
    $[I              § Unify I with the floor of this square root
       *I+I+1        § Build the expression I * I + I + 1
             =*2-?   § Evaluate the previous expression (say, M) and build the expression
                     § M * 2 - Input
                  =. § Unify the output with the evaluation of M * 2 - Input

```

A midly interesting fact about this answer is that it is easier and shorter to use `=` rather than parentheses.

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


title: Golf a golf chart

text:
# Question
Title: Golf a golf chart
Given a distance in meters as an integer \\$60\le d \le 260\\$, return the number of clubs that may be used according to the following arbitrary chart, where both \\$min\\$ and \\$max\\$ are inclusive:

```
 club           | min | max
----------------+-----+-----
 Driver         | 200 | 260
 3-wood         | 180 | 235
 5-wood         | 170 | 210
 3-iron         | 160 | 200
 4-iron         | 150 | 185
 5-iron         | 140 | 170
 6-iron         | 130 | 160
 7-iron         | 120 | 150
 8-iron         | 110 | 140
 9-iron         |  95 | 130
 Pitching Wedge |  80 | 115
 Sand Wedge     |  60 |  90

```

## Notes

* The club names are given for information only.
* Of course, the choice of the club depends on several other parameters. For instance the *Sand Wedge* is designed to escape from a sand bunker. But for the purposes of this challenge, only the distance matters.
* This is undoubtedly a challenge.

## Example

For \\$d=130\\$, we may choose *6-iron*, *7-iron*, *8-iron* or *9-iron*, so the expected answer is \\$4\\$.

## Test cases

```
Input Output
60    1
79    1
80    2
93    1
105   2
110   3
116   2
129   3
130   4
200   4
201   3
235   2
260   1

```

Or as lists:

```
Input : 60, 79, 80, 93, 105, 110, 116, 129, 130, 200, 201, 235, 260
Output: 1, 1, 2, 1, 2, 3, 2, 3, 4, 4, 3, 2, 1

```

# Answer
# x86-16 machine code, ~~47~~ 42 bytes

```
00000000: be14 01b3 01b1 0bad 3ad0 7205 3ad4 7701  ........:.r.:.w.
00000010: 43e2 f4c3 505a 5feb 6e73 78d2 8282 8c8c  C...PZ_.nsx.....
00000020: 9696 a0a0 aaaa b4b9 c8c8                 ..........

```

**Listing:**

```
BE 0114     MOV  SI, OFFSET CHART   ; SI point to distance chart
B3 01       MOV  BL, 1              ; start counter at 1
B1 0B       MOV  CL, 11             ; loop 11 clubs
        SCORE_LOOP:
AD          LODSW                   ; load AL = min, AH = max
3A D0       CMP  DL, AL             ; is d less than min?
72 05       JB   DONE               ; if so, continue
3A D4       CMP  DL, AH             ; is d greater than max?
77 01       JA   DONE               ; if so, continue
43          INC  BX                 ; otherwise increment counter
        DONE:
E2 F4       LOOP SCORE_LOOP         ; loop through end of chart
C3          RET                     ; return to caller

CHART   DB  80,90,95,235,110,115,120,210,130,130,140,140
        DB  150,150,160,160,170,170,180,185,200,200

```

Callable function, input `d` in `DX`, output in `BL`.

No compression (the data is only ~~24~~ 22 bytes in binary anyway) just a table comparison.

**Edit:** Huge props to @SE - stop firing the good guys for re-arranging the list and eliminating need to offset the `d` value, saving **5 bytes**!

**Test program runs:**

### Alternate version, 50 bytes

```
BB 0501     MOV  BX, 0501H          ; init counter to 1 in BL and
BF 556D     MOV  DI, 0556DH         ; magic number to 0x5556D in BH:DI
BE 011C     MOV  SI, OFFSET CHART   ; SI point to transition table
B1 16       MOV  CL, 22             ; loop 22 transitions
        SCORE_LOOP:
AC          LODSB                   ; load AL = next transition
3A C2       CMP  AL, DL             ; is d less than?
77 0B       JA   EXIT               ; if not, end
D0 EF       SHR  BH, 1              ; cascade bit shift high word into CF
D1 DF       RCR  DI, 1              ; bit shift lsb into CF
43          INC  BX                 ; increment counter
72 02       JC   NEXT               ; if CF was a 1, continue to next
4B          DEC  BX                 ; otherwise subtract 2
4B          DEC  BX
        NEXT:
E2 F0       LOOP SCORE_LOOP         ; keep looping
        EXIT:
C3          RET

CHART   DB 80,91,95,110,116,120,130,131,140,141,150,151,160,161,170,171,180,186,200,201,211,236

```

This is heavily inspired by Jonathan Allan's answer. This uses a table of values of `d` where the number of clubs transitions either `+1` or `-1`, and a corresponding binary *magic number* of `0x5556d` where a `1` indicates a positive change and `0` indicates a negative change.

Unfortunately, this doesn't help a lot here since encoding the original table is **24 bytes** versus the **22** transitions plus the **3 byte** magic number so really it's larger. It was fun trying though!
> 17 votes

# Answer
# Python 3, 71 bytes

```
lambda n:sum(a<=n/5<=b for a,b in zip(b'($" ',b'4/*(%" '))

```

Try it online!

The byte strings contain some unprintables, their escaped form is `b'($" \x1e\x1c\x1a\x18\x16\x13\x10\x0c'` and `b'4/*(%" \x1e\x1c\x1a\x17\x12'`.

---

# Python 3, 71 bytes

```
lambda n:sum(b>n-a*5>-1for a,b in zip(b'($" ',b'=8))$$$'))

```

Try it online!

---

# Python 3.8, ~~90~~ 86 bytes

```
lambda x:-~sum([79<x<91,94<x<236,-1<(a:=x-110)<6,9<a<101,69<a<76,a/10in{2,3,4,5,6,9}])

```

Try it online!

The last condition can also be written as `a%10<1<a/10<7,a==90` at the same length.
> 12 votes

# Answer
# Jelly, 25 bytes

```
“Ḳœẹ“rɓ?’ḃ5×5“ZO‘;"Ä⁸>§I‘

```

A full program which prints the result (or a monadic Link which returns a single-element list).

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

### How?

For any valid input, in \\$\[60,260\]\\$ we are able to use at least one club. For any given yardage, in \\$\[61,260\]\\$, we are able to use either the same, one more, or one less club than we could have done for one yard less. The code below encodes the yardages at which the number of available clubs goes up, and those at which the number of available clubs goes down and uses that to calculate the result.

```
“Ḳœẹ“rɓ?’ḃ5×5“ZO‘;"Ä⁸>§I‘ - Main Link: integer, Y  e.g. 129
“Ḳœẹ“rɓ?’                 - list of (two) base-250 integers = [11132965,7226564]
         ḃ5               - convert to bijective base five -> [[5,3,2,2,2,2,3,3,2,5],[3,3,2,2,2,2,2,2,2,4]]
           ×5             - multiply by five -> [[25,15,10,10,10,10,15,15,10,25],[15,15,10,10,10,10,10,10,10,20]]
             “ZO‘         - list of code-page indices = [90,79]
                  "       - zip with:
                 ;        -   concatenation -> [[90,25,15,10,10,10,10,15,15,10,25],[79,15,15,10,10,10,10,10,10,10,20]]
                   Ä      - Cumulative values -> [[90,115,130,140,150,160,170,185,200,210,235],[79,94,109,119,129,139,149,159,169,179,199]]
                    ⁸>    - is Y greater than (those)? -> [[1,1,0,0,0,0,0,0,0,0,0],[1,1,1,1,0,0,0,0,0,0,0]]
                      §   - sums -> [2,4]
                       I  - deltas -> [2]
                        ‘ - increment -> [3]
                          - implicit print -> "3"

```
> 7 votes

# Answer
# , 63 58 55 50 bytes

```
1#.1=(59 90+/\@,|:5*2+4#.inv 2424834 3408207)I."1]

```

Try it online!

*-5 bytes thanks to xash*

Encodes lists as numbers in base 4, reconstructs, then uses interval index `I.` to count how many of the ranges the input falls within.
> 6 votes

# Answer
# K (oK), ~~85~~ 82 bytes

**Solution:**

```
{+/z=x|y&z}.(-3 -1 .5 2 3 4 5 6 7 8 9 11;0 2.5 4 5 6 7 8 9.5 11 12 14.5 17),-9+.1*

```

Try it online!

**Explanation:**

Decidedly naive; highly likely that this is a bad approach. *Although nice golf by ngn to simplify the comparison logic!*.

```
{+/z=x|y&z}.(-3 -1 .5 2 3 4 5 6 7 8 9 11;0 2.5 4 5 6 7 8 9.5 11 12 14.5 17),-9+.1* / the solution
                                                                               .1* / multiply input by 0.1
                                                                            -9+    / subtract 9 from input
                                                                          ,        / append to
            (-3 -1 .5 2 3 4 5 6 7 8 9 11;0 2.5 4 5 6 7 8 9.5 11 12 14.5 17)        / club stats
{         }.                                                                       / call lambda with multiple args
       y&z                                                                         / min of input and min distance
     x|                                                                            / max compared to max distance
   z=                                                                              / is input the same?
 +/                                                                                / sum up

```

**Extra:**

* **-3 bytes** thanks to `ngn`
> 5 votes

# Answer
# Python 3, ~~180~~ ~~155~~ ~~153~~ ~~97~~ 88 bytes

```
lambda n:sum(a<=chr(n)<b for a,b in zip('<P_nx‚Œ– ª´È','[tƒ—¡«ºÉÓìą'))

```

Try it online!
> 5 votes

# Answer
# , ~~77~~ ~~76~~ 72 bytes

*Edit: -4 bytes thanks to Robin Ryder*

```
sum((d=scan()/10-9)>=c(11,9:2,.5,-1,d)&d<=c(d,14.5,12,11,9.5,8:4,2.5,0))

```

Try it online!

Fairly naive solution, but benefits from 's automatic vectorization and its `:` sequence operator.
> 5 votes

# Answer
# Python 3, 105 bytes

```
lambda n,a=[1],b=[2],c=[3],d=[4]:(a*20+b*11+a*4+b*15+c*6+b*4+c+(c*9+d)*6+d*5+c*14+d+c*10+b*25+a*25)[n-60]

```

Try it online!

Explanation: A simple bruteforce to store the list of answers and print the required index.
> 3 votes

# Answer
# Charcoal, 44 bytes

```
ＮθＩΣＥ¹²⁻›θ⁺⁵⁹×⁵Σ…”)⊞⊟‹Ｇ↔”ι›θ⁺⁹⁰×⁵Σ…”)⊟+.Ｄ↥”ι

```

Try it online! Link is to verbose version of code. Port of @JonathanAllen's answer. Explanation:

```
Ｎθ

```

Input `d`.

```
ＩΣＥ¹²⁻

```

Map over the 12 clubs and print the sum of the results cast to string of taking the differences between...

```
›θ⁺⁵⁹×⁵Σ…”)⊞⊟‹Ｇ↔”ι

```

... `d` compared with `59` added to `5` times the digital sum of prefix of the compressed string `43322222224`, and...

```
›θ⁺⁹⁰×⁵Σ…”)⊟+.Ｄ↥”ι

```

... `d` compared with `90` added to `5` times the digital sum of prefix of the compressed string `53222233235`.

Previous 48-byte answer:

```
ＮθＩΣＥＩ⪪”)¶∧!✂η}⌊⍘⪫⪫⊕#<e⌊W[qＹ9¤…”²∧›θ⁻×⁵ι﹪κ²⊖⊗﹪κ²

```

Try it online! Link is to verbose version of code. Explanation: The ending and starting distances of the 12 clubs are split from a compressed string of integers from 12 to 52 which are multiplied by 5. `d` is compared against them all, scoring `1` for greater or equal distances in odd positions and `-1` for greater distances in even positions and the final total is printed.
> 3 votes

# Answer
# Python 3, 62 60 bytes

```
lambda d:sum(b//25<=b%25+23-d/5<=7for b in b'BUNSWYQ+-}')+1

```

Try it online!

There's an invisible (on Stack Exchange) `\x18` character at the end of the string.
> 3 votes

# Answer
*I think it's possible to achieve more aggressive compression ratios in most non-esolangs.*

*As a little incentive, here are my own scores in Python and Node.*

*I will unveil both code snippets below as soon as a shorter or equally long answer is posted (or updated) in either language, or at 2PM UTC on Friday August 21, 2020 in the unlikely event that no such answer is published by then.*

**EDIT (2020-08-19):** Congratulations to @flornquake for being the first to post a Python answer below 70 bytes, using an idea similar to mine but pushing it a step further for a total of 62 bytes!

---

# Python 3.8 (pre-release), 70 bytes

```
lambda d,n=12:sum((n:=n+x//8-4)<=d/5<=n+x%8+6for x in b' A980001225F')

```

Try it online!

---

# JavaScript (Node.js), 74 bytes

```
d=>Buffer(' A980001225F').map(x=>t-=d/5<(n+=x-32>>3)|d/5>n+x%8+6,n=t=12)|t

```

Try it online!
> 2 votes

# Answer
# Perl 5, 70 bytes

The first byte in the string is added in `\x##` notation for easy testing, but is a literal byte.

```
$_=grep"@F">=($k+=(ord>>4)*5)&"@F"<=$k+(15&ord)*5,"\xc6G76&&&'((+L"=~/./g

```

Stores the details for each club (divided by 5) as a byte where the first four bits are the difference from start of the previous range and the start of this one, and the second four bits are the difference between the start of this range and the end.

```
start  end =>     / 5   =>   binary    #
--------------------------------------------
 60     90 => 12      6 => 11000110    # counter starts at 0
 80    115 => 4       7 => 00100100    # counter is 12 from before so we only need an extra 4
 95    130 => 3       7 => 00110111
110    140 => 3       6 => 00110110

```

Try it online!
> 2 votes

# Answer
# C (gcc), ~~83~~ 75 bytes

(not all characters show correctly on stack exchange, but are correct in TIO)

```
*i;c;f(d){c=0;for(i=L"ÈĄ´ëªÒ È–¹Œª‚ x–nŒ_‚Ps<Z";*i;c+=d/ *i++&*i++/d);d=c;}

```

Try it online!
> 1 votes

# Answer
# JavaScript (V8), ~~142~~ ~~132~~ ~~117~~ 113 bytes

-10 bytes: applied -9 to ranges and input after division rather than only dividing by 10 (inspired by other answers, understood why it was worth it after observing my range/10 numbers)

-15 bytes thanks to Arnauld's improvements

-5 bytes thanks to Shaggy's further improvements

```
d=>[11,17,9,14.5,8,12,7,11,6,9.5,...'58473625',.5,4,-1,2.5,-3,t=0].map((e,i,r)=>t+=++i%2&d>=e&d<=r[i],d=d/10-9)|t

```

Try it online!

Pretty naive solution but I wasn't comfortable attempting more complex methods used in other answers (not to mention I'm not sure if they're even possible/worth golfing with in JS!). I'll happily take advice/improvements, though.

Unminified & explained (slightly outdated but still explains the overall process):

```
f = (distance) => {
    // divide input by 10 and subtract 9 since the hardcoded ranges are shorter when those operations are done.
    distance = distance / 10 - 9

    // hardcoded ranges divided by 10 then subtracted 9 to save bytes (probably can be done better).
    // Will be used in pairs, only processing even indexes and using i & i+1
    //ranges = [20,26,18,23.5,17,21,16,20,15,18.5,14,17,13,16,12,15,11,14,9.5,13,8,11.5,6,9] // /10
    //ranges = [14,20,12,17.5,11,15,10,14,9,12.5,8,11,7,10,6,9,5,8,3.5,7,2,5.5,0,3] // /10 -6
    ranges = [11,17,9,14.5,8,12,7,11,6,9.5,5,8,4,7,3,6,2,5,0.5,4,-1,2.5,-3,0] // /10 -9 (winner! inspired by other answers)

    // .map used as .reduce
    ranges.map((e, i)=> { // e: current element, i: current index
        totalValidClubs += ( // increment total 'valid' counter if within range
            i%2 == 1 ? 0 : // skip odd indexes, will use i & i+1 on even indexes only
            distance>=e && distance<=ranges[i+1] ? 1 : 0) // if even index and distance is between ranges[i] & [i+1] (inclusive), increment by 1.
    }, totalValidClubs=0); // initialize valid club counter as 0
    return totalValidClubs;
}

```
> 1 votes

# Answer
# 05AB1E, ~~38~~ 36 bytes

**38 Bytes**

```
"ÈĄ´ëªÒ È–¹Œª‚ x–nŒ_‚Ps<Z"Ç2ôε.SOÄ2‹}O

```

I'm bad at compressing :( The best I could have think of is converting each number to an ASCII character.

Explanation:

```
"ÈĄ´ëªÒ È–¹Œª‚ x–nŒ_‚Ps<Z"Ç2ôε.SOÄ2‹}O
"ÈĄ´ëªÒ È–¹Œª‚ x–nŒ_‚Ps<Z"                Ranges of clubs as ASCII chars
                            Ç               Convert to values
                             2ô             Split into chunks of two
                               ε       }    Map on pairs
                                .S          -1 if lower than input, 1 if greater, 0 it equal
                                  O         Sum the result of the pair
                                   Ä        Absolute value
                                    2‹      Is it lower than 2? (The only cases the absolute value is 2 are when the input is out of range)
                                        O   Now we have list of 0 and 1 for each range. Sum it up :)

```

Try it online!

**36 Bytes** (thanks to @ovs)

```
"ÈĄ´ëªÒ È¹ª xn_Ps<Z"Ç2ôε-P(d}O

```

Using `-P(d` inside map, which will subtract the pair with the input, product it (out of range values will be positive), then apply `negative` with `(` and check if the value is non-negative using `d`.

Try it online!
> 1 votes

# Answer
# Io, 89 bytes

```
method(a," \"$("asList select(i,v,v at(0)<=a/5and a/5<=" \"%(*/4"at(i))size)

```

Try it online!
> 1 votes

# Answer
# Pyth, 36 bytes

```
s/RC-QTrV"2FUdnx‚Œ– ª¾""Qjyƒ—¡°¿Éâû

```

Try it online!

## Explanation

```
              "...   # String literal with end of ranges minus 10 as characters
         "..."       # String literal with start of ranges minus 10 as characters
       rV            # Generate the ranges
 /R                  # Count occurrences of
   C-QT              # input minus 10 converted to a characters (based on ascii value)
                     # in each of the ranges
s                    # sum

```
> 1 votes

# Answer
# \>\<\>, 51 bytes

```
"ÇÉ³º©«Ÿ¡•—‹ƒwÓmt^ìO["1&{:})${:}(*&+&55*0l3)?.&n;

```

(contains 7 unprintables)

Try it online!

Since there's at least 1 club for every input, one may re-arrange the ranges to get rid of one range, which has the added benefit of removing the "260" part which is just barely outside the range of a byte.
> 1 votes

# Answer
## Desmos, 106 bytes:

```
f(d)=total(\left\{join([18...11],[9.5,8,6,20])*10<=d<=[47,42,40,37,34,32,30,28,26,23,18,52]*5:1,0\right\})

```

View graph online

Delete `f(d)=` and subtract 5 bytes if you're cool with using a slider as input.
> 1 votes

# Answer
## APL, ~~52~~ ~~45~~ 50 bytes:

```
{+⌿1=(↓12 2⍴⎕ucs'Èą´ìªÓ Éº«¡xn_Pt<[')∘.⍸⍵}

```

Try it online!
> 0 votes

---
Tags: code-golf, compression
---


title: Tips for golfing in Io

text:
# Question
Title: Tips for golfing in Io
What general tips do you have for golfing in Io? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Io (e.g. "remove comments" is not an answer). Please post one tip per answer.

# Answer
## Higher-level function shorthand

This seems like a pretty interesting golfing point. E.g.

```
list(1,2,3)map(i,i+1)print

```

However, Io is pretty permissive on not specifying the counter; the map body can be used as a point-free function, as Io tries to fill in the operand of this expression. This can be golfed into

```
list(1,2,3)map(+1)print

```

---

Due to the helpful work of the language creator, you can even do this to reduces!

```
list(1,2,3)reduce(a,b,a*b)

```

Can easily be reduced into:

```
list(1,2,3)reduce(*)

```

(Unfortunately, I still haven't managed to understand how exactly this works, so I never managed to make the expression more complex.)
> 4 votes

# Answer
# You can stick methods onto the back of most literals

```
"text" print    # 12 bytes
"text"print     # 11 bytes

12 print        # 8 bytes
12print         # 7 bytes

(0<1,0,1) print # 15 bytes
(0<1,0,1)print  # 14 bytes

```

## Not everything

```
0x12print # prints nothing

```
> 3 votes

# Answer
## You can leave out the else part of the if function

This isn't in the documentation... I initially thought that you have to include the else part, like the elvis operator in other languages; turns out that I can leave out the else part. (*Please* add this to the tutorial/documentation!)

```
if("bug"size>2,"True",nil)

```

So, if you don't want the else part to return anything, you could just do

```
if("bug"size>2,"True")

```
> 3 votes

# Answer
## Use `~`, `:`, and `\` for variable names

You can stick methods onto the back of `~`. E.g. instead of this:

```
method(i,i pop)

```

You can do this:

```
method(~,~pop)

```

You can even put this between them. Instead of this:

```
and a sqrt

```

You can do this

```
and~sqrt

```

`:` also does this trick (I discovered it from the `:=` bug), as well as `\`. (This can empirically save a lot of bytes in your source code, if you use variables a lot)

## Some other valid symbolic names that you can't stick

* `_`
* `.`

## Can you stick these to other symbols as well?

~~Unfortunately, things get a little complicated here. Here's a table of how powerful these variable names are:~~

Unfortunately, you can't stick any of them before `:=` or on the rhs of `/`, so pick whatever name you like. :P
> 3 votes

# Answer
## Literal newlines

Just like JavaScript's \`\`, you can insert literal newlines. i.e. you can do:

```
"
"

```
> 1 votes

# Answer
## Parenthesis dropping in method applications

Say, I want to split a string by whitespace. I am pretty used to this method when I first got used to Io:

```
a_string split()

```

After I heard about how Io parses the arithmetic operations, I realized that this is perfectly valid:

```
a_string split

```

---

Sometimes, you can do that to some one-operand functions as well. If you want to join by spaces, you can do:

```
a string join" "

```

I guess this doesn't work sometimes, though I can't find any examples here.
> 1 votes

# Answer
## Prefer push over append

There are 2 methods that append values towards the caller object: `add`, `push`, and `append`. I didn't count `add` because `add` doesn't work. Try it online!

`push` and `append` basically do the same thing:

```
list(1,2,3)push(4) println
list(1,2,3)append(4) println

```

Try it online!

Therefore, whenever you want to write `append`, remember that you can substitute it for `push` to do the exact same thing.
> 1 votes

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


title: Codington Crescent

text:
# Question
Title: Codington Crescent
*Let's just see how this goes*

If you've ever listened to the radio program "I'm sorry, I haven't a clue", then you've probably heard of the game called "Mornington Crescent". For those who haven't, it's a game where players name random stations on the London Underground network. The first person to name "Mornington Crescent" wins the game.1

In the same sort of spirit as the classic radio game, I present to you **Codington Crescent**.

## The Challenge

The winner of this challenge is the first person to post a working program that prints the exact string `Codington Crescent`.

## The Rules

1. Each player has their own program that they will add/change characters. This is termed their **running program**.

**In this way, the only aspect is the rules. Everyone uses their own running program. No one shares a program at all**

2. Each answer (**a turn**) has to obey source restrictions defined by previous answers. These are called **rules**. Each varient lasts for 5 **turns**. Rules are in the style of either , or limiting of language names (but not both).
3. Running programs can change languages between turns.
4. Answerers (**players**) can either add or change (but not both) as many characters of their running program per turn as they like. Alternatively, they can choose to "pass", adding no new rules, and still counting as a turn. This may be the only choice if rules conflict with each other. The turn count is still incremented and is to be posted. Pro tip: You probably might want to mark it community wiki because it doesn't add much.
5. At the end of each turn, the player declares a new rule that will span the next 5 turns. Rules must be objective, and a TIO verification program is highly recommended. Also, rules have to be able to be applied to every language (e.g. `Programs must not error using Python 3.4.2` isn't a valid rule).
6. Play continues until a running program prints the target string.

## Starting Rules

As to kick off the game, the first 5 turns must follow these rules:

1. Turns may not print `Codington Crescent`.
2. Running programs must be irreducible. (Clarification, not a rule change: irreducible in this case means that the program doesn't produce the output of the whole program if characters from the whole program are removed. Ie. There does not exist a program that has the default same output that can be constructed by removing characters from the original program.)
3. Maximum program length is 20 bytes.

## Example Rules

These are purely examples of what you could add as rules to the challenge. They do not apply unless someone decides to use them.

* **Languages must have at least 3 characters in their name**
* **The first and last letter of the running program must be a space**
* **Running programs must have an even amount of bytes**
* **Languages must be in the practical category on TIO**
* **Running programs must not be more than 30 bytes**

## Extra Answer Chaining Rules

* You cannot answer twice in a row. Someone else needs to answer before you have another go.
* Languages need to be on Try It Online in order to be valid answers.

1 The original game of Mornington Crescent doesn't really have rules... It's more of an activity that looks like it's a complicated game.

**Pro-tip: sort by oldest for a more cohesive flow of answers**

## Answer Template

# [Language], turn number [your turn]

[Try it online link]
[prev answer link]
## Rules

- Rule (n turns left)
- Rule (n turns left)
- Rule (n turns left)
```
</code></pre>

# Answer
# , 43 bytes, codepoint total 59^2, turn number 6

Previous submission (turn 4)

*This turn: added 23 characters = 'Codington'+'Crescent'#H*

```
`+`=cat;'Kodington'+'Crescent'#@'C"pr'+'nt'

```

Try it online!

Rules

* Programs may not print Codington Crescent.(expired)
* Running programs must be irreducible. (expired)
* Maximum program length is 20 bytes. (expired)
* Programs must have the substring C"pr (last turn)
* Programs may not contain brackets of any kind. (1 turn left)
* Minimum program length is 19 bytes (2 turns left)
* Programs may not contain any whitespace characters (3 turns left)
* The codepoint sum needs to be a perfect square that's greater than 1444. (4 turns left)
* Programs may only output 'Codington Crescent' if they are irreducible AND modifications (additions OR changes) of at most 8 characters from a previously-submitted answer (5 turns left)
> 4 votes

# Answer
# , 158 bytes, codepoint total 105^2, turn number 9

Previous submission (turn 6)

*This turn: added 115 characters: 'a=";b=")";k="ZPEJOHUPO!ZSFTDFOU"\[`\156\143ha\162`(a)==48\];`\143a\164`(`\143ha\162\164\162`("B-Z","a-w\40\103","M"))'*

```
a="`+`=cat;'Kodington'+'Crescent'#@'C";b=")pr'+'nt'";k="ZPEJOHUPO!ZSFTDFOU"[`\156\143ha\162`(a)==48];`\143a\164`(`\143ha\162\164\162`("B-Z","a-w\40\103","M"))

```

Try it online!

Comments: *pppery*'s rule (turn 8) forbidding programs to output any of their own characters has rather scuppered any chance of me winning this turn, or even next turn, since my previous program (from turn 6) was packed-full of now-forbidden characters, and I'm not allowed to modify my code (to get rid of them) in the same turn as adding to it (to implement a new 'print X without X' approach).
So, for this turn, I'm trying to (1) begin the first half of building-up my program under the current rules, which will need continuing on a subsequent turn before being ready to win, and (2) add a rule to stop the other current contestants.

*Razetime*, *petStorm* and *Szewczyk* all already need more than \>8 characters of changes to their current programs before they can win. *pppery* currently has a program that requires only 2 characters to be changed to print `Codington Crescent`, leaving 6 characters free to comply with the perfect-square-codepoint rule, which is probably enough. However, the approach of adding `+25` to all the printed characters means that the  (space) character is encoded by a non-printable byte. Moreover, if the `+25` is changed, then \>8 other characters would need to be changed to get `Codington Crescent` again. So I think (hope) that simply restricting code to printable ASCII is sufficient to block this program (at least for now).

Rules:

* Programs may not contain any whitespace characters (last turn)
* The codepoint sum needs to be a perfect square that's greater than 1444. (1 turn left)
* Programs may only output 'Codington Crescent' if they are irreducible AND modifications (additions OR changes) of at most 8 characters from a previously-submitted answer (2 turns left)
* Programs may not output any characters contained in their source code (4 turns left)
* Programs may not contain any bytes corresponding to non-printable ASCII characters (that is, \<32 or \>126) (5 turns left)
> 4 votes

# Answer
# Io, turn number 1

```
"MoC"print

```

Try it online!

prev answer link

## Rules

* Turns may not print Codington Crescent. (1 turns left)
* Running programs must be irreducible. (1 turns left)
* Maximum program length is 20 bytes. (1 turns left)
* Your answer has to include the substring `C"pr`. Online Verifier (2 turns left)
> 3 votes

# Answer
# ///, Turn number 2

```
C"prodington

```

**Edit:** Changed the porgram to fit the guidelines on irreducibility, discussed here. Rules have not changed.

Try it online!

## Rules

* Programs may not print Codington Crescent.(3 turns left)
* Running programs must be irreducible. (3 turns left)
* Programs must have the substring `C"pr` (4 turns left)
* Maximum program length is 20 bytes. (3 turns left)
* Programs may not contain brackets of any kind. (5 turns left)
> 3 votes

# Answer
# str, 25 bytes, turn number 8

```
`*VKPUN\VU*YLZJLU\`25+p;

```

Note the invisible character with code point 7 between between `VU` and `*Y`

Rules

* Programs may not contain brackets of any kind. (expired)
* Minimum program length is 19 bytes (last turn)
* Programs may not contain any whitespace characters (1 turn left)
* The codepoint sum needs to be a perfect square that's greater than 1444. (2 turns left)
* Programs may only output 'Codington Crescent' if they are irreducible AND modifications (additions OR changes) of at most 8 characters from a previously-submitted answer (3 turns left)
* Programs may not output any characters contained in their source code (5 turns left)

Try it online!
> 3 votes

# Answer
# , 19 bytes, turn number 4

```
`+`=cat;'C"pr'+'nt'

```

Try it online!

Rules

* Programs may not print Codington Crescent.(1 turns left)
* Running programs must be irreducible. (1 turns left)
* Maximum program length is 20 bytes. (1 turns left)
* Programs must have the substring C"pr (2 turns left)
* Programs may not contain brackets of any kind. (3 turns left)
* Minimum program length is 19 bytes (4 turns left)
* Programs may not contain any whitespace characters (5 turns left)
> 2 votes

# Answer
# Io, turn number 3

```
"idoC"print

```

## Original submission: Befunge-98 (FBBI), 19 bytes, turn 3

**NOTE: invalidated per (transcript)**

```
"nidoC"4k,@@@@@C"pr

```

Try it online!

# Rules

* Programs may not print Codington Crescent.(2 turns left)
* Running programs must be irreducible. (2 turns left)
* Programs must have the substring `C"pr` (3 turns left)
* Maximum program length is 20 bytes. (2 turns left)
* Programs may not contain brackets of any kind. (4 turns left)
* Minimum program length is 19 bytes (5 turns left)
> 2 votes

# Answer
# Io, 19 bytes, turn number 5

```
"Codin34:::;C"print

```

Try it online!

Prev answer

## Rules

* Programs may not print Codington Crescent.(1 turns left)
* Running programs must be irreducible. (1 turns left)
* Maximum program length is 20 bytes. (1 turns left)
* Programs must have the substring `C"pr` (2 turns left)
* Programs may not contain brackets of any kind. (3 turns left)
* Minimum program length is 19 bytes (4 turns left)
* Programs may not contain any whitespace characters (5 turns left)
* The codepoint sum needs to be a perfect square that's greater than 1444. (6 turns left) Verifier
> 1 votes

# Answer
# ///, Turn number 7, FARKLE

```
C"prodington

```

This is a passed move. No change.

Try it online!

## Rules

* Programs must have the substring C"pr (expired)
* Programs may not contain brackets of any kind. (last turn)
* Minimum program length is 19 bytes (1 turns left)
* Programs may not contain any whitespace characters (2 turns left)
* The codepoint sum needs to be a perfect square that's greater than 1444. (3 turns left)
* Programs may only output 'Codington Crescent' if they are irreducible AND modifications (additions OR changes) of at most 8 characters from a previously-submitted answer (4 turns left)
> 1 votes

---
Tags: code-challenge, restricted-source, answer-chaining
---


title: Upper or Lower Wythoff?

text:
# Question
Title: Upper or Lower Wythoff?
First, let's talk about Beatty sequences. Given a positive irrational number ***r***, we can construct an infinite sequence by multiplying the positive integers to ***r*** in order and taking the floor of each resulting calculation. For example,

If ***r*** \> 1, we have a special condition. We can form another irrational number ***s*** as ***s*** = ***r*** / (***r*** \- 1). This can then generate its own Beatty sequence, ***B***s. The neat trick is that ***B***r and ***B***s are *complementary*, meaning that every positive integer is in exactly one of the two sequences.

If we set ***r*** = ϕ, the golden ratio, then we get ***s*** = ***r*** \+ 1, and two special sequences. The *lower Wythoff sequence* for ***r***:

```
1, 3, 4, 6, 8, 9, 11, 12, 14, 16, 17, 19, 21, 22, 24, 25, 27, 29, ...

```

and the *upper Wythoff sequence* for ***s***:

```
2, 5, 7, 10, 13, 15, 18, 20, 23, 26, 28, 31, 34, 36, 39, 41, 44, 47, ...

```

These are sequences A000201 and A001950 on OEIS, respectively.

### The Challenge

Given a positive input integer `1 <= n <= 1000`, output one of two distinct values indicating whether the input is in the *lower Wythoff sequence* or the *upper* sequence. The output values could be `-1` and `1`, `true` and `false`, `upper` and `lower`, etc.

Although your submitted algorithm must theoretically work for all inputs, in practice it only has to work with the first 1000 input numbers.

## I/O and Rules

* The input and output can be given by any convenient method.
* The input and output can be assumed to fit in your language's native number type.
* 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
> 13 votes
## JavaScript (ES6), ~~50~~ 35 bytes

```
f=(n,s="1",t=0)=>s[n-1]||f(n,s+t,s)
```

```
<input type=number min=1 oninput=o.textContent=this.value&&f(this.value)><pre id=o>
```

Outputs `1` for lower and `0` for upper. Explanation: Partial lists of boolean values can be constructed using a Fibonacci-like identity: given two lists, starting with `1` and `10`, each subsequent list is the concatenation of the previous two, resulting in `101`, `10110`, `10110101` etc. In this case it's slightly golfier to have a fake 0th entry of `0` and use that to construct the second element of the list.

# Answer
> 9 votes
# Python, 25 bytes

```
lambda n:-n*2%(5**.5+1)<2

```

Try it online!

Uses the very simple condition:

> `n` is in the lower Wythoff sequence exactly if `-n%phi<1`.

Note that the modulo result is positive even though `-n` is negative, matching how Python does modulo.

> **Proof:** Let `a = -n%phi`, which lies in the range `0 <= a < phi`. We can split `-n` modulo `phi` as `-n = -k*phi + a` for some positive integer `k`. Rearrange that to `n+a = k*phi`.
>
> If `a<1`, then `n = floor(n+a) = floor(k*phi)`, and so is in the lower Wythoff sequence.
>
> Otherwise, we have `1 <= a < phi` so
>
> ```
> n+1 = floor(n+a) = floor(k*phi)
> n > n+a-phi = k*phi - phi = (k-1)*phi
>
> ```
>
> so `n` falls in the gap between `floor((k-1)*phi)` and `floor(k*phi)` and is missed by the lower Wythoff sequence.

This corresponds to this code:

```
lambda n:-n%(5**.5/2+.5)<1

```

Try it online!

We save a byte by doubling to `-(n*2)%(phi*2)<2`.

# Answer
> 7 votes
# Haskell, 26 bytes

```
(l!!)
l=0:do x<-l;[1-x..1]

```

Try it online!

No floats, unlimited precision. Thanks for H.PWiz for two bytes.

# Answer
> 5 votes
# 05AB1E, 9 bytes

```
L5t>;*óså

```

Try it online!

---

0 means upper, 1 means lower. **Try the first 100: Try it online!**

---

```
    CODE   |      COMMAND      # Stack (Input = 4)
===========+===================#=======================
L          | [1..a]            # [1,2,3,4]
 5t>;      | (sqrt(5) + 1)/2   # [phi, [1,2,3,4]]
     *     | [1..a]*phi        # [[1.6,3.2,4.8,6.4]]
      ó    | floor([1..a]*phi) # [[1,3,4,6]]
       så  | n in list?        # [[1]]

```

---

**Raw Command Dump:**

```
----------------------------------
Depth: 0
Stack: []
Current command: L

----------------------------------
Depth: 0
Stack: [[1, 2, 3, 4]]
Current command: 5

----------------------------------
Depth: 0
Stack: [[1, 2, 3, 4], '5']
Current command: t

----------------------------------
Depth: 0
Stack: [[1, 2, 3, 4], 2.23606797749979]
Current command: >

----------------------------------
Depth: 0
Stack: [[1, 2, 3, 4], 3.23606797749979]
Current command: ;

----------------------------------
Depth: 0
Stack: [[1, 2, 3, 4], 1.618033988749895]
Current command: *

----------------------------------
Depth: 0
Stack: [[1.618033988749895, 3.23606797749979, 4.854101966249685, 6.47213595499958]]
Current command: ó

----------------------------------
Depth: 0
Stack: [[1, 3, 4, 6]]
Current command: s

----------------------------------
Depth: 0
Stack: [[1, 3, 4, 6], '4']
Current command: å
1
stack > [1]

```

# Answer
> 5 votes
# Jelly, 5 bytes

```
N%ØpỊ

```

Try it online!

Saved 1 byte thanks to xnor's Python golf.

---

### Jelly, 6 bytes

```
×€ØpḞċ

```

Try it online!

Returns **1** for lower and **0** for upper.

```
×€ØpḞċ – Full Program / Monadic Link. Argument: N.
×€     – Multiply each integer in (0, N] by...
  Øp   – Phi.
    Ḟ  – Floor each of them.
     ċ – And count the occurrences of N in that list.

```

Checking \\$(0,\\:N\]\cap \mathbb{Z}\\$ is most definitely enough because \\$\varphi \> 1\\$ and \\$N \> 0\\$ and therefore \\$0 \< N \< N\varphi\\$.

# Answer
> 4 votes
# Python 2, ~~39~~ ~~33~~ 32 bytes

-6 bytes thanks to Mr. Xcoder
-1 byte thanks to Zacharý

```
lambda n,r=.5+5**.5/2:-~n//r<n/r

```

Try it online!

Returns `False` for lower and `True` for upper

# Answer
> 4 votes
# Brain-Flak, 78 bytes

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

```

Try it online!

Outputs nothing for lower and `0` for upper. Changing to a more sensible output scheme would cost 6 bytes.

# Answer
> 3 votes
# Julia 0.6, 16 bytes

```
n->n÷φ<-~n÷φ

```

Try it online!

While playing around with the numbers, I came across this property: floor(n/φ) == floor((n+1)/φ) if n is in the upper Wythoff sequence, and floor(n/φ) \< floor((n+1)/φ) if n is in the lower Wythoff sequence. I haven't figured out *how* this property comes about, but it gives the correct results at least upto n = 100000 (and probably beyond).

---

Old answer:

# Julia 0.6, 31 bytes

```
n->n∈[floor(i*φ)for i∈1:n]

```

Try it online!

Returns `true` for lower and `false` for upper Wythoff sequence.

# Answer
> 3 votes
# Arn, 9 bytes

```
2>6Yx!¦ü#

```

Try it!

# Explained

Unpacked: `phi-1<%phi`

I found another way of calculating this:

> is true if `n` is in the Lower Wythoff Sequence

This example merely uses this formula (it was shorter than `1>((n_)%phi`). And here is how it works:

```
    phi  Builtin for the Golden Ratio
  -      Minus
    1    Literal one
<        Is less than
    _    Variable initialized to STDIN, implied
  %      Modulo
    phi

```

Returns true if lower, false if upper

# Answer
> 2 votes
# Wolfram Language (Mathematica), 26 bytes

```
#~Ceiling~GoldenRatio<#+1&

```

Try it online!

An integer `n` is in the lower Wythoff Sequence iff `ceil(n/phi) - 1/phi < n/phi`.

## Proof that `ceil(n/phi) - 1/phi < n/phi` is...

Sufficient:

1. Let `ceil(n/phi) - 1/phi < n/phi`.
2. Then, `ceil(n/phi) * phi < n + 1`.
3. Note `n == n/phi * phi <= ceil(n/phi) * phi`.
4. Hence, `n <= ceil(n/phi) * phi < n + 1`.
5. Since `n` and `ceil(n/phi)` are integers, we invoke the definition of floor and state `floor(ceil(n/phi) * phi) == n`, and `n` is in the lower Wythoff sequence.

Necessary; proof by contrapositive:

1. Let `ceil(n/phi) - 1/phi >= n/phi`.
2. Then, `ceil(n/phi) * phi >= n + 1`.
3. Note `n + phi > (n/phi + 1) * phi > ceil(n/phi) * phi`
4. Hence `n > (ceil(n/phi) - 1) * phi`.
5. Since `(ceil(n/phi) - 1) * phi < n < n + 1 <= ceil(n/phi) * phi`, `n` is not in the lower Wythoff sequence.

# Answer
> 2 votes
## APL (Dyalog Extended), ~~21~~ ~~19~~ 13 bytes

```
⊢∊∘⌊⍳×1+∘÷⍣=≢

```

-6 bytes from Adám after conversion to tacit function.

Try it online!

### Old answer:

```
{⍵∊⌊((1+∘÷⍣=1)×⍳⍵)}

```

Uses the same approach as Magic Octopus Urn's answer.

-2 bytes from ZippyMagician.

Prints 1 for upper and 0 for lower sequence.

## Explanation

```
{⍵∊⌊((2÷¯1+5*÷2)×⍳⍵)}
                 ⍳⍵   Generate list of 1 to n
     (2÷¯1+5*÷2)×     Multiply it by the golden ratio
   ⌊                  Floor the entire list
 ⍵∊                   is n in the list?

```

Try it online!

# Answer
> 1 votes
# Pyth, 8 bytes

```
/sM*.n3S

```

Try it here!

Returns **1** for lower and **0** for upper.

# Answer
> 1 votes
# Java 10, ~~77~~ ~~53~~ 52 bytes

```
n->{var r=Math.sqrt(5)/2+.5;return(int)(-~n/r)<n/r;}

```

Port of @Rod's Python 2 answer.
-1 byte thanks to *@Zacharý*.

Try it online.

---

**Old ~~77~~ 76 bytes answer:**

```
n->{for(int i=0;i++<n;)if(n==(int)((Math.sqrt(5)+1)/2*i))return 1;return 0;}

```

-1 byte thanks to *@ovs*' for something I recommended myself last week.. xD

Returns `1` for lower; `0` for upper.

Try it online.

**Explanation:**

```
n->{                    // Method with integer as both parameter and return-type
  for(int i=0;++i<=n;)  //  Loop `i` in the range [1, `n`]
    if(n==(int)((Math.sqrt(5)+1)/2*i))
                        //   If `n` is equal to `floor(Phi * i)`:
      return 1;         //    Return 1
  return 0;}            //  Return 0 if we haven't returned inside the loop already

```

`i*Phi` is calculated by taking `(sqrt(5)+1)/2 * i`, and we then floor it by casting it to an integer to truncate the decimal.

# Answer
> 1 votes
# Japt, 10 bytes

Returns **true** for lower and **false** for upper.

```
õ_*MQ fÃøU

```

Try it online!

## Explanation:

```
õ_*MQ fÃøU
             // Implicit U = Input
õ            // Range [1...U]
 _           // Loop through the range, at each element:
  *MQ        //   Multiply by the Golden ratio
      f      //   Floor
       Ã     // End Loop
        øU   // Return true if U is found in the collection

```

# Answer
> 1 votes
# Haskell, ~~153~~ ~~139~~ ~~126~~ 79 bytes

*Unlimited Precision!*

```
l=length
f a c|n<-2*l a-c,n<0||l a<a!!n=c:a|1>0=a
g x=x==(foldl f[][1..x+1])!!0

```

Try it online!

## Explanation

Instead of using an approximation of the golden ratio to calculate the result meaning they are prone to errors as the size of the input rises. This answer does not. Instead it uses the formula provided on the OEIS that `a` is the unique sequence such that

```
∀n . b(n) = a(a(n))+1

```

where `b` is the ordered compliment.

# Answer
> 1 votes
# Brachylog, 8 bytes

```
≥ℕ;φ×⌋₁?

```

Try it online!

The predicate succeeds if the input is in the lower Wythoff sequence and fails if it is in the upper Wythoff sequence.

```
 ℕ          There exists a whole number
≥           less than or equal to
            the input such that
  ;φ×       multiplied by phi
     ⌋₁     and rounded down
       ?    it is the input.

```

If failure to terminate is a valid output method, the first byte can be omitted.

# Answer
> 1 votes
# cQuents, 5 bytes

```
?F$`g

```

Try it online!

## Explanation

```
?         output true if in sequence, false if not in sequence
          each term in the sequence equals:

 F        floor (
  $               index *
   `g                     golden ratio
     )                                 ) implicit

```

# Answer
> 0 votes
# MATL, 8 bytes

```
t:17L*km

```

**Try it online!**

### Explanation

```
t      % Implicit input. Duplicate
:      % Range
17L    % Push golden ratio (as a float)
*      % Multiply, element-wise
k      % Round down, element-wise
m      % Ismember. Implicit output

```

# Answer
> 0 votes
# K (oK), 20 bytes

**Solution:**

```
x in_(.5*1+%5)*1+!x:

```

Try it online!

**Explanation:**

```
x in_(.5*1+%5)*1+!x: / the solution
                  x: / save input as x
                 !   / generate range 0..x
               1+    / add 1
              *      / multiply by
     (       )       / do this together
           %5        / square-root of 5
         1+          / add 1
      .5*            / multiply by .5
    _                / floor
x in                 / is input in this list?

```

# Answer
> 0 votes
# TI-BASIC (TI-84), 18 bytes

```
max(Ans=iPart((√(5)+1)/2randIntNoRep(1,Ans

```

Input is in `Ans`.
Output is in `Ans` and is automatically printed.
Prints `1` if input is in the lower sequence or `0` if it's in the upper sequence.

Coincidentally, this program will only run for \\$0\<N\<1000\\$ .

**Example:**

```
27
             27
prgmCDGFA
              1
44
             44
prgmCDGFA
              0

```

**Explanation:**

```
max(Ans=iPart((√(5)+1)/2randIntNoRep(1,Ans    ;full program, example input: 5
                        randIntNoRep(1,Ans    ;generate a list of random integers in [1,Ans]
                                               ; {1, 3, 2, 5, 4}
              (√(5)+1)/2                      ;calculate phi and then multiply the resulting
                                              ;list by phi
                                               ; {1.618 4.8541 3.2361 8.0902 6.4721}
        iPart(                                ;truncate
                                               ; {1 4 3 8 6}
    Ans=                                      ;compare the input to each element in the list
                                              ;and generate a list based off of the results
                                               ; {0 0 0 0 0}
max(                                          ;get the maximum element in the list and
                                              ;implicitly print it

```

---

**Note:** TI-BASIC is a tokenized language. Character count does *not* equal byte count.

# Answer
> 0 votes
# MathGolf, 5 bytes

```
╒φ*i╧

```

Try it online.

**Explanation:**

```
╒      # Push a list in the range [1, (implicit) input-integer]
 φ*    # Multiply each value by the golden ratio 1.618033988749895
   i   # Floor each by casting it to an integer
    ╧  # Check if the (implicit) input-integer is in this list
       # (after which the entire stack joined together is output implicitly as result)

```

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


title: Smooth a line graph

text:
# Question
Title: Smooth a line graph
Given an input of an integer *n* and a list of positive integers *m1*, *m2*, ..., output a list of integers *m1'*, *m2'*, ... where *mx'* is defined as the average of *mx-n* through *mx+n*.

When calculating these averages, ignore indices that are out of bounds (and adjust what you are dividing the sum by accordingly). *n* will always be ≥ 1 but never half of the length of *m* (rounded down) or more. This means that the minimum length of *m* is 4. The elements in *m* will be positive integers, but the output must be accurate to at least 3 decimal places.

The input / output elements that are lists may be either whitespace-/comma-separated strings or arrays/lists/etc. For input, if your solution is a function, you may additionally take a first argument of *n* and additional arguments as *mx* (this applies to command line arguments as well).

Here is a visual representation of `n=1`:

```
1 4 5 7 10
__/ | | |
L avg(1,4) = 2.5
    | | |
\___/ | |
  L avg(1,4,5) = 3.333
      | |
  \___/ |
    L avg(4,5,7) = 5.333
        |
    \___/
      L avg(5,7,10) = 7.333

      \___
        L avg(7,10) = 8.5

Final output: 2.5 3.333 5.333 7.333 8.5

```

Since this is , the shortest code in bytes wins.

Test cases (*these were done manually; please notify me of any errors*):

```
In                             Out
----------------------------------------------------------------------
n=1, m=12 6 3 9                9 7 6 6
n=1, m=1 4 5 7 10              2.5 3.333 5.333 7.333 8.5
n=1, m=1 3 3 7 4 2 4 2         2 2.333 4.333 4.666 4.333 3.333 2.666 3
n=2, m=1 3 5 9 10 14 15 16 23  3 4.5 5.6 8.2 10.6 12.8 15.6 17 18
n=3, m=1 1 1 1 1 1 1 1         1 1 1 1 1 1 1 1
n=3, m=1 2 3 4 5 6 7 8         2.5 3 3.5 4 5 5.5 6 6.5

```

# Answer
# Pyth, 20 bytes

```
m.O:vzeS,0-dQh+dQUvz

```

Test suite

Pretty straightforward, just slice the appropriate section out of the list, then average.
> 1 votes

# Answer
# MATL, ~~30~~ ~~28~~ ~~26~~ 24 bytes

```
2*1+:g2X53$X+1Mbgbb3$X+/

```

Tested on Matlab and on Octave. Uses current version (9.1.0) of the language/compiler.

Input is: first the number controlling window length, then the array with format `[1 4 5 7 10]`.

*EDIT (20 May 2016): Try it online! The code in the link has `X+` replaced by `Y+` to conform to version 18.0.0 of the language.*

### Example

```
>> matl
 > 2*1+:g2X53$X+1Mbgbb3$X+/
 >
> 1
> [1 4 5 7 10]
2.5 3.333333333333333 5.333333333333333 7.333333333333333               8.5

>> matl
 > 2*1+:g2X53$X+1Mbgbb3$X+/
 >
> 2
> [1 3 5 9 10 14 15 16 23]
3               4.5               5.6 8.199999999999999              10.6               2.8              15.6        17                18

```

### Explanation

The equivalent Matlab code would be

```
n = 1; %// first input: number controlling window length
x = [1 4 5 7 10]; %// second input: array
result = conv(x,ones(1,2*n+1),'same')./conv(ones(size(x)),ones(1,2*n+1),'same');

```

The MATL code makes use of the recently added features of implicit input and automatic function-input clipboard:

```
2*1+          % get implicit input "n". Multipliy by 2 and add 1
:g            % create a vector of 2*n+1 "true" values (will act as "one" values)
2X5           % 'same' string literal
3$X+          % get implicit input "x" (array). Convolution using three inputs
1M            % push all three inputs from last function
bgbb          % convert first input to "true" values. Will act as "one" values
3$X+          % convolution using three inputs
/             % divide element-wise. Implicitly print

```
> 3 votes

# Answer
# APL (Dyalog Unicode), ~~18~~ 16 bytes

```
{⍵⌹×⍵}⌺(1+2×⎕)⊢⎕

```

Try it online!

@ngn suggested an average trick using, and I took it further to shorten it by two bytes, eliminating the need of .

Since the input is positive integers and the Stencil's padding gives only zeros, it suffices to average the nonzero entries.

The default trick for average using  (matrix divide/solve linear equation/least squares fit) is "divide a vector by its all ones version", which solves the least squares of something like this:

```
1x = 1
1x = 3
1x = 5

```

where the least square solution is exactly the average. I modified it to ignore the zeros when calculating the average:

```
{⍵⌹×⍵}  Input: a vector of positive integers, possibly with zeros to ignore
   ×⍵   Signum of each number, which gives 1 for positives and 0 for zeros
 ⍵⌹     Matrix-divide the original vector by the above,
        which gives the system of equations, e.g. for 0 0 1 3 5:
0x = 0
0x = 0
1x = 1
1x = 3
1x = 5
        Then the zero-coefficient equations are ignored in the least squares,
        which leads to the average of only positive entries.

```

Alternatively, Extended can do the same in 15 bytes, exploiting the fact that the left argument is always zero (as opposed to the "padding size" in regular Dyalog version):

# APL (Dyalog Extended), 15 bytes

```
(⊢⌹<)⌺(1+2×⎕)⊢⎕

```

Try it online!

---

# APL (Dyalog Unicode) 18.0, 18 bytes

```
(+/÷≢)⍤↓⌺(1+2×⎕)⊢⎕

```

Try an equivalent 17.x program online!

What a fitting challenge for Dyalog APL's Stencil .

The Stencil operator extracts the moving window over an array exactly as described in the challenge. Specifically, for odd window size, the window is centered over each element, padded with zeros outside the array as necessary, and then the amount of padding is given as an extra information so that single Drop  will remove such padding. The rest is just specifying the right window size and taking average `(+/÷≢)` over each subarray.

### Illustration

```
Input array: 12 6 3 9
Input n: 1
Window size: 3 (1+2×n)
Arguments to left operand of Stencil:
  Left  Right
  1     0  12 6  ⍝ Zero padding 1 unit to the left; 1↓ drops 0 from the front
  0     12 6  3
  0     6  3  9
  ¯1    3  9  0  ⍝ Zero padding 1 unit to the right ¯1↓ drops 0 from the back

```

---

Matrix multiplication approach is also possible, but it is not short enough:

# APL (Dyalog Unicode), 21 bytes

```
{÷/⍵1+.×¨⊂⍺≥|∘.-⍨⍳≢⍵}

```

Try it online!

### How it works

```
{÷/⍵1+.×¨⊂⍺≥|∘.-⍨⍳≢⍵}  ⍝ Left:n, Right:m
                 ⍳≢⍵   ⍝ 1..length of m
             ∘.-⍨      ⍝ Self outer product by difference
          ⍺≥|          ⍝ 1 if abs diff is at most n, 0 otherwise
                       ⍝ which gives the band matrix
   ⍵1+.×¨⊂  ⍝ Inner product with m and all-one vector
 ÷/         ⍝ Divide left by right

```
> 3 votes

# Answer
## CJam, ~~31~~ 30 bytes

```
ri_S*l~1$++\2*)ew{S-_:+\,d/}%`

```

Input format is `n [m1 m2 ... mx]`.

Run all test cases. (Automatically converts the test suite to the required input format.)

This works by pre- and append `n` spaces, then taking all substrings of length `2n+1`, and removing the spaces again before computing their means.
> 2 votes

# Answer
# Julia, 57 bytes

```
f(n,m)=[mean(m[max(1,i-n):min(end,i+1)])for i=1:endof(m)]

```

This is a function that accepts two integers and returns an array of floats.

The approach here is very straightforward. We construct a new array by taking the mean of sections of the input array, truncating at the front and back.
> 1 votes

# Answer
## Pyth, 22 bytes

```
.OMsM.:++J*]YKE]MQJhyK

```

Explanation:

```
.OM sM .: +               Means of flattens of sublists of length 2K+1 of
            + J *
                  ] Y     J is E copies of [].
                  K E     Save E to a variable to use it later.
               ]MQ        the input
            J             Put J on both sides of ]MQ.
          h y K           2K+1

```

Try it here.
> 0 votes

# Answer
# JavaScript (ES6), 104

Running total / running sample size. In Javascript, reading a value outside the bounds of an array gives undefined, that can be converted to 0 using ~~

```
(l,n,p=0)=>l.map((v,i)=>(p+=~l[i-n-1]-~l[i+n])/(n+1+Math.min(n,l.length-1-i,i)),l.map((v,i)=>p+=i<n&&v))

```

**Ungolfed**

```
(l, n) => {
    p = 0;
    for (i = 0; i < n; i++) p += v;
    r = [];
    for (i = 0; i < l.length; i++) {
        p += (l[i + n] || 0) - (i > n ? l[i - n - 1] : 0);
        r.push(p / Math.min(n, l.length - i - 1, i);
    }
    return r;
}

```

**Test**

```
f=(n,l,p=0)=>l.map((v,i)=>(p+=~l[i-n-1]-~l[i+n])/(n+1+Math.min(n,l.length-1-i,i)),l.map((v,i)=>p+=i<n&&v))

console.log=x=>O.textContent+=x+'\n';

;[
  [1,[12,6,3,9],[9,7,6,6]]
, [1,[1,4,5,7,10],[2.5,3.333,5.333,7.333,8.5]]
, [1,[1,3,3,7,4,2,4,2],[2,2.333,4.333,4.667,4.333,3.333,2.667,3]]
, [2,[1,3,5,9,10,14,15,16,23],[3,4.5,5.6,8.2,10.6,12.8,15.6,17,18]]
, [3,[1,1,1,1,1,1,1,1],[1,1,1,1,1,1,1,1]]
, [3,[1,2,3,4,5,6,7,8],[2.5,3,3.5,4,5,5.5,6,6.5]]
].forEach(t=>{
  var n=t[0],l=t[1],x=t[2],r=f(n,l)
  // verify (limited to 3 decimals)
  var ok = r.every((v,i)=>v.toFixed(3)==x[i].toFixed(3))

  console.log((ok?'OK   ':'Fail ')+n+' '+l+' -> '+r+' ('+x+')')
})
```

```
<pre id=O></pre>
```
> 0 votes

# Answer
## Haskell, ~~97~~ 95 bytes

```
import Data.List
n#x|t<-2*n+1=[sum a/sum(1<$a)|a<-take t<$>take t(inits x)++tails x,length a>n]

```

Usage example: `2 # [1,3,5,9,10,14,15,16,23]` -\> `[3.0,4.5,5.6,8.2,10.6,12.8,15.6,17.0,18.0]`.

How it works:

```
t<-2*n+1                      -- assign t to the maximum number of elements of a
                              -- of sublist
     take t(inits x)          -- build the sublists from t elements of the inits
                ++tails x     -- of the input and the tails of the input,
                              -- e.g. x=[1,2,3,4], t=3:
                              -- [[],[1],[1,2]] ++ [[1,2,3,4],[2,3,4],[3,4],[4],[]]
  a<-take t<$>                -- take at most t elements from every sublist
                ,length a>n   -- keep those with a minimum length of n+1
sum a/sum(1<$a)               -- calculate average, "sum(1<$a)" is the length of a

```
> 0 votes

# Answer
# JavaScript (ES6), 82 bytes

**code:**

```
F=(n,a)=>a.map((e,i)=>(s=a.slice(i<n?0:i-n,i+n+1))&&s.reduce((l,c)=>l+c)/s.length)

```

**test:**

```
F=(n,a)=>a.map((e,i)=>(s=a.slice(i<n?0:i-n,i+n+1))&&s.reduce((l,c)=>l+c)/s.length)

document.write('<pre>' +
  [
    [1, [12, 6, 3, 9], [9, 7, 6, 6] ],
    [1, [1, 4, 5, 7, 10], [2.5, 3.333, 5.333, 7.333, 8.5] ],
    [1, [1, 3, 3, 7, 4, 2, 4, 2], [2, 2.333, 4.333, 4.667, 4.333, 3.333, 2.667, 3] ],
    [2, [1, 3, 5, 9, 10, 14, 15, 16, 23], [3, 4.5, 5.6, 8.2, 10.6, 12.8, 15.6, 17, 18] ],
    [3, [1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1] ],
    [3, [1, 2, 3, 4, 5, 6, 7, 8], [2.5, 3, 3.5, 4, 5, 5.5, 6, 6.5] ]
  ].map(t => {
    var [n, m, e] = t;
    var r = F(n, m);
    // verify to precision of 3 decimals
    var test = r.every((v, i) => v.toPrecision(3) === e[i].toPrecision(3));

    return 'F(' + n + ', [' + m + '])\t' + (test ? 'Pass' : 'Fail') +
      '\n\t{' + r + '} ' + (test ? '=' : '≠') + ' {' + e + '}';
  }).join('\n\n') +
  '</pre>');
```
> 0 votes

# Answer
## 05AB1E, 30 bytes

```
ćU˜©ε®NX@iX·>£ÅAV®¦©YëN>X+£ÅA}

```

Input is: `[n,[list_m]]` Output is: \`\[list\_of\_avgs\]

**Explanation**

```
ćU˜©ε®NX@iX·>£ÅAV®¦©YëN>X+£ÅA}
ć                                  Head extract (get n)
 U                                 Save in variable X
  ˜                                Flat the list
   ©                               Save the list in register c
    ε                        }     Map
     ®                             Get the list from register c
      NX@                          Is the iteration greater than or equal to n
         i                         if true
                     ë             if false
          X·>                      push (n*2)+1
             £                     extract (n*2)+1 elements from head
              ÅA                   Arithmetic mean
                V                  Save the result in variable Y
                 ®                 Push the list from register c again
                  ¦                remove head (first element)
                   ©               save the new list in register c
                    Y              get variable Y (to apply on map returned value)
                      N>X+         push i+1+n  (i=iteration index, loop count)
                          £        extract i+1+n elements from head
                           ÅA      Arithmetic mean

```

Try it here :)
> 0 votes

# Answer
# Wolfram Language (Mathematica), 46 bytes

```
Mean/@N@Partition[#2,UpTo[2#+1],1,{-#-1,#+1}]&

```

Try it online!
> 0 votes

---
Tags: code-golf, arithmetic
---