title: Draw Growing Stacks of Boxes

text:
# Question
Title: Draw Growing Stacks of Boxes
# The Task

In this challenge, your task is to draw an ASCII art representation of several stacks of boxes of increasing height. You are given as input the number of stacks, which is a positive integer. The first stack contains one box of size `2x2`. The second stack contains 2 boxes of size `3x3`. In general, the `k`th stack contains `k` boxes of size `(k+1)x(k+1)`.

The borders of each box are drawn using the characters `-|+`, and their interior consists of whitespace. Adjacent boxes share their borders, and corners should always be drawn with `+`, even when they are part of a border of another box.

# Examples

Output for `1`:

```
++
++

```

Output for `2`:

```
 +-+
 | |
 +-+
++ |
++-+

```

Output for `3`:

```
   +--+
   |  |
   |  |
   +--+
   |  |
 +-+  |
 | +--+
 +-+  |
++ |  |
++-+--+

```

Output for `5`:

```
          +----+
          |    |
          |    |
          |    |
          |    |
          +----+
          |    |
          |    |
          |    |
      +---+    |
      |   +----+
      |   |    |
      |   |    |
      +---+    |
      |   |    |
      |   +----+
   +--+   |    |
   |  +---+    |
   |  |   |    |
   +--+   |    |
   |  |   +----+
 +-+  +---+    |
 | +--+   |    |
 +-+  |   |    |
++ |  |   |    |
++-+--+---+----+

```

# Rules and Scoring

The input can be received from STDIN, as a command line argument, or as a function argument. Output **must** go to STDOUT or closest equivalent. Any finite amount of trailing whitespace is allowed, as are preceding and trailing newlines, but there cannot be any extra preceding spaces.

This is code-golf, so the lowest byte count wins. Standard loopholes are disallowed.

# Answer
> 10 votes
# CJam, ~~64 60~~ 58 bytes

```
]ri:X{'|'}{I))*\I**XX*)Se[s}:L~:M.e>S'-LaI*~M}fI]zN*'}/'+*

```

Constructing each column at a time.

Try it online here

# Answer
> 8 votes
# Java (~~407~~ 349 chars)

*A few chars thanks to @Zgarb and @Geobits*

**Code**

```
void s(int q){int d,h,y,i,j,x,z,t=q*q+1;char b;for(i=0;i<t;i++){z=x=0;d=t-i;for(j=0;j<(q*q+q)/2+1;j++){b=' ';h=x*x+1;if(x==z){y=x+1;if((d<=h&d%(x==0?1:x)==(x==1?0:1))|(y<=q&d<=y*y+1&d%(y==0?1:y)==(y==1?0:1)))b='+';else if(d<=h|y<=q&d<=y*y+1)b='|';x++;z=1;}else{if(d<=h&d%(x==0?1:x)==(x==1?0:1))b='-';z++;}System.out.print(b);}System.out.println();}}

```

Not sure if this is optimal, but it's my first attempt, I will probably try to put it in a better golfing language later. Any suggestions are welcome!

**Expanded**

```
class StackingBlocks{
    public static void main(String[]a){
        int d,h,y,i,j,x,z,t,q=10;
        t=q*q+1;
        char b;
        for(i=0;i<t;i++){
            z=x=0;
            d=t-i;
            for(j=0;j<(q*q+q)/2+1;j++){
                b=' ';
                h=x*x+1;
                if(x==z){
                    y=x+1;
                    if((d<=h&d%(x==0?1:x)==(x==1?0:1))|(y<=q&d<=y*y+1&d%(y==0?1:y)==(y==1?0:1)))
                        b='+';
                    else if(d<=h|y<=q&d<=y*y+1)
                        b='|';
                    x++;
                    z=1;
                }else{
                    if(d<=h&d%(x==0?1:x)==(x==1?0:1))
                        b='-';
                    z++;
                }
                System.out.print(b);
            }
            System.out.println();
        }
    }
}

```

Check it out here.

# Answer
> 5 votes
# Python 2, ~~144~~ 128 bytes

```
n=input()
i=n*n
while-~i:j=x=1;l="";exec'y=i%j<1;z=i>j*j;l+=j*z*" "or"|+"[x|y]+" -"[y]*~-j;x=y^z>z;j+=1;'*n;print l+"|+"[x];i-=1

```

Bit twiddling. Bit twiddling everywhere.

# Answer
> 3 votes
# Python, 188 bytes

Mathematically calculates the character at each `x,y` position. It was tricky making the `+`s print on both sides of each box as well as stopping the rightmost `+`s of what would be `n+1`th boxes.

```
n=input();l=1;c=0
for y in range(n*n,-1,-1):
 s=""
 for x in range((n*n+n)/2+1):k=((8*x+1)**.5+1)/2;i=int(k);b=y<=i**2;s+=" |-+"[((k==i)+2*((y%l+c)*(y%i+(k==n+1))<1))*b];l=i;c=b^1
 print s

```

# Answer
> 1 votes
## C# - 304 bytes (function)

```
void b(int s){int h=s*s,w=h+s>>1,x,y,j;var c=new int[w+1,h+1];for(;s>0;s--){for(y=s*s-s;y>=0;y-=s){x=s*s-s>>1;for(j=0;j<s;){c[x+j,y]=c[x+j,y+s]=13;c[x,y+j]=c[x+s,y+j++]=92;}c[x,y]=c[x+s,y]=c[x+s,y+s]=c[x,y+s]=11;}}for(y=h;y>=0;y--){for(x=0;x<=w;x++)Console.Write((char)(32+c[x,y]));Console.WriteLine();}}

```

or 363 bytes (full code)

```
namespace System{class C{static void Main(string[]a){int s=int.Parse(a[0]),h=s*s,w=h+s>>1,x,y,j;var c=new int[w+1,h+1];for(;s>0;s--){for(y=s*s-s;y>=0;y-=s){x=s*s-s>>1;for(j=0;j<s;){c[x+j,y]=c[x+j,y+s]=13;c[x,y+j]=c[x+s,y+j++]=92;}c[x,y]=c[x+s,y]=c[x+s,y+s]=c[x,y+s]=11;}}for(y=h;y>=0;y--){for(x=0;x<=w;x++)Console.Write((char)(32+c[x,y]));Console.WriteLine();}}}}

```

I tried to avoid if statements. Ungolfed:

```
namespace N
{
    public class Explained
    {
        static void boxes(string[] args)
        {
            int size = int.Parse(args[0]);
            int height = size * size + 1;
            int width = size * (size + 1) / 2 + 1;
            var canvas = new int[width, height];
            for (; size > 0; size--)
                drawboxes(size, canvas);

            for (int y = height - 1; y >= 0; y--)
            {
                for (int x = 0; x < width; x++)
                    Console.Write((char)(32 + canvas[x, y]));
                Console.WriteLine();
            }
        }

        static void drawboxes(int size, int[,] canvas)
        {
            int x = size * (size - 1) / 2;
            for (int i = size - 1; i >= 0; i--)
            {
                drawbox(x, i * size, size, canvas);
            }
        }

        static void drawbox(int x, int y, int size, int[,] canvas)
        {
            for (int i = 0; i < size; i++)
            {
                canvas[x + i, y] = 13; // +32 = '-'
                canvas[x + i, y + size] = 13;
                canvas[x, y + i] = 92; // +32 = '|'
                canvas[x + size, y + i] = 92;
            }
            canvas[x, y] = 11; // +32 = '+'
            canvas[x + size, y] = 11;
            canvas[x + size, y + size] = 11;
            canvas[x, y + size] = 11;
        }
    }
}

```

# Answer
> 1 votes
# Python 2, ~~294~~ 290

I got it working, but I still need to golf it more. I'm so happy, though, that was tough (for me, at least)!

I'll probably add an explanation later, unless it's immediately clear to someone...? I kind of doubt it.

**Try it here**

```
n=input()
w=n*n+n+2>>1
a=eval(`[[' ']*w]*-~n**2`)
r=range
j=[i*i+i>>1for i in r(n+1)]
p=0
for i in r(w):
 if i in j:
    p+=p<n
    for k in r(p*p+1):a[~k][i]='+'if k%p<1or' '<a[~k][i-1]<'.'else'|'
 else:
    for k in r(p*p+1):a[~k][i]=' 'if k%p else'-'
print'\n'.join(''.join(i)for i in a)

```

# Answer
> 1 votes
# Ruby (205 bytes)

Takes the number as a command line arguments. It starts with a fail leading newlines, but that's allowed.

```
n=$*[0].to_i
m=n+1
f=m.times.inject(:+)+1
c=((" "*f+p=?+)*n*m).split p
y=0
1.upto(n){|b|(b*b+1).times{|x|d=x%b==0;r=c[x]
d&&b.times{|g|r[y+g]=?-}
r[y]=d||r[y]==p ?p:?|
r[y+b]=d ?p:?|}
y+=b}
puts c.reverse

```

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

```
(n,o='',r,f,t,u,b,c,e=n*n+1,i)=>{for(t=0;e>t;t++){for(c=b=0,d=e-t,u=0;(n*n+n)/2+1>u;u++)i=" ",r=b*b+1,b==c?(f=b+1,d<=r&d%(0==b?1:b)==(1==b?0:1)|n>=f&d<=f*f+1&d%(0==f?1:f)==(1==f?0:1)?i="+":d<=r|n>=f&d<=f*f+1&&(i="|"),b++,c=1):(d<=r&d%(0==b?1:b)==(1==b?0:1)&&(i="-"),c++),o+=i;o+="\n"}return o}

```

I ran this in Firefox. Ignore the `"` the console adds between the strings. This is mostly ES5 stuff but I'll try to golf this more.

Ungolfed / ES5

```
function box(n, o, r, f, t, u, b, c, e, i) {
  if (o === undefined) o = "";
  if (e === undefined) e = n * n + 1;
  return (function() {
    for (t = 0; e > t; t++) {
      for (c = b = 0, d = e - t, u = 0;
        (n * n + n) / 2 + 1 > u; u++) i = " ", r = b * b + 1, b == c ? (f = b + 1, d <= r & d % (0 == b ? 1 : b) == (1 == b ? 0 : 1) | n >= f & d <= f * f + 1 & d % (0 == f ? 1 : f) == (1 == f ? 0 : 1) ? i = "+" : d <= r | n >= f & d <= f * f + 1 && (i = "|"), b++, c = 1) : (d <= r & d % (0 == b ? 1 : b) == (1 == b ? 0 : 1) && (i = "-"), c++), o += i;
      o += "\n";
    }
    return o;
  })();
}

document.getElementById('g').onclick = function(){ document.getElementById('o').innerHTML = box(+document.getElementById('v').value) };
```

```
<input id="v"><button id="g">Run</button><pre id="o"></pre>
```

# Answer
> 0 votes
# Python - 243 bytes

Generates all the columns, replacing the overlaps on columns except the first one. Then it pads with spaces, transposes, and prints.

```
Q=input()
Y=[]
for i in range(Q):
    f="+"+i*"-"+"+";x=map(list,zip(*([f]+["|"+" "*i+"|"]*i)*(i+1)+[f]))
    if i:y=Y.pop();x[0][-len(y):]=y
    Y+=x
print"\n".join("".join(i)for i in zip(*["".join(j[::-1]).ljust(Q*Q+1," ")for j in Y])[::-1])

```

I am considering translating to Pyth, but I will need a replacement for the pad function.

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


title: Cut a silicon wafer into dies

text:
# Question
Title: Cut a silicon wafer into dies
When manufacturing chips, circular silicon wafers are cut into dies of needed size:

The goal of this challenge is maximizing the number of whole dies that can be cut from a wafer of a given diameter.

The machine puts the wafer into an angular compartment:

```
_____________________
|     xxxxxx
|  xxxxxxxxxxxx
| xxxxxxxxxxxxxx
|xxxxxxxxxxxxxxxx
|xxxxxxxxxxxxxxxx
| xxxxxxxxxxxxxx
|  xxxxxxxxxxxx
|     xxxxxx     (this ascii art is meant to be a perfect circle)

```

It measures a distance `dx` from the left edge, and makes a vertical cut. Then it makes the needed number of additional vertical cuts, with spacing of the needed `width`. It makes the horizontal cuts in the same way: first one at a distance `dy`, and then with spacing of `height`.

The material remains perfectly still during the cutting: it's not allowed to move some slices of material before making the perpendicular cuts.

The machine has a stepper motor that works at absolute accuracy but can only go integer-sized distances.

Make a program or a subroutine that gets (or reads) the following parameters:

* Wafer `diameter`
* Die `width`
* Die `height`

and outputs (or prints)

* `dx` \- horizontal starting position
* `dy` \- vertical starting position

such that the number of rectangular dies is maximal.

Some fine points:

* If a corner of a die lies exactly on the circumference of the circle, the die is considered usable (rectangular)
* No edge cases: you can assume that the wafer's diameter is even; at least one die can be cut out; also make other reasonable assumptions
* All sizes are integer numbers of millimeters; maximum wafer diameter is 450

Shortest code wins!

P.S. The code must finish running in a reasonable amount of time, e.g. over a weekend (2 days) - for wafer diameter equal to 300.

P.P.S. If there are several different output values that are optimal, the code must output one of them - no need to output all of them!

Test cases:

```
Wafer diameter 8, die size 2 x 2 => dx = 0, dy = 1 (6 dies)
Wafer diameter 20, die size 5 x 4 => dx = 1, dy = 2 (10 dies)
Wafer diameter 100, die size 12 x 12 => dx = 9, dy = 3 (41 dies)
Wafer diameter 300, die size 11 x 11 => dx = 7, dy = 7 (540 dies) - a realistic example
Wafer diameter 340, die size 15 x 8 => dx = 5, dy = 2 (700 dies) - a Pythagorean triple
Wafer diameter 300, die size 36 x 24 => dx = 2, dy = 6 (66 dies) - full-frame sensors

```

Here is a visualization of the last test case:

# Answer
# Java, 242

This is a method that takes the three input parameters and returns a string containing optimal values for dx and dy.

