It's factors all the way down! This challenge is inspired by this fantastic animated diagram (thanks to flawr for posting it in chat).

Given an input n, draw all of its prime factors as nested polygons of dots, as specified.

For example, given the number 357 = 17x7x3, you arrange 3 dots in a triangle, 7 versions of those triangles in a heptagon, and 17 versions of those heptagons in a 17-gon. In short, nested polygons going from the largest prime factor on the outside to the smallest on the inside. For 357, your answer should look a little like this (with or without color):

Every polygon of every prime >= 3 should not be rotated around the diagram.

The only exception is the prime 2, specifically for odd powers of 2. As you can see in the example for 376 = 47x2x2x2 below, the 8s rotate and are not single lines of 2s, but are vertical stacks for 4s in a square. Even powers of 2, arranged in squares, do not need to be rotated in this way.

In fact, 448 = 7x2x2x2x2x2x2 has a diagram that looks like a heptagon of 64s, and 64 is arranged into a square of squares of squares, but without rotation.

Two more examples are 440 = 11x5x2x2x2 and 432 = 3x3x3x2x2x2x2. We see that 440 with an odd power of 2, has rotated 8s, but 432 with an even power of 2 does not rotate its 16s.

And finally, here is a minimal example, 10 = 5x2, without color that I mocked up with Python and its turtle module.

The challenge

Given an input n where 1 <= n <= 10000, output an image of its nested factor polygons.
Rules are:

The image is made up of nested polygons of dots, from a polygon with (the largest prime factor) sides on the outside to the smallest prime factor on the inside.
For the factor 2, the powers of 2 should stack as a line, then a squares, then a line of squares, and so on. Even powers of 2 should not be rotated. Odd powers of 2 should be rotated around their respective polygons, and they should be stacked vertically before rotation.

You may orient the image however you like (though I prefer up), but every nested polygon should be facing the same direction as any other polygon with the sole exception of odd powers of 2.
You have two options for image size and dot size:

The image size is static and the dot size decreases as n increases (as in the animation).
The dot size is static and the image size grows as n increases.

The first three layers of polygons should be distinguishable from neighboring polygons (i.e. not touching), but considering the size of the images at and around n=10000, it's okay if the layers after start to touch. I'd prefer it if they didn't, but it may be unavoidable to fit on an image that is uploadable to Stack Exchange.
Color is optional.
The shape of the dots is up to you. If squares are better for your language, use those.
No bonuses, but I would like to see someone animate and color the diagrams like in the original post.

Thanks to Conor O'Brien, EasterlyIrk, Martin Ender, Kritixi Lithos, Mego, DJ McMayhem, and El'endia Starman for their help in writing this question.

This code golf, so shortest code wins. Good luck and good golfing!

Python 3.5, 331 309 308 306 304 bytes

It took quite a bit of messing with the spacing of the polygons (and the specification, too, to be honest) to get this answer to work, but I finally did it and hopefully other answers can start coming in.

Edit: -2 bytes thanks to FlipTack. -8 bytes from removing a section of code that I forgot to remove earlier. -12 bytes from golfing the last function. -1 byte from changing the circumference of the drawings from size=2500 to size=2e3, which also allows the drawings to better fit on screens (diameter ~= 795.77 down to diameter ~= 636.62). -2 bytes from fixing a bug. -2 bytes from restructuring how I build a.

Golfing suggestions welcome. Trinket for testing and images to follow shortly.

from math import*
from turtle import*
ht();pu()
def g(n):
 i=1;a=[]
 while n%4<1:a+=4,;n//=4
 while n>1:
  i+=1
  while n%i<1:a+=i,;n//=i
 return f(a,2e3)
def f(a,s,x=0,y=0,t=0):
 if a:
  *c,b=a;s/=b
  for i in range(b):u=2*pi*i/b+t*(b<3)+pi/4*(b==4);f(c,s,x+s*sin(u),y+s*cos(u),u)
 else:goto(x,y);dot(4)

Here's g(448), which now fits on my 1366x768 screen.

Ungolfing

import math
import turtle

turtle.hideturtle()     # don't display the turtle itself)
turtle.penup()          # don't draw lines, just dots later on

def g(n):
    i = 1
    a = []
    while n % 4 == 0:   # get 4's into the list first,
        a = a + [4]     # so that the fractal will be easier to structure
        n = n // 4
    while n > 1:        # now get all of the other factors (including any stray 2's)
        i += 1
        while n % i == 0:
            a = a + [i]
            n = n // i
    return f(a, 2000)   # 2000 is the circumference of the circle
                        # on which we draw the polygons
def f(a, s, x=0, y=0, t=0):
    if a:
        c = a[-1]       # the size of the current outermost polygon
        b = a[:-1]      # the rest of the factors for recursion
        s = s/b         # the current circumference / the number of polygons at this layer
        for i in range(b):
            u = 2*math.pi*i/b   # angle around the circle
            if b == 2:          # if b == 2, add the previous angle to rotate the structure
                u += t
            if b == 4:          # if b == 4, add 45 degrees to keep the squares upright
                u += math.pi/4
            dx = s * math.sin(u)    # our coordinate changes for this polygon
            dy = s * math.cos(u)
            f(c, s, x+dx, y+dy, u)  # call the function again
                                    # on a new circle with new starting coordinates
    else:                   # when we run out of factors,
        turtle.goto(x,y)    # go to each coordinate
        turtle.dot(4)       # and draw a dot


Create a Parrot Program Given an input, output that input followed by a newline endlessly.

Input will be a string consisting only of printable ASCII characters (0x20-0x7E) and newlines (0x0A).

If input is length 0, endlessly output newlines.

This is code-golf so fewest bytes in each language wins!


Sort characters by darkness Your program must take as input a line of characters, like this:

@+.0

And output the characters sorted by how dark they are, like this:

.+0@

Requirements:

You must use a monospaced font for darkness detection.
You must find out how many pixels each character takes up. You must actually draw the character and count pixels, i.e. you can't just hardcode pixel amounts.

As a more concrete rule: if you switched fonts, your program should still work. Furthermore, your program should be able to switch fonts by simply changing a variable or value or string in the code.

If you use antialiasing, you must count pixels as percentages of a fully black pixel. For example, an rgb(32, 32, 32) pixel will count as 1/8 of a full pixel. Disregard this rule if your characters are not antialiased.
After counting pixels, you must sort the characters by the amount of pixels, and output them in order.
This is code-golf, so the shortest code in bytes will win.

Bash + ImageMagick: 164 147 148 characters

while read -n1 c
do
o=`convert -size 20x15 xc: +antialias -font cour.ttf -draw "text 0,10 '$c'" xpm:-`
o=${o//[^ ]}
a[${#o}]+=$c
done
echo "${a[@]}"

Sample run:

bash-4.1$ echo -n '@+.0' | bash graysort.sh
. + 0 @

Separators are inserted between grayness groups. Characters with identical grayness level are not separated:

bash-4.1$ echo -n 'abcdefghijklmnopqrstuvwxyz' | bash graysort.sh
i cl jortz esv ax u df bgnpq y hk w m


Help me accelerate linear recurrence relation! Background
A linear recurrence relation is a description of a sequence, defined as one or more initial terms and a linear formula on last \$k\$ terms to calculate the next term. (For the sake of simplicity, we only consider homogeneous relations, i.e. the ones without a constant term in the formula.)
A formal definition of a linear recurrence relation looks like this, where \$y_n\$ is the desired sequence (1-based, so it is defined over \$n\ge 1\$) and \$x_i\$'s and \$a_i\$'s are constants:
$$
y_n =
\begin{cases}
x_n,  & 1\le n\le k \\
a_1y_{n-1}+a_2y_{n-2}+\cdots+a_ky_{n-k}, & k<n
\end{cases}
$$
In this challenge, we will accelerate this sequence by converting it to a matrix form, so that the \$n\$-th term can be found by repeated squaring of the matrix in \$O(\log n)\$ steps, followed by inner product with the vector of initial terms.
For example, consider the famous Fibonacci sequence: its recurrence relation is \$y_n=y_{n-1} + y_{n-2}\$ with \$k=2\$, and let's use the initial values \$x_1=x_2=1\$. The recurrence relation can be converted to a matrix form:
$$
\begin{bmatrix} y_{n-1} \\ y_{n} \end{bmatrix} = \begin{bmatrix} y_{n-1} \\ y_{n-1}+y_{n-2} \end{bmatrix} = \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix}\begin{bmatrix} y_{n-2} \\ y_{n-1} \end{bmatrix}
$$
So multiplying the matrix once advances the sequence by one term. Since this holds for any \$n\$, it can be extended all the way until we reach the initial terms:
$$
\begin{bmatrix} y_{n-1} \\ y_{n} \end{bmatrix} = \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix}\begin{bmatrix} y_{n-2} \\ y_{n-1} \end{bmatrix} = \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix}^2\begin{bmatrix} y_{n-3} \\ y_{n-2} \end{bmatrix} \\
= \cdots = \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix}^{n-2}\begin{bmatrix} y_{1} \\ y_{2} \end{bmatrix} = \begin{bmatrix} 0 & 1 \\ 1 & 1 \end{bmatrix}^{n-2}\begin{bmatrix} 1 \\ 1 \end{bmatrix}
$$
In general, one way to construct such a matrix is the following:
$$
\begin{bmatrix} y_{n-k+1} \\ y_{n-k+2} \\ \vdots \\ y_{n-1} \\ y_{n} \end{bmatrix} = \begin{bmatrix} 0 & 1 & 0 & \cdots & 0 \\ 0 & 0 & 1 & \cdots & 0 \\ & \vdots & & & \vdots \\ 0 & 0 & 0 & \cdots & 1 \\ a_k & a_{k-1} & a_{k-2} & \cdots & a_1 \end{bmatrix}\begin{bmatrix} y_{n-k} \\ y_{n-k+1} \\ \vdots \\ y_{n-2} \\ y_{n-1} \end{bmatrix}
$$
Note that, if you reverse the vectors and the matrix in every dimension, the equation still holds, retaining the property of "advancing a term by matmul-ing once". (Actually any permutation will work, given that the rows and columns of the matrix are permuted in the same way.)
Challenge
Given the list of coefficients \$a_1,\cdots,a_k\$, construct a matrix that represents the recurrence relation (so that its powers can be used to accelerate the computation of \$n\$-th term of the sequence).
You can take the coefficients in reverse order, and you can optionally take the value \$k\$ as a separate input. \$k\$ (the number of terms) is at least 1.
Standard code-golf rules apply. The shortest code in bytes wins.
Test cases
In all cases, any other matrix that can be formed by permuting rows and columns in the same way is also valid.
Input
[1,1]
Output
[[0, 1],
 [1, 1]]

