title: Alphabetize Integers

text:
# Question
Title: Alphabetize Integers
# Alphabetize Integers

For a given set of numbers, put them in alphabetical order when they are spelled out (i.e. 1: one, 2: two, 90: ninety, 19: nineteen). Your code should work for the range `[-999999, 999999]`. Output must have a delimiter between numbers. A space will work, as will a space and a comma as shown in the examples below. Input can be an array of integers, a string of delimited numbers, or however you see fit. All integers are assumed to be unique.

Numbers are not hyphenated for the purposes of this challenge and spaces are alphabetized before any other characters. Negative numbers are assumed to be expressed by using the word `minus`. For example, `four` would precede `four thousand` and the number `-40` would be sorted using the string `minus forty`. Assume all numbers will be solely comprised of number words and no conjunctions (e.g. use `two thousand forty two` instead of `two thousand and forty two`).

---

## Test Cases

**Single Digit Integers:**

Input:

```
1, 2, 3, 4, 5

```

Output:

```
5, 4, 1, 3, 2

```

**Multiple Digit Integers:**

Input:

```
-1002, 5, 435012, 4, 23, 81, 82

```

Output:

```
81, 82, 5, 4, 435012, -1002, 23

```

**Spaces between words, no hyphens, commas or "and":**

Input:

```
6, 16, 60, 64, 600, 6000, 60000, 60004, 60008, 60204, 60804

```

Output:

```
6, 600, 6000, 16, 60, 64, 60000, 60008, 60804, 60004, 60204

```

Remember, this is , so the code with the fewest bytes wins. No loopholes allowed!

# Answer
# JavaScript (ES6), ~~189~~ ~~179~~ 186 bytes

```
let f =

a=>a.sort((x,y)=>!x-!y||(X=q(x),Y=q(y),X>Y)-(X<Y),q=n=>n<0?"L"+q(-n):n>999?q(n/1e3)+"Z"+q(n%1e3):n>99?q(n/100)+"K"+q(n%100):n>19?"  cYHFVSCO"[n/10|0]+q(n%10):"0PdaIGTQAMWDbXJEURBN"[n|0])

let g = a => console.log(`[${f(a)}]`)

g([1,2,3,4,5])
g([-1002,5,435012,4,23,81,82])
g([0,1000,1100])
```

```
<input id=I value="1 2 3 4 5"><button onclick="g(I.value.match(/\d+/g)||[])">Run</button>
```

The basic idea is to convert each input number into a short string that's in the correct lexographical position compared to all other number-string pairs. Here's the dictionary used: (Don't run the snippet; it's just used to hide the long list.)

```
A eight
B eighteen
C eighty
D eleven
E fifteen
F fifty
G five
H forty
I four
J fourteen
K hundred
L minus
M nine
N nineteen
O ninety
P one
Q seven
R seventeen
S seventy
T six
U sixteen
V sixty
W ten
X thirteen
Y thirty
Z thousand
a three
b twelve
c twenty
d two
```

This creates a very concise way of mapping each number to its lexographically correct position. That's what the recursive `q` function does:

```
q(-X)        => "L" + q(X)
q(XYYY)      => q(X) + "Z" + q(YYY)
q(XYY)       => q(X) + "K" + q(YY)
q(XY >= 20)` => "  cYHFVSCO"[X] + q(Y)
q(X)         => "0PdaIGTQAMWDbXJEURBN"[X]

