title: Self-Mutilating Program

text:
# Question
Title: Self-Mutilating Program
Simply put, your goal is to create a complete program that modifies its own source code until every character of the source is different than what it started as.

Please include the beginning source as well as the ending source in your post, as well as a description. E.g. Describe what (else) your program does, the language you used, your strategy, etc.

### Rules

* Your program must halt sometime after the modification is complete.
* It must actually modify its own, currently running source code (not necessarily the file you passed to the interpreter, it modifies its instructions), not print a new program or write a new file.
* Standard loopholes are disallowed.
* Shortest program wins.
* If your language can modify its own file and execute a new compiler process, but cannot modify its own (currently running) source code, you may write such a program instead at a +20% bytes penalty, rounded up. Real self-modifying languages should have an advantage.

**Edit**: If your program halts with errors, please specify it as such (and maybe say what the errors are.)

# Answer
> 20 votes
# ///, 1 byte

```
/

```

The program finds a `/` (the start of a pattern-replacement group), and removes it in preparation to make the replacement. Then it reaches EOF, so it gives up and halts.

# Answer
> 22 votes
## Labyrinth, 2 bytes

```
>@

```

The `>` rotates the source so that it becomes

```
@>

```

The instruction pointer is now in a dead end and turns around to hit the `@` which terminates the program.

Of course, `<@` would also work.

# Answer
> 12 votes
# Python 2, 225 bytes

```
import sys
from ctypes import*
c=sys._getframe().f_code.co_code
i=c_int
p=POINTER
class S(Structure):_fields_=zip("r"*9+"v",(i,c_void_p,i,c_char_p,i,p(i),i,c_long,i,c_char*len(c)))
cast(id(c),p(S)).contents.v=`len([])`*len(c)

```

The ending source code is a string of `"0"`s whose length is equal to the number of bytes in the original compiled code object.

The code finds the running code object, `sys._getframe().f_code.co_code`, and creates a structure which represents python string objects. It then gets the memory that the code actually takes and replaces it with `"0"*len(c)`.

When ran, the program exits with the following traceback:

```
XXX lineno: 7, opcode: 49
Traceback (most recent call last):
  File "main.py", line 7, in <module>
    cast(id(c),p(S)).contents.v=`1+1`*len(c)
SystemError: unknown opcode

```

This shows that the overwrite was successful and the program dies because `0` isn't a valid opcode.

I'm surprised that this is even possible in python, frame objects are read-only, I can't create new ones. The only complicated thing this does is change an immutable object (a string).

# Answer
> 11 votes
# evil, 1 byte

```
q

```

evil has several memory stores - one is the source code itself and one is the *wheel* which is a circular queue which is initialised to a single zero. `q` swaps the source code and the wheel, so it replaces the source with a null-byte. However, only lower-case letters are actual operators in evil, so that character is simply a no-op and the program terminates.

# Answer
> 6 votes
# MSM, 8 bytes

```
'.qp.;.;

```

Transforms the source code to `pqpqpqpq`

MSM operates on a list of strings. Commands are taken from the left and they treat the right side as a stack. MSM always works on it's own source.

Execution trace:

```
'.qp.;.;                       upon start the source is implicitly split into a
                               list of single char strings

' . q p . ; . ;                ' takes the next element and pushes it on the stack
    q p . ; . ; .              q is not a command so it's pushed
      p . ; . ; . q            same for p
        . ; . ; . q p          . concats the top and next to top element
          ; . ; . pq           ; duplicates the top element
            . ; . pq pq        concat
              ; . pqpq         dup
                . pqpq pqpq    concat
                  pqpqpqpq     MSM stops when there's only one element left

```

# Answer
> 6 votes
# Malbolge, 1 or 2 bytes.

```
D

```

The Malbolge language "encrypts" each instruction after executing it, so this letter (Malbolge NOP) will become an `!` (which is also a nop), and then terminate. For some reason, the Malbolge interpreter I use requires two bytes to run, giving `DC` (both of which are nops) becoming `!U` (both of which are also nops)

