title: Circular robot instructions

text:
# Question
Title: Circular robot instructions
This challenge is based on Project Euler problem 208. Also related to my Math Stack Exchange question, Non-self-intersecting "Robot Walks".

You have a robot that moves in arcs which are \\$1/n\\$ of a circle, with each step turning toward the left or to the right. The robot takes in an array of instructions of the form \\$(a\_1, a\_2, \dots, a\_{2m})\\$ with \\$a\_k \in \mathbb N\_0\\$. The robot follows these instructions by taking \\$a\_1\\$ steps to the right, followed by \\$a\_2\\$ steps to the left, followed by \\$a\_3\\$ steps to the right, continuing in this alternating fashion until completing the final instruction by taking \\$a\_{2m}\\$ steps to the left. If the robot is in the same position (and same orientation) that it began in, then it terminates, otherwise, it starts the sequence of moves over.

---

The goal of this challenge is to write a program that takes in an integer \\$n \geq 2\\$ and a list of instructions \\$(a\_1, a\_2, \dots, a\_{2m})\\$ and computes how many self-intersections the robot's path contains.

---

# Example

For example, with \\$n = 5\\$, these are the following walks for `[1,2]`, `[1,3]`, `[1,4]`, `[2,3]`, `[2,4]`, and `[3,4]` respectively:

The number of intersections are `0`, `5`, `10`, `0`, `5`, and `0` respectively.

### Play

Want to try it out for yourself? You can use the left/right arrow keys on your computer via this web app forked from Github user cemulate. Change the step size by modifying the `n=6` parameter in the URL. Change the initial walk by modifying the `w=5,3` parameter in the URL, or remove the initial walk by removing the `&w=5,3` parameter altogether.

---

# Test data

```
  n | instructions  | output
----+---------------+--------
  3 | [3,0]         | 0
  3 | [3,1]         | 3
  3 | [3,3]         | 1
  3 | [3,2,3,1]     | 2
  6 | [1,1]         | 0
  6 | [5,1]         | 3
  6 | [5,2]         | 1
  6 | [5,3]         | 3
  6 | [5,4]         | 6
  6 | [1,1,1,5]     | 3
  6 | [1,2,3,4]     | 0
  6 | [1,2,3,4,5,6] | 8
  7 | [2,3,1,3,1,1] | 14
  7 | [3,1,4,1]     | 56
 19 | [1,2]         | 0

```

Note: You can assume that the instructions will not cause the robot to *retrace* it's track (as in \\$n = 6\\$ and `[1,4,2,3]` or \\$n = 7\\$ and `[2,3,1,3]`.) That is, the robot may intersect its path tangentially or transverally, but it will not retrace a step. You can also assume that there will be a finite number of intersections (e.g., `[5,5]` will never be an instruction for \\$n = 6\\$).

---

# Challenge

Your program must take two parameters

* A positive integer, `n`, the reciprocal of which gives the step size, and
* An even-length array of nonnegative integers, `a`, the instruction for the robot.

Your program must output a single integer, which counts the number of times that the robot intersects its path, tangentially (as in \\$n=6\\$ with `[5,3]`) or transverally (as in \\$n=5\\$ with `[1,3]`).

This is a challenge, so the shortest code wins.

# Answer
> 10 votes
# Python 3.8 (pre-release), 1533 bytes

```
def w(n,ll,ans):
	global p,q
	from math import sin,cos,pi,atan2
	def y(s,e,f,a,b):
		x,y=f(s),f(e)
		g=lambda a,b,x:0<=(x-a)%2<=b-a
		while e-s>1e-15:
			m=(s+e)/2
			z=f(m)
			if x*z<=0:
				e,y=m,z
			else:
				s,x=m,z
		return (g(a,b,s)or g(a,b,e))and[s]or[]
	from fractions import Fraction as R
	s,v,d=(0,0,R(1,2)),[],1
	while True:
		for l in ll:
			b=s[2]+R(1,2)*d
			c=s+(R(2,n)*l,d,(s[0]-cos(b*pi),s[1]-sin(b*pi)),b,b-R(2,n)*l*d)
			if l:
				v.append(c)
				s=(c[5][0]+cos(c[7]*pi),c[5][1]+sin(c[7]*pi),(c[7]-R(1,2)*d)%R(2))
			d=-d
		if s[2]==R(1,2):
			break
	e,l=enumerate,len(v)
	q=lambda x:all(abs(i)<1e-7 for i in x)
	p=[]
	h=lambda i,p:any(all(q([j-k]) for j,k in zip(i,a))for a in p)
	def z(u):
		global p,q
		for i in u:
			if not h(i,p):
				p.append(i)
	if all(abs(i)<1e-6 for i in s[:2])and l>1:
		[z([c[:2]]) for c in v if c[3]==R(2)]
		x_=[t_ for n,c in e(v) for m,d in e(v) if (n-m)%l not in [0,1,l-1] and len(t_:=[(f,t) for f,g in [(c,d),(d,c)]if not q(x:=[f[5][i]-g[5][i]for i in[0,1]])and (a:=x[0])**2+(b:=x[1])**2<=4+1e-14 and(t:=sum((y((r:=[1,-1][b<0]*2/pi*atan2((1-(u:=a/(a*a+b*b)**.5)*u)**.5,u-1))-i,r+j,lambda t:(a+cos(pi*t))**2+(b+sin(pi*t))**2-1,*sorted(f[6:]))for i,j in[(1,0),(0,1)]),[]))])==2]
		[z([i for i in x[1] if h(i,x[0])])for x in[[[(f[5][0]+cos(i*pi),f[5][1]+sin(i*pi))for i in t]for f,t in t_]for t_ in x_]]
		print(len(p),sep='',end='')
		if len(p)!=ans:
			print(min((abs(i[0]-j[0])+abs(i[1]-j[1]),n,m) for n,i in e(p) for m,j in e(p) if n!=m))
		else:
			print('')
	else:
		print(0)

```

Try it online!

## Python 2 (PyPy), 1580 bytes

```
n,ll=map(eval,input().split(' '))
from math import sin,cos,pi,atan2
#and let's implement the bisection
def y(s,e,f,a,b):#solve f=0 within (s,e) if x in (a,b)
    x,y=f(s),f(e)
    g=lambda a,b,x:0<=(x-a)%2<=b-a
    while e-s>1e-15:# or g(a,b,s)!=g(a,b,e):
        m=(s+e)/2
        z=f(m)
        if x*z<=0:
            e,y=m,z
        else:
            s,x=m,z
    c,d=g(a,b,s),g(a,b,e)
    #c,d
    #True,True [s]
    #True,False [s]
    #False,True [s]
    #False,False []
    return (c or d)and[s]or[]
from fractions import Fraction as R
#the start point
s=(0,0,R(1,2))
#now let's compute the arcs
#we need to store x0,y0,angle,length,direction,center,start angle,end angle
#arcs array
v=[]
d=1#the direction, 1 for clockwize
while True:
    for l in ll:
        b=s[2]+R(1,2)*d#start angle
        c=s+(R(2,n)*l,d,(s[0]-cos(b*pi),s[1]-sin(b*pi)),b,b-R(2,n)*l*d)#the arc
        if l:
            v.append(c)
            s=(c[5][0]+cos(c[7]*pi),c[5][1]+sin(c[7]*pi),(c[7]-R(1,2)*d)%R(2))
        d=-d
    if s[2]==R(1,2):
        break
e,l=enumerate,len(v)
q=lambda x:abs(x)<1e-7
p=[]#array of intersection points
#like in array
h=lambda i,p:any(all(q(j-k) for j,k in zip(i,a))for a in p)
def z(u):#add points if not in array
    global p,q
    #print(p,u)
    for i in u:
        if not h(i,p):
            p.append(i)
if all(abs(i)<1e-6 for i in s[:2])and l>1:
    #returned to the same point
    for n,c in e(v):
        if c[3]==R(2):z([c[:2]])
        for m,d in e(v):
            if (n-m)%l not in [0,1,l-1]:
                #compute the intersection
                x=[]
                for f,g in [(c,d),(d,c)]:
                    a,b=[f[5][i]-g[5][i]for i in[0,1]]
                    if q(a)and q(b):
                        break
                    if a*a+b*b>4+1e-14:
                        break
                    u=a/(a*a+b*b)**.5
                    #the angle from a to b
                    r=[1,-1][b<0]*2/pi*atan2((1-u*u)**.5,u-1)
                    t=sum(
                    (y(r-i,r+j,lambda t:(a+cos(pi*t))**2+(b+sin(pi*t))**2-1,\
                        *sorted(f[6:]))for i,j in[(1,0),(0,1)]),[])
                    #that's it
                    if not t:
                        break
                    x.append([(f[5][0]+cos(i*pi),f[5][1]+sin(i*pi))for i in t])
                else:
                    #intersection points
                    z([i for i in x[1] if h(i,x[0])])
    print(len(p))
else:
    #infinite, return 0
    print(0)

```

Try it online!

Runs in all test cases.

# Python 3.8 + sympy, ungolfed,