```
String k(int d,int w,int h){int m=0,f=0,g=0,r=d/2,s=r*r+1,a,b,p=-1;while(++p<w)for(int q=-1;++q<h;)for(int x=p-r,c=0;(a=x+w)<r;x=a)for(int y=q-r;(b=y+h)<r;y=b)if(x*x+y*y<s&&a*a+b*b<s&&x*x+b*b<s&&a*a+y*y<s&&++c>m){m=c;f=p;g=q;}return f+" "+g;}

```

Ungolfed:

```
String k(int diameter, int width, int height) {
    int
        maxDieCount = 0,
        bestDx = 0,
        bestDy = 0,
        radius = diameter / 2,
        radiusSquared = radius * radius;
    for (int dx = 0; dx < width; ++dx) {
        for (int dy = 0; dy < height; ++dy) {
            int dieCount = 0;
            for (int x1 = dx - radius; x1 + width < radius; x1 += width) {
                int x2 = x1 + width;
                for (int y1 = dy - radius; y1 + height < radius; y1 += height) {
                    int y2 = y1 + height;
                    if (    x1 * x1 + y1 * y1 <= radiusSquared &&
                            x2 * x2 + y2 * y2 <= radiusSquared &&
                            x1 * x1 + y2 * y2 <= radiusSquared &&
                            x2 * x2 + y1 * y1 <= radiusSquared )
                        ++dieCount;
                }
            }
            if (dieCount > maxDieCount) {
                maxDieCount = dieCount;
                bestDx = dx;
                bestDy = dy;
            }
        }
    }
    return bestDx + " " + bestDy;
}

```

Pretty straightforward bruteforce approach - try every dx in \[0, width) and every dy in \[0, height), then loop through every rectangle in the resulting grid and check if all four corners are inside the circle (using basic pythagorean relations), count the number of such rectangles, and return the first dx and dy that produced the highest count for the given configuration.

Test with: (assuming both methods are placed in a class named CG52148)

```
public static void main(String[] args) {

    CG52148 o = new CG52148();
    System.out.println("8\t2\t2\t=> " + o.k(8, 2, 2));
    System.out.println("20\t5\t4\t=> " + o.k(20, 5, 4));
    System.out.println("100\t12\t12\t=> " + o.k(100, 12, 12));
    System.out.println("300\t11\t11\t=> " + o.k(300, 11, 11));
    System.out.println("340\t15\t8\t=> " + o.k(340, 15, 8));
    System.out.println("300\t36\t24\t=> " + o.k(300, 36, 24));

}

```

The third test case produces `0 8` rather than `9 3`, but they are both valid, equally optimal, and are both found by my algorithm.
> 2 votes

# Answer
## Python 2.7, 317

Here is my solution. Could be golfed a bit more, I think - but I like the solving better than the golfing. Suggestions are welcome.

I solve it using brute force, iterating over all dx and dy and then counting by column. It all runs pretty fast (\<0,05 sec. on my Mac).

Code:

```
import math as m
def D(d,w,h):
 r=d/2
 s=[0,0,0]
 for dx in range(0,w):
  for dy in range(0,h):
   t=0
   for c in range(1,int(d/w)+1):
    l=r-dx-(c-1)*w
    if l<w/2:
     l-=w
    if abs(l)<=r:
     f=r*m.sin(m.acos(1.0*l/r));t+=int((2.0*f-(dy+m.ceil((r-dy-f)/h)*h+f-r))/h)
   if t>s[0]:
    s=[t,dx,dy]
 return s

```

A main to test and profile the given cases:

```
def runTestcases():
    for d,w,h in [[8,2,2],[20,5,4],[100,12,12],[300,11,11],[340,15,8],[300,36,24]]:
        S=D(d,w,h)
        print "Wafer diameter {}, die size {} x {} => dx = {}, dy = {} ({} dies)".format(d,w,h,S[1],S[2],S[0])

def main():
    import cProfile
    cProfile.run("runTestcases()")

if __name__ == "__main__":
    main()

```

And its output:

```
Wafer diameter 8, die size 2 x 2 => dx = 0, dy = 1 (6 dies)
Wafer diameter 20, die size 5 x 4 => dx = 1, dy = 2 (10 dies)
Wafer diameter 100, die size 12 x 12 => dx = 0, dy = 8 (41 dies)
Wafer diameter 300, die size 11 x 11 => dx = 7, dy = 7 (540 dies)
Wafer diameter 340, die size 15 x 8 => dx = 5, dy = 2 (700 dies)
Wafer diameter 300, die size 36 x 24 => dx = 2, dy = 6 (66 dies)
         55354 function calls in 0.049 seconds

```
> 3 votes

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


title: m3ph1st0s's programming puzzle 1 (C++)

text:
# Question
Title: m3ph1st0s's programming puzzle 1 (C++)
This is the first of a series of C++ puzzles for you. Hope you will enjoy.

So, puzzle no.1:

Given the following program:

```
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

```

Insert some code on a single new line anywhere inside the program so that the output will be 0. The new line will contain AT MOST 18 characters (including spaces), and the rest of the lines will remain unmodified. To be clear, here is an example of a valid new code:

```
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   int* p = NULL;
   const float c=0.5;
   std::cout << a/b-a*c;
}

```

A new line with 15 characters was inserted so it's ok. However it does not solve the problem.

If this is too simple for you, don't worry, more is coming!!

# Answer
> 14 votes
```
#define int float

```

should work as well and is the same length.

# Answer
> 35 votes
We can get rid of a=1 by moving it into another scope:

```
#include <iostream>
main()
{
int a=0;if(0)
    const int a=1;
    const int b=2;
    const float c=0.5;
    std::cout << a/b-a*c;
}

```

This is I think 13 characters. Or better yet get a new `a` that also results in 0:

```
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
if(int a=2)
   std::cout << a/b-a*c;
}

```

That's 11 characters

# Answer
> 24 votes
```
#include <iostream>
main()
{
   const int a=1;
#define a 0
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

```

1 new line, 12 new chars

# Answer
> 23 votes
So, `#define a 0`, Done. I saw that was posted - unsurprisingly.

Surprisingly, this wasn't posted:

```
#include <iostream>
main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout<<0||
   std::cout << a/b-a*c;
}

```

*14 chars*

That should do, right?

# Answer
> 22 votes
```
#include <iostream>
main()
{
const int a=0;//\
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

```

17 chars.

By the way, the original program doesn't compile under MSVC, which complains that `main` doesn't have a return type.

# Answer
> 12 votes
18, including newline

```
#define float int

```

# Answer
> 11 votes
```
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   1?std::cout<<0:
   std::cout << a/b-a*c;
}

```

15 chars.

# Answer
> 9 votes
```
#include <iostream>
main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
#define a 0;1
   std::cout << a/b-a*c;
}

```

14 characters.

# Answer
> 8 votes
```
#include <iostream>
main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
std::cout<<0;//\
   std::cout << a/b-a*c;
}

```

It's 17 characters so it just fits.

# Answer
> 8 votes
```
#include <iostream>
main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   return puts("0");
   std::cout << a/b-a*c;
}

```

17 chars.

# Answer
> 7 votes
I do not know C++, however based on the question, couldn't you just input a line to simply output 0? the question specifies the output should be 0, it does not specify you must CHANGE the output to 0.

```
std::cout << 0

```

(I have 0 clue on C++, perhaps somebody can use this concept though)

# Answer
> 3 votes
12 chars, similar to mob's solution

```
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
#define a b
   std::cout << a/b-a*c;
}

```

other combinations also work, like `#define a c` or `#define c 0`

# Answer
> 2 votes
I know it's not , but I seem to be wearing that hat today!

```
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;

```

# --a;

```
   std::cout << a/b-a*c;
}

```

five chars, including the newline;

# Answer
> 0 votes
c++ whatever...

```
echo "0"; exit
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

```

run via:

```
sh mp.cpp

```

# Answer
> 0 votes
A variant on Mr Lister's answer but slightly less obvious.

```
#include <iostream>
int main()
{
   const float a=1; //??/
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

```

# Answer
> -1 votes
```
#include <iostream>
int main()
{
int a;if(a)
   const int a=1;
   const int b=2;
   const float c=0.5;
   std::cout << a/b-a*c;
}

```

How about these 11 chars...

# Answer
> -1 votes
```
#define a 0

```

http://codepad.org/N06weGJc

```
#include <iostream>
int main()
{
   const int a=1;
   const int b=2;
   const float c=0.5;
#define a 0
   std::cout << a/b-a*c;
}

```

---
Tags: code-challenge, programming-puzzle
---


title: Workweek completion

text:
# Question
Title: Workweek completion
I work from Monday to Friday. I start my day at `8:12` and have lunch from `12:00` to `12:42`. My workday ends at `16:30`.

If you are wondering why 8:12 and 12:42:

* `8:00` is the goal, but I never actually make it
* `12:42` because I take 45 minute breaks, but this works better for the challenge spec

---

### Challenge

Write a function or full program that returns the smallest fraction of time I have worked and still need to work for the current week. The interval you must use is 6 min.

Each day has 76 six-minute intervals

---

### Examples

```
Monday 02:00 -> 0/1
Monday 08:24 -> 1/190
Monday 18:00 -> 1/5
Saturday xx:xx -> 1/1

Monday 08:17 -> 0/1
Monday 08:18 - Monday 08:23 -> 1/380

```

---

### Scoring

Shortest code win but golfing languages get a \*3 multiplier.

* Pyth
* CJam
* GolfScript

(note to self: add more)

---

**Edit:** I've lowered the modifier, but I will not remove it. Some languages have some overhead like variable declaration and other long keywords; `function` ,`return`, etc. I don't want to discourage someone from writing the skeleton of a method in their chosen language because it's longer than a complete CJam answer.

# Answer
> 2 votes
# C++: 204 bytes

**g++ 4.9.2**

```
int f(char*a){int d=380,n=*a-'M'?*a-'W'?*a-'F'?*a-'S'?a[1]-'u'?3:1:5:4:2:0,m,h;sscanf(a,"%*s%d:%d",&h,&m);h=(m=h*10+m/6-82)<38?m:m>83?76:m-7;n=min(d,n*76+max(h,0));m=__gcd(n,d);printf("%d/%d\n",n/m,d/m);}

```

Live demo

Same as old answer, just replaced 5 ternary conditions of form `a==b?c:d` with `a-b?d:c` to save 1 byte each condition. Rest of the explanation remains same.

---

Old answer:

# ~~C++: 210 bytes~~

~~int f(char\*a){int d=380, n=\*a=='M'?0:\*a=='W'?2:\*a=='F'?4:\*a=='S'?5:a\[1\]=='u'?1:3,m,h;sscanf(a,"%\*s%d:%d",&h,&m);h=(m=h\*10+m/6-82)83?76:m-7;n=min(d,n\*76+max(h,0));m=\__gcd(n,d);printf("%d/%d\n",n/m,d/m);}~~

~~Live demo~~

# Explanations

```
int f(char* a) {  // Function name. Returning int instead of void to save one char
    int d=380;  // denominator

    int n= *a == 'M' ?  // Number of days
               0 :  // Monday
               *a == 'W' ?
                   2 :  // Wednesday
                   *a == 'F' ?
                       4 :  // Friday
                       *a == 'S' ?
                           5 :  // Saturday or Sunday
                           a[1] == 'u' ?
                                 1 :  // Tuesday
                                 3;   // Thurdays

    int m, h;  // Minutes and hours

    sscanf(a, "%*s%d:%d", &h, &m);  // %*s - Skip day, %d:%d - Read hour and min

    h= (
         m=h*10+m/6-82  // Calculate (h * 60 + m) / 6 - (8 * 60 + 12) / 6
       ) < 38 ? m       // Before lunch
              : m>83 ? 76  // If it is past end of day 76) clamp to 76
                     :m-7; // After lunch, subtract lunch time

    n = min(d,                  // numerator (n) can not be more than denominator
            n * 76 + max(h,0) ); // Number of day * units (6 min) per day + units of current day (from time) clamped to 0 if negative

    m=__gcd(n, d);  // Find gcd to get normalized form of rational number

    printf("%d/%d\n", n/m, d/m);  // Print the result
}  // Function ends

```

# Answer
> 0 votes
# Python - 195 bytes

Very simple, uses fractions library for simplest terms. Had a Pyth solution, but the `*4.5` was too much.

```
from fractions import*
z=raw_input()
Q=input()
n=("SMTWTF".index(z[0])-1if z[0]!='T'else"uh".index(z[1])*2+1)*76
Q=max(Q[0]*10+Q[1]/6-82,0)
print Fraction(n+(min(Q, 38)if Q<45 else min(Q-7,76)),380)

```

Takes input in two lines, the time as a tuple, since no input format was specified.

# Answer
> 0 votes
## JavaScript (ES6), ~~201~~ 191 bytes

```
f=i=>{z=(a,b)=>b?z(b,a%b):a,i=/(\w+) (\d+):(\d+)/.exec(i),t=+i[3]/6+i[2]*10-82;t=i[0][0]=='S'?380:'neduit'.indexOf(i[1][2])*76+(t<0?0:t>82?76:t>45?t-7:t>38?38:t);g=z(t,380);return+t/g+'/'+380/g}

```

### ECMAScript 5: ~~223~~ 214 bytes