Input
[5]
Output
[[5]]

Input
[3, -1, 19]
Output
[[0,  1,  0],
 [0,  0,  1],
 [19, -1, 3]]
or reversed in both dimensions:
[[3, -1, 19],
 [1, 0,  0],
 [0, 1,  0]]
or cycled once in both dimensions:
[[3, 19, -1],
 [0, 0,  1],
 [1, 0,  0]]
etc.

MATL, 8 7 bytes
-1 byte thanks to @LuisMendo
Xy4LY)i

Takes the coefficients in reverse order
Try it online!
Explanation
Xy4LY)i
Xy        : Create an identity matrix of size equal to input
  4LY)    : Remove the first row
      i   : Insert input onto the stack


Let's get the gang back together! A narcissist program is a program that only accepts its own source code. A bigotous program is a program that only accepts the source code of programs semantically equivalent to itself. A gang member is somewhere in between.

In particular, we will define a gang as set of programs G, which may or may not be in the same programming language, such that each program, when executed, will only accept members of its gang, and reject everything else (since they all do the same thing, this means that are semantically equivalent). A gang member is a program that is part of a gang, and the set of programs that it accepts is its gang.

So, a narcissist program is a gang of size 1, and a class of bigots is a maximally sized gang (every equivalent program gets to be part of the gang).