covering almost all test cases (except 7 and 19 -- sympy can't simplify some expressions)
at least to know what you have to bear.
Major improvement in comparison with previous version is that:

1. It simply holds array of intersection points,
2. Any arc end counts as intersection if arc length \\$=2\pi\\$ unless arc array length is \\$1\\$
Still need to be rewritten into precise \\$i^{\frac{2\pi}{n}}\\$ arithmetic

```
from sympy import *
R=Rational
angle=R(0)
class Arc:
    def __init__(self,x0,y0,angle,length,direction):
        #','.join('self.%s'%i for i in 'x0,y0,angle,length'.split(','))
        (self.x0,
         self.y0,
         self.angle,
         self.length,
         self.dir)=x0,y0,angle,length,direction
        self.start=(angle+pi/R(2)*direction)#%(R(2)*pi)
        self.end_=self.start-self.length*self.dir
        self.center=(x0-cos(self.start),y0-sin(self.start))
    def i(self,a0):
        #t=symbols('t')
        #param_form=(self.center[0]+cos(self.start+t),
        #            self.center[1]+sin(self.start+t))
        #z=solveset((a.center[0]-param_form[0])**2+
        #           (a.center[1]-param_form[1])**2-1,t)
        #return z
        #to (a + cos(t))^2 + (b + sin(t))^2 = 1
        a,b=[self.center[i]-a0.center[i] for i in [0,1]]
        try:
            d={frozenset([-cos(3*pi/7) - sin(pi/14), -2*sin(3*pi/7)]):False,
               frozenset([cos(3*pi/7) + sin(pi/14), 2*sin(3*pi/7)]):False}
            if (frozenset([a,b]) in d and d[frozenset([a,b])]) or \
               (frozenset([a,b]) not in d and a**R(2)+b**R(2)>R(4)):
                return set()
            if a**R(2)+b**R(2)==R(4):
                #https://www.wolframalpha.com/input/?i=%28a%2Bcos%28t%29%29%5E2%2B%28b%2Bsin%28t%29%29%5E2%3D1+and+a%5E2%2Bb%5E2%3D4
                #s=R(-1,2)*sqrt(R(4)-a**R(2))
                #c=R(-1,2)*a
                if (a==R(2)):
                    return set([pi])
                return set([(R(-1) if b<R(0) else R(1))*R(2)*\
                            atan2(sqrt(R(4)-a**R(2)),a-R(2))])
        except Exception:
            print((a,b))
            raise
        #https://www.wolframalpha.com/input/?i=%28a%2Bcos%28t%29%29%5E2%2B%28b%2Bsin%28t%29%29%5E2%3D1
        if a!=R(0) and a!=R(2) and ((z0:=b**R(2)+a**R(2)-R(2)*a)==0 or\
           abs(float(z0))<1e-6):
            s=R(2)*(R(-1) if b<R(0) else R(1))*atan2(sqrt(-(a-R(2))*a),(a-R(2)))
            return set([s])
        if not ((z0:=b**R(2)+a**R(2)-R(2)*a)==0 or\
           abs(float(z0))<1e-6):
            s=sqrt(-a**R(4)-2*a**R(2)*b**R(2)+4*a**R(2)-b**R(4)+R(4)*b**R(2))
            r=set()
            for sg in [R(-1),R(1)]:
                d=a**R(3)-2*a**R(2)+sg*b*s+a*b**R(2)-R(2)*b**R(2)
                if d!=0 or abs(float(d))>=1e-6:
                    r.add(R(2)*atan2((sg*s-R(2)*b),z0))
            return r
        #thank you so much for such interesting coding challenge
        if a==R(0) and b==R(0):
            return set()
        print((a,b))
        raise Exception('')
    def end(self):
        return (self.center[0]+cos(self.start-self.length*self.dir),
                self.center[1]+sin(self.start-self.length*self.dir),
                (self.end_-pi/R(2)*self.dir)%(R(2)*pi))

from PIL import Image,ImageDraw
d=300
x0,y0=d//2,d//2
r,r0=20,2
n,l=7 , [2,3,1,3,1,1]#5,[3,4]
s=(r'''  3 | [3,0]         | 0
  3 | [3,1]         | 3
  3 | [3,3]         | 1
  3 | [3,2,3,1]     | 2
  6 | [1,1]         | 0
  6 | [5,1]         | 3
  6 | [5,2]         | 1
  6 | [5,3]         | 3
  6 | [5,4]         | 6
  6 | [1,1,1,5]     | 3
  6 | [1,2,3,4]     | 0
  6 | [1,2,3,4,5,6] | 8
  7 | -[2,3,1,3,1,1] | 14
  7 | -[3,1,4,1]     | 56
 19 | -[1,2]         | 0'''
r'''5 | -[0,1,1,3,4,1,2,1,1,4,1,2,1,3] | 2
'''
)
def add_point(point):
    global points,count
    if not any(all(abs(float(j-k))<1e-6 \
                   for j,k in zip(i,point)) for i in points):
        points.append(point)
        count+=1

import re
for n,l,ans in\
re.findall(r'\s*(\d+)\s*\|\s*\[(.*?)\]\s*\|\s*(\d+)',s):
#[(5,'0,1,1,3,4,1,2,1,1,4,1,2,1,3',2)]:
#[('7', '2,3,1,3,1,1', '14')]:
#    [('6', '1, 1', '0')]:
#    [(6,'1,1,1,5',3)]:
    print(n,l,end='')
    n=int(n)
    l=[int(i.strip()) for i in l.split(',')]
    fn='196399/%d_%s.png'%(n,'_'.join(map(str,l)))
    start=(0,0,pi/R(2))
    dir_=1
    a_array=[]
    for count in range(30):
        for l_ in l:
            a=Arc(*start,pi/R(n)*R(2*l_),dir_*2-1)
            a_array.append(a)
            start=[simplify(i) for i in a.end()]
            #print(start,a.center,a.start,a.end_)
            dir_^=1
        if (abs(float(start[0]))<1e-3) and \
           (abs(float(start[1]))<1e-3) and start[2]%(R(2)*pi)==pi/R(2):
            break
##        else:
##            continue
##        break
    print(' ',count,'loops made',end='')
    a_array=[a for a in a_array if a.length!=0]
    print(' ',len(a_array),end='')
    count=0
    points=[]
    if len(a_array)==1:
        print(' ans=%s, count=%d'%(ans,count))
        continue
    for n,a in enumerate(a_array):
        if a.length==R(2)*pi:
            add_point((a.x0,a.y0))
        for m,b in enumerate(a_array):
            if (n-m)%len(a_array) not in [0,1,len(a_array)-1]:
                #print('.',sep='',end='')
                try:
                    i_=[list(a.i(b)),list(b.i(a))]
                    p_=list(list(0<=((-R(d_)*(i-st))%(R(2)*pi))<=l_ for i in s) \
                           for s,l_,st,d_ in \
                           zip(
                               (i_),
                               [a.length,b.length],
                               [a.start,b.start],
                               [a.dir,b.dir]
                               ))
                    if all(any(i) for i in p_):
                        for t,angle in zip(p_[0],i_[0]):
                            if t:break
                        point=tuple(i+f(angle) for i,f in zip(a.center,[cos,sin]))
                        add_point(point)
                        #print('\n',(n,m),sep='')
                except Exception:
                    print(i_,[a.length,b.length],[a.start,b.start])
                    raise
    #assert count//2==int(ans)
    print(' ans=%s, count=%d'%(ans,count))
    #break
    continue
    xy=[sum(map(f,a_array))/len(a_array) for f in \
        [(lambda i:lambda a:a.center[i])(i) for i in [0,1]]]
    image = Image.new('RGB',(d,d),'white')
    draw = ImageDraw.Draw(image)
    point=lambda x,y:draw.ellipse((x0-r0+x,y0-r0-y,x0+r0+x,y0+r0-y),'blue','blue')
    for a in a_array:
        start=[a.x0,a.y0,a.angle]
        dir_=a.dir
        point(*[int((i-xy_)*R(r)) for i,xy_ in zip(start[:2],xy)])
        c=[int((i-xy_)*R(r)) for i,xy_ in zip(a.center,xy)]
        draw.arc((c[0]-r+x0,-c[1]-r+y0,c[0]+r+x0,-c[1]+r+y0),
                 *([int(-a.start*180/pi),int(-a.end_*180/pi)][::dir_]),
                 0x3a2af6)
    #image.save(fn,'PNG')
    #break
#image.show()
a=a_array
f=lambda n,m:(a[n].i(a[m]),a[n].start,a[n].length,a[n].dir)
g=lambda a,b:list(list((0,((-R(d_)*(i-st))%(R(2)*pi)),l_) for i in s) \
                           for s,l_,st,d_ in \
                           zip(
                               (i_),
                               [a.length,b.length],
                               [a.start,b.start],
                               [a.dir,b.dir]
                               ))

```

Output:

```
3 3,0  0 loops made  1 ans=0, count=0
3 3,1  2 loops made  6 ans=3, count=3
3 3,3  0 loops made  2 ans=1, count=1
3 3,2,3,1  0 loops made  4 ans=2, count=2
6 1,1  29 loops made  60 ans=0, count=0
6 5,1  2 loops made  6 ans=3, count=3
6 5,2  1 loops made  4 ans=1, count=1
6 5,3  2 loops made  6 ans=3, count=3
6 5,4  5 loops made  12 ans=6, count=6
6 1,1,1,5  2 loops made  12 ans=3, count=3
6 1,2,3,4  2 loops made  12 ans=0, count=0
6 1,2,3,4,5,6  1 loops made  12 ans=8, count=8

```

But it can generate such things although it was not in the task.

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


title: Simulate move left for 2048

text:
# Question
Title: Simulate move left for 2048
I have a fixed length vector of 4 elements. The inputs of which are always 0 or 2^n for n = 1 to 15 (so n = 0 excluded i.e. 2^0 = 1 will not appear)

`x = [32, 4, 4, 8]`

the result should be

`x = [32, 8, 8, 0]`

The way it works is that values that are the same will get combined, but one it's combined it can not be combined with another value for another turn.

and we want to simulate the shortest code to make simulate 2048 move left on this one row.

The shortest code wins! It's fixed-size 4 vector. So it's not the same as the other problem. Also, you need to put zeros here.

Test cases:

```
[0,0,0,0] -> [0,0,0,0]
[0,0,0,2] -> [2,0,0,0]
[2,0,0,4] -> [2,4,0,0]
[8,0,0,8] -> [16,0,0,0]
[16,16,32,64] -> [32,32,64,0]
[16,16,8,8] -> [32,16,0,0]
[2,2,2,0] -> [4,2,0,0]

```

# Answer
> 1 votes
# APL (Dyalog Unicode), 36 bytesSBCS

Anonymous tacit prefix function.

```
⎕UCS{4↑⍺⍺t⎕R(1⌽∪¨t←2/¨⍺⍺2*⍳16)⍺⍺⍵~0}

```

Try it online!

`⎕UCS{``}` derived function where  is the argument and `⍺⍺` converts to/from code points:

`⍵~0` the argument without zeros

`⍺⍺` convert to code points

`t⎕R(``)`**R**eplace the texts `t` (defined below) with the corresponding texts from:

`⍳16` the indices from 1 to 16

`2*` two raised to the power of those

`⍺⍺` convert them to characters

`2/¨` make two of each

`t←` assign to `t`

`∪¨` get the unique element from each (i.e. deduplicate them)

`1⌽` cyclically rotate the first string to the end

`⍺⍺` convert to code points

`4↑` take the first four elements, padding with zeros

# Answer
> 1 votes
# , 31 bytes

```
4$!.0[:;_2([:<,`+@.=/)\ ::0-.&0

```

Try it online!

# Answer
> -3 votes
# Julia 277 248 bytes

```
m(x)=begin
t=true
e=falses(3)
for i in 2:4
if x[i]!=0
d=!t
for j in i-1:-1:1
if x[j]!=0
if(x[j]!=x[i])|e[j]
p=x[i]
x[i]=0
x[j+1]=p
d=t
break
elseif x[j]==x[i]
x[j],x[i]=x[i]*2,0
e[j]=t
d=t
break
end
end
end
if !d
x[1],x[i]=x[i],0
end
end
end
x
end

```

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


# Question
Title: Transformers in Disguise (Robbers' Thread)
The cop's thread is here

The robber's task is to find a program of size equal to or less than the cop's program, which, when given an itself as input, produces the same output as the cop's program.

Additionally, even if a cop's answer is provisionally marked Safe and has been revealed, you can still crack it by finding an input that is not the same as the given source code, but still produces the same output.

## Rules:

* Submissions consist of
    + Language name + flags
    + Username of the cop with a link to the original post
    + The cracked program
* An explanation would be appreciated
* Your goal is to crack the most Cop's programs

## Some Examples:

### brainfuck, xxx's submission

```
[,[>,]<[.<]]

```

Try It Online!

This program simply reverses the input

Good luck!

# Answer
# Node.js v10.9.0, Arnauld

```
o=>[...o].sort(n=>16&(j+=13),j=9).join``