```
function f(i){z=function(a,b){return!b?a:z(b,a%b)},i=/(\w+) (\d+):(\d+)/.exec(i),t=+i[3]/6+i[2]*10-82;t=i[0][0]=='S'?380:'neduit'.indexOf(i[1][2])*76+(t<0?0:t>82?76:t>45?t-7:t>38?38:t);g=z(t,380);return+t/g+'/'+380/g}

```
Ungolfed
```
function f(input) {
    var greatestCommonDivisor = function (a, b) {
        // From https://stackoverflow.com/a/17445304/404623
        return !b ? a : greatestCommonDivisor(b, a % b);
    };

    // Get input from string
    var input = /(\w+) (\d+):(\d+)/.exec(input);

    // Parse time relative to day
    var t = Number(input[3]) / 6 + Number(input[2]) * 10 - 82;

    var m, g, divisor;

    if (input[0][0] == 'S') {
        // Weekend - week is over
        m = 380;
    } else {
        if (t < 0) {
            // Before start of work day
            m = 0;
        } else if (t > 82) {
            // After end of work day
            m = 76;
        } else if (t > 45) {
            // After lunch
            m = t - 7;
        } else if (t > 38) {
            // During lunch
            m = 38;
        } else {
            m = t;
        }

        // Indices correspond to third letter of day of week
        m += 'neduit'.indexOf(input[1][2]) * 76;
    }

    // Find common divisor
    divisor = greatestCommonDivisor(m, 380);

    // Return value
    return m / divisor + '/' + 380 / divisor;
}

```

```
function f(i) {
  z = function(a, b) {
    return !b ? a : z(b, a % b)
  }, i = /(\w+) (\d+):(\d+)/.exec(i), t = +i[3] / 6 + i[2] * 10 - 82;
  t = i[0][0] == 'S' ? 380 : 'neduit'.indexOf(i[1][2]) * 76 + (t < 0 ? 0 : t > 82 ? 76 : t > 45 ? t - 7 : t > 38 ? 38 : t);
  g = z(t, 380);
  return t / g + '/' + 380 / g
}

['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'].forEach(function(d) {
  var str;
  for (var h = 8; h < 17; h++) {
    for (var m = 0; m < 60; m += 6) {
      str = d + ' ' + (h < 10 ? '0' + h : h) + ':' + (m < 10 ? '0' + m : m);
      document.body.innerHTML += str + ' -> ' + f(str) + '<br>';
    }
  }
});
```

Assumes that Sunday is the last day of the week.

# Answer
> 0 votes
## PHP, 254 bytes

This is just a port of my JavaScript answer. Due to PHP's odd behaviour with ternary operators, parentheses are necessary.

```
function z($a,$b){return$b?z($b,$a%$b):$a;}function f($q){preg_match('/(\w+) (\d+):(\d+)/',$q,$i);$t=$i[3]/6+$i[2]*10-82;$t=$i[0][0]=='S'?380:strpos('neduit',$i[1][2])*76+($t<0?0:($t>82?76:($t>45?$t-7:($t>38?38:$t))));$g=z($t,380);return$t/$g.'/'.(380/$g);}

```

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


title: Nuggets of Code

text:
# Question
Title: Nuggets of Code
# Nuggets of Code

It's a hypothetical situation where it is Friday evening, and you've invited over the usual golfing buddies to participate in your favourite hobby: code golfing. However, as this is such a brain-draining task, you need to pick up some brain food for the group so you can golf as much as possible off your code.

Now, everyone's favourite snack is chicken nuggets, but there's a problem: There is no single pack of them which covers everyone's needs. So, since you're already in the golfing mood, you decide to create a program that figures out exactly what packs you must buy to be able to cover everyone's Nugget needs.

Chicken nugget pack sizes are all over the place, and depending on where you live in the world, the standard sizes change too. However, the closest *\[place that serves nuggets\]* stocks the following sizes of nugget packs:

`4, 6, 9, 10, 20, 40`

Now you may notice that you cannot order certain combinations of nuggets. For example, `11` nuggets is not possible, since there is no combination that equals `11` exactly. However, you can make `43` by getting 1 pack of `20`, 1 pack of `10`, 1 pack of `9` and 1 pack of `4`,

`20 + 10 + 9 + 4 = 43 (597)`

where `597` is each term squared and added together *(hint: the optimal solution has this as the highest value)*. There are of course other ways of making `43`, but as you know, the more nuggets per pack, the cheaper it gets per nugget. So, you want to ideally buy the least number of packs and in the greatest quantities to minimize your cost.

# The Task

You should create a *program* or *function* which takes a list of integers corresponding to each person's requirements. You should then calculate and *print* the most cost-efficientα order to buy the chicken nuggets. The most cost-efficientα order is the combination by which the sum of the squares of each quantity is the highest. If there is absolutely no way to buy the nuggets perfectly, you must *print* a falsy value such as `0`, `False`, `Impossible!`, or whatever is available in your language.

**Example I/O:**

```
[2 7 12 4 15 3] => [20 10 9 4]
     1, 1, 2, 1 => False
  6 5 5 5 5 5 9 => 40
      [6, 4, 9] => 9 10
              1 => 0
            199 => 40, 40, 40, 40, 20, 10, 9
              2 => Impossible!

```

Here is the list of ideal solutions for the first 400. Note these are not formatted how I would expect yours to be, each `tuple` is in the form `(N lots of M)`.

# Rules

1. No standard loopholes.
2. No use of built-in functions that do all or the majority of the task, such as `FrobeniusSolve` in Mathematica.

---

α - To clarify this with an example, you could also make 43 by doing `4 + 6 + 6 + 9 + 9 + 9 = 43 (319)`, but this would not be optimal, and thus an incorrect output, as the sum of the squares is less than the combination I noted in the introduction. Essentially, higher sum of squares = lower cost = most cost-efficient.

# Answer
# Pyth, ~~26~~ 25 bytes

```
e+Zo.aNf!-TCM"
("./sQ

```

Notice that there are some unprintable chars. Try it online: Demonstration. It is quite slow (but not as slow as my 26 byte solution).

### Explanation:

```
                          implicit: Q = input list
                     sQ   sum(Q)
                   ./     generate all integer partitions
       f                  filter for partitions T, which satisfy:
             "   ("          string containing chars with the ASCII-values of 4,6,9,10,20,40
           CM                convert each char to the ASCII-value
         -T                  remove this numbers from T
        !                    and check, if the resulting list is empty
    o                      order the remaining subsets N by:
     .aN                      the vector length of N (sqrt of sum of squares)
  +Z                       insert 0 at the beginning
 e                         print the last element

```

# Pyth, 32 bytes

```
e+Zo.aNfqsTsQysm*]d/sQdCM"
(

```

Notice that there are some unprintable chars. Try it online: Demonstration This version is way faster. It finds the solution for the input `[6,7,8]` in about one second and the solution for the input `[30]` in about 90 seconds.

### Explanation:

```
                                 implicit: Q = input list
                          "...(  the string containing chars with the ASCII-values of 4,6,9,10,20,40
                        CM       convert each char to the ASCII-value
                m                map each number d to:
                  ]d                create the list [d]
                 *  /sQd            and repeat it sum(Q)/d times
               s                 unfold
              y                  generate all subsets
        f                        filter for subsets T, which satisfy:
         qsTsQ                      sum(Q) == sum(T)
    o                            order the remaining subsets N by:
     .aN                            the vector length of N (sqrt of sum of squares)
  +Z                             insert 0 at the beginning
 e                               print the last element

```
> 7 votes

# Answer
## Perl, 175 153

```
sub f{my$n=$_[0];if(!$n){return 1;}foreach$o(40,20,9,10,6,4){if($n>=$o&&f($n-$o)){print"$o ";return 1;}}return 0;}$n+=$_ for@ARGV;if(!f($n)){print":(";}

```

Takes it's input from the program arguments. Prints a **:(** if it can't find a perfect solution.

### Ungolfed Code:

```
sub f
{
    my $n = $_[0];
    if(!$n)
    {
        return 1;
    }
    foreach $o(40,20,9,10,6,4)
    {
        if($n>=$o&&f($n-$o))
        {
            print "$o ";
            return 1;
        }
    }
    return 0;
}

$n += $_ for @ARGV;
if(!f($n))
{
    print ":(";
}

```

P.S.: This is probably the first entry that doesn't take 10 minutes for `1 2` ;)

Check it out here.
> 5 votes

# Answer
# CJam, ~~45~~ ~~29~~ 28 bytes

```
q~:+_[40K9A6Z)U]m*_::+@#=0-p

```

Note that this approach is *very* slow and memory-intensive.

Try it online in the CJam interpreter.

It can be sped up significantly at the cost of 5 bytes:

```
q~:+_40/4+[40K9A6Z)U]m*_::+@#=0-p

```

Complexity is still exponential in the sum of the input, but this should handle test cases up to 159 with the online interpreter and up to 199 with the Java interpreter in a couple of seconds.

Try it online in the CJam interpreter.

### Idea

An optimal purchase (maximal sum of squares) is a valid purchase (correct number of nuggets) that has as many **40**'s as possible, then as many **20**'s as possible, then as many **9**'s as possible (e.g., `9 9` is preferable over `10 4 4`) and so forth for **10**'s, **6**'s and **4**'s.

In this approach, we generate the Cartesian product of **N** copies of the array **\[40 20 9 10 6 4 0\]**, where **N** is the desired number of nuggets. **N** is a (bad) upper bound for the number of purchases we have to make. In the sped up version of the code, we use **N/40 + 4** instead.

Because of how the array is ordered, the Cartesian product will start with the vector **\[40 ... 40\]** and end with the vector **\[0 ... 0\]**. We compute the index of the first vector that has the correct sum (which will also have the optimal sum of squares), retrieve the corresponding array element, remove the zeroes that served as placeholders and print the result.

If no vector could be found, the index will be **-1**, so we retrieve **\[0 ... 0\]**, which will print an empty array instead.

### Code

```
q~                            e# Read from STDIN and evaluate the input.
  :+                          e# Push N, the sum of all elements of the resulting array.
     [40K9A6Z)U]              e# Push B := [40 20 9 10 6 4 0].
    _           m*            e# Push B**N, the array of all vectors of dimension N
                              e# and coordinates in B.
                  _::+        e# Copy and replace each vector by its sum.
                      @#      e# Get the first index of N.
                        =     e# Retrieve the corresponding element.
                         0-p  e# Remove 0's and print.

```
> 3 votes

# Answer
# Julia, 126 bytes

```
r->(t=filter(i->all(j->j∈[4,6,9,10,20,40],i),partitions(sum(r)));show(!isempty(t)&&collect(t)[indmax(map(k->sum(k.^2),t))]))

```

This creates an unnamed function that accepts an array as input and prints an array or boolean to STDOUT, depending on whether a solution exists. To call it, give it a name, e.g. `f=n->...`.

Ungolfed + explanation:

```
function f(r)
    # Nugget pack sizes
    packs = [4, 6, 9, 10, 20, 40]

    # Filter the set of arrays which sum to the required number of nuggets
    # to those for which each element is a nugget pack
    t = filter(i -> all(j -> j ∈ packs, i), partitions(sum(r)))

    # Print the boolean false if t is empty, otherwise print the array of
    # necessary nugget packs for which the sum of squares is maximal
    show(!isempty(t) && collect(t)[indmax(map(k -> sum(k.^2), t))])
end

```

Examples:

```
julia> f([1])
false

julia> f([2,7,12,4,15,3])
[20,10,9,4]

```
> 2 votes

# Answer
# Python 3 - 265 characters

```
import itertools as i
n=list(map(int,input().split(',')));m=[]
for f in range(1,9):
 for j in range(6*f):
  for x in i.combinations((4,6,9,10,20,40,)*f,j+1):
   if sum(n)==sum(x):m.append(x)
if m!=[]:v=[sum(l**2for l in q)for q in m];print(m[v.index(max(v))])
else:print(0)

```

Showing spacing:

```
import itertools as i
n=list(map(int,input().split(',')));m=[]
for f in range(1,5):
 for j in range(6*f):
\tfor x in i.combinations((4,6,9,10,20,40,)*f,j+1):
\t if sum(n)==sum(x):m.append(x)
\t\tif m!=[]:v=[sum(l**2for l in q)for q in m];print(m[v.index(max(v))])
else:print(0)

```

Passes all test cases

**Note:** I don't know if this will pass all cases because it is so slow... But it *should*...
> 1 votes

# Answer
# JavaScript, ~~261~~ ~~256~~ 261

```
d="length";function g(a){for(z=y=0;y<a[d];z+=+a[y++]);return z}x=[40,20,10,9,6,4];l=prompt().split(",");o=g(l);p=[];for(i=0;i<x[d];i++)r=g(p),s=r+x[i],(s<o-3||s==o)&&p.push(x[i]),(i==x[d]-1||40<o-r)&&r+x[i]<o-3&&(i=-1,0==i||o-r<p[p[d]-1]&&p.pop());g(p)==o&&p||0

```

I'm not sure if this is alright, it seems to work but I'm surely missing things.

It doesn't seem to be slow though, up to `123456` it outputs `[40 x 3086, 10, 6]` almost immediatly.

Explanation:

Iterating over the nugget sizes (biggest first)

* If the sum of the stack plus the nugget size is less than the goal - 3 -\> push it on a stack
* If there is more than 40 left -\> reset the loop counter
* If the sum of the stack is more than the goal when the last nugget-size was reached -\> pop the last element, reset the loop counter
* If the sum of the stack adds up, return it, otherwise return 0

For 199 | 1 the stack built looks like this

```
i | stack
0   [40]
0   [40, 40]
0   [40, 40, 40]
0   [40, 40, 40, 40]
0   [40, 40, 40, 40]
1   [40, 40, 40, 40, 20]
2   [40, 40, 40, 40, 20, 10]
3   [40, 40, 40, 40, 20, 10, 9]
4   [40, 40, 40, 40, 20, 10, 9]
5   [40, 40, 40, 40, 20, 10, 9]
==> [40, 40, 40, 40, 20, 10, 9]

```

For 1

```
i | stack
0   []
1   []
2   []
3   []
4   []
5   []
==> 0

```
> 1 votes

---
Tags: code-golf
---


title: Play a Perfect Game of 4x4 Hex

text:
# Question
Title: Play a Perfect Game of 4x4 Hex
# Background

Hex is a two-player abstract strategy game played on a `K×K` rhombus of hexagonal tiles. Two opposite sides of the rhombus are colored white, and the other two black, and the two players, black and white, take turns in placing a token of their color on an unoccupied tile. The player who first manages to construct a path between the opposite sides of their color is the winner. It is known that the game cannot end in a draw, and that the first player has a winning strategy regardless of the board size (see the Wikipedia page for details).