Edit: The initial state of Malbolge memory depends on the last two characters in the code, so it is not well defined for one character programs. (Though this code doesn't care about the initial state of memory)

# Answer
> 5 votes
# SMBF, 92 bytes

Can be golfed, and I'll probably work more on it later.

```
>>+>>+>>+>>+>>+>>+[<-[>+<---]>+++++<<]>>>>>--[>-<++++++]>--->>++>+++++[>------<-]>->>++[<<]<

```

### Explanation

The program generates the following commands at the end of its tape to erase itself, so it has to generate the following values on the tape:

```
[[-]<]          ASCII: 91 91 45 93 60 93

```

Make a bunch of `91`s, with nulls (shown as `_`) between to use for temp values.

```
>>+>>+>>+>>+>>+>>+[<-[>+<---]>+++++<<]

code__91_91_91_91_91_91_
   ^

```

Adjust the values by the differences

```
>>>>>--[>-<++++++]>---  Sub 46
>>++                    Add 2
>+++++[>------<-]>-     Sub 31
>>++                    Add 2
[<<]<                   Shift left to the code
code__[_[_-_]_<_]_      Zero out the code
   ^

```

The tape following execution will be all zeros, with the exception of the generated code `[_[_-_]_<_]`.

### Note:

This program made me realize that my Python interpreter for SMBF has a bug or two, ~~and I haven't figured out a fix yet.~~ It's fixed now.

# Answer
> 5 votes
**x86 asm** \- 6 bytes

not sure if "until every character of the source is different than what it started as" refers to each byte, each nemonic, or general modification. if I'm invalid I can change the xor to a rep xor so each bit changes values but was hoping not to do that to save 6 more bytes to stay at least a little bit comparable to these specialty golf languages.

All this does is change a c2 to a c3 retn by getting live address of eip and xoring 5 bytes in front.

```
58          | pop eax                        ; store addr of eip in eax
83 70 05 01 | xor dword ptr ds:[eax + 5], 1  ; c2 ^ 1 = c3 = RETN
c2          | retn                           ; leave

```

# Answer
> 4 votes
### Redcode, 7 bytes, 1 instruction (Just an example. Not competing)

This is a trivial example.

Moves the next memory location onto itself, then halts (because the entire memory is initialized to `DAT 0 0`, which halts the program when executed.)

```
MOV 1 0

```

# Answer
> 4 votes
# Emacs Lisp 22 bytes

```
(defun a()(defun a()))

```

Run from REPL:

```
ELISP> (defun a()(defun a()))
a
ELISP> (symbol-function 'a)
(lambda nil
  (defun a nil))

ELISP> (a)
a
ELISP> (symbol-function 'a)
(lambda nil nil)

```

Function now evaluates to `nil`.

Alternately (unbind itself) **30 bytes**

```
(defun a()(fmakunbound 'a)(a))

```

Evaluate and errors as `void-function`. Function existed prior to being run.

# Answer
> 3 votes
# Powershell 65 bytes

```
function a{si -pat:function:a -va:([scriptblock]::create($null))}

```

Define a function that rewrites itself to null.

Evaluate it once and it eliminates itself.

Alternately (deletes itself from memory) **36 bytes**

```
function a{remove-item function:a;a}

```

Calling it first removes it then attempts to evaluate recursively. Erroring out as an unknown command.

# Answer
> 3 votes
## MIXAL, 6 bytes (counting 2 tabs)

```
    STZ    0

```

The program starts at memory location 0 and then writes 0 to memory location 0, thus erasing itself. The machine halts automatically.

This is the assembly language for Donald Knuth's hypothetical MIX computer, which may be assembled and run using GNU MIX development kit (https://www.gnu.org/software/mdk/).

# Answer
> 3 votes
# \>\<\>, ~~40~~ ~~34~~ 30 bytes

```
0&00a6*0&1+:&060"c"l=?!.~~r >p

```

Try it here!

Explanation:

```
0&          Adds 0 to the registry
00a6*       Adds "0,0,<" to the stack; coords followed by a character
------------loop start (for clarity)
0           0 added to stack
&1+:&       Registry retrieved, increased by 1, duplicated, one put back in registry
0           ASCII character 0 added to stack (just a 0 but will be converted to that character when inserted in the code)
60          6 and 0 added to stack
"c"         The number 99 added to stack (length of code + 1 * 3)
l=?         Code length added to stack, checks if it is equal to 111

!.          If false, pointer jumps back to character (9,0) (loop start position)
~~r >p      If true, removes the 0 and 9, reverses stack, then loops the p command setting
all the characters to a "<" character and the 2nd character to a " "

```

Basically this puts a bunch of 3 character blocks in the stack like so: (ypos, xpos, ASCII character) which gets reversed at the end so the final 'p' command reads (character, xpos, ypos) and sets that position in the code to that character. The first character is manually set as '\<', so that the code ends up being '\>p\<' at the end to loop the command. Then every other character is overwritten as a ' ' including the p character. The ' ' is actually "ASCII CHAR 0" which is NOT a NOP and will give an error when read.

Also there have to be an odd(?) number of characters before the 'p' command or else it wont be looped back into a last time and overwritten.

# Answer
> 2 votes
# Batch, 11 bytes

```
@echo>%0&&*

```

Modifies source code to `ECHO is on.`

```
@           - don't echo the command.
 echo       - print ECHO is on.
     >%0    - write to own file.
        &&* - execute * command after the above is done, * doesn't exist so program halts.

```

The `@` is there so the command isn't echoed, but mostly so the two `echo`s don't line up.

# Answer
> 2 votes
# Jolf, 4 bytes, noncompeting

```
₯S₯C

```

This `₯S`ets the `₯C`ode element's value to the input, `undefined` as none is given. Try it here!

# Answer
> 0 votes
# (Filesystem) Befunge 98, 46 bytes

```
ff*:1100'aof0'ai
               21f0'ai@

```

Note that this program creates and manipulates a file named `a`. How it works:

1. The code creates a file named `a` containing the entire code (out to 256 characters in each dimension) shifted one space upward and two the left.
2. This program then reads the file named `a` as one line, replacing the entire first line with the contents of the `a` file.
3. The second line, which has been copied in front of the IP, is executed
4. Which reads the `a` file into the second line shifted two places to the right.

As a side effect, the ending source code isn't even valid Befunge! (because it contains newlines as data in a single line)

# Answer
> 0 votes
## Python 2, 238 bytes + 20% = 285.6

```
# coding: utf-8
import codecs
with codecs.open(__file__,'r') as f:
    t = f.read()
n="utf-8" if t.startswith("# coding: ascii") else "ascii"
with codecs.open(__file__,'w', encoding=n) as f:
    f.write(t[0]+" coding: "+n+t[t.find("\n"):])

```

Basically, this toggles the current file encoding of the python source between `ascii` and `utf-8`, thus essentially changing every character of the source!

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


title: 7-segment differences

text:
# Question
Title: 7-segment differences
I think most people around here know what a 7-segment display for digits is:

```
 _         _   _         _    _    _    _    _
| |    |   _|  _|  |_|  |_   |_     |  |_|  |_|
|_|    |  |_   _|    |   _|  |_|    |  |_|   _|

```

We can define the **7-segment difference** (7SD) between two *digits* to be the number of segments that need to be toggled to switch from one to the other. E.g. the 7SD between `1` and `2` is **5** (the three horizontal segments and the lower two vertical segments need to be toggled), and the 7SD between 6 and 8 is **1**.

Furthermore, we can define the 7SD between two *numbers* to be the sum of 7SDs between their corresponding digits. If one number is longer than the other, we assume they are right-aligned and add the number of segments needed to display the additional most-significant digits of the larger number. As an example, consider the 7SD between `12345` and `549`:

```
  x:  1 2 3 4 5
  y:      5 4 9
7SD:  2+5+2+0+1 = 10

```

Your task is to **compute 7SD between *n* and *n+1*, given *n***.

For convenience, here is the full table of 7SDs between individual digits. The row `_` represents an empty position.

```
   _ 0 1 2 3 4 5 6 7 8 9

_  0 6 2 5 5 4 5 6 3 7 6
0  6 0 4 3 3 4 3 2 3 1 2
1  2 4 0 5 3 2 5 6 1 5 4
2  5 3 5 0 2 5 4 3 4 2 3
3  5 3 3 2 0 3 2 3 2 2 1
4  4 4 2 5 3 0 3 4 3 3 2
5  5 3 5 4 2 3 0 1 4 2 1
6  6 2 6 3 3 4 1 0 5 1 2
7  3 3 1 4 2 3 4 5 0 4 3
8  7 1 5 2 2 3 2 1 4 0 1
9  6 2 4 3 1 2 1 2 3 1 0

```

## Input

* Input is a single positive integer `n`.
* You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument.
* You may assume that the input is at most one less than the largest number which can be represented by your language's standard integer type, as long as that type supports at least values up to and including 127.

## Output

* You should print a single integer, the 7SD between `n` and `n+1`.
* You may output via STDOUT (or closest alternative), function return value or function (out) argument.

## Scoring

Standard rules apply, shortest code (in bytes) wins.

## Test Cases

For some obscure reason, this sequence isn't in OEIS yet, although there is the closely related sequence A123587. Here are the first 100 numbers (starting with `n = 1, 2, 3, ...`):

```
5, 2, 3, 3, 1, 5, 4, 1, 4, 4, 5, 2, 3, 3, 1, 5, 4, 1, 7, 4, 5, 2, 3, 3, 1,
5, 4, 1, 4, 4, 5, 2, 3, 3, 1, 5, 4, 1, 5, 4, 5, 2, 3, 3, 1, 5, 4, 1, 5, 4,
5, 2, 3, 3, 1, 5, 4, 1, 3, 4, 5, 2, 3, 3, 1, 5, 4, 1, 7, 4, 5, 2, 3, 3, 1,
5, 4, 1, 6, 4, 5, 2, 3, 3, 1, 5, 4, 1, 3, 4, 5, 2, 3, 3, 1, 5, 4, 1, 6, 4

```

The first input for which the 7SD is greater than 9 is `1999` which should yield 11. Here are some other larger examples:

```
n          7SD
1999        11
12345        1
999999      14
5699999     15
8765210248   1

```

# Answer
> 8 votes
# Jelly, ~~25~~ ~~22~~ ~~21~~ 20 bytes

```
‘DṁDḟ"DFị9979482ḃ5¤S

```

Try it online! or verify all test cases.

### Background

We first increment the input **n** and discard all digits of **n + 1** that haven't changed.

For example, if **n** is **5699999**, we get the following.

```
n     : 5700000
n + 1 : 5699999
Result:  700000

```

All digits in this result have a fixed number of segments that have to get toggled. We can convert the list of toggles to bijective base 5 to save some bytes.

```
digit:   1 2 3 4 5 6 7 8 9 0
toggles: 4 5 2 3 3 1 5 4 1 2

```

The output is simply the sum of the individual toggles.

This works for most values of **n**, but special care must be taken if **n + 1** has more digits than **n**. In this case, all digits must be **9**'s, and we solve this problem by chopping off a trailing **0** from **n + 1**.

For example, if **n** is **999999**, we get the following.

```
n     :  999999
n + 1 : 1000000
Result: 100000

```

This works because the leading **1** evaluates to **4** toggles (distance between **0** and **1**), while the actual amount of toggles is **2** (distance between **0** and **1**), and suppressing one trailing **0** removes its **2** toggles from the sum.

### How it works

```
‘DṁDḟ"DFị9979482ḃ5¤S  Main link. Argument: n

‘                     Compute n+1.
 D                    Convert n+1 from integer to base 10.
   D                  Convert n from integer to base 10.
  ṁ                   Mold the left result as the right result.
                      This chops of a 0 if n+1 has more digits than n.
    ḟ"D               Vectorized filter-false with the base 10 digits of n.
                      This removes the digits from n+1 that are identical to
                      the corresponding digits of n.
       F              Flatten the resulting list of lists.
         9979482ḃ5¤   Convert 9979482 to bijective base 5.
                      This yields [4, 5, 2, 3, 3, 1, 5, 4, 1, 2].
        ị             Retrieve the digits at the right that correspond to the
                      indices at the left.
                   S  Compute the sum of the results.

```

# Answer
> 10 votes
## JavaScript (ES6), ~~46~~ 40 bytes

```
f=n=>n?+"452331541"[n%10]||f(n/10|0)+2:2

```

Alternative formulation, also ~~46~~ 40 bytes:

```
f=n=>n?26523308>>n%10*3&7||f(n/10|0)+2:2

```

Edit: Saved 6 bytes thanks to @xsot.

# Answer
> 10 votes
# Python, 50 48 bytes

```
f=lambda n:26523308-0**n*2>>n%10*3&7or f(n/10)+2

```

## Explanation

This function operates on the least significant digit of the number `n`, summing the 7SD of the digits when incremented by one until after the first non-`9` digit.

`26523308` is a bitmask that encodes the mapping for the digits `0-8`. When `n=0`, which only occurs when `n` comprises only `9`s, the answer will be off by two. This is compensated by the expression `0**n*2`. As for the digit `9`, the bitmask evaluates to zero which will trigger the recursive call while adding `2` to the 7SD.

# Answer
> 8 votes
# 05AB1E, ~~31~~ ~~30~~ ~~28~~ ~~27~~ 26 bytes

Code:

```
9Ü©T%•2X›ùì•sè¹g®g-·¹Ú9Q·O

```

**Explanation** (*outdated*):

```
9Ü                              # Trim off trailing 9's
  ©                             # Copy this into the register
   T%                           # Get the last non-9 digit
     žh                         # Short for 0123456789
       •2X›ùì•§                 # Compressed version of 4523315412
               ‡                # Transliterate

```

We are changing the following to the last non-9 digit:

```
0 -> 4
1 -> 5
2 -> 2
3 -> 3
4 -> 3
5 -> 1
6 -> 5
7 -> 4
8 -> 1
9 -> 2

```

For the special cases:

```
                ¹g              # Get the length of the input
                  ®g            # Get the length of the input with all trailing 9 gone
                    -           # Substract, giving the number of 9's at the end of
                                  the input
                     2*         # Multiply by two
                       O        # Sum everything up
                        ¹Ú      # Uniquify the input
                          9Qi   # If this is equal to 9 (only 9's in the input)
                             Ì  #   Increment by 2 (_ -> 1)

```

Uses the **CP-1252** encoding. Try it online!.

28 byte alternative: `D[¤©•2X›ùì•sès®9Ê#¨]\rÚ9Q4*O`.

# Answer
> 5 votes
## Java, 63 bytes

The world is righted as Python passes Java once more.

Cause, ya know, Java.

```
int f(int n){return n>0?n%10<9?26523308>>n%10*3&7:2+f(n/10):2;}

```

See it on ideone

Maxes out at 2147483647, as that is Java's `Integer.MAX_VALUE`.

This is a port of my Python answer which is a port of the ES6 answer.

# Answer
> 3 votes
# MATL, ~~61~~ ~~39~~ 36 bytes

```
tQvV15\'3dAsMh818RG5'6Y27WZaw)Z}Z~Bz

```

**Try it online!**

### Explanation

```
tQv            % Implicit input. Duplicate, add 1, concatenate vertically
V              % Convert to 2D char array: each number in a row, possibly left-padded
               % with a space
15\            % Modulo 15. With modular indexing this corresponds to the order
               % '9', ' ', '0', '1', ..., '8'
'3dAsMh818RG5' % This string encodes active segments for each of the 11 chars
6Y2            % Source alphabet printable ASCII chars (predefined literal)
7W             % Target alphabet: [0 1 ... 127]
Za             % Base conversion: decode string into vector of 11 numbers, where each
               % number from 0 to 127 encodes the 7-segment representation of a digit,
               % in the order '9', ' ', '0', '1', ..., '8'
w              % Swap top two elements in stack
)              % Use as index. Gives 2-row array, where each column is a digit
Z}             % Split into the two rows
Z~             % Bitwise XOR, elementwise
B              % Convert to binary. Each number gives a row
z              % Number of nonzero elements. Implicitly display

```

# Answer
> 3 votes
# Julia, 44 bytes

```
!x=x<1?2:(t=x%10÷1)<9?3045058÷6^t%6:2+!.1x

```

Try it here.

Dennis saved a byte!

# Answer
> 3 votes
## Python, ~~71~~ 66 bytes

48 bytes by xsot. Even more magic maths!

```
f=lambda n:(2+f(n/10)if n%10==9else 26523308>>n%10*3&7)if n else 2

```

See it on ideone

Because the prior Python answer doesn't work and is far from optimal. A simple port of a previous ES6 version. Now using bit twiddling (from the ES6 alternate formulation) to cut out a cast!

Can be made to work with Python 3 by explicitly using floordiv for +1 byte.

# Answer
> 2 votes
# Pyth - ~~78~~ ~~30~~ 27 bytes

That first one was embarrassing.

```
s@LjC"
(J"ThC{I#.tjRThBQT

```

Test Suite.

# Answer
> 2 votes
# Jolf, 32 bytes

```
Ώ?H?<γ%Ht9P."452331541"γ+2Ώc/Ht2

```

Try it here!

## Explanation

This is a transpilation of Neil's answer.

```
Ώ?H?<γ%Ht9P."452331541"γ+2Ώc/Ht2
Ώ                                 define a function Ώ of H
 ?H                            2  (when H is zero, return is 2)
      %Ht                         H mod 10
     γ                            γ = ^
   ?<    9                        is it less than 9?
                                  if so:
           ."452331541"γ           get the γth element of that string
          P                        as a number
                                  else
                        +2         add two to
                          Ώ        Ώ over
                           c/Ht    int(H / 10)

```

# Answer
> 0 votes
# J, 53 bytes

```
2:`((2+10$:@<.@%~[)`(6|3045058<.@%6^])@.(9>])10&|)@.*

```

Originally based on @Neil's solution. Then improved by saving a byte using the same formula in @Lynn's solution.

The 54 byte version based on the string is

```
2:`((2+10$:@<.@%~[)`('452331541'".@{~])@.(9>])10&|)@.*

```

## Usage

```
   f =: 2:`((2+10$:@<.@%~[)`(6|3045058<.@%6^])@.(9>])10&|)@.*
   f 1999
11
   f 1999 12345 999999 5699999 8765210248
11 1 14 15 1

```

# Answer
> 0 votes
## Retina, 34 bytes

```
M!`.9*$
^9
0
T`d`4523315412
.
$*
.

```

Try it online! (The first line just allows the processing of multiple test cases at once.)

### Explanation

Like most answers have discovered by now, we don't need to use the full table, since only the least-significant non-`9` digit changes when incrementing. That's also how this answer works.

```
M!`.9*$

```

This matches (`M`) the regex `.9*$` i.e. the first digit that is only separated by `9`s from the end. The `!` tells Retina to replace the input with this match, discarding everything that doesn't affect the 7SD.

```
^9
0

```

If the input now starts with a `9` that means, the input itself consisted *only* of `9`s, so the 7-segment display needs to prepend a `1` which costs `2`. The simplest way to handle this is to replace the leading `9` in this case with a `0`, since the cost of incrementing a `9` (to `0`) is `2` and the cost of incrementing `0` (to `1`) is `4`, so this raises the overall cost by `2` as required.

```
T`d`4523315412

```

Now we have a transliteration stage which replaces each digit with its cost for incrementing it (since the `d` expands to `0123456789`). Note that this is the first subdiagonal of the 7SD table.

```
.
$*

```

This replaces each digit `n` with `n` copies of `1`, i.e. it converts each digit to unary, and since there are no separators immediately adds them together.

```
.

```

Finally, we count the number of characters (i.e. number of matches of `.`) in the result, which converts the unary sum back to decimal.

---
Tags: code-golf, number, counting
---


title: Counting Eisenstein primes

text:
# Question
Title: Counting Eisenstein primes
# Introduction

**Eisenstein integers** are complex numbers of the form

`a+bω`

Where `a,b` are integers, and

`ω = e^(2πi/3)`

The Eisenstein integers form a triangular lattice in the complex plane:

We say that an Eisenstein integer `z=a+bω` is **prime** if it cannot be written as the product of two non-unit (not 1,-1,ω,-ω,ω^2, or -ω^2) Eisenstein integers

# Program

**Input**: A natural number `n`.

**Output**: The number of Eisenstein primes which are of the form `a+bω` for which `a,b` are natural numbers (including zero) less than or equal to `n`

# Test Cases

0 → 0

1 → 0

2 → 5

3 → 9

4 → 13

5 → 20

# Scoring

This is `code-golf`, so least amount of bytes wins

# Answer
# Jelly, 24 bytes

```
Rð_²+×µ€µ³RḊm3,µÆP×1¦3FS

```

Roughly the same approach as my Julia answer.

```
                          Initial argument: n
R                           Compute [1, 2, …, n]
 ð_²+×                      (λ, ρ) —→ (λ − ρ)² + λρ (which is λ² − λρ + ρ²)
      µ€                    Zip with itself. Call this Q.

        µ                 Refocus argument: Q
         ³                  The initial argument n
          RḊm3              Compute candidate green line primes: [2, 5, 8, …, n]
              ,             Call this P. Make pair with argument.

               µ          Refocus argument: [P, Q]
                ÆP          Check primality
                  ×1¦3      Multiply the first element by 3
                      FS    Sum everything
                            (The result is 3·countprimes(P) + countprimes(Q))

```
> 1 votes

# Answer
# Julia, ~~66~~ ~~62~~ 60 bytes

```
!n=sum(isprime,[a<1<b%3?b:a^2-a*b+b^2for a=[0;0;0:n],b=0:n])

```

Try it online!

## Explanation

We’re interested in the primes in this parallelogram on the complex plane (example for **n = 4**):

We can split them into primes on the **green lines**, and on the **gray lines**.

Wikipedia tells me an Eisenstein number **z** is a **green line Eisenstein prime** iff **|z|** is a natural prime equal to **2** mod 3.

It also says **z** is a **gray line Eisenstein prime** iff **|z|² = a² − ab + b²** is a natural prime.

---

So we loop over **a = 0…n** and **b = 0…n**, and check:

* If **(a = 0 or b = 0 or a = b)** and **max(a, b) % 3 = 2**, then count whether **max(a, b)** is a prime.
* Else, count whether **a² − ab + b²** is a prime.

However, we can abuse the distribution’s symmetry. Instead of counting each green line once, we can just count one green line thrice! That is, only check **a = 0** and increment the counter by three when we find a green line prime. The `a=[0;0;0:n]` achieves exactly this.

Since we know we’re only considering the green line **a = 0**, we can replace **max(a, b)** by **b**.

The “green line condition” is nicely expressed in Julia using operator chaining: `a<1<b%3`.

(For the remaining green lines, we will never return a false positive: if **a = b** or **b = 0** then **a² − ab + b² = a²**, which can’t be prime.)

## Ideas

Maybe, instead of writing `a^2-a*b+b^2`, I can conditionally replace the exponent at `b` by `1` when `a<1<b%3` – then the expression reduces to `b`. This doesn’t seem to be shorter, but it’s neat!
> 8 votes

# Answer
## CJam (34 bytes)

```
qi,:)_2m*{_:*\:-_*+}%\1>3%3*+:mp1b

```

Online demo
> 1 votes

---
Tags: code-golf, primes, hexagonal-grid, complex-numbers
---


title: ¡ǝƃuǝןןɐɥɔ uʍop ǝpısdn

text:
# Question
Title: ¡ǝƃuǝןןɐɥɔ uʍop ǝpısdn
Turn the characters `abcdefghijklmnopqrstuvwxyz!?.,` upside down and don't modify the other characters. Then, reverse the text to achieve the upside down affect. If text is already upside down, turn it right side up. Don't modify capitals.

Use this as a reference:

```
abcdefghijklmnopqrstuvwxyz!?.,
ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz¡¿˙'

```

## Rules

* Newlines must be supported
* You only have to convert the above character set.
* **Don't forget you need to reverse the characters.**
* This question is symmetrical unlike Small Caps Converter.

## Test cases

```
42 is the meaning of life -> ǝɟıן ɟo ƃuıuɐǝɯ ǝɥʇ sı 24
halp why is my keyboard typing upside down??? :( -> (: ¿¿¿uʍop ǝpısdn ƃuıdʎʇ pɹɐoqʎǝʞ ʎɯ sı ʎɥʍ dןɐɥ
lol -> ןoן
uoɥʇʎpʎzɐɹc -> ɔrazydython

```

Look at my username!

# Answer
# Ruby, 78 bytes

I need to use an actual byte counter more often

```
->s{s.reverse.tr'a-z!?.,',"ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz¡¿˙'"}

```

Try it online
> 3 votes

# Answer
# Retina, 73 bytes (54 chars)

Translate the chars, then reverse the input. I was pretty confused while making this until I realized some of the chars need to be escaped.

```
T`ɐqɔ\pǝɟƃɥıɾʞןɯu\o\dbɹsʇnʌʍxʎz¡¿˙'l!?.,`l!?.,o
O$^s`.

```

**Try it online!**
> 3 votes

# Answer
# Pyth, 59 bytes

```
X_z+G"!?.,'˙¿¡zʎxʍʌnʇsɹbdouɯןʞɾıɥƃɟǝpɔqɐ

```

Test suite.

Obligatory hexdump:

```
58 5F 7A 2B 47 22 21 3F 2E 2C 27 CB 99 C2 BF C2
A1 7A CA 8E 78 CA 8D CA 8C 6E CA 87 73 C9 B9 62
64 6F 75 C9 AF D7 9F CA 9E C9 BE C4 B1 C9 A5 C6
83 C9 9F C7 9D 70 C9 94 71 C9 90

```
> 2 votes

# Answer
## Python 3, 144 bytes

Don't work in the Windows terminal...

```
print(''.join([dict(zip("abcdefghijklmnopqrstuvwxyz!?.,","ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz¡¿˙'")).get(x,x)for x in input()[::-1]]))

```
> 2 votes

# Answer
## JavaScript (ES6), 140 bytes

```
f=
s=>[...s].map(c=>r=((i=u.indexOf(c)+26)<26?c:u[i%52])+r,r="",u="abcdefghijklmnpqrtuvwy!?.,ɐqɔpǝɟƃɥıɾʞןɯudbɹʇnʌʍʎ¡¿˙'")&&r
;
```

```
<input oninput=o.value=f(this.value)><input id=o style=text-align:right>
```

Edit: Saved 8 bytes thanks to @Dúthomhas.
> 2 votes

# Answer
## Perl, 88 bytes

**78 bytes code + 10 for `-Mutf8 -n`**

```
y/a-z!?.,/ɐqɔpǝɟƃɥıɾʞןɯuodbɹsʇnʌʍxʎz¡¿˙'/;print reverse/./g

```

### Usage

Save as upsidedown.pl and run:

```
perl -Mutf8 -n upsidedown.pl <<< '42 is the meaning of life'
ǝɟıן ɟo ƃuıuɐǝɯ ǝɥʇ sı 24

```
> 1 votes

---
Tags: code-golf
---


title: Output the answer above yours

text:
# Question
Title: Output the answer above yours
Write a program that outputs the contents of the first HTML `<code>...</code>` block of the answer to this question that is just above yours when the answers are sorted by votes. Output `Top!` if you are the top answer.

Ignore answers that have negative votes or no `<code>...</code>` tags. The source of your program must appear in the first `<code>...</code>` block in your post. These blocks are created automatically when you `use backticks` or

```
indent things with 4 spaces.

```

This is code-golf, the answer with the fewest characters wins.

**Additional Rules (Updated)**

* Answer in any programming language you want but if you answer multiple times use different languages.
* You may not hard code your output. Your program's ability to run correctly should not depend on it's vote count or on what the answer above is. If the vote distribution changed drastically your program should still correctly output the code of the answer above it.
* You *may* hard code your program to search for itself on this page (so as to find the next highest) via some unique property of your answer, such as your username (if you only have one answer) or the answer's direct link.
* If two answers have equal votes you should still use the one just above yours (which I believe will be the newest one).
* You may have multiple `<code>...</code>` blocks in your answer but the first one must contain your program's source.

# Answer
> 5 votes
# Javascript + jQuery (~~92~~ ~~86~~ 64 char)

**To test, open Dev Tools on *this* page (usually F12), and run my code!**

This Javscript needs to be run using the console from this page (and only this page).

```
alert($("code",$("#answer-34767").prev().prev()).html()||"Top!")

```

So short, it doesn't even need a scrollbar!

Basically, it finds my answer by ID, and then gets two nodes ahead (skipping the anchor link). If that does not exist, I must be on top. Then it digs down to the first `code` element and gets it's `.innerHTML`.

The nice thing is that SE uses jQuery by default, so I get that advantage without even trying.

# Answer
> 6 votes
## PHP 666 611 593 588 580 Characters

Edit: Used even smaller url than previously from tinyurl.

Edit: Following comment on other answer I used int rather than boolean. Also needed to correct an error that became apparent but fixed now.

Here is my code

```
<?
$a=34727;$b=new DOMDocument();$b->loadHTMLFile("http://turl.no/t2u");$c=$b->saveHTML();$d=$e=1;$f='data-answerid="';$g=strpos($c,$f);$h=substr($c,0,$g);$c=substr($c,($g+15));while($d==1){$g=strpos($c,'"');$i=substr($c,0,$g);if($i==$a){$j=$h;$k=$e;}$g=strpos($c,'vote-count-post ">');$c=substr($c,($g+18));$g=strpos($c,'<');$l=substr($c,0,$g);$g=strpos($c,'data-answerid="');if($g){++$e;++$e;$h=substr($c,0,$g);$c=substr($c,($g+15));}else{$d=2;}}if($k==1){echo 'Top!';}else{$g=strpos($j,'><code>');$m=strpos($j,'</code></pre>');$n=$m-$g-7;$o=substr($j,($g+7),$n);echo nl2br($o);}

```

I am sure this can be improved using DOMXPath and nodes. However am quite pleased with it. I could not decide what to do in the case of mine is the only answer but with -ve points so ignored. However another answer was posted so not a problem any more.

I also used tinyurl to shorten the url, saving lots of characters.

I hope you like it,

Paul.

PS This will not run in codepad so can't show a fiddle.

Edit: saved 5 more with the php tags being altered

You can see it working here on a domain I do not currently use (so am not just trying a sneaky link). This is not a permanent link though but is currently available.

# Answer
> 4 votes
# Delphi (~~688 873 859 848~~ 840)

I will still try to shave off some characters but it will do the job :)

**Edit:** instead of getting it shorter I made it longer :P
I forgot to add in the ignoring of answers when it has a negative votecount or no code blocks.

I'm just updating the un-golfed version while editing.
Thanks to @manatwork for the suggested edits that took off 8 characters.

### Golfed version:

```
uses IdHTTP,Classes,MSHTML;const u='http://codegolf.stackexchange.com/questions/34705/output-the-answer-above-yours/34718#34718';var g:TIdHTTP;m:TMemoryStream;l:TStringList;p,t,r,o:OleVariant;s,i,j:int32;c:boolean;begin L:=TStringList.Create;g:=TIdHTTP.Create(nil);m:=TMemoryStream.Create;g.Get(u,m);m.Position:=0;L.LoadFromStream(m);p:=coHTMLDocument.Create as IHTMLDocument2;p.write(l.Text);for I:=0to p.body.all.length-1do begin c:=0>1;t:=p.body.all.item(i);if(t.classname='answer')and(t.id='answer-34718')then if s=0 then writeln('Top!') else for j:=0to o.all.length-1do begin t:=o.all.item(j);if t.tagname='CODE'then writeln(t.innertext);end else if t.classname='answer'then begin for j:=0to t.all.length-1do begin r:=t.all.item(j);if r.tagname='CODE'then c:=1>0 else if c and(r.class='vote-count-post')and(r.innertext[1]<>'-')then begin o:=t;s:=1;end;end;end;end;end.

```

### Ungolfed version:

```
uses
  IdHTTP,Classes,MSHTML;
const
  u='http://codegolf.stackexchange.com/questions/34705/output-the-answer-above-yours/34718';
  a='answer';b='CODE';
var
  g:TIdHTTP;
  m:TMemoryStream;
  l:TStrings;
  p,t,r,o,z:OleVariant;
  s,i,j:int32;
  c:byte;
begin
  L:=TStringList.Create;
  g:=TIdHTTP.Create(nil);
  m:=TMemoryStream.Create;
  g.Get(u,m);
  m.Position:=0;
  L.LoadFromStream(m);
  p:=coHTMLDocument.Create as IHTMLDocument2;
  p.write(l.Text);
  z:=p.body.all;
  for I:=0to z.length-1do
  begin
    c:=0;
    t:=z.item(i);
    if(t.classname=a)and(t.id='answer-34718')then
      if s=0 then
        write('Top!')
      else
        for j:=0to o.all.length-1do
        begin
          t:=o.all.item(j);
          if t.tagname=b then
            write(t.innertext)
        end
    else if t.classname=a then
      for j:=0to t.all.length-1do
      begin
        r:=t.all.item(j);
        if r.tagname=b then
          c:=1
        else if(c=1)and(r.class='vote-count-post')and(r.innertext[1]<>'-')then
        begin
          o:=t;
          s:=1;
        end;
      end;
  end;
end.

```

# Answer
> 4 votes
## Dart 412 403

```
import"dart:io";import"dart:convert";main(){new HttpClient().get("pi.vu",0,"BYga").then((v)=>v.close()).then((r)=>r.transform(UTF8.decoder).join()).then((s,[i,c="Top!"])=>new RegExp(r'<div id="answer-(\d+)[^]*?vote-count-post ">(\d+)[^]*?<table class="fw"').allMatches(s).forEach((m)=>m[1]=="34735"?print(c):m[2][0]!='-'&&(i=(s=m[0]).indexOf("<code>"))>0?c=s.substring(i+6,s.indexOf("</code>",i)):0));}

```

Ungolfed (well, with newlines and leading whitespace)

```
import"dart:io";
import"dart:convert";
main(){
  new HttpClient().get("pi.vu",0,"BYga")
  .then((v)=>v.close())
  .then((r)=>r.transform(UTF8.decoder).join())
  .then((s,[i,c="Top!"])=>
      new RegExp(r'<div id="answer-(\d+)[^]*?vote-count-post ">(\d+)[^]*?<table class="fw"')
      .allMatches(s)
      .forEach((m)=>
          m[1]=="34735"?print(c)
                       :m[2][0]!='-'&&(i=(s=m[0]).indexOf("<code>"))>0
                           ?c=s.substring(i+6,s.indexOf("</code>",i)):0
  ));
}

```

# Answer
> 3 votes
**Python - 280**

```
import os, sys, cgi
os.system('wget http://codegolf.stackexchange.com/questions/34705/output-the-answer-above-yours.html -q -O a')
b=[ x[:-2] for x in open('a').read().split('code>') if x[-1]=='/']
for i, m in enumerate(b):
    if m == cgi.escape(open(sys.argv[0]).read()):
        print b[i-1]

```

This is my first codegolf, so I hope this is golf-y enough!

Edit: Thanks for the tips! It's looking a bit golfier now.

# Answer
> 2 votes
# Mathematica - 159

First time doing parsing in Mathematica

```
FirstCase[
 Cases[Import["http://bit.do/JGta1","XMLObject"],
 {__,a_,_,_,_,XMLElement[_, {_, "id""answer-34780",__},_],__}a,∞],
 XMLElement["code",_,{c_}]c,"Top!",∞]

```

# Answer
> 2 votes
## Ruby 283+17 = 300

This succeeds regardless how few votes this answer gets and no matter if there's a second (or fifteenth) page of answers or not. It uses the data API.

```
d=34849
JSON.parse(Net::HTTP.get(URI("http://api.stackexchange.com/2.2/questions/34705/answers?site=codegolf&filter=8G3Ng9T*")))['items'].map{|a|abort$1.gsub(/&.+?;/){|g|g[?a]??&:g[?g]??>:?<}if !d&&a['score']>=0&&/<code>(.*?)<\/code>/m=~a['body']
d=p if a['answer_id']==d}
$><<'Top!'

```

must be run with `ruby -rnet/http -rjson` (hence the +17)

ungolfed:

```
d = 34849 # this answer id
i = JSON.parse(Net::HTTP.get(URI("http://api.stackexchange.com/2.2/questions/34705/answers?site=codegolf&filter=8G3Ng9T*")))['items'] # stackexchange api answers for this question
i.map{ |a|
  # if we've already hit this answer, the score's above 0 and there's code...
  if !d && a['score']>=0 && /<code>(.*?)<\/code>/m=~a['body'] then
    # abort with html-unescaped code
    abort $1.gsub(/&.+?;/){ |g|
      # this turns &, > and < into &, > and <, respectively
      g[?a] ? ?& : g[?g] ? ?> : ?<
    }
  end
  # if we are at our answer, set d = nil
  if a['answer_id']==d then
    d = p
  end
}
# no abort. puts 'Top!'
$><<'Top!'

```

### Changelog

**300** removed parens in symbol regex

**302** initial commit

# Answer
> 2 votes
# Python 3, ~~197 191~~ 186 bytes

```
import urllib.request as u,gzip,json;p='Top!'
for r in json.loads(gzip.decompress(u.urlopen("https://bit.ly/Ƶ").read()).decode())["items"]:
 if r['answer_id']==82837:exit(p)
 p=r['body']

```

The rules don't say that I can't use the API and that I can't use a url shortener.

`https://bit.ly/Ƶ` expands to `https://api.stackexchange.com/2.2/questions/34705/answers?order=desc&sort=votes&site=codegolf&filter=withbody&pagesize=100` This only works if it is in the top 100 answers sorted by votes.

# Answer
> 1 votes
## PHP - 412 \- 422 \- 416 \- 252 \- 248:

Still a work in progress, I haven't done anything regarding multiple pages (nor has anyone else?)

I got the 200 character drop by cutting out a lot of extra dom, why search for objects when I can just find their position?

This is also my first code golf! I'm happy to have done it in the 200s and using dom methods. Thanks to comments, I just shaved off 4 more characters.

I wanted to do something like jquery/jscript in regards to traversing the dom, and am still working on slimming this down. Maybe I could get away with searching for "asi" as my user name?

Golf:

```
<? $d=new DOMDocument;$d->loadHTMLFile("http://bit.do/JGta");$x=new DOMXPath($d);$r=$x->query("//*[@class='answer']");$a=-1;while($f=$r->item(++$a))if(strpos($f->nodeValue,"Asitaka"))echo$x->query(".//pre//code",$r->item($a-1))->item(0)->nodeValue;

```

Formatted:

```
    <?php
$d = new DOMDocument();
$d->loadHTMLFile("http://bit.do/JGta");
$x = new DOMXPath($d);
$r = $x->query("//*[@class='answer']");
$a = -1;
while($f = $r->item(++$a))
        if ( stripos($f->nodeValue, "Asitaka")!= 0)
            echo $x->query(".//pre//code",$r->item($a-1))->item(0)->nodeValue;
?>

```

Cheers

# Answer
> 1 votes
# PHP 135

```
<?
preg_match_all('@(\d+?)"></a.*de>(.*)</c@Us',join('
',file('http://pi.vu/BYga')),$m);echo$m[2][array_search(34786,$m[1])-1]?:'Top!';

```

**Edit:** lrn's URL shortener produces the shortest URL :)

The RegEx matches the anchor before each answer (together with the answer ID) and the contents inside the first `<code>` tag. The `U` flag triggers the `U`ngreedy mode and the `s` flag make `.` matches new lines (very handful). I'm not worried if this matches something else as the answers are escaped, so nobody can insert the `<` literal in the page's source.

After I get all the answers in `$m[2]` and their IDs in `$m[1]`, I just use `echo` to print the answer above mine, as it's in `$m[2][array_search(34786,$m[1])-1]`, or "Top!", if my answer eventually gets first :)

I like the fact that in PHP the ternary operator can be used as a short-circuit operator `?:`

# Answer
> 1 votes
## Delphi, ~~461 bytes~~, 553 bytes

*Now handles multiple pages too!*

Golfed:

```
uses IdHTTP,RegularExpressions;var T,S,O:String;K,V,C:Int32;begin repeat Inc(C);Str(C,S);S:=TIdHTTP.Create.Get('http://codegolf.stackexchange.com/questions/34705/output-the-answer-above-yours?page='+S);T:=T+S;until Pos('<span class="page-numbers next',S)=0;O:='Top!';for T in TRegEx.Split(T,'<a name="') do begin S:=T;Val(Copy(S,1,Pos('"',S)-1),K,C);if C=1then Continue;Delete(S,1,Pos('post ">',S)+6);Val(Copy(S,1,Pos('<',S)-1),V,C);C:=Pos('<code>',S);if(C=0)or(V<0)then Continue;if K=34844then Break;O:=Copy(S,C+6,Pos('</code>',S)-C-6);end;Write(O)end.

```

(slightly) Ungolfed:

```
uses
  IdHTTP,RegularExpressions;
var
  T,S,O:String;
  K,V,C:Int32;
begin
  // download all pages in thread and concat them
  repeat
    Inc(C);
    Str(C,S);
    S:=TIdHTTP.Create.Get('http://codegolf.stackexchange.com/questions/34705/output-the-answer-above-yours?page='+S);
    T:=T+S;
  until Pos('<span class="page-numbers next',S)=0;
  O:='Top!'; // initialize code string to 'Top!'
  for T in TRegEx.Split(T,'<a name="') do begin
    S:=T;
    Val(Copy(S,1,Pos('"',S)-1),K,C); // try to extract user id
    if C=1then Continue; // if failed, continue loop
    Delete(S,1,Pos('post ">',S)+6); // prepare S for next parse
    Val(Copy(S,1,Pos('<',S)-1),V,C); // try to extract vote count
    C:=Pos('<code>',S); // check if <code> tag exists
    if(C=0)or(V<0)then Continue; // make sure vote count is positive and <code> tag exists
    if K=34844then Break; // if its our answer, break the loop
    O:=Copy(S,C+6,Pos('</code>',S)-C-6); // get string in <code> tag
  end;
  Write(O); // write <code> string
end.

```

How to run:

```
app.exe > output.txt

```

---
Tags: code-golf
---


title: Cities: Sightlines

text:
# Question
Title: Cities: Sightlines
I'm at position **(0, 0)** of an infinite two-dimensional city, which is perfectly divided into blocks centered at each lattice point, some of which contain buildings. A building at a certain point **(x, y)** takes up the entire square with opposite corners at **(x-.5, y-.5)** and **(x+.5, y+.5)**, including its border. A building is visible iff there is some line segment from **(0, 0)** to a point in the building which does not intersect any other building.

For example, I (the `@`) can see 6 buildings (`*`) in the following city:

```
  *
 *
*
*@
x**
 *  y

```

I can't see the building marked with an `x`, at **(-1, -1)** because it's obstructed by the two adjacent to it; or the one marked with a `y` at **(3, -2)** because it's obstructed by the edge of the **(1, -1)** building.

### Input

A multiline string, or list of lines, optionally padded with spaces into a rectangle. It will contain only:

* a single `@` (my position)
* Spaces
* `*`, which represent buildings.

There will always be at least one building, and therefore at least one visible building.

### Output

The number of visible buildings.

### Test cases

```
*@
1

* *******
 @     *
7

*****
**@**
*****
4

   *
  **
@ **
2

*      *
 *    *
@
4

@
 *
  ***
1

```

<sub>*Thanks to @Geobits for the title.*</sub>

# Answer
# Unity + C#, 589 bytes

This is probably the worst language to do a code golf in (read: worse than Java), but Unity comes with a lot a helpful features for this challenge.

EDIT: missed a couple of spaces, returns list length, not counter

Golfed:

```
using UnityEngine;using System.Collections;public class c:MonoBehaviour{public int h(string[]i){ArrayList k=new ArrayList();for(int y=0;y<i.Length;y++){char[]l=i[y].ToCharArray();int x=0;foreach(char c in l){if(c=='*'){GameObject b=GameObject.CreatePrimitive(PrimitiveType.Cube);b.transform.position=new Vector3(x,y);}if(c=='@')transform.position=new Vector3(x,y);x++;}}for(int n=0;n<3600;n++){RaycastHit h;Physics.Raycast(transform.position,Quaternion.Euler(0,0,n/10)*Vector3.up,out h);if(h.collider!=null){GameObject o=h.collider.gameObject;if(!k.Contains(o))k.Add(o);}}return k.Count;}}

```

Ungolfed:

```
using UnityEngine;
using System.Collections;

public class citiessightlines : MonoBehaviour {

    public ArrayList todelete;   // Anything concerning this array just has to do with cleanup of
                                 //objects for testing, and doesn't contribute to the byte count.
    void Start()
    {
        todelete = new ArrayList();
    }
    public int calcSight(string[]input)
    {
        todelete = new ArrayList();
        int total = 0;
        ArrayList check = new ArrayList();
        for (int y=0;y < input.Length; y++)
        {
            char[] line = input[y].ToCharArray();
            for (int x = 0; x < line.Length; x++)
            {
                char c = line[x];
                if (c == '*')
                {
                    GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    cube.transform.position = new Vector3(x, y);
                    todelete.Add(cube);
                }
                if (c == '@')
                {
                    transform.position = new Vector3(x, y);
                }
            }
        }
        for (int angle=0; angle < 3600; angle++)
        {
            RaycastHit hit;
            Physics.Raycast(transform.position, Quaternion.Euler(0, 0, angle/10) * Vector3.up, out hit);
            if (hit.collider!=null)
            {
                GameObject hitObject = hit.collider.gameObject;
                if (!check.Contains(hitObject)&&hitObject!=this)
                {
                    total += 1;
                    check.Add(hitObject);
                }
           }
        }
        return total;
    }
}

```

I used 3600 raycasts because it fails the 5th test case with lower. It still might fail for even larger/more precise test cases.

Unfortunately, both webgl and desktop builds seem to break, so all I have is the source code to test with on github.
> 4 votes

# Answer
## Java 8 lambda, ~~1506~~ ~~1002~~ ~~972~~ 942 characters

I wanted to beat this challenge, as it is very interesting. The result ~~(not very golfy)~~ can be seen here:

```
import java.util.*;f->{Set<double[]>B=new HashSet(),r,n;double a,M,m,P=Math.PI*2,z=.5;int x=0,y,v=0,i,j,c[],p,q,l=g.length;for(;x<l;x++)for(y=0;y<g[x].length;y++)if(g[x][y]>63)for(;;){c=new int[]{-1};M=2e31-1;for(i=0;i<l;i++)for(j=0;j<g[i].length;j++)if(g[i][j]==42)if((m=(p=x-i)*p+(q=y-j)*q)<M){M=m;c=new int[]{i,j};}if(c[0]<0)break;g[c[0]][c[1]]=0;double[]A={(a=Math.atan2((c[1]-=y)-z,(c[0]-=x)-z))<0?a+P:a,(a=Math.atan2(c[1]+z,c[0]-z))<0?a+P:a,(a=Math.atan2(c[1]+z,c[0]+z))<0?a+P:a,(a=Math.atan2(c[1]-z,c[0]+z))<0?a+P:a};r=new HashSet();M=-P;m=P;for(double d:A){M=d>M?d:M;m=d<m?d:m;}r.add(new double[]{m,M});for(double[]t:B){n=new HashSet();for(double[]h:r)for(double[]u:t[0]<h[0]?t[1]<h[0]?new double[][]{h}:t[1]<h[1]?new double[][]{{t[1],h[1]}}:new double[0][]:t[0]>h[1]?new double[][]{h}:t[1]>h[1]?new double[][]{{h[0],t[0]}}:new double[][]{{h[0],t[0]},{t[1],h[1]}})if(u[0]<u[1])n.add(u);r=n;}B.addAll(r);if(!r.isEmpty())v++;}return v;}

```

Of course this also exists in the ungolfed version:

```
import java.util.*;

public class AngleCheck {

    static int getViewableBuildingsC(char[][] grid) {

        Set<double[]> blocked = new HashSet(), ranges, newRanges;

        double angle, max, min, PI2 = Math.PI * 2, half = 0.5;

        int x = 0, y, viewable = 0, i, j, building[], dX, dY, length = grid.length;

        for (; x < length; x++) {
            for (y = 0; y < grid[x].length; y++) {
                if (grid[x][y] > 63) {
                    for (;;) {
                        building = new int[]{-1};
                        max = 2e31-1;
                        for (i = 0; i < length; i++) {
                            for (j = 0; j < grid[i].length; j++) {
                                if (grid[i][j] == 42) {
                                    if ((min = (dX = x - i) * dX + (dY = y - j) * dY) < max) {
                                        max = min;
                                        building = new int[]{i, j};
                                    }
                                }
                            }
                        }

                        if (building[0] < 0)
                            break;

                        grid[building[0]][building[1]] = 0;
                        double[] angles = {
                                        (angle = Math.atan2((building[1] -= y) - half, (building[0] -= x) - half)) < 0 ? angle + PI2 : angle,
                                        (angle = Math.atan2(building[1] + half, building[0] - half)) < 0 ? angle + PI2 : angle,
                                        (angle = Math.atan2(building[1] + half, building[0] + half)) < 0 ? angle + PI2 : angle,
                                        (angle = Math.atan2(building[1] - half, building[0] + half)) < 0 ? angle + PI2 : angle};

                        ranges = new HashSet();

                        max = -PI2;
                        min = PI2;
                        for (double d : angles) {
                            max = d > max ? d : max;
                            min = d < min ? d : min;
                        }

                        ranges.add(new double[]{min, max});

                        for (double[] reference : blocked) {
                            newRanges = new HashSet();
                            for (double[] currentRange : ranges) {
                                for (double[] subRange : reference[0] < currentRange[0] ?
                                            reference[1] < currentRange[0] ?
                                                // whole range after referencerange
                                                new double[][]{currentRange}
                                            :
                                                reference[1] < currentRange[1] ?
                                                    // lower bound inside referencerange, but upper bound outside
                                                    new double[][]{{reference[1], currentRange[1]}}
                                                :
                                                    // whole range inside referencerange -> nothing free
                                                    new double[0][]
                                        :
                                            // greater or equal lower bound
                                            reference[0] > currentRange[1] ?
                                                // whole range before referencerange
                                                new double[][]{currentRange}
                                            :
                                                // ranges overlap
                                                reference[1] > currentRange[1] ?
                                                    // range starts before and ends in reference range
                                                    new double[][]{{currentRange[0], reference[0]}}
                                                :
                                                    // referencerange is in the range -> two free parts, one before, one after this
                                                    new double[][]{{currentRange[0], reference[0]}, {reference[1], currentRange[1]}}) {
                                    if (subRange[0] < subRange[1])
                                        newRanges.add(subRange);
                                }
                            }
                            ranges = newRanges;
                        }

                        blocked.addAll(ranges);
                        if (!ranges.isEmpty()) {
                            viewable++;
                        }
                    }
                }
            }
        }
        return viewable;
    }
}

```

So it looks very difficult but it's way easier than one might think. My first idea was to use some intersection algorithm to check whether a line from my position to the building can be made without any intersections. To do this I decided to use the Cohen-Sutherland algorithm and draw lines to all four corners of the building. This worked pretty well for the first tests, but the last one failed. I soon found out, that it's a case where you can't see the corners but a part of an edge. So I thought about some sort of ray casting like @Blue did it. I put that challenge away, as I didn't got some progress. Then I saw Blue's answer and the following simple idea came to my mind: Each building blocks some angle in which nothing else can be seen. I just need to keep track of what can be seen and what is already hidden by other buildings. That's it!

The algorithm works as follows: It determines the building with the smallest distance to the person. Then we imagine four lines drawn from the person to the corners of the building. Two of these have an extreme value: The minimum and maximum angle in which the building can be seen. We take them as a range and compare them with other buildings of which we know that they can be seen (none at the beginning). The ranges may overlap, include each other or don't touch at all. I compare the ranges and get some new ranges of the building which aren't hidden by the viewable buildings. If there is something remaining after comparing it with the buildings in-sight the building is also viewable. We add the remaining angle range to the list of ranges to compare to and start off with the next building with the next longer distance.

Sometimes the ranges may overlap in a way that I end up with a range of 0 degrees. These ranges will be filtered to don't mistakenly add a building that isn't even viewable.

I hope someone understood this explanation :)

~~I know this code isn't golfed very much, I'll do this asap.~~

That was a really challenging task. You thought you found a solution that works but instead you are far away still. I think this solution works pretty good. It isn't very fast but at least it works ;) Thanks for that puzzle!

---

**Update**

I found the time to golf the whole thing down into a single function, which thus can be turned into a lambda. All functions were only called once and thus can be put into one method. I switched from lists to sets as this saves some additional characters. The declarations have been put together. The comparisons have been put together and characters were replaced by there ascii value. The range comparing can be expressed as many ternaries. Some tricks here and there to prevent long expressions like Double.NEGATIVE\_INFINITY got done. Where possible inline assigments are done. To save a bit more I switched from comparing the angles in degrees to comparing the radians. The whole change saved over 500 characters, I hope to get it all under 1000 though ;)

I removed the generics where possible and shortened the return comparison by creating an one element array and check it's value instead. I also replaced the Double.NEGATIVE\_INFINITY with PI2 and -PI2 as these are the upper and lower bounds of the angles. Now it's finally under 1000 chars long!

I merged the loops for finding the persons location and the building iterator to save some characters. Unfortunately this requires us to move the return out of the loop and still use a break but this time without a label. I merged `max` and `distanceSquared` and `min` and `newDistanceSquared` as they aren't required at the same time. I changed `Integer.MAX_VALUE` to `2e31-1`. Also I created a constant `half = 0.5` which is used to calculate the corners of the building. This is shorter in the golfed version. Overall we saved another 30 characters!
> 3 votes

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


title: OMG! We're Twinning!

text:
# Question
Title: OMG! We're Twinning!
# Introduction

We define **twin primes** as two natural numbers `p,p+2` which both are prime.

***Example***: `5` and `7` are twin primes.

Let's define the *twin number* of some set of numbers as the number of twin prime numbers in that set

***Example***: {`6`,`7`,`11`,`13`,`18`,`29`,`31`} has a twin number `4`, since there are four twin primes; `11,13` and `29,31`.

# Program

**Input**: A number `n`

**Output**: The twin number of the set of all **natural** numbers below `n`

# Scoring

This is , so lowest bytes wins.

# Answer
> 2 votes
# MATL, 7 bytes

```
qZqd2=s

```

This solution exploits the fact that the prime gap (the difference between successsive prime numbers) is always \>= 2 (with the exception being the gap between 2 and 3). Because of this fact, all *twin primes* will be successive prime numbers. In this solution we just compute the differences between all primes less than the input `n` and count how many of these differences are equal to 2.

**Try it Online**

**Explanation**

```
    % Implicitly grab input, N
q   % Subtract one from the input (N-1)
Zq  % Get an array of all primes <= (N-1)
d   % Compute successive differences (prime gaps)
2=  % Create a boolean array indicating which prime gaps are equal to 2
s   % Count the TRUE values in this array to determine the twin number
    % Implicitly display the result

```

If you instead want the *not* the number of pairs but the number of primes that are *part of a pair*, the following would work

```
qZqt!-|H=az

```

**Try it Online**

# Answer
> 1 votes
# Jolf, 10 bytes

```
ZlZd~Bx©{2

```

Try it here!

## Explanation

```
ZlZd~Bx©{2
    ~B     all numbers satisfying
       ©{  the prime condition ("the prime directive"?)
      x    below x
  Zd       (the differences between indices)
Zl       2 count the number of 2's

```

# Answer
> 1 votes
# Ruby, 43 + 8 (`-rprime` flag) = 51 bytes

```
->n{Prime.each(n-1).count{|i|(i-2).prime?}}

```

# Answer
> 0 votes
# Perl 6,  ~~54~~  53 bytes

```
~~{2*(3..$_).rotor(3=>-1).grep: {all .[0,2]».is-prime}}~~
{2*(3,5...$_).rotor(2=>-1).grep: {all $_».is-prime}}
```

### Explanation:

```
{
  2
  *
  (3,5...$_)        # odd numbers
  .rotor( 2 => -1 ) # grab 2 then backup one, repeat
  .grep:            # find all that match the following
    {
      # create a Junction object of the following
      all

        # call .is-prime on both elements of the
        # list given to this inner block
        $_».is-prime
    }
}

```

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


title: A Hundred Squares!

text:
# Question
Title: A Hundred Squares!
### Back to basics...

As a teacher at the local primary (grade?) school, you need a way to teach your class their times tables. At your disposal, you have hundred squares and a load of red pens. You need to also be able to show your class the correct answers quickly.

Now, you're clever enough to write a program that can do times tables, but can you draw them on a hundred square?

# The challenge

Output a hundred square to stdout or equivalent using ansi-escape codes to shade in numbers which are multiples of the input.

* Output a 10x10 grid containing the numbers 1-100.
    + It doesn't matter the alignment of 2 digit numbers in each box as long as it's consistant
    + For 1 digit numbers, you may pad to 2 digits and use the same formatting as 2 digit numbers or centered in the middle of the box.
* If the number in the box is a multiple of the input, colour the entire box red.
    + This means the whole box, not just the number part

For example, given the input `3`, print the given hundred square

**This is code golf so the shortest answer in bytes wins!**

# Answer
# Python 2, 166 bytes

```
R=range;n=input()
for y in R(21):print''.join('♥[%dm%s♥[m'%(any(5>x-k%10*4>-1<y-k/10*2<3for k in R(n-1,100,n))*41,('+---|%2d '%(x/4+y*5-4))[y%2*4+x%4])for x in R(41))

```

Replace  by octal `033` (the ANSI escape character).

## Explanation

We treat the output as a `41×21` grid, and directly compute the character and color at each point.

That is, the structure of the code is:

```
n = input()
for y in range(21):
    print ''.join(F(x, y) for x in range(41))

```

for some function `F`.

The result of `F` is always of the following form:

> * An ANSI *Control Sequence Introducer* (`\33[`).
> * An SGR code: `0m` for reset, or `41m` for red background.
> * A single character. (`+`, `-`, `|`, space, or digit)
> * An SGR reset sequence (`\33[m`).

We use the format string `'\33[%dm%s\33[m'`, where the first `%d` is either 0 or 41, and the `%s` is the character we wish to print.

---

For the **color**, we have the following formula:

```
any(5>x-k%10*4>-1<y-k/10*2<3for k in R(n-1,100,n))*41

```

I’m not going to fully explain this, but it basically loops over all rectangles that should be colored red, and checks if `(x, y)` is inside any of them.

Note the use of operator chaining: I rewrote `-1<A<5 and -1<B<3` into `5>A>-1<B<3`.

---

For the **character**, we have the following formula:

```
('+---|%2d '%(x/4+y*5-4))[y%2*4+x%4]

```

If `y % 2 == 0` then for `x = 0, 1, …` this will generate `+---+---+---…`

If `y % 2 == 1` then for `x = 0, 1, …` this will generate `| p |p+1|p+2…`
> 8 votes

# Answer
# Julia, ~~219~~ ~~182~~ ~~169~~ 167 bytes

```
!n=(~j=j%n<1;k(v=j->"---",c=+,s="$c\e[m";l=~)=println([(l(j)?"\e[;;41m$c":s)v(j)for j=10i+(1:10)]...,s);i=0;k();for i=0:9 k(j->lpad(j,3),|);k(l=j->~j|~(j+10(i<9)))end)

```

Used like this: `!7`

Ungolfed:

```
function !(n::Integer)
     for j=(1:10)     #This loop generates the top of the box
       if (j%n==0)
         print("\e[;;41m+---") #"\e[;;41m" is the ANSI escape code
                               #for red background colour in Julia
       else
         print("+\e[m---")     #"\e[m" resets to original colours
       end
     end
     println("+\e[m")
     for i=0:9
       for j=10i+(1:10)  #This loop generates the rows with the numbers
         if (j%n==0)
           print("\e[;;41m|",lpad(j,3))
         else
           print("|\e[m",lpad(j,3))
         end
       end
       println("|\e[m")
       for j=10i+(1:10)  #This loop generates the other rows
         if (j%n==0)||((j+10)%n==0&&i<9)
           print("\e[;;41m+---")
         else
           print("+\e[m---")
         end
       end
       println("+\e[m")
     end
   end

```

Note that this is *very* ungolfed, for maximal readability.
> 4 votes

# Answer
### HTML + Javascript, 379

HTML:

```
<input id=a value=3><pre id=z>

```

Javascript:

```
for(i=0,s=`\n|`,o='+';i++<109;x=i<10?` ${i} `:i-100?' '+i:i,s+=x+'|',o+=x='---+',i%10||(o+=s+'\n+',s=`\n|`));z.innerHTML=[...o+x].map((x,i)=>`<span id=i${i}>${x}</span>`).join``;f=m=>window['i'+m].style.background='red';for(j=k=+a.value;j<=100;j+=k){p=(j/10|0)*84+((m=j%10)?(m-1)*4:-48);'000102030442434445468485868788'.match(/../g).map(x=>f(+x+p))}

```

jsfiddle.
> 0 votes

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


title: Simplify a Date

text:
# Question
Title: Simplify a Date
This is similar to simplifying fractions, but with Dates!

The input of your program must be of the form `mm/dd` For example

```
3/4 //March 4
12/15 //December 15
1/1 // January 1

```

We assume that the input will be valid such that the months have these numbers of days in them:

```
January 31
February 28
March 31
April 30
May 31
June 30
July 31
August 31
September 30
October 31
November 30
December 31

```

Your program's job is to take the assumed valid input, and iteratively (or recursively) simplify the date, and at each iteration (including the 0th), output the date with the full name of the month as written above.

For example:

Given an input of:

```
12/18

```

Would output

```
December 18
June 9
February 3

```

An input that is already simplified only outputs itself:

```
11/17

```

Outputs:

```
November 17

```

The month names cannot come from a function in your language. The strings can be obfuscated, computed, however you like, but you cannot use a standard function like GetMonthString(4) or something, you either have to write that function, or find a way to output the month names as described.

I cannot think of any cases where the simplified date produces an illegal date, but if ever you produce an illegal date along the way, output:

```
Illegal Date

```

But if you are sure this cannot happen, you do not need to have code covering this case. The dates outputted just always need to be valid according to what was described above (it goes without saying that months and days start at 1).

The algorithm:

At each iteration you divide by the smallest number that divides numerator and denominator.

That is, you find all the numbers such that, dividing both the numerator and denominator by this number produces a new numerator and denominator that are both integers (common factors). Select the smallest one and individually divide the numerator and denominator to produce a new fraction. If the only number you can divide by is 1, then you have simplified as much as possible and you stop.

I hope this is clear.

Any language is allowed. This is Code Golf, shortest code wins!

# Answer
# Jelly, 59 bytes

```
ṣ”/VµÆDf/2ị:@µÐĿị1¦€“£ṢtẒ⁽ẹ½MḊxɲȧėAṅ ɓaṾ¥D¹ṀẏD8÷ṬØ»ṣ⁶¤j€⁶j⁷

```

Try it online!

### How it works

```
ṣ”/VµÆDf/2ị:@µÐĿị1¦€“...»ṣ⁶¤j€⁶j⁷  Main link. Argument: mm/dd

ṣ”/                                Split at slashes.
   V                               Eval each chunk, yielding [m, d] (integers).
    µ                              Begin a new, monadic chain. Argument: [m, d]
             µÐĿ                   Execute the chain to the left until the results
                                   are no longer unique. Yield the list of all
                                   intermediate results.
     ÆD                              Compute the divisors of each number.
       f/                            Intersect them.
         2ị                          Select the one at index 2. If there is only
                                     one divisor, ị wraps around and selects 1.
           :@                        Divide [m, d] by this common divisor.
                        ¤            Combine the links to the left into a chain.
                 “...»                 Yield the month's name, space-separated.
                      ṣ⁶               Split at spaces.
                €                    For each pair...
             ị                          index into the month's names...
              1¦                        for the first element.
                         j⁶€         Join each pair, separating by spaces.
                            j⁷       Join, separating by linefeeds.

```
> 2 votes

# Answer
# Pyth - ~~116~~ 87 bytes

```
jm++@rR3c."ayÖèÈÒ+J÷z4wëÝ~ñ!Õ¥´{mCØóy|å²z¼qP?ë"\qhd;ed.u/RYNPiFKsMcz\/K

```

Test Suite.
> 4 votes

# Answer
# TSQL 296 bytes

Not being allowed to use the standard datename cost me alot of bytes, however to save a few bytes, I used the first 3 characters of the default date description(with the format mon dd yyyy hh:miAM (or PM)) and added the rest of the month name.

Golfed:

```
use master
DECLARE @ varchar(5) = '12/2'

DECLARE @m int=month('2000/'+@),@d INT=day('2000/'+@)WHILE @m>0BEGIN PRINT left(dateadd(d,@m*29,0),3)+choose(@m,'uary','uary','ch','il','','e','y','ust','tember','ober','ember','ember')+' '+LEFT(@d,2)SELECT @m/=min(n),@d/=min(n)FROM(SELECT number FROM spt_values)x(n)WHERE @m%n+@d%n=0 and n>1 END

```

Try it online

Ungolfed:

```
use master
DECLARE @ varchar(5) = '12/2'

DECLARE @m int=month('2000/'+@),@d INT=day('2000/'+@)
WHILE @m>0
BEGIN
PRINT
 left(dateadd(d,@m*29,0),3)
 +choose(@m,'uary','uary','ch','il','','e','y','ust',
  'tember','ober','ember','ember')+' '+LEFT(@d,2)
SELECT @m/=min(n),@d/=min(n)
FROM
(
  SELECT number
  FROM spt_values
)x(n)
WHERE
  @m%n+@d%n=0
  and n>1
END

```
> 0 votes

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


title: Is my emoji dry?

text:
# Question
Title: Is my emoji dry?
This is my pet emoji, Billy:

```
-_-

```

Emojis don't like to be in the rain, so Billy is sad... Let's draw him an umbrella to make him feel better!

```
  /\
 /  \
/    \

  -_-

```

This is good, he is entirely covered by his umbrella! Here is an example where only part of him is covered:

```
  /\
 /  \
/    \

     -_-

```

In this case, sections 2 and 3 of his body are exposed to the rain.

Umbrellas come in many shapes and sizes, but they're always made up from a series of ascending slashes `/` followed by a series of descending backslashes `\`. For example, these are all valid umbrellas:

```
  /\
 /  \
/    \

/\

    /\
   /  \
  /    \
 /      \
/        \

```

And these are not:

```
/   \

\/

  \
 / \
/   \

 0\
/  \

//\\
/  \

```

You need to determine which parts of my emoji are exposed to the rain.

# Clarifications

* Your program (or function) will take a 2d string as input. This can be in whatever format is most convenient or natural to your language. An array of strings, an array of arrays of characters, a string with newlines in it etc.
* You must output which sections of the emoji are exposed to the rain. This can be zero-indexed or one-indexed, as long as you make this clear. Output can be in any reasonable format. If the entire emoji is protected from the rain, output nothing (or an empty array).
* You can assume that all inputs will have a valid umbrella, and the same emoji: `-_-`. The emoji will always be on the last line of the input, however their might be several empty lines between the umbrella and the emoji.
* Everything that isn't part of the umbrella or the emoji will be a space  character or newline.
* The input will be padded with spaces so that the length of each line is the same.

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

# Test IO:

All of the sample cases will use one-indexing.

```
  /\
 /  \
/    \

  -_-

Outputs: []

----------------

   /\
  /  \

     -_-

Outputs: [2, 3]

----------------

    /\
   -_-

Outputs: [1]

----------------

     /\
    /  \
   /    \
  /      \
 /        \
/          \

               -_-

Outputs: [1, 2, 3]

```

# Answer
> 8 votes
# 05AB1E, ~~18~~ ~~17~~ 15 bytes

Code:

```
|…-_-123:)ø€J€ï

```

Explanation:

```
|                  # Take all input as a list of strings.
 …-_-              # 3-char string, which results into "-_-".
     123:)         # Replace "-_-" with 123.
          ø        # Zip, resulting into the columns of the 2D array.
           €J      # Join each of them.
             €ï    # For each, convert to integer. If this is not possible, it will ignore
                     the result.
                   # Implicitly output the array.

```

Uses the **CP-1252** encoding. Try it online! (make sure to pad *all* lines with spaces to the same length..

# Answer
> 5 votes
# JavaScript (ES6), 95 bytes

```
a=>[...a[n=0]].map((_,i)=>a.map(s=>(c=s[i])>"-"&c<"_"?p=1:n+=!++c,p=0)|p<!c&&o.push(n),o=[])&&o

```

Input should be an array of strings, with each line padded with spaces to form a square. Output is an array of 1-indexed numbers.

## Explanation

```
var solution =

a=>
  [...a[n=0]].map((_,i)=>  // n = current index of emoji, for each column i of input
    a.map(s=>              // for each line s
      (c=s[i])             // c = character in column
      >"-"&c<"_"?p=1       // p = 1 if column is protected from rain
      :n+=!++c,            // increment n if emoji character found, c = 1 if last line
                           // contained a space in the current column
      p=0
    )
    |p<!c&&o.push(n),      // if the emoji is not protected in the current column
    o=[]
  )
  &&o
```

```
<textarea id="input" rows="6" cols="40">   /\
  /  \

     -_-</textarea><br />
<button onclick="result.textContent=solution(input.value.split('\n'))">Go</button>
<pre id="result"></pre>
```

# Answer
> 3 votes
# , ~~20~~ 19 bytes (non-competing)

```
G^R123?/
f\GddHÍó

```

Alternate, competing version (21 bytes):

```
G^R123?/
f\òjòddHÍó

```

Try it online! (Note, tryitonline.net uses a slightly old version of V. To compensate for this, it uses this slightly longer version)

Explanation:

```
G^          "Move to the first non-whitespace character on the last column
  R123<esc> "Replace the emojii with '123'

?/          "Move backwards to the last '/' character
  <C-v>     "Start a blockwise selection
       f\G  "Move the selection to the next '\', and then to the last line
d           "Delete the block selection
 dH         "Delete the umbrella

```

This alone produces the correct result in 17 bytes. However, it also creates some extra whitespace. I don't mind it, but I don't want to give myself an unfair advantage, so I'm adding two bytes:

```
Íó          "Remove all whitespace

```

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

```
a=>a.map(s=>s.replace(/\S/g,(c,i)=>c>'-'&c<'_'?u[i]=3:++n&u[i]||r.push(n)),n=0,u=[],r=[])&&r

```

Accepts a ragged array of lines and returns a 1-indexed result. Explanation:

```
a=>a.map(               Loop through all lines
 s=>s.replace(/\S/g,    Loop through all non-whitepsace
  (c,i)=>c>'-'&c<'_'    If it's part of the umbrella
   ?u[i]=3              Mark that column as dry
   :++n&                Add 1 to the emoji index
     u[i]||             If the column is not dry
      r.push(n)         Add the emoji index to the result
  ),n=0,u=[],r=[]       Initialise variables
 )&&r                   Return result

```

# Answer
> 3 votes
## Java 8 lambda, ~~241~~ ~~218~~ ~~201~~ ~~191~~ ~~185~~ 184 (or 161) characters

Because ya know, also Java needs dry emojis.

```
import java.util.*;f->{int e,i=e=-1,c,l=f.length-1;while(++e<f[l].length&&f[l][e]!=45);List p=new Stack();l:for(;++i<3;){for(char[]r:f)if((c=r[e+i])==47|c==92)continue l;p.add(i);}return p;}

```

It returns ~~an ArrayList~~ a HashSet a Stack containing the parts of the emoji which are exposed to the rain (indexing starts at 0). The whole thing unwrapped:

```
import java.util.*;

public class Q82668 {
    static List isEmojiDryRevE(char[][] fieldToCheck) {
        int emojiStart, i = emojiStart = -1, j, rows = fieldToCheck.length - 1;

        while (++emojiStart < fieldToCheck[rows].length && fieldToCheck[rows][emojiStart] != 45)
            ;

        List parts = new Stack();
        emojiLoop: for (; ++i < 3;) {
            for (j = -1; ++j < rows;) {
                if (fieldToCheck[j][emojiStart + i] > 46) {
                    // umbrella part found
                    continue emojiLoop;
                }
            }
            // no umbrella part found
            parts.add(i);
        }
        return parts;
    }
}

```

---

**Updates**

I did some basic golfing. This includes putting the declarations together, compare with the ascii values to save some characters and shorten the loops.

Thanks to @user902383 for pointing out my dump mistake using ArrayLists instead of just Lists. I replaced the ArrayLists/Lists with HashSets/Sets which saves some more characters. Also thanks for his tip to use a foreach loop in the inner loop! Through that change I am able to create a variable for the index of the last grid row which shortens it a bit more. Overall 17 characters have been saved!

@KevinCruijssen suggested to remove the generics in the initialization, I went one step further: Remove all the generics. This saves another 10 characters.

I switched back from the foreach loop to the for loop. This makes it possible to skip comparing the last line which in turn allows me to shorten the comparison of the ascii values. In this context only '/', '\\' and '\_' have an ascii value over 46. If we don't check the last line we can use a `> 46 check` instead to checks for the actual value.

Thanks again to @user902383 for showing me that I use a lambda and can use List+Stack instead of Set+HashSet to shave off another character.

---

**String returning version**

@user902383 pointed out I can instead just create a String with the digits. This sounds very cheaty but others seem to solve it this way so here is a shorter version using a String return:

```
f->{int e,i=e=-1,c,r=f.length-1;while(++e<f[r].length&&f[r][e]!=45);String p="";l:for(;++i<3;){for(char[]o:f)if((c=o[e+i])==47|c ==92)continue l;p+=i;}return p;}

```

Ungolfed:

```
public class Q82668 {
    public static String isEmojiDryRevD(char[][] fieldToCheck) {
        int emojiStart, i = emojiStart = -1, c, rows = fieldToCheck.length - 1;

        while (++emojiStart < fieldToCheck[rows].length && fieldToCheck[rows][emojiStart] != 45)
            ;

        String parts = "";
        emojiLoop: for (; ++i < 3;) {
            for (char[] row : fieldToCheck) {
                if ((c = row[emojiStart + i]) == 47 | c == 92) {
                    // umbrella part found
                    continue emojiLoop;
                }
            }
            // no umbrella part found
            parts += i;
        }
        return parts;
    }
}

```

# Answer
> 3 votes
# JavaScript (ES6), ~~117~~ 112 bytes

```
s=>s.map(r=>r.map((c,i)=>~'-_'[o='indexOf'](c)&&!s.some(a=>~'/\\'[o](a[i]))?i-r[o]('-'):-1)).pop().filter(n=>~n)

```

Accepts a ragged array of ~~strings~~ arrays of characters, and returns 0-indexed results.

```
s=>s.map(     // for each row
  r=>         // row
    r.map(    // for each character
      (c,i)=> // character, index
        ~'-_'[o='indexOf'](c) // if character is part of emoji
        &&                    // and
        !s.some(              // none of the rows have umbrella in this column
          a=>~'/\\'[o](a[i])
        )
        ? // then return 0-index of emoji
          i-r[o]('-')
        : // else return -1
          -1
  )
)
.pop()         // get last element of string array
.filter(n=>~n) // filter out -1s

```

## Demo

```
f=s=>s.map(r=>r.map((c,i)=>~'-_'[x='indexOf'](c)&&!s.some(a=>~'/\\'[x](a[i]))?i-r[x]('-'):-1)).pop().filter(n=>~n)
i.oninput=()=>o.value=f(i.value.split`\n`.map(r=>r.split``))
i.oninput()
```

```
<textarea rows=6 cols=20 id=i>
   /\
  /  \

     -_-</textarea>
<br/>
<input readonly id=o>
```

# Answer
> 2 votes
## Retina, 56 bytes

Byte count assumes ISO 8859-1 encoding.

```
m`(?<!(?(2)!)^(?<-2>.)*\S(.*¶)+(.)*).(?<=([-_]+))|\D
$.3

```

Try it online!

This is a single substitution stage, where the regex matches one of the emoji characters, provided that there's a non-space character (i.e. a `/` or `\`) somewhere above in the same horizontal position, and then we capture the number of emoji characters up to that point. This match is replaced with the length of that last capture, which gives us the index of this unsheltered emoji character. The regex also contains a `|\D` to match everything else which gets replaced with nothing at all, so we remove all the other characters.

# Answer
> 1 votes
# Pyth, ~~27~~ 23 bytes

0-indexed.

```
-m.xsd;.T:R"-_-"s`M3.zd

```

Try it online!

### Explanation

```
-m.xsd;.T:R"-_-"s`M3.zd

                    .z   all lines of input, as a list
         :R"-_-"s`M3     replace "-_-" by "012"
                         "012" is generated by s`M3
       .T                transpose, return all columns
                         The sample input becomes:
                           0
                           1
                          /2
                         /
                         \
                         \
 m   d                   for each line:
  .xs                        attempt to convert to integer.
      ;                      if errors, replace to space
-                     d  remove all spaces

```

## History

27 bytes: `sM:#"^ *\d"0.T:R"-_-"s`M3.z` (Try it online!)

# Answer
> 1 votes
## Matlab, 43 bytes

```
@(x)find(sum((x(:,x(end,:)~=' '))~=' ')==1)

```

This code finds column positions of non-space characters in the final row of the input, sums the number of non-space characters in those columns, and finds where there's only one such character (the emoji's character, un-shielded by umbrella!). This code only returns proper results for well-formed umbrellas (it assumes any character above our emoji is part of a well-formed umbrella).

Here is a bit of utility code for writing test cases and checking my work:

```
ws = @(x) repmat(' ',1,x);  %  for making strings of spaces
% for writing three-storey umbrellas over an emoji located left-edge at position x
thrht = @(x) strvcat([ws(3) '/\' ws(3); ws(2) '/  \' ws(2); ws(1) '/' ws(4) '\' ws(1); ws(8)], [ws(x-1) '-_-']);
twht = @(x) strvcat([ws(3) '/\' ws(3); ws(2) '/  \' ws(2); ws(8)], [ws(x-1) '-_-']);

```

Running `x = thrht(7)` gives

```
x =

   /\
  /  \
 /    \

      -_-

```

Or `x = twht(0)` gives

```
x =

   /\
  /  \

 -_-

```

# Answer
> 0 votes
# Python 2, ~~114~~ 111 bytes

```
def f(a):c=a.find("\n")+1;r=a.rfind;g=lambda i:([i],[])[r("\\")%c>=r("-")%c-2+i>=r("/")%c];print g(0)+g(1)+g(2)

```

Uses 0 based indexing.

Try it here.

# Answer
> 0 votes
# APL, 31 bytes

```
{(⍳3)∩,(~∨⌿⍵∊'/\')/+\+\'-_-'⍷⍵}

```

This takes a character matrix as input.

Tests:

```
      t1 t2 t3 t4
┌──────┬────────┬──────┬─────────────────┐
│  /\  │   /\   │    /\│     /\          │
│ /  \ │  /  \  │   -_-│    /  \         │
│/    \│        │      │   /    \        │
│      │     -_-│      │  /      \       │
│  -_- │        │      │ /        \      │
│      │        │      │/          \     │
│      │        │      │                 │
│      │        │      │                 │
│      │        │      │                 │
│      │        │      │                 │
│      │        │      │              -_-│
└──────┴────────┴──────┴─────────────────┘
      {(⍳3)∩,(~∨⌿⍵∊'/\')/+\+\'-_-'⍷⍵} ¨ t1 t2 t3 t4
┌┬───┬─┬─────┐
││2 3│1│1 2 3│
└┴───┴─┴─────┘

```

Explanation:

* `'-_-'⍷⍵`: in a matrix of zeroes the size of the input, mark the position of the beginning of `'-_-'` in the input with a 1.
* `+\+\`: Running sum over rows. The first one makes `0 0 0 1 0 0 ...` into `0 0 0 1 1 1 ...`, the second one then makes it into `0 0 0 1 2 3 ...`.
* `⍵∊'/\'`: mark all occurrences of '/' and '\\' in the input with 1s.
* `∨⌿`: `or` over columns. This marks with an 1 all positions on the last row that are covered by the umbrella.
* `~`: `not`, because we need the opposite
* `(`...`)/`...: Select all uncovered columns from the running sum matrix from earlier
* `,`: Get a list of all values in the resulting matrix.
* `(⍳3)∩`: Intersection between that and `1 2 3` (this gets rid of any selected 0s or higher values, which would be spaces).

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


# Question
Title: Golf the Inverse of Exponential Generating Function
Earlier, we talked about exponential generating functions (e.g.f.).

# Task

You will take a few terms of a sequence.

Your task is to find another sequence with that many terms, whose e.g.f., when multiplied to the original e.g.f., would be exactly the constant function `1` accurate to that many terms.

That is, given `a0=1, a1, a2, ..., an`, find `b0=1, b1, b2, ..., bn` such that `a0 + a1x + a2x^2/2! + a3x^3/3! + ... + anx^n/n!` multiplied by `b0 + b1x + b2x^2/2! + b3x^3/3! + ... + bnx^n/n!` equals `1 + O(x^(n+1))`.

# Specs

* They will start at the zeroth power and will be consecutive.
* The first term is guaranteed to be `1`.
* All the terms are guaranteed to be integers.
* There will not be negative powers.

# Testcases

```
Input : 1,0,-1,0,1,0,-1,0 (this is actually cos x)
Output: 1,0, 1,0,5,0,61,0 (this is actually sec x)

Input : 1, 2, 4, 8, 16, 32 (e^(2x))
Output: 1,-2, 4,-8, 16,-32 (e^(-2x))

Input : 1,-1,0,0, 0,  0,  0 (1-x)
Output: 1, 1,2,6,24,120,720 (1/(1-x) = 1+x+x^2+...)

```

# Answer
# Julia, ~~91~~ ~~81~~ 77 bytes

```
!v=(b=[1;0v[r=2:end]];for i=r,j=0:i-2 b[i]-=binomial(i-1,j)v[i-j]b[j+1]end;b)

```

Usage: `![1 0 -1 0 1 0 -1 0]`

Saved 4 bytes thanks to Dennis!

This is a fairly straightforward implementation - it uses the fact that the "exponential" part causes a binomial to appear in the solution. Otherwise, it's just solving for the relevant coefficients.
> 3 votes

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


title: "Bit-borrow" two numbers

text:
# Question
Title: "Bit-borrow" two numbers
Did you know that a small number can *borrow* bits from a larger number? Here's an example. Let's say our two numbers 5 and 14. First, write them out in binary:

```
5       14
000101  001110

```

First we take the smallest *on* bit away from the larger number, and we give it to the smallest *off* bit on the other number. So

```
This bit turns off
            |
            v
000101  001110
    ^
    |
This bit turns on

```

Now we have

```
000111  001100

```

and our numbers are 7 and 12. The first number is still smaller, so we continue.

```
000111  001100
001111  001000

```

Now we have 15 and 8, so we can stop. We'll call this set of operations "bit-borrowing" two numbers. Let's do another example. 20 and 61.

```
20        61
010100    111101
010101    111100
010111    111000
111111    100000
63        32

```

So our end result is 32, 63. Let's do *one* more. 31, and 12. 31 is already bigger than 12, so there's nothing to do! Bit-borrowing 31 and 12 gives 31 and 12, no change.

# The challenge

Your challenge is to write a program or function that takes two numbers and bit-borrows them. The two numbers will always positive integers. Your input and output can be in any reasonable format.

# Test IO:

```
Input: 2, 3
Output: 3, 2

Input: 3, 2
Output: 3, 2

Input: 8, 23
Output: 31, 0

Input: 42, 81
Output: 63, 0

Input: 38, 41
Output: 47, 32

Input: 16, 73
Output: 23, 0

Input: 17, 17
Output: 17, 17

```

Standard loopholes apply, and shortest answer in bytes wins!

# Answer
> 12 votes
# Jelly, 11 bytes

```
~1¦&N$^µ</¿

```

Try it online! or verify all test cases.

### Background

We can extract the last set bit of an integer **n** as follows.

**n + 1** toggles all trailing set bits of **n** and the adjacent unset bit. For example, **100112 \+ 1 = 101002**.

Since **~n = -(n + 1) = -n - 1**, **-n = ~n + 1**, so **-n** applies the above to the bitwise NOT of **n** (which toggles *all* bits), thus toggling all bits before the last **1**.

For example, **-101002 = ~101002 \+ 1 = 010112 \+ 1 = 011002**.

By taking **n & -n** the bitwise AND of **n** and **-n** all bits before the last set bit are nullified (since unequal in **n** and **-n**), thus yielding the last set bit of **n**.

For example, **101002 & -101002 = 101002 & 011002 = 001002**.

Thus XORing **n** with **n & -n** unsets the last set bit of **n**.

Conversely, to unset the last set bit of **n**, it suffices to apply the above to **~n**, from where we derive the formula **n ^ (~n & -~n)**.

### How it works

```
~1¦&N$^µ</¿  Main link. Argument: A (list of pairs)

          ¿  While loop:
        </     Condition: Reduce p by less-than. True iff x < y.
       µ       Body chain:
~1¦              Apply bitwise NOT to the x, first item of the pair.
     $           Convert the two links to the left into a monadic chain.
    N              Negate; multiply [~x, y] by -1, yielding [-~x, -y].
   &               Logical AND. Yields [-~x & ~x, -y & y].
      ^            Vectorized XOR with p. Yields [(-~x & ~x) ^ x, (-y & y) ^ y].

```

# Answer
> 6 votes
# J, ~~31~~ 26 bytes

```
,`(($:~(OR>:))~(AND<:))@.<

```

Straight-forward approach using recursion and bitwise tricks. In order to turn off (set to **0**) the right-most on (**1**) bit for a value *n*, you can perform bitwise-and between *n* and *n*-1, and to turn on (set to **1**) the right-most off (**0**) bit for a value *n*, you can perform bitwise-or between *n* and *n*+1.

## Usage

The input consists of two integers, one applied on the LHS and the other on the RHS, and the output is a list of the bit-borrowed values.

```
   f =: ,`(($:~(OR>:))~(AND<:))@.<
   2 f 3
3 2
   3 f 2
3 2
   8 f 23
31 0
   42 f 81
63 0
   38 f 41
47 32
   16 f 73
23 0
   17 f 17
17 17

```

## Explanation

```
,`(($:~(OR>:))~(AND<:))@.<  Input: x on LHS, y on RHS
                            If x < y,
,                             Form a 2-element array [x, y] and return
                            Else
                   <:         Decrement y
                AND           Perform bitwise-and on y and y-1, call it y'
          >:                  Increment x
        OR                    Perform bitwise-or on x and x+1, call it x'
    $:                        Call recursively on x' and y' and return

```

# Answer
> 4 votes
# Python, 42 bytes

```
f=lambda x,y:x<y and f(x|x+1,y&y-1)or(x,y)

```

*Thanks to @jimmy23013 for golfing off 4 bytes!* *Thanks to @LeakyNun for golfing off 2 bytes!*

Test it on Ideone.

# Answer
> 3 votes
# Pyth, ~~29~~ ~~27~~ ~~25~~ ~~22~~ ~~21~~ ~~20~~ ~~19~~ ~~18~~ 16 bytes

```
~~MxG^2x_+\0.BG`HCm.W<FHgVZU2dC~~
~~MxG^2x_+0jG2HCm.W<FHgVZU2dC~~
~~Cm.W<FH.bxN^2x_+0jN2YZ2dC~~
~~m.W<FH.bxN^2x_+0jN2YZ2~~      <-- changed input/output format
~~m.W<FH.exb^2x_+0jb2kZ~~
~~m.W<FH.U,.|bhb.&ZtZZ~~
~~.W<FH.U,.|bhb.&ZtZZ~~         <-- changed input/output format
~~.W<FH.U,.|bhb.&ZtZ~~
.W<FH.U,.|bhb.&t

```

Test suite.

# Answer
> 3 votes
# Mathematica, 46 bytes

```
If[#<#2,BitOr[#,#+1]~#0~BitAnd[#2,#2-1],{##}]&

```

Same method as used in my solution in J.

Thanks to @Martin for saving 1 byte and reminding me of infix application `~`.

## Usage

The input consists of two integer arguments and the output is a list with the bit-borrowed values.

# Answer
> 2 votes
## 05AB1E, ~~16~~ 15 bytes

```
[D`›#`D<&sD>~s‚

```

Try it online

# Answer
> 2 votes
## Labyrinth, ~~37~~ 34 bytes

```
?"
}
|=:{:
)   }
: :;-{
=&( {!;\!@

```

Try it online!

### Explanation

Quick Labyrinth primer:

* Labyrinth operates on two stacks of arbitrary-precision integers, *main* and *auxiliary*, which are initially filled with an (implicit) infinite amount of zeros.
* The source code resembles a maze, where the instruction pointer (IP) follows corridors. All interesting control flow happens at junctions: when the IP has more than one cell to go to, the top of the main stack is inspected. If the value is negative, the IP turns left, if it's positive, the IP turns right, and otherwise it moves straight ahead. If the chosen direction is blocked by a wall (i.e. a space), the IP moves in the opposite direction instead.

The program uses the same algorithm as the other answers: we replace `(a, b)` with `(a | a+1, b & b-1)` as long as `a < b`. I'll add a full explanation after I've tried golfing it some more.

The IP starts in the top left corner, going right. `?` reads an integer `a`. Then `"` is a no-op, but it's necessary to prevent the IP from moving down immediately. This is also a dead end, so the IP turns around and executes `?` again to read `b`. `}` then moves `b` from *main* to *aux*, so now we've got:

```
Main [ ... 0 a | b 0 ...] Aux

```

The `|` then does nothing, because it takes the bitwise OR of `a` and `0`. Since we know `a` is always positive, the IP turns east (because it can't turn west). This begins the main loop of the program. We start with a short linear section in order to compare `a` and `b`:

```
=   Swap tops of stacks, i.e. swap a and b.
:   Duplicate b.
{   Pull a over to main.
:   Duplicate a.
}   Push one copy back to aux.
-   Compute b-a.

```

The IP is now at another junction. First, let's consider the case where the result is positive. That means `b > a` and we need to perform one more iteration. That iteration is also completely linear. Note that the stacks are currently:

```
Main [ ... 0 b (b-a) | a 0 ...] Aux

;   Discard b-a.
:   Duplicate b.
(   Decrement.
&   Bitwise AND with b, clearing the least-significant 1.
=   Swap new b with old a.
:   Duplicate a.
)   Increment.
|   Bitwise OR with a, setting the least-significant 0.

```

And then we're back to the start of the loop (since `a` is again positive, the IP turns east again).

If at some point `b-a` is no longer positive, the IP will take one of the other two paths. Note that in both cases we fetch `a` with `{`, then hit a corner where the IP follows the bend and then print `a` with `!`. Now the top of the stack is again `b-a` which means that in both cases the IP will end up moving east. All that's left is a short linear bit now:

```
;   Discard b-a.
\   Print a linefeed.
!   Print b.
@   Terminate the program.

```

# Answer
> 1 votes
# Java 7, 73 bytes

```
void d(int x,int y){while(x<y){x|=x+1;y&=y-1;}System.out.print(x+","+y);}

```

**Ungolfed & test cases:**

Try it here.

```
public class Main{
  static void d(int x, int y){
    while(x < y){
      x |= x + 1;
      y &= y - 1;
    }
    System.out.print(x + "," + y);
  }

  public static void main(String[] a){
    print(2, 3);
    print(3, 2);
    print(8, 23);
    print(42, 81);
    print(38, 41);
    print(16, 73);
    print(17, 17);
  }

  public static void print(int a, int b){
    d(a, b);
    System.out.println();
  }
}

```

**Output:**

```
3,2
3,2
31,0
63,0
47,32
23,0
17,17

```

---

**Old challenge rules \[~~126~~ ~~125~~ 123 bytes\]:**

*NOTE: The old challenge rules used two integer-arrays as input, instead of two loose integers.*

```
void d(int[]a,int[]b){int i=-1,x,y;while(++i<a.length){x=a[i];y=b[i];for(;x<y;x|=x+1,y&=y-1);System.out.println(x+","+y);}}

```

# Answer
> 1 votes
# Julia, 27 bytes

```
x<|y=x<y?x|-~x<|y&~-y:[x,y]

```

Try it online!

### How it works

We define the binary operator `<|` for our purposes. It is undefined in recent versions of Julia, but still recognized as an operator by the parser. While `\` (not explicitly defined for integers) is one byte shorter, its high precedence would require replacing `x|-~x<|y&~-y` with `(x|-~x)\(y&~-y)`, thus increasing the byte count.

`<|` checks if its first argument is strictly less than the second one. If so, it recursively calls itself with arguments **x | -~x = x | (x + 1)** and **y & ~-y = y & (y - 1)**.

Since adding **1** to **x** toggles all trailing set bits and the lowest unset bit, **x | (x + 1)** toggles the lowest unset bit (and no other bits). Likewise, since subtracting **1** from **y** toggles all trailing unset bits and the lowest set bit, **y & (y + 1)** toggles the lowest set bit.

Finally, when the inequality **x \< y** no longer holds, `<|` returns the pair **\[x, y\]**.

# Answer
> 1 votes
## JavaScript (ES6), 33 bytes

```
f=(n,m)=>n<m?f(n|n+1,m&m-1):[n,m]

```

Simple port of the answers by @miles.

# Answer
> 0 votes
## MATLAB, ~~67~~ 66 bytes

loop:

```
function[]=f(x,y)
while x<y
x=bitor(x,x+1);y=bitand(y,y-1);end
x,y

```

recursive (67 bytes):

```
function[]=f(x,y)
if x<y
f(bitor(x,x+1),bitand(y,y-1))
else
x,y
end

```

Same approach to changing bits as many other anwers.

# Answer
> 0 votes
# Clojure, 63 bytes

```
#(if(< % %2)(recur(bit-or %(inc %))(bit-and %2(dec %2)))[% %2])

```

Same method as used in my solution in J.

## Usage

```
=> (def f #(if(< % %2)(recur(bit-or %(inc %))(bit-and %2(dec %2)))[% %2]))
=> (f 38 41)
[47 32]
=> (map (partial apply f) [[2 3] [3 2] [8 23] [42 81] [38 41] [16 73] [17 17]])
([3 2] [3 2] [31 0] [63 0] [47 32] [23 0] [17 17])

```

---
Tags: code-golf, math, bitwise
---