```

Try it online!

This outputs this particular permutation of itself when using Node's current sorting algorithm:

```
&`nij.9=j.,)r31n=+(=ooj`[o.o.)1.s](>=6>t

```

An insightful comment by l4m2 gave me a headstart, but I had to write a brute-forcer to figure out which permutation of digits gives the correct output...
> 5 votes

# Answer
# JavaScript Firefox, l4m2

```
btoa

```

`btoa(btoa)` encodes the following string (including linefeeds):

```
function btoa() {
    [native code]
}

```

which gives:

```
"ZnVuY3Rpb24gYnRvYSgpIHsKICAgIFtuYXRpdmUgY29kZV0KfQ=="

```
> 4 votes

# Answer
# Python 3.6+, agtoever

```
print("".join([f"{ord(c)^170}" for c in input()]))

```

Since the byte count was 50 and there were 150 digits, I split it into groups of 3, and then guessed that some XOR had been applied to the ASCII representations of the characters so iterated over all possible XORs.

Try it online!
> 3 votes

# Answer
# Perl 6, donaldh

```
bag(get.comb).kv.sort.join.say

```

Try it online!

(This produces the same output for all permutations of the input, for example `().....aabbceggijkmnooorssttvy`, but I strongly suspect that this is donaldh's program.)
> 2 votes

# Answer
# A Pear Tree, ais523

```
eval(x=q[print"eval(x=q[$x])"ne$_||exit|UPNR])

```

Try it online!
> 2 votes

# Answer
# Pepe, u\_ndefined

Bit late back to this, but this looks to be simply add the character index to the char value

```
REEerEEReEeREEEEEeeeree

```

You can try it here. The permalink forces in breaks, but it should still work.
> 2 votes

---
Tags: cops-and-robbers
---


title: The strange ordering of Sharkovskii

text:
# Question
Title: The strange ordering of Sharkovskii
## Introduction

In this challenge, we will be dealing with a certain ordering of the positive integers. The ordering goes like this:

```
   3,    5,    7,    9,    11, ...
 2*3,  2*5,  2*7,  2*9,  2*11, ...
 4*3,  4*5,  4*7,  4*9,  4*11, ...
 8*3,  8*5,  8*7,  8*9,  8*11, ...
16*3, 16*5, 16*7, 16*9, 16*11, ...
 ...
... 64, 32, 16, 8, 4, 2, 1

```

We first list all odd integers greater than 1 in ascending order. Then we list two times odd integers greater than 1, then 4 times, then 8 times, and so on: for all **k**, we list **2k** times the odd integers greater than 1 in ascending order. Finally, we list the powers of two in *descending* order, ending at 1. Every positive integer occurs in this "list" exactly once.

More explicitly, consider two distinct positive integers **A = n·2p** and **B = m·2q**, where **n, m ≥ 1** are odd, and **p, q ≥ 0**. Then **A** comes before **B** in the ordering, if one of the following conditions holds:

* **n \> 1**, **m \> 1** and **p \< q**
* **1 \< n \< m** and **p = q**
* **n \> m = 1**
* **n = m = 1** and **p \> q**

This ordering appears in the surprising mathematical result known as Sharkovskii's theorem, which concerns the periodic points of dynamical systems. I will not go into the details here.

## The task

Your task in this challenge is to compute the above ordering. Your inputs are two positive integers **A** and **B**, which may be equal. Your output is a truthy value if **A** comes before **B** in the ordering, and a falsy value otherwise. If **A = B**, your output should be truthy. You can take **A** and **B** in either order, as long as you're consistent.

You don't have to worry about integer overflow, but your algorithm should theoretically work for arbitrarily large inputs.

## Test cases

Truthy instances

```
3 11
9 6
48 112
49 112
158 158
36 24
14 28
144 32
32 32
32 8
3 1
1 1

```

Falsy instances

```
1 2
1 5
11 5
20 25
2 8
256 255
256 257
72 52
2176 1216
2176 2496

```

# Answer
## JavaScript (ES6), ~~53~~ 49 bytes

```
f=(a,b)=>b<2||a>1&&(a&b&1?a<=b:a&1|~b&f(a/2,b/2))

```

Explanation:

* If b is 1, then a precedes (or equals) b
* Otherwise, if a is 1, then a does not precede b
* Otherwise, if both a and b are odd, then use regular inequality check
* Otherwise, if a is odd, then it precedes b
* Otherwise, if b is odd, then a does not precede b
* Otherwise, divide both a and b by 2 and try again.

Edit: Saved 2 bytes thanks to @Arnauld.
> 7 votes

# Answer
# Python 2, 87 71 bytes

```
k=lambda n:[n&~-n<1,(n&-n)*cmp(n&~-n,1),n/(n&-n)]
lambda a,b:k(a)<=k(b)

```

This probably won't win any size awards, but this answer works by constructing a 3-tuple using 3 expressions from an integer that when lexicographically ordered will result in the correct ordering.

In readable terms, the tuple is for **A = n·2p**:

```
[n == 0, p * (1 - 2*(n == 0)), n]

```
> 6 votes

# Answer
## Python 2, 50 bytes

```
lambda*l:cmp(*[([-n][n&n-1:],n&-n,n)for n in l])<1

```

Each number is mapped to a triple whose sorted order is the desired order.

* The primary value is `[-n][n&n-1:]`, which handles the powers of 2 at the end. The bitwise "and" `n&n-1` is zero exactly when `n` is a power of `2`. If so, we get the list `[-n]`, and otherwise the empty list `[]`. This puts all powers of 2 at the end of the order, in decreasing order.
* The secondary value `n&-n` extracts the power-of-2 factor of `n`.
* The final value `n` tiebreaks equal powers of 2 in favor of the greater number.

The respective tuples are passed to `cmp` to see if that comparison is `<=0`. Python 3 would save a byte with float division `(n&n-1<1)/n` for the first value in the triple, but lacks `cmp`.
> 6 votes

# Answer
## JavaScript (ES6), ~~70~~ 64 bytes

Could probably be golfed some more, but as a first attempt:

```
x=>y=>(a=x&-x,x/=a,b=y&-y,y/=b,y<2?x>1|b<=a:x>1&(b>a|b==a&y>=x))

```

Takes input with currying syntax `(x)(y)`. Returns `0` / `1`.

### Test cases

```
let f =

x=>y=>(a=x&-x,x/=a,b=y&-y,y/=b,y<2?x>1|b<=a:x>1&(b>a|b==a&y>=x))

console.log('Testing truthy instances ...');
console.log(f(3)(11));
console.log(f(9)(6));
console.log(f(48)(112));
console.log(f(49)(112));
console.log(f(158)(158));
console.log(f(36)(24));
console.log(f(14)(28));
console.log(f(144)(32));
console.log(f(32)(32));
console.log(f(32)(8));
console.log(f(3)(1));
console.log(f(1)(1));

console.log('Testing falsy instances ...');
console.log(f(1)(2));
console.log(f(1)(5));
console.log(f(11)(5));
console.log(f(20)(25));
console.log(f(2)(8));
console.log(f(256)(255));
console.log(f(256)(257));
console.log(f(72)(52));
console.log(f(2176)(1216));
console.log(f(2176)(2496));
```
> 4 votes

# Answer
# Perl 6, ~~89~~ 84 bytes

~~```
->\a,\b{my \u=*>max a,b;a==first a|b,flat [1,2,4...u].&{(3*$_,5*$_...u for $_),.reverse}}

```~~
```
{my \u=*>@_.max;@_[0]==first @_.any,flat [1,2,4...u].&{.map(*X*(3,5...u)),.reverse}}

```

(Try it online.)

Not exactly short, but I thought it would be interesting to write a solution that actually generates the ordering sequence (up to a safe upper bound for each sub-sequence), and then checks which input appears in it first.

For example:

* For input `2, 3` it generates:

```
3 5
6
12
4 2 1
```
...and then observes that `3` appears before `2`.
* For input `9, 6` it generates:

```
3 5 7 9 11
6 10
12
24
48
16 8 4 2 1
```
...and then observes that `9` appears before `6`.

It could be smarter and generate even less of the sequence, but that would take more bytes of code.
> 3 votes

# Answer
# Python 2, 54 bytes

```
f=lambda a,b:b<2or[f(a/2,b/2),a>1,0,1<a<=b][a%2+b%2*2]

```

A recursive solution similar to Neil's.
> 2 votes

# Answer
# APL (Dyalog Extended), 27 bytes

```
1⊃∘⍋⍮⍥{p⍵⍮⍨-⍵⍴⍨⍵=2*p←⊥⍨~⊤⍵}

```

Try it online!

A tacit dyadic function whose left argument is `a` and the right is `b`.

The approach is almost identical to xnor's Python 2 solution, in that we convert each number to a nested array and do lexicographical comparison between them.

### Part 1: Convert number to nested array

```
{p⍵⍮⍨-⍵⍴⍨⍵=2*p←⊥⍨~⊤⍵}  ⍝ Input: positive integer N
                  ⊤⍵   ⍝ Convert N to binary digits
                 ~     ⍝ Flip all the bits (1 to 0, 0 to 1)
             p←⊥⍨      ⍝ Count trailing ones and assign it to p
                       ⍝ (maximum power of 2 that divides N)
         ⍵=2*          ⍝ Test if N itself is equal to 2^p
     -⍵⍴⍨              ⍝ If true, create 1-element array containing -N;
                       ⍝ otherwise, an empty array
 p⍵⍮⍨                  ⍝ Form a 2-element nested array;
                       ⍝ 1st element is the above, 2nd is [p, N]

```

### Part 2: Compare two nested arrays

```
1⊃∘⍋⍮⍥f  ⍝ Input: A (left) and B (right)
     ⍥f  ⍝ Evaluate f A and f B
    ⍮    ⍝ Create a 2-element nested array [f A, f B]
   ⍋     ⍝ Grade up; indexes of array elements to make it sorted
         ⍝ Here, the result is [0 1] if A ≤ B, [1 0] otherwise
1⊃∘      ⍝ Take the element at index 1 (0-based)

```

The dfn syntax does support conditional statements e.g. `{a:x ⋄ b:y ⋄ z}` meaning `if a then x else if b then y else z`, but it's way too verbose to use in this case.
> 2 votes

# Answer
# Mathematica, 65 bytes

```
OrderedQ[{1,#}&/@#//.{a_,b_/;EvenQ@b}->{2a,b/2}/.{a_,1}->{∞,-a}]&

```

Unnamed function taking a list of positive integers and returning `True` if the list forms an ascending sequence in the Sharkovskii order, `False` otherwise. (In particular, the input list doesn't have to have only two elements—we get the added functionality for free.)

The heart of the algorithm is the function `{1,#}&/@#//.{a_,b_/;EvenQ@b}->{2a,b/2}`, which repeatedly moves factors of 2 around to convert an integer of the form `m*2^k`, with `m` odd, to the ordered pair `{2^k,m}` (and does so to every element of the input list). `OrderedQ` then decides whether the resulting list of ordered pairs is already sorted; by default, that means in increasing order by the first element, then increasing order by the second element.

That's exactly what we want, except numbers that are powers of 2 follow different rules. So before checking in with `OrderingQ`, we apply one last rule `/.{a_,1}->{∞,-a}`, which converts (for example) `{64,1}` to `{∞,-64}`; that puts powers of 2 in the correct spot in the ordering.
> 1 votes

# Answer
# Haskell, ~~143~~ 138 bytes

Basically a relatively straightforward implementation of the criteria:

```
e n=head[k-1|k<-[0..],n`mod`(2^k)>0]   -- exponent of 2
f n=n`div`2^e n                        -- odd part
a#b|n<-f a,p<-e a,m<-f b,q<-e b=n>1&&(m>1&&p<q||n<m&&p==q||m<2)||n<2&&m<2&&p>q||a==b

```

Try it online!
> 0 votes

# Answer
# Python, ~~159~~ ~~158~~ ~~153~~ ~~144~~ ~~142~~ 141 bytes

*Saved ~~a~~ 2 bytes thanks to Kritixi Lithos!*

This is mainly just to practice golfing my Python!
Used the formula given by the OP rather than the ways of all the cleverer answers

```
f=lambda a,p=0:(a&1)*(a,p)or f(a>>1,p+1)
t=lambda(n,p),(m,q):(n==1)*(m==1)&(p>=q)or (m>1)&(p<=q)|(n<=m)&(p==q)or m==1
lambda a,b:t(f(a),f(b))

```
> 0 votes

# Answer
# 05AB1E, 14 bytes

```
ΣxÓs1ǝzDg≠i(]Q

```

Try it online! or validate all test cases.
> 0 votes

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


title: Convert from binary to negabinary

text:
# Question
Title: Convert from binary to negabinary
Given a binary integer inclusively between `0` and `1111111111111111` (i.e. a 16-bit unsigned integer) as input, output the same integer in negabinary.

The input can be in whatever format is most convenient for your language; for example, if it is easier for the program to handle input with 16 digits, like `0000000000000101`, rather than simply `101`, you can write the program to only accept input that way.

## Sample I/O

```
> 1
1
> 10
110
> 1010
11110
> 110111001111000
11011001110001000
> 1001001
1011001

```

Here is a sample program I wrote that does base conversions, including negative and non-integer bases. You can use it to check your work.

# Answer
> 6 votes
# APL, 21 characters

```
'01'[-(16/¯2)⊤-2⊥⍎¨⍞]

```

I used Dyalog APL for this, with `⎕IO` set to 0, allowing us to index arrays starting at 0 rather than 1.

Explanation, from right to left:

* gives us the user's input as a character vector.
* `⍎¨` applies the execute function () to each (`¨`) of the aforementioned characters, resulting in a vector of integer 1's and 0's.
* `2⊥` decodes the vector from base 2 into decimal.
* `-` negates the resulting decimal integer.
* `(16/¯2)⊤` encodes the decimal integer into base `¯2` (negative 2). (`16/¯2` replicates `¯2`, `16` times, yielding 16 digits in our negabinary number.)
* `-` negates each element of our newly encoded number (before this, it consists of -1's and 0's), so that we can use it to index our character vector.
* `'01'[ ... ]` indexes the character array (`'01'`) using the 0's and 1's of the negated negabinary vector. This is so we get a prettier output.

Example:

```
      '01'[-(16/¯2)⊤-2⊥⍎¨⍞]
10111010001
0001101011010001

```

# Answer
> 4 votes
# Ruby, 32 31 characters

```
m=43690
'%b'%(gets.to_i(2)+m^m)

```

Uses the negabinary calculation shortcut.

# Answer
> 3 votes
## GolfScript, 34 29 27 characters

```
n*~]2base{.2%\(-2/.}do;]-1%

```

A plain straigt-forward approach. It is quite interesting that the shortest version is the one which first converts to number and then back to base -2 (at least the shortest version I could find up to now). But the nice thing about this one is, that it contains almost 15% `%`.

*Edit 1:* For base 2 we can save one modulo operation and also join both loops.

*Edit 2:* I found an even shorter code to convert binary string to integer.

# Answer
> 3 votes
## Haskell, ~~86~~ 83 Bytes

```
import Data.Bits
import Data.Digits
c n|m<-0xAAAAAAAA=digits 2$xor(unDigits 2 n+m)m

```

Call using c and then an integer array for digits, e.g.

```
c [1,1]

```

PS: I'm new, did I submit this correctly?

EDIT: Saved some bytes thanks to Laikoni and also fixed some typos

EDIT2: Alternatively, c :: String -\> String:

```
import Data.Bits
import Data.Digits
c n|m<-0xAAAAAAAA=concatMap show.digits 2$xor(unDigits 2(map(read.(:[]))n)+m)m

```

For 114 bytes (but you call it with a string: c "11")

# Answer
> 2 votes
## Python (2.x), 77 characters

(not as short as the other solutions due to the need to manually switch base...) Should satisfy the requirements.

```
i=input();d=""
while i:i,r=i//-2,i%-2;i+=r<0;d+=`r+[0,2][r<0]`
print d[::-1]

```

Suggestions for further improvements are welcome!

Feed it with starting values like this: `0b1001001`

# Answer
> 2 votes
## JavaScript, 68 bytes

```
function(b){for(r='',n=parseInt(b,2);r=(n&1)+r,n>>=1;n=-n);return r}

```

Would be 52 bytes in ES6, but that post-dates the challenge:

```
b=>eval(`for(r='',n=0b${b};r=(n&1)+r,n>>=1;n=-n);r`)

```

# Answer
> 2 votes
# Jelly, 4 bytes, language postdates challenge

```
Ḅb-2

```

Try it online!

Takes input, and produces output, as a list of digits.

## Explanation

```
Ḅb-2
Ḅ     Convert binary to integer
 b-2  Convert integer to base -2

```

This is pretty much just a direct translation of the specification.

# Answer
> 1 votes
# k, 17 bytes noncompeting

Some of the features used probably postdate the challenge.

```
1_|2!{_.5+x%-2}\2/

```

Input is a list of 1's and 0's, and output is also a list of 1's and 0's.

# Answer
> 0 votes
# PHP, 69 Bytes

```
for($i=bindec($argn);$i;$i+=$i%2&$c,$i>>=1,$c^=1)$r=($i%2).$r;echo$r;

```

Online Version

# Answer
> 0 votes
# ES8, 54B

```
b=>eval`for(r='',n=0b${b};r=(n&1)+r,n>>=1;n=-n);r`

```

# Answer
> 0 votes
# Japt, 4 bytes

Input as a binary string, output as a negabinary digit array.

```
Íì2n

```

Try it

Or, taking input as a binary digit array:

```
ì2JÉ

```

Try it

# Answer
> 0 votes
# 05AB1E, 4 bytes

```
C2(в

```

Try it online!

---
Tags: code-golf, binary, base-conversion
---


title: How close are we, really?

text:
# Question
Title: How close are we, really?
# Please note: *this is a* * challenge — see details below!*

Each natural number \\$n\\$ has 10 *faces*: its decimal representations in bases \\$1\\$ through to \\$10\\$. For example, the 10 faces of \\$12\\$ are \\$\[111111111111, 1100, 110, 30, 22, 20, 15, 14, 13, 12\]\\$, and the 10 faces of \\$4\\$ are \\$\[1111, 100, 11, 10, 4, 4, 4, 4, 4, 4\]\\$

We can then say that two numbers *face* each other \\$n\\$ times if they share \\$n\\$ faces, counting duplicate faces repeatedly. For instance \\$12\\$ and \\$4\\$ do *not* share a face as no number is in both of their list of faces, whereas \\$6\\$ and \\$11\\$ do:

* \\$\text{faces}(6) = \[111111, 110, 20, 12, 11, 10, 6, 6, 6, 6\]\\$
* \\$\text{faces}(11) = \[11111111111, 1011, 102, 23, 21, 15, 14, 13, 12, 11\]\\$

Both \\$11\\$ and \\$12\\$ are in both lists, so \\$6\\$ and \\$11\\$ share 2 faces, and so face each other twice.

Finally, we will say that any pair of numbers has a *closeness*, which is defined as the number of times the two numbers face each other. So far we already have:

* \\$\text{closeness}(12, 4) = 0\\$
* \\$\text{closeness}(6, 11) = 2\\$

Notice that \\$\text{closeness}(1, 1)\\$ is \\$100\\$ because all 100 possible pairs of \\$1\\$'s faces are equal i.e. duplicate faces count multiple times.

Your task is, given two natural numbers \\$a\\$ and \\$b\\$, output \\$\text{closeness}(a, b)\\$. You may take input and output in any convenient method or format.

However, **your program must only consist of pairs of characters that face each other**. In order to determine if a pair of characters face each other, take their code points \\$(m, n)\\$ in whatever code page you are using to score your program, then, if \\$\text{closeness}(m, n) \ne 0\\$, then that pair of characters faces each other and can be in your program. This applies to all *overlapping* pairs in your program. So if your code is `abcd`, then `ab`, `bc` and `cd` must all be pairs that face each other.

You may use any *pre-existing* code page to score your answer, but it must have existed before this challenge was posted.

For instance, none of the pairs of letters in `print` (`pr`, `ri`, `in` and `nt`) face each other, so your code cannot contain any of those pairs of characters. However, all the pairs in `(p b>` (`(p`, `p` ,  `b` and `b>`) do face each other, so your code may contain them. Here is a newline-separated list of printable ASCII pairs that face each other for reference, this (Thanks to @Kevin Cruijssen) is a list of all pairs of integers between \\$0\\$ and \\$255\\$ which face each other, and this is a Jelly program which verifies that a given string complies with the rules, according to Unicode encoding. It does take 10-15 seconds to run, so be patient with it.

This is , so the shortest code in bytes wins

## Test cases

```
a, b => closeness(a, b)
24, 35 => 1
10, 15 => 0
50, 11 => 0
18, 12 => 3
16, 15 => 2
 1,  1 => 100
12, 10 => 5
30, 18 => 2
 6,  6 => 22
20,  4 => 0
 3, 35 => 0
23,  3 => 0

```

Here is a list of \\$\text{closeness}(a, b)\\$ for all pairs \\$\\{(a, b) \\:|\\: 1 \le a \le 50, 1 \le b \le 50\\}\\$, where the \\$n\\$-th element of the \\$m\\$-th row is the result for \\$\text{closeness}(m, n)\\$:

```
[100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 66, 2, 2, 2, 2, 2, 2, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 2, 52, 2, 2, 2, 3, 2, 2, 2, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]
[0, 2, 2, 40, 2, 2, 2, 2, 3, 2, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
[0, 2, 2, 2, 30, 3, 3, 3, 3, 4, 2, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 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, 0, 0, 0, 0, 1, 0, 0, 2, 0, 1, 0, 1, 0, 0, 2, 1, 0, 0, 0, 10, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 10, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 10, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 10, 0]
[0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 1, 0, 0, 2, 0, 2, 0, 0, 2, 0, 0, 0, 1, 2, 0, 0, 0, 0, 10]

```

# Answer
# Jelly, ~~37~~ 27 bytes

```
b ȷ2½RJÞ©¤µ€$ p /Aµ~E)UCCTL

```

Try it online!

A monadic link that takes a pair of integers as its argument and returns the closeness as an integer. When run as a full program implicitly prints the result.

Note encoding is using the Jelly codepage (available at Jelly); byte count and neighbouring pair closeness both reflect this.

This TIO link has a footer that breaks the program itself into overlapping pairs, converts each to the codepoints in the Jelly code page and then calls the code itself on each pair. The code section actually isn’t used; it actually evaluates the copy of the code seen in the argument.

A (possibly) minimal implementation of the closeness algorithm without the code restriction would be 9 bytes `bⱮ€⁵ŒpE€S`, so there’s effectively a 18 byte cost to ensuring all pairs are close.

Test using version of OP’s link

Verification of closeness of every pair between 1 and 30 using the data from the question (will print 1 if all match).

## Explanation

Code explained below. I’ve omitted the spaces since they are ignored here. I’ve indicated steps that are only there because of the code restriction in square brackets. Note many of these aren’t no-ops, but they do not change the final result.

```
           $              | [Following as a monad]
         µ€               | - For each integer in input:
b       ¤                 | - Convert to each of the following bases:
 ȷ2                       |   - 100
   ½                      |   - Square root
    R                     |   - Range
     JÞ©                  |   [- Sort by sequence along each list]
            p/            | Reduce using Cartesian product
              A           | [Absolute]
               µ          | Start a new monadic chain
                  )       | For each sublist:
                ~         | [- Bitwise not]
                 E        | - Check whether equal
                   U      | [Reverse]
                    C     | [1 minus this]
                     C    | [1 minus this]
                      T   | Convert to list of indices for each positive entry
                       L  | Length

```

Finally, here’s a handy TIO link to generate the pairs of integers 0-255 as well as characters in any codepage. The link as provided will give the pairs for Jelly, but you can change the argument for any other code page provided the characters exist in Unicode. They should be provided as a single string from 0 to 255. Example for 05AB1E, without the preceding integer bit (just characters).
> 11 votes

# Answer
# 05AB1E, ~~59~~ ~~52~~ ~~51~~ 43 bytes

```
εηθA~TLTBB™ÿćV9yΓиΓdJRzzªh}¯``ðð~V¢ 2
D//wO

```

Ok, that took a while.. Did it by trial-and-error, but I have the feeling that creating a brute-force program would have been more time-efficient now that I'm finally done.. But, it works!

-9 bytes thanks to *@Grimy*.

Uses the 05AB1E encoding; the characters map to these `0..255` values.

Try it online or verify all test cases or verify the program itself.

**Explanation:**

The base program I started with was 12 bytes, which was either `εTLBćy×š}`¢O` or `vyTLBćy×š}¢O`.

Here an explanation of the first base program (second is similar, but with a loop instead of map):

```
ε         # Map both values in the (implicit) input-pair to:
 TL       #  Push a list in the range [1,10]
   B      #  Convert the current value to each of these [1,10] bases
    ć     #  Extract head; pop and push remainder-list and first item separated to the stack
     y    #  Push the current value again
      ×   #  Repeat the "1" that many times
       š  #  And prepend it back to the list
}`        # After the map: push both lists separated to the stack
  ¢       # Count for each value in the second list how many times it occurs in the first list
   O      # And sum those counts together
          # (after which the result is output implicitly)

```

Note that the `ćy×š` is to fix the base-1 conversions, since in 05AB1E any number converted to base-1 would result in a single `1` instead of \\$n\\$ consecutive `1`s.

That was the easy part.. I then had to add no-ops to comply to the challenge rules.. I've first created a list of all unique pairs of the `0..255` values (since the one in the challenge description is incorrect I noticed..). And then used this helper program I created to get all characters in the 05AB1E encoding facing the character I've input in the header (you may want to collapse the Input section on TIO in this helper program).

As for the resulting program and how I (and *@Grimy*) have made the no-ops:

```
ε           # Map both numbers in the (implicit) input-pair to:
 η          #  Pop and push a list of prefixes of the number
 θ          #  Pop and push the last prefix (the number itself)
 A          #  Push the lowercase alphabet "abcdefghijklmnopqrstuvwxyz"
 ~          #  Bitwise-OR the number and alphabet (results in the number)
  T         #  Push 10
   L        #  Pop and push a list in the range [1,10]
    TB      #  Convert each to base-10 (they'll remain the same)
    B       #  Convert the current value to each of these [1,10] bases
      ™     #  Titlecase each number (does nothing on integers)
      ÿ     #  String interpolation (does nothing outside of a string)
      ć     #  Extract head; pop and push the remainder-list and first item separated to the stack
       V    #  Pop this 1, and save it in variable `Y`
       9    #  Push 9
       y    #  Push the current value
        Γ   #  Actual no-op; this character is unbound as any builtin
        и   #  Repeat the 9 the value amount of times as list
            #  (alternative for the `×`, since the builtins facing `×` were useless;
            #   this does mean I need an additional join `J` though)
         Γ  #  Actual unbound no-op again
         d  #  Check for each 9 if its non-negative; which is truthy, so they'll become 1s
         J  #  Join the list of 1s together to a string
          R #  Reverse this string of 1s (no change)
          z #  Take 1 divided by this number
          z #  And do it again so we're back at this number again
          ª #  Append it back to the list
          h #  Transform all values to hexadecimal (since we only care about equality,
            #  it doesn't matter the numbers are now hexadecimal strings
            #  - except for a weird bug where the string `"3E#"` equals `3`..)
}           # Close the map
 ¯          # Push the global array (empty by default)
 `          # Push its content (nothing) to the stack
 `          # Push the inner lists we just mapped separated to the stack
  ðð        # Push two space characters
  ~         # Bitwise-OR between the two space characters
  V         # Pop and store it in variable `Y`
  ¢         # Count for each value in the second list how many times it occurs in the first list
     2      # Push a 2
    \nD     # Duplicate this 2
    //      # Divide the 2 by 2, and then each count by 1 (so they remain the same)
    w       # Another unbound no-op
       O    # And sum all counts together
            # (after which the result is output implicitly)

```
> 9 votes

# Answer
# Jelly, 27 bytes

```
5+5ɓz2z2b ð€Z<Ƈp /*6EE¹?ƇTL

```

A full program accepting a pair of integers which prints the closeness integer.

**Try it online!**

Or see the 50 by 50 grid (takes ~30s when not cached)

For verification, the bytes used (in hexadecimal) are:

```
35 2B 35 9B 7A 32 7A 32 62 20 18 0C 5A 3C 90 70 20 2F 2A 36 45 45 81 3F 90 54 4C

```

...which, as a list of integers, is:

```
[53, 43, 53, 155, 122, 50, 122, 50, 98, 32, 24, 12, 90, 60, 144, 112, 32, 47, 42, 54, 69, 69, 129, 63, 144, 84, 76]

```

### How?

```
5+5ɓz2z2b ð€Z<Ƈp /*6EE¹?ƇTL - Main Link: list of (two) integers, [a, b]
5+5                         - five plus five -> ten
   ɓ      ð€                - for €ach n in [1..10] do f([a, b], n):
    z2                      -   transpose [a, b] with filler two -> [[a,b]]
      z2                    -   transpose that with filler two -> [[a],[b]]
        b                   -   convert that to base n (vectorises) [[[xs]],[[ys]]]
            Z               - transpose -> [[[xs],[ys]]]
              Ƈ             - filter keep if:
             <              -   less than [a, b] (always true so filter is a no-op)
                 /          - reduce by:
               p            -   Cartesian product (get all pairs of wrapped representations)
                  *6        - raise to the sixth power (vectorises)
                        Ƈ   - filter keep those for which:
                       ?    -   if...
                      ¹     -   ...condition: identity
                    E       -   ...then: all equal?
                     E      -   ...else: all equal?
                         T  - truthy indexes
                          L - length

```

---

Combining the start of Nick Kennedy's and the end of mine gives us a joint **26 byte** answer!:

```
b ȷ2½RJÞ©¤µ€$ p /*6EE¹?ƇTL

```

**Try it online!**
> 6 votes

# Answer
# Japt, 60 bytes

```
Ë5A $$ óKS{3N=DVNìN=KDV)q-2
DU=CgM=U)UxPÈ4C=Mg493)UCè¶r4 $$P

```

Try it

I used this program to find facing pairs. This program is Japt-specific, as it filters out characters Japt doesn't use. To use, enter any characters in the input section, and it will find all valid Japt characters that face them. To include control characters in the input, input `《number》` into the input section. To include control characters in the list of facing characters, prepend  before the character, like `。#`.

This challenge is made much more difficult by the fact that there are many characters in the ISO-8859-1 codepage (Japt's default) that are unused in Japt, and cause syntax errors if they are not part of a string. Additionally, since calls to functions must be closed with , `)`, or `¹`, many functions are off limits. The code only contains calls to 8 functions total.

Here is the equivalent Javascript code:

```
U = U.m(function(D, E, F) { return (D, 5, A ).ó(function(K, S) { return (3, N = D, V, N.ì(N = K, D, V)).q("-", 2) }) });
(D, U = C.g(M = U)), U.x(function(P, X, Y, Z) { return (X, 4, C = M.g(493)), U, C.è("===".r(4), P) })

```

As you can see, there are many assignments made to different variables, because very few variables face a function. The Cartesian product function (`ï`) is locked, since every character `ï` faces is an unprintable that results in a syntax error in Japt.

A thing to note is that when values are chained together not like `DU` or `5A`, only the value at the end is used, but only if the values are not arguments to a function. The values before are essentially no-ops.

```
Ë5A $$ óKS{3N=DVNìN=KDV)q-2
Ë                                //Map each variable D in the input
 5A                              //A is the variable for 10
  \t$$                           //Tab (a no-op) followed by $$, followed by a single space
                                 //Everything between 2 dollar signs is
                                 //injected into the transpiled JavaScript
                                 //literally. In this case, we inject nothing
                                 //Space is not a no-op in Japt, it acts like parentheses
      ó                          //Range, 0-9
                                 //Map each in the range through the following function
       KS{                       //An "old-style" function, taking in parameters K and S
                                 //K = current #, S = index (ignored)
                                 //Obsolete nowadays, replaced by '@','_','È',and 'Ï'
           3N=D                  //Assign N to D
               V                 //No-op variable
                NìN=KDV          //Convert N to base K array, the last two variables are
                                 //ignored in the function call. Luckily, if 0
                                 //is passed as the base, it returns base-10 digits
                                 //Though 's' is much more handy as it returns a string,
                                 //It only accepts bases 2-36
                         )q-2    //Join the base-K array with '-' (2 is a no-op)
                                 //Newline - assign the result of the previous to U
DU=CgM=U)UxPÈ4C=Mg493)UCè¶r4 $$P
   C                             //12
    g                            //Index into (wrapping)
     M=U)                        //U, essentially getting first element, also assign U to M
DU=                              //Assign that to U

         Ux                      //Map everything in U to the following function, then sum
           PÈ                    //Function w/ parameters 'P','X','Y','Z'
             4C=Mg493)           //Assign C to M[1] (indices are wrapping)
                         ¶r4     //Replace all "4" strings in "===" with ""
                      UCè    $$P //No. of elements in C that "===" (equals) P

```
> 6 votes

---
Tags: code-golf, math, restricted-source, base-conversion
---


title: Blackjack Bust Calculator

text:
# Question
Title: Blackjack Bust Calculator
Blackjack, also known as twenty-one, is a comparing card game between yourself and a dealer, where each player in turn competes against the dealer, but players do not play against each other.

Play goes as follows, the dealer deals you a card. The dealer then deals them-self a card, face down. The dealer then deals you another card. Then finally, the dealer deals them-self a card, face-up.

# Challenge

Your challenge is to write a program (or function) that when run (or called), outputs (or returns) the probability that the next card the dealer gives you will make you bust, which means the cumulative score of cards in your hand after the dealer gives you another card is over 21.

# Input

The three visible cards in play. They are the two cards you have in your hand, and the one face card you can see in the dealers hand. This can be in whatever format you find suitable for your application.

There are 52 cards in a deck(4 of each of the cards below). The value of the cards are as follows:

```
Symbol(Case Insensitive)  Name     Value
2                         Two      2
3                         Three    3
4                         Four     4
5                         Five     5
6                         Six      6
7                         Seven    7
8                         Eight    8
9                         Nine     9
T                         Ten      10
J                         Jack     10
Q                         Queen    10
K                         King     10
A or 1                    Ace      1

```

*In Blackjack, an ace can count as 1 or 11. In our challenge, only count it as a 1*

# Output

The probability, in a ratio or percentage format, that the next card we draw will make us bust.

You may output the percentage, the fraction, or just the numerator of the fraction.

# Examples

*In this example, the first two cards are in our hand, the third card is the dealers visible card*

```
 Input          ->       Output

 A 2 Q          ->       0.00%  or  0/49 or 0
 A 2 3          ->       0.00%  or  0/49 or 0
 T T T          ->       91.84% or 45/49 or 91.84
 T J K          ->       91.84% or 45/49 or 45
 9 7 3          ->       61.22% or 30/49 ...
 9 7 Q          ->       59.18% or 29/49 ...

```

# Rules

Standard loopholes are not allowed.

This is , so the shortest code in bytes for each language wins!

# Answer
> 8 votes
# Jelly,  ~~26~~  24 bytes

```
O%48«⁵µ13R«⁵ẋ4œ-+ṖS$>21S

```

A monadic link accepting a list of characters (using either the lower-case option OR the upper-case option with `1` for `A`) which returns the numerator (the number of 49ths) in `[0,49]`.

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

### How?

Note that by using lower-case the minimum of **10** and the ordinals modulo by **48** gives the card values. The same holds for upper-case `T`, `J`, `Q`, `K` and `1` for an ace, as shown on the right (but an upper-case `A` does not work):

```
     card:   a   2   3   4   5   6   7   8   9   t   j   q   k   |   1   T   J   Q   K
  ordinal:  97  50  51  52  53  54  55  56  57 116 106 113 107   |  49  84  74  81  75
   mod 48:   1   2   3   4   5   6   7   8   9  20  10  17  11   |   1  36  26  33  27
min(_,10):   1   2   3   4   5   6   7   8   9  10  10  10  10   |   1  10  10  10  10

```

```
O%48«⁵µ13R«⁵ẋ4œ-+ṖS$>21S - Link: list of characters   e.g. "q3a"
O                        - ordinals (of the input list)    [113, 51, 97]
 %48                     - modulo by 48                    [17,3,1]
     ⁵                   - ten
    «                    - minimum                         [10,3,1]
      µ                  - start a new monadic chain
       13R               - range of 13                     [1,2,3,4,5,6,7,8,9,10,11,12,13]
           ⁵             - ten                             10
          «              - minimum                         [1,2,3,4,5,6,7,8,9,10,10,10,10]
            ẋ4           - repeat four times               [1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10]
              œ-         - multi-set difference            [1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10,1,2,3,4,5,6,7,8,9,10,10,10,10  ,2  ,4,5,6,7,8,9   ,10,10,10]
                   $     - last two links as a monad:
                 Ṗ       -   pop                           [10,3]
                  S      -   sum                           13
                +        - add (vectorises)                [14,15,16,17,18,19,20,21,22,23,23,23,23,14,15,16,17,18,19,20,21,22,23,23,23,23,14,15,16,17,18,19,20,21,22,23,23,23,23,15,17,18,19,20,21,22,23,23,23]
                    >21  - greater than 21?                [0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,0,0,0,1,1,1,1]
                       S - sum                             19

```

# Answer
> 4 votes
# JavaScript (ES6), ~~73~~ 62 bytes

Takes input as an array of 3 characters with `1` for aces. Returns the integer **X** representing the probability **X/49** to be busted.

```
a=>([b,c]=a.map(v=>v*4||40)).map(n=>b-=n+b>52,b+=c-32)|b>12&&b

```

Try it online!

### Exhaustive test

The golfed formula is not very intuitive. So, the easiest way to prove its consistency is probably to just compare all possible outputs against the ones provided by a basic ungolfed implementation:

```
g = a => {
  deck = [...'123456789TJQK'.repeat(4)];
  a.forEach(card => deck.splice(deck.indexOf(card), 1));

  return deck.filter(card =>
    (+a[0] || 10) +
    (+a[1] || 10) +
    (+card || 10) > 21
  ).length;
}

```

Try it online!

# Answer
> 2 votes
# Pyth, 35 bytes

```
Jm?}dGTsdQclf>T-21sPJ.-*4+ST*3]TJ49

```

Takes input as a list of characters (or as a string).
Try it here

### Explanation

```
Jm?}dGTsdQclf>T-21sPJ.-*4+ST*3]TJ49
Jm?}dGTsdQ                            Convert each input to the appropriate number.
                     .-*4+ST*3]TJ     Remove each from the deck.
           lf>T-21sPJ                 Count how many remaining cards bust.
          c                      49   Get the probability.

```

# Answer
> 1 votes
# Perl 5, 115 bytes

```
map{//;$k{$_}=4-grep$' eq$_,@F}1..9,T,J,Q,K;map{s/\D/10/}@F;$_=grep{$F[0]+$F[1]+$_>21}map{(s/\D/10/r)x$k{$_}}keys%k

```

Try it online!

# Answer
> 1 votes
# Python 2, ~~97~~ 96 bytes

```
def f(s):C=[min(int(c,36),10)for c in s];D=C[0]+C[1];return(4*D-35+sum(v+D<22for v in C))*(D>11)

```

Try it online!

Takes a 3-character string as input, with '1' being used as Ace. Returns the numerator.

# Answer
> 1 votes
# Java 8, 109 bytes

```
a->{int r=3;for(;r-->0;a[r]=a[r]<59?a[r]*4-192:40);r=a[0]+a[1]-32;for(int v:a)r-=v+r>52?1:0;return r>12?r:0;}

```

Port of *@Arnauld*'s JavaScript (ES6) answer.
Input as character-array with three values, Aces as `'1'`; output is the probability `p` in `p/49`.

Try it online.

**Explanation:**

```
a->{                   // Method with integer-array as parameter and integer return-type
  int r=3;for(;r-->0;  //  Loop over the array
    a[r]=a[r]<59?      //   If the current item is a digit:
          a[r]*4-192   //    Multiply it by 4
         :             //   Else:
          40);         //    Change it to 40
  r=a[0]+a[1]-32;      //  Set `r` to the first value, plus the second value, minus 32
  for(int v:a)         //  Loop over the now modified array again
    r-=v+r>52?         //   If the current value plus `r` is larger than 52
        1              //    Decrease the result-integer by 1
       :0;             //   Else: Leave the result-integer the same
  return r>12?         //  If the result-integer is larger than 12
          r            //   Return the result-integer
         :             //  Else:
          0;}          //   Return 0

```

# Answer
> 1 votes
# 05AB1E, 46 bytes

```
Y9ŸJ.•§®т•«Á4×©sð.;#S|UεX‚˜ε®sk>T‚W}O21›}DOsg/

```

Try it online!

This can be done better, working on it.

# Answer
> 1 votes
# 05AB1E, ~~23~~ ~~22~~ 21 bytes

```
AST:4-D¨OÐ4@*4*Š+T@O-

```

Try it online!

```
AST:                   # replace all letters in the input with 10
    4-                 # subtract 4 from each card value
      D                # duplicate
       ¨               # drop the last element
        O              # sum (hand value of the player - 8)
         Ð             # triplicate that
          4@*          # set to 0 if it's less than 4
             4*        # multiply by 4
               Š       # 3-way swap
                +      # add the player's hand value to each card value
                 T@O   # count how many are >= 10
                    -  # subtract

```

---
Tags: code-golf, card-games
---


title: An "Iniative" game mechanic

text:
# Question
Title: An "Iniative" game mechanic
This challenge is inspired by turn based videogames like "Heroes of Might and Magic"

---

## Implement this game mechanic:

* There is some units(Imps, Swordsmans etc...) in our game
* Every unit have an integer "initiative"
* Your program must decide which unit's turn now - based on unit's initiative
* The more initiative means more frequent turns(for example unit with 10 iniative will move 5 times more often than 2 iniative unit)
* Unit with highest initiative moves first
* Input: Array of pairs of \[unit\_name: string, unit\_initiative: integer\]
* Output: Unit names in moving sequence separated by line break (\n)
* Make 50 turns total

---

## Test case:

Units: \[\["Imp", 500\], \["Mammoth", 50\], \["Swordsman", 250\], \["Elf", 350\]\]

turn sequence(50 turns) output:

```
Imp
Elf
Imp
Swordsman
Elf
Imp
Imp
Swordsman
Elf
Imp
Elf
Imp
Swordsman
Imp
Elf
Imp
Swordsman
Elf
Imp
Elf
Imp
Swordsman
Mammoth
Imp
Elf
Imp
Swordsman
Elf
Imp
Imp
Swordsman
Elf
Imp
Elf
Imp
Swordsman
Imp
Elf
Imp
Swordsman
Elf
Imp
Elf
Imp
Swordsman
Mammoth
Imp
Elf
Imp
Swordsman

```

## Other rules:

* Use your favorite language
* Write shortest code possible
* Attach a link to an online iterpreter
* Please follow standard code golf rules

# Answer
> 1 votes
# Jelly, ~~20~~ 15 bytes

```
P:ṭ×¥Ɱ"Ɗ,€"ẎṢṪ€

```

Try it online!

A dyadic link taking a list of initiative scores as its left argument and a list of characters as its right and returning a list of the characters in movement order.

# Jelly, 14 bytes

```
İṭ×¥Ɱ"$,€"ẎṢṪ€

```

Try it online!

This version is one bytes shorter but I expect may sometimes get the order wrong because of inaccuracies in floating point calculations.

---
Tags: code-golf, game
---


# Question
Title: What is a short code for generating this matrix in R?
I can see that it is 101 'moving to the right' but I cannot think of a short way to generate it in R language.

\\$\begin{bmatrix} 0 & 1 & 0 & 0 & 0 & 0 \\ 1 & 0 & 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 & 0 & 1 \\ 0 & 0 & 0 & 0 & 1 & 0 \\ \end{bmatrix}\\$

# Answer
> 7 votes
# , ~~24~~ ~~23~~ ~~22~~ 20 bytes

```
diag(0,6)+c(!-1:4,1)

```

Try it online!

Just use R's recycling! This does give a warning, but otherwise is fine.

Thanks to Robin Ryder for the 2 byte golf.

# Answer
> 5 votes
# , ~~30~~ 27 bytes

```
+!abs(outer(1:6,1:6,`-`))-1

```

Try it online!

Another alternative. Note this matrix shows which integers between 1 and 6 are exactly 1 apart. (i.e. \\$|i - j| = 1\\$).

Thanks to @RobinRyder for saving a byte! I was forgetting `+` could be used as a unary operator. Thanks also to @Giuseppe for saving 2 bytes!

If a matrix of logical values is permissible, then this also works:

# , 26 bytes

```
abs(outer(1:6,1:6,`-`))==1

```

Try it online!

This is also the closest to my shortest Jelly solution to this:

# Jelly, 5 bytes

```
6ạþ=1

```

Try it online!

# Answer
> 4 votes
# , 34 bytes

```
x=cbind(rbind(0,diag(5)),0)
x+t(x)

```

Try it online!

Outputs

```
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    1    0    0    0    0
[2,]    1    0    1    0    0    0
[3,]    0    1    0    1    0    0
[4,]    0    0    1    0    1    0
[5,]    0    0    0    1    0    1
[6,]    0    0    0    0    1    0

```

Builds a \\$5\times5\\$ diagonal matrix, pads with 0s at the top and the right, and adds it to its own transpose.

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


title: Draw the € sign

text:
# Question
Title: Draw the € sign
The goal is to output or display an image with an € (euro) sign according to the following specs (ignoring the border of the sign).

Source: http://en.wikipedia.org/wiki/File:Euro\_Construction.svg

Rules:

* The program / script must take the height of the  sign in pixels as an argument (empty space around the sign is optional)
* The  sign can't be drawn as or from a character, directly (it's forbidden to `print` the  in the image) or indirectly (calculating `8364` then displaying it in a HTML page)
* The output does not need to be saved to any file, it can be displayed then just shown as a screenshot
* Standard “loopholes” are forbidden
* Shortest code wins

# Answer
> 25 votes
# PostScript/GhostScript, 100

(96 for the program, 4 for the command-line switch prefix)

Fully golfed and hand-tokenized:

```
$ hexdump -C euro.ps
00000000  68 20 88 78 92 36 92 38  92 8b 88 4b 88 3c 92 ad  |h .x.6.8...K.<..|
00000010  88 00 88 00 88 3c 88 2d  88 ce 92 05 88 00 88 00  |.....<.-........|
00000020  88 32 88 d8 88 28 92 06  92 16 88 b9 88 fb 92 6b  |.2...(.........k|
00000030  88 b5 88 f1 92 63 88 13  88 f1 92 63 88 17 88 fb  |.....c.....c....|
00000040  92 63 92 16 88 b9 88 0f  92 6b 88 b5 88 05 92 63  |.c.......k.....c|
00000050  88 1b 88 05 92 63 88 1f  88 0f 92 63 92 16 92 42  |.....c.....c...B|
00000060

```

You can get a copy here, for your own viewing.

After seeing @ThomasW's answer, and considering my program carefully, I realized that I could do it even better.

The tokenized version is equivalent to this:

```
h 120 div dup scale
75 60 translate

0 0 60 45 -50 arc
0 0 50 -40 40 arcn
closepath

-71 -5 moveto
-75 -15 lineto
19 -15 lineto
23 -5 lineto
closepath

-71 15 moveto
-75 5 lineto
27 5 lineto
31 15 lineto
closepath

fill

```

An explanation of the optimizations:

First off, I converted my first solution into a union of some simpler subpaths, rather than one path circumscribing the entire thing. I borrowed Thomas's method of inputting a parameter, which is much better than what I had had.

Then I multiplied all the coordinates by 10 and rounded everything off to give me just integer coordinates. I also rounded off the angles, and converted the two large ones to equivalent negative angles. This conveniently makes every single number fall between -128 and 127.

And then I tokenized *everything*. Each operator can be represented with a two-byte sequence each. And because each number can be represented by a single signed byte, each one *also* becomes only two bytes. The only part I couldn't do that with was the `h` at the start, but it too is only two bytes, just the `h` and a space after it.

Run it as:

```
gs -dh=200 euro.ps

```

```
gs -dh=80 euro.ps

```

```
gs -dh=20 euro.ps

```

---

## New: Even shorter versions!

Using encoded user paths, I have managed to reduce the program size by a few bytes. Each of these programs is equivalent to the first one, producing identical output:

92 bytes:

```
hexdump -C euro.ps
00000000  68 20 88 78 92 36 92 38  92 8b 88 4b 88 3c 92 ad  |h .x.6.8...K.<..|
00000010  7b 7b 88 b5 88 c4 88 2d  88 3c 30 20 30 88 3c 88  |{{.....-.<0 0.<.|
00000020  2d 88 cf 30 20 30 88 32  88 d8 88 28 88 b9 88 fb  |-..0 0.2...(....|
00000030  88 b5 88 f1 88 13 88 f1  88 17 88 fb 88 b9 88 0f  |................|
00000040  88 b5 35 88 1b 35 88 1f  88 0f 7d 8e 0b 00 07 08  |..5..5....}.....|
00000050  0a 01 23 03 0a 01 23 03  0a 7d 92 b3              |..#...#..}..|
0000005c

```

Which is equivalent to:

```
h 120 div dup scale
75 60 translate
{
 {-75 -60 45 60
  0 0 60 45 -50
  0 0 50 -40 40
  -71 -5
  -75 -15
  19 -15
  23 -5
  -71 15
  -75 5
  27 5
  31 15}
  <00 07 08 0A 01 03 03 03 0A 01 03 03 03 0A>
} ufill

```

And a slightly counterintuitive confusing solution saves one more character, for only 91:

```
$ hexdump -C euro.ps
00000000  68 20 88 78 92 36 92 38  92 8b 88 4b 88 3c 92 ad  |h .x.6.8...K.<..|
00000010  5b 5b 8e 1e b5 c4 2d 3c  00 00 3c 2d ce 00 00 32  |[[....-<..<-...2|
00000020  d8 28 b9 fb b5 f1 13 f1  17 fb b9 0f b5 05 1b 05  |.(..............|
00000030  1f 0f 7b 92 38 88 7f 92  50 7b 32 35 36 92 a9 7d  |..{.8...P{256..}|
00000040  92 54 7d 92 49 5d 92 32  8e 0b 00 07 08 0a 01 23  |.T}.I].2.......#|
00000050  03 0a 01 23 03 0a 5d 92  32 92 b3                 |...#..].2..|
0000005b

```

Which is equivalent to:

```
h 120 div dup scale
75 60 translate
[
  [
   <b5 c4 2d 3c
    00 00 3c 2d ce
    00 00 32 d8 28
    b9 fb
    b5 f1
    13 f1
    17 fb
    b9 0f
    b5 05
    1b 05
    1f 0f> {dup 127 gt {256 sub} if} forall
  ] cvx
  <00 07 08 0A 01 23 03 0A 01 23 03 0A>
] cvx
ufill

```

# Answer
> 50 votes
## Mathematica, ~~193~~ ~~183~~ ~~177~~ ~~173~~ ~~169~~ 166 bytes

Yay, maths! I'm plotting the region that satisfies a certain (rather complicated) set of inequalities:

```
e=RegionPlot[(1<Abs@y<3||c)&&{x,y+12}.(d=2{-5Sin@40°-6,m=5Cos@40°})*{x+15,y+1-2Sign@y}.d<0||c&&x<2m/.c->100<x^2+y^2<144,{x,-15,9},{y,-12,12},Frame->0>1,ImageSize->#]&

```

Usage is `e[height]`, e.g. `e[100]`:

Or `e[200]`:

You may notice, that the sharper edges are slightly rounded off. That's because the region can only be plotted by sampling the points in space, and Mathematica doesn't sample each pixel by default. The sampling resolution can be increased by adding another option `PlotPoints->#` (which uses one sample per pixel), which adds **14 characters**. I don't recommend running it with that option, because it significantly increases runtime and barely increases visual appeal beyond `#/4` or so. Hence, (after approval of the OP) it is not included in the score.

Here is a slightly ungolfed version:

```
e[height_] := (
  angle = 40°;
  d = {-5 Sin[angle] - 6, 5 Cos[angle]};
  RegionPlot[
      (Abs[y] > .5 && Abs[y] < 1.5
        ||
       r > 25 && r < 36)
    &&
      {x, y + 6}.d > 0
    &&
      {x + 7.5, y + .5 - Sign[y]}.d < 0
    ||
      r > 25 && r < 36 && x < 5 Cos[angle]
    /. r -> x^2 + y^2
    ,
    {x, -7.5, 4.5},
    {y, -6, 6},
    Frame -> False,
    ImageSize -> height
  ]
);

```

Note that in the golfed version, I've scaled the coordinate system by a factor of 2 to avoid the `.5`s, but it turns out that the character count is actually identical.

Here is an explanation for how I worked out the formula. I divided the shape into two regions. One contains the ring and the stripes and is cut off to the right with the `BCDE` slope and to the left with the `IJ` and `GH` slopes (more on that later). The other contains the same ring, but is simply cut off at the *x* coordinate of point `D`. The conditions for the two regions are combined with `||`, which acts as a set union here.

The ring is just defined as `5 < r < 6`, where `r` is the distance from the origin.  is easier to work out though (`x²+y²`), so I'm using `25 < x² + y² < 36` to get all the points in the ring.

The stripes are between `±.5` and `±1.5`. We can handle both stripes at the same time, by taking the modulus of *y*, so the stripes (of infinite length) just fulfil `.5 < |y| < 1.5`. Again, to take the union of the stripes and the ring, I'm just using `||`.

The interesting thing is probably how to get the "masks" though. Point `D` has an *x* coordinate of `5 cos 40°`, so the mask taking care of lower edge (combined with the ring only) is just `x < 5 cos 40°`. This can be applied via set intersection which translates to `&&` in logic.

The other masks are the really tricky part. First, let's get the slope of `BCDE`. We can easily construct points `C` and `D`, as `(0, -6)` and `5 (cos 40°, sin 40°)`, respectively. The vector pointing along the line is then just `D - C = (5 cos 40°, 5 sin 40° + 6)`. To apply the mask on the right, I only need to figure out if a point lies to the left or the right of that line (let's call line vector `p`). I can figure this out by taking the vector from `C` to my point of interest and projecting it onto a vector *perpendicular* to `p`. The sign of the projection will tell me the side the point is on. Obtaining the perpendicular vector is pretty simple in 2D: flip the coordinates and reverse the sign of one of them. That's the variable `d` in my code: `(-5 sin 40° - 6, 5 cos 40°)`. The vector from `C` to a point of interest `q = (x, y)` is `q - C = (x, y + 6)`. The projection is just the scalar product (or dot product) between `q` and `d`. The way I chose `d` it happens to point to the left, so I want `d.(q-C) > 0`. This condition applies the right-hand mask.

For the left-hand mask I can use basically the same idea. The slope is the same and therefore so is `d`. I just need offset my point from the lower-left corners of stripes instead of from `C`. Those have coordinates `(-7.5, 0.5)` (upper stripe) and `(-7.5, -1.5)` (lower stripe). So that would call for two independent rules for the two stripes. However, note that all points affected by the lower mask are in the lower stripe and hence have negative *y*. And all points affected by the upper mask have positive *y*. So I can simply switch my offset using `Sign[y]` which is `1` for positive and `-1` for negative `y`. So my offset point becomes `(-7.5, -0.5 + Sign[y])`. Otherwise the mask works just like the right-hand mask. Of course, this time the projection needs to be negative. So, naively that would be something like `RH-projection > 0 && LH-projection < 0` (which is also what I originally had in the code). But we can shorten this, because multiplying a positive and a negative number has to give a negative number, so it's just `RH * LH < 0` (where `RH` and `LH` are the respective projections).

That's it. Putting it all together leads to the following logical structure:

```
(
  (is_in_circle || is_in_stripe)
  &&
  is_between_left_and_right_mask
)
||
(
  is_in_circle && left_of_edge
)

```

Just to be clear, the coordinates in my explanation refer to the construction diagram given in the challenge. As mentioned above my code actually multiplies all of them by `2` \- I changed it to save bytes, but the byte count is actually identical, and I couldn't be bothered to revert the change again. Also integers look nicer.

# Answer
> 29 votes
# BBC BASIC, 202

```
INPUTh:w=h/12s=w/2.4p=25VDU22,6,29,640;400;p,4,0;1.5*w;p,153,6*w;0;p,4,0;1.5*w;p,159,h/3.1;4.7*w;p;9*s;9*w;p,87,h/3.1;-19*w;p,4,-7.5*w;0;p;s;w;p,85,4.5*s;0;p,81,s;w;p;s;w;p;s;w;p,85,-7.5*w;2*w;p,81,s;w;

```

download emulator at http://www.bbcbasic.co.uk/bbcwin/bbcwin.html

**In BBC basic, all graphics are handled at the low level using machine-specific ASCII control characters** (but some high level commands are also available for the common ones for convenience.) The ones used here are 22 (change display mode) 29(change origin) and 25, equivalent to the PLOT statement, which takes an additional action parameter (draw line, circle, triangle, etc. in background/foreground with relative/absolute move) before the X and Y parameters.

**So all I have to do is send a load of characters to the VDU controller.** values terminated in semicolon are 16 bit. others are 8 bit. **The total number of bytes sent to the VDU controller is 91**, though that in itself would not qualify as an answer because by that stage the size is hardcoded.

The obvious place for the origin is the centre of the circle, but there are actually more commands involved in producing the bars. So I shifted the origin down 1.5 to the bottom of the lower bar, which reduces the number of fractions and negative numbers required. It remains on the vertical line with the centre of the circle, which is important because the line E starts from this vertical line.

Actually, I only had to calculate 3 numbers off the drawing: the top inner corner of the C shape (5 cos 40, 5 sin 40 + 1.5) = (3.8302,3.1394+1.5) = approx (12/3.1, 4.6) and the gradient of the line E:x/y=3.8302/(6+3.1394)=0.4157 = approx 1/2.4

As I only have the free evaluation version (interpreted), I take the symbol height as user input. If you buy the full version (29.99GBP) you can compile and then read the command line with `w=VAL(@cmd$)/12`.

**Ungolfed code**

In the golfed code, there is only one VDU statement, but in the ungolfed code I break it down into several for clarity. Also, because BBC basic is little endian, the combination `p,0,` can be golfed to `p;` but I left it ungolfed for clarity.

```
  INPUT h
  w=h/12                   :REM w is the width of the line, which is 1/12 the height of the symbol, hardcoded at 900.
  s=w/2.4                  :REM s/w is the gradient x/y of line E. s is the horizontal offset of the top and bottom of the ends of horizontal bars
  p=25                     :REM VDU p,action,x;y; is the equivalent of PLOT action,x,y

  VDU 22,6                 :REM change mode
  VDU 29,640;400;          :REM set origin

  VDU p,4,0;1.5*w;         :REM move to centre of circle
  VDU p,153,6*w;0;         :REM draw circle in foreground colour
  VDU p,4,0;1.5*w;         :REM move to centre of circle
  VDU p,159,h/3.1;4.6*w;   :REM draw circle in background colour, ending at the upper inner point of the C shape.
  VDU p,0,9*s;9*w;         :REM move relative along slant gradient, 9 spaces in y direction, to define the upper cut on the circle
  VDU p,87,h/3.1;-19*w;    :REM draw triangle in background colour, based on the last two points and the absolute point specified here (vertical line for lower cut)

  VDU p,4,-7.5*w;0;        :REM move absolute to bottom left of lower bar
  VDU p,0,s;w;             :REM move relative to top left of lower bar
  VDU p,85,4.5*s;0;        :REM draw triangle to bottom right corner of lower bar (absolute)
  VDU p,81,s;w;            :REM draw triangle to top right of lower bar (relative)

  VDU p,0,s;w;             :REM move relative to bottom right of upper bar
  VDU p,0,s;w;             :REM move relative to top right of upper bar
  VDU p,85,-7.5*w;2*w;     :REM draw triangle to bottom left of upper bar (absolute)
  VDU p,81,s;w;            :REM draw triangle to top left of upper bar (relative)

```

# Answer
> 25 votes
# HTML, ~~250~~ ~~249~~ ~~248~~ ~~242~~ ~~244~~ ~~234~~ 229

```
<svg viewBox=-7.5,-6,12,12
onload=this.style.height=prompt()><clipPath
id=c><path
d=M5-6,1.8,1.5,3.8,3.2V6H-9.4L-7.1,.5-7.5-.5-5.2-6>
</clipPath><g
clip-path=url(#c) fill=none stroke=#000><circle
r=5.5 /><path
d=M-8,1h15M-8-1h15>

```

While this is only using SVG stuff, it heavily relies on lax HTML parsing and has to be served as HTML. Strict SVG would require a lot more bytes.

Try it!

# Answer
> 17 votes
## CSS, ~~512~~ 494 bytes

```
<style>*,:after,:before{position:absolute;width:20;content:"";background:#fff}#a{margin:150;height:20;border:2px solid;border-radius:20px}#a:after{width:10;height:10;bottom:0;right:-8}p{top:7;left:-6;width:29;height:2;border:solid;border-width:2 0;transform:skewX(-23deg);margin:0;background:0}p:before{width:2;height:4;bottom:-3;left:-.5}p:after{width:16;height:16;bottom:-3;right:-8}</style><div id=a><p><script>document.getElementById('a').style.transform='scale('+(prompt()/24)+')'</script>

```

Not the smallest answer by a fair bit, but as small as I could get even when summoning all my css-minification-fu

## Caveats:

The above code with all 'px' stripped works in Firefox & IE but not Chrome & Safari which are fussier about their units :)