# The Task

In this challenge, we fix the board size at `K = 4`, and represent the board as the following grid. The thick lines denote adjacent tiles.

Your task is to produce a winning strategy for the first player, which you can choose to be either black or white. This means that whichever legal moves the opposing player makes, your play must result in a victory. Your input is a game position (the arrangement of tokens on the board), and your output is a legal move, in the format specified below. If you want to find a winning strategy yourself, do not read this spoiler:

> **Outline of one possible winning strategy, assuming white goes first.** First select 5. After that, if you have a path from 5 to the bottom row OR black selects 0 or 1 at any point, respond by selecting whichever of 0 or 1 is vacant. If black selects 9 or 13, select 10 and then whichever of 14 or 15 is vacant. If black does not select 9, 13 or 14, then select 9 and next whichever of 13 or 14 is vacant. If black selects 14, respond by selecting 15. Next, select 10 if it is vacant; if black selects 10, respond with 11. If black then selects 6, respond with 7, and next whichever of 2 or 3 is vacant. If black does not select 6, select it, so you have a path from 5 to the bottom row.

# Input and Output

Your input is a string of 16 characters `WBE`, which stand for white, black and empty. They represent the tiles of the board, as enumerated above. You can choose the input method (which also determines your output method) from the following:

1. Input from STDIN, output to STDOUT.
2. Input as one command line argument, output to STDOUT.
3. Input as 16 single-character command line arguments, output to STDOUT.
4. Input as argument of named function, output as return value.

Your output represents the tile on which you place your next token, as it is your turn to move. You can choose from the following output formats:

1. A zero-based index (as used in the above picture).
2. A one-based index.
3. The input string with one `E` replaced by whichever of `W` or `B` you chose for your player.

# Rules

Your strategy must be deterministic. You are not required to correctly handle game positions that are unreachable from the empty board using your strategy, or positions that are already winning for either player, and you may crash on them. Conversely, on boards that are reachable using your strategy, you must return a legal move.

This is code-golf, so the lowest byte count wins. Standard loopholes are disallowed.

# Testing

I have written a Python 3 controller for validating entries, since it would be extremely tedious to do by hand. You can find it here. It supports the first three input formats and Python 3 functions (functions in other languages have to be wrapped into programs), all three output formats, and both players. If a strategy is not winning, it will output a losing game it found, so you can tweak your program.

# Answer
# Marbelous, 973b

This is a naive implementation of the hinted strategy in the question. It expects the board to be provided as 16 commandline/mainboard parameters like `hex.mbl B W E E E W E E E B E E E E E E` and it will output the zero-indexed position of white's next move.

```
00 }1 }0
&G B? W!
&0 &G &G
!!
00 }0 }1
&H B? W!
&1 &H &H
!!
.. }D .. }9 }9 }D }E }A }D }9 }A .. }E }F }5
}9 B! }E E? W? E? .. E? B? B? W? .. E? .. E?
B! ?0 B! &M &N &O E? &I \\ .. &J .. &K E? &5
?0 ++ ?0 &9 .. &D &P &A &I /\ &J .. &E &L !!
++ .. ++ !! .. !! &E !! \/ &L /\ &K !! &F
\\ .. // .. .. .. !! .. .. \/ .. \/ .. !!
.. =3 \/
&M /\ &N
\/ &O /\ &P
}0 }1 }6 .. }6 .. }7 &7 }2 }3 }A }A }B }E }F
..
..
..
..
..
..
..
..
..
.. .. .. .. .. .. .. .. .. .. .. .. .. B? W!
.. .. .. .. .. .. .. .. .. .. .. .. .. &Q &Q
.. .. .. .. B? .. E? W? E? .. E? B? E? &F \/
.. .. .. &S /\ &T &S &T &U E? &A &R &R !!
.. .. .. &7 .. .. \/ .. &2 &V !! &B \/
.. .. .. !! .. .. &U /\ &V &3 .. !!
.. .. .. .. .. .. .. .. .. !!
.. .. ..
.. .. E?
E? .. &6
&X E? !!
!! &Y
.. !!
}4 }8 }C
\/ \/ \/
30 30 31 31 32 33 35 36 37 39 31 30 31 31 31 33 31 34 31 35
&0 &X &1 &Y &2 &3 &5 &6 &7 &9 &A &A &B &B &D &D &E &E &F &F
:W?
}0
^4
=1
{0
:B?
}0
^0
=0
{0
:E?
}0
^1
=0
{0
:W!
}0
^4
=0
{0
:B!
}0
^0
>0
{0

```

I think I can probably golf about 200 characters out of this with better branching and elimination of code re-use.
> 6 votes

---
Tags: code-golf, graph-theory, board-game, hexagonal-grid
---


title: Olympic Games Logo - Free Style Edition

text:
# Question
Title: Olympic Games Logo - Free Style Edition
In a similar spirit as this question, your mission is to create the best-looking logo in at most 1K of code.

**Rules:**

1. At most 1K of code (inclusive), no external data.
2. The answer with the most upvotes wins.

Have fun!

# Answer
# SVG

1kB? Luxury. I can even pretty-print the output rather than removing all unnecessary whitespace. (The indentation does, of course, use tabs, which Markdown converts to spaces, so that's why the char count might *seem* higher than the actual 977. Removing unnecessary whitespace drops it to 861).

The overlaps are handled correctly by drawing the rings in one direction, then applying a clip and drawing them in the other direction. The colours and ratios are extracted from an official document which for some reason uses Bézier curves rather than circles.

```
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="504" height="228">
    <defs>
        <clipPath id="t">
            <rect width="504" height="114" />
        </clipPath>
    </defs>
    <g fill="none" stroke-width="12">
        <g id="u" transform="translate(82,82)" stroke="#0b8ed8">
            <g id="O">
                <circle r="72" stroke="#fff" stroke-width="20" />
                <circle r="72" />
            </g>
        </g>
        <g id="y" transform="translate(167,146)" stroke="#f9a91f">
            <use xlink:href="#O" />
        </g>
        <g id="k" transform="translate(252,82)" stroke="#231f20">
            <use xlink:href="#O" />
        </g>
        <g id="g" transform="translate(337,146)" stroke="#009e59">
            <use xlink:href="#O" />
        </g>
        <g transform="translate(422,82)" stroke="#ee2049">
            <use xlink:href="#O" />
        </g>
        <g clip-path="url(#t)">
            <use xlink:href="#g" />
            <use xlink:href="#k" />
            <use xlink:href="#y" />
            <use xlink:href="#u" />
        </g>
    </g>
</svg>

```
> 44 votes

# Answer
# Javascript (core) – 1000 on the dot. – WebKit (Chrome)

Playing with canvas.

Not sure if it is 1024 or 1000 the `K` is for, but managed to get it down to 1000 982 940 :D

Only suitable for WebKit browsers. Chrome OK. Firefox a mess. Might look into making it cross browser.

---

### Code:

```
var w=window;w.onload=function(){function e(e,t){return r()*(t-e+1)+e}function d(e,t){function r(e,t,r,i){c.beginPath();c[u]="xor";c.strokeStyle="#"+e;c.arc(t,r,66,n*i[0],n*i[1]);c.stroke();c[u]="destination-atop";c.arc(t,r,66,n*i[1],n*i[0]);c.stroke()}var i=79+e,s=66+t,o=158,a=[2,1.2],f=[1.8,.8];c.lineWidth=13;r("007a9c",e,t,f);r("ffa100",i,s,a);r("000",e+=o,t,f);r("009b3a",i+=o,s,a);r("e10e49",e+=o,t,f)}var t=Math,n=t.PI,r=t.random,i,s,o=0,u="globalCompositeOperation",a=document.getElementById("c"),f=w.innerWidth,l=w.innerHeight,c=a.getContext("2d"),h=9,p=[];a.width=f;a.height=l;for(i=0;i<l;++i){p.push({x:r()*f,y:r()*l,r:e(1,3),d:e(1,l)})}setInterval(function(){c.clearRect(0,0,f,l-h);d(f/2-200,l-200);c[u]="xor";c.fillStyle="#fff";c.beginPath();o+=e(0,7)?.01:-.01;for(i=0;i<l-h;++i){s=p[i];c.moveTo(s.x,s.y);c.arc(s.x,s.y,s.r,0,n*2);s.y+=t.cos(o+s.d)+1+s.r/9;s.x+=(i%2?1:-1)*t.sin(o)*.4;if(s.x>f+7||s.x<-7||s.y>l-(h-1.2)){p[i]={x:r()*f,y:-9,r:s.r,d:s.d}}}c.fill();if(h<l/1.7)h+=l/9e3},32)}

```

**940:** Dropped wrapping it in `onload` and rely on script being inserted at end of `body` tag + alignment bug and Firefox fix.

```
function e(e,t){return r()*(t-e+1)+e}function d(e,t){function r(e,t,r,i){c.beginPath();c[u]="xor";c.strokeStyle="#"+e;c.arc(t,r,66,n*i[0],n*i[1]);c.stroke();c[u]="destination-over";c.arc(t,r,66,n*i[1],n*i[0]);c.stroke()}var i=79+e,s=66+t,o=158,a=[2,1.2],f=[1.8,.8];c.lineWidth=13;r("007a9c",e,t,f);r("ffa100",i,s,a);r("000",e+=o,t,f);r("009b3a",i+=o,s,a);r("e10e49",e+=o,t,f)}var w=window,t=Math,n=t.PI,r=t.random,i,s,o=0,u="globalCompositeOperation",a=document.getElementById("c"),f=w.innerWidth,l=w.innerHeight,c=a.getContext("2d"),h=9,p=[];a.width=f;a.height=l;for(i=0;i<l;++i,p.push({x:r()*f,y:r()*l,r:e(1,3),d:e(1,l)}));setInterval(function(){c.clearRect(0,0,f,l-h);d(f/2-158,l-200);c[u]="xor";c.fillStyle="#fff";c.beginPath();o+=e(0,7)?.01:-.01;for(i=0;i<l-h;++i){s=p[i];c.moveTo(s.x,s.y);c.arc(s.x+=(i%2?.4:-.4)*t.sin(o),s.y+=t.cos(o+s.d)+1+s.r/9,s.r,0,n*2);if(s.y>l-(h-1.2)){p[i].x=r()*f;p[i].y=-9}}c.fill();if(h<l/1.7)h+=l/9e3},32)

```

### Fiddle:

http://jsfiddle.net/Ifnak/XSBLg/embedded/result/

http://jsfiddle.net/Ifnak/4fSWm/5/embedded/result/

Loads in Firefox as well as Chrome, but is rather heavy on resources in FF. Using `requestAnimationFrame()` helped a bit, but not enough.

Note that snow lays on bottom, thus scroll down to see the slow growth. Initially had some overpainting on the ground, but could not make it fit into 1024 chr.

### Result (low quality GIF'ed screencast):
> 39 votes

# Answer
## *Mathematica*

From my answer in the Mathematica.SE Q&A:

```
ring[x_, y_, v_, t_] :=
  Table[
    {1.2 y, -v x, 0} + {Cos@i, Sin@i}.{{0, -1, 0}, {1, 0, 1/4 - v/2}},
    {i, 0, 2 π, π/200}
  ] ~Tube~ t

Graphics3D[
  Riffle[
    {Cyan, Yellow, Darker @ Gray, Green, Red},
    Array[ring[Sqrt@3/2, #, # ~Mod~ 2, 0.17] &, 5, 0] ],
  Boxed -> False,
  ViewPoint -> {0, 0, ∞}
]

```

*Edit:* In version 10 the default lighting style changed; to render the graphic above one will need to add the Option `Lighting -> "Classic"` to `Graphics3D`.

Further playing with lighting to produce a flat two-dimensional affect:

```
Graphics3D[
  Riffle[
    Glow /@ {Hue[.59], Hue[.13], Black, Hue[.3, 1, .7], Hue[0, 1, .85]},
    Array[ring[Sqrt@3/2, #, # ~Mod~ 2, 0.13] &, 5, 0] ],
  Boxed -> False,
  ViewPoint -> {0, 0, ∞},
  Lighting -> None
]

```

---

For Oliver who said my first result was "too 3D-ish" here is an actual 2D rendering via jVincent's code with my refactoring, also from the linked thread:

```
ringSegment[mid_, deg_, color_] := {CapForm["Butt"],
  Thickness[0.042], White,                   Circle[mid, 1, deg],
  Thickness[0.03],  RGBColor @@ (color/255), Circle[mid, 1, deg + {-0.1, 0.1}]}

blue   = {  0, 129, 188};
yellow = {255, 177,  49};
black  = { 35,  34,  35};
green  = {  0, 157,  87};
red    = {238,  50,  78};

Graphics @ GraphicsComplex[
  {{2.5, 0}, {1.3, -1}, {0, 0}, {5, 0}, {3.8, -1}},
  ringSegment @@@
   {{1, {0, 5/4 π},      black},
    {2, {0, π},          yellow},
    {3, {0, 2 π},        blue},
    {2, {-π 9/8, 1/4 π}, yellow},
    {4, {0, 5/4 π},      red},
    {5, {0, 7/8 π},      green},
    {1, {5/4 π, 5/2 π},  black},
    {5, {7/8 π, 2 π},    green},
    {4, {-3/4 π, 1/4 π}, red}}
 ]

```
> 32 votes

# Answer
## Ruby, 321

Sadly, a certain head of state seems to be the headline subject of most Olympic news so far. Thus, here is my freestyle logo (mascot?) for the 2014 Games.

```
w=?$;"UW[NASY_LAQVgKAPSlKAOKGLnHAOIHMnHAOHILpHANHJLqFAOFLKAVMAVMAWKAWLAWKAMIHFGK
NFMLAMGOFFGAGJPGFIAHGFFOWPPAIGFFKQFOKMJHAIJJQGNLGFMAJIJNFIGHFHSGASMMFHHASHGGPK
MFJHTKARJSKAMGFOPJAPPOJAPRKLAQRJLAQTHLAR^LFARaARaAR]HFASZAS[FFRGAT_QGAUZGFFG
U]AQGITAPHKPANKKSALMNSGGAJPOP".codepoints{|r|r-=69;$><<(r<0??\n:(w=w==?$?' ':?$)*r)}

```

Output: (Back up and squint. Sorry for the primitive rendering but he deserves no better.)
> 27 votes

# Answer
# Bash + ImageMagick

```
convert \
  -size 330x150 xc:white -strokewidth 10 -fill none \
  -stroke \#0885c2 -draw 'arc 100,100 10,10 0,360' \
  -stroke black -draw 'arc 210,100 120,10 0,360' \
  -stroke \#ed334e -draw 'arc 320,100 230,10 0,360' \
  -stroke \#fbb132 -draw 'arc 155,140 65,50 0,360' \
  -stroke \#1c8b3c -draw 'arc 265,140 175,50 0,360' \
  -stroke \#0885c2 -draw 'arc 100,100 10,10 -20,10' \
  -stroke black -draw 'arc 210,100 120,10 -20,10' -draw 'arc 210,100 120,10 90,120' \
  -stroke \#ed334e -draw 'arc 320,100 230,10 90,120' \
  x:

```

Sample output:
> 25 votes

# Answer
# FreePascal

Winter Olympics? How about some fractal snowflakes instead of regular rings.

The recursion for the centre branch is pretty obvious: (dx,dy)= 0.5(dx,dy). Left and right branches are based on rotation by matrix multiplication:

x= x cos(a) - y sin(a)

y= x sin(a) + y cos(a)

1/4 = 0.5 cos(60) and 7/16 is a good approximation of 0.5 sin(60).

```
uses graph;
var gd, gm : integer;
var n:integer;

Procedure tree(x,y,dx,dy: integer);
begin
  if dx*dx+dy*dy>0 then begin
    line(x, y, x+dx, y+dy);
    tree(x+dx, y+dy, dx div 2, dy div 2);
    tree(x+dx, y+dy, dx div 4 + dy*7 div 16, dy div 4 - dx*7 div 16);
    tree(x+dx, y+dy, dx div 4 - dy*7 div 16, dy div 4 + dx*7 div 16);
  end;
end;

begin
  gd := D4bit;
  gm := m640x480;
  initgraph(gd,gm,'');
  setbkcolor(white); clearviewport;
  setbkcolor(black); setlinestyle(0,0,3);

  For n:=-1 to 1  do  begin
    setColor(yellow);
    tree(215,240-120*n,0,120*n);
    setColor(lightgreen);
    tree(425,240-120*n,0,120*n);
    setColor(black);
    tree(320,120-120*n,0,120*n);
    setColor(lightred);
    tree(530,120-120*n,0,120*n);
    setColor(lightblue);
    tree(110,120-120*n,0,120*n);
  end;
  readln;
  closegraph;
end.

```

. .
> 23 votes

# Answer
# Commodore 64 BASIC

Again, a C64 answer, but this time I'm allowed to use *sprites*! Yay!

I remember if you wanted to use sprites, you'd begin your program with a lots of boring `DATA` statements. To define a "high resolution" (24x21 pixels) monochromatic sprite pattern you need 63 bytes. There's actually an online sprite editor that calculates the DATA for you, so:

```
10 DATA 0,254,0,3,255,128,7,255,192,15,131,224,30,0,240,60,0,120,56,0,56,120,0
20 DATA 60,112,0,28,112,0,28,112,0,28,112,0,28,112,0,28,120,0,60,56,0,56,60,0
30 DATA 120,30,0,240,15,131,224,7,255,192,3,255,128,0,254,0

```

I'll also need some more DATA for the colours and positions. I just copied that from my answer to the original Olympic Games Logo question:

```
40 DATA 6,0,0,0,2,0,2,4,0,7,1,1,5,3,1

```

Then, you'd usually set `V=53248`. This `53248` must be an important number, because I still remember it 25 years later :) It turns out it is the base address of VIC-II (Video Interface Controller):

```
50 V=53248

```

Then I read the sprite pattern into the memory starting at the address `832`. It feels weird to just write to a memory location, no allocating, no `new`, nothing like that :) The start address needs to be a multiple of 64.