```

The `0` at the beginning of the string is to ensure that e.g. 100 (`one hundred`, converted to `PK0`) is sorted before `101` (`one hundred one`, converted to `PKP`). This creates an odd scenario where 0 (`zero`) is sorted to the front of the array, so to get around this, in the sorting function we first sort any zeroes to the right with `!x-!y||(...`.
> 5 votes

# Answer
## Inform 7, ~~214~~ ~~201~~ 118 bytes

Inform 7 is an absolutely terrible language for golfing, so I wanted to give it a chance here.

Indentation should use tab (`\t`) characters, but HTML doesn't like those. Conversely, Inform doesn't like spaces for indentation, so you'll have to replace the spaces with tabs if you copy-paste the code from here to test it. Or just copy-paste from the Markdown source instead.

Golfed:

```
To X:
    repeat through Table 1:
        now Q entry is "[R entry in words]";
    sort Table 1 in Q order;
    say "[R in Table 1]".

```

Input should be an Inform table, like so (with `\t` between the columns):

```
Table 1
R (number)  Q (text)
-1002
5
435012
4
23
81
82

```

Output:

> 81, 82, 5, 4, 435012, -1002, 23

This function runs through the table once, adding a textual representation of each number in a new column. Then it sorts the table rows according to the text column; in Inform, strings are sorted lexicographically. Finally, it prints out the original column in the new order. Conveniently, Inform 7's "crude but sometimes useful" format for printing out table columns turns out to be comma separated, exactly as requested.

Ungolfed, with boilerplate showing how to call the function:

```
To print the numbers in alphabetical order:
    repeat through the Table of Sortable Numbers:
        now the name entry is "[the index entry in words]";
    sort the Table of Sortable Numbers in name order;
    say "[the index column in the Table of Sortable Numbers]".

Table of Sortable Numbers
index (number)  name (text)
-1002
5
435012
4
23
81
82

There is a room.
When play begins: print the numbers in alphabetical order.

```
> 11 votes

# Answer
# Mathematica, 67 bytes

```
SortBy[#,#~IntegerName~"Words"~StringReplace~{","->"","-"->""}&]&

```

Unnamed function taking a list of integers as its argument and returning a list of integers as its value. `#~IntegerName~"Words"` is a built-in that changes an integer to its name in English. `IntegerName` sometimes has commas and hyphens in its output, so the `StringReplace` call gets rid of those. (Sadly the hyphen is actually the 3-byte character, 8208, in UTF-8.) Then `SortBy` sorts the original list alphabetically according to the value of the modified integer name.

A nice coincidence: `IntegerName` uses `negative` instead of `minus` in its output—but no word appearing in the names of any of the allowed numbers is alphabetically between those two words, so no replacement is needed!

(Hat tip to ngenisis for reminding me of `Sortby`.)
> 4 votes

# Answer
# Bash + GNU utils + bsdgames, 52

* 4 bytes saved thanks to @izabera.

```
sed 's/.*/echo `echo &|number`:&/e'|sort|sed s/.*://

```

I/O is newline-delimited lines.

* The first sed expression replaces each numerical number with a shell command that outputs the word form of the number (as given by the bsdgames `number` utility), followed by a `:` then the numerical form of the number.
* This is then `sort`ed.
* Then the second `sed` strips leading characters up to and including the `:`, leaving the numerical form sorted as required.

`number` correctly handles "minus", and its output is close enough to the specificed format that the `sort` works as required. It does output "fourty-four" instead of "fourty four", but this shouldn't matter from the sorting perspective.

The bsdgames package may need installation:

```
sudo apt-get install bsdgames

```

The `sed` and `sort` utilities are almost certainly already in your distro.
> 4 votes

# Answer
# Python + inflect, ~~97~~ ~~91~~ 89 bytes

```
from inflect import*
a={x:engine().number_to_words(x)for x in words}
sorted(a,key=a.get)

```

Used the `inflect` library to transform the `words` array of integers into their phonetic/string representation. Stored into a dictionary of k/v pairs where the keys were the numeric representation and values were the string representation. Returned the list of keys as sorted by values.

EDIT: Saved 5 and 3 bytes, thanks to ETHproductions and Alex.S!
> 1 votes

# Answer
# Mathematica, 30 bytes

The answer below outputs a pure function which will take a list of integers as an input and sort them by their alphabetic name. Just what the doctor ordered ;)

```
SortBy[#~IntegerName~"Words"&]

```

Here is the ungolfed version:

```
SortBy[IntegerName[#, "Words"]&]

```

And here is an example usage:

```
SortBy[#~IntegerName~"Words"&][{0,1,2,3,4,5,6,7,8,9,10}]

```

Which could also be written as

```
SortBy[#~IntegerName~"Words"&]@{0,1,2,3,4,5,6,7,8,9,10}

```

They produce identical outputs - in mathematica, `f[x]` is equivilant to `f@x`.

```
Outputs: {8, 5, 4, 9, 1, 7, 6, 10, 3, 2}

```

There is a much longer answer that another user posted in Mathematica. That answer tries to correct for some small differences between the way mathematica alphebatizes numbers to better conform to the way the OP stated numbers should be alphebatized, however the things they correct for don't affect sorting order, and my answer outputs identically to theirs:

```
MyF = SortBy[#~IntegerName~"Words"&];
TheirF = SortBy[#, #~IntegerName~"Words"~ StringReplace~{"," -> "", "-" -> ""} &] &;
MyF[Range[-999999, 999999]] == TheirF[Range[-999999, 999999]]
(*Outputs True*)

```
> 0 votes

# Answer
# Common Lisp, 113 bytes

No external libraries necessary.

```
(print(mapcar #'cdr(sort(loop for i in x collect(cons(format()"~r"i)i))(lambda(y z)(string-lessp(car y)(car z))))))

```

Output if `x` is `'(1 2 3 4 5)`:

```
(5 4 1 3 2)

```
> 0 votes

---
Tags: code-golf, sorting, natural-language, integer
---


title: Natural Pi #2 - River

text:
# Question
Title: Natural Pi #2 - River
## Goal

Given an string with a train of hashes, calculate its total length and divide by the distance from start to finish.

## Simulation

**What are we simulating?** According to this paper, the ratio of the length of a river to the distance between start and end is approximately Pi! (This may have been disproved empirically, but I could find the data and for this challenge we'll assume it is true).

**How are we simulating this?**

* Take a string input of whitespace and hashes
* Each hash will have two others adjacent to it
    + With the exception of the first and last hash which will have only 1
* Each character lies on a lattice point `(x, y)`
* `x` is the character's index in its line
    + eg `c` is the 4th character in `0123c567`
* `y` is the character's line number
    + eg `c` is on the 3rd line:

```
      0line
      1line
      2line
      3c...

```
* Sum the distances between adjacent hashes, call it `S`
* Take the distance between the first and last hashes, call it `D`
* Return `S/D`

## Specification

* **Input**
    + Flexible, take input in any of the standard ways (eg function parameter,STDIN) and in any standard format (eg String, Binary)
* **Output**
    + Flexible, give output in any of the standard ways (eg return, print)
    + White space, trailing and leading white space is acceptable
    + Accuracy, please provide at least 4 decimal places of accuracy (ie `3.1416`)
* **Scoring**
    + Shortest code wins!

## Test Cases

These are my approximations of the rivers. My approximations might be poor or these my be poor sample of the river population. Also, I did this calculations by hand; I could have miss calculated.

Yellow River

```
        ### ####
       #   #    #
       #       #          #
       #       #         #
       #       #        #
      #         #      #
##   #          # #####
  ##  #          #
    ##

```

```
1.6519

```

Nile River

```
         #
         #
          #
           #
           #
          #
         #
        #
        #  #
        # # #
         #  #
            #
          ##
         #
         #
        #
        #
       #
       #
       #
       #
   #  #
  # ##
  #
  #
   #
    #
     #
     #
      #
     #
    #
     #
      #

```

```
1.5498

```

Mississippi River

```
 ###
#   #
     #
     #
    #
   #
  #
  #
  #
   #
    #
     #
      #
       #
        #
        #
        #
         #
          #
           #
          #
       ###
      #
       #
      #
     #
    #
    #
    #
    #
     #
      ##
        #
        #
         ##
           ##
             ##
               #
              #
             #
            #
           #
          #
         #
        #
        #
        #
        #
        #
       #
      #
     #
      #
       #
        ####
            #
             #

```

```
1.5257

```

### TL;DR

These challenges are simulations of algorithms that only require nature and your brain (and maybe some re-usable resources) to approximate Pi. If you really need Pi during the zombie apocalypse, these methods don't waste ammo! There are nine challenges total.

# Answer
> 6 votes
# MATL, ~~48~~ ~~44~~ ~~42~~ ~~37~~ 33 bytes

*Quite a few bytes saved thanks to rahnema1's idea (Octave answer) of collapsing two convolutions into one*

```
t5BQ4B&vX^Z+*ssGt3Y6Z+1=*&fdwdYy/

```

This takes the input as a binary matrix, with `;` as row separator. `1` corresponds to hash and `0` to space.

Try it online! Or verify all test cases.

Here's a format converter that takes inputs as 2D char arrays (again, with `;` as separator) and produces string representations of the corresponding binary matrices.

### Explanation

This was fun! The code uses ~~three~~ two 2D-convolutions, each for a different purpose:

1. To detect vertical and horizontal neighbours, which contribute a distance of `1`, the required mask would be

```
0 1 0
1 0 1
0 1 0

```

But we only want each *pair* of neighbours to be detected once. So we take half the mask (and the last row of zeros can be removed):

```
0 1 0
1 0 0

```

Similarly, to detect diagonal neighbours, which contribute a distance of `sqrt(2)`, the mask would be

```
1 0 1
0 0 0
1 0 1

```

but by the same reasoning as above it becomes

```
1 0 1
0 0 0

```

If this mask is multiplied by `sqrt(2)` and added to the first, the two convolutions can be replaced by one convolution with the combined mask

```
sqrt(2) 1  sqrt(2)
1       0        0

```
2. Start and end points are, by definition, the points with only one neighbour. To detect them we convolve with

```
1 1 1
1 0 1
1 1 1

```

and see which points give `1` as result.

To produce the combined mask of item 1 it's shorter to generate its square and then take the square root. The mask in item 2 is a predefined literal.

```
t     % Take input matrix implicitly. Duplicate
5B    % 5 in binary: [1 0 1]
Q     % Add 1; [2 1 2]
4B    % 4 in binary: [1 0 0]
&v    % Concatenate vertically
X^    % Square root of each entry
Z+    % 2D convolution, maintaining size
*     % Multiply, to only keep results corresponding to 1 in the input
ss    % Sum of all matrix entries. This gives total distance
Gt    % Push input again. Duplicate
3Y6   % Predefined literal. This gives third mask
Z+    % 2D convolution, maintaining size
1=    % Values different than 1 are set to 0
*     % Multiply, to only keep results corresponding to 1 in the input
&f    % Push array of row indices and array of column indices of nonzeros
d     % Difference. This is the horizontal difference between start and end
wd    % Swap, difference. This is the vertical difference between start and end
Yy    % Hypothenuse. This gives total distance in straight line
/     % Divide. Display implicitly

```

# Answer
> 4 votes
# Octave, 99 bytes

```
@(a)sum((c=conv2(a,[s=[q=2^.5 1 q];1 0 1;s],'same').*a)(:))/2/{[x y]=find(c<2&c>0),pdist([x y])}{2}

```

nearly same method as MATL answer but here kernel of convolutions is

```
1.41 ,  1  , 1.41
1    ,  0  , 1
1.41 ,  1  , 1.41

```

that `sqrt(2) =1.41` is for diagonal neighbors and `1` is for direct neighbors so when we sum values of the result over the river we get twice the real distance.
**ungolfed version**:

```
a=logical([...
0 0 0 0 0 0 0 0 1 1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 1 0 0
0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0
1 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 1 1 1 1 0 0 0 0
0 0 1 1 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ]);
sq = sqrt(2);
kernel = [...
    sq ,  1  , sq
    1  ,  0  , 1
    sq ,  1  , sq];
%2D convolution
c=conv2(a,kernel,'same').*a;
#river length
river_length = sum(c (:))/2;
#find start and end points
[x y]=find(c<2&c>0);
# distance between start and end points
dis = pdist([x y]);
result = river_length/ dis

```

Try (paste) it on Octave Online

# Answer
> 2 votes
# JavaScript (ES6), 178

Input as a string with newlines *in rectangular form* : each line padded with spaces to the same length (as in the examples)

```
r=>r.replace(/#/g,(c,i)=>([d=r.search`
`,-d,++d,-d,++d,-d,1,-1].map((d,j)=>r[i+d]==c&&(--n,s+=j&2?1:Math.SQRT2),n=1),n||(v=w,w=i)),w=s=0)&&s/2/Math.hypot(v%--d-w%d,~(v/d)-~(w/d))

```

*Less golfed*

```
r=>(
  r.replace(/#/g, // exec the following for each '#' in the string
    (c,i) => // c: current char (=#), i: current position
    ( // check in 8 directions
      // note: d starts as the offset to next row, prev x position
      // and is incremented up to offset to next row, succ x position
      // note 2: there are 2 diagonal offsets, then 2 orthogonal offsets
      //         then other 2 diagonal, then 2 more orthogonal
      [d=r.search`\n`,-d, ++d,-d, ++d,-d, 1,-1].map( // for each offset
        (d,j) => // d: current offset, j: array position (0 to 7)
        r[i+d] == c && // if find a '#' at current offset ...
          (
            --n, // decrement n to check for 2 neighbors or just 1
            s += j & 2 ? 1 : Math.SQRT2 // add the right distance to s
          ),
      n = 1), // n starts at 1, will be -1 if 2 neighbors found, else 0
      // if n==0 we have found a start or end position, record it in v and w
      n || (v=w, w=i)
   ),
  w=s=0), // init s and w, no need to init v
  // at the end
  // d is the length of a line + 1
  // s is twice the total length of the river
  // v and w can be used to find the x,y position of start and end
  s/2/Math.hypot(v%--d-w%d,~(v/d)-~(w/d))
)

```

**Test**

```
F=
r=>r.replace(/#/g,(c,i)=>([d=r.search`\n`,-d,++d,-d,++d,-d,1,-1].map((d,j)=>r[i+d]==c&&(--n,s+=j&2?1:Math.SQRT2),n=1),n||(v=w,w=i)),w=s=0)&&s/2/Math.hypot(v%--d-w%d,~(v/d)-~(w/d))

Yellow=`        ### ####
       #   #    #
       #       #          #
       #       #         #
       #       #        #
      #         #      #
##   #          # #####
  ##  #          #
    ##                     `

Nile=`         #
         #
          #
           #
           #
          #
         #
        #
        #  #
        # # #
         #  #
            #
          ##
         #
         #
        #
        #
       #
       #
       #
       #
   #  #
  # ##
  #
  #
   #
    #
     #
     #
      #
     #
    #
     #
      #        `

Missi=` ###
#   #
     #
     #
    #
   #
  #
  #
  #
   #
    #
     #
      #
       #
        #
        #
        #
         #
          #
           #
          #
       ###
      #
       #
      #
     #
    #
    #
    #
    #
     #
      ##
        #
        #
         ##
           ##
             ##
               #
              #
             #
            #
           #
          #
         #
        #
        #
        #
        #
        #
       #
      #
     #
      #
       #
        ####
            #
             #  `
console.log('Yellow River',F(Yellow))
console.log('Nile River',F(Nile))
console.log('Mississippi River',F(Missi))
```

---
Tags: code-golf, string, math, pi, approximation
---


title: Plant a binary forest!

text:
# Question
Title: Plant a binary forest!
Inspired by A014486.

**Challenge**

Given an integer input in base 10, construct a representation for the binary forest corresponding to the input. Representations include, but are not limited to, nested arrays and strings.

**How?**

Convert the input to binary. `1`s represent branches, and `0`s represent leaves.

To make this easier to understand, let's use `834` (1101000010 in binary) as an example.

---

We start with the first digit. The first digit is a `1`, so we draw branches:

```

\ /
 1

```

or as an array, `{{1}}`

---

The next digit is `1`, so we draw more branches (we go from left to right):

```
\ /
 1
  \   /
    1

```

or as an array, `{{1, {1}}}`

---

The next digit is `0`, so we place a leaf:

```
0
 \ /
  1
   \   /
     1

```

or as an array, `{{1, {1, 0}}}`

---

The next digit is a `1`, so we place a branch:

```
     \ /
0     1
 \   /
   1
      \     /
         1

```

or as an array, `{{1, {1, 0, {1}}}}`

---

Repeating the process, we obtain the following tree after the 8th digit:

```
    0   0
     \ /
0     1
 \   /
   1           0
      \     /
         1

```

or as an array, `{{1, {1, 0, {1, 0, 0}}, 0}}`

---

For the remaining digits, we draw more trees:

The 9th digit is a `0`, so we place a leaf (aww, it's a young shoot!)

```
    0   0
     \ /
0     1
 \   /
   1           0
      \     /
         1         0

```

or as an array, `{{1, {1, 0, {1, 0, 0}}, 0}, 0}`

---

When we use all the digits, we end up with this:

```
    0   0
     \ /
0     1
 \   /
   1           0       0
      \     /           \ /
         1         0     1

```

or as an array, `{{1, {1, 0, {1, 0, 0}}, 0}, 0, {1, 0}}`

---

That looks weird, so we pad a zero to complete the tree:

```
    0   0
     \ /
0     1
 \   /
   1           0       0   0
      \     /           \ /
         1         0     1

```

or as an array, `{{1, {1, 0, {1, 0, 0}}, 0}, 0, {1, 0, 0}}`

Note that the flattening the array yields the original number in binary, but with a padded zero.

**Criteria**

* The output must clearly show the separation of the trees and branches (if it is not a nested array, please explain your output format).
* Extracting all digits from the output must be identical to the binary representation of the input (with the padded zero(s) from the above process).

**Test cases**

The output may differ as long as it meets the criteria.

```
0    -> {0}
1    -> {{1, 0, 0}}
44   -> {{1, 0, {1, {1, 0, 0}, 0}}}
63   -> {{1, {1, {1, {1, {1, {1, 0, 0}, 0}, 0}, 0}, 0}, 0}}
404  -> {{1, {1, 0, 0}, {1, 0, {1, 0, 0}}}}
1337 -> {{1, 0, {1, 0, 0}}, {1, {1, {1, 0, 0}, {1, 0, 0}}, 0}}

```

**Scoring**

This is , so lowest bytes wins!

# Answer
# JavaScript (ES6), ~~96~~ ~~89~~ ~~80~~ ~~79~~ ~~74~~ 73 bytes

```
f=($,_=~Math.log2($))=>0>_?[(g=f=>$&1<<~_++&&[1,g(),g()])(),...f($,_)]:[]
```

```
<input type="number" value="1337" oninput="document.querySelector('#x').innerHTML=JSON.stringify(f(+this.value))"/><br/><pre id="x"></pre>
```

Defines a function `f` that returns a nested array. The HTML code is just for testing.
> 2 votes

# Answer
# Befunge, ~~138~~ ~~117~~ 104 bytes

```
p&1v
%2:_v#:/2p9p00+1:g00
3\9g<>$\:!v!:<
9g!v ^,"}"_1-\1-:
"0"_2\"1{",,:|:,
`#@_\:#v_"}",>$\:8
,"0":-1<^

```

Try it online!

**Explanation**

Line 1 reads a number from stdin, and line 2 converts that number to a binary sequence which it stores in the playfield on line 10. Lines 3 to 5 then iterate over those binary digits, outputting the appropriate tree representation as each digit is processed. The Befunge stack is used to keep track of the depth into the tree and how much leaf space is left at each level so we know when to create a new branch. Lines 6 and 7 handle the final `0` padding to fill up any empty leaves.

In order to golf this as much as possible, I removed the commas from the output as well as the extraneous outer braces. This still hasn't beat the Mathematica solution, but it's been fun trying.

If you want to see what it looked like with the original verbose output format, I saved an earlier version of the code here (131 bytes).
> 9 votes

# Answer
# Mathematica, ~~167~~ 161 bytes

```
b=Append;a=If[#&@@#>0,a[Rest@#~b~0,a[#,#3[#,{1,#4,#2},##5]&,#3,#2,##4]&,#2,##3],
#2[Rest@#~b~0,0,##3]]&;a[#~IntegerDigits~2,If[c=#3~b~#2;Tr@#>0,a[#,#0,c],c]&,
{}]&

```

Anonymous function. Takes a number as input, and returns an arbitrarily nested list of numbers as output. Line breaks added for clarity. Uses some mechanism involving continuations, but I'm too tired to think about it any longer.
> 4 votes

# Answer
# Mathematica, ~~115~~ ~~109~~ ~~108~~ ~~104~~ 98 bytes

```
(i=#~IntegerDigits~2;f:=Switch[If[i=={},0,i={##2};#]&@@i,0,0,1,f~1~f];NestWhileList[f&,f,i!={}&])&

```

Generates error messages that can safely be ignored. Outputs a binary forest. It's slightly different from the sample output because `1` is a `Head`, not the first element of a list. (e.g. `1[0, 0]` instead of `{1, 0, 0}`)

**Error-free version (104 bytes)**

```
(i=#~IntegerDigits~2;f:=Switch[If[i=={},i={0}];(i={##2};#)&@@i,0,0,1,f~1~f];NestWhileList[f&,f,i!={}&])&

```

**Explanation**

```
i=#~IntegerDigits~2;

```

Convert input to a base-2 list. Store it in `i`.

```
f:=

```

`SetDelay` `f` the following (evaluated whenever `f` is called):

```
Switch[If[i=={},0,i={##2};#]&@@i,0,0,1,f~1~f]

```

`Switch` statement.

First, if `i` is empty, output `0`. If not, output the first element of `i`and drop it from the list. Use the output as the control variable.

If the control variable is `0`, output `0`. If it is `1`, output `1[f, f]` (recursive).

```
NestWhileList[f&,f,i!={}&]

```

While `i` is not empty, keep calling `f`. Output the result, wrapped with `List`.

**Example**

```
(i=#~IntegerDigits~2;f:=Switch[If[i=={},0,i={##2};#]&@@i,0,0,1,f~1~f];NestWhileList[f&,f,i!={}&])&[1337]

```

> `{1[0, 1[0, 0]], 1[1[1[0, 0], 1[0, 0]], 0]}`

**Alternative solution (120 bytes)**

Identical to my 104 byte solution but converts the output into the format given in the question.

```
(i=#~IntegerDigits~2;f:=Switch[If[i=={},i={0}];(i={##2};#)&@@i,0,0,1,f~1~f];NestWhileList[f&,f,i!={}&]//.1[a__]:>{1,a})&

```
> 4 votes

# Answer
# Python 2, ~~133~~ ~~118~~ 117 bytes

Partially recursive, partially iterative. I tried using an integer, but the tree starts with the most significant bits, so I don't think it's worth it.

```
def t():global b;a=b[:1];b=b[1:];return a and'0'<a and[1,t(),t()]or 0
b=bin(input())[2:]
L=[]
while b:L+=t(),
print L

```

**Try it online**
> 2 votes

# Answer
# Java 8, 367 bytes

Golfed:

```
class f{static String r="";static int p=0;static void g(char[]s,int k){if(p>=s.length||s[p]=='0'){r+="0";p++;return;}else{r+="{1";p++;g(s,k+1);g(s,k+1);r+="}";}if(k==0&&p<s.length)g(s,0);}public static void main(String[]a){java.util.Scanner q=new java.util.Scanner(System.in);r+="{";g(Integer.toBinaryString(q.nextInt()).toCharArray(),0);r+="}";System.out.print(r);}}

```

Ungolfed:

```
class f{
    static String r="";
    static int p=0;
    static void g(char[]s,int k){
        // if there's empty space in last tree or current character is a 0
        if(p>=s.length || s[p]=='0'){
            r+="0";
            p++;
            return;
        }
        // if current character is a 1
        else{
            r+="{1";
            p++;
            // left branch
            g(s,k+1);
            // right branch
            g(s,k+1);
            r+="}";
        }
        // if they're still trees that can be added
        if(k==0 && p<s.length)g(s,0);
    }
    public static void main(String[]a){
        java.util.Scanner q=new java.util.Scanner(System.in);
        r+="{";
        g(Integer.toBinaryString(q.nextInt()).toCharArray(),0);
        r+="}";
        System.out.print(r);
    }
}

```
> 1 votes

# Answer
# DUP, 84 bytes (82 chars)

```
0[`48-$1_>][\10*+]#%1b:[$1>][2/b;1+b:]#[['{,1.b;1-b:FF'},][0.b;1-b:]?]⇒F[b;0>][F]#

```

For golfing reasons, I got rid of the outer curly braces and the commas because they are not necessary for reconstructing the trees.

Example outputs:

```
0      → 0
1      → {100}
44     → {10{1{100}0}}
63     → {1{1{1{1{1{100}0}0}0}0}0}
404    → {1{100}{10{100}}}
1023   → {1{1{1{1{1{1{1{1{1{100}0}0}0}0}0}0}0}0}0}
1024   → {100}00000000
1025   → {100}0000000{100}
1026   → {100}000000{100}
1027   → {100}000000{1{100}0}
1028   → {100}00000{100}
1337   → {10{100}}{1{1{100}{100}}0}
4274937288 → {1{1{1{1{1{1{10{1{100}{1{1{100}{10{1{1{10{1{1{100}{100}}0}}0}0}}}0}}}0}0}0}0}0}0}
4294967297 → {100}00000000000000000000000000000{100}

```

Explanation:

```
0[`48-$1_>][\10*+]#           While loop to read in the characters and convert them into a
                              base-10 integer.
0                             Push 0 (temporary value)
 [`48-$0>]       #            While input character-48 (digit)>-1
          [     ]
           \                      Swap top values
            10                    Push 10
              *                   Multiply (temporary value by 10)
               +                  Add to input value
%                                 Pop stack (EOL)
1b:                           Variable b=1 (bit count)
[$1>][2/b;1+b:]#              While loop to convert the number to base-2 digits on the
                              data stack, MSB on top. Each iteration increments bit count b.
[$1>]          #              While (DUP>1)
     [        ]#
      2                           Push 2
       /                          MOD/DIV (pushes both mod and div on the stack)
        b;1+b:                    Fetch b, increment, store b

[['{,1.b;1-b:FF'},][0.b;1-b:]?]⇒F
[                             ]⇒F     Define operator F:
                                      pop top stack value
 [                ]          ?        if value != 0:
  '{,1.                                   print '{1'
       b;1-b:                             fetch b, decrement b, store b
             F                            execute operator F
              F                           execute operator F again
               '},                        print '}'
                   [        ]?        if value == 0:
                    0.                    print '0'
                      b;1-b:              fetch b, decrement b, store b