I also had to re-add the px's to get the jsfiddle to work:

http://jsfiddle.net/9A3J9/

100:

200:

## ungolfed code:

```
 <style>
*,:after,:before{
    position:absolute;
    width:20;
    content:"";
    background:#fff
}
#a{
    margin:150;
    height:20;
    border:2px solid;
    border-radius:20px
}
#a:after{
    width:10;
    height:10;
    bottom:0;
    right:-8
}
p{
    top:7;
    left:-6;
    width:29;
    height:2;
    border:solid;
    border-width:2 0;
    transform:skewX(-23deg);
    margin:0;
    background:0
}
p:before{
    width:2;
    height:4;
    bottom:-3;
    left:-.5
}
p:after{
    width:16;
    height:16;
    bottom:-3;
    right:-8
}
</style>

<div id=a><p>

<script>
document.getElementById('a').style.transform='scale('+(prompt()/24)+')'
</script>

```

# Answer
> 16 votes
# PostScript+Ghostscript 137 + 6 = 143 (binary), 209 + 6 = 215 bytes

Fully golfed version with binary tokens:

```
$ hexdump -C euro_golfed.ps
00000000  68 20 31 32 20 92 36 92  38 92 8b 37 2e 35 20 36  |h 12 .6.8..7.5 6|
00000010  92 ad 35 20 36 0a 31 2e  38 20 2d 31 2e 35 0a 33  |..5 6.1.8 -1.5.3|
00000020  2e 38 20 2d 33 2e 32 0a  33 2e 38 20 2d 36 0a 2d  |.8 -3.2.3.8 -6.-|
00000030  39 2e 34 20 2d 36 0a 2d  37 2e 31 20 2d 2e 35 0a  |9.4 -6.-7.1 -.5.|
00000040  2d 37 2e 35 20 2e 35 0a  2d 35 2e 32 20 36 92 6b  |-7.5 .5.-5.2 6.k|
00000050  37 7b 92 63 7d 92 83 35  2e 35 92 14 30 92 6f 2d  |7{.c}..5.5..0.o-|
00000060  38 20 2d 31 0a 2d 38 20  31 92 6b 32 7b 31 35 20  |8 -1.-8 1.k2{15 |
00000070  30 92 85 92 6b 7d 92 83  30 20 30 20 35 2e 35 20  |0...k}..0 0 5.5 |
00000080  30 20 33 36 30 92 05 92  a7                       |0 360....|
00000089

```