```
60 FOR I=0 TO 62
70 READ D:POKE 832+I,D
80 NEXT I

```

I'll be using the same pattern for all the sprites.

```
90 FOR I=0 TO 4
100 READ C,X,Y

```

`C` is the colour code, `X` and `Y` are horizontal and vertical positions of the circles.

A few more `POKE`s are needed:

```
110 POKE V+I*2,150+X*11
120 POKE V+I*2+1,130+Y*10

```

`V+0`, `V+2`, `V+4`, etc... are the horizontal locations of each sprite, while `V+1`, `V+3`, `V+5`... are vertical. The sprite colours start at the register `V+39`:

```
130 POKE V+39+I,C

```

The sprite data pointers start at `2040`, and since the data starts at `832`, we get `832/64`=`13`, so:

```
140 POKE 2040+I,13
150 NEXT I

```

To turn on the sprites I set bits `0-4` of the register `V+21`. I also changed the background to white, so we can see the blue circle.

```
160 POKE 53281,1
170 POKE V+21,31

```

That's it!
> 17 votes

# Answer
## Java

Similar to my SVG answer, but

* Uses two clips, to avoid slight discrepancies due to double-drawing with anti-alias.
* Because Java has actual loops, the structure is a bit nicer.

Note that I've not tried to golf it, despite the possibility of some interesting tricks (like `-57*~dir` instead of `57*(1+dir)`. It's at 923 chars, but golfs down to 624 quite easily.

```
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

public class Rings {
    public static void main(String[] args) throws Exception {
        int[] pal = new int[] {0x0b8ed8, 0xf9a91f, 0x231f20, 0x009e59, 0xee2049};
        BufferedImage img = new BufferedImage(505, 229, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = img.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        for (int dir = -1; dir < 2; dir += 2) {
            g.setClip(0, 57 * (1 + dir), 520, 114);
            for (int ring = 2 - 2 * dir; ring != 2 + 3 * dir; ring += dir) {
                for (int subring = 0; subring < 2; subring++) {
                    g.setColor(new Color(pal[ring] | (subring - 1)));
                    g.setStroke(new BasicStroke(20 - 8 * subring));
                    g.drawOval(10 + 85 * ring, 10 + 64 * (ring & 1), 144, 144);
                }
            }
        }
        ImageIO.write(img, "PNG", new File("rings.png"));
    }
}

```
> 16 votes

# Answer
## LaTeX/TikZ

**Size: 876 bytes** (12 lines, line with 72 characters and end of line)

```
\documentclass{standalone}\usepackage{tikz}\def\W{3.762bp}\def\R{71.682
bp}\def\D{12.9041bp}\usetikzlibrary{calc,hobby}\def\Y{-71.7013bp}\def\X
{169.5538bp}\begin{document}\tikz[use Hobby shortcut,every path/.style=
{line width=\W,double distance=\D, white}]{\def\Z{coordinate}\path(0,0)
\Z(A)++(\X,0)\Z(C)++(\X,0)\Z(E)($(A)!.5!(C)$)++(0,\Y)\Z(B)++(\X,0)\Z(D)
;\def~#1#2{\definecolor{#1}{cmyk}{#2}} ~A{1,.25,0,0}~B{0,.342,.91,0}~C{
0,0,0,1}~D{1,0,.91,.06}~E{0,.94,.65,0}\def~#1#2#3#4{\draw[save Hobby p%
ath={#1},double=#1,overlay](#1)+([closed] 225:\R)..+([#2]315:\R)..+([#3
]45:\R)..+([#4]135:\R); \path let\n!={\R+\D/2}in(#1)+(-\n!,0)+(\n!,0)+(
0,-\n!)+(0,\n!);}\def\0#1{\draw[double=#1,restore and use Hobby path={%
#1}{disjoint,invert soft blanks}];}~A{}{blank=soft}{}~B{}{}{blank=soft}
~C{}{blank=soft}{}\0B\0A~E{blank=soft}{}{}~D{}{}{}\0C\0E}\end{document}

```

>

**Size: 817 bytes** in one line and with two optimizations:

* Option `tikz` of class `standalone`, see comment of Wheat Wizard.
* The multiple uses of `soft=blank` can be shortened by defining a style `b`.

```
\documentclass[tikz]{standalone}\def\W{3.762bp}\def\R{71.682bp}\def\D{12.9041bp}\usetikzlibrary{calc,hobby}\def\Y{-71.7013bp}\def\X{169.5538bp}\begin{document}\tikz[use Hobby shortcut,every path/.style={line width=\W,double distance=\D,white},b/.style={blank=soft}]{\def\Z{coordinate}\path(0,0)\Z(A)++(\X,0)\Z(C)++(\X,0)\Z(E)($(A)!.5!(C)$)++(0,\Y)\Z(B)++(\X,0)\Z(D);\def~#1#2{\definecolor{#1}{cmyk}{#2}} ~A{1,.25,0,0}~B{0,.342,.91,0}~C{0,0,0,1}~D{1,0,.91,.06}~E{0,.94,.65,0}\def~#1#2#3#4{\draw[save Hobby path={#1},double=#1,overlay](#1)+([closed]225:\R)..+([#2]315:\R)..+([#3]45:\R)..+([#4]135:\R); \path let\n!={\R+\D/2}in(#1)+(-\n!,0)+(\n!,0)+(0,-\n!)+(0,\n!);}\def\0#1{\draw[double=#1,restore and use Hobby path={#1}{disjoint,invert soft blanks}];}~A{}b{}~B{}{}b~C{}b{}\0B\0A~E b{}{}~D{}{}{}\0C\0E}\end{document}

```

## LaTeX/TikZ (readable version)

The following longer version is probably easier to understand.

* The overlapping of the rings is handled by drawing the rings with blank segments first. Then at a later stage, the rings are drawn again, but this time the blank segments are filled and the other already drawn segments of the rings remain untouched. Therefore clipping is not used at all.
* The ring with the white margins is drawn by circle with a double line. The area between the lines is filled with the color of the ring and the thinner double lines form the outer and inner white margin.
* The colors and dimensions are taken from the PDF page description of page 5 of the official document (see the answer of Peter Tayler).

```
\nofiles % .aux file is not needed
\documentclass[tikz]{standalone}
\usetikzlibrary{calc}
\usetikzlibrary{hobby}

\newcommand*{\xshift}{169.5538bp}
\newcommand*{\yshift}{-71.7013bp}
\newcommand*{\radius}{71.6821bp}
\newcommand*{\whitelinewidth}{3.762bp}
\newcommand*{\colorlinewidth}{12.9041bp}

\definecolor{color@A}{cmyk}{1, .25, 0, 0}
\definecolor{color@B}{cmyk}{0, .342, .91, 0}
\definecolor{color@C}{cmyk}{0, 0, 0, 1}
\definecolor{color@D}{cmyk}{1, 0, .91, .06}
\definecolor{color@E}{cmyk}{0, .94, .65, 0}

\begin{document}
  \begin{tikzpicture}[
    use Hobby shortcut,
    every path/.style = {
      line width      = \whitelinewidth,
      double distance = \colorlinewidth,
      white,
    },
  ]
    % define center coordinates for the five rings
    \path
      (0,0) coordinate (center@A)
      ++(\xshift, 0) coordinate (center@C)
      ++(\xshift, 0) coordinate (center@E)
      ($(center@A)!.5!(center@C)$) ++(0, \yshift) coordinate (center@B)
      ++(\xshift, 0) coordinate (center@D)
    ;
    % \drawring draws the first part of the ring with blank parts
    \newcommand*{\drawring}[4]{%
      \draw[
        save Hobby path = {path@#1},
        double          = {color@#1},
        overlay,
      ]
        (center@#1)
        +([closed] 225:\radius) .. +([#2] 315:\radius) ..
        +([#3] 45:\radius) .. +([#4] 135:\radius)
      ;
    }
    % \finishring draws the blank parts of the rings
    \newcommand*{\finishring}[1]{%
      \draw[
        double                     = {color@#1},
        restore and use Hobby path = {path@#1}{
          disjoint,
          invert soft blanks
        },
      ];
    }
    \drawring{A}{}{blank=soft}{}
    \drawring{B}{}{}{blank=soft}
    \drawring{C}{}{blank=soft}{}
    \finishring{B}
    \finishring{A}
    \drawring{E}{blank=soft}{}{}
    \drawring{D}{}{}{}
    \finishring{C}
    \finishring{E}
    % set calculated bounding box
    \useasboundingbox
      let \n{r} = {\radius + \colorlinewidth/2}
      in
        (center@A) +(-\n{r}, \n{r}) % upper left corner
        (center@B -| center@E) +(\n{r}, -\n{r}) % lower right corner
    ;
  \end{tikzpicture}
\end{document}

```
> 12 votes

# Answer
# R, 70 characters

Using CRAN-R statistics.

```
l=c(1,9);plot(3:7,c(6,4,6,4,6),col=c(4,7,1,3,2),cex=10,ylim=l,xlim=l)

```
> 10 votes

# Answer
**C++ 1024 bytes**

**Updated:** Now with antialiasing. Code has been somewhat de-golfed while still fitting in (exactly) 1K.

Doesn't use any library functions except ostream functions to write output file.