[b;0>][F]#
[b;0>]   #                            While (fetch b, b>0==true)
      [F]#                                execute operator F

```

Try it out with the online Javascript DUP interpreter on quirkster.com or clone my GitHub repository of my DUP interpreter written in Julia.
> 1 votes

---
Tags: code-golf, binary-tree
---


title: Maths Metagolf Mania!

text:
# Question
Title: Maths Metagolf Mania!
## Mathemania Specs:

Every piece of Mathemania code starts off with the number `2`. From the `2`, you can do the following operations:

* `e`: Exponentiation. This command's default is squaring the number.
* `f`: Factorial. This command's default is using the single factorial on the number (`using f on 2 = 2! = 2`).
* `r`: Root. This command's default is square-rooting the number.
* `c`: Ceiling function.
* `l`: Floor function.

To generate a number in Mathemania, you must string together these commands, which are performed left-to-right on the number `2`.

## Examples:

```
ef = (2^2)! = 4! = 24
rl = floor(sqrt(2)) = floor(1.4...) = 1
er = sqrt(2^2) = sqrt(4) = 2
efrrc = ceil(sqrt(sqrt((2^2)!)))
      = ceil(sqrt(sqrt(24)))
      = ceil(sqrt(4.89...))
      = ceil(2.21...)
      = 3

```

The `e`, `f` and `r` commands can be altered by extra Mathemania commands (which also start off with `2` as its "base" number) to generate different exponentiations, factorials and roots by placing brackets after the altered function and placing the Mathemania commands inside it.

For example, to cube a number instead of squaring it, you can put the command for `3` after `e` like so:

```
e(efrrc) -> cube a number, "efrrc" = 3

```

*NOTE: for our purpose, the factorial command (`f`) start off with `2` as a single factorial. So if you do `f(efrrc)`, that will get evaluated to a double factorial, not a triple factorial.*

*For `n`-factorials (e.g. double factorials = 2-factorial, triple factorial = 3-factorial etc.), the base number is multiplied by the number that is `n` less than it, and `n` less than that, and so on until the final number cannot be subtracted by `n` without becoming `0` or negative.*

*For example:*

```
7!! = 7 * 5 * 3 * 1 = 105 (repeatedly subtract 2, 1 is the last term as
                           1 - 2 = -1, which is negative)
9!!! = 9 * 6 * 3 = 162 (repeatedly subtract 3, 3 is the last term as
                        3 - 3 = 0, which is 0)

```

*For more information, see here.*

You can insert it anywhere, and it will get treated by Mathemania as a single function:

```
e(efrrc)rc = ceil(sqrt(2^3))
           = ceil(2.82...)
           = 3

```

You're also allowed to nest these inside one another:

```
e(e(e)) = e(4th power)
        = (2^4)th power
        = 16th power

```

For an interpreter of Mathemania code, click here (cheers, @BradGilbertb2gills!)

## Task:

Your task is to create a program that, when given a positive integer `n` as input, generates a Mathemania program that when executed, returns `n`.

However, the Mathemania programs that you generate must be as small (golfed) as possible, and your final score is determined by the sum of the number of bytes in the generated Mathemania programs of the sample, which are the integers `10,000` to `10,100`. The lowest score wins.

## Rules and specs:

* Your program must output a valid Mathemania program for any positive integer, but only the numbers between `10,000` and `10,100` will be tested.
* You are not allowed to output Mathemania programs that do not result in an integer. If you do so, your program is disqualified.
* For the commands `e`, `f` and `r`, the Mathemania code inside those functions (e.g. `e(efrrc)`, where the `efrrc` is the code inside the function) must evaluate to a positive integer above `2`. If your program doesn't follow this rule, it is disqualified as well.
* Your program must return a Mathemania program for any one of the 101 test integers in at most 30 minutes on a modern laptop.
* Your program must return the same solution for any integer every time it is run. For example, when a program is given an input `5` and it outputs `efrc`, it must output that every time the input `5` is given.
* You may not hard-code any solutions for any positive integer.
* In order to fully maximise golfing potential in your output, your program should be able to handle arbitrarily large integers. It is not a requirement, though good luck if your language doesn't support this.

This is , so lowest score wins!

# Answer
# Python 3.5, Score of ??

As of now I don't have the output for all 101 inputs, but once I run the program for all the test cases I will update with my score.

```
from math import *

memoized = {}
same = {}

def _(mathmania, n):
    memoized[n] = mathmania
    return mathmania

def is_prime(n):
    if n == 2:
        return True
    if n % 2 == 0 or n <= 1:
        return False
    for divisor in range(3, int(sqrt(n)) + 1, 2):
        if n % divisor == 0:
            return False
    return True

def pair_key(pair):
    low, high = pair
    diff = high - low
    if diff == 0:
        return 100
    low_done, high_done, diff_done = low in memoized, high in memoized, diff in memoized
    if high_done and memoized[high] == None or low_done and memoized[low] == None:
        return -1
    return (high_done + diff_done + (diff + 1 == low)) * 33 + low / high

def major_pairs(n):
    for i in range(n, int(sqrt(n)), -1):
        d = n / i
        if i - d < d - 1:
            break
        if d == int(d):
            yield (int(d), i)

def fact_key(pair):
    i, f = pair
    if i in memoized:
        if memoized[i] == None:
            return -1
        return 1
    return i / f

def near_fact(n, level):
    s = 4
    if n in same:
        s = same[n]
    for i in range(s, n ** 2 ** level):
        f = factorial(i)
        if f > (n - 1) ** 2 ** level:
            if f < (n + 1) ** 2 ** level:
                same[n] = i
                yield (i, f)
            else:
                return