Download hand coded binary file

ASCII version:

```
h 12 div dup scale
7.5 6 translate
5 6
1.8 -1.5
3.8 -3.2
3.8 -6
-9.4 -6
-7.1 -.5
-7.5 .5
-5.2 6
moveto
7{lineto}repeat
clip newpath
5.5 0
-8 -1
-8 1
moveto
2{15 0 rlineto moveto}repeat
0 0 5.5 0 360 arc
stroke

```

Save as `euro.ps` and run with Ghostscript like

```
gs -dh=80 euro.ps

```

```
gs -dh=20 euro.ps

```

As there is no such thing as a pixel in PostScript, that height is interpreted in points instead. I calculated +6 for the switch on the command line.

# Answer
> 13 votes
# PHP, ~~432~~ ~~435~~ ~~367~~ ~~356~~ 334 bytes

<sub>(Edit: Apparently IJ and GH are supposed to be parallel with BCDE. Now fixed)</sub>

This script outputs an SVG image, but will serve it as `text/html` by default. I think most browsers will treat this as an HTML web page containing an embedded SVG image. It seems to work OK for me anyway.

The height of the image is passed as a query string parameter. (Note: the byte count includes a newline character at the end of line 3, which is necessary for this to work properly).

```
<?php $x=$_GET['x']/12;$a=$x*5;$b=$x*6;$c=$x*7;$d=$x*12.4884;$e=$x*2.2863;$f=$x*5.5;$g=$x*.4157;$h=$x*6.5;$i=$x*7.5;$j=$x*12;$k=$x*11.3302;$l=$x*9.1628;$m=$x*8;$s=$x*12;echo<<<Q
<svg width="$s" height="$s"><clipPath id="c"><path d="M$d 0H$e L0 $f L$g $h L0 $i V$s H$k V$m H$l z"/></clipPath><g clip-path="url(#c)" fill="none" stroke="#000" stroke-width="$x"><circle cx="$i" cy="$b" r="$f"/><path d="M0 $a H$k M0 $c H$k"/></g></svg>
Q;

```