```
#include <fstream>

namespace {
typedef double d;

int w=512;
d a=1./6,g=1./w,h=1./72,j=h+g,k=h-g,r=5./36;

struct p{d x,y;}ps[]={{5*a,a},{4*a,2*a},{3*a,a},{2*a,2*a},{a,a}};
struct c{unsigned char r,g,b;}cs[]={{237,51,78},{28,139,60},{0,0,0},{251,177,50},{8,133,194}};

d abs(d x) {return x<0?-x:x;}

d sqrt(d x) {
    d e=1e-6,y=1;
    for(;abs(y*y-x)>e;y=.5*(y+x/y));
    return y;
}

d dist(p c,p z) {
    d u=z.x-c.x,v=z.y-c.y;
    return abs(r-sqrt(u*u+v*v));
}

c lerp(c a,c b,d t) {
    auto l=[=](d a,d b){return a+(b-a)*t;};
    return {l(a.r,b.r),l(a.g,b.g),l(a.b,b.b)};
}

d smoothstep(d z) {
    z=(z-j)/(k-j);
    z=z<0?0:z>1?1:z;
    return z*z*(3-2*z);
}

c color(p z) {
    c o{255,255,255};
    for(int i=0,j;i<5;++i){
        j=z.y<.25?i:4-i;
        o=lerp(o,cs[j],smoothstep(dist(ps[j],z)));
    }
    return o;
}
}

int main() {
    std::ofstream o("r.ppm",std::ofstream::binary);
    o<<"P6 "<<w<<" "<<w/2<<" 255\n";
    for(int y=0;y<w/2;++y)
        for(int x=0;x<w;++x)
            o.write((char*)&color(p{x*g,y*g}),3);;
}

```

Outputs a .ppm file:
> 10 votes

# Answer
# GLSL

I feel like I'm a little late to the party, but maybe I can make up for that with the first GLSL submission on this site. It is meant to be used as the fragment shader for a screen-filling primitive, and expects the viewport resolution in the `iResolution` uniform.

Colors and positions are "borrowed" from Peter Taylor's submission. I had to shorten some variable names to get below 1024 characters, but I hope it's still readable.

See it at Shadertoy (if your browser supports WebGL).

```
uniform vec3 iResolution;

float circle(vec2 pos, float r) {
    return clamp(r - distance(gl_FragCoord.xy, pos), 0., 1.);
}

float ring(vec2 pos, float r, float d) {
    return circle(pos, r + d) * (1. - circle(pos, r - d));
}

void paint(vec3 color, float a) {
    gl_FragColor.rgb = mix(gl_FragColor.rgb, color, a);
}

void main() {
    struct r_t {
        vec2 pos;
        vec3 col;
    } rs[5];
    rs[0] = r_t(vec2( 82, 146), vec3(.04, .56, .85));
    rs[1] = r_t(vec2(167,  82), vec3(.98, .66, .12));
    rs[2] = r_t(vec2(252, 146), vec3(.14, .12, .13));
    rs[3] = r_t(vec2(337,  82), vec3(.00, .62, .35));
    rs[4] = r_t(vec2(422, 146), vec3(.93, .13, .29));

    float s = min(iResolution.x / 504., iResolution.y / 228.);
    vec2 b = (iResolution.xy - vec2(504, 228) * s) * .5;
    bool rev = gl_FragCoord.y > iResolution.y * .5;

    gl_FragColor.rgb = vec3(1);

    for (int i = 0; i < 5; ++i) {
        r_t r = rev ? rs[4 - i] : rs[i];
        paint(vec3(1), ring(r.pos * s + b, 72. * s, 11. * s));
        paint(r.col,   ring(r.pos * s + b, 72. * s,  6. * s));
    }
}

```
> 9 votes

# Answer
# Mathematica

I've replaced my original answer with one that draws on regions and their intersections. The code size is 973 bytes, ungolfed.

Regions 1-5 are the rings. The rings have an inner radius of 2.5 units; the outer radius is 3 units. The ratio of inner to outer ratio, and the general logic of the approach are to be found here.

```
i = Implicit Region;
R1 = i[6.25 <= (x + 6.4)^2 + y^2 <= 9 , {x, y}];
R2 = i[6.25 <= x^2 + y^2 <= 9 , {x, y}];
R3 = i[6.25 <= (x - 6.4)^2 + y^2 <= 9 , {x, y}];
R4 = i[6.25 <= (x + 3.2)^2 + (y + 3)^2 <= 9 , {x, y}];
R5 = i[6.25 <= (x - 3.2)^2 + (y + 3)^2 <= 9 , {x, y}];

```

## Why we cannot simply print out the 5 rings without taking layers into account.

If we plot these rings straightaway, they do not interlock. Notice that the yellow ring lies atop the blue and black rings; the green ring lies atop both the black and red rings.

```
Show[{RegionPlot[R1, PlotStyle -> Blue, BoundaryStyle -> Blue],
  RegionPlot[R2, PlotStyle -> Black, BoundaryStyle -> Black],
  RegionPlot[R3, PlotStyle -> Red, BoundaryStyle -> Red],
  RegionPlot[R4, PlotStyle -> Yellow, BoundaryStyle -> Yellow],
  RegionPlot[R5, PlotStyle -> Green, BoundaryStyle -> Green]
  }, PlotRange -> All, PerformanceGoal -> "Quality",
 ImageSize -> Large, AspectRatio -> 1/2,
 Frame -> False]

```

---

## Flipping colors at 4 intersections of rings.

Regions 6, 8, 10 and 12 are rectangles that serve to specify which intersection of two rings to focus on.

Regions 7, 9, 11, and 13 are the "ring overlaps" where the ring on the bottom should be on top.

```
R6 = Rectangle[{-5, -1}, {-2, 1}];
R7 = RegionIntersection[R1, R4, R6];
R8 = Rectangle[{2, -1}, {4, 1}];
R9 = RegionIntersection[R2, R5, R8];
R10 = Rectangle[{-2, -3}, {2, -2}];
R11 = RegionIntersection[R2, R4, R10];
R12 = Rectangle[{5, -3}, {7, -2}];
R13 = RegionIntersection[R3, R5, R12];

Show[{RegionPlot[R1, PlotStyle -> Blue, BoundaryStyle -> Blue],
  RegionPlot[R2, PlotStyle -> Black, BoundaryStyle -> Black],
  RegionPlot[R3, PlotStyle -> Red, BoundaryStyle -> Red],
  RegionPlot[R4, PlotStyle -> Yellow, BoundaryStyle -> Yellow],
  RegionPlot[R5, PlotStyle -> Green, BoundaryStyle -> Green],
  RegionPlot[R7, PlotStyle -> Blue, BoundaryStyle -> Blue],
  RegionPlot[R9, PlotStyle -> Black, BoundaryStyle -> Black],
  RegionPlot[R11, PlotStyle -> Black, BoundaryStyle -> Black],
  RegionPlot[R13, PlotStyle -> Red, BoundaryStyle -> Red]},
PlotRange -> All, PerformanceGoal -> "Quality",
 ImageSize -> Large, AspectRatio -> 1/2,
 Frame -> False]

```

---

## Which intersections had their colours flipped?

The following highlights the intersection regions where colours were "flipped". This was accomplished by changing the `BoundaryStyle` of regions 7, 9, 11, and 13 to `White`.
> 5 votes

# Answer
### Javascript (three.js) - 910 bytes

Given an html element, this function will create the rings as 3D objects and then render a still image to the element. Works in browsers that support WebGL. FIDDLE

```
function Logo(l){
    var s, c, r;
    s = new THREE.Scene();
    c = new THREE.PerspectiveCamera(45, 4/3, 1, 500);
    c.position.set(75,0,300);
    c.lookAt(new THREE.Vector3(0,0,0));
    var rings = [
        new THREE.Mesh(ring(), mat(0x0885c2)),
        new THREE.Mesh(ring(), mat(0xfbb132)),
        new THREE.Mesh(ring(), mat(0x000000)),
        new THREE.Mesh(ring(), mat(0x1c8b3c)),
        new THREE.Mesh(ring(), mat(0xed334e))
    ];
    for(var i = 0; i < rings.length; i++){
        s.add(rings[i]);
        rings[i].position.set(i*55-125,-(i%2)*50,0);
        rings[i].rotation.set(0,(i%2*2-1)*.18,0,'xyz');
    }
    r = new THREE.WebGLRenderer();
    r.setSize(400, 300);
    l.appendChild(r.domElement);
    r.render(s, c);
}
function ring(){ return new THREE.TorusGeometry(50, 8, 16, 32); }
function mat(color){ return new THREE.MeshBasicMaterial({color: color}); }

```
> 3 votes

# Answer
### C++ w/SFML (1003 incl. whitespace)

Not small by any stretch of the imagination, but kept as terse-yet-readable as possible and still under 1k.

```
#include <SFML/Graphics.hpp>

using namespace sf;

int main() {
    CircleShape circles[5];
    Color backcolor(255,255,255);
    Color colors[5] = {
        Color(0x0b,0x8e,0xd8),
        Color(0xf9,0xa9,0x1f),
        Color(0x23,0x1f,0x20),
        Color(0x00,0x9e,0x59),
        Color(0xee,0x20,0x49),
    };

    for (int i = 0; i < 5; i++) {
        circles[i] = CircleShape(144, 60);
        circles[i].setPosition(15+160*i, 46+160*(i&1));
        circles[i].setFillColor(Color::Transparent);
        circles[i].setOutlineColor(colors[i]);
        circles[i].setOutlineThickness(-16);
    }

    RenderWindow window(VideoMode(960, 540), L"Olympic Logo", Style::Close);

    while (window.isOpen()) {
        Event event;

        while (window.pollEvent(event))
            if (event.type == Event::Closed)
                window.close();

        window.clear(backcolor);

        for (int i = 0; i < 5; i++)
            window.draw(circles[i]);

        window.display();
    }

    return 0;
}

```

**Edit:** Updated colors based on @Peter Taylor's SVG submission.
> 2 votes

# Answer
# cat (10 bytes)

It was so short that the website refused to upload it until I added this description. The logo represents Olympic Games.

```
$ $ $
 $ $

```
> 2 votes

# Answer
## Delphi

```
  Canvas.Pen.Width := 10;
  Canvas.Brush.Style:=bsClear;//To prevent solid background
  Canvas.Pen.Color:=clBlue; Canvas.Ellipse(20,30,220,230);
  Canvas.Pen.Color:=clBlack; Canvas.Ellipse(240,30,440,230);
  Canvas.Pen.Color:=clRed; Canvas.Ellipse(460,30,660,230);
  Canvas.Pen.Color:=clYellow; Canvas.Ellipse(130,130,330,330);
  Canvas.Pen.Color:=clGreen; Canvas.Ellipse(350,130,550,330);

```

### Result
> 1 votes

# Answer
# SpecBAS

Each ring is made up of an inner/outer circle, then flood-filled.

Had to find the intersections manually and fill those individually (so you can still see some of the lines between them).

```
1 INK 0: PAPER 15: CLS: LET r=50
2 FOR x=1 TO 3
3 CIRCLE x*100,100,r: CIRCLE x*100,100,r-10
4 IF x<3 THEN CIRCLE (x*100)+50,150,r: CIRCLE (x*100)+50,150,r-10
5 NEXT x
6 INK 0: FILL 165,130: FILL 195,145: FILL 200,55: FILL 215,145: FILL 245,105
7 INK 9: FILL 100,55: FILL 130,130: FILL 145,105
8 INK 10: FILL 270,135: FILL 295,145: FILL 300,55
9 INK 12: FILL 205,145: FILL 215,120: FILL 250,195: FILL 255,105: FILL 280,120
10 INK 14: FILL 105,145: FILL 110,125: FILL 150,195: FILL 155,105: FILL 190,130

```
> 1 votes

# Answer
made a solution based on a Java Swing GUI UltraGolfed edition (696 charas)

```
import java.awt.Color;import java.awt.Graphics;import javax.swing.JFrame;import javax.swing.JPanel;class A extends JFrame{public A(){JPanel j=new JPanel(){protected void paintComponent(Graphics g){;((java.awt.Graphics2D)g).setStroke(new java.awt.BasicStroke(3));g.setColor(new Color(0xb,0x8e,0xd8));g.drawOval(10, 10, 80, 80);g.setColor(new Color(0xf9,0xa9,0x1f));g.drawOval(50,40,80,80);g.setColor(new Color(0x23,0x1f,0x20));g.drawOval(90, 10, 80, 80);g.setColor(new Color(0,0x9e,0x59));g.drawOval(130,40,80,80);g.setColor(new Color(0xee,0x20,0x49));g.drawOval(170, 10, 80, 80);}};j.setBounds(0,0,600,400);setSize(600,400);add(j);}public static void main(String[]a){new A().setVisible(true);}}

```

Semiuncompressed one: (971)

```
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
class A extends JFrame
{
    public A()
    {
        JPanel j = new JPanel(){
        protected void paintComponent(Graphics g)
        {;
            ((java.awt.Graphics2D)g).setStroke(new  java.awt.BasicStroke(3));
            g.setColor(new Color(0xb,0x8e,0xd8));
            g.drawOval(10, 10, 80, 80);
            g.setColor(new Color(0xf9,0xa9,0x1f));
            g.drawOval(50,40,80,80);
            g.setColor(new Color(0x23,0x1f,0x20));
            g.drawOval(90, 10, 80, 80);
            g.setColor(new Color(0,0x9e,0x59));
            g.drawOval(130,40,80,80);
            g.setColor(new Color(0xee,0x20,0x49));
            g.drawOval(170, 10, 80, 80);}};
        j.setBounds(0,0,600,400);
        setSize(600,400);
        add(j);
    }
    public static void main(String[]a)
    {
        new A().setVisible(true);
    }
}

```
> 0 votes

# Answer
**POWERSHELL , 869**
code and output in screenshot
> 0 votes

---
Tags: popularity-contest
---


title: Highest perimeter polyomino

text:
# Question
Title: Highest perimeter polyomino
This is code golf. The winner is the valid code with the smallest number of bytes.

---

## Challenge

Given inputs ***M*** and ***N***, the width and height of a rectangular grid of squares, output a polygon that satisfies the following:

* **The polygon edges are made up only of square edges:** there are no diagonal edges - all are vertical or horizontal.
* **The polygon has no holes:** every square outside the polygon may be reached by orthogonal steps on squares outside the polygon, starting from a square outside the polygon on the outer boundary of the rectangle.
* **The polygon has no self-intersection:** of the square edges meeting at a vertex, no more than 2 may be part of the polygon perimeter.
* **The polygon is connected:** any square in the polygon must be reachable from any other square in the polygon via orthogonal steps that stay within the polygon.
* **The polygon has the maximum possible perimeter:** according to the formula shown below.