def generate_mathmania(n):
    if n in memoized and memoized[n] != None:
        return memoized[n]
    memoized[n] = None
    binx = log(n, 2)
    if binx == int(binx):
        if binx == 2:
            return _("e", n)
        if binx == 1:
            return _("er", n)
        if binx == 0:
            return _("rl", n)
        return _("e(" + generate_mathmania(int(binx)) + ")", n)
    sq = sqrt(n)
    if sq == int(sq):
        return _(generate_mathmania(int(sq)) + "e", n)
    low, high = max(major_pairs(n), key=pair_key)
    if pair_key((low, high)) == -1:
        level = 1
        while True:
            try:
                i, f = max(near_fact(n, level), key=fact_key)
            except:
                level += 1
                continue
            if fact_key((i, f)) == -1:
                return _(generate_mathmania((n - 1) ** 2 + 1) + "rc", n)
            if f == n ** 2 ** level:
                return _(generate_mathmania(i) + "f" + "r" * level, n)
            if f < n ** 2 ** level:
                return _(generate_mathmania(i) + "f" + "r" * level + "c", n)
            return _(generate_mathmania(i) + "f" + "r" * level + "l", n)
    if low != 1:
        if low == high:
            return _(generate_mathmania(low) + "e", n)
        if high - low == 1:
            return _(generate_mathmania(high) + "f", n)
        return _(generate_mathmania(high) + "f(" + generate_mathmania(high - low + 1) + ")", n)
    good = None
    for i in range(n ** 2 - 1, (n - 1) ** 2, -1):
        if i in memoized:
            return _(generate_mathmania(i) + "rc", n)
        if not is_prime(i):
            good = i
    if good:
        return _(generate_mathmania(good) + "rc", n)
    for i in range((n + 1) ** 2 - 1, n ** 2, -1):
        if i in memoized:
            return _(generate_mathmania(i) + "rl", n)
        if not is_prime(i):
            good = i
    if good:
        return _(generate_mathmania(good) + "rl", n)
    return _(generate_mathmania((n - 1) ** 2 + 1), n)

```

Additionally, I was unable to verify the outputs of some of the test cases I tried due to sheer number size, and at that point @BradGilbertb2gills's online interpreter times out. Hopefully all the outputs work.
> 1 votes

---
Tags: math, metagolf
---


title: Golf a Compute interpreter

text:
# Question
Title: Golf a Compute interpreter
# Introduction

Compute is a ~~esoteric~~ joke language.

From the esolangs entry:

> Compute has no required syntax and has the power to solve any and all problems. It is smart enough to interpret any human language (English, Spanish, Latin, etc), any programming language (C++, Java, brainfuck, etc), or any kind of data you can think of. **The only downfall is that there is absolutely no I/O.**

### Some example programs

```
Hello World

```

A basic Hello World program

```
What is love?

```

Determines was love is (baby don't hurt me).

```
When will we ever graduate?