---

### Updated version (~~367~~ ~~356~~ 334 bytes):

`preg_replace_callback()` is a much more efficient way of scaling the numerical values. This code produces the same output as the original version. (Edit: Further reductions thanks to Einacio)

```
<?php
echo preg_replace_callback('/[\d\.]+/',function($m){return$m[0]*$_GET['x']/12;},'<svg width=12 height=12><clipPath id=c><path d=M12.4884,0H2.2863L0,5.5,0.4157,6.5,0,7.5V12H11.3302V8H9.1628z /></clipPath><g clip-path=url(#c) fill=none stroke=black stroke-width=1><circle cx=7.5 cy=6 r=5.5 /><path d=M0,5H11M0,7H11 /></g></svg>');

```

## Output:

**euro.php?x=60**

**euro.php?x=200**

# Answer
> 13 votes
# Python - turtle - 517

```
import turtle,sys
from math import *
q=sqrt
h=int(sys.argv[1])/24
t=turtle.Turtle()
z=t.begin_fill
y=t.end_fill
x=t.goto
w=t.towards
v=t.fd
u=t.circle
r=t.seth
o=t.setx
n=t.xcor
t.pu()
x(10*h,0)
t.left(90)
t.circle(10*h,40)
z()
A=w(0,-12*h)
B=2/sin(A*pi/180)
u(10*h,280)
r(-90)
C=n()/h
v((q(144-C*C)-q(100-C*C))*h)
D=w(0,0)
r(D+90)
u(-12*h,D+135.42)
y()
F=2*pi/9
G=h*cos(F)/(5*sin(F)+6)
x(45*G,-3*h)
z()
o(-15*h)
r(A)
v(B*h)
o(45*G+15*h+n())
y()
x(65*G,h)
z()
o(-15*h)
r(A)
v(B*h)
o(65*G+15*h+n())
y()
t.ht()
input()

```