Your code must work for ***M*** and ***N*** from 1 to 255.

---

## Formula for maximum perimeter

The challenge here is finding the most golfable of those polygons with the maximum perimeter. The maximum perimeter itself is always defined by the formula:

This is true because for a maximum perimeter every square vertex must be on the perimeter. For an odd number of vertices this is not possible and the best that can be attained is one vertex less (since the perimeter is always even).

---

## Output

Output the shape as a string of newline separated characters (***N*** rows of exactly ***M*** characters). Here I am using space for squares outside the polygon, and '#' for squares inside the polygon, but you may use any two visually distinct characters, provided their meaning is consistent for all inputs.

You may include up to one leading newline and up to one trailing newline.

If you wish, you may instead output ***M*** rows of exactly ***N*** characters, and you may choose ***M*** by ***N*** output for some inputs and ***N*** by ***M*** output for others.

---

## Examples

**Invalid** due to a hole:

```
###
# #
###

```

**Invalid** due to intersection (touching diagonally - a vertex with 4 square edges on the perimeter) and, incidentally, a hole:

```
##
# #
###

```

**Invalid** due to being disconnected:

```
#
# #
  #

```

**Valid** polygon of maximum perimeter:

```
# #
# #
###

```

---

## Credits

I initially underestimated how quickly the value of the maximum perimeter could be calculated, and was going to just ask for that value as the output. Thanks to the wonderfully helpful people in chat for explaining how to work out the maximum perimeter for arbitrary N and M and helping turn this into a challenge that will last for more than one answer...

Specifically thanks to:

Sparr, Zgarb, feersum, jimmy23013.

# Answer
> 4 votes
# CJam, 47 bytes

```
l~_2%{\}|_'#:H*@({N+1$(2md\HS+*H+\SH+R=*++}fR\;

```

Try it online

Explanation:

```
l~      Get and convert input.
_2%     Calculate second value modulo 2.
{\}|    If value is even, swap the two inputs. This puts odd on top if one is odd.
_'#:H*  Create top row of all # signs. Also save away # character as shortcut for later.
@(      Pull number of rows to top, and decrement because first is done.
{       Start loop over rows.
N+      Add newline.
1$      Copy row length to top of stack.
(2md    Decrement, and calculate mod/div with 2.
\       Swap mod and div, will use div first.
HS+     "# "
*       Repeat it based on div 2 of row length.
H+      Add one more #.
\       Swap mod of earlier division to top.
SH+     " #"
R=      Pick space or # depending on even/odd row number.
*       Repeat 0 or 1 times depending on mod 2 of row length.
+       Add the possible extra character to line.
+       Add line to result.
}fR     End of for loop over lines.
\;      Remove row length from stack, leaving only result string.

```

There are two main cases for the result. If at least one of the sizes is odd, the pattern is a plain "rake". For example, for input `7 6`:

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

```

If both sizes are even, there is an extra column where every second square is "on". For example, for input `8 6`:

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

```

Now, to show that these patterns reach the theoretical maximum of the perimeter as given in the problem description, we need to confirm that the first pattern has perimeter `(M + 1) * (N + 1)`, and the second one the same value minus 1.

For the first pattern, we have for the perimeter, with `M` an odd dimension:

1. `M` for the top edge.
2. `2` on the side of the top row.
3. `(M - 1) / 2` for the gaps between the teeth.
4. `(M + 1) / 2` teeth with perimeter `2 * (N - 1) + 1` each.

This adds up to:

```
M + 2 + (M - 1) / 2 + (M + 1) / 2 * (2 * (N - 1) + 1) =
M + 2 + (M - 1) / 2 + (M + 1) * (N - 1) + (M + 1) / 2 =
2 * M + 2 + (M + 1) * (N - 1) =
(M + 1) * 2 + (M + 1) * (N - 1) =
(M + 1) * (N + 1)

```

For the second case where both `M` and `N` are even, the perimeter adds up from:

1. `M` for the top edge.
2. `2` on the side of the top row.
3. `M / 2` for the open # in the top row.
4. `M / 2` teeth with perimeter `2 * (N - 1) + 1` each for the plain teeth.
5. The rightmost tooth has an extra `2 * (N / 2 - 1)` perimeter pieces for the jaggies.

Adding this all together:

```
M + 2 + M / 2 + (M / 2) * (2 * (N - 1) + 1) + 2 * (N / 2 - 1) =
M + 2 + (M / 2) * (2 * (N - 1) + 2) + N - 2 =
M + M * N + N =
(M + 1) * (N + 1) - 1

```

# Answer
> 5 votes
# Ruby, Rev 1, 66

```
->(m,n){n.times{|i|puts ("#"*m**(1-i%2)).rjust(m,i>n-2?"# ":" ")}}

```

Used raising `m` to power 0 o 1 to decide whether 1 or `m` `#`'s will be printed.

Used `>` to test for last row instead of `==`.

Can't get rid of the space after puts, nor any brackets!

# Ruby, Rev 0, 69

```
->(m,n){n.times{|i|puts ("#"*(i%2==0?m:1)).rjust(m,i==n-1?"# ":" ")}}

```

This is an anonymous lambda function. Use it like this:

```
f=->(m,n){n.times{|i|puts ("#"*(i%2==0?m:1)).rjust(m,i==n-1?"# ":" ")}}

M=gets.to_i
N=gets.to_i
f.call(M,N)

```

In the end, after asking if M and N could be interchanged I didnt need it.

---

Typical outputs for N odd. If we delete the `#` on their own on the right hand side, clearly we will have (N+1)(M+1). Including them to join the shape removes 2 squares of horizontal perimeter and adds 2 squares of vertical perimeter, so there is no change.

Here we rely on the expression `"#"*(i%2==0?m:1)` to give alternating rows of M`#` symbols and one `#` symbol, and right justify to M characters.

```
5                        6
5                        5
#####                    ######
    #                         #
#####                    ######
    #                         #
#####                    ######

```

---

Typical outputs for N even. `5 6` clearly has the same perimeter as `6 5`, or an increment of M+1=6 compared with `5 5` by addition of vertical perimeter due to the crenelation of the bottom row. `6 6` has the same as `6 5` plus an increment of (M+1)-1=6 in the vertical perimeter. Thus they are in accordance with the formula.

```
5                        6
6                        6
#####                    ######
    #                         #
#####                    ######
    #                         #
#####                    ######
# # #                    # # ##

```

It's very handy that Ruby's `rjust` allows you to specify the padding to use for the empty cells. Normally the padding is set to `" "` but for the last row we switch to `"# "` (note that padding will only be needed on the last row if N is even. Where N is odd the last row will be complete and there will be no justifying, so you won't see the crenelations.)

Check it out here.

# Answer
> 5 votes
# C, ~~109~~ 97 bytes and correctness proof

I was writting up my solution but @steveverrill beat me to it. I thought i'd share it all the same, since I included a correctness proof for the strategy used.

**Reduced Code:**

```
m,n,x;main(){for(scanf("%i%i",&m,&n); n;)putchar(x<m?"# "[x%2*(++x^m||~n&1)&&n^1]:(x=0,n--,10));}

```

**Before Reduction:**

```
m,n,x;

main(){
    for(scanf("%i%i",&m,&n); n;)

        /* If x == m, prints out a newline, and iterates outer
         * loop (x=0,n--) using comma operator.
         * Otherwise, paints a '#' on :
         *     Every even column (when x%2 is 0)
         *     On odd columns of the last row (++x^m||~n&1 is 0)
         *     On the first row (when n^1 is 0)
         * And a ' ' on anything else (when predicate is 1) */
        putchar(x<m?"# "[x%2*(++x^m||~n&1)&&n^1]:(x=0,n--,10));
}

```

**Strategy and Proof:**

Assuming the correctness of the maximum perimiter equation *(M+1)(N+1) - ((M+1)(N+1)) mod 2*, the following explains the optimal strategy used and proves its correctness by induction:

For odd M, we draw a hand-like shape with M/2 + 1 fingers, for example:

```
3x2
# #
###

5x3
# # #
# # #
#####

```

We now prove this strategy is optimal for all odd M by induction:

**Base Case:** M=N=1
The single cell is filled. The solution is correct since (1 + 1)\*(1 + 1) = 2\*2 = 4, and a square has 4 sides.

**Induction on width:**
Assume that the hand-shape strategy works for *(N, M-2)* where M is odd, that is, its perimiter is optimal and is *(N + 1)(M - 2 + 1) + ((M-1)(N+1)) mod 2*. We now show that it will work for *(N,M)*.

The process of adding a finger removes one edge from the polygon, and adds *3 + 2N*. For example:

```
 5x3 -> 7x3
 # # # $
 # # # $
 #####$$

```

Combining this with our hypothesis that the previous perimeter was optimal, the new perimeter is:

```
(N + 1)*(M - 2 + 1) - ((M+1)*(N+1)) mod 2 - 1 + 3 + 2*N
(N + 1)*(M + 1) - ((M-1)*(N+1)) mod 2 - 2(N + 1) - 1 + 3 + 2*N
(N + 1)*(M + 1) - ((M-1)*(N+1)) mod 2

```

Since we are dealing with modulo 2 arithmetic,

```
((M-1)*(N+1)) mod 2 = ((M+1)*(N+1)) mod 2

```

Thus, proving that increasing the width by adding fingers leads to an optimal perimeter.

**Induction on height:**
Assume the hand-shape strategy works for *(N-1, M)*, where *M* is odd, that is, its perimeter is optimal and is *N(M + 1) + ((M+1)N) mod 2*. We now show that it will work for *(N,M)*.

Increasing the height of the hand merely elongates the fingers, located at the first and every other x-index. For each height increase, each finger adds two to the perimeter, and there are *(M+1)/2* fingers, thus, an increase in *N* leads to an increase of *2(M+1)/2=M+1* in the perimeter.

Combining this with the hypothesis, we have that the new perimeter is:

```
N*(M + 1) + ((M+1)*N) mod 2 + M + 1
(N + 1)*(M + 1) + ((M+1)*N) mod 2

```

Modular arithmetic permits us to simplify the last term, so that we obtain:

```
(N + 1)*(M + 1) + ((M+1)*(N+1)) mod 2

```

Proving that the solution is optimal for all N\>0 and odd M\>0.

For even M, we fill in the board the same as we would for odd M, but we add crenelations to the last segment, for example:

```
4x3
# ##
# #
####

6x4
# # #
# # ##
# # #
######

```

We now prove that this strategy is optimal.

**Induction for even M:**
Assume that the the solution is correct for (N,M-1), with odd M-1 (as was proven in the last case), which has an optimal perimeter of *(N + 1)M - (M(N+1)) mod 2*. We now show that it will work for (N,M).

Like increasing the fingers, each crenelation adds two to the perimeter of the polygon. The total number of crenelations is *(N + N mod 2)/2*, for a total of *N + N mod 2* perimeter added.

Combining this with the hypothesis, we have that the new perimeter is:

```
(N + 1)*M - (M*(N+1)) mod 2 + N + N mod 2
(N + 1)*(M + 1) - (M*(N+1)) mod 2 + N mod 2 - 1
(N + 1)*(M + 1) - (M*(N+1)) mod 2 - (N + 1) mod 2

```

We have that

```
(M*(N+1)) mod 2 - (N + 1) mod 2 = ((M+1)*(N+1)) mod 2

```

Because if N is odd, then this reduces to 0=0, and if N is even, it reduces to

```
- A mod 2 - 1 = -(A + 1) mod 2

```

Thus the strategy is optimal for all *M,N\>0*.

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


# Question
Title: Write "Code Golf" without using any letters
# Goal

Your goal is to write "Code Golf" without using any letters \[A-Z, a-z\], even in your source code. It can't use of the following special characters either (!, \_, \<, (, ), ., {, }, ', and \>).

# Bonus / Scoring

* If the code backwards also writes "Code Golf", you get -10.

Good luck! Standard loopholes disallowed. Mine also isn't a duplicate, because it also has character restrictions.

# Answer
# CJam, 25

```
"¡ÍÂÃ~¥ÍÊÄ"94"`[]":^"-"+~

```

Try it online

**Explanation:**

"¡ÍÂÃ~¥ÍÊÄ" is "Code Golf" with each character (code point) incremented by 94.

```
"¡ÍÂÃ~¥ÍÊÄ"94    push that string and 94
"`[]":^          xor the characters '`', '[' and ']', obtaining 'f'
"-"+             concatenate with "-", resulting in "f-"
~                evaluate "f-", which subtracts 94 from each character

```
> 2 votes

# Answer
# HTML, 46 bytes

```
Code Golf

```

This prints / outputs:

Code Golf
> 5 votes

# Answer
# Whitespace, 146 characters

I have included `S`pace, `T`ab, and `L`ine feed indicators.

```
S S S T S S S S T   T   L
T   L
S S S S S T T   S T T   T   T   L
T   L
S S S S S S S T T   S S T   S S L
T   L
S S S S S S S T T   S S T   S T L
T   L
S S S S S S S S T   S S S S S L
T   L
S S S S S S S T S S S T T   T   L
T   L
S S S S S T T   S T T   T   T   L
T   L
S S S S S T T   S T T   S S L
T   L
S S S S S T T   S S T   T   S L
T   L
S S L
L
L

```

Try it online

**Explanation:**

* `S S` pushes a number to the stack
* `S T S S S S T T L` is the number 67 in binary ending with a line
* `T L
S S` outputs the top of the stack
* This process repeats for each letter
* Three linefeeds at the end terminates the program

Note that this does not end with a linefeed, so the command prompt will appear directly after the output. There is also some easy golfing by manipulating the stack and/or creating the numbers more efficiently, but it's past my bedtime...

**Edit:** I am unable to sleep and have been inspired by vihan1086's HTML answer. I don't see a requirement that the backwards-forwards running be in one language, so here is an **WHITESPACE + LMTH** answer that runs forwards and backwards:

```