Your job is to create a gang of programs. It must be of size at least 2, and can have programs in different languages (you can even count the same program multiple times if it's a polyglot).

Your score is (average length of gang member)/(# of unique programming languages), which you are trying to minimize (so you are rewarded for using different languages). It is considered cheating to use built in language features that allow a program to access its own code.

Note: We'll define acceptance v.s. rejection via https://codegolf.meta.stackexchange.com/a/12685/16842 or https://codegolf.meta.stackexchange.com/a/12684/16842, your choice.

0 points (average length 0 bytes, 2 unique language)

I'm assuming we can define acceptance and rejection as the output of two different values.

The gang size is 2 (the languages are 05AB1E and 2sable), and the program is the empty program.

For some reason, both an empty 05AB1E program and an empty 2sable program appear to outputs 2 (plus a newline in the case of 2sable) when the input is not empty (i.e. a different program; rejection). They output nothing if there is no input (i.e. the same program; acceptance).

Since I "can even count the same program multiple times if its a polygot", these are two programs.

(I know neither 05AB1E nor 2sable at all and just tried golfing languages in TIO until I found some that seemed to work, so this answer might be wrong if they output something else for some specific inputs.)


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 code-golf challenge, so the shortest code wins.

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.


New Order #1: How does this feel? Introduction

Putting all positive numbers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive numbers.

The first challenge in this series is to output a(n) for a given n as input, where a(n) is A064413, also known as the EKG sequence because the graph of its values resembles an electrocardiogram (hence the "How does this feel" reference). Interesting properties of this sequence are that all positive integers appear exactly once. Another notable feature is that all primes occur in increasing order.

Task

Given an integer input n, output a(n).

\$a(n)\$ is defined as:

\$a(1) = 1; a(2) = 2;\$
for \$n > 2\$, \$a(n)\$ is the smallest number not already used which shares a factor with \$a(n-1)\$

Note: 1-based indexing is assumed here; you may use 0-based indexing, so \$a(0) = 1; a(1) = 2\$, etc. Please mention this in your answer if you choose to use this.

Test cases

Input | Output
--------------
1     | 1
5     | 3
20    | 11
50    | 49
123   | 132
1234  | 1296
3000  | 3122
9999  | 10374

Rules

Input and output are integers (your program should at least support input and output in the range of 1 up to 32767)
Invalid input (floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour.
Default I/O rules apply.
Default loopholes are forbidden.
This is code-golf, so the shortest answers in bytes wins

Final note

See this related PP&CG question.


Merge two sorted lists Merge Sort

In this challenge, you will implement the merge subroutine of merge sort. Specifically, you must create a function or program or verb or similar which takes two lists, each sorted in increasing order, and combines them into one list sorted in increasing order.
Requirements:

 - Your algorithm must take an asymptotically linear amount of time in the size of the input. Please stop giving O(n^2) solutions.

You may not use any built-in functions capable of sorting a list, or merging a list, or anything like that. Author's discretion.
The code should be able to handle repeated elements.
Don't worry about empty lists.

Examples:

merge([1],[0,2,3,4])
[0,1,2,3,4]

merge([1,5,10,17,19],[2,5,9,11,13,20])
[1, 2, 5, 5, 9, 10, 11, 13, 17, 19, 20]

This is code-golf, so may the shortest code win!

Rebmu (35 32 chars)

u[iG^aNXa[rvA]apGtkFaM?fA]apGscA

Test

>> rebmu/args [u[iG^aNXa[rvA]apGtkFaM?fA]apGscA] [[1 5 10 17 19] [2 5 9 11 13 20]]
== [1 2 5 5 9 10 11 13 17 19 20]

>> rebmu/args [u[iG^aNXa[rvA]apGtkFaM?fA]apGscA] [[2 5 9 11 13 20] [1 5 10 17 19]]
== [1 2 5 5 9 10 11 13 17 19 20]

About

Rebmu is a dialect of Rebol that permits 'mushing' of regular code for situations that require brevity. Unmushed, the code works somewhat like:

u [                     ; until
    i g^ a nx a [       ; if greater? args next args
       rv a             ; reverse args
    ]                   ; (we want the block containing the next value first)

    ap g tk f a         ; append output take first args
    m? f a              ; empty? first args
]                       ; (first block is now empty)

ap g sc a               ; append output second args
                        ; (add the remainder of the second)

I believe this satisfies the O(n) requirement as the until block is at most looped as many times as the length of the input (and the reverse only switches the order of the container of the input blocks, not the blocks themselves). Using take is perhaps a liberty, but is still a minor efficiency hit.

Rebol (83 75 chars)

Just a wee bit different: in Rebol, paths are a shorter expression than first or second. a is the input block containing the two blocks:

until[if a/2/1 < a/1/1[reverse a]append o:[]take a/1 tail? a/1]append o a/2


Dimensional countdown Write a function f(n,k) that displays the k-dimensional countdown from n.

A 1-dimensional countdown from 5 looks like

 54321

A 2-dimensional countdown from 5 looks like

 54321
 4321
 321
 21
 1

Finally, a 3-dimensional countdown from 5 looks like

 54321
 4321
 321
 21
 1
 4321
 321
 21
 1
 321
 21
 1
 21
 1
 1

Formal definition

The 1-dimensional countdown from any n is a single line with the digits n, n-1,...,1 concatenated (followed by a newline).

For any k, the k-dimensional countdown from 1 is the single line

 1

For n > 1 and k > 1, a k-dimensional countdown from n is a (k-1)-dimensional countdown from n followed by a k-dimensional countdown from n-1.

Input

Two positive integers k and n <= 9, in any format you choose.

Output

The k-dimensional countdown from n, with a newline after each 1-dimensional countdown. Extra newlines are permitted in the output.

Scoring

Standard golf scoring.

Bonus example

Here's an example with k > n, a 4-dimensional countdown from 3 (with extra comments that are not to be included in actual solutions):

 -- 3-dimensional countdown from 3
 321
 21
 1
 21
 1
 1
 -- 4-dimensional countdown from 2:
 ---- 3-dimensional countdown from 2:
 21
 1
 1
 ---- 4-dimensional countdown from 1:
 1

Clarifications:

Digits on a line do not need to be adjacent, but they must be evenly-spaced.

You may write a full program instead of just a function, if you prefer.

Python, 60 bytes

f=lambda n,k:n>1<k and f(n,k-1)+f(n-1,k)or'987654321\n'[~n:]

Test it on Ideone.

How it works

The k-dimensional countdown from n can be defined with a single base case:

  If n = 1 or k = 1, the output is n || n-1 || ... || 1 || ¶, where || indicates concatenation.

Using the recursive definition from the question, f(n,k) returns f(n,k-1)+f(n-1,k) if n > 1 and k > 1; otherwise it returns the last n + 1 characters from '987654321\n'.


Implement INTERCAL's Binary Operators The Compiler Language With No Pronounceable Acronym, abbreviated INTERCAL, is a very unique programming language. Among its unreproducible qualities are its binary operators.

INTERCAL's two binary operators are interleave (also known as mingle), and select. Interleave is represented with a change (¢), and select is represented with a sqiggle (~).

Interleave works by taking two numbers in the range 0-65535 and alternating their bits. For instance:

234 ¢ 4321
234   = 0000011101010
4321  = 1000011100001
Result: 01000000001111110010001001
Output: 16841865

Select works by taking two numbers in the range 0-65535, taking the bits in the first operand which are in the same position as 1s in the second operand, and right packing those bits.

2345 ~ 7245
2345  = 0100100101001
7245  = 1110001001101
Taken : 010   0  10 1
Result: 0100101
Output: 37

In this challenge, you will be given a binary expression using either the interleave or select operation. You must calculate the result, using the fewest possible bytes.

The expression will be given as a space separated string, consisting of an integer in 0-65535, a space, either ¢ or ~, a space, and an integer in 0-65535.

Input and output may be through any standard system (STDIN, function, command line, etc.). Standard loopholes banned.

Examples:

5 ¢ 6
54

5 ~ 6
2

51234 ¢ 60003
4106492941

51234 ~ 60003
422

This is code golf - fewest bytes wins. Good luck.

EDIT: Since some languages do not support INTERCAL's change (¢) symbol, you may use the big money ($) symbol instead, at a 5 byte penalty.

Python 2, 115 112 bytes

x,y,z=input().split()
d=y<""
f=lambda a,b:a+b and(b%2+5&4-d)*f(a/2,b/2)+(a%2*2+b%2)/3**d
print f(int(x),int(z))

The string on the second line contains a single unprintable character \x7d, the next char after ~.

All hopes of a nice, single lambda get crushed by the input format. There's probably a better way to read in input. Input like "51234 ¢ 60003" via STDIN.

The function f combines the following two recursive functions:

g=lambda a,b:a+b and 4*g(a/2,b/2)+a%2*2+b%2    # ¢
h=lambda a,b:a+b and(b%2+1)*h(a/2,b/2)+a*b%2   # ~

(-3 bytes with the help of @xnor)


Is this number Loeschian? A positive integer \$k\$ is a Loeschian number if

\$k\$ can be expressed as \$i^2 + j^2 + i\times j\$ for \$i\$, \$j\$ integers.

For example, the first positive Loeschian numbers are: \$1\$ (\$i=1, j=0\$); \$3\$ (\$i=j=1\$); \$4\$ (\$i=2, j=0\$); \$7\$ (\$i=2, j=1\$); \$9\$ (\$i=-3, j=3\$); ... Note that \$i, j\$ for a given \$k\$ are not unique. For example, \$9\$ can also be generated with \$i=3, j=0\$.
Other equivalent characterizations of these numbers are:

\$k\$ can be expressed as \$i^2 + j^2 + i\times j\$ for \$i, j\$ non-negative integers. (For each pair of integers \$i, j\$ there's a pair of non-negative integers that gives the same \$k\$)

There is a set of \$k\$ contiguous hexagons that forms a tesselation on a hexagonal grid so that corresponding cells are the same distance apart (see illustrations for \$k = 4\$ and for \$k = 7\$). (Because of this property, these numbers find application in mobile cellular communication networks.)

See more characterizations in the OEIS page of the sequence.

The challenge
Given a positive integer, output a truthy result if it is a Loeschian number, or a falsy result otherwise.
The program or function should handle (say in less than a minute) inputs up to \$1000\$, or up to data type limitations.
Code golf. Shortest wins.
Test cases
The following numbers should output a truthy result:
1, 4, 7, 12, 13, 108, 109, 192, 516, 999

The following numbers should output a falsy result:
2, 5, 10, 42, 101, 102, 128, 150, 501, 1000

Jelly, 11 9 bytes
ÆF‘%3,2ḄȦ

Try it online! or verify all test cases.
Background
In Elementary results on the binary quadratic form a² + ab + b², the author proves the following theorem about Löschian numbers.

Theorem 16. The necessary and sufficient condition of any non-negative integer to be in the form a² + ab + b² is that, in its prime factorization, all primes other than 3 that are not in the form (6k + 1) have even exponents.

As noted on the relevant OEIS page, since all integers are are congruent to 0, 1 or 2 modulo 3, the number 3 is the only prime that is congruent to 0, and all numbers of the form (6k + 1) are congruent to 1, the theorem can be stated alternatively as follows.
A non-negative integer n is a Löschian number if and only if all prime factors of n that are congruent to 2 modulo 3 have even exponents.
How it works
ÆF‘%3,2ḄȦ  Main link. Argument: n (integer)

ÆF         Yield the prime factorization of n, as prime-exponent pairs.
  ‘        Increment all primes and exponents, turning primes of the form 3k - 2
           into multiples of 3 and odd exponents into multiples of 2.
   %3,2    Reduce all incremented primes/exponents modulo 3/2.
           n is Löschian if and only if this does not result in a [0, 0] pair.
           Due to Jelly's form of vectorization, this yields [3, 2] if n = 1.
       Ḅ   Unbinary; convert each pair from base 2 to integer.
           Note that [x, y] = [0, 0] if and only if 2x + y = 0.
        Ȧ  All; return 1 if the result contains no zeroes, 0 otherwise.


Random Password Generator The domain server requires that all employees have a strong, random password conforming to the following rules:

Exactly 15 characters long.
Keyboard-typeable characters only (as shown in code-type below).  Teaching the sales to use ALT+NUMPAD codes is not permitted.
At least 1 lower case letter: abcdefghijklmnopqrstuvwxyz
At least 1 upper case letter: ABCDEFGHIJKLMNOPQRSTUVWXYZ
At least 1 numeric digit: 0123456789
At least 1 symbol: `~!@#$%^&*()_+-={}|[]\:";'<>?,./

For this purpose IT have commissioned and will be distributing a Random Password Generator to all employees.  All employees will be required to use the Random Password Generator.  The requirements for the Random Password Generator are, in addition to the password restrictions above:

It must be able to generate all permutations of all allowable characters.
It must display the generated password on the screen.
The code is required to be as small as possible (in bytes).

Please submit your proposed solution within the next week.

Mathematica (18)
Let me a little cheat
= 15char ASCII pwd

&(^F7yP8k:*1P<t

P.S. not safety :)


Visualize Merge Sort Merge sort is a sorting algorithm which works by splitting a given list in half, recursively sorting both smaller lists, and merging them back together to one sorted list. The base case of the recursion is arriving at a singleton list, which cannot be split further but is per definition already sorted.

The execution of the algorithm on the list [1,7,6,3,3,2,5] can be visualized in the following way:

       [1,7,6,3,3,2,5]
       /             \      split
   [1,7,6,3]       [3,2,5]
    /     \        /    \   split
 [1,7]   [6,3]   [3,2]  [5]
 /   \   /   \   /   \   |  split
[1] [7] [6] [3] [3] [2] [5]
 \   /   \   /   \   /   |  merge
 [1,7]   [3,6]   [2,3]  [5]
    \     /         \   /   merge
   [1,3,6,7]       [2,3,5]
       \             /      merge
       [1,2,3,3,5,6,7]

The Task

Write a program or function which takes a list of integers in any reasonable way as input and visualizes the different partitions of this list while being sorted by a merge sort algorithm. This means you don't have to output a graph like above, but just the lists are fine:

[1,7,6,3,3,2,5]
[1,7,6,3][3,2,5]
[1,7][6,3][3,2][5]
[1][7][6][3][3][2][5]
[1,7][3,6][2,3][5]
[1,3,6,7][2,3,5]
[1,2,3,3,5,6,7]

Furthermore, any reasonable list notation is fine, therefore the following would also be a valid output:

1 7 6 3 3 2 5
1 7 6 3|3 2 5
1 7|6 3|3 2|5
1|7|6|3|3|2|5
1 7|3 6|2 3|5
1 3 6 7|2 3 5
1 2 3 3 5 6 7

Finally, the way to split a list in two smaller lists is up to you as long as the length of both resulting lists differs at most by one. That means instead of splitting [3,2,4,3,7] into [3,2,4] and [3,7], you could also split by taking elements at even and odd indexes ([3,4,7] and [2,3]) or even randomize the split every time.

This is code-golf, so the shortest code in any language measured in bytes wins.

Test cases

As noted above, the actual format and the way to split lists in half is up to you.

[10,2]
[10][2]
[2,10]

[4,17,1,32]
[4,17][1,32]
[4][17][1][32]
[4,17][1,32]
[1,4,17,32]

[6,5,4,3,2,1]
[6,5,4][3,2,1]
[6,5][4][3,2][1]
[6][5][4][3][2][1]
[5,6][4][2,3][1] <- Important: This step cannot be [5,6][3,4][1,2], because 3 and 4 are on different branches in the the tree
[4,5,6][1,2,3]
[1,2,3,4,5,6]

Haskell, 137 128 127 125 121 109 106 bytes

(-2)+(-4)=(-6) bytes thanks to nimi! Changing it to collect all the steps in a list (again due to nimi) saves 12 more bytes.

Another 3 bytes due to Laikoni, with pattern guard binding and a clever use of list comprehension to encode the guard.

import Data.List
g x|y<-x>>=h=x:[z|x/=y,z<-g y++[sort<$>x]]
h[a]=[[a]]
h x=foldr(\x[b,a]->[x:a,b])[[],[]]x

Try it online!

Splitting the lists into the odd and the even positioned elements is a shorter code than into the two sequential halves, because we're spared having to measure the length, then.

Works by "printing" the lists, then recursing with the split lists (x >>= h) if there actually was any splitting done, and "printing" the sorted lists; starting with the one input list; assuming the non-empty input. And instead of actual printing, just collecting them in a list.

The list produced by g[[6,5..1]], printed line-by-line, is:

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


Self-loathing program/function Simple task, write a program/function that returns error if and only if presented with itself.

The program must give a valid output for any input other than itself.

For the error part, you can only use errors already built in errors that comes with your language of choice. New/ self-defined error messages are not allowed.

The output should be of the same type as the input. (int, float, string, array, boolean, etc.) Except in the case if presented with itself of course.

Standard loopholes forbidden, lowest byte wins.

05AB1E, 20 bytes
"34çìD«QiF"34çìD«QiF

Outputs the input if it's not equal to the program. If it is equal, it will output the error:

** (RuntimeError) Could not convert "34çìD«QiF"34çìD«QiF to integer.

Try it online.
Explanation:
It's based on this base quine: "34çìD«"34çìD«.

"34çìD«QiF"           # Push string "34çìD«QiF"
           34ç        # Push 34, converted to a character: '"'
              ì       # Prepend it to the string: '"34çìDJQiF'
               D«     # Append a copy of itself: '"34çìDJQiF"34çìDJQiF'
                 Qi   # If it's equal to the (implicit) input-string:
                   F  #  Start a loop, using the (implicit) input-string as argument,
                      #  resulting in the error
                      # (implicit else: use the implicit input as implicit output)


Fibonacci-style matrix expansion For each row and then column of a matrix, we can add an extra entry with the sum of the last two entries in that row or column.  For example with the following input matrix:
[ 1 1 1 ]
[ 2 3 4 ]

The resulting matrix would be:
[ 1 1 1 2 ]
[ 2 3 4 7 ]
[ 3 4 5 9 ]

Given an input of an integer N and an [X,Y] matrix of size at least 2x2, perform the above expansion N times and output the result.  The resulting matrix will always be of size [X+N,Y+N].
Examples:
Input:                     Output:

2, [ 0 0 ]                 [ 0 0 0 0 ]
   [ 0 0 ]                 [ 0 0 0 0 ]
                           [ 0 0 0 0 ]
                           [ 0 0 0 0 ]

3, [ 1 1 1 ]               [ 1  1  1  2  3  5 ]
   [ 2 3 4 ]               [ 2  3  4  7 11 18 ]
                           [ 3  4  5  9 14 23 ]
                           [ 5  7  9 16 25 41 ]
                           [ 8 11 14 25 39 64 ]

MATL, 13 14 15 16 20 21 bytes

2*:"!tP2:Y)sv

Thanks @Zgarb for removing 1 byte!

Try it online!

2*         % implicitly input number N and multiply by 2
:          % create vector [1,2,...,2*N]
"          % for loop: do this 2*N times
  !        %   transpose. Implicitly input matrix in the first iteration
  tP       %   duplicate and flip vertically
  2:       %   vector [1,2]
  Y)       %   pick submatrix formed by the first two rows
  s        %   sum of each column
  v        %   append as a new row
           % end for
           % implicit display


Mixed Number to an Improper Fraction Mixed Number to an Improper Fraction

In this challenge you will be converting a mixed number to an improper fraction.

Because improper fractions use fewer numbers, your code will need to be as short as possible.

Examples

4 1/2
9/2

12 2/4
50/4

0 0/2
0/2

11 23/44
507/44

Specification

You may assume the denominator of the input will never be 0. The input will always be in the format x y/z where x,y,z are arbitrary nonnegative integers. You do not need to simplify the output.

This is code-golf so shortest code in bytes wins.


Generate all brace-strings of length n A brace string is defined as a string consisting of the characters *()[] in which braces match correctly:

[brace-string] ::= [unit] || [unit] [brace-string]
[unit]         ::= "" || "*" || "(" [brace-string] ")" || "[" [brace-string] "]"

This is a valid brace-string:

((())***[]**)****[(())*]*

But these are not:

)(
**(**[*](**)
**([*)]**

Your task is to write a program (or function) that, given a positive integer n, takes a number as input and outputs (or returns) all valid brace strings of length n.

Specifications

You may output the strings in any order.
You may output as a list or a string separated by a different character.
Your program must handle 0 correctly. There is 1 possible brace-string of length 0, which is the empty string "".
This is code-golf, so the shortest valid answer – measured in bytes – wins.

Test Cases

0.
1. *
2. ** () []
3. *** ()* []* (*) [*] *() *[]
4. **** ()** []** (*)* [*]* (**) **() **[] *(*) *[*] (()) ()() ()[] ([]) [**] [()] [[]] []() [][] *()* *[]*

Prolog, 69 bytes

s-->[];e,s.
e-->"*";"(",s,")";"[",s,"]".
b(N,A):-length(A,N),s(A,[]).

One of the most interesting properties of Prolog is that in many cases it's capable of running a program backwards; for example, instead of testing to see if something's true, you can generate all solutions for which it's true, and instead of checking the length of a string, you can generate all strings with a given length. (Another nice property of Prolog is that it requires whitespace after the end of each predicate definition, and a newline can be inserted as cheaply as a space; thus even golfed programs are often fairly readable.)
The above defines a predicate (the equivalent of a function) b which tests to see if a string has a given length and is a "brace string" as defined in the question. Specifically, it does this via Prolog's grammar/regex/pattern-match support that gives some nice, short sugar for defining this sort of expression (apparently this is standard/portable, but I was unaware of this while originally writing the answer, and thus assumed the answer would work on only one Prolog implementation; it seems it works on every implementation that complies with the standards, though). The program can be translated into English fairly directly; the first two lines say "an s is an empty string, or an e followed by an s; an e is an asterisk, or an s in parentheses, or an s in square brackets". The third line can be interpreted as "The b of N can be A if A is a list with length N and A is an s followed by a null string."
I took some care to write s (and thus b) so that they match each "brace string" in exactly one way (which is the reason that both s and e have to exist, rather than grouping them into one predicate). This makes them both entirely reversible; thus b can be used to generate all "brace strings" of a given length, in addition to testing if a string is a brace string of a given length (it can also be used a third way round, to figure out the length of a brace string, but that is almost certainly its least useful mode of operation). The implementation is recursive, e.g. to generate an s, the code will generate all possible es that are no longer than the required length of the output, and append all possible ss that fit in the remaining space to them; because I specified the length of the argument in advance (within b), the Prolog engine knows that it can't generate output that's longer than the given length, which allows the recursion to terminate.
Here's an example of the program in operation:
| ?- b(4,A),format("~s ",[A]),fail.
**** **() **[] *()* *(*) *[]* *[*] ()** ()() ()[] (*)* (**) (()) ([]) []** []() [][] [*]* [**] [()] [[]]


Convert between Lambda Calculus Notations The lambda calculus is a system of functional programming. Lambda calculus consists of variables, abstractions, and applications.

A variable is simply a name denoting a function parameter. It is a single letter. An abstraction is a "function literal" of sorts, it consists of a backslash \ followed by a variable name, and then an expression, which is the function body. For example, the function \x.x is a function which takes an argument x and returns x, a.k.a. the identity function. Abstractions can also return other abstractions. For example, \x.\y.x is a function which takes an argument x and returns a new function that returns x.

There is also application. In application, you remove the header on the first value and substitute all instances of the function's argument with the value it is applied to. For example, to apply \x.xx to \y.y, substitute all x's with \y.y's, yielding (\y.y)(\y.y) (Parenthesis may need to be added for clarification.) Applications are denoted in an expression by writing the two values next to each other, where the first is the function to apply and the second is the argument to apply to. For example, you can write xy to apply x to y. However, you may need parenthesis (for example in a(bcd) or y(\x.xx).

The first lambda calculus notation is the one I just described.

\f.(\x.xx)(\x.f(xx))

The second lambda calculus notation does not need parenthesis. It matches the following grammar:

<expression> ::= <variable> || <abstraction> || <application>
<abstraction> ::= "\" <variable> <expression>
<application> ::= "`" <expression> <expression>

Here, a <variable> can be any uppercase or lowercase letter. This is an example of an expression in the second notation:

\f`\x`xx\x`f`xx

Your task is to write a program that takes a lambda calculus expression in the first notation and outputs it rewritten in the second notation.

Specifications

Every variable name is 1 letter.
Abstractions in the first notation go as far as possible, and application goes left to right: d(abc) -> `d``abc.
You do not have to deal with free/bound variables and scoping.

Test Cases

\a.a                                  -> \aa
(\x.xx)(\x.xx)                        -> `\x`xx\x`xx
\x.\y.\z.xz(yz)                       -> \x\y\z``xz`yz
(\S.\K.SKK)(\x.\y.\z.xz(yz))(\p.\q.p) -> ``\S\K``SKK\x\y\z``xz`yz\p\qp

Haskell, 211 197 186 bytes

(Saved 10 bytes by using interact as suggested by @Challenger5, and one more by not having a final newline.)

m(')':r)=([],r)
m s|(a,u)<-e s,(b,v)<-m u=(a:b,v)
f s|(a,r)<-m s=(tail(a>>"`"):a>>=id,r)
e('\\':v:_:s)|(a,r)<-f s=('\\':v:a,')':r)
e('(':s)=f s
e(v:s)=([v],s)
main=interact$fst.f.(++")")

Initially I had a function to perform the whole transformation, but now that is inlined into the main function which makes it a complete program. Dealing with a complete program instead of using a function String -> String at the interpreter also avoids the need to type and read double backslashes. The other functions follow the (simplified) pure functional parsing pattern of returning a parsing result and the unparsed rest of the string. f parses a list of expressions (possibly a multiple application) . It uses a helper function m  that also parses a list of expressions and has a list of parses as result. e handles the remaining cases: lambdas, parenthesized expressions, and variables. Instead of generating a parsing tree, we directly generate the desired output.

Try it online!

Using interact ruined clean I/O behaviour. If you don't use the TIO link but run it at the  command line of your computer, you have to make sure that there is no trailing whitespace, it would be treated like a variable. You can do something like echo -n '\f.(\x.xx)\x.f(xx)' | ./prog. Alternatively, you could replace the last line by the previous version main=getLine>>=putStrLn.fst.f.(++")").


Print the first 128 prime numbers without using any reserved words The obvious solution would be to just print them as a string, but is it possible to write a shorter code?

Requirements:

No input should be processed, and the output should be in the form of 2 3 5 7 11 13 ... etc.
No reserved words in the language are used at all
The language should at least allow structured programming, and have reserved words (otherwise point 2 would be moot).

first I had exclusively C/C++ in mind, but extended the question while still trying to prevent cheating

C, 60 chars

The "no keywords" limitation doesn't matter here. I'm pretty sure that improving it, if possible, won't be done by adding keywords.

n=2;main(m){n<720&&main(m<2?printf("%d ",n),n:n%m?m-1:n++);}

Alternate version:
The output isn't as nice, but I like the printf abuse.

n=2;main(m){n<720&&main(m<2?printf("%*d",n,n):n%m?m-1:n++);}

The trick in both solutions is to merge two loops (implemented by recursion) into one.
n is the next potential prime, m the next potential divisor.
In each recursive call, we either increment n (while setting m to its previous value) or decrement m.


Zero the byte (eventually) Given an infinite arithmetically-progressive¹ sequence, compute the minimum length of a prefix with a product divisible by 2^8.

Sample cases & reference implementation

Here is a reference implementation that I wrote in Io.

  1, 1 -> 10
  2, 4 -> 8
  3, 5 -> 10
  2, 6 -> 5
  7, 5 -> 6
  4, 1 -> 9
 10, 9 -> 7
256, 9 -> 1

Spec

The input will always be provided in a way such that it won't take forever to zero the accumulator.
¹ An arithmetically progressive infinite list can be generated by a constant step each time starting from an initial number.

For the infinite list input, you're are allowed to simply take the initial number and the step of the infinite list.

There are only going to be integers in this sequence.

Examples
1*2*3*4*5*6*7*8*9*10 = 3,628,800
= 14,175*256
2*6*10*14*18*22*26*30 = 518,918,400 = 2,027,025 * 256

Python 2, 39 bytes

f=lambda a,d,p=1:p%256and-~f(a+d,d,p*a)

Try it online!

Tracks the product p of the arithmetic progression until it's divisible by 256.


Monday Mini-Golf #6: Meeesesessess upp teeexexextext Monday Mini-Golf: A series of short code-golf challenges, posted (hopefully!) every Monday.

True story1: The other day, I was playing around on my tablet when I had the idea to visit the page I normally use on my PC for testing JavaScript. After the page loaded, I entered this simple program:

alert("Hello!")

I then proceeded to press the Execute button, and was surprised when it told me that the code I had entered was invalid. I took a second look at the textbox and saw this:

alllelelerlerlertlert("Heeelelellellelloello!")

Wha??? That's not what I entered! So what happened here? To figure it out, I entered two simple lines:

abcdefg
0123456

This turned out as:

abbbcbcbcdbcdbcdebcdebcdefbcdefbcdefgbcdefg
0112123123412345123456

By now, I still had no clue about what happened to letters, but the numbers seemed simpler, so I took a closer look. As it turned out, the webpage was simply entering the first character, then repeating all the rest in the string every time a new one was pressed:

0112123123412345123456
0
 1
  12
    123
       1234
           12345
                123456

But what about the sections of letters? After pondering for a minute, I realized that it's just the same, but instead of repeating each subsection once, it repeats it twice:

abbbcbcbcdbcdbcdebcdebcdefbcdefbcdefgbcdefg
a
 bb
   bcbc
       bcdbcd
             bcdebcde
                     bcdefbcdef
                               bcdefgbcdefg

A combination of the two works with a combination of these techniques:

abc123z
abbbcbcbc1bc12bc123bc123zbc123z
a
 bb
   bcbc
       bc1
          bc12
              bc123
                   bc123zbc123z

Whatever glitch causes this seems to reset at punctuation and spaces, so abc def becomes abbbcbc deeefef.

By this point, I was so absorbed in figuring it out and turning it into an interesting challenge that I forgot why I had been on there in the first place. (I did figure out how to type normally, however: pressing space-backspace after every character. Pretty tedious, but you gotta do what you gotta do.)

Challenge

The goal of the challenge is to write a program or function that takes in the text to be processed, makes the changes listed above, and outputs/returns the result.

Details

The input will only contain printable ASCII, and no tabs or newlines.

Test-cases

Inputs: (one per line)

Mess up text
This is some longer text.
CAPS LOCK && "Punc-tua"+'tion'
under_score_style
CaPs wItHIn loWERs
1337 numb3r5
abcdefghij 0123456789
Code-golf is the best!

Outputs:

Meeesesessess upp teeexexextext
Thhhihihishis iss sooomomomeome looononongongongeongeongeronger teeexexextext.
CAAAPAPAPSAPS LOOOCOCOCKOCK && "Puuunununcunc-tuuuaua"+'tiiioioionion'
unnndndndendendernder_scccococorcorcorecore_stttytytyltyltyletyle
CaaaPaPaPsaPs wIIItItItHItHItHIItHIItHInItHIn loooWoWoWEoWEoWERoWERoWERsoWERs
1333337 nuuumumumbumbumb3umb3rumb3rumb3r5
abbbcbcbcdbcdbcdebcdebcdefbcdefbcdefgbcdefgbcdefghbcdefghbcdefghibcdefghibcdefghijbcdefghij 0112123123412345123456123456712345678123456789
Cooodododeode-gooolololfolf iss thhhehe beeesesestest!

Scoring

This is code-golf, so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. The winner will be chosen next Monday, Nov 2. Good luck!

Edit: And the winner is... @MartinBüttner using Retina for an incredible 43-byte solution!

1 Yes, this story is completely true, and if you need any more clarification, see footnote 1.

Retina, 43 bytes

.(?<=[^_\W]([^_\W]+))(?<=(\1)(?<=\D))?
$1$2

Run the code from a single file with the -s flag. Since this is just a single regex substitution, you can test it here (click the Context tab to see the results).

Explanation

This matches any digit and letter which is not the first in a run. While . can match any non-linefeed character, the lookbehinds ensure the other conditions:

(?<=[^_\W]([^_\W]+))

This matches backwards from the position after the .. First it matches one or more alphanumeric characters and captures them into group 1 with ([^_\W]+). This immediately ensures that the . corresponds to an alphanumeric character itself. Then the additional [^_\W] makes sure that there is one more alphanumeric character in the current run, which we don't include the match. Now group 1 is what we want to replace the match with if it is a digit - if it is a letter we want to replace it with twice this string. That's where the second lookbehind comes into play:

(?<=(\1)(?<=\D))?

This one is optional, so if it fails it won't affect the match at all. It first ensures that the . was not a digit via (?<=\D) - so this lookbehind is only relevant when we're matching letters. In that case, we match group \1 once more (this always matches, because we've captured the group from the same position), but capture it into group 2.

Hence, we simply replace the regex with the contents of both groups ($1$2). If the match was a digit, $2 will still be empty and we write back the prefix only once. If it was a letter, $2 is the same as $1 and we write it back twice.


Gear Train, Rotating Gears transfer different amount of speeds, depending on the size of the meshed gear.

Jack has a machine, that rotates a Gear Train. but you don't know the speed of the last gear.

Luckily, You are a great code golfer, so you can help him!

So, What should I do?

Each gear is represented by 2 numbers, the radius of the inner gear and the radius of the outer gears.

If gear A is [a,b] and gear B is [c,d], then the ratio between the speed of A and the speed of B would be c:b.

Given a list of gears (list of 2-tuples), output the speed of the last gear.

You can assume the speed of the first gear is 1.

Worked out example

Let's say our input is [[6,12],[3,10],[5,8]].

The first gear, [6,12], would have a speed of 1.

Then, the second gear, [3,10], would have a speed of 1*12/3 = 4.

Then, the last gear, [5,8], would have a speed of 4*10/5 = 8.

Testcases

input                    output
[[1,1],[2,2]]            0.5     (1/2)
[[1,2],[1,2],[1,2]]      4       (2/1*2/1)
[[6,12],[3,10],[5,8]]    8       (12/3*10/5)

Rules

Basic code-golf rules apply.

Haskell, 19 bytes

foldr1(/).tail.init

Given a flat list like [a,b,c,d,e,f], tail.init removes the first and last elements, and then foldr1(/) creates a cascade of divisions b/(c/(d/e)))) that works out to alternating * and /: b/c*d/e.


Identifying the triangles Counting the amount of triangles in a picture is a task commonly used in brain tests. You are given a picture that contains shapes consisting of triangles. You then must find all possible triangles in the picture.

Task

You are given a list of lines in a format of your choice. You must then output a list of triangles found in that

Input

You are given a list of lines, each given by four integer coordinates (eg. x1 y1 x2 y2). You may choose the input format, as long as it is clearly documented. Examples:

0 4 8 1
0 4 9 5
8 1 9 5
2 8 0 4
9 5 2 8

[[0, 4, 8, 1], [0, 4, 9, 5], [8, 1, 9, 5], [2, 8, 0, 4], [9, 5, 2, 8]]

Here's the same input as an image:

Another one, with intersections (only in one format to save space):

[[2, 1, 5, 0], [2, 1, 2, 7], [5, 0, 6, 6], [5, 0, 2, 7], [6, 6, 2, 1], [2, 7, 6, 6]]

Output

You must output a list of all triangles, each given by six floating-point coordinates (eg. x1 y1 x2 y2 x3 y3), in the picture specified by the input. These might not be integers, since the lines may cross at any point. You may choose the output format, as long as it is clearly documented. Example outputs for the example inputs above:

0 4 8 1 9 5
0 4 9 5 2 8

[[0, 4, 8, 3, 9, 5], [0, 4, 9, 5, 2, 8]]

[[2, 1, 5, 0, 2, 7], [2, 1, 5, 0, 6, 6], [5, 0, 6, 6, 2, 7], [2, 1, 6, 6, 2, 7], [2, 1, 5, 0, 3.674, 3.093], [5, 0, 6, 6, 3.674, 3.093], [6, 6, 2, 7, 3.674, 3.093], [2, 7, 2, 1, 3.674, 3.093]]

You may assume that

there are no edge cases where a line crosses an intersection but not any lines, like

[[0, 9, 1, 8], [1, 8, 2, 9], [2, 9, 3, 8], [3, 8, 4, 9], [4, 9, 0, 9]]

there are no angles over 179 degrees, like

[[0, 0, 0, 1], [0, 1, 0, 2], [0, 2, 0, 0]]

Rules

You may use any language you want.
No external resources must be used.
Standard loopholes apply.

Scoring

This is code-golf, so the shortest answer in bytes wins.

Mathematica 915 395 401 405
Update
This programming challenge is much more difficult than it first appears to be.
The present approach works with simple cases, where there is but a single intersection along the length of any line segment.  With multiple crossings along one segment, it is necessary to
keep track of all of the intersection points along each line and create new sub-segments (hence additional graph edges) connecting the new intersection to all the intersection points along the target line.
Despite that limitation, it may be worth sharing the logic underlying the current approach.

The input line segments are treated as regions. If they intersect, the centroid will be the coordinates of the intersection.
We need to eliminate those intersections that occur at the vertices of line segments.
Lines that do not intersect will have an indeterminate centroid.
Four new edges are created for each intersection point. They connect the intersection point to the four vertices of the two intersecting lines.
A graph such as the one below on the right is generated using both the old and new edges.
The vertices are the coordinates of the respective points.
Cycles, i.e., closed loops of three vertices will be triangles provided that the three vertices are not collinear.
Presently we check to see whether any "triangle" has an indeterminate area.  (For some reason it does not return an area of 0 for three collinear points.)

A simple example
Below are (a) the figure plotted in the coordinate plane and (b) the graph showing the given nodes as well as the intersection node, {114/23, 314/69}.  In the latter, the vertices are not located at the respective Cartesian coordinates.
It may appear that their are more edges in the right figure than in the left. But remember that there are overlapping graph edges on the left.  Each diagonal actually corresponds to 3 graph edges!

    f@w_ :=(h@{a_, b_, c_, d_} := (r = RegionCentroid@RegionIntersection[Line@{a, b}, Line@{c, d}];
     {r <-> a, r <-> b, r <-> c, r <-> d});
      Cases[FindCycle[Graph[Union@Join[w /. {{a_, b_Integer}, {c_, d_}} :> {a, b} <-> {c, d},
      Cases[Flatten[h /@ Cases[{Length[Union@#] < 4, #} & /@ (FlattenAt[#, {{1}, {2}}] & /@
      Subsets[w, {2}]),{False, c_} :> c]], Except[{Indeterminate, _} <-> _]]]], {3}, 50],
      x_ /; NumericQ[RegionMeasure@Triangle[x[[All, 1]]]]][[All, All, 1]]//N//Grid)

Each row below is a triangle.
f[{{{2,8},{8,1}},{{0,4},{8,1}},{{0,4},{9,5}},{{8,1},{9,5}},{{2,8},{0,4}},{{9,5},{2,8}}}]

A more complex example
f@{{{9, 5}, {0, -10}}, {{9, 5}, {0, 2}},  {{9, 5}, {2, -1}}, {{0, -10}, {2, -1}}, {{0, -10}, {-2, -1}}, {{-9, 5}, {0, -10}}, {{-9, 5}, {0, 2}}, {{-9, 5}, {-2, -1}}, {{0, 2}, {0, -10}}, {{-9, 5}, {2, -1}}, {{9, 5}, {-2, -1}}, {{-9, 5}, {9, 5}}}

Here's the graph corresponding to the input coordinates. The vertices are at their expected Cartesian coordinates. (If you run the golfed code it will display the vertices elsewhere while respecting the vertex labels and edges. For readability, I assigned the vertex coordinates using a smattering of additional code, not necessary for the solution.)

Here's the derived graph.
It includes the derived point of intersection (0,1/11), where some of the input lines cross.

The code found 19 triangles.  Nine of them have the point, (0,1/11) as one of the vertices.


Tips for golfing with numpy, scipy, or pylab There's already a comprehensive list of tips for python here, so what I'm asking for are tips that specifically apply to using the numpy, scipy or pylab libraries.
These can be either ways to shorten code already using numpy, or ways to shorten common python operations by using these libraries.
One tip per answer, please.

Make use of Numpy's broadcasting

Broadcasting means replicating a multidimensional array along some of its singleton dimensions to match the size of another array. This happens automatically for Numpy arrays when arithmetic operators are applied to them.

For example, to generate a 10×10 multiplication table you can use

import numpy
t=numpy.arange(1,11)
print(t*t[:,None]) # Or replace t[:,None] by [*zip(t)]

Try it online!

Here t is created as the Numpy array [1, 2, ..., 10]. This has shape (10,), which is equivalent to (1,10). The other operand array, t[:,None], has size (10,1). Multiplying the two arrays implicitly replicates them, so they behave as if they both had shape (10,10). The result, which also has shape (10,10), contains the products for all pairs of entries in the original arrays.


Finding variables in code Given some code in your language as a string, find and display all the variable names.

Examples in pseudocode:

a=2
b=3
for(i, 0->9) do b=b-10
if a=b then write "a equals b"

Returns: a b i

abcdefgh=20000000000000
bcdifhgs="hello"
if abcdefgh=bcdifhgs then da44="hax"
if abcdefgh*2=da44 then write da44

Returns: abcdefgh bcdifhgs da44

2=3
3=5
5=7
if 2=7 then exit

Returns:

a=2
while True do b=3

Returns: a b

Shortest code wins.

For stack-based languages, display the highest height of the stack.
For memory cell based languages, display all the memory cells that have been changed.

Python 3, 73 66 86

Now follows the updated test cases:

import sys
print(*set(compile(sys.argv[1],'','exec').co_names)-set(dir(__builtins__)))

Note that this also prints the names of non-builtin objects and methods / attributes of objects (e.g. if you use sys.argv in the input code it'll print sys and argv). Still, it does technically fit the test cases.

Assuming we're allowed to simply run the code, it can be done in 66 characters. Note that this fails the while True test case and, unlike the above solution, does not print things like sys and argv:

import sys
print(*(lambda:(exec(sys.argv[1]),set(locals())))()[1])


Improving a Rubik's Cube scrambler's byte count Okay, I recently wrote a Javascript Rubik's Cube scrambler that outputs a 25-move scramble. It's 135 bytes. The Gist is here, but for reference, I have the formatted code:

function(){
  for(a=s=y=r=[],m='RLUDFB',x=Math.random;++a<26;y=r,s.push(r+["'",2,''][0|x()*2]))
  for(;r==y;r=m[0|x()*5]);
  return s.join(' ')
}

Any tips?

EDIT: Code is updated, with @Optimizer's edits.

140 135 127 bytes

Still a big one, but here's for starters:

function(){for(a=s=y=r=[],x=Math.random;a<25;s[a++]=r+["'",2,''][0|x(y=r)*3])for(;r==y;r='RLUDFB'[0|x()*6]);return s.join(' ')}

Some of the few tips used:

Loose the var. There is no point in using var when your aim is to golf!
When a = [], a++ gives 0. We use this fact to remove a 0 and ,
Combine the a<25 and a++
You don't need to split a string. You can access its characters anyways via [i]
Get rid of {} in for loops

More to come.


Tile the plane with squashed hexagons I came across an interesting tiling of the plane using squashed hexagons in a popular math book. All the six edges of the squashed hexagon are the same length. Two opposite corners are right angles and the rest four corners are 135 degrees each. This shape allows four squashed hexagons be arranged so that they meet at a point. Then “concentric rings” of squashed hexagons can outline the resulting cross indefinitely.

Write a full program or a function that accepts an integer 0 < n < 10 and renders n rings of this tessellation. You can rotate the image by 45 dergrees if it's more convenient for your algorithm. You can render directly to the screen, or save the result to a file. In either case, please provide an image demonstrating the the result of your code. You can crop the resulting image so that it contains only the hexagons.

Examples:

n = 1

n = 2

n = 3

n = 4

The shortest code in bytes in each language wins.

JavaScript (ES6), 319 313 bytes

f=
n=>{s=`<svg viewBox=${n*=-12},${n},${n*=-2},${n}><use href=#d transform=rotate(180) /><g id=d><use href=#s transform=rotate(90) /><path id=s fill=none stroke=#000 d=`
for(n/=24;n--;)for(j=0;j<=n;j++)s+=`M${n*5+j*7},${n*12-j*7}h7l5,5v7h-7l-5,-5z`+(j<n?`M${n*12},${n*5-j*10}h7l5,-5l-5,-5h-7l-5,5z`:``)
return s+`>`}
<input type=number min=1 oninput=o.innerHTML=f(this.value)><div id=o>

Output is an HTML5 SVG, which the snippet inserts into a DOM node so that you can see it. Output is rotated by 45° as allowed by the question. Edit: Saved 3 bytes thanks to @KevinCruijssen.


Draw a spiral in a box This geometric spiral looks complicated, but it's fairly simple to draw; take the following box:

Draw a straight line between the corner of the box and some set distance above the next corner counter-clockwise.

Continue this pattern inward, always staying that set distance away from the corner of the next line. Here's a few more lines in.

As you can see, as the pattern continues, the spiral approaches the center and the boxes you draw begin to rotate. Note that the distance remains constant, regardless of angle.

The Challenge

The Inspiration (and also thanks to the wonderful person who introduced me to this concept <3)

Given a numerical (possibly fractional) input from 1 to 25, write an image to disk that uses this pattern or display the output on the screen, where the distance from each corner is the distance of one initial side of the box divided by the input. Continue the pattern inward until the distance from the corner specified is longer than the length of the next side.

Rules

You may not use built-ins for this spiral creation, but you may use image processing builtins.
If you write to disk, you must output an image in any of .jpg, .gif, .tiff, .pbm, .ppm, and .png.
The initial side length must be at least 500 pixels.
The initial corner may be whichever you choose.
As always, the Standard Loopholes are disallowed.

Shoes (Ruby) 163 bytes
Shoes is a ruby-based GUI toolkit.
Shoes.app{n=ask('').to_f
r=s=5E2
a=[0,s*i="i".to_c,s*i+s,s,0]
(q=a[-3]-a[-4]
r=q.abs/s*n
a<<a[-4]+q/r)while r>1
1.upto(a.size-1){|j|line *(a[j-1].rect+a[j].rect)}}

Ungolfed
Shoes.app{
  n=ask('').to_f                 #Open a dialog box with no message, get n from user
  r=s=5E2                        #Initialize s to sidelength=500. r can be initialized to any vale, we use the same one for convenience.
  a=[0,s*i="i".to_c,s*i+s,s,0]   #intialize array a with 5 points needed to draw a square, in complex number format (first point=0 is duplicated.)

  (
    q=a[-3]-a[-4]                #find the vector from point plotted 4 before to the following point (plotted 3 before)
    r=q.abs/s*n                  #r is the scale factor
    a<<a[-4]+q/r                 #add a new point derived from a[-4] by moving toward a[-3] by a distance s/n
  )while r>1                     #break loop when length of line is less than s/n

  1.upto(a.size-1){|j|           #for all points except 1st and last one
    line *(a[j-1].rect+a[j].rect)#take the two complex numbers correspondimg to the current and previous point,
  }                              #convert to 2-element arrays (rectangular coordinates
}                                #combine to make a 4-element array, use * to splat into 4 parameters, and draw using the line method.

Outputs n=4 and n=25

Note that the shape always ends in a triangle, which collapses further to a line. Replacing size-1 with size makes no difference to the appearance of the output and would save 2 bytes, but I left it in for theoretical correctness.
Output n=300
Inspired by a comment by OP, the higher numbers do look great!


There's an ant on my Rubik's Cube A standard, solved, 3×3×3 Rubik's Cube has 6 differently colored faces, where each face is a 3×3 grid of squares of one color. The white face is opposite the yellow, the red opposite orange, the blue opposite green, and when white points upward, red is to the left of blue:

Imagine an ant sits on the center square of the white face, facing the red face. You can give him 3 commands:

Forward (^) - take a step in the direction he's facing to the next grid square, stepping over an edge of the cube if necessary.
Right (>) - rotate to the right (clockwise) by 90°, staying in the same grid square.
Left (<) - rotate to the left (counter-clockwise) by 90°, staying in the same grid square.

Given an arbitrary list of commands, find the colors of the squares that the ant visits (not including the white starting square).

  For example, the command sequence ^^>^^<^^^ has a path that looks
  like this:

  The colors of the grid squares visited in order, not counting the
  starting square, are white red red green green green yellow,
  or just wrrgggy.

Write a program or function that takes in a string of the command characters <^> and prints or returns a string of the characters wyrobg (white, yellow, red orange, blue, green) that corresponds to the ant's path over the cube.

The shortest code in bytes wins. Tiebreaker is earlier answer.

Notes

The cube is in midair and the ant has effective pulvilli, so he can traverse the whole of the cube.
The cube always remains in its solved state.
A square's color is only recorded upon movement into the square, not rotation. The starting white square should not be recorded.
A single optional trailing newline may be present in the input and/or output.

Test Cases

input : output

[empty string] : [empty string]
^ : w
< : [empty string]
> : [empty string]
><><<<>> : [empty string]
>^ : w
<<^> : w
^<^<^<^< : wwww
^^ : wr
<^^ : wb
>><<<<^^ : wo
<^^^<^^^^<>^>^^>^ : wbbboooggyo
^^^^^^^^^^^^^^ : wrrryyyooowwwr
<<<^<^>^<^<^<^>^^^^<^>>>>>^^<^>^^<^>^>^>^>< : wwgrwgggoooobbbbyrby
^^>^^<^^^ : wrrgggy

Perl, 156 143 134 128 127 125 120 119 117 113 109 bytes

Includes +1 for -p

Run with the control string on STDIN, e.g.

perl -p rubic.pl <<< "^^>^^<^^^"

rubic.pl:

@1=wryobg=~/./g;s##$n=w&$&;$y+=$x-=$y+=$x,@1[0,4,2,5,3,1]=@1while--$n%9;@{$n&&--$y%3}[3,0..2]=@1;$1[$n+9]#eg

Explanation

Older version:

@f=gboyrw=~/./g;s##$n=w&$&;$y+=$x-=$y+=$x,@f=@f[2,4,1,3,0,5]while--$n%9;@f=@f[0,$y=1,5,2..4]if$n&&$y--<0;$f[$n+8]#eg

The challenge of this question is to find a coordinate system that makes it easy to track the position and direction of the ant and to still easily get the face identity.

The system I chose was to put standard (x,y) coordinates on the face the ant is on such that the ant is always facing in the negative y direction with the center of the face being (0,0). So:

rotate right: (x',y') <- (-y,  x)
rotate left:  (x',y') <- ( y, -x)  alternatve: 3 right rotations
Step forward:   y' <- y-1

If y was already -1 the ant will leave the current face and step onto the next one. In the new coordinate system there x keeps its value, but y' becomes 1.

This gives an easy coordinate system within a face. I also need something for the faces themselves. There I use an array consisting of

The face to right of the ant            g in the initial position
The face to the left of of the ant      b
The face behind the ant                 o
The face opposite to the ant            y
The face before the ant                 r
The face the ant is on                  w

So the initial array is (g,b,o,y,r,w). Moving to the next face corresponds to rotating the last 4 elements, so moving from white to red makes this (g,b,w,o,y,r). Turning right is a permutation of the first 5 elements giving (o,r,b,y,g,w). Turning left is a simular permutation but can also be done by turning right 3 times, so applying this permutation 3 times. And not turning at all can also be done by applying the permutation 8 times. In fact turning right can also be done by applying the permutation 5 times.

Knowing this the program is rather simple:

@f=gboyrw=~/./g                 Set up the initial face orientation
s## ... #eg                     Process each control string character
                                {this is equivalent to s#.#...#eg because
                                the empty regex repeats the last
                                succesful regex)
$n=w&$&                         Calculate n, the number of right
                                rotations+1 modulo 9.
                                This abuses a coincidence of the control
                                characters:
                                 "<" & "w" = "4" -> 3 right rotations
                                 ">" & "w" = "6" -> 5 right rotations
                                 "^" & "w" = "V" = 0 but that is 9 mod 9
                                 so leads to 8 right rtations

$y+=$x-=$y+=$x,                 This is the same as ($x,$y)=(-$y,$x), so
                                a right rotation of the face coordinates
@f=@f[2,4,1,3,0,5]              Right rotation of the face array
   while --$n%9                 Rotate right n-1 times. After this n=0
                                If this was a step then n was effectively 0.
                                So rotate right 8 times leaving n=-9

    ... if $n                   If a step...
               $y--             ... decrease y ...
             &&$y--<0           ... but if y was already negative ...
@f=@f[0,$y=1,5,2..4]            ... change face and set y to 1

$f[$n+8]                        return the last element (current face)
                                if this was a step, otherwise empty

So for that last statement rotations lead to the empty string and steps forward lead to the current face. Therefore $_ gets replaced by the faces visited on each step.


Convert Brainfuck to another language! The Task

Write the shortest program, that accepts script in brainfuck from STDIN (or equivalent) and outputs to STDOUT (or equivalent) a program written in the SAME language you're using.

For example, if you write in Java, with the input

++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.

The output can be

public class B {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

Brainfuck, 5 bytes
+[,.]

This sentence circumvents the 30 char answer requirement.


Supersonic domino tilings Task

Write a program that reads three integers m, n either from STDIN or as command-line arguments, prints all possible tilings of a rectangle of dimensions m × n by 2 × 1 and 1 × 2 dominos and finally the number of valid tilings.

Dominos of an individual tiling have to be represented by two dashes (-) for 2 × 1 and two vertical bars (|) for 1 × 2 dominos. Each tiling (including the last one) has to be followed by a linefeed.

For scoring purposes, you also have to accept a flag from STDIN or as command line argument that makes your program print only the number of valid tilings, but not the tilings itself.

Your program may not be longer than 1024 bytes. It has to work for all inputs such that m × n ≤ 64.

(Inspired by Print all domino tilings of 4x6 rectangle.)

Example

$ sdt 4 2
----
----

||--
||--

|--|
|--|

--||
--||

||||
||||

5
$ sdt 4 2 scoring
5

Scoring

Your score is determined by the execution time of your program for the input 8 8 with the flag set.

To make this a fastest code rather than a fastest computer challenge, I will run all submissions on my own computer (Intel Core i7-3770, 16 GiB PC3-12800 RAM) to determine the official score.

Please leave detailed instructions on how to compile and/or execute your code. If you require a specific version of your language's compiler/interpreter, make a statement to that effect.

I reserve the right to leave submissions unscored if:

There is no free (as in beer) compiler/interpreter for my operating system (Fedora 21, 64 bits).
Despite our efforts, your code doesn't work and/or produces incorrect output on my computer.
Compilation or execution take longer than an hour.
Your code or the only available compiler/interpreter contain a system call to rm -rf ~ or something equally fishy.

Leaderboard

I've re-scored all submissions, running both compilations and executions in a loop with 10,000 iterations for compilation and between 100 and 10,000 iterations for execution (depending on the speed of the code) and calculating the mean.

These were the results:

User          Compiler   Score                              Approach

jimmy23013    GCC (-O0)    46.11 ms =   1.46 ms + 44.65 ms  O(m*n*2^n) algorithm.
steveverrill  GCC (-O0)    51.76 ms =   5.09 ms + 46.67 ms  Enumeration over 8 x 4.
jimmy23013    GCC (-O1)   208.99 ms = 150.18 ms + 58.81 ms  Enumeration over 8 x 8.
Reto Koradi   GCC (-O2)   271.38 ms = 214.85 ms + 56.53 ms  Enumeration over 8 x 8.


Divide food to the poor equally! The problem

Through a terrible procastination accident you are reborn as Scrooge McDuck for a day. To make the most out of the situation you decide to give away food to the poor. Since you also are a mathematician you store the food in a vector v(1,2,3).

You want to give each family approximately the same food. To make things simple each family has n members.  The task is to write a code to split the vector v into rows of length n where each row has the same amount of ''food''.

Equality is measured by the standard deviation; how different the sum of each row (the food each family receives) is from the mean.

Input

Input should be an integer n and a vector v The length of v does not have to be divisible by n; zero pad it if that is the case.

Example

v = (4, 9, 3, 6, 19, 6, 9, 20, 9, 12, 19, 13, 7, 15)
n = 3

Should return

 4     6    19
 9     9    13
 3    20     7
 6     9    15
19    12     0

The sum of each row is 29,31,30,30,31, so the standard deviation is 0.748331 for n = 2. Note the presence of a 0 that we added.

The output

The code should output the standard deviation. You can also print the matrix but this is not a requirement.

The score

The winner is judged not by the shortest code, but by the sum of the standard deviations, given the test vector and n = 2, 3, and 23. e.g.

Score = your_func(2, foodvec) + your_func(3, foodvec) + your_func(23, foodvec)

Use the following vector to test http://pastebin.com/ybAYGHns and test for n=2,3,23. The final score is the sum of those three tests.
The vector is somewhat big since Scrooge has a lot of food saved up.

Python 3 using PyPy: 6.368014 + 0.701679 + 0.486916 = 7.556608

Optimal for n = 2

There are 1000 numbers, so we want to distribute the food to 500 families. If the food vector is sorted (food[1] >= food[2] >= ... >= food[500]), then the minimal std is reached by giving the first family the food items food[1] and food[500], the second family food[2] and food[499], the third family food[3] and food[498], ...

I thought of a quite easy proof. Basically I expanded the product of the std, removed the terms that appear in each food partition, and proofed that the result is minimal. If someone wants a more detailed explanation, just ask me nice.

Approximation for n > 2

I don't think, that there's a fast way of finding the optimal solution for n > 2.

I start with an heuristic solution. I distribute the food items in sorted (descending) order to the family with the lowest food so far (only to such families, which have received less than n food items).

Afterwards I improve the solution, by swapping 1 food item between a pair of families.
I use the N families with to lowest food and the N families with the most food so far. After all possible swaps, I choose the best swap, and call the local search recursively.

The bigger the value of N is, the lower will be the std (but also the running time will be longer). I used N = 20 and when I can't find swap, I try again with N = 100. PyPy finishes all 3 test cases in less than 8 minutes.

Code

def findSmallestStd(food, n):
    food.sort(reverse=True)
    while len(food) % n:
        food.append(0)
    family_count = len(food) // n

    if n == 2: # optimal
        return list(zip(food[:len(food)//2], reversed(food[len(food)//2:])))
    else: # heuristic approach
        partition = [[] for _ in range(family_count)]
        for food_item in sorted(food, reverse=True):
            partition.sort(key=lambda f: sum(f) if len(f) < n else float('inf'))
            partition[0].append(food_item)
        return local_search(partition, calc_std(partition))

def local_search(partition, best_std, N = 20):
    # find indices with smallest and largest sum
    families1 = nsmallest(N, partition, key=sum)
    families2 = nlargest(N, partition, key=sum)
    best_improved_swap = None

    for family1, family2 in product(families1, families2):
        for index1, index2 in product(range(len(family1)), range(len(family2))):
            family1[index1], family2[index2] = family2[index2], family1[index1]
            std = calc_std(partition)
            if std < best_std:
                best_std = std
                best_improved_swap = (family1, family2, index1, index2)
            family1[index1], family2[index2] = family2[index2], family1[index1]

    if best_improved_swap:
        family1, family2, index1, index2 = best_improved_swap
        family1[index1], family2[index2] = family2[index2], family1[index1]
        partition = local_search(partition, best_std)
    elif N < 100:
        return local_search(partition, best_std, 100)
    return partition

The complete code and the output is available on Github: Code, Output

edit

I was confused about the std-calculation, that N3buchadnezzar proposed in the original question. I updated it to the correct mathematical definition, so we can compare different solutions.

edit 2

In my last submission I varied the family count. E.g. the best solution for n = 2 used 507 families. N3buchadnezzar told me, that there have to be exactly ceil(len(food) / n) families. So I changed my code a little bit. Basically removed the loop over the family counts and improved the local search.


What degree is this palindrome? Your task is to determine the palindromic degree of a given non-empty string.

To do this, loop until one of the following conditions are met:

The string is not a palindrome.
You encounter a string that has already been encountered.

And do the following:

If it is a palindrome, add one to the degree.
Depalindromize.

For example, if I had the string babababab, the calculation would go:

babababab     1
babab         2
bab           3
ba

For the string zzzzz, it would go:

zzzzz         1
zzz           2
zz            3
z             4
z

Test cases

abc 0
cenea 0
pappap 2
aa 2
aba 1
aaa 3
cccc 3
zzzzz 4

Explanation:

abc : 0
cenea : 0
pappap -> pap -> pa : 2
aa -> a -> a : 2
aba -> ab : 1
aaa -> aa -> a -> a: 3
cccc -> cc -> c -> c: 3
zzzzz -> zzz -> zz -> z -> z : 4

Remember, this is code-golf, so the code with the fewest bytes wins.


Optimal solution to go to opposite corner of a rectangle Your job is to write a program that finds the optimal number of moves it takes to get from the lower-left corner of a rectangle to the upper-right corner directly opposite.

Your program will accept input as an ordered pair (width, height). These will be the dimensions of the rectangle you will work with. Your program will create an ASCII-art of the solution (use . for empty square and # for part of the solution, X for starting square) and count the number of moves it takes to reach the endpoint. Diagonal moves are not allowed. If there are multiple solutions, choose one to output.

The shortest program in bytes wins.

Example

Input: (4, 5)

Output:

..##
..#.
.##.
.#..
X#..

Move count: 7

Retina, 54 53 bytes

\d+
$*.
S_`(?<=(.+)¶.*).|\D
T`.`#`.¶|.*$
:m-1=`^#
X
#

Takes input separated by a linefeed and outputs the solution grid followed by the move count.

Try it online!

Explanation

\d+
$*.

Turn both integers into that many .s, i.e. convert them to unary.

S_`(?<=(.+)¶.*).|\D

This builds a grid of .s, by matching each . in the unary height and capturing the unary representation of the width. The S activates split mode which returns the captured strings, and the |\D and _ together ensure that everything else is removed from the string.

T`.`#`.¶|.*$

This turns the last character of each line as well as the entire last line into #s.

:m-1=`^#
X

This uses a ton of options to convert only the first # on the last row to X (we need to make sure that only the last row is affected because of width-1 inputs). m activates multi-line mode which makes ^ match the beginning of lines. -1= tells Retina to perform the substitution only on the last match. Finally, : switches off the default silent mode such that the grid is printed to STDOUT as an intermediate result.

#

Finally, we simply count the number # in the string, which corresponds to the number of moves.


Concatenating n with n + 1 Introduction

OEIS sequence A127421 is the sequence of numbers whose decimal expansion is a concatenation of 2 consecutive increasing non-negative numbers. Put simply, every number in the sequence is formed by putting together n with n+1 for some non-negative, integer value of n. The first several terms are:

  1, 12, 23, 34, 45, 56, 67, 78, 89, 910, 1011, 1112, 1213, 1314, 1415,
  1516, 1617, 1718, 1819, 1920, 2021, 2122, 2223, 2324, 2425, 2526,
  2627, 2728, 2829, 2930, 3031, 3132, 3233, 3334, 3435, 3536, 3637,
  3738, 3839, 3940, 4041, 4142, 4243, 4344, 4445, 4546, …

Challenge

Given a single positive integer n, print the first n entries of OEIS sequence A127421 in increasing order.

Input and output can be in any acceptable format. Strings or numbers are fine for output.
Leading zeroes are not permitted.
Either a full program or function is permitted.
For the purposes of this challenge, n will be positive and under 100.
Standard loopholes are disallowed by default.
This question is code golf, so lowest byte-count wins.
Here is some sample input and output:

1 => 1
2 => 1, 12
3 => 1, 12, 23
10 => 1, 12, 23, 34, 45, 56, 67, 78, 89, 910

If you have any questions, don't hesitate to ask. Good luck.

P.S this is my first challenge, so hopefully this all makes sense.

EDIT: Removed output restriction to allow numbers or strings.

Jelly, 3 bytes

ŻVƝ

A monadic link accepting an integer which yields a list of integers

Try it online!

How?

ŻVƝ - Link: integer       e.g. 59
Ż   - zero-range               [0,1,2,3,4,5,6, ... ,58,59]
  Ɲ - apply to each pair: i.e: [0,1] or [5,6]  or  [58,59]
 V  -   evaluate* jelly code   1     or 56     or  5859
    -                       -> [1,12,23,45,56, ... 5859]

* When given a list V actually joins the Python string values and evaluates that
  ...so e.g.: [58,59] -> ['58','59'] -> '5859' -> 5859


Align a horizontally-aligned, right-angled ASCII shape along a diagonal Your program will receive an ascii shape consisting of only underscores _, pipes |, spaces  and newlines \n, which, together, represent a horizontally-aligned, right-angled shape. Together with this shape, on a new line, you will also receive either a positive or a negative integer, whose absolute value will be either one of 45, 135, 225 or 315 — signifying the degree that the original image should rotate. For instance:

 _
| |_
|___|
-45

Your program's job is to rotate this shape the provided amount of degrees. Following are the example outputs, for all possible degrees, given the above provided example shape:

for 45° or -315°:

 /\
/ /
\ \
 \/

for 135° or -225°:

 /\
/  \
\/\/

for 225° or -135°:

/\
\ \
/ /
\/

for 315° or -45°:

/\/\
\  /
 \/

Remember though: the original shape above is just an example. Your program should be able to handle any shape constructed with said characters (within reason, of course — let's say: with a maximum of 100 x 100 characters).

The output of your program should be the rotated image, constructed with forward slashes /, backward slashes \, spaces and newlines.

Shortest code, after one week, wins.

Note: although this challenge offers many similarities with these [1] [2] two challenges, I think this one offers just enough variation (because the original image is not supposed to be rotated at 90° angles) for it to generate interesting new results.

Python 2 - 285

import sys
l=list(sys.stdin)
L=len;R=range
r=L(l)-2
c=L(max(l,key=L))-2
k=r+c+1
d=int(l[-1])/90%4
a=d/2;x=a^d%2
z=1-x*2;t=1-a*2
m=[k*[' ']for i in R(k)]
for i in R(r+1):
 for j in R(L(l[i])-1):m[a*c+x*r+z*i+t*j][r-a*r+x*c-t*i+z*j]='  \/'[ord(l[i][j])/40^d%2]
for s in m:print''.join(s)

I strongly suspect it can be golfed more, tips are welcome.

Examples:

% python r45.py <<< "||
_____
45"
 /
\ /
 \
  \
   \
    \

% python r45.py <<< " _
| |_
|___|
-45"

    / \
 / \ /
    /
 \ /
  \

If the 2nd one looks misaligned, that's because of some issues with the question:
First, the underscore is at the bottom of the character "cell", while the pipe, slash and backslash are all in the middle. It would be fairer to use a dash (-) instead of underscore.
Second, with the rotation of the heart in the question, you couldn't represent it in any reasonable way if the first line was ___ (3 underscores) instead of
 _, as the 1st and 3rd underscore would be "capping" the pipes in the 2nd line.

Here's a better heart:

% python r45.py <<< " _
| |
|  _
|   |
 ___
-45"

 / \ / \

 \     /
  \   /
   \ /