`python % 100` and `python % 500` respectively:

# Answer
> 9 votes
## sh, 8604

I *think* someone can probably do better, but let’s start this off.

```
echo [encoded data, 8524 characters]|base64 -d|unxz>e.svg;echo \<img src=e.svg height=$1\>>e.htm;firefox e.htm

```

# Answer
> 9 votes
# HTML5, 395

**==\> Try it online**

```
<canvas id=c><script>_='function e,t,n){c.savtranslate,trotatn?0:.42)}v=docuEleById("c"c=vContex"2d"scalw=(v.width=v.height=promp))/12,w76,1arc(56--114.2,6,66-13,6.-   2,1 11.5)c.clearRec2restor-7mov-71lin6,.5,strokt(   .5--e(0,);1,ment.geteTo(';for(Y in $='  ')with(_.split($[Y]))_=join(pop());eval(_)</script>

```

The code is compressed using JSCrush.

Here is the uncompressed code :

```
<canvas id=c>
<script>
v=document.getElementById('c');
c=v.getContext('2d');
function r(){c.rotate(0.42)}
function t(x,y){c.save();c.translate(x,y)}
c.scale(w=(v.width=v.height=prompt())/12,w);
t(7.5,6);
c.arc(0,0,5.5,0,6);
c.stroke();
c.moveTo(-7.5,-1);c.lineTo(6,-1);
c.moveTo(-7.5,1);c.lineTo(6,1);
c.stroke();
c.clearRect(4.2,0,6,6);
t(0,6);r();
c.clearRect(0,-11,3,6.2);
c.restore();
t(-7.5,-0.5);r();
c.clearRect(-1,-2,1,2);
c.restore();
t(-7.5,1.5);r();
c.clearRect(-1,-1.5,1,1.5)
</script>

```