;201#&;801#&;111#&;17#&;23#&;101#&;001#&;111#&;76#&
```

This scores 146 + 50 - 10 = 186
> 4 votes

# Answer
# GolfScript, 27 bytes

```
0000000: 5b 31 32 33 20 31 32 36 20 31 32 35 5d 2b 7e  [123 126 125]+~
000000f: 22 bc 90 9b 9a df b8 90 93 99 22 25           "........."%

```

The above is a reversible xxd dump.

The only ASCII characters the code uses are `[123 65]+~"%`.

### Proof of work

```
$ LANG=en_US
$ xxd -ps -r > codegolf.gs <<< 5b31323320313236203132355d2b7e22bc909b9adfb89093992225
$ wc -c codegolf.gs
27 codegolf.gs
$ golfscript codegolf.gs
Code Golf

```

### How it works

* Lacking input, GolfScript initially has an empty string on the stack.
* The array `[123 126 125]` contains the character codes of `{`, `~` and `}`.
* `+` concatenates. Since strings take priority over arrays, this pushes `"{~}"`.
* `~` evaluates that string, pushing the block `{~}`.
* The string of non-ASCII characters contains the logical NOTs of the character code of the string **Code Golf**.
* `%` maps the pushed block over the string. `~` is logical NOT, which is involutive, so this pushes the character codes of **Code Golf**.
* Finally, GolfScript prints the string on the stack.
> 1 votes

---
Tags: code-golf, restricted-source
---


# Question
Title: Number of characters in an integer's name
The goal of this challenge is to show how many characters are in the name of a given integer. This is code golf, so the smallest code wins.

**RULES**

* The input will be between 0 and 100 (inclusive). If it is not the program won't return anything.
* The result has to be printed as `input : answer`
* Result for `100` is `hundred`

For example, if the input is `23` you have to count the numbers of letters `twenty-three` : here the answer is 12, and you should print `23 : 12`

# Answer
> 3 votes
# Common Lisp - 72 bytes

```
(lambda(x)(if(<= 0 x 100)(format t"~A : ~A~%"x(length(format()"~R"x)))))

```

### Output from 0 to 20

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

```

# Answer
> 4 votes
# C : 117 bytes

(From kind suggestion of @edc65 and @ColeCameron)

```
f(a){char *d="0446554665366887798803665557667";printf("%d : %d",a,(a?a<20?d[a]-(a<10):d[a%10]+d[20+a/10]-48:52)-48);}

```

Live example

# C++ : 159 bytes ~~178 bytes~~

```
int f(int a){char *d[3]={"0446554665","0366555766","3668877988"};printf("%d : %d",a,(a?a<20?a>9?d[2][a-10]:d[0][a]-1:a>99?55:d[0][a%10]+d[1][a/10]-48:52)-48);}

```

Live example

# Explanation

Explanation from previous code, with all suggestions from comments incorporated.

```
int f(int a) {  // Return int to save a byte, a is the argument

    int d[3][10]={
             {0,4,4,6,5,5,4,6,6,5},  // Length of "", "-one", "-two", "-three" etc.
             {0,3,6,6,5,5,5,7,6,6},  // Length of "", "ten", "twenty", etc.
             {3,6,6,8,8,7,7,9,8,8}   // Length of "ten", "eleven", etc.
           };
    printf ("%d : %d", a,
               a
                 // If a is not zero
                 ? a < 20
                     // If a is less than 20
                     ? a > 9
                         // a is in range 10-19
                         ? d[2][a-10]
                         // a is in range 0-9
                         : d[0][a]-1  // Subtract one as '-' is not required
                     // If a is >= 20
                     : a > 99
                         // If a is 100
                         ? 7  // Length of hundred
                         // a is between 20-99
                         : d[0][a%10] + d[1][a/10]  // unit digit length + tens digit length
                 // If a is zero
                 : 4
            );
}

```

# Answer
> 0 votes
# Prolog, ~~261~~ 211 bytes

```
u(X,Y):-nth0(X,[4,3,3,5,4,4,3,5,5,4,3,6,6,8,8,7,7,9,8,8],Y).
a(X):-X>=0,X<101,(X=100,Y=7;X<20,u(X,Y);A is X//10-2,nth0(A,[6,6,5,5,5,7,6,6],B),C is X-X//10*10,(C=0,D=0;u(C,D)),Y is B+D+1),writef('%t : %t',[X,Y]).

```

# Answer
> 0 votes
# Python, 172 bytes

```
l='33544355436688779980'
a='776668778'
n=int(raw_input())
if n==0:
 print n,':',4
elif n<20:
 print n,':',l[n-1]
elif n<100:
 print n,':',int(a[n/10-2])+int(l[n-n/10*10-1])

```

Stores all the units number name lengths in a string, from 1 to 19. Combines them with 10s number name lengths if the number \>=20.

`0` is an exception. `100` is taken to be `hundred`.

# Answer
> 0 votes
**PHP** 613 Characters

As a bonus, I don't use a dictionary of integer character lengths.

```
<?php $i=10;$b[0]='zero';$b[1]='one';$b[2]='two';$b[3]='three';$b[4]='four';$b[5]='five';$b[6]='six';$b[7]='seven';$b[8]='eight';$b[9]='nine';$t='teen';$c[0]='ten';$c[1]='eleven';$c[2]='tweleve';$c[3]='thir'.$t;$c[4]=$b[4].$t;$c[5]='fif'.$t;$c[6]=$b[6].$t;$c[7]=$b[7].$t;$c[8]=$b[8].$t;$c[9]=$b[9].$t;$d[2]='twenty';$d[3]='thirty';$d[4]='fourty';$d[5]='fifty';$d[6]='sixty';$d[7]='seventy';$d[8]='eighty';$d[9]='ninety';$z='onehundred';$j=str_split($i);if(strlen($i)===1){$a=$b[$i];}elseif(strlen($i===3)){$a=$z;}elseif(substr($i,0,1)==='1'){$a=$c[$j[1]];}else{$a=$d[$j[0]].' '.$b[$j[1]];}echo$i.' : '.strlen($a);

```

**Long hand**

```
<?php
// Input
$i=10;
// 0-9
$b[0]='zero';
$b[1]='one';
$b[2]='two';
$b[3]='three';
$b[4]='four';
$b[5]='five';
$b[6]='six';
$b[7]='seven';
$b[8]='eight';
$b[9]='nine';
// 10-19 (Very tricky)
$t='teen';
$c[0]='ten';
$c[1]='eleven';
$c[2]='tweleve';
$c[3]='thir'.$t;
$c[4]=$b[4].$t;
$c[5]='fif'.$t;
$c[6]=$b[6].$t;
$c[7]=$b[7].$t;
$c[8]=$b[8].$t;
$c[9]=$b[9].$t;
// Left digit of 20-99
$d[2]='twenty';
$d[3]='thirty';
$d[4]='fourty';
$d[5]='fifty';
$d[6]='sixty';
$d[7]='seventy';
$d[8]='eighty';
$d[9]='ninety';
// 100
$z='one hundred';
// Split input
$j=str_split($i);
// 1 digit inputs
if (strlen($i)===1){$a=$b[$i];}
// 3 digit input
else if (strlen($i===3)){$a=$z;}
// 10-19
else if (substr($i, 0, 1)==='1'){$a=$c[$j[1]];}
// 20-99
else{$a=$d[$j[0]].' '.$b[$j[1]];}
// result
echo $i.' : '.strlen($a);

```

# Answer
> 0 votes
# Python 2, 158 Bytes

Just a little bit of hex :)

```
n=input()
print(`n`+' : '+`int('433544355436688779886aacbbaccb6aacbbaccb599baa9bba599baa9bba599baa9bba7bbdccbddc6aacbbaccb6aacbbaccb7'[n%101],16)`)*(-1<n<101)

```

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


# Question
Title: Compute the shortest decimal representation of a IEEE 754 double-precision binary floating-point number
**Format**

The format is a 64 bit value **x** representing a IEEE-754 double-precision binary floating-point number (a.k.a "a double"). **x** is assumed to represent a real number (not a NaN or Infinity).

**Goal**

The goal is to print/output the shortest string containing a decimal representation for which **x** is the closest IEEE 754 representation. Scientific notation is allowed. You can choose whether or not to allow a missing 0 in front of the ".".

x = 0x4000CCCCCCCCCCCD could be represented as "2.10000000000000008881784197001" but also as "2.1", which is much shorter. x = 0x3DDB7CDFD9D7BDBB can be represented as "1e-10" which is much shorter than alternative representation "1.0000000000000000364321973155E-10"

**Rules**

In addition to being correct, the program must run in a reasonable amount of time on a modern CPU, ruling out some forms of exhaustive search.

This being code-golf entries should be judged by concision, but voters should feel free to attribute points based on a discretionary judgment of elegance, and efficiency.

**A few test cases**

In these test cases, I represent the input as an hexadecimal number to make it clear that a IEEE 754 double 64 is passed. You can pass it as a double if the language supports it, or as a 64 bit integer, at your convenience.

```
f(0x4000CCCCCCCCCCCD) == "2.1"
f(0x3DDB7CDFD9D7BDBB) == "1e-10"
f(0x40934A456D5CFAAD) == "1234.5678" // N.B. not 1.2345678e3
f(0x3FEFFFFFFAA19C47) == "0.99999999"
f(0xC088A8CF13CEE9DD) == "-789.101112"`

```

# Answer
# C - ~~47~~ 45 characters

Counting just the function `f`, and not including `#include`s and `main`.

In C, the `%g` `fprintf` specifier will always choose the shortest format. Add a precision specifier equal to the usual maximum precision of `double` and a bit of casting hocus-pocus to coerce `int64` to `double` and Bob's your uncle.

```
#include <assert.h>
#include <stdint.h>
#include <stdio.h>

// The following line is what I'm counting...
f(int64_t u){printf("%.14g\n",*(double*)&u);}

int main()
{
    assert(sizeof(int64_t) == sizeof(double));

    f(0x4000CCCCCCCCCCCD);
    f(0x3DDB7CDFD9D7BDBB);
    f(0x40934A456D5CFAAD);
    f(0x3FEFFFFFFAA19C47);
    f(0xC088A8CF13CEE9DD);

    return 0;
}

```

Output is as per specs:

```
2.1
1e-10
1234.5678
0.99999999
-789.101112

```

Summary: `C` rocks!
> 5 votes

# Answer
## Common Lisp - 138 bytes

```
 (ql:quickload'(ieee-floats cl-ppcre))(lambda(x)(#1=ppcre:regex-replace"e0$"(#1#"\\.?d"(format()"~a"(ieee-floats:decode-float64 x))"e")""))

```

(138 = 101 for the actual function + 37 for quickload'ing libraries)

## Ungolfed

The default representation of floating-points in CL is already quite close to the requested output. However, there are some discrepancies. For example, double-precisions numbers are written with a `d` exponent character (e.g., `2.10d0`). That is why I modify the output of the formatted string with regexes:

```
(ql:quickload '(ieee-floats cl-ppcre))
(lambda (x)
  (cl-ppcre:regex-replace  ; remove "e0" at end of string
     "e0$"
     (cl-ppcre:regex-replace ; change ".d" and "d" to "e"
       "\\.?d"
       (format nil "~a" (ieee-floats:decode-float64 x))
       "e")
     ""))

```

## Example

```
;; NB: * is set by the REPL to the last returned value.
;; Here, we store the previously defined lambda:
(defparameter *fun* *)

;; Test cases
(defparameter *sample*
  '(#x4000CCCCCCCCCCCD
    #x3DDB7CDFD9D7BDBB
    #x40934A456D5CFAAD
    #x3FEFFFFFFAA19C47
    #xC088A8CF13CEE9DD))

;; Default representation
(mapcar #'ieee-floats:decode-float64 *sample*)
=> (2.1d0 1.d-10 1234.5678d0 0.99999999d0 -789.101112d0)

;; Custom conversion
(mapcar *fun* *sample*)
=> ("2.1" "1e-10" "1234.5678" "0.99999999" "-789.101112")

```

## Round-trip

Here, we convert the printed representations back to IEEE-754 doubles.

```
;; read values as double-precision numbers
(let ((*read-default-float-format* 'double-float))
  (mapcar #'read-from-string *))
=> (2.1 1.e-10 1234.5678 0.99999999 -789.101112)

;; Encode
(mapcar #'ieee-floats:encode-float64 *)
=> (4611911198408756429 4457293557087583675 4653144502051863213 4607182418709945415 13873524259458836957)

;; Check
(equal * *sample*)
=> T

```
> 0 votes

# Answer
# Julia, 20 characters

```
r(h)=hex2num(hex(h))

```

Function to test the results for correctness:

```
function decrep()
    tests=[0x4000CCCCCCCCCCCD 0x3DDB7CDFD9D7BDBB 0x40934A456D5CFAAD 0x3FEFFFFFFAA19C47 0xC088A8CF13CEE9DD]
    results=[2.1 1e-10 1234.5678 0.99999999 -789.101112]

    for i=1:length(tests)
        println("input   : $(hex(tests[i]))")
        println("result  : $(r(tests[i]))")
        println("expected: $(results[i])")
        println("$(r(tests[i]) == results[i])")
    end
end

```

Executing the test function:

```
julia> decrep()
input   : 4000cccccccccccd
result  : 2.1
expected: 2.1
true
input   : 3ddb7cdfd9d7bdbb
result  : 1.0e-10
expected: 1.0e-10
true
input   : 40934a456d5cfaad
result  : 1234.5678
expected: 1234.5678
true
input   : 3feffffffaa19c47
result  : 0.99999999
expected: 0.99999999
true
input   : c088a8cf13cee9dd
result  : -789.101112
expected: -789.101112
true

```

If the output absolutely has to be a string, then the solution would be:

```
s(h)=string(hex2num(hex(h)))

```

with 28 characters.

```
julia> h=0x4000cccccccccccd
0x4000cccccccccccd

julia> s(h)=string(hex2num(hex(h)))
s (generic function with 1 method)

julia> s(h)
"2.1"

```

Summary: Julia rocks, too ;)
> 0 votes

---
Tags: code-golf, floating-point
---