# Question
Title: Who wants to be a Kolmogorov complexity winner?
You mission today is to invent a text compressor.

# Task

You'll write two functions:

* The **packer** is a function that accepts a string of ASCII characters (U+0000 to U+007F) and outputs a Unicode string (U+0000 to U+10FFFF), containing the fewest characters possible.
* The **unpacker** is a function that accepts an encoded Unicode string and outputs exactly the original ASCII string.

# Input

The only authorized input is the ASCII string (for the packer) and the packed Unicode string (for the unpacker). No user input, no internet connection, no use of file system.

Your functions can have access to this list of english words. You can use this list as a local txt file, or copy its content in your source code as a string or an array of strings.

You can't hardcode the snippets below in your functions.

# Output

The only authorized output for both functions is a string.

The output of the unpacker must contain exactly the same characters as the input of the packer.

Your inputs and outputs can use any character encoding supporting all Unicode (UTF-8/16/32, GB18030, ...), as your score will only depend on the number of Unicode characters in the output. Please precise which encoding you're using, though.

To count the number of Unicode characters in your output, you can use this tool: http://mothereff.in/byte-counter

# Scoring

Your entry must be able to pack and unpack the 10 following text snippets (that I took on this forum).

Your score will be the sum of the sizes of your 10 packed strings (in Unicode characters) + the size of your two functions (in Unicode characters, too)

Don't count the size of the dictionnary if you use it.

Please include in your entries the "score" of each snippet and their packed version.

Lowest score wins.

# Data

Here are the snippets to encode to compute your score:

1: Rick Roll lyrics (1870b): We're no strangers to code golf, you know the rules, and so do I

```
We're no strangers to love
You know the rules and so do I
A full commitment's what I'm thinking of
You wouldn't get this from any other guy
I just wanna tell you how I'm feeling
Gotta make you understand

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

We've known each other for so long
Your heart's been aching but
You're too shy to say it
Inside we both know what's been going on
We know the game and we're gonna play it
And if you ask me how I'm feeling
Don't tell me you're too blind to see

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

(Ooh, give you up)
(Ooh, give you up)
(Ooh)
Never gonna give, never gonna give
(Give you up)
(Ooh)
Never gonna give, never gonna give
(Give you up)

We've know each other for so long
Your heart's been aching but
You're too shy to say it
Inside we both know what's been going on
We know the game and we're gonna play it

I just wanna tell you how I'm feeling
Gotta make you understand

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

```

2: The Golfer (412b): Golfing ASCII-art

```

      '\                   .  .                        |>18>>
        \              .         ' .                   |
       O>>         .                 'o                |
        \       .                                      |
        /\    .                                        |
       / /  .'                                         |
 jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

```

3: the number diamond (233b): Print this diamond

```
        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1

```

4: the alphabet four times (107b): Print the alphabet four times

```
abcdefghijklmnopqrstuvwxyz
qwertyuiopasdfghjklzxcvbnm
pyfgcrlaoeuidhtnsqjkxbmwvz
zyxwvutsrqponmlkjihgfedcba

```

5: Old McDonald's lyrics (203b): Old MacDonald function

```
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a cow, E-I-E-I-O,
With a moo moo here and a moo moo there,
Here a moo, there a moo, everywhere a moo moo,
Old MacDonald had a farm, E-I-E-I-O!

```

6: Rock around the clock lyrics (144b): Rock Around the Clock

```
1, 2, 3 o'clock, 4 o'clock rock,
5, 6, 7 o'clock, 8 o'clock rock,
9, 10, 11 o'clock, 12 o'clock rock,
We're gonna rock around the clock tonight.

```

7: Hello World (296b): Say "Hello" to the world in ASCII art