# Answer
> 6 votes
# PostScript, 270

```

7 7 translate
/l{lineto}def
/o{0 0}def
o 6 44.85 165.52 arc
-7.08 1.5 l
-7.5 .5 l
o 6 175.22 184.74 arc
-7.08 -.5 l
-7.5 -1.5 l
o 6 194.48 309.67 arc
o 5 320 197.46 arcn
1.87 -1.5 l
2.29 -.5 l
o 5 185.74 174.26 arcn
2.7 .5 l
3.12 1.5 l
o 5 162.54 40 arcn
closepath fill

```

This just defines the outline by appending path elements based on coordinates I calculated with the help of GeoGebra, and then fills the outline.

I saved a few chars by adding shortcuts for `lineto` (`/l{lineto}def`) and the origin of the circle (`/o{0 0}def`).

To specify a different size, add a command of the form `*height* *width* scale` after the first blank line.

When run on its own, this draws the euro sign in the bottom left-hand corner of the page of the default page size. Just save it as `*anything*.ps` and view it with a document viewer.

Here is an image of it at the default size, rasterized to a little over 90 pixels per inch:

At 4x size:

You can also download the original for your own viewing pleasure.

# Answer
> 5 votes
# PHP (without SVG), ~~628~~ 597 bytes

Thanks to AsksAnyway for the nice shortcut for functions (e.g. `$c = print; $c('Hello world!');`).

```
<?php header('Content-type:image/png');$h=$_GET['h'];$i=imagecreatetruecolor($h*1.1,$h*1.1);$c=imagecolorallocate;$b=$c($i,0,0,0);$w=$c($i,255,255,255);imagefill($i,0,0,$w);$l=$h*.7;$t=$h*.55;$u=$h/12;$e=imagefilledellipse;$e($i,$l,$t,$h,$h,$b);$e($i,$l,$t,$h*5/6,$h*5/6,$w);$f=imagefilledpolygon;$f($i,array($l+$u*5,$t+$u*1.5,$l-$u*7.5,$t+$u*1.5,$l-$u*7.125,$t+$u*0.5,$l+$u*4,$t+$u*.5,$l+$u*4,$t-$u*.5,$l-$u*7.5,$t-$u*.5,$l-$u*7.125,$t-$u*1.5,$l+$u*5,$t-$u*1.5),8,$b);$f($i,array($l+$u*4.24,$t-$u*4.24,$l+$u*1.84,$t+$u*1.5,$l+$u*3.84,$t+$u*3.26,$l+$u*3.84,$t+$u*4.62,$h*2,$t,),5,$w);imagepng($i);

```

Call `file.php?h=200` from your browser in order to see the image

The coordinates are based on measurements performed with GIMP

## 100 pixels:

## 200 pixels:

## Layers added step by step:

## Ungolfed code (with fractions, the golfed code has rounded values)

```
<?php
header('Content-type: image/png');

$h = $_GET['h'];

$i = imagecreatetruecolor($h * 1.1,$h * 1.1);

$c = imagecolorallocate;

# black
$b = $c($i,0,0,0);
# white
$w = $c($i,255,255,255);

imagefill($i,0,0,$w);

$l = $h * .7; # distance between left and center of the circle
$t = $h * .55; # distance between top and center of the circle

# one "unit", as defined by the specs
$u = $h / 12;

$e = imagefilledellipse;
# disk is black
$e($i, $l, $t, $h, $h, $b);
# inner disk is white
$e($i, $l, $t, $h * (5 / 6), $h * (5 / 6), $w);

$f = imagefilledpolygon;
# draw 2 bars in black
$f($i, array(
# bottom bar
$l + $u * 5, $t + ($u * 1.5), # bottom right
$l-$u * 7.5, $t + ($u * 1.5), # bottom left
$l-$u * 7.125, $t + ($u * 0.5), # top left
$l + $u * 4, $t + ($u * 0.5), # top right
# top bar
$l + $u * 4, $t - ($u * 0.5), # bottom right
$l-$u * 7.5, $t - ($u * 0.5), # bottom left
$l-$u * 7.125, $t - ($u * 1.5), # top left
$l + $u * 5, $t - ($u * 1.5) # top right
), 8, $b);

# hide right parts of bars and circle by drawing white
$f($i, array(
$l + $u * 6 * (212 / 300), $t - ($u * 6 * (212 / 300)), # right of the disk
$l + $u * 6 * (92 / 300), $t + ($u * 6 * (74 / 300)), # left = bottom right of bottom bar
$l + $u * 6 * (191 / 300), $t + ($u * 6 * (163 / 300)), # bottom of the circle
$l + $u * 6 * (191 / 300), $t + ($u * 6 * (231 / 300)), # bottom of the circle too
$h * 2, $t, # some point at the right of the image (outside the image)
), 5, $w);

imagepng($i);

```

# Answer
> 4 votes
# Bash + ImageMagick + linux command-line tools, 460 bytes

```
base64 -d<<<H4sIADBMaVMAAy1Ru27DMAz8FUJdBVsk9QziLFo8uD/QrUDSOIDTBo1Rt39fUsl0POp0PEr7+88Zfq/L530w87redn2/bVu3cff1fe7JOdeLwsB2Oa7zYDw7A/Ppcp5XJWQO+9v7OsN9/VtOg/m4LMvuRS4ZOA7m1VkseQpBoQZvyXlQQPeA2JpEjVEGURL7EePkLCU3Rqw5Wo4EmLALVgaC9BUrk392OAWt0HUBPHrb+NQq4i5UzigeSU6Zsii5xOYiWLE0BCT1Z89QVKLD2dPEIbdEBasINWIDaiDxG2BjslpBXXTk5CeWFkYa1a2KuS0OMBfJ8RgdKzMr03DRP5Ojy5O8sE2ksdU1g+pcu+SqvILUWddNCBHbCIxvpj/s9ZsO/xXfC57OAQAA|zcat|convert -scale $1 svg:- png:-|xview stdin

```

This is the same technique as @minitech's answer. But the .svg data comes from here, which is much shorter: http://commons.wikimedia.org/wiki/File:Euro\_symbol\_black.svg. ImageMagick converts the vector data to .png data at the requested scale and pipes to xview.

Output for `./euro.sh 30`:

Output for `./euro.sh 300`:

# Answer
> 3 votes
# POV-Ray (370 bytes)

I couldn't figure out how to render the same vertical area and preserve the aspect ratio at the same time, so I decided to go for the correct height and its up to the user to render only in 4:3 format

```
camera{angle 9 location 102*z right x*8 up y*6 look_at 0}
light_source{99*z color 1}
plane{z,0 pigment{color rgb 1}}
#declare b=difference{box{<-5,-.5,1>,<8,.5,1>}box{-2,2 rotate-67*z translate 9.4*x}}
difference{union{torus{5.5,.5 rotate 90*x}object{b translate y}object{b translate -y}}box{<-3.83,-5,-3>,<-7,0,3>}box{<0,7,3>,<-4,-2,-3>rotate 23*z translate-2.5*x}}

```

run with `povray.exe /RENDER euro.pov -w600 -h800`

# Answer
> 3 votes
# Processing, 232 bytes

Processing doesn't really allow taking in command line arguments since it is so specialized for drawing, but my function takes in the parameter as height to compensate. Coordinates are hard-coded/approximated from the image above, and the entire canvas is scaled based on the input parameter to get drawings of arbitrary sizes.

```
void E(int h){scale(h/12,h/12);noFill();strokeWeight(1);arc(7.5,6,11,11,0.7,PI*2-0.7,OPEN);noStroke();fill(0);shearX(-PI/6);rect(3.2,4.5,9,1);rect(4.4,6.5,8,1);shearX(PI/6);fill(255);rect(11,6,9,6);triangle(8.75,6,12.25,6,12.25,0);}

```

# Ungolfed + entire program

```
void setup()
{
  size(575, 500);
}

void draw()
{
  background(255);
  E(height);
  noLoop();
}

void E(int h)
{
  scale(h/12,h/12);
  //Main "C"
  noFill();
  strokeWeight(1);
  arc(7.5,6,11,11,0.7,PI*2-0.7,OPEN);
  //settings for other shapes
  noStroke();
  //the two bars
  fill(0);
  shearX(-PI/6);
  rect(3.2,4.5,9,1);
  rect(4.4,6.5,8,1);
  //bottom cut of "C"
  shearX(PI/6);
  fill(255);
  rect(11,6,9,6);
  //top cut of "C"
  triangle(8.75,6,12.25,6,12.25,0);
}

```

# Output

# Answer
> 2 votes
# C (gcc) (MinGW), ~~277~~ 276 bytes

-1 byte thanks to @ceilingcat

Added `-lm` compiler flags to TiO for illustrative purposes, but MinGW does not need it.

Outputs a 3-shade PGM file to STDOUT.

```
q,i,c;main(s,v)char**v;{float u=atoi(v[1])/12.,d,r;q=u*15;for(*v=memset(calloc(q,q+1),2,i=q*q);i--;i[*v]-=d<6&d>5|r>6&r<7|r>8&r<9&&r<7|c<q/2+u*3.83&&u*31.538-s>r*u|r>10&&u*7-s<r*u&&u*9-s<r*u|r<8)r=i/q/u,c=i%q,d=hypot(q/2-c,q/2-r*u)/u,s=2.405*c;printf("P5 %d %d 2 %s",q,q,*v);}

```

Try it online!

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