```

Determines the exact date of this site to get out of beta.

# The Challenge

Your task is to write a full Compute interpreter. This sounds pretty hard, but keep in mind that Compute has absolutly no I/O. So your interpreter will just sleep one second for every **line** in the input program and output `\n\nDone.` after this (this is the only exception to the no I/O thing).

You can find the official interpreter at the bottom of this site.
*Note that the official interpreter pauses one second for every character in the given source code. To avoid long waiting times while testing your interpreter with meaningful questions **we stay with lines** in this challenge.*

# Rules

* The input might contain multiple lines seperated by a `\n`. There will always be at least one line.
* Unlike the official implementation you don't have to take a file as input. You can take the Compute program in any form of input you want.
* The only output allowed is `\n\nDone.`. A trailing newline is allowed.
* Function or full program allowed.
* Default rules for input/output.
* Standard loopholes apply.
* This is , so lowest byte-count wins. Tiebreaker is earlier submission.

# Answer
> 5 votes
# 05AB1E, ~~16~~ ~~15~~ ~~14~~ 13 bytes

Code:

```
[Ig>#w’

D€µ.

```

Explanation:

```
[        # Starts an infinite loop
 I       # Input string
  g>     # Length + 1
    #    # If equal to 1, break out of the loop
     w   # Wait 1 second

```

This part is equivalent to `"\n\nDone."`:

```
      ’  # Push "\n\nDone." on top of the stack

D€µ.     # The compressed string is ended implicitly
         # Implicit, print top of the stack

```

Try it online!

Uses **CP-1252** encoding.

# Answer
> 4 votes
## JavaScript Shell REPL, 38 bytes

As a function that accepts the program as a string argument and returns the result:

```
s=>sleep(s.split`
`.length)||`

Done.`

```

29 bytes if the function can accept its input in the form of an array of lines, or if it should sleep 1 second per character:

```
s=>sleep(s.length)||`

Done.`

```

34 bytes if it should also be more like a program and explicitly print Done:

```
s=>sleep(s.length)||print`

Done.`

```

This works for me in the standalone Spidermonkey interpreter.

# Answer
> 4 votes
## Javascript ES6, ~~46~~ 45 bytes

```
a=>setTimeout(x=>alert`

Done.`,a.length*1e3)

```

Thanks to ӍѲꝆΛҐӍΛПҒЦꝆ for saving one byte

Assumes an array as input.

As both ӍѲꝆΛҐӍΛПҒЦꝆ and edc65 have pointed out you can write the following, but it won't save any bytes:

```
a=>setTimeout("alert`\n\nDone`",a.length*1e3)

```

# Answer
> 4 votes
# Bash + coreutils, 28

```
sleep `wc -l`
echo "

Done."

```

Sleeps 1 second for every line. Use `wc -c` instead for every byte, or `wc -m` instead for every character.

# Answer
> 4 votes
# Oration, 117 bytes

```
I need time!
To iterate, input().
Inhale.
Now sleep(1).
Backtracking.
Boring,
boring.
Listen!
Capture Done.
Carry on!

```

Let's explain this. First, this transpiles to:

```
import time
while input():
    time.sleep(1)
print("\n")
print("\n")
print("Done")

```

Still confused? Let's put it like this:

```
I need time!

```

Imports the module `time`.

```
To iterate, input().

```

This is a while loop whose condition is `input()`.

```
Inhale.

```

Our program needs to breathe now, and `inhale`, whilst less healthy, is golfier.

```
Now sleep(1).

```

`Now` take the most recent module imported and appends `.sleep(1)` to it.

```
Backtracking.

```

Let's exit the while loop.

```
Boring,
boring.

```

Prints two newlines.

```
Listen!

```

Begins capturing a string.

```
Capture Done.

```

Adds `Done.` to the captured string.

```
Carry on!

```

Finishes capturing string.

# Answer
> 3 votes
# Pyth, ~~15~~ 14 bytes

```
.dcl.z1b"Done.

```

(You can try it online, but there's really no point in doing so.)

# Answer
> 2 votes
# MATL, 17 bytes

```
10c'Done.'`jt?1Y.

```

A trailing empty line (followed by newline) is used to mark end of input. This is needed in MATL because input is interactive and each input ends with a newline.

**Try it online!**

```
10c           % push newline character
'Done.'       % push string
`             % do...while
  j           % input string
  t           % duplicate
  ?           % if non-empty
    1Y.       % pause for 1 second
              % loop condition is the current string. If non-empty: next iteration
              % If empty: exit loop and print stack contents. There are two strings
              % and a newline is printed after each, so the desired output is obtained

```

# Answer
> 2 votes
## Perl, 21 + 1 = 22 bytes

```
sleep 1}{$_="\n\nDone."

```

Requires the `-p` flag:

```
$ perl -pe'sleep 1}{$_="\n\nDone."' <<< $'a\nb\nc'

Done.

```

# Answer
> 2 votes
## Python 3, 58 bytes

```
import time
while input():time.sleep(1)
print("\n\nDone.")

```

# Answer
> 2 votes
# QBasic, 54 bytes

```
LINE INPUT x$
IF x$=""GOTO 1
SLEEP 1
RUN
1?
?
?"Done."

```

Takes the program line by line from user input, terminated by a blank line. Abides by the letter of the law, though possibly not the spirit, by pausing 1 second after reading each line. (The specification doesn't technically say that the pauses all have to come after the input is completed.) If this is considered too shady, here's a 64-byte version that pauses after the whole program has been input:

```
DO
LINE INPUT x$
IF x$=""GOTO 1
t=t+1
LOOP
1SLEEP t
?
?
?"Done."

```

---

Bonus version with file I/O (87 bytes):

```
INPUT f$
OPEN f$FOR INPUT AS 1
1LINE INPUT #1,x$
SLEEP 1
IF 0=EOF(1)GOTO 1
?
?
?"Done."

```

# Answer
> 1 votes
## Ruby, 32 bytes

```
$<.map{sleep 1}
puts"\n\nDone."

```

Reads from stdin.

# Answer
> 1 votes
# OCaml, 61 bytes

```
fun a->List.iter(fun _->Unix.sleep 1)a;print_string"\n\nDone"

```

Assumes the input is a list.

# Answer
> 0 votes
# Jelly, 12 bytes

```
ỴLœS@⁷⁷“ẋḲp»

```

Try it online!

Note: Please **do not** suggest putting the `⁷⁷` in the compressed string, it will make it longer (`“¡OÑL[Ṁ»`).

Explanation:

```
ỴLœS@⁷⁷“ẋḲp» Main link. Arguments: z.
ỴL           The number of lines in z. (x)
     ⁷       Newline ("\n") (y)
  œS@        After sleeping for x seconds, return y.
      ⁷      Newline ("\n")
       “ẋḲp» Compressed string ("Done.")

```

# Answer
> 0 votes
## awk, 34 bytes

```
END{print"\nDone."|"cat;sleep "NR}

```

As there is no I/O and the final outcome is inevitable, the `Done.` part is outputed right in the beginning.

```
$ awk 'END{print"\nDone."|"cat;sleep "NR}' file

```

Only way to sleep in awk is to use system `sleep`. Shortest way to invocate it is to `print|"sleep "NR` and we might as well abuse that useless `print`.

---
Tags: code-golf, interpreter
---


title: Are you lost yet?

text:
# Question
Title: Are you lost yet?
Your task is to implement integer sequence A130826:

> **an** is the smallest positive integer such that **an \- n** is an entire multiple of **3** and twice the number of divisors of **(an \- n) / 3** gives the **n**th term in the first differences of the sequence produced by the Flavius Josephus sieve.

Lost yet? Well, it's actually quite easy.

The Flavius Josephus sieve defines an integer sequence as follows.

1. Start with the sequence of positive integers and set **k = 2**.
2. Remove every **k**th integer of the sequence, starting with the **k**th.
3. Increment **k** and go back to step 2.

**fn** is the **n**th integer (1-indexed) that never gets removed.

If – as usual – **σ0(k)** denotes the number of positive divisors of the integer **k**, we can define **an** as the smallest positive integer such that **0((an \- n) / 3) = fn+1 \- fn**.

### Challenge

Write a program or function that takes a positive integer **n** as input and prints or returns **an**.

Standard rules apply. May the shortest code win!

### Worked examples

If we remove every second element of the positive integers, we are left with

```
 1  3  5  7  9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 ...

```

After removing every third element of the remainder, we get

```
 1  3  7  9 13 15 19 21 25 27 31 33 37 39 ...

```

Now, removing every fourth, then fifth, then sixth element gets us

```
 1  3  7 13 15 19 25 27 31 37 39 ...
 1  3  7 13 19 25 27 31 39 ...
 1  3  7 13 19 27 31 39 ...
 1  3  7 13 19 27 39 ...

```

The last row shows the terms **f1** to **f7**.

The differences of the consecutive elements of the these terms are

```
 2  4  6  6  8 12

```

Dividing these forward differences by **2**, we get

```
 1  2  3  3  4  6

```

These are the target divisor counts.

* **4** is the first integer **k** such that **σ0((k - 1) / 3) = 1**. In fact, **σ0(1) = 1**.
* **8** is the first integer **k** such that **σ0((k - 2) / 3) = 2**. In fact, **σ0(2) = 2**.
* **15** is the first integer **k** such that **σ0((k - 3) / 3) = 3**. In fact, **σ0(4) = 3**.
* **16** is the first integer **k** such that **σ0((k - 4) / 3) = 3**. In fact, **σ0(4) = 3**.
* **23** is the first integer **k** such that **σ0((k - 5) / 3) = 4**. In fact, **σ0(6) = 4**.
* **42** is the first integer **k** such that **σ0((k - 6) / 3) = 6**. In fact, **σ0(12) = 6**.

### Test cases

```
   n     a(n)

   1        4
   2        8
   3       15
   4       16
   5       23
   6       42
   7       55
   8      200
   9       81
  10       46
  11      119
  12      192
  13      205
  14   196622
  15    12303
  16       88
  17      449
  18      558
  19      127
  20     1748
  21   786453
  22       58
  23     2183
  24     3096
  25     1105
  26   786458
  27 12582939
  28      568
  29     2189
  30     2730

```

# Answer
# Jelly, ~~30~~ ~~29~~ ~~27~~ 25 bytes

*Saved 2 bytes thanks to @Dennis notifying me about `Æd`, and another 2 bytes for combining the two chains.*

```
RUð÷‘Ċ×µ/
‘Ç_ÇH0Æd=¥1#×3+

```

Try it online!

This was probably the most fun I've ever had with Jelly. I started from the second line, which calculates **fn** from **n** using the formula on OEIS, and is quite beautiful.

### Explanation

```
RUð÷‘Ċ×µ/    Helper link to calculate F<sub>n</sub>. Argument: n
R            Get numbers [1..n]
 U           Reverse
        /    Reduce by "round up to next 2 multiples":
   ÷           Divide by the next number
    ‘          Increment to skip a multiple
     Ċ         Ceil (round up)
      ×        Multiply by the next number

‘Ç_ÇH0Æd=¥1#×3+    Main link. Argument: n
‘                  Increment n
 Ç                 Calculate F<sub>n+1</sub>
   Ç               Calculate F<sub>n</sub>
  _                Subtract
    H              Divide by 2
     0    1#       Starting from 0, find the first candidate for (a<sub>n</sub>-n)/3
                   that satisfies...
      Æd             σ<sub>0</sub>((a<sub>n</sub>-n)/3)
        =            = (F<sub>n+1</sub>-F<sub>n</sub>)/2
            ×3     Multiply by 3 to turn (a<sub>n</sub>-n)/3 into a<sub>n</sub>-n
              +    Add n to turn a<sub>n</sub>-n into a<sub>n</sub>

```
> 7 votes

# Answer
# Python 2, ~~121~~ ~~119~~ 118 bytes

```
n=input();r=range(1,4**n);d=s,=r*1,
for k in r:del s[k::k+1];d+=sum(k%j<1for j in r)*2,
print d.index(s[n]-s[n-1])*3+n

```

Run time should be roughly **O(16n)** with **O(4n)** memory usage. Replacing `4**n` with `5<<n` – which I *think* is sufficient – would improve this dramatically, but I'm not convinced that it works for arbitrarily large values of **n**.

Try it online!

### Asymptotic behavior and upper bounds of an

Define **bn** as **(an \- n)/3**, i.e., the smallest positive integer **k** such that **σ0(k) = ½(fn+1 \- fn)**.

As noted on the OEIS page, **fn ~ ¼πn2**, so **fn+1 \- fn ~ ¼π(n + 1)2 \- ¼πn2 = ¼π(2n + 1) ~ ½πn**.

This way, **½(fn+1 \- fn) ~ ¼πn**. If the actual number is a prime **p**, the smallest positive integer with **p** divisors is **2p-1**, so **bn** can be approximated by **2cn**, where **cn ~ ¼πn**.

Therefore **bn \< 4n** will hold for sufficiently large **n**, and given that **2¼πn \< 2n \<\< (2n)2 = 4n**, I'm confident there are no counterexamples.

### How it works

```
n=input();r=range(1,4**n);d=s,=r*1,

```

This sets up a few references for our iterative process.

* **n** is the user input: a positive integer.
* **r** is the list **\[1, ..., 4n \- 1\]**.
* **s** is a copy of **r**.

Repeating the list once with `r*1` creates a shallow copy, so modifying **s** won't modify **r**.
* **d** is initialized as the tuple **(s)**.

This first value is not important. All others will hold divisor counts of positive integers.

```
for k in r:del s[k::k+1];d+=sum(k%j<1for j in r)*2,

```

For each integer **k** from **1** to **4n \- 1**, we do the following.

* `del s[k::k+1]` takes every **(k + 1)**th integer in **s** – starting with the **(k + 1)**th – and deletes that slice from **s**.

This is a straightforward way of storing an initial interval of the Flavius Josephus sieve in **s**. It will compute much more than the required **n + 1** initial terms, but using a single `for` loop to update both **s** and **d** saves some bytes.
* `d+=sum(k%j<1for j in r)*2,` counts how many elements of **r** divide **k** evenly and appends **0(k)** to **d**.

Since **d** was initialized as a singleton tuple, **0(k)** is stored at index **k**.

```
print d.index(s[n]-s[n-1])*3+n

```

This finds the first index of **fn+1 \- fn** in **d**, which is the smallest **k** such that **0(k) = fn+1 \- fn**, then computes **an** as **3k + 1** and prints the result.
> 3 votes

# Answer
# Java 8, 336, 305, 303, 287, 283 279 bytes

57 bytes removed thanks to Kritixi Lithos

Golfed

```
class f{static int g(int s,int N){return s<1?N+1:g(s-1,N+N/s);}static int h(int k){int u=0,t=1,i;for(;u!=(g(k,k)-g(k,k-1))/2;t++)for(i=1,u=0;i<=t;)if(t%i++<1)u++;return 3*t-3+k;}public static void main(String[]a){System.out.print(h(new java.util.Scanner(System.in).nextInt()));}}

```

Ungolfed

```
class f {
    static int g(int s,int N){return s < 1 ? N + 1 : g(s - 1, N + N / s);}

    static int h(int k) {
        int u = 0, t = 1, i;
        // get the first number with v divisors
        while(u != (g(k, k) - g(k, k - 1))/2){
            u = 0;
            for (i = 1; i <= t; i++)
                if (t % i < 1) u++;
            t++;
        }
        // 3*(t-1)+k = 3*t+k-3
        return 3 * t + k - 3;
    }

    public static void main(String[] a) {
        System.out.print(h(new java.util.Scanner(System.in).nextInt()));
    }
}

```
> 2 votes

# Answer
# Mathematica, ~~130~~ ~~116~~ ~~106~~ 103 bytes

```
3Catch@Do[f=#2⌈#/#2+1⌉&~Fold~Reverse@Range@#&;If[Tr[2+0Divisors@k]==f[#+1]-f@#,Throw@k],{k,∞}]+#&

```

or

```
3Catch@Do[f=#2⌈#/#2+1⌉&~Fold~Reverse@Range@#&;If[2DivisorSum[k,1&]==f[#+1]-f@#,Throw@k],{k,∞}]+#&

```

Ended up being almost identical to @Pietu1998's Jelly code...

**Explanation**

```
Catch@

```

`Catch` whatever is `Throw`-ed (thrown).

```
Do[ ... ,{k,∞}]

```

Infinite loop; `k` starts from `1` and increments every iteration.

```
f= ...

```

Assign `f`:

```
Reverse@Range@#

```

Find `{1, 2, ... , n}`. Reverse it.

```
#2⌈#/#2+1⌉&

```

A function that outputs ceil(n1/n2 + 1) * n2

```
f= ... ~Fold~ ... &

```

Assign `f` a function that recursively applies the above function to the list from two steps above, using each output as the first input and each element of the list as the second input. The initial "output" (first input) is the first element of the list.

```
Tr[2+0Divisors@k]==f[#+1]-f@#

```

Check whether twice the number of divisors of `k` is equal to f(n + 1) - f(n).

```
If[ ... ,Throw@k]

```

If the condition is `True`, `Throw` the value of `k`. If not, continue looping.

```
3 ... +#&

```

Multiply the output by 3 and add n.

**130 byte version**

```
Catch@Do[s=#+1;a=k-#;If[3∣a&&2DivisorSigma[0,a/3]==Differences[Nest[i=1;Drop[#,++i;;;;i]&,Range[s^2],s]][[#]],Throw@k],{k,∞}]&

```
> 1 votes

# Answer
# 05AB1E, ~~35~~ ~~34~~ 39 bytes

```
1Qi4ë[N3*¹+NÑg·¹D>‚vyy<LRvy/>îy*}}‚Æ(Q#

```

It looks awful, so is runtime performance. It takes several seconds for input that yield small values. Don't try numbers like 14; it will eventually find the result but it would take ages.

## Explanation

It works as 2 sequentially called programs. The first one computes **Fn+1 \- Fn** and the second one determines **an** based on its definition, using a bruteforce approach.

**Fn+1 \- Fn** is evaluated for each iteration even though it is loop invariant. It makes the code time inefficient, but it makes the code shorter.

Try it online!
> 1 votes

# Answer
# Perl 6, ~~154~~ ~~149~~ ~~136~~ 107 bytes

```
->\n{n+3*first ->\o{([-] ->\m{m??&?BLOCK(m-1).rotor(m+0=>1).flat!!1..*}(n)[n,n-1])/2==grep o%%*,1..o},^Inf}

```

Ungolfed:

```
-> \n {                    # Anonymous sub taking argument n
  n + 3 * first -> \o {    # n plus thrice the first integer satisfying:
    (                      #
      [-]                  #
      -> \m {              # Compute nth sieve iteration:
        m                  # If m is nonzero,
          ?? &?BLOCK(m-1).rotor(m+0=>1).flat # then recurse and remove every (m+1)-th element;
          !! 1..*          # the base case is all of the positive integers
      }                    #
      (n)                  # Get the nth sieve
      [n,n-1]              # Get the difference between the nth and (n-1)th elements (via the [-] reduction operator above)
    ) / 2                  # and divide by 2;
    ==                     # We want the number that equals
    grep o %% *, 1..o      # the number of divisors of o.
  }
  ,^Inf
}

```
> 1 votes

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


# Question
Title: Smallest positive integer which is coprime to the last two predecessors and has not yet appeared; a(1)=1, a(2)=2
# Definition

* Two integers are **coprime** if they share no positive common divisors other than `1`.
* `a(1) = 1`
* `a(2) = 2`
* `a(n)` is the smallest positive integer which is coprime to the `a(n-1)` and `a(n-2)` and has not yet appeared, for integer `n >= 3`.

# Task

* Given positive integer `n`, output/print `a(n)`.

# Example

* `a(11) = 6` because `6` is coprime with the last two predecessors (namely, `11` and `13`) and `6` has not appeared before.

# Notes

* Note that the sequence is not ascending, meaning that an element can be smaller than its predecessor.

# Specs

* You **must** use 1-indexed.

# Testcases

```
n      a(n)
1      1
2      2
3      3
4      5
5      4
6      7
7      9
8      8
9      11
10     13
11     6
12     17
13     19
14     10
15     21
16     23
17     16
18     15
19     29
20     14
100    139
1000   1355
10000  13387
100000 133361

```

# Scoring

* Since coprime means that the two numbers share only one divisor (`1`), and `1` is a small number, your code should be as small as possible in terms of byte-count.

# References

# Answer
# Python 3.5, ~~160~~ ~~141~~ ~~126~~ ~~124~~ ~~121~~ 109 bytes

This is a simple implementation of the sequence's definition. Golfing suggestions welcome.

**Edit:** -17 bytes thanks to Leaky Nun. -9 bytes thanks to Peter Taylor. -6 bytes thanks to Sp3000 and switching to Python 3.5.

```
import math;f=lambda n,r=[2,1],c=3:n<2and r[1]or(c in r)+math.gcd(c,r[0]*r[1])<2and f(n-1,[c]+r)or f(n,r,c+1)

```

**Ungolfing:**

```
import math
def f(n, r=[2,1], c=3):
    if n<2:
        return r[1]
    elif (c in r) + math.gcd(c,r[0]*r[1]) < 2:
        return f(n-1, [c]+r)
    else:
        return f(n, r, c+1)

```
> 5 votes

# Answer
# MATL, ~~28~~ 27 bytes

```
2:i:"`@ym1MTF_)Zdqa+}@h]]G)

```

The code is slow, but gives the correct result.

Try it online! Or verify the first ten cases.

A small modification of the code produces a plot of the sequence:

```
2:i:"`@ym1MTF_)Zdqa+}@h]]G:)XG

```

See it as ASCII art, or with graphical output in the offline compiler:

### Explanation

```
2:         % Push [1 2] to initiallize the sequence
i:         % Input n. Push [1 2 ... n]
"          % For loop: repeat n times
  `        %   Do while loop
    @      %     Push iteration index, starting at 1. This is the candidate number
           %     to extend the sequence
    y      %     Duplicate vector containing the sequence so far
    m      %     Is member? Gives true if the candidate is in the sequence
    1M     %     Push candidate and vector again
    TF_)   %     Get last two elements of the vector
    Zd     %     GCD between the candidate and those two elements. Produces a
           %     two-element vector
    qa     %     True if any of the two results exceeds 1, meaning
           %     the candidate is not coprime with the latest two sequence values
    +      %     Add. This corresponds to logical "or" of the two conditions, namely
           %     whether the candidate is member of the sequence so far, and
           %     whether it is not coprime with the latest two. In either case
           %     the do...while must continue with a next iteration, to try a new
           %     candidate. Else the loop is exited, and the current candidate
           %     is the new value of the sequence
  }        %   Finally (execute when the loop is exited)
    @h     %     Push current candidate and concatenate to the sequence vector
  ]        %   End do...while
]          % End for
G)         % Get n-th value of the sequence. Implicitly display

```
> 2 votes

# Answer
# C, 185 bytes

```
G(a,b){return a%b?G(b,a%b):b;}
i,j,k;f(n){int a[n+2];for(i=0;i++<n;){a[i]=i<3?i:0;for(j=2;!a[i];++j){for(k=i;--k;){if(a[k]==j)++j,k=i;}a[G(a[i-1],j)*G(a[i-2],j)<2?i:0]=j;}}return a[n];}

```
> 1 votes

# Answer
# Actually, ~~38~~ ~~37~~ ~~35~~ ~~33~~ ~~31~~ 30 bytes

This is a simple implementation of the function definition. Golfing suggestions welcome. Try it online!

**Edit:** -3 bytes thanks to Leaky Nun.

```
2R#╗,;`1";2±╜tπg@╜í+Y"£╓╖`nD╜E

```

**Ungolfing:**

```
2R#╗    Push [1,2] and store it in register 0
,;      Take input and duplicate
`1      Start function, push 1
  "       Start string
  ;       Duplicate i
  2±╜t    Push (list in register 0)[-2:]
  πg      gcd(i, product of list[-2:])
  @╜í     Rotate the gcd and bring up i, check for i in list (0-based, -1 if not found)
  +Y      Add the gcd and the index, negate (1 if coprime and not found in list, else 0)
  "£      End string, turn into a function
╓       Push first (1) values where f(x) is truthy, starting with f(0)
╖`      Append result to the list in register 0, end function
n       Run function (input) times
D╜E     Return (final list)[n-1]

```
> 1 votes

# Answer
## Haskell, ~~81~~ 73 bytes

```
c l@(m:n:_)=m:c([x|x<-[1..],gcd(m*n)x<2,all(/=x)l]!!0:l)
((0:1:c[2,1])!!)

```

Usage example: `((0:1:c[2,1])!!) 12`-\> `17`.

Build the list of all `a(n)`, starting with `0` to fix the 1-based index and `1` and followed by `c[2,1]`. `c` takes the head of it's argument list `l` followed by a recursive call with then next number that fits (co-prime, not seen before) added in front of `l`. Pick the `n`th element of this list.
> 0 votes

# Answer
# R, 141 bytes

```
 f=Vectorize(function(n)ifelse(n>3,{c=3;a=f(n-1);b=f(n-2);d=f(4:n-3);while(!c%%which(!a%%1:a)[-1]||!c%%which(!b%%1:b)[-1]||c%in%d)c=c+1;c},n))

```

ungolfed

```
f=Vectorize( function(n)     #build a recursive function. Vectorize allows
    if(n>3) {                #the function to be called on vectors.
        c=3                  #Tests size. Builds some frequent variables.
        a=f(n-1)
        b=f(n-2)
        d=f(4:n-3)           #Should really golf this out, but its horribly slow.
        while(!c%%which(!a%%1:a)[-1]||!c%%which(!b%%1:b)[-1]||c%in%d)
              c=c+1          #If we are coprime and not already seen. add.
        c
     } else n)               #First three are 1,2,3.

```
> 0 votes

# Answer
# Mathematica, ~~97~~ 90 bytes

```
a@1=1;a@2=2;a@n_:=SelectFirst[Range[2n],GCD[a[n-1]a[n-2],#]<2&&!MemberQ[a/@Range[n-1],#]&]

```

Based on ~~my conjecture that~~ `a(n) < 2n` for all `n`.

To get a faster run, add `a@n=` after the original `:=` so that the function doesn't need to recalculate previous values.

*Saved 7 bytes thanks to Sherlock9* (if `gcd(a,b)=1` then `gcd(ab,m) = gcd(a,m)*gcd(b,m)`)
> 0 votes

# Answer
# Pyth, 23 bytes

```
eu+Gf&-TGq1iT*F>2G1tQ]1

```

Test suite

A fairly straightforward implementation, but with some nice golfing tricks.

```
eu+Gf&-TGq1iT*F>2G1tQ]1
 u                 tQ]1    Apply the following function input - 1 times,
                           where G is the current state (List of values so far)
  +G                       Add to G
    f             1        The first number, counting up from 1
      -TG                  That has not been seen so far
     &                     And where
               >2G         The most recent two numbers
             *F            Multiplied together
           iT              Gcd with the current number being checked
         q1                Equals 1
e                          Output the final element of the list.

```
> 0 votes

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


title: Merry Golfmas, Everyone!

text:
# Question
Title: Merry Golfmas, Everyone!
It's Christmas everybody, and here's a code-golf challenge to celebrate. You need to make a program to print out a present. Specifically, the words "Merry Christmas". BUT, there is a catch: this program must only work if it is the 25th of December. If the code is run on any other day, then the program should crash.

This is Code-Golf, so the answer with the least amount of bytes wins.

Merry Christmas!

# Answer
## Pyke, 21 bytes

```
.dↄґ6C65h*325q/Al

```

Try it here!

```
     C65h*        -   multiply the day by the (current month + 1)
          325q    -  ^ == 325
    6         /   - 6 / ^
.dↄґ              -  load "merry christmas"
               Al - ^.capwords()

```

Or 18 bytes noncompetitive.

```
.dↄґ6Cs6Y1q/Al

```

Exactly the same except for this section:

```
Cs6Y1q
C      -    get_time()
 s6    -   add 1 week
   Y   -  get day of the year
    1q - ^ == 1

```

Try it here!
> 8 votes

# Answer
# JavaScript, ~~55~~ ~~53~~ 46 bytes

Note: this has only been tested in Google Chrome, program may behave differently from browser to browser (or device to device)

*2 bytes saved thanks to @ConorO'Brien*

*7 bytes saved thanks to @ETHProductions*

```
alert(/c 25/.test(Date())?"Merry Christmas":a)

```

Exits with `Uncaught ReferenceError: a is not defined` if the date is not `Dec 25`. I'm not really sure if this counts as crashing

```
alert(/c 25/.test(Date())?"Merry Christmas":a)
```
> 6 votes

# Answer
# PHP, ~~39~~ 38 bytes, not competing (doesn´t crash)

```
<?=date(md)-1225?"":"Merry Christmas";

```

or

```
<?date(md)-1225?die:0?>Merry Christmas

```

or

```
<?=["Merry Christmas"][date(md)-1225];

```
> 5 votes

# Answer
# Python 3, ~~66~~ 63 bytes

Thanks to ideas from JavaScript / ES answers here I managed to squeeze some bytes. Index a dictionary - non-existent keys will raise a `KeyError`. The following code works in local time zone

```
import time;print({1:'Merry Christmas'}['c 25'in time.ctime()])

```

The output format for `ctime` isn't locale-dependent - the format is always ~ `'Sun Dec 25 19:23:05 2016'`. Since only in December does the 3-letter abbreviation end with `c`, it is safe to use `'c 25'in time.ctime()` here.

---

**Previous version:**

This works in UTC time zone. For local time zone one needs to `s/gm/local` for 3 more bytes. For Python 2, one can remove parentheses from `print` for 65 bytes.

```
import time;print({(12,25):'Merry Christmas'}[time.gmtime()[1:3]])

```

The construct throws `KeyError` on other dates:

```
>>> import time;print({(1,1):'Happy New Year'}[time.gmtime()[1:3]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: (12, 25)

```
> 5 votes

# Answer
## R, 52 61 58 bytes

```
`if`(format(Sys.Date(),"%m%d")=="1225","Merry Christmas",)

```

If the current date is not the 25th of December then an error is returned because no third argument is supplied to `if`.

Edit: Fixed a silly error
> 4 votes

# Answer
# Python 2, ~~68~~ ~~67~~ 65 bytes

-1 with thanks to @muddyfish

Thanks to @AnttiHaapala for the idea that saved another couple.

```
import time;print['Merry Christmas'][(12,25)!=time.gmtime()[1:3]]

```

Try it online!

Throws an IndexError if not 25th Dec.

Non-competing version for 59 bytes as it only works for non Leap years (uses day of year which is 360 this year but 361 in leap years)

```
import time;print['Merry Christmas'][360!=time.gmtime()[7]]

```
> 4 votes

# Answer
My first time around here... Started with the best language ever for this job:

# Java, ~~200~~ ~~188~~ bytes (thanks to @Daniel Gray), 186 bytes removing "ln" from print.

```
import java.util.*;public class a{public static void main(String[]r){Calendar c=Calendar.getInstance();if(!(c.get(2)==11&&c.get(5)==25)){int i=1/0;}System.out.print("Merry Christmas");}}

```

Try it here!
> 4 votes

# Answer
# MATL, ~~34~~ 33 bytes

```
'Merry Christmas'IHh&Z'5U12h=?}Yl

```

This works in current version (19.7.0) of the language. To cause the error, the following code exploits the fact that the logarithm of a string gives an error (this may change in future versions).

Try it online!

### Explanation

```
'Merry Christmas'  % Push this string
IHh                % Push 3, then 2, concatenate: gives array [3 2]
&Z'                % Get 3rd and 2nd outputs of clock vector: current day and month
5U12h              % Push 5, square, push 12, concatenate: gives [25 12]
=                  % Compare if corresponding entries are equal in the two arrays
?                  % If all entries are equal: do nothing
}                  % Else
  Yl               %   Logarithm. Gives an error when applied on a string
                   % End (implicit). Display (implicit)

```
> 3 votes

# Answer
# C# / CS Script ~~106~~ ~~100~~ 99 bytes

99 byte solution

```
using System;int i;Console.WriteLine(DateTime.Now.ToString("dM")=="2512"?"Merry Christmas":i/0+"");

```

Try it here!

100 byte solution (prefer this one... a bit different)

```
using System;int i;Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1?"Merry Christmas":i/0+"");

```

Explained:

```
using System;
int i;

// if today plus 7 days is the first day of the year, then it's xmas!
Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1
    ? "Merry Christmas"

// otherwise divide i by 0
    : i/0+"");

```

`DateTime.Now.AddDays(7).DayOfYear==1` is one byte shorter than `DateTime.Now.ToString("ddMM")=="2512"` but 1 byte longer than `DateTime.Now.ToString("dM")=="2512"`
> 3 votes

# Answer
## QBIC, 48 bytes

```
~left$$|(_D,5)=@12-25||?@Merry Christmas|\?a(12)

```

Explanation:

```
~             IF
left$$|(_D,5) the date string starts with
=@12-25|      the string "12-25"
|             THEN
?@Me..as|     PRINT "Merry Christmas"
\             ELSE
?a(12)        Print the twelfth index of an undefined array.
              Since there are only 11 elements in undefined arrays, this
              results in an index-out-of-bounds error.
The the IF statement is auto-closed by QBIC.

```

This assumes American `MM-DD` date notation. This would be shorter if I'd finally make a Substring function in QBIC.
> 3 votes

# Answer
# 05AB1E, ~~32~~ 21 bytes

Saved 11 bytes thanks to Adnan's string compression :) .

```
1žfže‚12D·>‚Q÷”ÞÙŒÎ”×

```

## Explanation

```
 žfže‚                Push [current month, current day]
      12D·>‚          Push [12, 25]
            Q         Push tmp = 1 if the two arrays are equal, tmp = 0 otherwise
1            ÷        Evaluate x = 1/tmp. If tmp = 0 a division by 0 exception is thrown
              ”ÞÙŒÎ”× Implicitly display "Merry Christmas" x times

```

Try it online!

I did what came to mind first, so there may be better approaches for this one. But PPCG deserves a Merry Christmas in 05AB1E as well ;) .
> 3 votes

# Answer
# C#/CS Script, 96 Bytes, Mostly Plagiarized from Erresen

```
using System;Console.WriteLine(DateTime.Now.AddDays(7).DayOfYear==1?"Merry Christmas":1/0+"");

```

Deletes the `int i` declaration in favor of hard coding the division. I would leave this as a comment but don't have the reputation.
> 2 votes

# Answer
# bash + Unix utilities, ~~51~~ ~~49~~ 47 bytes

```
((`date +%m%d`-1225))&&${};echo Merry Christmas

```

\*Thanks to @KenY-N for pointing out that the quotes in the echo can be removed, and to @IporSircer for reducing the condition size by 2 bytes.
> 2 votes

# Answer
# Groovy, 57 bytes

```
print new Date().format("Md")=="1225"?"Merry Christmas":b

```

Crashes on dates other than 25.12. with `groovy.lang.MissingPropertyException` because `b` is not defined.
> 1 votes

# Answer
# Python 2, ~~69 77~~ 75 or ~~72~~ 70 Bytes

```
import time
if time.strftime("%d%m")=="2512":print"Merry Christmas"
else:1/0

```

If it doesn't matter if it exits with an error when it is Christmas, then:

```
import time
if time.strftime("%d%m")=="2512":print"Merry Christmas"
1/0

```

EDIT:

Thanks @Flp.Tkc for pointing out that I needed to raise an error

-2 Bytes from @Max for pointing out about removing colons from the strftime function
> 1 votes

# Answer
# Stacked, 42 bytes

Try it here!

```
('Merry Christmas')'MMDD'date'1225'=¬#out

```

This creates a single-element array containing namely `'Merry Christmas!'`. After, it puts the date into a string with the month followed by the day. It checks for equality with `'1225'` (Christmas), inverts it with `¬`, then gets that member from the preceding array. If it isn't Christmas, this will error with an index error. Otherwise, it prints `Merry Christmas`. (Change the date in the string to see how it works on other days.)
> 1 votes

# Answer
## Batch, 66 bytes

```
@echo off
if %date:~0,5%==25/12 echo Merry Christmas&exit/b
if

```

The trailing newline is significant, as it causes parsing of the `if` statement to fail. You may need to tweak the date check to match your local date format.
> 1 votes

# Answer
# CJam, 28

```
et[C25]#1="Merry Christmas"/

```

Try it online

**Explanation:**

```
et                   push an array of current [year month day hour ...]
[C25]                push the array [12 25] (C=12)
#                    find the position of the 2nd array within the first one
1=                   compare it with 1, resulting in 1 for 1 and 0 otherwise
"Merry Christmas"/   split "Merry Christmas" into pieces of that length
                      (it crashes if the length is 0)
                     at the end, all the pieces are concatenated
                      and printed automatically

```
> 1 votes

# Answer
## C#.NET, ~~180~~ ~~172~~ 171 bytes

*Saved 8 bytes thanks to Kritixi Lithos*

*Saved 1 byte thanks to Kritixi Lithos, again ;)*

```
namespace System{class P{static void Main(string[] args){var d=DateTime.Today;if(d.Day==25)if(d.Month>11){Console.Write("Merry Christmas!");return;}throw new Exception();}}}

```

Alternative, ungolfed variant:

```
namespace System //In System, so we don't have to use system.
{
    class Program
    {
        static void Main(string[] args) //Main function.
        {
            var d = DateTime.Today; //Get Today.
            if (d.Day == 25) if (d.Month == 12) //Day has to be 25th, Month has to be 12nd.
                {
                    Console.Write("Merry Christmas!"); return; //Prints.
                }
            throw new NotChristmasException(); //Errors/Crashes the program.
        }
    }
    class NotChristmasException : Exception { } //Holiday exception, hooray!
}

```
> 0 votes

# Answer
# C#, ~~122~~ 104 bytes

18 bytes saved, thanks to @raznagul

```
using System;i=>{if(DateTime.Now.AddDays(7).DayOfYear==1)Console.Write("Merry Christmas");else{i/=0;};};

```

It adds 7 days to the current day, and checks if it is the first day of the year, if yes, it displays "Merry Christmas", otherwise it divides by zero.
> 0 votes

# Answer
# Mathematica, 46 bytes

```
If[Today[[1,2;;]]=={12,25},"Merry Christmas!"]

```
> 0 votes

# Answer
# Common Lisp, 140

```
(let((m(multiple-value-list(decode-universal-time(get-universal-time)))))(if(and(eq(nth 3 m)25)(eq(nth 4 m)12))(write"Merry Christmas")(c)))

```

Crashes with undefined function if the date isn't right.
> 0 votes

# Answer
## awk, 29 bytes (+ length("Merry xmas"))

```
v=1225==strftime("%m%d")||1/0

```

Running it:

```
$ echo Merry xmas | awk 'v=1225==strftime("%m%d")||1/0'
awk: cmd. line:1: (FILENAME=- FNR=1) fatal: division by zero attempted

```

Season greeting is piped to `awk`. `strftime` returns month+day (for example `1226`) and if it matches `1225` `$0` record gets outputed. Result of comparison `1225==1226` is placed to `v` var which is used to divide 1 if the date comparison fails.
> 0 votes

# Answer
## Haskell, 116

Crashes with "Non-exhaustive patterns in function f" if it's not Christmas.

```
import Data.Time
f(_,12,25)="Merry Christmas"
main=getZonedTime>>=print.f.toGregorian.localDay.zonedTimeToLocalTime

```

Unfortunately, there's no function that allows you to just immediately get the time in a useful format, so most of this is converting the date formats.
> 0 votes

# Answer
# bash command line, ~~45~~ ~~48~~ 49 48 bytes

```
date +%m%d|grep -q 1225&&echo Merry Christmas||!-
date +%m%d|grep -q 1225||!-;echo Merry Christmas

```

Similar to Mitchell Spector's, but use `grep` in silent mode to check for a match, then `&&` will ensure that it only prints on success, and the `||` causes it to look up history with `!-`, which gives me this:

```
-bash: !-: event not found

```

And it stops execution as `!- ; echo foo` demonstrates. The `bash` documentation says that `!-n` refers to the current command minus `n`, so perhaps it is being interpreted as `!-0`, which gives an identical (and non-localised) error message.
> 0 votes

# Answer
## Ruby, 69 bytes

```
if Time.now.strftime("%j")=="360";puts "Merry Christmas";else 0/0;end

```

Works in 2016. Doesn't differentiate between normal and leap years, may need to be adjusted for non-leap years.
> 0 votes

# Answer
# ForceLang, 180 bytes

```
set s datetime.toDateString datetime.now()
set t "Dec 25"
def c s.charAt i
def d t.charAt i
set i -1
label 1
set i 1+i
if i=6
 io.write "Merry Christmas!"
 exit()
if c=d
goto 1
z.z

```

(Remember that `datetime.toDateString` is locale-dependent, so this may not work depending on your locale)
> 0 votes

# Answer
# C#, 90 bytes

```
using System;Console.Write(new[]{"Merry Christmas"}[DateTime.Now.AddDays(7).DayOfYear-1]);

```

Throws IndexOutOfRangeException if it's not christmas.

Try it here!
> 0 votes

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


title: Tips for golfing in D2

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

# Answer
> 2 votes
Look, no parens!

D's functions and template functions can be called as values, methods (won't help), and properties.

I can't believe no one has said this yet. I'll list the ones that save bytes:

* `fun()` and `fun!()()` shorten to `fun` (assuming there is no variable `fun`).
* `fun(par)` shortens to `par.fun` (assuming `par` has no property/method `fun`, as well as `par` not being an expression like `5+2`).
* `fun!(T)()` shortens to `fun!T`
* `fun!(T)(par)` shortens to `par.fun!T` (assuming `par` has no property/method `fun`)

And with objects:

* `new cls()` shortens to `new cls` (More JavaScript anyone?)
* `obj.fun()` and `obj.fun!()()` shorten to `obj.fun`
* `obj.fun!(T)()` shortens to `obj.fun!T`

One final thing, **use old versions**. It allows you to use deprecated features that shorten your code. That said, best advice: D isn't good for code-golf. It is a great language, just not for code-golf.

# Answer
> 2 votes
D is JavaScript.

---

Obviously not. But, when dealing with `float`, `double` and `real`, `nan` is a value which must be handled, and, as specified by IEEE 754, NaN does not compare equal with itself.

```
writeln(double.nan == double.nan); // false

```

Meaning,

```
writeln(value!=value); // only true for nan

```

is way shorter than

```
import std.math;
writeln(isNaN(value));

```

Obviously, always use `math.isNaN` for *real* code. ;)

# Answer
> 1 votes
D has type inference and an `auto` keyword. If the object is not `int`, then `auto` is probably shorter.

# Answer
> 1 votes
If the question requires a full program, the `module` declaration is surprisingly unnecessary.

*\*cough\** Java, anyone? *\*clears throat\** *Actually*, D's `module` system is older than Java's.

# Answer
> 1 votes
D is great at method chaining, but:

```
str.toLower.strip().split("").sort();

```

is the same as

```
sort(split(strip(str.toLower),""));

```

and usually the non-chained one is shorter, which I just realised, which lets me shorten my answer to Manage Trash So :D

# Answer
> 1 votes
D, as a multiparadigm (Object Functional) systems programming language, seems to embrace TIMTOWTDI, or There Is More Than One Way To Do It.

Case in point, writing the program's argv:

```
import std.stdio, std.array, std.algorithm;

void main(string[] args) {
    for(int i=0;i<args.length;writeln(args[i++])){};

    foreach(a;args)writeln(a);

    each!writeln(args);
}

```

Note the C-style for-loop requires `{}` as the empty block and will not accept a semicolon or nothing as a blank statement, *in this case*. Usually,  or `;` are no-ops.

# Answer
> 1 votes
D has a few types of C#-style lambda expressions, which can be assigned and stand alone:

```
(int a,int b)=>a*b;

auto a=(int a,int b)=>a*b;

```

However, unlike C#, the signature's types are still needed because D doesn't have Haskell-level type inferencing.

https://dlang.org/spec/expression.html#Lambda

# Answer
> 0 votes
Like C/C++, `main` can be `int` or `void`, but `void main(){}` will always be shorter than `int main(){return my_func_returning_int;}`.

# Answer
> 0 votes
Calling a function on an object with no other arguments

```
reverse(x);

```

can nearly always be shortened to

```
x.reverse;

```

to shave a byte or more.

This is because the `.` makes the LHS an implicit first argument, and templating lets us choose the right function for the args.

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


title: Tips for golfing in Pike

text:
# Question
Title: Tips for golfing in Pike
Pike is a dynamically typed interpreted scripting language, heavily influenced by C, which typically compiles to C99 with a few `#define`s. (It even has a preprocessor!)

What general tips do you have for golfing in Pike? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Pike (e.g. "remove comments" is not an answer).

# Answer
> 1 votes
Array operators.

Pike's arrays have some operators that act ... weird.

* `({1})+({2})` returns `({1,2})` (concatenation)
* `({1,3,8,3,2}) - ({3,1})` returns `({8,2})` (the former argument without elements in the latter argument)
* `({1,3,7,9,11,12}) & ({4,11,8,9,1})` will return: `({1,9,11})` (intersection)
* `({1,2,3}) | ({1,3,5})` will return `({1,2,3,5})` (union)
* `({1,3,5,6}) ^ ({4,5,6,7})` will return `({1,3,4,7})` (symmetric difference)
* `({1,2,3,4,5})/({2,3})` will return `({ ({1}), ({4,5}) })` (split at occurences)
* `({1,2,3,4})/2` will return `({ ({1,2}), ({3,4}) })` (split by length, truncates the excess.)
* `({1,2,3,4,5})/2.0` will return `({ ({1,2}), ({3,4}), ({5}) })` (split by length, keeps the excess.)
* `({1,2,3,4,5})%3` will return `({4,5})` (excess of split by length).

# Answer
> 1 votes
### Abuse `mixed`.

Pike is unfortunately not *exactly* identical to C; for instance the type of a list of strings is `array(string)`, not `char[][]` or even `string[]`.

Any time you need a type declarator and it's not `int`, `mixed` (the "any" type, which gets promoted to the actual type of the RHS at runtime) is liable to be shorter.

A function that takes a list of ints and sorts it, then returns it, for a whopping **41 bytes**:

```
array(int)s(array(int)l){return sort(l);}

```

Or, the type-inferencing version, which is **31 bytes**:

```
mixed s(mixed l){return sort(l);}

```

My answer to Manage Trash So uses a lot of `mixed`.

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


title: A 2D Traffic Jam

text:
# Question
Title: A 2D Traffic Jam
The Biham-Middleton-Levine traffic model is a self-organizing cellular automaton that models simplified traffic.

> It consists of a number of cars represented by points on a lattice with a random starting position, where each car may be one of two types: those that only move downwards (shown as blue in this article), and those that only move towards the right (shown as red in this article). The two types of cars take turns to move. During each turn, all the cars for the corresponding type advance by one step if they are not blocked by another car.

Your task is to visualize this model as an animation. Here are some good demonstrations.

## Input

A floating point number between 0 and 1 representing density, and two integers representing the displayed grid height and width. Assume inputs are valid, and parameters to a function or reading from user input are both fine.

Example: `0.38 144 89` (corresponds to image above)

## Output

A grid, at least 80x80, that displays the animation of this model running. At the start, cars are randomly placed on the grid until the grid reaches the input density, with half red and half blue (that is density times total number of grid squares, rounded however you like). The density *must* be this value, which means you cannot fill each cell with density as a probability. For each step, one type of car either moves downwards or right, wrapping around if they go past the edge. The type of car that moves alternates each step. To make the animation viewable, there must be at least 10 ms between each step.

## Rules

* The cars can be any color or symbol as long as they are distinguishable from each other and the background, and each car type is the same color or symbol.
* Console and graphical output are both allowed. For console output, any printable symbol is fine, but output must be as a grid of characters.
* Please specify what kind of output you've produced if you don't have a screenshot or gif.
* The simulation must run forever.

The output is a bit complex, so if you have any questions, please comment.

# Answer
> 5 votes
# Mathematica, ~~237~~ ~~228~~ ~~203~~ ~~198~~ 181 bytes

```
(b=RandomSample@ArrayReshape[Table[{0,i=2},##/2],{1##2},1]~Partition~#2;Dynamic@Colorize[i=-i;b=CellularAutomaton[{193973693,{3,{a=0{,,},{3,9,1},a}},{1,1}},b];If[i>0,b,2-b]])&

```

The output is a dynamic `Image`. The background is light green, and the cars are black or magenta, depending on their direction.

### Explanation

```
b=RandomSample@ArrayReshape[Table[{i=1,2},##/2],{1##2},1]~Partition~#2

```

Create the initial board:

```
Table[{0,i=2},##/2]

```

Set `i` to `2`. Create a `List` of `{0, 2}`, whose length is floor(density * width * height / 2) (divided by two because `{0, 2}` is length-2).

```
ArrayReshape[ ... ,{1##2},1]

```

Reshape the resulting 2-D `List` (2 x something) into 1-D `List` (length = width * height). Pad `1` if there aren't enough values.

```
RandomSample@ ...

```

(Pseudo-)randomly sort the result.

```
... ~Partition~#2

```

Partition that result into length (width).

```
b= ...

```

Store that in `b`.

---

```
Dynamic@Colorize[i=-i;b=CellularAutomaton[{193973693,{3,{a=0{,,},{3,9,1},a}},{1,1}},b];If[i>0,b,2-b]]

```

Create a `Dynamic` `Image`:

```
i=-i;

```

Flip the sign of `i`.

```
b=CellularAutomaton[{193973693,{3,{a=0{,,},{3,9,1},a}},{1,1}},b]

```

Apply the cellular automaton with rule `193973693` and neighbor weights `{{0, 0, 0}, {3, 9, 1}, {0, 0, 0}}` to `b` transposed. Set `b` equal to that.

```
If[i>0,b,2-b]

```

If `i` is positive, leave `b` alone. If not, transpose the `b` (`2-` is there because I golfed the `CellularAutomaton` a bit). Essentially, this transposes `b` every other iteration (to undo the transposition)

```
Colorize[ ... ]

```

Convert the array into a colorful `Image`.

```
Dynamic@ ...

```

Make the expression `Dynamic`. i.e. the above functions are run repeatedly.

### Output

Here's a sample output (inputs: `0.35, 192, 108`) for 2000 frames (magnified 2x).

https://i.imgur.com/zmSyRut.mp4

# Answer
> 5 votes
# R, ~~350~~ ~~338~~ ~~293~~ ~~291~~ ~~273~~ ~~268~~ 264 bytes

```
function(d,x,y){f=function(w){v=length(w);for(j in which(w>0&!w[c(2:v,1)]))w[c(j,j%%v+1)]=0:1;w};m=matrix(sample(c(rep(1,q<-floor(d*y*x/2)),rep(-1,q),rep(0,x*y-2*q))),x);p=animation::ani.pause;o=image;a=apply;repeat{o(m<-t(a(m,1,f)));p();o(m<--1*a(-1*m,2,f));p()}}

```

### Ungolfed:

```
function(d,x,y){
  q=floor(d*y*x/2)

  m=matrix(sample(c(rep(1,q),rep(-1,q),rep(0,x*y-2*q))),x)

  f=function(w){
    v=length(w)
    for(j in which(w>0&!w[c(2:v,1)])){
      w[c(j,j%%v+1)]=0:1
    }
    w
  }

  library(animation)
  repeat{
    m=t(apply(m,1,f))
    image(m)
    m=-1*apply(-1*t(m),2,f))
    ani.pause()
    image(m)
    ani.pause()
  }
}

```

Function that takes 3 arguments: `d` as density, and dimensions `x,y`. `q` is the number of cars in each colour. `m` is the matrix with cars, which is initially filled by taking a random sort of the number of cars and empty spaces. Cars are either `1` or `-1`, empty space is `0`.

`f` is a function that moves the cars one row, looking at cars coded as `1`. It checks if the car can move by checking for `1`s followed by `0`. We use `apply` to run `f` on every row or column, depending on which cars.

`f` handles the moving of the `1` cars, to move the `-1` cars, we transpose the matrix, chaninging the direction of movement, multiplying the matrix by `-1`, so the `-1` cars become `1` cars, and v.v. and the resulting matrix is transformed again.

This uses `image` to create the plot, using 3 default colours for the three values. Uses the `animation` package to handle the animations using the default options, which is 1 fps.

`0.38, 144, 89:`

`0.2, 144, 89:`

`0.53, 144, 89:`

# Answer
> 4 votes
# Dyalog APL, ~~190~~ ~~108~~ ~~115~~ 112 bytes

### Solution

```
S←{⍉⍣⍺⊢d[⍺]↑d[⍺]↓⍉↑(⍺⊃'(↓+) ' '(→+) ')⎕R' \1'↓(,⍨,⊢)⍉⍣⍺⍉⎕←⍵⊣⎕DL÷4}
{1S 0S⍵}⍣≡' ↓→'[d⍴{⍵[?⍨⍴⍵]}c↑1 2⍴⍨⌊⎕×c←×/d←⎕]

```

TryAPL online (slightly modified because of online restrictions):

1. Set `⎕IO←0`, define the function *S*, and then define and display a random 38% 14×29 grid, *G*.
2. Make one move down.
3. Make one move to the right.
4. Go to step 2.

<sup>*Animation of previous algorithm, which did not guarantee density.*</sup>

### Explanation

`S←{` define the direct function *S* (explained here from right to left):

`÷4` reciprocal of 4 (0.25)

`⎕DL` wait that many seconds (returns actual elapsed time)

`⍵⊣` discard that in favour of ⍵ (the right argument; the grid)

`⎕←` output that

transpose

`⍉⍣⍺` transpose back again if ⍺ (the left argument; 0=down, 1=right)

`(` apply the function train (explained here from left to right):

`,⍨` the argument appended to itself

`,` appended to

itself

`)`

split matrix into list of lists

`(` search regex (explained here from left to right):

`⍺⊃` pick one of the following two based on ⍺ (0=down/first, 1=right/second)

`'(↓+) ' '(→+) '` down and left arrow sequences followed by a space

`)⎕R' \1'` replace with a space followed by the found sequence

mix list of lists into matrix

transpose

`d[⍺]↓` drop "height" rows if ⍺ (left argument) is 0 (down) or "width" rows if ⍺ is 1 (right)

`d[⍺]↑` then take that many rows

pass through (serves as separator)

`⍉⍣⍺` transpose if ⍺ (the left argument; 0=down, 1=right)

`}`

---

`' ↓→'[` index the string with (explained here from right to left):

numeric input (dimensions)

`d←` assign that to *d*

`×/` multiply the dimensions (finds count of cells)

`c←` assign that to *c*

`⎕×` multiply that with numeric input (the density)

round down

`1 2⍴⍨` cyclically repeat one and two until that length

`c↑` extend that until length *c*, padding with zeros

`d⍴` use *d* (the dimensions) to reshape

`{` apply this anonymous function to that (explained here from left to right):

`⍵[` the right argument (the list of zeros, ones, and twos) indexed by

`?⍨` the shuffled indices up to

`⍴⍵` the length of the argument

`]`

`}`

`]`

`{` apply the following anonymous function (explained from right to left):

`0S⍵` apply *S* with 0 (down) as left argument and the grid as right argument

`1S` with that as right argument, apply *S* with 1 (right) as left argument

`}⍣≡` until two successive iterations are identical (a traffic jam)

### Notes

1. Requires `⎕IO←0`, which is default on many systems.
2. Prompts for (height,width), and then for density.
3. Does not use any built-in automaton.
4. Does use built-in regex support.
5. Stops if there is a traffic jam (no car can move).
6. Outputs character matrices where  represents cars moving right,  represents cars moving down, and spaces are empty roads.
7. As above, it outputs to the session at 4 Hz, but frequency can be adjusted by changing `÷4`; e.g `÷3` is 3 Hz and `.3` is ³⁄₁₀ Hz.
8. It is easier to see what is going on if executing `]Box on -s=max -f=on` first.
9. The required distribution is now guaranteed, and the two types of cars occur in exactly 50-50, save for rounding.

# Answer
> 1 votes
# Java (624 Bytes + 18 Bytes for Java.awt.\* = 642 Bytes)

```
static void k(double b,final int c,final int d){final int[][]a=new int[c+1][d+1];int i=0,j;for(;i<c;i++){for(j=0;j<d;j++){a[i][j]=Math.random()<b?Math.random()<0.5?1:2:0;}}Frame e=new Frame(){public void paint(Graphics g){setVisible(1>0);int i=0,j;for(;i<c;i++){for(j=0;j<d;j++){g.setColor(a[i][j]==2?Color.BLUE:a[i][j]==1?Color.RED:Color.WHITE);g.drawLine(i,j,i,j);}}for(i=c-1;i>=0;i--){for(j=d-1;j>=0;j--){if(a[i][j]==1&&a[i][(j+1)%d]==0){a[i][(j+1)%d]=1;a[i][j]=0;}else if(a[i][j]>1&&a[(i+1)%c][j]==0){a[(i+1)%c][j]=2;a[i][j]=0;}}}}};e.show();while(1>0){e.setSize(c,d+i++%2);try{Thread.sleep(400L);}catch(Exception f){}}}

```

Ungolfed:

```
static void k(double b,final int c,final int d){
        final int[][]a=new int[c+1][d+1];
        int i=0,j;
        for(;i<c;i++) {
            for(j=0;j<d;j++) {
                a[i][j]=Math.random()<b?Math.random()<0.5?1:2:0;
            }
        }

        Frame e=new Frame(){
            public void paint(Graphics g){
                setVisible(1>0);
                int i=0,j;
                for(;i<c;i++) {
                    for(j=0;j<d;j++) {
                        g.setColor(a[i][j]==2?Color.BLUE:a[i][j]==1?Color.RED:Color.WHITE);
                        g.drawLine(i,j,i,j);
                    }
                }
                for(i=c-1;i>=0;i--) {
                    for(j=d-1;j>=0;j--) {
                        if(a[i][j]==1&&a[i][(j+1)%d]==0){
                            a[i][(j+1)%d]=1;a[i][j]=0;
                        }else if(a[i][j]>1&&a[(i+1)%c][j]==0){
                            a[(i+1)%c][j]=2;a[i][j]=0;
                        }
                    }
                }
            }
        };
        e.show();
        while(1>0){e.setSize(c,d+i++%2);try{Thread.sleep(400L);}catch(Exception f){}}
    }

```

Picture:

---
Tags: code-golf, ascii-art, graphical-output, animation
---