```
 _   _      _ _                             _     _ _
| | | | ___| | | ___    __      _____  _ __| | __| | |
| |_| |/ _ \ | |/ _ \   \ \ /\ / / _ \| '__| |/ _` | |
|  _  |  __/ | | (_) |   \ V  V / (_) | |  | | (_| |_|
|_| |_|\___|_|_|\___( )   \_/\_/ \___/|_|  |_|\__,_(_)
                    |/

```

8: Irish blessing (210b): An Old Irish Blessing

```
May the road rise up to meet you
May the wind be always at your back
May the sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand

```

9: There was an old lady lyrics (1208b): There Was an Old Lady

```
There was an old lady who swallowed a fly.
I don't know why she swallowed that fly,
Perhaps she'll die.

There was an old lady who swallowed a spider,
That wriggled and iggled and jiggled inside her.
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.

There was an old lady who swallowed a bird,
How absurd to swallow a bird.
She swallowed the bird to catch the spider,
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.

There was an old lady who swallowed a cat,
Imagine that to swallow a cat.
She swallowed the cat to catch the bird,
She swallowed the bird to catch the spider,
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.

There was an old lady who swallowed a dog,
What a hog to swallow a dog.
She swallowed the dog to catch the cat,
She swallowed the cat to catch the bird,
She swallowed the bird to catch the spider,
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.

There was an old lady who swallowed a horse,
She died of course.

```

10: gettysburg address (1452b): How random is the Gettysburg Address

```
Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battlefield of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we can not dedicate, we can not consecrate, we can not hallow this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us-that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion-that we here highly resolve that these dead shall not have died in vain-that this nation, under God, shall have a new birth of freedom-and that government of the people, by the people, for the people, shall not perish from the earth.

```

Total (uncompressed): 6135 chars/bytes.

Have fun!

# Answer
> 6 votes
# Haskell - 5322 points

Bytes of code : `686`

Original size : `6147` `= 1871+415+234+108+204+145+297+211+1209+1453`

Encoded size : `4636` `= 1396+233+163+92+153+115+197+164+979+1144`

Score : `686+ 4636`

Character count compression : `~25%`

## Code

Optimizations aside, this stores values between `0` and `7f` in unicode characters as their prime factors.

It does not lower the number of bytes of the encoded output, it only lowers the number of unicode characters. For instance, test #4 contains `108` characters and the encoded output, `92`. Their respective sizes are however `108` and `364` bytes.

```
import Data.Bits
import Data.List
import Data.Numbers.Primes
import qualified Data.Text as T
a=nub$concat$map(primeFactors)[0..127]
d(a:r)c=let s=shift c 5in if s<=0x10ffffthen d r(s+a)else c:d r a
d[]c=[c]
f(a:r)=let o=a.&.0x1fin(if o/=a then f((shiftR a 5):r)else f r)++[o]
f[]=[]
g=T.pack.map(toEnum).(\(a:r)->d r a).concatMap j.map(map(\x->head$elemIndices x a)).map(primeFactors.fromEnum).T.unpack
h=T.pack.map(toEnum.product.map((!!)a)).i.f.reverse.map(fromEnum).T.unpack
i(a:r)=let z=a`clearBit`4;x=if a`testBit`4then(take z$repeat$head r,tail r)else splitAt z r in[fst x]++i(snd x)
i[]=[]
j x@(a:_)=let l=length x in if(take l(repeat a))==x then[l`setBit`4,a]else[l]++x
j[]=[0]

```

## How it works

* Encoding

1. Each character is converted to its numeric equivalent, lets call this number `n`.
    2. `n` is then converted into a list of its prime factors, `ps`.
        + It conveniently happens that the numbers 0 through 127 have 32 common prime factors, excluding `1`. This mean they, the factors, can be stored as indexes on as little as 5 bits.
        + `1` is a special case and is represented by an empty list.
    3. With `ps` the encoding can now start.
        1. Each number of `ps` is converted into its index in the list of 32 unique factors (In the above code this list is identified as `a`).
        2. (Keep in mind at this point we are dealing with a list of list of indexes of prime factors) To proceed to the next step, `ps` needs to be flattened. To preserve the integrity of the data, each list is converted into another list of two parts
            1. The first element stores its length and if the it is composed of the same factor.
                + There are at most 6 prime factors per list, this information is stored on the rightmost 3 bits. The fifth bit is used as a flag to indicate if the list is comprised of a single factor.
            2. The remaining elements are the indexes themselves or a single index if there is less than two different factors in the list.
        3. These lists are then concatenated into a single flattened list, `fs`.
    4. The elements of `fs` can then be packed into unicode characters using bit shifting.
* Decoding

+ Do the encoding steps in reverse.
    + If you are wondering how `1` fits into this, I would like to remind you that `product [] == 1`.

## Tests

Using this interface for testing would be painful so I used this function to provide the results below.

```
edTest f = do
    t <- readFile f
    let txt = T.pack t
        enc = g txt
        dec = h enc
        tst = txt == dec
    putStrLn $ (show $ T.length txt) ++ "," ++ (show $ T.length enc) ++ "," ++ (show $ T.length dec)++","++(show tst)
    putStrLn $ if not tst then T.unpack txt ++ "\n---NEXT---\n" ++ T.unpack dec else ""

```

```
λ> edTest "1"
1871,1396,1871,True

λ> edTest "2"
412,233,412,True

λ> edTest "3"
234,163,234,True

λ> edTest "4"
108,92,108,True

λ> edTest "5"
204,153,204,True

λ> edTest "6"
145,115,145,True

λ> edTest "7"
297,197,297,True

λ> edTest "8"
211,164,211,True

λ> edTest "9"
1209,979,1209,True

λ> edTest "10"
1453,1144,1453,True

```

## Sample

The output of the encoding function `g` for test #4 is this
`"\99429\582753\135266\70785\35953\855074\247652\1082563\68738\49724\164898\68157\99429\67973\1082404\587873\73795\298017\330818\198705\69861\1082435\595009\607426\36414\69873\855074\265249\346275\67779\68738\77985\1082513\821353\132131\101410\247652\1082562\49724\164898\67649\594977\34915\67746\50273\135265\103997\563265\103457\1086021\99399\584802\70753\73889\34882\582722\411459\67779\68740\1084516\1082563\1091681\103491\313282\49724\164897\68705\135741\69858\50241\607426\35905\608421\1082435\69858\50274\71777\43075\298018\280517\1082404\67971\36017\955425\67665\919600\100452\132129\214883\35057\856097\101474\70753\135737"`
or if you are an adept of gibberish, this
`豱숼踾숼衣쑡衂숼쑁豁쑢ꡃ貱裱`

## Additionnal notes

* Using http://mothereff.in/byte-counter, directory listings and `edTest` the size of the tests are all consistent but still differs from the indicated size in the question.
* Test #10 contains a couple of EM DASHes () that I replaced with `-` since they are outside of the `0`-`7f` range.
* Further compression could be achieved using the remaining fourth bit while flattening, for instance, `00` base case, `01` repeat all, `10` repeat except last, `11` repeat except last two.
* The test files and the code are all available here https://github.com/gxtaillon/codegolf/tree/master/Kolmogorov

# Answer
> 5 votes
# C++ (C++11), 2741 points

This answer uses UTF-32 as the encoding for the compressed text.

```
#include <cstdio>
#include <iostream>
#include <locale>
#include <string>
#define L locale
using namespace std;long b,n,i,l;void c(){string d;char x;while((x=cin.get())!=EOF)d+=x;b=(d.size()*7)%20;n=5;wcout.imbue(L());for(char y:d){b=b<<7|y&127;n+=7;if(n>=20)wcout.put(b>>(n-=20)&0xFFFFF);}if(n)wcout.put(b<<20-n&0xFFFFF);}void d(){wstring d;wchar_t w;wcin.imbue(L());while((w=wcin.get())!=EOF)d+=w;l=-1;for(wchar_t y:d){b=b<<20|y;n+=20;if(l<0)l=b>>15&31,n-=5;while(n>=7&(i<d.size()-1|n>20-l))cout.put(b>>(n-=7)&127);++i;}}int main(int t,char**a){L::global(L("en_US.utf8"));**++a<'d'?c():d();}

```

## Char counts and scoring

**Code: 593 chars** (the trailing newline is stripped)

**Compressed texts (unicode characters)**: 654 + 145 + 82 + 38 + 51 + 104 + 73 + 423 + 506 = **2148** (counted with `wc -m` for the number of unicode characters rather than bytes, the byte counts are, as as with @gxtaillon's answer, higher than the originals, 8413 bytes in total, as counted with `wc -c`).

**Compression ratio (ASCII to unicode)**: 35.01% (using the 6135 bytes from the question (same as `wc -c`))

## Beware:

A lot of shells cannot handle the unicode characters this program produces. Thus, decompressing may lead to the text being cut off somewhere when the shell cannot handle a character, as input is taken via `stdin` from the shell.

## Compiling

It should compile with `clang++` and `g++ -std=c++11`, but it will show some warnings about operator precedence, as an expression like `b<<20-n&0xFFFFF` will not be treated as `((b << 20) - n) & 0xFFFFF`, as one might expect, but rather as `(b << (20 - n)) & 0xFFFFF`.

## Usage

* Compile the program into an executable, e.g. `./compress`.
* Run the program as `./compress c` to compress or `./compress d` to decompress. (Careful, leaving out the option gives a *SEGFAULT* (error checking is so character expensive...) and other options (such as using `D` instead of `d`) may give unexpected results
* Input is read from `stdin` and output written to `stdout`

## How it works

### Ungolfed

```
#include <cstdio>
#include <iostream>
#include <locale>
#include <string>

using namespace std;

long b, n, i, l;

// Compress
void c() {
    string d;
    char x;
    // Read from STDIN until EOF
    while((x = cin.get()) != EOF)
        d += x;
    // Calculate the number of bits used from the last unicode character
    // (maximum 19) and store it into the first 5 bits
    b = (d.size() * 7) % 20;
    n = 5;
    // Set the output locale to allow unicode
    wcout.imbue(locale());
    // For each character in the input...
    for (char y : d) {
        // Add its bit representation (7 bits) to the right of the buffer
        // by shifting the buffer left and ORing with the character code
        b = (b << 7) | (y & 127);
        // Add 7 to the bit counter
        n += 7;
        // If enough data is present (20 bits per output character),
        // calculate the output character by shifting the buffer right,
        // so that the last 20 bits are the left 20 bits of the buffer.
        // Also decrement the bit counter by 20, as 20 bits are removed.
        if (n >= 20)
            wcout.put((b >> (n -= 20)) & 0xFFFFF);
    }
    // If there are still bits in the buffer, write them to the front of
    // another unicode character
    if (n)
        wcout.put((b << (20 - n)) & 0xFFFFF);
}

// Decompress
void d() {
    wstring d;
    wchar_t w;
    // Set STDIN to UNICODE
    wcin.imbue(locale());
    // Read wide characters from STDIN (std::wcin) until EOF
    while ((w = wcin.get()) != EOF)
        d += w;
    // `l' represents the number of bits used in the last unicode character.
    // It will be set later
    l = -1;
    // For each input character...
    for (wchar_t y : d) {
        // Add it to the buffer and add 20 to the bit counter
        b = (b << 20) | y;
        n += 20;
        // If the number of bits in the last unicode character has not been
        // set yet, read the first 5 buffer bits into `l'. This is
        // necessary because the last character may contain more than 7
        // (one entire uncompressed character) unused bits which may
        // otherwise be interpreted as garbage.
        if (l < 0) {
            l = (b >> 15) & 31;
            n -= 5;
        }
        // As long as there is data to turn into output characters
        // (at least 7 bits in the buffer and either not the last
        // unicode character or before the unused bits)
        while (n >= 7 && ((i < d.size() - 1) || (n > (20 - l)))
            cout.put((b >> (n -= 7)) & 127); // Output the left 7 bits in the buffer as an ASCII character
        ++i; // Increment the character index, so that we know when we reach the last input character
    }
}
int main(int t, char**a) {
    // Set the default locale to en_US.utf8 (with unicode)
    locale::global(locale("en_US.utf8"));
    // Decide whether to compress or decompress.
    // This is just fancy pointer stuff for a[1][0] < 'd' ? c() : d()
    (**(++a) < 'd') ? c() : d();
}

```

### Explanation

As all unicode characters from `U+0000` to `U+10FFFF` are allowed, we can use 20 bits per unicode char: `U+FFFFF` uses 20 bits and is still included in the allowed range. Thus, we just try to cram all the individual ASCII char bits into the unicode characters to store multiple ASCII characters in one unicode character. However, we also need to store the number of bits used in the last unicode character, because unused garbage bits may otherwise be interpreted as proper compressed ASCII characters. As the maximum number of used bits in the last unicode character is 20, we will need 5 bits for that, which are placed in the beginning of the compressed data.

### Example output

This is the output for example #4 (as given by `less`):

```
<U+4E1C5><U+8F265><U+CD9F4><U+69D5A><U+F66DD><U+DBF87><U+1E5CF><U+A75ED>
<U+DFC79><U+F42B8><U+F7CBC><U+BA79E><U+BA77F>쏏<U+A356B><U+D9EBC><U+63ED8>
<U+B76D1><U+5C3CE><U+6CF8F><U+96CC3><U+BF2F5><U+D3934><U+74DDC><U+F8EAD>
<U+7E316><U+DEFDB><U+D0AF5><U+E7C77><U+EDD7A><U+73E5C><U+786FD><U+DB766>
<U+BD5A7><U+467CD><U+97263><U+C5840>

```

( give `<U+C3CF><U+266CF>` as character codes, but I might have gotten that wrong)

# Answer
> 2 votes
# Python 3, 289+818=1107 points

Only lightly golfed.

```
import zlib as Z
def p(s):
 z=int.from_bytes(Z.compress(s),'big');o=''
 while z:
  z,d=divmod(z,1<<20)
  if d>0xd000:d+=1<<16
  o+=chr(d)
 return o[::-1]
def u(s):
 i=0
 for c in s:
  d=ord(c)
  if d>0xe000:d-=1<<16
  i=(i<<20)+d
 return Z.decompress(i.to_bytes(i.bit_length()//8+1,'big'))

```

The total code size is 289 bytes, and encodes the given 6135 bytes into 818 Unicode characters -- the total output byte count is 3201 bytes, significantly smaller than the original inputs.

Encodes using zlib, then secondarily using unicode encoding. Some extra logic was needed to avoid surrogates (which Python really hates).

Example output from #4, as seen by `less` (37 Unicode chars):

```
x<U+AC0DC><U+BB701><U+D0200><U+D00B0><U+AD2F4><U+EEFC5><U+F4F34>멍<U+3C63A><U+2F62C><U+BA5B6><U+4E70A><U+F7D88><U+FF138><U+40CAE>
<U+CB43E><U+C30F5><U+6FFEF><U+698BE><U+9D73A><U+95199><U+BD941><U+10B55E><U+88889><U+75A1F><U+4C4BB><U+5C67A><U+1089A3><U+C75A7>
<U+38AC1><U+4B6BB><U+592F0>ᚋ<U+F2C9B>

```

Driver program for testing:

```
if __name__ == '__main__':
    import os
    total = 0
    for i in range(1,10+1):
        out = p(open('data/%d.txt'%i,'rb').read())
        total += len(out)
        open('out/%d.bin'%i,'w',encoding='utf8').write(out)
    print(total)
    for i in range(1,10+1):
        out = u(open('out/%d.bin'%i,'r',encoding='utf8').read())
        open('data2/%d.txt'%i,'wb').write(out)

```

Output byte counts:

```
 607 out/1.bin
 128 out/2.bin
 101 out/3.bin
 143 out/4.bin
 177 out/5.bin
 145 out/6.bin
 186 out/7.bin
 222 out/8.bin
 389 out/9.bin
1103 out/10.bin
3201 total

```

# Answer
> 1 votes
# Python 2 - 1141 points

```
from zlib import *;v=256
def e(b):
 x=0
 for c in compress(b,9):x=(x*v)+ord(c)
 b=bin(x)[2:]
 return "".join(unichr(int("1"+b[a:a+19],2))for a in range(0,len(b),19))
def d(s):
 y=int("".join(bin(ord(a))[3:]for a in s),2);x=""
 while y:y,d=(y/v,chr(y%v));x=d+x
 return decompress(x)

```

Code size is `281` bytes and it encodes the `6135` bytes into `860` unicode characters.

How it works:

To Encode:

1. Compress the string to be encoded.
2. Interpret the compressed string as a base 256 number.
3. Convert the number to binary.
4. Split the binary into groups of `19` bits, add a `1` bit to the beginning of each of them, and then convert to Unicode characters.

Decoding is the reverse.

Note that some versions of python can only handle unicode characters up to `0xFFFF`, and thus this code will raise a `ValueError`.

---
Tags: code-golf, kolmogorov-complexity
---


# Question
Title: Find amount of heads and tails from percentages
**Note: as this question has been marked as a duplicate, I have accepted an answer. However, I will still check this question if users can find a shorter way of doing it, and accept that answer.**

Given two numbers (which are multiples of `0.5`) representing `heads-percentage` and `tails-percentage` from a series of coin-flipping, output the *minimum* amounts of heads and tails to produce percentages such as those. Input and output can be in any form. However, output must be in a readable format (Good examples are `x y`, `[x y]`, etc).

Examples:

* Input: `25 75` (25% heads, 75% tails) Output: `1 3` (an output of `25 75` is invalid since that is not the *minimum* amounts of heads and tails to produce those percentages)
* Input: `30 70` (30% heads, 70% tails) Output: `3 7`
* Input: `99.5 0.5` (99.5% heads, 0.5% tails) Output: `199 1`

You may assume that there will always be a digit before and after a decimal point in an input (no `.5`s or `15.`s). You may also assume the input adds up to 100%. This is , shortest code in bytes wins!

# Answer
# Dyalog APL, 3 bytes

```
,÷∨

```

This is a dyadic function train that accepts the percentages as left and right arguments:

```
┌─┼─┐
, ÷ ∨

```

It is equivalent to the following, train-less function:

```
{(⍺,⍵)÷⍺∨⍵}

```

Try it online on TryAPL.

### How it works

```
  ∨  Compute the GCD of both arguments.
,    Concatenate both arguments.
 ÷   Divide the latter by the former.

```
> 12 votes

# Answer
## Python 2, 47 bytes

```
A,B=a,b=input()
while b:a,b=b,a%b
print A/a,B/a

```

Takes input like `15,20` and prints the output like `3 4`.

Performs the Euclidian algorithm to find the gcd, then scales the numbers by it.

Fortunately, Python will happily compute `%` on fractions, so inputs like `0.5 99.5` behave just the same. More type-strict languages (cough, Haskell) aren't so lucky.
> 7 votes

# Answer
# J, 4 bytes

```
,%+.

```

Explanation:

```
       (x +. y)     NB. GCD of the left and right inputs
      %             NB. divided by
(x, y)              NB. a vector consisting of the inputs

```

Try it online
> 7 votes

# Answer
# CJam, ~~25~~ 14 bytes

```
{_~{_@\%}h;f/}

```

This is an unnamed function that pops a list from the stack and leaves one in return. Like @xnor's answer, it uses the Euclidean algorithm to find the GCD, then divides the list elements by it.

Try it online in the CJam interpreter.

### How it works

```
_             Push a copy of the input array.
 ~            Dump its elements on the stack.
  {    }h     Do:
   _            Push a copy of the topmost integer.
    @           Rotate the bottom-most integer on top of it.
     \          Swap them.
      %         Calculate the residue of their division.
              While the residue is positive, repeat the loop.
         ;    Discard the last residue (0).
              This leaves the GCD on the stack.
          f/  Divide the elements of the input array by their GCD.

```
> 4 votes

# Answer
# Pyth, 12 bytes

```
J/R.5Q/RiFJJ

```

Like @xnor's answer, this divides each list item by their GCD. Pyth has the GCD as a built-in, but it doesn't work for floats out of the box.

Try it online.

### How it works

```
              (implicit) Save the evaluated input in Q.
 /R.5Q        Divide each element of Q by 0.5.
              This transforms the array's floats into integers.
J             Save the result in J.
        iFJ   Compute the GCD of the elements of J.
      /R   J  Divide the elements of J by their GCD.

```
> 3 votes

# Answer
# APL, 20 bytes

```
{⍺⍵÷⍺{0<⍵:⍵∇⍵|⍺⋄⍺}⍵}

```

This creates an unnamed dyadic function that accepts the inputs on the left and right and returns an array. Unlike Dennis' super slick Dyalog solution, this works with other versions of APL because it doesn't use trains and it doesn't assume that GCD () works for floats.

Explanation:

```
    ⍺{0<⍵:⍵∇⍵|⍺⋄⍺}⍵}   ⍝ Compute the GCD of the inputs using the Euclidean algorithm
{⍺⍵÷                   ⍝ Divide the inputs by their GCD

```

Try all test cases online
> 1 votes

# Answer
# Mathematica, 21 bytes

```
#/GCD@@Rationalize@#&

```

Another program with the same byte count is

```
#/GCD@@(Floor[2#]/2)&

```

Mma has never supported FP well...
> 1 votes

# Answer
# TI-BASIC, ~~31~~ ~~22~~ 24 bytes

Forgot to count new lines before...

```
Prompt A,B
gcd(2A,2B➡C
Disp 2A/C,2B/C

```

This was done in the middle of math class...
> 1 votes

# Answer
# Common Lisp, ~~168~~ 94

```
(let((x(floor(*(read)2)))(y(floor(*(read)2))))(format t "~A ~A"(/ x(gcd x y))(/ y(gcd y x))))

```

I missed the original bit about everything being a multiple of 0.5 (thanks xnor!), so this is a good bit shorter than my first go (Gotta' love that almost a third of those bytes are parentheses.)
> 0 votes

---
Tags: code-golf
---


title: Detect Time Travel

text:
# Question
Title: Detect Time Travel
Computers are everywhere nowadays - in cars, trains, skateboards, even nuclear reactors. The possibility that your software will run in a time travelling device is just a matter of time. Can you deal with it? Can you at least detect it?

Your task:

1. Write a program that loops and keeps querying the system time, in order to detect time travel.
2. If time moves forward a day or more between two consecutive queries, it's forward time travel. In this case, your program should print:
`TS TS: YYYY? You mean we're in the future?`
3. If time moves back, by any amount, between two consecutive queries, it's backward time travel. In this case, your program should print:
`TS TS: Back in good old YYYY.`
4. `TS TS` are the timestamps before and after the time travel. `YYYY` is the destination year.
5. Timestamps may be in any format, that includes at least the 4-digit year, month, day, hour, minute and second, separated by non-digits.

Limitations:

1. You must support dates in the 19th, 20th and 21st centuries, at least.
2. You must use a language that existed before this challenge was posted.
3. You must post your answers only after this challenge was posted.
4. You must use a language that existed before your answer was posted.
5. You may edit your answer only after you've posted it.
6. Your program must not print any output other than the required output. An occasional "Great Scott!" is allowed.

This is code-golf. The shortest answer wins.
Relevant movie references will probably make your answer too long, but might get you upvotes.

# Answer
> 3 votes
# CJam, 118 bytes

```
et:Tes{es_@-[TS*Set:TS*':S]\_864e5<{[1$et0="? You mean we're in the future?"N]o}|0<{[_"Back in good old "et0='.N]o}&}g

```

This does not work with the online interpreter.

Sample output after adjusting my computer's time twice:

```
2015 10 21 11 2 45 1 3 -10800000 2015 10 23 11 2 45 0 5 -10800000: 2015? You mean we're in the future?
2015 10 23 11 2 53 448 5 -10800000 2015 10 21 11 2 52 0 3 -10800000: Back in good old 2015.

```

# Answer
> 10 votes
## Python 2, 210 bytes

```
from datetime import*
o=0
while 1:n=datetime.now();o=o or n;print"%s;%s: %s? You mean we're in the future?"%(o,n,n.year)if(n-o).days>=1else"%s;%s: Back in good old %s."%(n,o,n.year)if(n<o)else"Great Scott!";o=n

```

Timestamps are printed in in `YYYY-MM-DD HH:MM:SS` format, separated with semicolons. Switched to Python 2 from 3 since it's 2 chars shorter to print. Spams stdout with `Great Scott!` for ~~normies~~ non-time-travellers, since it's easier and cheaper to do that than set up a conditional print.

# Answer
> 7 votes
# JavaScript (ES6), 263 bytes

```
n=Date;o=n.now();(function g(){k=new n;j=new n(o);s=`${k} ${o} `;if(n.now()-o>86400)console.log(`${s}${k.getFullYear()}? You mean we're in the future?`);if(o-n.now()>84600){console.log(`${s}Back in good old ${k.getFullYear()}.`);}o=n.now();setTimeout(g,100);}());

```

This could probably do with some rewriting to make it more efficient/small.

Source:

```
n=Date;
o=n.now();

(function go() {
   k=new n;
   j=new n(o);
   s=`${k} ${o} `;
   if (n.now() - o > 86400) {
      console.log(`${s}${k.getFullYear()}? You mean we're in the future?`);
   }
   if (o - n.now() > 84600) {
      console.log(`${s}Back in good old ${k.getFullYear()}.`);
   }
   o=n.now()
   setTimeout(go,100);
}());

```

# Answer
> 5 votes
# Bash + coreutils, 177

```
d()(date -d@"$@")
for((b=`date +%s`;a=`date +%s`;b=a)){
t=`d $a`\ `d $b`
((a<b))&&d $b "+$t: Back in good old %Y."
((a>b+86400))&&d $b "+$t: %Y? You mean we're in the future?"
}

```

# Answer
> 4 votes
# Python 3, 195

```
from datetime import*
n=datetime.now
p=n()
while 1:
 c=n();f=(p,c,p.year);s=(0,("%s %s: %s? You mean we're in the future?"%f,"%s %s: Back in good old %s."%f)[p.day>c.day])[p>c];p=c
 if s:print(s)

```

Currently doesn't print Great Scott because I can't find a good way of only making it occasional.

# Answer
> 2 votes
# Lua 5.3, ~~179~~ ~~178~~ ~~173~~ ~~171~~ ~~169~~ ~~168~~ 163 bytes

```
q="%Y %c: "c=os.date::a::d=f f=os.time()_=d and(f-d>86399or f<d)and print(c(q,d)..c(q..(f<d and"Back in good old %Y."or"%Y? You mean we're in the future?")))goto a

```

Side note: If you take out the need for a full year number then subtract six bytes. The reason is that lua's (or windows' or someone's!) %c doesn't output the full year. Because of this, the timestamps may look weird!

This also takes advantage of timestamps being able to be seperated by any non digit characters!

Thanks for notifying me of my old math.abs reference and other improvements @thenumbernine :)

# Lua 5.3, 151 bytes

This is 'copying' off of @thenumbernine's method of displaying time by just showing the timestamp instead of the actual date. This isn't competitive since I think it is a bit of cheating, just posting it here to display my work :)

```
::a::d=f f=os.time()_=d and(f-d>86399or f<d)and print(d.." "..f..os.date(f<d and": Back in good old %Y."or": %Y? You mean we're in the future?"))goto a

```

# Answer
> 2 votes
# Lua 5.3, 174 bytes

```
T=os.time P=print l=T()::a::t=T()b=l.." "..t..": "y=os.date('%Y',t)_=t<l and
P(b.."Back in good old "..y)or t>l+86399 and
P(b..y.."? You mean we're in the future?")l=t goto a

```

This is playing heavily off of the "Timestamps may be in any format" rule ... which I took the liberty of using the format of "seconds since Jan 1, 1970"
If I keep my shoddy interpretation of printing timestamps, and adopt the structure of MeepDarknessMeep, I can (unethically) squeeze this down to ...

# 155 bytes

```
T=os.time::G::l=t or T()t=T()_=(t>l+86399or t<l)and
print(l.." "..t..": "..os.date(t<l
and"Back in good old %Y"or"%Y? You mean we're in the future?"))goto G

```

# Answer
> 2 votes
# Ruby, 194 bytes

I haven't had the time to really cut this down to size yet. I'm sure there are a few optimizations hiding in there.

```
require 'time';t=nil;while 1;n=Time.now;if t;s="#{t} #{n}: ";y=n.year;puts t>n ? "#{s}Back in good old #{y}" : (n>t+86400 ? "#{s}#{y}? You mean we're in the future?": "Great Scott!");end;t=n;end

```

Ungolfed (and a lot more readable):

```
require 'time'
t=nil
while 1
  n=Time.now
  if t                                             # on second or later pass
    s="#{t} #{n}: "                                # prepare the timestamp
    y=n.year
    puts t>n ?                                     # if we go back
      "#{s}Back in good old #{y}" :                # timestamp + phrase
      (n>t+86400 ?                                 # else, more than one day forward
        "#{s}#{y}? You mean we're in the future?": # timestamp + future
        "Great Scott!")                            # Great Scott!
  end
  t=n                                              # set a new jump point
end

```

Edit: corrected to ask OS for time, rather than a human.

# Answer
> 2 votes
# Python, 170 165 bytes

```
from datetime import*
n=datetime.now
c=n()
while 1:
 p=c;c=n()
 if(c-p).days:print p,"%s:"%c,["%s? You mean we're in the future?","Back in good old %s."][c<p]%c.year

```

This owes a lot to Morgan Thrapp's answer. The main trick here is timedelta normalization, which conveniently makes timedelta.days negative when moving even slightly towards the past, and 0 when moving less than a day to the future.

# Answer
> 1 votes
# Caché ObjectScript, 199 bytes

```
l s k=86400 f  s e=+$H,t=$P($H,",",2) s:'d d=e,s=t s z=$ZDT(h)_" "_$ZDT($H)_": ",y=h\365+1841 w:e>d !,z,y,"? You mean we're in the future?" w:(k*t+e)<(k*s+d) !,z,"Back in good old ",y s h=$H,d=e,s=t

```

This problem is solvable in plain old MUMPS, but would be unreasonably lengthy, since ANSI MUMPS lacks the `$ZD[ATE]T[IME]` intrinsic function for formatting dates into human-readable timestamps.

This program will probably not detect time-travel to before 1 Jan 1841, nor time-travel to after 31 Dec 9999, since these are the bounds of the `$H[OROLOG]` timekeeping intrinsic. This program also only has second-level precision; sub-second-level backwards time glitches will likely escape its notice.

# Answer
> 1 votes
## TSQL, 355 bytes

At the work so no fancy cool languges stick with your SQL Server production server =)

Golfed version

```
declare @a datetime=getdate(),@b datetime,@d float,@ char(99),@y char(4)while 0=0begin select @b=getdate(),@d=cast(@b as float)-cast(@a as float),@y=' '+DATEPART(y,@b),@=cast(@a as char(20))+' '+cast(@a as char(20))+': 'if @d>=1set @=@+@y+'? You mean we''re in the future?'if @d<0set @=@+'Back in good old '+@y+'.'print @ set @a=@b end

```

More readable version with minor changes.

```
declare @t0 datetime = getdate(), @t1 datetime, @d float, @m varchar(99), @y char(4)

while 0=0
begin

    set @t1 = getdate()
    set @d = cast(@t1 as float) - cast(@t0 as float)
    set @y = ' ' + DATEPART(yy, @t1)
    set @m = cast(@t0 as varchar(30)) + ' ' + cast(@t0 as varchar(30)) + ': '

    if @d >= 1 set @m = @m + @y + '? You mean we''re in the future?'
    if @d < 0 set @m = @m +  'Back in good old ' + @y + '.'

    print @m

    set @t0 = @t1
end

```

SQL is not that bad in respect to timestamps since it's a first class data type.

For the golf's sake we are using a type with 3 milliseconds precision. The loop itself takes less that that to iterate (depending of your server). The key here is internaly that time stamp is a float and the integer type counts how many days passed. It ill work fine in January 1, 1753, through December 31, 9999 date range.

# Answer
> 1 votes
# VBA, 258 Bytes

### Ran with:Excel 2007 in Windows 7

**305 bytes** if Usability is required

> WARNING This MAY Max your CPU and Crash Excel/Windows if you are on a Single Threaded single core computer (Most likely found in 1985)

```
Sub q()
h=CDbl(Now())
While 1
t=CDbl(Now())
If t>h+1 Then Debug.Print (CDate(t) & " " & CDate(h) & ":" & Year(t) & "? You mean we're in the future?")
If t<h Then Debug.Print (CDate(t) & " " & CDate(h) & ": Back in good old " & Year(t) & ".")
h=t
Wend
End Sub

```

If you want this Code to be "Testable" then add `Application.Wait (Now() + TimeValue("0:00:01"))` after `h=t`

### Output

```
10/22/2015 3:04:45 PM 10/22/2015 3:04:43 PM:2015?You mean we're in the future?
10/22/2015 3:06:48 PM 10/22/2015 3:06:46 PM: Back in good old 2015.

```

Below is the test file I used. I'm Honestly Amazed at how little security Windows has sometimes. May not run as expected on all computers

> Run at Own Risk Could Have Major lasting Side Effects!!!!
> `Sub DOC()
>  t = 31346.6868055556
>  Date = DateSerial(Year(t), Month(t), Day(t))
>  Time = TimeSerial(Hour(t), Minute(t), Second(t))
>  q
>  End Sub`

# Answer
> 1 votes
# JavaScript (ES6) 181 174 170 Bytes

```
for(a=Date;c=b||a.now(),b=d();e=new a(b).getFullYear(),f=`${a(c)} ${a(b):`})b>c+864e5?(g=alert)`${f} ${e}? You mean we're in the future?`:c>b&&g`${f} Back in good old `+e

```

**Note:** Has not been tested with a real time machine.

This code runs in Firefox, Chrome, Edge, Node.js Harmony (or io.js for that matter). But, I use `alert`, so that will have to be replaced by `console.log` for Node and Io Suport: (187 Bytes)

```
for(a=Date,b=0;c=b||(d=a.now)(),b=d();e=new a(b).getFullYear(),f=`${a(c)} ${a(b):`})b>c+864e5?(g=console.log)`${f} ${e}? You mean we're in the future?`:c>b&&g`${f} Back in good old ${e}.`

```

Explained:

```
// Using for like a while loop, defining relevant variables:
  for (a = Date, b = 0;
// Defing b and c: c becomes b, b becomes now. Also defining a shorthand for Date.now:
  c = b || a.now(),
  b = d();
// Defining Variables Relevant to this loop: e is the year according to b, f is the "TS TS:" string:
  e = new a(b).getFullYear(),
  f = `${a(c)} ${a(b):`
  )
// If b is greater than c plus a day (in milliseconds):
  b > c + 864e5 ?
  // Alert Time Forwand String:
    (g = alert)
    `${f} ${e}? You mean we're in the future?`:
// else if c is greater than b:
  c > b &&
  // Alert Time Back String:
    g `${f} Back in good old `+e

```

# Answer
> 1 votes
# C: 363 bytes

Minified using this handy script:

```
#include<stdio.h>
#include<time.h>
void p(time_t*t){char b[64];strftime(b,64,"%FT%T",localtime(t));printf("%s ",b);}int main(void){time_t a,b,d=60*60*24;int y;time(&a);while(1){time(&b);y=localtime(&b)->tm_year+1900;if(b<a){p(&a);p(&b);printf("Back in good old %d\n",y);}else if(b>a+d){p(&a);p(&b);printf("%d? You mean we're in the future?\n",y);}a=b;sleep(1);}}

```

Original:

```
#include <stdio.h>
#include <time.h>

void p(time_t * t) {
  char b[64];
  strftime(b, 64, "%FT%T", localtime(t));
  printf("%s ", b);
}

int main(void) {
  time_t a, b, d = 60*60*24;
  int y;

  time(&a);
  while(1) {
    time(&b);
    y = localtime(&b)->tm_year+1900;
    if (b < a) {
      p(&a); p(&b); printf("Back in good old %d\n", y);

    } else if (b > a + d) {
      p(&a); p(&b); printf("%d? You mean we're in the future?\n", y);
    }
    a = b;
    sleep(1);
  }
}

```

Example run:

```
2015-10-23T23:30:03 1985-06-14T16:27:00 Back in good old 1985
1985-06-14T16:27:07 1999-02-09T14:15:00 1999? You mean we're in the future?
1999-02-09T14:15:09 2015-02-09T14:15:00 2015? You mean we're in the future?
2015-02-09T14:15:36 2015-10-21T07:28:00 2015? You mean we're in the future?
2015-10-21T07:29:06 1985-10-26T09:00:00 Back in good old 1985
1985-10-26T09:00:28 2055-11-12T06:38:00 2055? You mean we're in the future?
2055-11-12T06:38:12 1919-10-07T00:09:57 Back in good old 1919
1919-10-07T00:09:57 2055-11-12T06:38:14 2055? You mean we're in the future?  # tried to go to 1955 - fail.
2055-11-12T06:39:09 2015-10-23T23:32:03 Back in good old 2015  # auto-time back to 2015 because my laptop didn't like the jump to 2055!

```

I could get rid of 10 bytes by removing the `sleep` I guess.

By the way, some time-jumping handiness for Mac/Linux:

```
sudo date 1026090085  # Sat 26 Oct 1985 09:00:00
sudo date 1021072815  # Wed 21 Oct 2015 07:28:00
sudo date 1112063855  # Intended to be 1955 but is 2055. Don't use!

```

# Answer
> 0 votes
## Processing, 270 bytes

```
int p;long x=System.currentTimeMillis();void draw(){int q=millis(),y=year();if(q<p){t(p);print("Back in good old "+y+".");}if(q>p+86400000){t(p);print(y+"? You mean we're in the future?");}p=q;}void t(int m){print(new java.util.Date(x+m)+" "+new java.util.Date()+": ");}

```

Expanded:

```
int p;
long x=System.currentTimeMillis();
void draw() {
  int q=millis(), y=year();
  if (q<p) {
    t(p);
    print("Back in good old "+y+".");
  }
  if (q>p+86400000) {
    t(p);
    print(y+"? You mean we're in the future?");
  }
  p=q;
}
void t(int m) {
  print(new java.util.Date(x+m)+" "+new java.util.Date()+": ");
}

```

Sample output:

```
Wed Oct 21 13:21:59 EDT 2015 Mon Oct 19 13:21:59 EDT 2015: Back in good old 2015.
Mon Oct 19 13:22:08 EDT 2015 Wed Oct 21 13:22:08 EDT 2015: 2015? You mean we're in the future

```

# Answer
> 0 votes
# Javascript 173 169 162 bytes

Javascript is pretty popular...

```
for(e=Date,n=e.now;o=n(a=alert);)d=new e,f=d.getFullYear(n(o>n(s=d+` ${e(o)}:`)&&a(s+`Back in good old ${f}.`))-o>864e5&&a(s+f+`? You mean we're in the future?`))

```

Explanation (Older version of the code):

```
for(e=Date,n=e.now,a=alert,o=n();;o=n()) //Set up the variables and update o, the previous time

d=new e,s=d+` ${e(o)} `,f=d.getFullYear(), //d is the date, s is a string with the 2 timestamps, f is the year
n()-o>8.64e7&&a(s+f+`? You mean we're in the future?`), //Future check
o>n()&&a(s+`Back in good old ${f}.`) //Past check

```

# Answer
> 0 votes
# Ruby, ~~160~~ ~~157~~ ~~155~~ 154 bytes

A lot of things to golf here

```
a=Time.new;loop{b,s,y=Time.new,"#{a} #{b}: ",b.year;$><<(a>b ? s+"Back in good old #{y}.\n":b>a+86400 ? s+"#{y}? You mean we're in the future?\n":"");a=b}

```

# Answer
> 0 votes
# Mathematica, 295 bytes

The program asks the OS every second for new TS.

```
f:=LocalTime[]
p=Print;
y:=DateString[#,"Year"]&
s:=ToString[#]<>" "&
d:=QuantityMagnitude@DateDifference[a,b]
j=StringJoin;
While[True,
  a=b;
  b=f;
  Pause@1;
  Which[d>=0,
   p@(j@@{s@a,s@b,": ",y@b,
       "? You mean we are in the future?"}),
   d<0,
   p@(j@@{s@a,s@b," Back in good old ",y@b,"."})]];

```

# Output

Tested by manually feeding in date/time.

```
DateObject[{2015, 10, 23}, TimeObject[{18, 36, 17.9618}], TimeZone -> \
-4.] DateObject[{2015, 10, 25}, TimeObject[{18, 42, 0.264913}], \
TimeZone -> -4.] : 2015? You mean we are in the future?

DateObject[{2015, 10, 23}, TimeObject[{18, 43, 0.141572}], TimeZone -> -4.] DateObject[{2015, 10, 23}, TimeObject[{18, 42, 3.30681}], TimeZone -> -4.]  Back in good old 2015.

```

Definitely could have format the output better. It does fulfill the requirements as stated.

# Answer
> 0 votes
# Groovy, 244 bytes

```
def s=9999,d={new Date()},y={it.year+1900},f={t,n->"$t $n: ${y(n)}? You mean we're in the future?"},p={t,n->"$t $n: Back in good old ${y(n)}."},t=d()
while(!sleep(s)){n=d()
c=n.time-t.time
println c<0?p(t,n):c>s*2?f(t,n):'Great Scott!'
t=n}

```

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


title: Circular Blues

text:
# Question
Title: Circular Blues
Write a program or function that takes in a positive integer N and recreates this pattern of circles scaled to fit an N×N pixel image:

This image is a valid output example for N = 946.

In case it's not clear, all the small light-blue circles have the same radius and are positioned in the four dark-blue circles in the same way. The dark-blue circles have double that radius and are similarly positioned in the large light-blue circle.

* Any two visually distinct colors may be used in place of the two shades of blue.
* The background square does need to be colored.
* Anti-aliasing is optional.
* Save the image to a file, display it, or pipe the raw image data to stdout.
* Any common image file format is allowed.

**The shortest code in bytes wins.**

Brownie points if you extend the recursive aspects of this circle pattern into further levels. (Keep this distinct from your challenge entry.)

# Answer
> 6 votes
# CJam, 83 bytes

```
"P1"li___,.5f+2.@/f*1fm2m*{[3{_~mh1<[[VX][ZmqV]]_Wff*+@2f*f.+{~mh}$0=}*;0]0#2%}%]S*

```

Try it online

CJam does not have dedicated image output functionality. My code generates an image in PBM ASCII. For posting, I converted that image to a PNG using GIMP.

Note that no circle drawing functionality, or anything like that, it used. The image is calculated pixel by pixel.

Higher degrees of the subdivision can easily be created by increasing the constant `3` around the middle of the code.

The degree 4 and 5 images look like this:

The overall sequence of the code is:

1. Generate the coordinates of all pixels, normalized to range \[-1.0, 1.0\].
2. Loop over all pixels.
3. Loop over degrees of subdivision.
4. For each subdivision, check if the pixel is inside/outside, and keep the result. The scale/translate the pixel coordinates to the coordinate systems centered at one of the 4 sub-circles. Pick the one where the transformed coordinates are closest to the center.
5. From the binary inside/outside results of each degree, find the first 0, corresponding to the first degree where the pixel was outside, and take its modulo 2 to determine the color of the pixel.

Explanation:

```
"P1"    Start of header for PBM ASCII file.
li      Get input n.
__      Two copies for the width/height of the image in the PBM header.
_,      Generate [0 .. n - 1].
.5f+    Add 0.5 to each list entry, since we want to test the pixel centers.
2.@/    Calculate 2.0 / n, which is the distance between two pixels.
f*      Multiply the unscaled pixel coordinates with the pixel distance.
        We now have coordinates in the range [0.0, 2.0].
1fm     Subtract one from each, giving coordinates in range [-1.0, 1.0].
2m*     Cartesian power to calculate all y/x pairs.
{       Start loop over all pixel coordinates.
  [       Start wrapping the inside/outside results for all degrees.
  3{      Start loop over degrees.
    _~mh    Calculate distance from center.
    1<      Compare with 1. This gives inside/outside result for degree.
    [       Start building list of centers for 4 sub-circles.
    [VX]    One is at [0 1]. Note that coordinate order is y/x.
    [ZmqV]  Next one is at [sqrt(3) 0].
    ]       Wrap these two...
    _       ... and copy them.
    Wff*    Mirror all coordinates by multiplying with -1.
    +       Concatenate, giving the centers of all 4 sub-circles.
    @       Get current coordinates to top.
    2f*     Multiply them by 2. Note that the coordinates need to be scaled up by
            a factor 2 to give a circle with half the radius when we test the distance
            to the origin against 1.0.
    f.+     Add the current coordinates to the centers of all 4 sub-circles.
            For each sub-circle, this puts the current coordinates in a coordinate
            space with the origin at the center, and with a radius of 1.0
    {~mh}$  Sort them by distance to the origin...
    0=      ... and take the first one. This picks the sub-circle which has its
            center closest to the current coordinates.
            We now have one coordinate pair, for the closest sub-circle, and are
            ready for the next loop iteration, which tests the next degree of the
            subdivision.
  }*      End loop over degrees.
  ;       Have remaining coordinate pair on stack, pop it.
  0       Add a sentinel for find operation before, so that a 0 is always found.
  ]       End wrapping the inside/outside results for all degrees.
  0#      Find the first 0 (outside) degree.
  2%      Modulo 2 to determine color.
}%      End loop over all pixel coordinates.
]       Wrap the pieces of the PBM header and the pixel list.
S*      Join them with spaces, to produce the necessary spaces for the header.

```

# Answer
> 17 votes
# Python 2 + PIL, 262 bytes

This approach determines the color of each individual pixel coordinate using recursive function `c`. `c(x,y,0)` renders a circle; `c(x,y,1)` renders a circle with four circles cut out of it; `c(x,y,2)` renders the image in the OP. Anything larger than 2 earns me brownie points.

```
import PIL.Image as I
d=3**.5/2
c=lambda x,y,l=0:c(x,y)&~any(c((x+i)*2,(y+j)*2,l-1)for i,j in[(.5,0),(-.5,0),(0,d),(0,-d)])if l else x*x+y*y<1
z=input()
f=lambda s:2.*s/z-1
I.frombytes("L",(z,z),"".join(" ~"[c(f(i%z),f(i/z),2)]for i in range(z*z))).save("p.png")

```

Non-golfed version:

```
from PIL import Image
import math
def in_shape(x,y, level=0):
    d = math.sqrt(3)/2
    if level == 0:
        return x**2 + y**2 <= 1
    else:
        t = True
        for dx,dy in [(0.5, 0), (-0.5, 0), (0, d), (0,-d)]:
            if in_shape((x+dx)*2, (y+dy)*2, level-1):
                t = False
        return in_shape(x,y) and t

f = lambda s: ((2*s / float(size))-1)

size = input()
img = Image.new("RGB", (size, size))
pix = img.load()
for i in range(size):
    for j in range(size):
        if in_shape(f(i), f(j), 2):
            pix[i,j] = (0,0,0)
        else:
            pix[i,j] = (255,255,255)
img.save("output.png")

```

Bonus extra-recursive image:

# Answer
> 9 votes
# PostScript, 335 bytes.

```
%!
/D{def}def/B{bind D}D/E{exch}B/A{add}D/c{3 copy 3 -1 roll A E moveto 0 360 arc}B/f{5 dict begin/d E D/r E D/y E D/x E D gsave x y r c clip d 2 mod setgray x y r c fill d 0 gt{/h 3 sqrt 2 div r mul D/r r 2 div D/d d 1 sub D x r A y r d f x r sub y r d f x y h A r d f x y h sub r d f}if grestore end}B 512 2 div dup dup 2 f showpage

```

PostScript isn't just a graphics file format with both vector and bitmap capabilities, it's actually an object-based Turing-complete programing language. The code above is a fairly straight-forward recursive function implementation. All PostScript operators are functions, and it's commonplace to redefine them to condense code. Note that PostScript uses Reverse Polish notation (aka postfix notation).

PostScript interpreters generally read metadata (like page size and title) from special comments at the start of the file; obviously I've removed all but the bare essential PostScript signature comment `%!` from my entry, but it should still display ok in any standard PostScript interpreter, eg GhostScript or Okular. It can also be viewed using the *display* utility that comes with ImageMagick / GraphicsMagick.

Note that the file should end in a newline (which I've included in my byte count), or the interpreter may get upset.

The size parameter `N` for this code is 512; it's divided by 2 and duplicated twice to create the parameters for the initial call of the recursive function `f`. The recursion depth is 2, which is given just before the `f` in `512 2 div dup dup 2 f`. To keep the size small the output is black & white. Although you can set any reasonable non-negative integer recursion depth this version only looks good with even depths.

This image is a vector graphic, so it can be displayed in any resolution without pixelization, depending on the quality & settings of the PostScript interpreter / printer used. (FWIW, PostScript uses Bézier cubic curves to draw circular arcs, with enough splines used to ensure that the error is always less than one pixel in device space). To view it using ImageMagick's *display* in reasonably high quality you can do:

```
display -density 300 -geometry 512x512 -page 512x512

```

the same parameters are also good if you wish to use ImageMagick's `convert` to convert it to another format. Eg, here's a 640x640 version of the above PostScript code converted to PNG:

---

Here's a slightly larger version that handles RGB color and odd recursion depths:

```
%!PS-Adobe-3.0
/D{def}def/N 512 D/d 2 D/B{bind D}D/E{exch}B/A{add}D/c{3 copy 3 -1 roll A E moveto 0 360 arc}B/k{2 mod 0 eq{.3 .6 .9}{0 .2 .5}ifelse setrgbcolor}B d 1 A k 0 0 N N rectfill/f{5 dict begin/d E D/r E D/y E D/x E D gsave x y r c clip d k x y r c fill d 0 gt{/h 3 sqrt 2 div r mul D/r r 2 div D/d d 1 sub D x r A y r d f x r sub y r d f x y h A r d f x y h sub r d f}if grestore end}B N 2 div dup dup d f showpage

```

It also allows you to set the size parameter `N` and the recursion depth `d` near the top of the script.

---

Finally, here's the more readable form of the code. (Unfortunately, the syntax highlighting used here for PostScript leaves a *lot* to be desired, but I *guess* it's better than nothing...). Smart PostScript interpreters will read the page geometry from the `%%BoundingBox:` special comment.
```
%!PS-Adobe-3.0
%%BoundingBox: 0 0 640 640
%%Title: Circle fractal
%%Creator: PM 2Ring
%%Creationdate: (Oct 29 2015)
%%Pages: 1 1
%%EndComments

% for http://codegolf.stackexchange.com/questions/61989/circular-blues

% ----------------------------------------------------------------------

16 dict begin

%Total image width & height in points / pixels
/N 640 def

%Maximum recursion depth
/Depth 4 def

% ----------------------------------------------------------------------

%Draw a circle centred at (x,y), radius r. x y r circle -
/circle{
    3 copy      % x y r  x y r
    3 -1 roll   % x y r  y r x
    add exch    % x y r  x+r y
    moveto
    0 360 arc
}bind def

% ----------------------------------------------------------------------

%Select 1st color if n is even, select 2nd color if n is odd. n color -
/color{
    2 mod 0 eq
    {.36 .6 .9}
    {0 .25 .5}
    ifelse
    setrgbcolor
}bind def

%Do background square
Depth 1 add color
0 0 N N rectfill

/Q 3 sqrt 2 div def

%Recursive circle pattern. x y r Depth cfrac -
/cfrac{
    5 dict begin
    /Depth exch def
    /r exch def
    /y exch def
    /x exch def

    gsave
    x y r circle clip
    Depth color
    x y r circle fill

    Depth 0 gt
    {
        /dy Q r mul def
        /r r 2 div def
        /Depth Depth 1 sub def

        x r add y r Depth cfrac
        x r sub y r Depth cfrac
        x y dy add r Depth cfrac
        x y dy sub r Depth cfrac
    }if
    grestore
    end
}bind def

%Call it!
N 2 div dup dup Depth cfrac

showpage

% ----------------------------------------------------------------------

%%Trailer
end
%%EOF

```

And here's the depth==4 output in PNG format, once again created using *convert* (and optimized with *optipng*):

# Answer
> 6 votes
# Python 2 + PIL, 361 bytes

```
import PIL.Image as p,PIL.ImageDraw as d
W=input()
q=W/4
h=2*q
t=3*q
e=W/8
o=int(q*3**.5)
I,J=[p.new("1",(s,s),s>h)for s in[W,h]]
Q=lambda i,x,y,s=q,c=0:d.Draw(i).ellipse((x,y,x+s,y+s),fill=c)
Q(I,0,0,W)
Q(J,0,0,h,1)
[Q(J,k,e)for k in[0,q]]
[Q(J,e,e+k/2)for k in[-o,o]]
[I.paste(1,k,J)for k in[(0,q,h,t),(h,q,4*q,t),(q,q-o,t,t-o),(q,q+o,t,t+o)]]
I.save("c.png")

```

Saves the image in black & white to the file `c.png`:

I basically generate one of the half-sized circles in the image `J`. I then use itself as a mask to paint the shape onto image `I`, which has the main circle.

It could be shortened using `I.show()` at the end instead of `I.save("c.png")`, but I didn't get it working on Python 2. If someone can confirm it works on Python 2 I'll change to that.

The following program generates the image as in the question (419 bytes):

```
import PIL.Image as p,PIL.ImageDraw as d
W=int(input())
q=W/4
h=2*q
t=3*q
e=W/8
o=int(q*3**.5)
I,J=[p.new(["1","RGB"][s>h],(s,s),s>h and"rgb(13,55,125)")for s in[W,h]]
Q=lambda i,x,y,s=q,c=0:d.Draw(i).ellipse((x,y,x+s,y+s),fill=c)
Q(I,0,0,W,"rgb(97,140,224)")
Q(J,0,0,h,1)
[Q(J,k,e)for k in[0,q]]
[Q(J,e,e+k/2)for k in[-o,o]]
[I.paste("rgb(13,55,125)",k,J)for k in[(0,q,h,t),(h,q,4*q,t),(q,q-o,t,t-o),(q,q+o,t,t+o)]]
I.save("c.png")

```

# Answer
> 4 votes
## SVG (1249 characters)

Yeah, lots of characters. But it’s static and renders at any size, so that gives it some bonus.

```
<svg xmlns="http://www.w3.org/2000/svg"><path d="M15,33c-2.5,0-4.6,1.9-4.9,4.3c2.8,1.6,6.1,2.6,9.5,2.6c0.3-0.6,0.4-1.3,0.4-2C20,35.2,17.8,33,15,33zM15,7c2.8,0,5-2.2,5-5c0-0.7-0.1-1.4-0.4-2c-3.5,0.1-6.7,1-9.5,2.6C10.4,5.1,12.5,7,15,7zM25,33c-2.8,0-5,2.2-5,5c0,0.7,0.1,1.4,0.4,2c3.5-0.1,6.7-1,9.5-2.6C29.6,34.9,27.5,33,25,33zM25,7c2.5,0,4.6-1.9,4.9-4.3C27.1,1,23.9,0.1,20.4,0C20.1,0.6,20,1.3,20,2C20,4.7,22.2,7,25,7zM35,28.7C34.8,26,32.6,24,30,24s-4.8,2.1-5,4.7c-3-1.7-5-5-5-8.7c0,3.7-2,6.9-5,8.7C14.8,26,12.6,24,10,24S5.2,26,5,28.7c-3-1.7-5-5-5-8.7c0,7.4,4,13.9,10,17.3c0.1-1.2,0.4-2.4,0.8-3.4c0.9-1.9,2.3-3.5,4.1-4.5c0,0,0,0,0.1,0c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c0,0,0,0,0.1,0c1.8,1,3.2,2.6,4.1,4.5c0.5,1.1,0.8,2.2,0.8,3.4c6-3.5,10-9.9,10-17.3C40,23.7,38,26.9,35,28.7zM5,11.3c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c3,1.7,5,5,5,8.7c0-3.7,2-6.9,5-8.7c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c3,1.7,5,5,5,8.7c0-7.4-4-13.9-10-17.3c-0.1,1.2-0.4,2.4-0.8,3.4C28.3,8,26.8,9.6,25,10.6c0,0,0,0-0.1,0C24.8,8,22.6,6,20,6s-4.8,2.1-5,4.7c0,0,0,0-0.1,0c-1.8-1-3.2-2.6-4.1-4.5C10.4,5,10.1,3.9,10,2.6C4,6.1,0,12.6,0,20C0,16.3,2,13,5,11.3z"/><circle cx="15" cy="20" r="5"/><circle cx="5" cy="20" r="5"/><circle cx="35" cy="20" r="5"/><circle cx="25" cy="20" r="5"/></svg>

```

Viewable snippet:

```
svg { fill: #9FD7FF; background: #2176AA; }
```

```
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 40 40">
  <path d="M15,33c-2.5,0-4.6,1.9-4.9,4.3c2.8,1.6,6.1,2.6,9.5,2.6c0.3-0.6,0.4-1.3,0.4-2C20,35.2,17.8,33,15,33zM15,7c2.8,0,5-2.2,5-5c0-0.7-0.1-1.4-0.4-2c-3.5,0.1-6.7,1-9.5,2.6C10.4,5.1,12.5,7,15,7zM25,33c-2.8,0-5,2.2-5,5c0,0.7,0.1,1.4,0.4,2c3.5-0.1,6.7-1,9.5-2.6C29.6,34.9,27.5,33,25,33zM25,7c2.5,0,4.6-1.9,4.9-4.3C27.1,1,23.9,0.1,20.4,0C20.1,0.6,20,1.3,20,2C20,4.7,22.2,7,25,7zM35,28.7C34.8,26,32.6,24,30,24s-4.8,2.1-5,4.7c-3-1.7-5-5-5-8.7c0,3.7-2,6.9-5,8.7C14.8,26,12.6,24,10,24S5.2,26,5,28.7c-3-1.7-5-5-5-8.7c0,7.4,4,13.9,10,17.3c0.1-1.2,0.4-2.4,0.8-3.4c0.9-1.9,2.3-3.5,4.1-4.5c0,0,0,0,0.1,0c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c0,0,0,0,0.1,0c1.8,1,3.2,2.6,4.1,4.5c0.5,1.1,0.8,2.2,0.8,3.4c6-3.5,10-9.9,10-17.3C40,23.7,38,26.9,35,28.7zM5,11.3c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c3,1.7,5,5,5,8.7c0-3.7,2-6.9,5-8.7c0.2,2.6,2.3,4.7,5,4.7s4.8-2.1,5-4.7c3,1.7,5,5,5,8.7c0-7.4-4-13.9-10-17.3c-0.1,1.2-0.4,2.4-0.8,3.4C28.3,8,26.8,9.6,25,10.6c0,0,0,0-0.1,0C24.8,8,22.6,6,20,6s-4.8,2.1-5,4.7c0,0,0,0-0.1,0c-1.8-1-3.2-2.6-4.1-4.5C10.4,5,10.1,3.9,10,2.6C4,6.1,0,12.6,0,20C0,16.3,2,13,5,11.3z"/>
  <circle cx="15" cy="20" r="5"/>
  <circle cx="5" cy="20" r="5"/>
  <circle cx="35" cy="20" r="5"/>
  <circle cx="25" cy="20" r="5"/>
</svg>
```

# Answer
> 3 votes
# Mathematica ~~336~~ 359 bytes

The principal graphics objects are regions defined through logical combinations of equations.

```
r=Red;i=ImplicitRegion;m=i[-2<x<2&&-2<y<2,{x,y}];n=Input[];
t[a_,b_,c_]:=i[(x+a)^2+(y+b)^2<=c,{x,y}];
a_~f~b_:={t[a,b,1],t[-.5+a,b,1/4],t[.5+a,b,1/4],t[a,b-.865,1/4],t[a,b+.865, 1/4]}
g@d_:=RegionIntersection[m,BooleanRegion[#1&&!#2&&!#3&&!#4&&!#5&,d]]
RegionPlot[{m,t[0,0,4],g@f[1,0],g@f[-1,0],g@f[0,1.75],
g@f[0, -1.75]},ImageSize->n,PlotStyle->{r,Blue,r,r,r,r}]

```

# Answer
> 1 votes
# Java, 550

```
import javafx.application.*;import javafx.scene.*;import javafx.scene.layout.*;import javafx.scene.shape.*;import javafx.stage.*;public
class C extends Application{static long n;Shape d(float m,float k,float x,float y){float h=m/2;Shape
s=new Circle(x+h,y+h,h);return k>0?s.subtract(s,s.union(s.union(s.union(d(h,k-1,x,y+m/4),d(h,k-1,x+h,y+m/4)),d(h,k-1,x+m/4,y-m*.183f)),d(h,k-1,x+m/4,y+m*.683f))):s;}public
void start(Stage s){s.setScene(new Scene(new Pane(d(n,2,0,0))));s.show();}public
static void main(String[]a){n=Long.valueOf(a[0]);launch();}}

```

Mostly just experimenting with JavaFX.

Screenshot:

For brownie points, change the `2` in the code (`d(n,2,0,0)`) to a different number.

**Old version, 810**

```
import javafx.application.*;import javafx.scene.*;import javafx.scene.canvas.*;import javafx.scene.effect.*;import javafx.scene.layout.*;import javafx.scene.paint.*;import javafx.stage.*;public
class C extends Application{static long n;Canvas c;GraphicsContext g;void
d(float m,float k,float x,float y){if(k>0){float
h=m/2;g.save();g.beginPath();g.arc(x+h,y+h,h,h,0,360);g.clip();g.fillRect(x,y,m,m);d(h,k-1,x,y+m/4);d(h,k-1,x+h,y+m/4);d(h,k-1,x+m/4,y-m*.183f);d(h,k-1,x+m/4,y+m*.683f);g.restore();}}public
void start(Stage s){c=new Canvas(n,n);g=c.getGraphicsContext2D();g.setGlobalBlendMode(BlendMode.DIFFERENCE);g.setFill(Color.TAN);g.fillRect(0,0,n,n);d(n,3,0,0);Pane
p=new Pane();p.getChildren().add(c);s.setScene(new Scene(p));s.show();}public
static void main(String[]a){n=Long.valueOf(a[0]);launch();}}

```

It leaves some undesired edges as you can see in this screenshot.

# Answer
> 0 votes
# JavaScript (ES6), 279

Recursively create canvases and add the child canvas four times to its parent canvas. At the bottom layer, the canvas is a single circle; that canvas gets stamped four times onto a parent canvas, and then *that* canvas is stamped four times onto the final master canvas.

```
(n,o=0)=>(r=o-2&&f(n/2,o+1),c=document.createElement`canvas`,X=c.getContext`2d`,d=(x,Q)=>(X.drawImage(r,x,k+Q*k*Math.sqrt(3)),d),c.width=c.height=n,m=n/2,k=n/4,X.fillStyle=o%2||"red",X.fill(X.clip(X.arc(m,m,m,0,7))),r&&d(0,0)(m,0)(k,-1)(k,1),o?c:location=c.toDataURL`image/jpeg`)

```

Runnable demo:

```
f = function (n) {var o = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];return r = o - 2 && f(n / 2, o + 1), c = document.createElement("canvas"), X = c.getContext("2d"), d = function (x, y) {return X.drawImage(r, x, y || k), d;}, c.width = c.height = n, m = n / 2, k = n / 4, q = k * Math.sqrt(3), X.fillStyle = o % 2 || "red", X.arc(m, m, m, 0, 7),X.clip(),X.fill(), r && d(0)(m)(k, k - q)(k, k + q), o || (location = c.toDataURL("image/jpeg")), c;};f(400)
```

With whitespace, comments, and mildly ungolfed:

```
f=(n,o=0)=>(
    // recursively create another canvas if we're not at the deepest layer
    var r;
    if(o < 2) { r = f(n/2,o+1); }

    // create this canvas
    c=document.createElement("canvas"),
    c.width=c.height=n,
    X=c.getContext("2d"),

    // helpful postions
    m=n/2, k=n/4, q=k*Math.sqrt(3),

    // draw a circle and clip future draws within this circle
    // either fills red (the shortest color name) or a non-color that defaults to black
    X.fillStyle= o%2 || "red",
    X.arc(m,m,m,0,7),
    X.clip(),
    X.fill(),

    // define a chainable `drawImage` alias (the `d` function returns itself)
    d=(x,y)=>(X.drawImage(r,x,y),d)

    // if we have a recursive canvas, draw it four times by chaining `d`
    if(r) { d(0,k)(m,k)(k,k-q)(k,k+q); }

    // if this is the top-layer (o==0), show the final jpeg
    if(o == 0) { location = c.toDataURL("image/jpeg"); }

    // return this canvas, to be used recursively
    c
)

```

This can easily produce deeper layers of recursion by changing the initial `o-2` or any larger `o-z` value.

Note that this will submission only run in Firefox, due to the use of ES6 features and inconsistency in the canvas API for `fill` and `clip` arguments.

---
Tags: code-golf, graphical-output, geometry
---


title: Play the elimination game

text:
# Question
Title: Play the elimination game
## Introduction

In this challenge, your task is to simulate a certain type of elimination game. In the game, the participants stand in a circle, and everyone is holding an integer. On each round of the game, every participant points at the person `n` steps away, if `n` is the number they are holding. If `n` is positive, they count to their right, if `n` is negative, they count to their left, and if `n` is zero, they point at themselves. Every participant who has someone pointing at them is eliminated, and leaves the circle; this ends the round. The rounds continue until there are no participants left.

## Input

Your input is a non-empty list of integers, in any reasonable format. It represents the numbers that the participants of the game are holding.

## Output

Your output is the number of rounds it takes until the game ends.

## Example

Consider the input list `[3,1,-2,0,8]`. On the first round, the following happens:

* The person holding `3` points right at the person holding `0`.
* The person holding `1` points right at the person holding `-2`.
* The person holding `-2` points left at the person holding `3`.
* The person holding `0` points at themself.
* The person holding `8` points right at the person holding `-2` (the list represents a circle, so it wraps around at the ends).

This means that `0`, `-2` and `3` are eliminated, so the second round is done with the list `[1,8]`. Here, `1` points at `8`, and `8` points at themself, so `8` is eliminated. The third round is done with the list `[1]`, where `1` simply points at themself and is eliminated. It took three rounds to eliminate all participants, so the correct output is `3`.

## Rules and scoring

You can write a full program or a function. The lowest byte count wins, and standard loopholes are disallowed.

## Test cases

```
[3] -> 1
[0,0,0] -> 1
[-2,-1,0,1,2,3,4,5,6,7] -> 2
[5,5,5,6,6,6] -> 2
[3,-7,-13,18,-10,8] -> 2
[-7,5,1,-5,-13,-10,9] -> 2
[4,20,19,16,8,-9,-14,-2,17,7,2,-2,10,0,18,-5,-5,20] -> 3
[11,2,7,-6,-15,-8,15,-12,-2,-8,-17,6,-6,-5,0,-20,-2,11,1] -> 4
[2,-12,-11,7,-16,9,15,-10,7,3,-17,18,6,6,13,0,18,10,-7,-1] -> 3
[18,-18,-16,-2,-19,1,-9,-18,2,1,6,-15,12,3,-10,8,-3,7,-4,-11,5,-15,17,17,-20,11,-13,9,15] -> 6

```

# Answer
> 4 votes
# Pyth, 15 bytes

```
f!=.DQ.e%+bklQQ

```

Test suite thanks to kirby

Uses the same iteration mechanism as @orlp, but detects the number of iterations using `f`, the "Repeat until falsy" function, to detect the `[]` once we're done.

# Answer
> 5 votes
# Matlab, ~~91~~ 77 bytes

```
function k=f(a);k=0;while a*0+1;l=numel(a);a(mod((1:l)+a-1,l)+1)=[];k=k+1;end

```

Old version:

```
function k=f(a);for k=1:numel(a);a(mod((1:l)+a-1,l)+1)=[];l=numel(a);if l==0;break;end;end

```

This is a challenge where matlab shines, the heart of this code is the deletion of the array entries: `a(mod((1:l)+a-1,l)+1)=[]` which is quite elegant I think.

# Answer
> 4 votes
# CJam, 21 bytes

```
q~{__ee{~+0t}/0-}h],(

```

Test suite.

Takes input as a CJam style list, but the test suite takes care of the conversion from the format in the challenge.

## Explanation

```
q~     e# Read and evaluate the input.
{      e# While the array is non-empty...
  _    e#   Copy the array. The original is left on the stack so that we can use the
       e#   stack depth to count the number of iterations later.
  _ee  e#   Make another copy and enumerate it, which means that each element is replaced
       e#   by a pair containing the element and its index in the array.
  {    e#   For each such pair...
    ~+ e#     Add the value to the index, giving the index it points at.
    0t e#     Set the value in the original array at the pointed-at index to 0.
       e#     This works without giving false positives because all 0s point to themselves.
  }/
  0-   e#   Remove all 0s from the array.
}h
],(    e# Wrap the stack in an array, get its length and decrement it to determine how
       e# many iterations this process took.

```

# Answer
> 3 votes
# C#, ~~251~~ ~~219~~ ~~211~~ ~~197~~ 193 bytes

The most ungolfable non-esoteric language strikes again.

```
using System.Linq;class X{static void Main(string[]a){int i=0,c;for(;(c=a.Length)>0;i++)a=a.Where((e,x)=>!a.Where((f,y)=>((int.Parse(f)+y)%c+c)%c==x).Any()).ToArray();System.Console.Write(i);}}

```

This program expects the input sequence as command-line arguments. For example, to input the list `[5,5,5,6,6,6]`, call it with command-line arguments `5 5 5 6 6 6`.

Thanks to Martin Büttner for some tips.

Golfed it to **197** by realizing that I can reuse the `args` array even though it’s an array of strings. I only need to parse them into an integer in one place.

Golfed to **193** by realizing that `.Where(...==x).Any()` is shorter than `.Select(...).Contains(x)`.

## Ungolfed

```
using System.Linq;
class X
{
    static void Main(string[] args)
    {
        var iterations = 0, count;

        // In the golfed version, this is a `for` loop instead.
        while ((count = args.Length) > 0)
        {
            // Create a new args array containing the items to be kept.
            args = args.Where((item, index) =>
            {
                // Should the item at index `index` be deleted?
                var deleteThisIndex = args.Where((item2, index2) =>
                    // Modulo that works with negative numbers...
                    ((int.Parse(item2) + index2) % count + count) % count
                        == index);

                return !deleteThisIndex.Any();

            }).ToArray();

            iterations++;
        }

        System.Console.Write(iterations);
    }
}

```

# Answer
> 2 votes
# R, 105 bytes

### code

```
l=scan();o=c();z=0;while((n=length(l))>0){for(i in 1:n)o=c(o,(i+l[i]-1)%%n+1);l=l[-o];o=c();z=z+1};cat(z)

```

### ungolfed

```
l <- scan()                  # get input as a 'l' vector from user
o <- c()                     # create a empty vector
z=0                          # create a counter starting at 0
while((n=length(l))>0){      # while the length of the input is more than 0
  for(i in 1:n){             # iterate through the vector
    o=c(o,(i+l[i]-1)%%n+1)   # add the index that will be deleted to the 'o' vector
  }
  l=l[-o]                    # remove the 'o' vector indexes from 'l'
  o=c()                      # empty 'o'
  z=z+1                      # add 1 to counter
}
cat(z)                       # print the counter

```

# Answer
> 2 votes
# Pyth, 21 bytes

```
lt.u@LN-UlN.e%+kblNNQ

```

Live demo with test cases.

# Answer
> 2 votes
# Pyth, 17 bytes

```
tl.u.DN.e%+kblNNQ

```

Coincidentally very similar to kirbyfan's answer.

# Answer
> 2 votes
# Mathematica, 71 bytes

```
Length@FixedPointList[#~Delete~Mod[Plus~MapIndexed~#,Length@#,1]&,#]-2&

```

# Answer
> 1 votes
## STATA, 146 bytes

```
inf a using a.
gl b=0
qui while _N>0{
g q$b=0
g c$b=mod(_n+a-1,_N)+1
forv y=1/`=_N'{
replace q$b=1 if _n==c$b[`y']
}
drop if q$b
gl b=$b+1
}
di $b

```

Uses the paid version of STATA. Assumes the input is in a newline separated file called `a.`. Limited to situations where no more than 1023 rounds are required due to a maximum number of variables allowed (can be fixed at the cost of 10 bytes). It reads the data and runs a loop until there are no more observations. In each iteration, make a variable with the value of the index it points to. For each observation, if another observation points to it, set an indicator to drop the variable. Then drop all observations with that indicator and increment the counter. After the loop, print the counter.

# Answer
> 1 votes
# Ruby, ~~78~~ 74 bytes

```
f=->a{b,i=[],0;(a.map{|e|b<<a[(e+i)%a.size]};a-=b;i+=1)while a.size>0;p i}

```

# Answer
> 1 votes
# awk, 66 bytes

```
{for(;n=split($0=$0,a);++r)for(i in a)$((i+a[i]%n+n-1)%n+1)=X}$0=r

```

Simply uses `mod length array` to keep it inside the array. In the input the numbers need to be separated by spaces.

## Usage example

```
echo "-2 -1 0 1 2 3 4 5 6 7" | awk '{for(;n=split($0=$0,a);++r)for(i in a)$((i+a[i]%n+n-1)%n+1)=X}$0=r'

```

Here's all the input examples in the appropriate format

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

```

# Answer
> 0 votes
# Python 2, 122 bytes

```
def f(l):
 if not l:return 0
 L=len(l);x=[1]*L
 for i in range(L):x[(i+l[i])%L]=0
 return 1+e([v for i,v in zip(x,l)if i])

```

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


title: Will it ambigram?

text:
# Question
Title: Will it ambigram?
First challenge!

# What is an ambigram?

Ambigrams are word(s) that read the same word(s) or another word given a certain transformation and possibly stylistic alterations.

Example:

That's an example of a rotational ambigram; it reads the same word, even when flipped around.

# The Challenge

You are to create a function, program, etc. that can detect whether a given input (consisting of only a-zA-Z chars) is a natural symmetric ambigram (an ambigram that reads the same word without significant artistic alteration given a transformation). You can compete in one or more of the following categories:

## Rotational

Examples: `I`, `O`, `ae`, `AV`, `pod`

### Transformation table (both ways)

```
a  e/D
b  q
d  p/P
h  y
l  l
m  w
n  u/U
o  o/O/G/Q
s  s/S
t  t
x  x/X
z  z/Z
A  v/V
B  E
D  G
H  H
I  I
M  W
N  N

```

Output truesy or falsy value.

## Reflectional (Vertical Line)

Examples: `wow`, `mom`, `HOH`

### Chars to match

```
b/d i j l m n o p/q s/z t u v w x y A B/E G/D H I M O Q S/Z T U V W X Y

```

Output truthy or falsy value.

## Reflectional (Horizontal Line)

Examples: `XOD`, `KEK`, `BED`

### Chars to match

```
a l o t x B C D E H I K O X

```

Output truthy or falsy value.

## Totem

Examples:

```
x  n  O
o  u  H
x  M  I
      O

```

### Chars to match

```
A H I M O T U V W X Y i l m n o t u v w x y

```

Output truthy or falsy value.

## Any (bonus of -50%)

This code should either output the type(s) of ambigram(s) that the input could possibly be (if the input is an ambigram) or a falsy value (if the input is not an ambigram).

# Code rules

* Standard loopholes are disallowed.
* Input is case-sensitive. This means that AV would count, but aV would not count as a rotational ambigram.
* An input of zero length is considered to be a natural symmetric ambigram.
* Make sure to write your header as: `# Division, Language, Byte-Count`.
* This is code-golf! You know what that means.

# Answer
# Python 2, 258 bytes (~~622~~ ~~567~~ ~~543~~ 516-50%)

Here's my attempt at an answer.

```
R=dict(zip(list('abdhlmnostxzABDHIMN'),'eD q pP y l w uU oOGQ sS t xX zZ vV E G H I W N'.split()))
V='ijlmnotuvwxyAHIMOQTUVWXY'
W=dict(b='d',p='q',s='z',B='E',G='D',S='Z')
H='lotxBCDEHIKOX'
T='AHIMOTUVWXYilmnotuvwxy'
s=raw_input()
r=v=h=t=1
for i,j in R.items():
 for c in j:R[c]=R.get(c,'')+i
for i,j in W.items():
 for c in j:W[c]=W.get(c,'')+i
for i in range(len(s)):
 c,l=s[i],s[-i-1]
 r&=(c in R and l in R[c])
 v&=c in V or(c in W and l in W[c])
 h&=(c in H)+(l in H)>1
 t&=c in T
print 'R'*r+'V'*v+'H'*h+'T'*t

```

Prints the possible types of ambigrams, or `0` if no ambigrams are possible.

`RVHT` for rotational, vertical, horizontal and totem respectively.
> 3 votes

# Answer
# All, Ruby, 289 - 50% = 144.5 bytes

```
i=gets.chop;s=i.tr('ijlmnotuvwxyAHIMOQTUVWXY','').tr'bpsBGS','dqzEDZ';t=i.tr'eDqpPylwuUOGQStXZvVEGHIWN','aabddhlmnnooostxzAABDHIMN';o=(i.tr('alotxBCDEHIKOX','')=='' ? 'V':'')+(s==s.reverse ? 'H':'')+(i.tr('AHIMOUVWXYilmnotuvwxy','')=='' ? 'T':'')+(t==t.reverse ? 'R':'');puts o=='' ? 1<0:o

```

This seems too long...
> 1 votes

---
Tags: code-golf
---


title: Epcot World Reorder

text:
# Question
Title: Epcot World Reorder
# Intoroduction

If you've ever been to Epcot at Disney World, you've probably been to the world showcase: a lake surrounded by various country-themed locations. One thing that's always bothered me about it is that the countries don't appear in the order you would run into them around the world. There are officially eleven of them, and the order is (going clockwise around the circle):

```
Mexico
Norway
China
Germany
Italy
United States
Japan
Morocco
France
United Kingdom
Canada

```

# Challenge

Write a function or program that takes the list of countries (as a list, separated string, or other convenient form) in the order given above, and return/output them in an order that you would run into them if you were head around the world (either east-west or west-east) from a start point of your choosing. For specificity, lets define the capital of each country as it's "position", and order longitudinally. Output format should be the same as the input format.

Standard code golf rules apply. Shortest code wins, with exception to the bonus below. The winner will be determined by the code with the lowest score that accomplishes the criteria, and will be selected in a minimum of seven days.

# Bonus

If your code can take in arbitrary country names (beyond just the eleven listed above) and order them as well, subtract 33% from your score. If you invoke this bonus, you must start from the Prime Meridian, but which direction you go from there is up to you. Because the total number of "sovereign states" is a disputed thing, I'll settle for at least 190 of them.

# Example

## Input

```
['Mexico', 'Norway', 'China', 'Germany', 'Italy', 'Unites States', 'Japan', 'Morocco', 'France', 'United Kingdom', 'Canada']

```

## Output

```
['Mexico', 'United States', 'Canada', 'Morocco', 'United Kingdom','France', 'Norway', 'Italy', 'Germany', 'China', 'Japan']

```

# Answer
> 4 votes
## CJam (18 bytes)

This is an anonymous function which takes input as an array of strings and returns it as an array of strings.

```
{36061983185Bb\f=}

```

Online demo

A slightly more general version, which takes any subset of the 11 countries in any order and sorts them correctly, is 26 bytes:

```
{{71b226%75585218525Bb=}$}

```

For the 30% bonus to give a better score, it would be necessary to encode the data for 190 countries in at most 37 bytes (including the code to use it); that's about 1.5 bits per country. But 190! is about 2^1169.3, requiring 147 bytes, so the 30% bonus is obviously not at all interesting without cheating by using external data sources.

# Answer
> 5 votes
# Mathematica, 50 bytes

```
f=SortBy[CountryData[#,"CapitalLocation"][[1,2]]&]

```

Example:

```
In[12]:= f@{"Mexico", "Norway", "China", "Germany", "Italy",
  "United States", "Japan", "Morocco", "France", "United Kingdom",
  "Canada"}

Out[12]= {Mexico,United States,Canada,Morocco,United Kingdom,France,Norway,Italy,Germany,China,Japan}

```

Mathematica has built-in functions for every kind of data like this...

---

With bonus:

# Mathematica, 58 bytes − 33% = 38.86 bytes

```
f=SortBy[CountryData[#,"CapitalLocation"][[1,2]]~Mod~360&]

```

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


title: The arrow maze escape

text:
# Question
Title: The arrow maze escape
**Question**

You have a 50 by 50 character array. Each cell has an arrow pointing in any one of four directions. No cell is empty. On entering a cell, you must exit it in the direction specified by the arrow. The arrow may also point in the same direction you came from, resulting in a dead end.

You may start from any cell on the outermost border of the maze and find a path that takes you in the maze, and causes you to exit at some other cell. Input will be given as an array containing \<, \>, ^ and v. Output will be a single digit (Boolean, integer or character, anything will do) as 0 (indicating that the task is impossible) or 1 (indicating that you have achieved the task).

**Example** (actual array will be bigger than this)

```
^ v < >
> < v <
v > v ^

```

Output will be

```
1
```
as you can enter from the \< on the right, which will cause you to exit from the bottom v by the path "\< v v"

**The task is to write the shortest possible code that will receive the maze as input, and determine where there exists a path in it as specified in the rules and output a single digit 0 or 1**

Outputing TRUE and FALSE instead of actual digits is also allowed.

# Answer
> 8 votes
# CJam, ~~89~~ 81 bytes

```
q~"><v^":A2/{f{\*}z}/sA[1W52-52]er:T,,{[52md]51f%0e=1=},:E{[2704{__T=+}*]\-E&},,g

```

Try it online in the CJam interpreter.

### How it works

```
q~        e# Read and evaluate all input. This pushes an array of strings.
"><v^":A  e# Push that string and save it in A.
2/        e# Split it into ["><" "v^"].
{         e# For each chunk:
  f{      e#   For each input string, push the string and the chunk; then:
    \*    e#     Join the chunk, using the string as separator.
  }       e#
  z       e#   Transpose rows and columns.
}/        e#
s         e# Flatten the resulting array of strings.
A         e# Push "><v^".
[1W52-52] e# Push [1 -1 52 -52].
er        e# Perform transliteration.
:T        e# Save the result in T.
,,        e# Push [0 ... 2703].
{         e# Filter; for each integer I in [0 ... 2703]:
  [52md]  e#   Push [I/52 I%52].
  51f%    e#   Take both integers modulo 51 to map 51 to 0.
  0e=     e#   Count the number of resulting zeroes.
  1=      e#   Check if the count is 1.
},        e# If it is, keep I.
:E        e# Save the filtered array in E.
{         e# For each integer I in E:
  [2704{  e#   Do 2704 times:
    __    e#     Push two copies of the integer on the stack.
    T=    e#     Select the corresponding element from T.
    +     e#     Add it to the first copy.
  }*]     e#   Collect all results in an array.
  \-      e#   Remove I from that array.
  E&      e#   Intersect with E.
},        e# If the intersection is non-empty, keep the integer.
,g        e# Push the sign of the length of the filtered array.

```

---
Tags: code-golf, maze
---


title: Roller coaster of numbers

text:
# Question
Title: Roller coaster of numbers
Write a program that generates a sequence of numbers starting with zero and then 100 random integers between -9 and 9.

That sequence will be displayed like a roller coaster.

Any increasing number in the sequence will go up and any decreasing number will go down

Sample sequence:

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

```

Sample output

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

```

This is code golf. Shortest code in bytes by November 5th wins.

# Answer
> 1 votes
# Ruby, 167 bytes

```
l={}
y=p=n=0
101.times{|i|
d/=d.abs if(d=n-p)!=0
l[y-=d]||=Array.new 101," "*4
l[y][i]=n.to_s.ljust 4
p,n=n,rand(18)-9}
puts l.sort_by(&:first).map(&:last).map(&:join)

```

First time golfing Ruby, so I'm sure I'm missing something.

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


title: Which language is shortest?

text:
# Question
Title: Which language is shortest?
Create a program that find the latest 50 challenges with the -tag that have at least 20 answers. Then, extract the scores for each language in each of the challenges. If there are more than one answer using the same language, count all scores. Thereafter, take the top 20 most common languages and output a list with the language names, the number of answers, the average byte counts and the median byte counts. The list should be sorted by number of answers, in descending order.

You must account for variations in capitalization (for instance: Matlab = MATLAB).

In languages with many different version numbers (e.g. Python), count them as unique languages, so: `Python != Python 2 != Python 2.7 != Python 3.x`

Example output (output format is optional):

```
cJam,       66,  12.4,  8.5
Pyth,       58,   15.2,  19
Ruby,       44,   19.2,  22.5
Python,     34,   29.3,  32
Python 2.7, 22,   31.2,  40
...
...
Java,       11,   115.5, 94.5

```

Header formats that must be supported:

* Starts with `# Language name,` or `#Language name`
* Ends with `xx bytes`, `xx Bytes` or just `xx`
* There can be a lot of garbage between the first comma and the last number.
* If the language name is a link (`[Name](link)`), it can be skipped

If the answer has another header format, you may choose to skip it (or include it if your code can handle it).

As an example, all of the below headers must be supported:

```
# Language Name, N bytes
# Ruby, <s>104</s> <s>101</s> 96 bytes
# Perl, 43 + 2 (-p flag) = 45 Bytes
# MATLAB, 5

```

Rules:

* It's OK to use API or just the website-url
    + The following can be extracted from the byte count (nothing else), so no need to use a url-shortener (Maximum 44 bytes):
        - `https://` (or `http://`)
        - `codegolf`
        - `.stackexchange.com`
        - `/questions`
* The program can take input. The input will be included in the byte count.

Other than that, standard rules apply.

# Answer
> 14 votes
# R, 821 - 44 = 777 bytes

*Updated results*: please see the edit history to make sense of all the comments below.

```
           language num_answers avg_count median_count
1              RUBY          49  49.97959         30.0
2              CJAM          48  32.64583         22.0
3              PYTH          48  21.02083         14.0
4          PYTHON 2          46  86.78261         77.0
5             JULIA          43  58.90698         45.0
6           HASKELL          41  74.65854         56.0
7               PHP          40  73.52500         48.0
8              PERL          36  53.30556         34.0
9          PYTHON 3          34  90.91176         90.5
10       POWERSHELL          33  60.24242         44.0
11                C          32 221.84375         79.5
12                R          32  77.40625         62.5
13             JAVA          29 170.68966        158.0
14 JAVASCRIPT (ES6)          29  90.79310         83.0
15       JAVASCRIPT          28  68.39286         61.0
16               C#          25 193.92000        130.0
17      MATHEMATICA          23  56.04348         47.0
18           MATLAB          22  67.45455         55.0
19         TI-BASIC          19  47.05263         37.0
20              APL          18  16.55556         15.0

```

The code, which I could shorten a bit more:

```
W=library;W(XML);W(plyr)
X=xpathSApply;Y=xmlValue;D=data.frame;H=htmlParse;S=sprintf
Z="http://codegolf.stackexchange.com/"
R=function(FUN,...)do.call(rbind,Map(FUN,...))
G=function(url){d=H(url)
a=as.double(sub(".*?(\\d+)a.*","\\1",X(d,"//div[starts-with(@class,'status')]",Y)))
u=paste0(Z,X(d,"//*[contains(@class,'question-hyperlink')]",xmlGetAttr,"href"))
D(u,a)}
u=S("%s/questions/tagged/code-golf?page=%i",Z,1:50)
q=R(G,u)
u=with(q,head(u[a>20],50))
A=function(url){u=S("%s?page=%i",url,1:10)
f=function(u){d=H(u)
h=X(d, "//div[@class='post-text']//h1",Y)
p="^(.*?),.*? (\\d+)( [Bb]ytes)?$"
k=grep(p,h,v=T)
l=toupper(sub(p,"\\1",k))
c=as.double(sub(p,"\\2",k))
D(l,c)}
R(f,u)}
a=R(A,u)
L=names(tail(sort(table(a$l)),20))
x=subset(a,l%in%L)
arrange(ddply(x, "l",summarise,n=length(c),a=mean(c),m=quantile(c,0.5)),-n)

```

De-golfed:

```
library(XML)
library(plyr)
LoopBind <- function(FUN, ...) do.call(rbind, Map(FUN, ...))
GetQuestions <- function(url) {
  d = htmlParse(url)
  a=as.double(sub(".*?(\\d+)a.*","\\1",xpathSApply(d, "//div[starts-with(@class, 'status')]", xmlValue)))
  u=paste0("http://codegolf.stackexchange.com/",xpathSApply(d, "//*[contains(@class, 'question-hyperlink')]", xmlGetAttr, "href"))
  data.frame(u, a)
}
u <- sprintf("http://codegolf.stackexchange.com/questions/tagged/code-golf?page=%i", 1:50)
q <- do.call(rbind, Map(GetQuestions, u))
u <- with(q, head(u[a > 20], 50))

GetAnswers <- function(url) {
  u=sprintf("%s?page=%i",url,1:10)
  f=function(u) {
    d = htmlParse(u)
    h = xpathSApply(d, "//div[@class='post-text']//h1", xmlValue)
    p = "^(.*?),.*? (\\d+)( [Bb]ytes)?$"
    k = grep(p,h,v=T)
    l = toupper(sub(p,"\\1",k))
    c = as.double(sub(p,"\\2",k))
    data.frame(language=l,c)
  }
LoopBind(f,u)
}
a=LoopBind(GetAnswers, u)
L=names(tail(sort(table(a$l)),20))
x=subset(a,language%in%L)
arrange(ddply(x, "language", summarise, num_answers = length(c), avg_count = mean(c), median_count = quantile(c,0.5)),
        -num_answers)

```

# Answer
> 7 votes
# Python 2, 934 - 44 (url stuff) = 890 bytes

Using the API:

```
from urllib2 import urlopen as u
from gzip import GzipFile as f
from StringIO import StringIO as s;x="https://api.stackexchange.com/2.2%s&site=codegolf"
import re;j=u(x%'/search/advanced?pagesize=50&order=desc&sort=creation&answers=20&tagged=code-golf');q=s(j.read());g=f(fileobj=q);true=1;false=0;l=';'.join(str(a['question_id'])for a in eval(g.read())['items']);w=[]
def r(p):
 j=u(x%('/questions/%s/answers?page=%s&filter=!9YdnSMlgz&pagesize=100'%(l,p)));g.seek(0);q.truncate();q.write(j.read());q.seek(0);k=eval(g.read());w.extend(a['body_markdown']for a in k['items'])
 if k['has_more']:r(p+1)
r(1);x={};s=sorted
for m in w:
 try:
  l,n=re.match("(.*?),.*?([0-9]+)[^0-9]*$",m.splitlines()[0]).groups();l=re.subn("# ?","",l,1)[0].upper()
  if l not in x:x[l]=[]
  x[l]+=[(l,int(n))]
 except:pass
for l in s(x,cmp,lambda a:len(x[a]),1)[:20]:
 v=s(x[l])
 print l,len(v),sum(map(lambda a:a[1],v))/len(v),v[len(v)/2][1]

```

Note that this code **does not** pay attention to the API throttling.

Output:

```
RUBY 60 430 32
PYTH 57 426 16
CJAM 56 35 23
C 52 170 76
PYTHON 2 51 88 79
JULIA 42 63 48
HASKELL 42 81 63
JAVASCRIPT (ES6) 41 96 83
PERL 40 44 27
PYTHON 3 37 91 89
PHP 36 98 59
JAVASCRIPT 36 743 65
POWERSHELL 35 86 44
JAVA 32 188 171
R 30 73 48
MATLAB 25 73 51
MATHEMATICA 24 57 47
APL 22 14 13
SCALA 21 204 59
TI-BASIC 21 42 24

```

---
Tags: code-golf, internet
---


title: Area of Polygon

text:
# Question
Title: Area of Polygon
Given the number of vertices `N` of a convex polygon and each of their `(x, y)` calculate the polygon's area. vertexes are in clockwise order

You must handle all `N <= 45` ,`-600 <= x,y <= 600`, and your answer must be accurate to at least 2 decimal places.

Example:

```
3
 1 6
 1 2
-4 2

```

The area is 10.00.

This is , fewest bytes wins. Input to be taken in code.

# Answer
# Mathematica, 29 bytes

```
RegionMeasure@*ConvexHullMesh

```

Example usage:

```
(RegionMeasure@*ConvexHullMesh)[{{1, 6}, {1, 2}, {-4, 2}}]
(* 10. *)

```
> 5 votes

# Answer
# JavaScript (ES6) 131

```
f=l=>(p=l.pop(t=Math.atan2),l.sort((a,b)=>t(a.y-p.y,a.x-p.x)-t(b.y-p.y,b.x-p.x)),[...l,p].map(t=>(v+=p.x*t.y-p.y*t.x,p=t),v=0),v/2)

// More readable
u=l=>(
  t=Math.atan2,
  p=l.pop(),
  l.sort((a,b)=>t(a.y-p.y,a.x-p.x)-t(b.y-p.y,b.x-p.x)),
  v=0,
  [...l,p].map(t=>(v+=p.x*t.y-p.y*t.x,p=t)),
  v/2
)

//TEST
console.log=x=>O.innerHTML+=x+'\n'

T=[{x:1,y:6},{x:1,y:2},{x:-4,y:2}] // area 10
console.log(JSON.stringify(T)+' '+f(T))
T=[{x:12,y:12},{x:2,y:2},{x:4,y:10},{x:11,y:2}] // area 75
console.log(JSON.stringify(T)+' '+f(T))
```

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

# Answer
## C# - 268

with all the output handling included, yup this ain't gonna win

```
using System;class P{static void Main(string[]a){int i,v=int.Parse(a[0]),j=v-1;var x=new float[v];var y=new float[v];for(i=0;i++<v;){x[i-1]=float.Parse(a[i]);y[i-1]=float.Parse(a[i+v]);}float s=0;for(i=0;i<v;j=i++)s+=(x[j]+x[i])*(y[j]-y[i]);Console.Write(s/2);}}

```

Program reads input from the string array **args**. Example input: 3 1 1 -4 6 2 2. Output: 10

First number is the number of vertices, all the rest are X & Y coordinates. After vertice number input all x coordinates, then all y coordinates, each one separated by whitespace.

I'm not fully certain if I need to include **using, namespace, main void etc...** but I included them anyway.

EDIT: Saved some bytes, thanks to @edc65 !
> 1 votes

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