Polynomial Laplace transform This is a repost of this challenge, intended to revamp it for looser I/O formats and updated rules
You are to write a program which takes an integer polynomial in \$t\$ as input and outputs the Laplace transform of this polynomial. Some definitions and properties:

The Laplace transform of a given function \$f(t)\$ is

$$\mathcal{L}\{f(t)\} = F(s) = \int_0^\infty f(t)e^{-st}dt$$

The Laplace transform of \$f(t) = t^n, \, n = 0, 1, 2, ...\$ is

$$\mathcal{L}\{t^n\} =  \frac{n!}{s^{n+1}}$$

Laplace transforms distribute over addition:

$$\mathcal{L}\{f(t)+g(t)\} = \mathcal{L}\{f(t)\} + \mathcal{L}\{g(t)\}$$

The Laplace transform of a constant multiplied by a function equals the constant multiplied by the transform:

$$\mathcal{L}\{af(t)\} = a\mathcal{L}\{f(t)\}$$

An integer polynomial is a polynomial where each term has an integer coefficient, and a non-negative order

An worked example:
$$\begin{align}
\mathcal{L}\{3t^4+2t^2+t-4\} & = \mathcal{L}\{3t^4\}+\mathcal{L}\{2t^2\}+\mathcal{L}\{t\}-\mathcal{L}\{4\} \\
& = 3\mathcal{L}\{t^4\}+2\mathcal{L}\{t^2\}+\mathcal{L}\{t\}-4\mathcal{L}\{1\} \\
& = 3\left(\frac{4!}{s^5}\right)+2\left(\frac{2!}{s^3}\right)+\left(\frac{1!}{s^2}\right)-4\left(\frac{0!}{s}\right) \\
& = \frac{72}{s^5}+\frac{4}{s^3}+\frac{1}{s^2}-\frac{4}{s}
\end{align}$$

You may take input in a standard representation of a polynomial. Some examples (for \$3x^4+2x^2+x-4\$ as an example) are:

A list of coefficients. [-4, 1, 2, 0, 3] or  [3, 0, 2, 1, -4]
Pairs of coefficients and powers. [[3, 4], [2, 2], [1, 1], [-4, 0]] and various different orderings
A string, using whatever variable you like. 3x^4+2x^2+x-4

Similarly, as the output will be a polynomial with negative orders, you may output in similar formats, such as (using \$\mathcal{L}\{3x^4+2x^2+x-4\} = \frac{72}{s^5}+\frac4{s^3}+\frac1{s^2}-\frac4s\$):

A list of coefficients. [72, 0, 4, 1, -4] or [-4, 1, 4, 0, 72]
Pairs of coefficients and powers. [[72, -5], [4, -3], [1, -2], [-4, -1]] and various different orderings (or the positive versions of the powers)
A string, using whatever variable you like. 72s^-5+4s^-3+s^-2-4s^-1

If you have an alternative I/O method you're unsure about, please comment below to ask.
This is code-golf so the shortest code in bytes wins.

Haskell, 25 bytes

zipWith(*)$scanl(*)1[1..]

Try it online!
Pretty straightforward: Generates the list of factorials [1,1,2,6,...] with a scanl, then does zipWith(*) to multiply each element of the input by the corresponding value.
32 bytes

foldr(\(i,x)r->x:map((i+1)*)r)[]

Try it online!
A pretty folding-based solution. Takes inputs as (exponent, coefficient) pairs.


Sum of (at most) 5 primes Terence Tao recently proved a weak form of Goldbach's conjecture!  Let's exploit it!

Given an odd integer n > 1, write n as a sum of up to 5 primes.  Take the input however you like, and give output however you like.  For example,

def g(o):
    for l in prime_range(o+1):
        if l == o:
            return l,
        for d in prime_range(l+1):
            for b in prime_range(d+1):
                if l+d+b == o:
                    return l,d,b
                for c in prime_range(b+1):
                    for h in prime_range(c+1):
                        if l+d+b+c+h == o:
                            return l,d,b,c,h

is Sage code that takes an integer as input, and returns a list of integers as output whose sum is n.  By Tao's theorem, this will always terminate!

Input

An odd integer n.  You decide how to take the input, but if it's weird, explain it.

Output

Rather open-ended.  Return a list.  Print a string.  Gimme one, a few, or all.  Leave crap lying around on the stack (GS, Piet, etc) or in a consecutive (reachable) memory block (BF, etc) in a predictable manner.  For these later cases, explain the output.  In all cases, what you return / print / whathaveyou should be a straightforward representation of a partition of n into primes with fewer than 6 parts.

Scoring

This is code golf, smallest byte count wins.

Bonus! if the word 'goldbach' appears as a subsequence (not necessarily consecutive; just in order. Case doesn't matter) of your program subtract 8 points.  The code above is an example of this.

Mathematica, 38

IntegerPartitions[n,5,Prime~Array~n,1]


Log Scales are for Quitters Everyone knows log scales are for quitters. Therefore, you must write a program or function that de-quitifies a bar graph with a log scale given a base.

The bar graph input is taken as a single string which is a list of bars, where each bar of the log scale bar graph is separated by the printable (or whitespace) delimiter of your choosing (so 0x09-0x0A + 0x20-0x7E) and composed of a printable non-whitespace (so 0x21-0x7E) filler character of your choosing.

The program or function outputs a single string which is a list of bars, where each bar is separated by the same delimiter the input was separated by and is composed of the same filler character the input was composed of.

Example

We choose a delimiter of "\n" (one newline) and a filler character of "#".
The input passed to our program or function is:

base=2
and
string=

####
##
######
###

The code would find that the lengths of the bars are [4,2,6,3]. It would compute the anti-log of each length with base 2 to get [2^4,2^2,2^6,2^3] = [16,4,64,8]. Then, the lengths are output in linear scale bar format:

################
####
################################################################
########

Input / Output

Your program or function may input and output in any reasonable format.

The input base is guaranteed to be an integer greater than 1. You may assume the base is less than 256.
The string input is guaranteed to fully match the regex (f+s)+f+, where f and s are replaced with your filler and delimiter respectively.

The string output must fully match the regex (f+s)+f+, where f and s are replaced with the same filler and delimiter respectively. The output may optionally have a trailing newline.

The output and input may also be a list of strings instead of delimited by a substring, though it must be possible to understand which bar is which.

Testcases

(assume filler is # and delimiter is \n)

base
-
input string
-
output string
-----
2
-
####
##
######
###
-
################
####
################################################################
########
-----
3
-
##
#
###
#
-
#########
###
###########################
###
-----
100
-
#   I am not the delimiter
###  nor the filler
-
Anything (You do not have to handle input which does not match the regex)
-----
1
-
###
#######
###################################################
-
Anything (You do not have to handle bases less than or equal to 1).
-----
5
-
####
##
###
#
-
#################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
#########################
#############################################################################################################################
#####
-----
2
-
#
#
##
##
#
##
#
#
#
#
##
##
#
#
##
#
-
##
##
####
####
##
####
##
##
##
##
####
####
##
##
####
##

x86 32-bit machine code function, 21 bytes

x86-64 machine code function, 22 bytes

The 1B saving in 32-bit mode requires using separator = filler-1, e.g. fill=0 and sep=/.  The 22-byte version can use an arbitrary choice of separator and filler.

This is the 21-byte version, with input-separator = \n (0xa), output-filler = 0, output-separator = / = filler-1.  These constants can be easily changed.

; see the source for more comments
; RDI points to the output buffer,  RSI points to the src string
; EDX holds the base
; This is the 32-bit version.
; The 64-bit version is the same, but the DEC is one byte longer (or we can just mov al,output_separator)
08048080 <str_exp>:
 8048080:       6a 01           push   0x1
 8048082:       59              pop    ecx           ; ecx = 1 = base**0
 8048083:       ac                      lods   al,BYTE PTR ds:[esi]  ; skip the first char so we don't do too many multiplies

; read an input row and accumulate base**n as we go.
08048084 <str_exp.read_bar>:
 8048084:       0f af ca        imul   ecx,edx       ; accumulate the exponential
 8048087:       ac              lods   al,BYTE PTR ds:[esi]
 8048088:       3c 0a           cmp    al,0xa        ; input_separator = newline
 804808a:       77 f8           ja     8048084 <str_exp.read_bar>
 ; AL = separator or terminator
 ; flags = below (CF=1) or equal (ZF=1).  Equal also implies CF=0 in this case.

 ; store the output row
 804808c:       b0 30           mov    al,0x30       ; output_filler
 804808e:       f3 aa           rep stos BYTE PTR es:[edi],al  ; ecx bytes of filler
 8048090:       48              dec    eax           ; mov al,output_separator
 8048091:       aa              stos   BYTE PTR es:[edi],al  ;append delim

 ; CF still set from the inner loop, even after DEC clobbers the other flags
 8048092:       73 ec           jnc    8048080 <str_exp>  ; new row if this is a separator, not terminator

 8048094:       c3              ret

08048095  <end_of_function>
; 0x95 - 0x80 = 0x15 = 21 bytes

The 64-bit version is 1 byte longer, using a 2-byte DEC or a mov al, output_separator.  Other than that, the machine-code is the same for both versions, but some register names change (e.g. rcx instead of ecx in the pop).

Sample output from running the test program (base 3):

$ ./string-exponential $'.\n..\n...\n....' $(seq 3);echo
000/000000000/000000000000000000000000000/000000000000000000000000000000000000000000000000000000000000000000000000000000000/

Algorithm:

Loop over the input, doing exp *= base for every filler char.  On delimiters and the terminating zero byte, append exp bytes of filler and then a separator to the output string and reset to exp=1.  It's very convenient that the input is guaranteed not to end with both a newline and a terminator.

On input, any byte value above the separator (unsigned compare) is treated as filler, and any byte value below the separator is treated as an end-of-string marker.  (Checking explicitly for a zero-byte would take an extra test al,al vs. branching on flags set by the inner loop).

The rules only allow a trailing separator when it's a trailing newline.  My implementation always appends the separator.  To get the 1B saving in 32-bit mode, that rule requires separator = 0xa ('\n' ASCII LF = linefeed), filler = 0xb ('\v' ASCII VT = vertical tab).  That's not very human-friendly, but satisfies the letter of the law.  (You can hexdump or
tr $'\v' x the output to verify that it works, or change the constant so the output separator and filler are printable.  I also noticed that the rules seem to require that it can accept input with the same fill/sep it uses for output, but I don't see anything to gain from breaking that rule.).

NASM/YASM source.  Build as 32 or 64-bit code, using the %if stuff included with the test program or just change rcx to ecx.

input_separator equ 0xa  ; `\n` in NASM syntax, but YASM doesn't do C-style escapes

output_filler equ '0'                 ; For strict rules-compliance, needs to be input_separator+1
output_separator equ output_filler-1  ; saves 1B in 32-bit vs. an arbitrary choice
    ;; Using output_filler+1 is also possible, but isn't compatible with using the same filler and separator for input and output.

global str_exp
str_exp:                        ; void str_exp(char *out /*rdi*/, const char *src /*rsi*/,
                                ;              unsigned base /*edx*/);
.new_row:
    push   1
    pop    rcx                  ; ecx=1 = base**0

    lodsb                       ; Skip the first char, since we multiply for the separator
.read_bar:
    imul   ecx, edx             ; accumulate the exponential
    lodsb
    cmp    al, input_separator
    ja .read_bar                ; anything > separator is treated as filler
    ; AL = separator or terminator
    ; flags = below (CF=1) or equal (ZF=1).  Equal also implies CF=0, since x-x doesn't produce carry.

    mov    al, output_filler
    rep stosb                   ; append ecx bytes of filler to the output string
%if output_separator == output_filler-1
    dec   eax         ; saves 1B in the 32-bit version.  Use dec even in 64-bit for easier testing
%else
    mov    al, output_separator
%endif
    stosb                       ; append the delimiter

    ; CF is still set from the .read_bar loop, even if DEC clobbered the other flags
    ; JNC/JNB here is equivalent to JE on the original flags, because we can only be here if the char was below-or-equal the separator
    jnc .new_row            ; separator means more rows, else it's a terminator
    ; (f+s)+f+ full-match guarantees that the input doesn't end with separator + terminator
    ret

The function follows the x86-64 SystemV ABI, with signature
void str_exp(char *out /*rdi*/, const char *src /*rsi*/, unsigned base /*edx*/);
It only informs the caller of the length of the output string by leaving a one-past-the-end pointer to it in rdi, so you could consider this the return value in a non-standard calling convention.

It would cost 1 or 2 bytes (xchg eax,edi) to return the end-pointer in eax or rax.  (If using the x32 ABI, pointers are guaranteed to be only 32 bits, otherwise we have to use xchg rax,rdi in case the caller passes a pointer to a buffer outside the low 32 bits.)  I didn't include this in the version I'm posting because there are workarounds the caller can use without getting the value from rdi, so you could call this from C with no wrapper.

We don't even null-terminate the output string or anything, so it's only newline-terminated.  It would take 2 bytes to fix that: xchg eax,ecx / stosb  (rcx is zero from rep stosb.)

The ways to find out the output-string length are:

rdi points to one-past-the-end of the string on return (so the caller can do len=end-start)
the caller can just know how many rows were in the input and count newlines
the caller can use a large zeroed buffer and strlen() afterwards.

They're not pretty or efficient (except for using the RDI return value from an asm caller), but if you want that then don't call golfed asm functions from C. :P

Size/range limitations

The max output string size is only limited by virtual memory address-space limitations.  (Mainly that current x86-64 hardware only supports 48 significant bits in virtual addresses, split in half because they sign-extend instead of zero-extend.  See the diagram in the linked answer.)

Each row can only have a maximum of 2**32 - 1 filler bytes, since I accumulate the exponential in a 32-bit register.

The function works correctly for bases from 0 to 2**32 - 1.  (Correct for base 0 is 0^x = 0, i.e. just blank lines with no filler bytes.  Correct for base 1 is 1^x = 1, so always 1 filler per line.)

It's also blazingly fast on Intel IvyBridge and later, especially for large rows being written to aligned memory.  rep stosb is an optimal implementation of memset() for large counts with aligned pointers on CPUs with the ERMSB feature.  e.g. 180**4 is 0.97GB, and takes 0.27 seconds on my i7-6700k Skylake (with ~256k soft page-faults) to write to /dev/null.  (On Linux the device-driver for /dev/null doesn't copy the data anywhere, it just returns.  So all of the time is in the rep stosb and the soft page-faults that triggers when touching the memory for the first time.  It's unfortunately not using transparent hugepages for the array in the BSS.  Probably an madvise() system call would speed it up.)

Test program:

Build a static binary and run as ./string-exponential $'#\n##\n###' $(seq 2) for base 2.  To avoid implementing an atoi, it uses base = argc-2.  (Command-line length limits prevent testing ridiculously large bases.)

This wrapper works for output strings up to 1 GB.  (It only makes a single write() system call even for gigantic strings, but Linux supports this even for writing to pipes).  For counting characters, either pipe into wc -c or use strace ./foo ... > /dev/null to see the arg to the write syscall.

This takes advantage of the RDI return-value to calculate the string length as an arg for write().

;;; Test program that calls it
;;; Assembles correctly for either x86-64 or i386, using the following %if stuff.
;;; This block of macro-stuff also lets us build the function itself as 32 or 64-bit with no source changes.

%ifidn __OUTPUT_FORMAT__, elf64
%define CPUMODE 64
%define STACKWIDTH 8    ; push / pop 8 bytes
%define PTRWIDTH 8
%elifidn __OUTPUT_FORMAT__, elfx32
%define CPUMODE 64
%define STACKWIDTH 8    ; push / pop 8 bytes
%define PTRWIDTH 4
%else
%define CPUMODE 32
%define STACKWIDTH 4    ; push / pop 4 bytes
%define PTRWIDTH 4
%define rcx ecx      ; Use the 32-bit names everywhere, even in addressing modes and push/pop, for 32-bit code
%define rsi esi
%define rdi edi
%define rsp esp
%endif

global _start
_start:
    mov  rsi, [rsp+PTRWIDTH + PTRWIDTH*1]  ; rsi = argv[1]
    mov  edx, [rsp]          ; base = argc
    sub  edx, 2              ; base = argc-2  (so it's possible to test base=0 and base=1, and so ./foo $'xxx\nxx\nx' $(seq 2) has the actual base in the arg to seq)
    mov  edi, outbuf         ; output buffer.  static data is in the low 2G of address space, so 32-bit mov is fine.  This part isn't golfed, though

    call str_exp             ; str_exp(outbuf, argv[1], argc-2)
    ;  leaves RDI pointing to one-past-the-end of the string
    mov  esi, outbuf

    mov  edx, edi
    sub  edx, esi               ; length = end - start

%if CPUMODE == 64 ; use the x86-64 ABI
    mov  edi, 1                 ; fd=1 (stdout)
    mov  eax, 1                 ; SYS_write  (Linux x86-64 ABI, from /usr/include/asm/unistd_64.h)
    syscall                     ; write(1, outbuf, length);

    xor edi,edi
    mov eax,231   ; exit_group(0)
    syscall

%else  ; Use the i386 32-bit ABI (with legacy int 0x80 instead of sysenter for convenience)
    mov ebx, 1
    mov eax, 4                  ; SYS_write (Linux i386 ABI, from /usr/include/asm/unistd_32.h)
    mov ecx, esi  ; outbuf
    ; 3rd arg goes in edx for both ABIs, conveniently enough
    int 0x80                    ; write(1, outbuf, length)

    xor ebx,ebx
    mov eax, 1
    int 0x80     ; 32-bit ABI _exit(0)
%endif

section .bss
align 2*1024*1024 ; hugepage alignment (32-bit uses 4M hugepages, but whatever)
outbuf:    resb 1024*1024*1024 * 1
; 2GB of code+data is the limit for the default 64-bit code model.
; But with -m32, a 2GB bss doesn't get mapped, so we segfault.  1GB is plenty anyway.

This was a fun challenge that lent itself very well to asm, especially x86 string ops.  The rules are nicely designed to avoid having to handle a newline and then a terminator at the end of the input string.

An exponential with repeated multiplication is just like multiplying with repeated addition, and I needed to loop to count chars in each input row anyway.

I considered using one-operand mul or imul instead of the longer imul r,r, but its implicit use of EAX would conflict with LODSB.

I also tried SCASB instead of load and compare, but I needed xchg esi,edi before and after the inner loop, because SCASB and STOSB both use EDI.  (So the 64-bit version has to use the x32 ABI to avoid truncating 64-bit pointers).

Avoiding STOSB is not an option; nothing else is anywhere near as short.  And half the benefit of using SCASB is that AL=filler after leaving the inner loop, so we don't need any setup for REP STOSB.

SCASB compares in the other direction from what I had been doing, so I needed to reverse the comparisons.

My best attempt with xchg and scasb.  Works, but isn't shorter.  (32-bit code, using the inc/dec trick to change filler into separator).

; SCASB version, 24 bytes.  Also experimenting with a different loop structure for the inner loop, but all these ideas are break-even at best
; Using separator = filler+1 instead of filler-1 was necessary to distinguish separator from terminator from just CF.

input_filler equ '.'    ; bytes below this -> terminator.  Bytes above this -> separator
output_filler equ input_filler       ; implicit
output_separator equ input_filler+1  ; ('/') implicit

 8048080:       89 d1                   mov    ecx,edx    ; ecx=base**1
 8048082:       b0 2e                   mov    al,0x2e    ; input_filler= .
 8048084:       87 fe                   xchg   esi,edi
 8048086:       ae                      scas   al,BYTE PTR es:[edi]

08048087 <str_exp.read_bar>:
 8048087:       ae                      scas   al,BYTE PTR es:[edi]
 8048088:       75 05                   jne    804808f <str_exp.bar_end>
 804808a:       0f af ca                imul   ecx,edx           ; exit the loop before multiplying for non-filler
 804808d:       eb f8                   jmp    8048087 <str_exp.read_bar>   ; The other loop structure (ending with the conditional) would work with SCASB, too.  Just showing this for variety.
0804808f <str_exp.bar_end>:

; flags = below if CF=1 (filler<separator),  above if CF=0 (filler<terminator)
; (CF=0 is the AE condition, but we can't be here on equal)
; So CF is enough info to distinguish separator from terminator if we clobber ZF with INC

; AL = input_filler = output_filler
 804808f:       87 fe                   xchg   esi,edi
 8048091:       f3 aa                   rep stos BYTE PTR es:[edi],al
 8048093:       40                      inc    eax         ; output_separator
 8048094:       aa                      stos   BYTE PTR es:[edi],al
 8048095:       72 e9                   jc     8048080 <str_exp>   ; CF is still set from the inner loop
 8048097:       c3                      ret

For an input of ../.../., produces ..../......../../.  I'm not going to bother showing a hexdump of the version with separator=newline.


Shortest Pong, AI vs AI Your task is to write the shortest possible Pong game without human interaction, so AI plays vs AI. I assume all of you know Pong, just to make sure, this is the target (just as running code):http://www.youtube.com/watch?v=xeEFMhdnR6c

The following game rules apply:

No ASCII "graphics".
You must actually have code to count the scores, even if the AI never scores.
It must be possible to adjust the size of the output window/area in some way to any (reasonable) size. Which means you must include some form of output scaling.
No need for a menu or other features of the game, just what's in the video.

The following play fair rules apply as well:

No language specifically designed for code golfing.
You may only use standard libraries offered by the language of your choice. No external library downloading, no jQuery, no full-sized game-libraries.
Exception: if no library for graphical output is available with the default offering of the language of your choice, you are allowed to use a library that offers basic graphical output similar to what other languages include in their basic library set.
import statements (or however they are called in your language) can be skipped in the character count.
Doorknob-rule: The paddles may not be bigger than 15% of the game area.

Bonus points:

-50 if you include sound. External sound sources (e.g. wav) do not need to be added to the char count and may be downloaded during execution. If you choose to copy & paste the data into the code, only the actual data is allowed to be skipped for character count.
Another -150 (for -200 total) if you do not use external sounds but generate it. Generate means: you have some form of sound synthesizing, copy & pasting e.g. wav data does not count.

Pure HTML and CSS, 355 characters

0-0

You may need an up-to-date or beta browser for the CSS animation properties.

Here is a fiddle, with -webkit- vendor prefixes added so that it works in latest Chrome.

The ball just bounces back and forth. The AIs are extremely smart and know not to move.

The 0-0 at the bottom is the score, and you can resize the window.


Not so good roads in Rnccia Here in the absolutely made up country Rnccia we have a lot of good stuff, but the roads aren't good. There are lots of holes and only half of them get fixed. Even then, only half of the fixes are well done. Your task is to embrace the bad roads of this country and draw them for me.

Input

You receive two positive integers as input. One represents the length of the road, and the second represents the number of lanes in each direction. The length of the road is guaranteed to be an even number.

Output

Output or return an ASCII-art image of the road with as many holes as will fit. Read the next two sections to see how the road and holes should be generated.

Road layout

Every road has a straight line of minuses(-) above and below it.
Every road has the same number of lanes in both directions.
Every road has a line of equal signs(=) down the middle.
Lanes have dashed lines between them (excep the special middle line from rule #3). One minus, one whitespace and so on. Starting with the minus.

Examples of roads:

Road with one lane in both sides:

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

==============

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

Road with two lanes in both sides:

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

- - - - - - -

==============

- - - - - - -

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

Hole layout

Every road has 7n total holes. n is the ceiling of the number of holes that will fit on the road divided by seven.
Every road has 4n unfixed holes. An unfixed hole is represented as double O (OO).
Every road has 2n holes that are fixed and represented as double # (##).
Every road also has n holes that are fixed well and represented as double H (HH).
Holes (in any state) appear on every lane in diagonal pattern, starting at the top right and moving down-across. A new line of holes should start in every 4th lane and every 8 characters in the top lane. See the examples for clarification.
The order of holes is irrelevant.
If 7n holes can't fit in road of given length, you may use #6 to choose which of the holes will not be visible.

In this example we have 14 holes, 4 of which are fixed poorly, and 2 which are fixed well:

------------------
OO      HH      OO
- - - - - - - - -
  ##      OO
- - - - - - - - -
    ##      OO
==================
      OO      OO
- - - - - - - - -
OO      ##      HH
- - - - - - - - -
  ##      OO
------------------

In this example we hava 9 holes, which is not multiple of 7. So your pool of holes to use is size 14 with 8 (OO), 4(##), 2(HH). You may use any holes from it to fill road.

------------------
OO  OO  OO  OO  OO
==================
  OO  OO  OO  ##
------------------

Another corner example. Road can have only 3 holes. So pool is 7: 4(OO), 2(##), 1(HH). Again, any can be used:

------
##
- - -
  ##
======
    HH
- - -

------

Other rules

You may change the appearance of holes to two of any other character, except -, = and whitespace. Just mention it in your answer.
It's code-golf, so make your code as compact as possible.

Python 2, 229 213 204 200 188 bytes

lambda n,l:"\n".join(["-"*l]+[i%2and"".join(j-i/2&1+2*(n>1)and"  "or x.append(1)or"H0000##"[len(x)%7]*2for j in range(l/2))or((i-n*2and"- "or"=")*l)[:l]for i in range(1,n*4)]+["-"*l])
x=[]

Try it online!

My longest codegolf answer so far


Self-compiling compiler This is based on a talk on compilers I listened to a while back, but I, unfortunately, can't remember when or where.

Create the shortest compiler in any language that can compile itself.  Target any reasonable ISA (68K, x86, MIPS, ARM, SPARC, IBM BAL, etc.) that doesn't have a "compile-program" instruction (this may exclude some versions of VAX).  Read source programs from stdin and print generated code to stdout.  You may use the standard C library for I/O and string processing (e.g., _printf).  You don't need to compile the whole language, just any subset that contains the compiler (i.e., just printing an assembly language quine, while impressive, does not count as a solution.)

Haskell subset → C - 18926 characters

This compiles a small subset of Haskell to C.  Features it supports:

Pattern matching and guards
Data declarations
Select infix operators
Lazy evaluation

The biggest missing features are nested variables (meaning no lambda/let/where/case), type checking, and type classes.  Resulting programs leak memory, and self-compilation takes about 200 megabytes on my system (the Boehm garbage collector helps a lot, but only if the compiler optimizes tail recursion well).

To bootstrap, uncomment the first three lines (not counted in the score) and compile with GHC.  The compiler takes Haskell-subset code on stdin and produces C code on stdout.

It's long not because the language is complex, but because I'm lazy.  However, it's currently the shortest solution  Not anymore.  Guess I won't be bored this weekend.

-- import Prelude hiding (fmap, lookup, snd, zip);import Data.Char
-- import Data.List hiding (lookup, zip);data P a b = P a b;data B = B
-- add=(+);sub=(-);showInt=show;append[]ys=ys;append(x:xs)ys=x:append xs ys
data Program = Program [[Constructor]] [Function]
data Toplevel = TD [Constructor] | TE Equation | TO
data Constructor = Constructor String Int
data Function = Function String Int [Equation]
data Equation = Equation String [Pattern] (Maybe Expression) Expression
data Pattern = PVar String | PCon String [Pattern]
data Expression = Var String | Con String | Int String | Char String | String String | Ap Expression Expression
data Environment = Environment [P String Int] [P String VarInfo]
data VarInfo = VBox String | VArg Int | VItem VarInfo Int
main = interact (compile . parse)
constructorName (Constructor name _) = name
functionName (Function name _ _) = name
equationName (Equation name _ _ _) = name
sortToplevels [] = (P [] [])
sortToplevels (TD x : xs) = applyFst ((:) x) (sortToplevels xs)
sortToplevels (TE x : xs) = applySnd ((:) x) (sortToplevels xs)
sortToplevels (TO : xs)   = sortToplevels xs
pcons x xs = PCon "Cons" [x, xs];pnil = PCon "Nil" []
ebinary op a b = Ap (Ap (Var op) a) b;ebinaryE op a b = Ap (Ap op a) b
econs x xs = Ap (Ap (Con "Cons") x) xs
enil = Con "Nil"
listEq eq [] [] = True
listEq eq (x:xs) (y:ys) | eq x y = listEq eq xs ys
listEq _ _ _ = False
snd (P a b) = b
zip = zipWith P
lookup q (P k v : _)  | listEq (==) q k = Just v
lookup q (_     : xs)                   = lookup q xs
lookup q _                              = Nothing
compose2 f g x y = f (g x y)
applyFst f (P x y) = P (f x) y
applySnd f (P x y) = P x (f y)
fMaybe f Nothing  = Nothing
fMaybe f (Just x) = Just (f x)
cond f t False = f
cond f t True = t
condList f t [] = f
condList f t xs = t xs
countFrom n = n : countFrom (add n 1)
range l h | l > h = []
range l h         = l : range (add l 1) h
parse = makeProgram . sortToplevels . concatMap parse_p . ((:) prelude) . preprocess
parse_p (P lineno line) = maybe (parse_err lineno line) snd (parseLine line)
parse_err lineno line = error (concat ["Parse error on line ", showInt lineno, ": `", line, "`"])
preprocess = filter (not . isCommentOrEmpty . snd) . zip (countFrom 1) . map (dropWhile isBlank) . lines
isCommentOrEmpty = parserSucceeds (pro (ignore (pro (parseS "--") (parseS "import "))) parseEof)
liftA2 f a b = ap (fmap f a) b
parserSucceeds p s = maybe False (const True) (p s)
fmap f p = fMaybe (applySnd f) . p
pure x s = Just (P s x)
ap1 b (P s x) = maybe Nothing (ap2 x) (b s)
ap2 x (P s y) = Just (P s (x y))
empty = (const Nothing)
pro a b s = maybe (b s) Just (a s)
ap a b = maybe Nothing (ap1 b) . a
prc = liftA2 (:)
pra = liftA2 append
prl = liftA2 const
prr = liftA2 (const id)
many p = pro (some p) (pure [])
some p = prc p (many p)
optional p = pro (fmap Just p) (pure Nothing)
choice = foldr pro (const Nothing)
parseEof = parseEof_1
parseEof_1 [] = Just (P "" B)
parseEof_1 _  = Nothing
parsePred pred = parsePred_1 pred
parsePred_1 pred (x:xs) | pred x = Just (P xs x)
parsePred_1 _    _               = Nothing
manyParsePred = justFlipSplit
justFlipSplit pred xs = Just (P (dropWhile pred xs) (takeWhile pred xs))
someParsePred pred = prc (parsePred pred) (manyParsePred pred)
parseC = parsePred . (==)
parseS = foldr (prc . parseC) (pure [])
wrapC = wrapSpace . parseC
wrapS = wrapSpace . parseS
skipPred pred = prr (parsePred pred) (pure B)
manySkipPred pred = prr (manyParsePred pred) (pure B)
preSep p sep = many (prr sep p)
sepBy1 p sep = prc p (many (prr sep p))
sepByChar p c = pro (sepByChar1 p c) (pure [])
sepByChar1 p c = sepBy1 p (wrapSpace (parseC c))
wrapSpace p = prl (prr skipSpace p) skipSpace
ignore = fmap (const B)
isBlank c | c == ' ' || c == '\t' = True
isBlank _                         = False
isDigit1 c = c >= '1' && c <= '9'
parseBetween l r p = prl (prr (parseC l) (wrapSpace p)) (parseC r)
skipSpace = manySkipPred isBlank
chainl1 f sep p = fmap (foldl1 f) (sepBy1 p sep)
chainr1 f sep p = fmap (foldr1 f) (sepBy1 p sep)
chainl f z sep p = pro (fmap (foldl f z) (sepBy1 p sep)) (pure z)
chainr f z sep p = pro (fmap (foldr f z) (sepBy1 p sep)) (pure z)
parseNonassoc ops term = liftA2 (flip ($)) term (pro (liftA2 flip (choice ops) term) (pure id))
parseVar = prc (parsePred (orUnderscore isLower)) (many (parsePred (orUnderscore isAlphaNum)))
orUnderscore p c | p c || c == '_' = True
orUnderscore _ _ = False
parseCon = prc (parsePred isUpper) (many (parsePred (orUnderscore isAlphaNum)))
parseInt = pro (parseS "0") (prc (parsePred isDigit1) (many (parsePred isDigit)))
parseEscape q (c:x:xs) | c == '\\' = Just (P xs (c:x:[]))
parseEscape q [c]      | c == '\\' = Just (P [] [c])
parseEscape q (c:xs)   | c /= q    = Just (P xs [c])
parseEscape q _                    = Nothing
parseStringLiteral q = pra (parseS [q]) (pra (fmap concat (many (parseEscape q))) (parseS [q]))
parsePattern = chainr1 pcons (wrapC ':') (pro (liftA2 PCon parseCon (preSep parsePatternPrimary skipSpace)) parsePatternPrimary)
parsePatternPrimary = choice [fmap PVar parseVar, fmap (flip PCon []) parseCon, parseBetween '(' ')' parsePattern, parseBetween '[' ']' (fmap (foldr pcons pnil) (sepByChar parsePattern ','))]
relops f = relops_1 (ops_c f)
otherops f = f ":" (Con "Cons") : otherops_1 (ops_c f)
ops_c f x y = f x (Var y)
relops_1 f   = [f "<=" "_le", f "<" "_lt", f "==" "_eq", f ">=" "_ge", f ">" "_gt", f "/=" "_ne"]
otherops_1 f = [f "$" "_apply", f "||" "_or", f "&&" "_and", f "." "_compose"]
parseRelops = parseNonassoc (relops parseRelops_f)
parseRelops_f op func = prr (wrapS op) (pure (ebinaryE func))
parseExpression = chainr1 (ebinary "_apply") (wrapC '$') $ chainr1 (ebinary "_or") (wrapS "||") $ chainr1 (ebinary "_and") (wrapS "&&") $ parseRelops $ chainr1 econs (wrapC ':') $ chainr1 (ebinary "_compose") (wrapC '.') $ chainl1 Ap skipSpace $ choice [fmap Var parseVar, fmap Con parseCon, fmap Int parseInt, fmap Char (parseStringLiteral '\''), fmap String (parseStringLiteral '"'), parseBetween '(' ')' (pro parseSection parseExpression), parseBetween '[' ']' (chainr econs enil (wrapC ',') parseExpression)]
parseSection = choice (append (relops parseSection_f) (otherops parseSection_f))
parseSection_f op func = prr (wrapS op) (pure func)
parseEquation = ap (ap (ap (fmap Equation parseVar) (many (prr skipSpace parsePatternPrimary))) (optional (prr (wrapC '|') parseExpression))) (prr (wrapC '=') parseExpression)
skipType = ignore (sepBy1 (sepBy1 skipTypePrimary skipSpace) (wrapS "->"))
skipTypePrimary = choice [ignore parseVar, ignore parseCon, parseBetween '(' ')' skipType, parseBetween '[' ']' skipType]
parseDataDecl = prr (parseS "data") (prr skipSpace (prr parseCon (prr (preSep parseVar skipSpace) (prr (wrapC '=') (sepByChar1 (liftA2 Constructor parseCon (fmap length (preSep skipTypePrimary skipSpace))) '|')))))
skipTypeSignature = prr parseVar (prr (wrapS "::") skipType)
skipTypeAlias = prr (parseS "type") (prr skipSpace (prr parseCon (prr (preSep parseVar skipSpace) (prr (wrapC '=') skipType))))
parseToplevel = choice [fmap (const TO) (pro skipTypeSignature skipTypeAlias), fmap TD parseDataDecl, fmap TE parseEquation]
parseLine = prl (prl (sepByChar1 parseToplevel ';') skipSpace) parseEof
patternCount (Equation _ ps _ _) = length ps
makeProgram (P ds es) = Program ds (makeFunctions es)
makeFunctions = map makeFunctions_f . groupBy makeFunctions_g
makeFunctions_f []     = error "Internal error: No equations in binding group"
makeFunctions_f (x:xs) = cond (error (concat ["Equations for ", equationName x, " have different numbers of arguments"])) (Function (equationName x) (patternCount x) (x:xs)) (all (((==) (patternCount x)) . patternCount) xs)
makeFunctions_g (Equation name_a _ _ _) (Equation name_b _ _ _) = listEq (==) name_a name_b
lookupCon name (Environment c _) = lookup name c
lookupVar name (Environment _ v) = lookup name v
walkPatterns f = walkPatterns_items f VArg
walkPatterns_items f base = concat . zipWith (walkPatterns_f2 f) (map base (countFrom 0))
walkPatterns_f2 f v (PCon name ps) = append (f v (PCon name ps)) (walkPatterns_items f (VItem v) ps)
walkPatterns_f2 f v p              = f v p
compile (Program decls funcs) = concat [header, declareConstructors decls, declareFunctions funcs, boxConstructors decls, boxFunctions funcs, compileConstructors decls, compileFunctions (globalEnv decls funcs) funcs]
globalEnv decls funcs = Environment (append (globalEnv_constructorTags decls) (globalEnv_builtinConstructors)) (append (map (globalEnv_f . functionName) funcs) globalEnv_builtinFunctions)
globalEnv_f name = (P name (VBox name))
globalEnv_constructorTags = concatMap (flip zip (countFrom 0) . map constructorName)
globalEnv_builtinConstructors = [P "Nil" 0, P "Cons" 1, P "P" 0]
globalEnv_builtinFunctions = map globalEnv_f ["add", "sub", "_lt", "_le", "_eq", "_ge", "_gt", "_ne", "_and", "_or", "divMod", "negate", "not", "error"]
localEnv ps (Environment t v) = Environment t (append (walkPatterns localEnv_f ps) v)
localEnv_f v (PVar name) = [P name v]
localEnv_f _ (PCon _ _)  = []
declareFunctions_f [] = ""
declareFunctions_f xs = concat ["static Function ", intercalate ", " xs, ";\n"]
declareConstructors = declareFunctions_f . map ((append "f_") . constructorName) . concat
declareFunctions = declareFunctions_f . map ((append "f_") . functionName)
boxConstructors = concatMap boxConstructors_f . concat
boxConstructors_f (Constructor name n) = boxThing name n
boxFunctions = concatMap boxFunctions_f
boxFunctions_f (Function name n _) = boxThing name n
boxThing name n | n == 0 = concat ["static Box b_", name, " = {0, f_", name, ", NULL};\n"]
boxThing name n = concat ["static Partial p_", name, " = {", showInt n, ", 0, f_", name, "};\n", "static Box b_", name, " = {1, NULL, &p_", name, "};\n"]
compileConstructors = concatMap (concat . zipWith compileConstructors_f (countFrom 0))
compileConstructors_f tag (Constructor name n) = concat ["static void *f_", name, "(Box **args)\n", "{\n", allocate n, "\tv->tag = ", showInt tag, ";\n", concatMap initialize (range 0 (sub n 1)), "\treturn v;\n", "}\n"]
allocate n | n == 0 = "\tValue *v = malloc(sizeof(Value));\n\t(void) args;\n"
allocate n = concat ["\tValue *v = malloc(sizeof(Value) + ", showInt n, " * sizeof(Box*));\n"]
initialize i = concat ["\tv->items[", showInt i, "] = args[", showInt i, "];\n"]
compileFunctions env = concatMap (compileFunction env)
compileFunction env (Function name argc equations) =  concat ["static void *f_", name, "(Box **args)\n", "{\n", concatMap (compileEquation env) equations, "\tNO_MATCH(", name, ");\n", "}\n"]
compileEquation genv (Equation _ patterns guard expr) = compileEquation_a (localEnv patterns genv) patterns guard expr
compileEquation_a env patterns guard expr = compileEquation_b (concat ["\treturn ", compileExpressionStrict env expr, ";\n"]) (append (compilePatterns env patterns) (compileGuard env guard))
compileEquation_b returnExpr preds = condList returnExpr (compileEquation_f returnExpr) preds
compileEquation_f returnExpr xs = concat ["\tif (", intercalate " && " xs, ")\n\t", returnExpr]
compilePatterns env = walkPatterns (compilePatterns_f env)
compilePatterns_f _ _ (PVar name) = []
compilePatterns_f env v (PCon name ps) = compilePatterns_h v name (lookupCon name env)
compilePatterns_h v name (Just n) = [concat ["match(", compileVarInfo v, ",", showInt n, ")"]]
compilePatterns_h v name Nothing  = error (append "Not in scope: data constructor " name)
compileGuard env Nothing     = []
compileGuard env (Just expr) = [concat ["isTrue(", compileExpressionStrict env expr, ")"]]
compileExpressionStrict env (Var name) = concat ["force(", compileVar (lookupVar name env) name, ")"]
compileExpressionStrict _   (Con name) = concat ["force(&b_", name, ")"]
compileExpressionStrict _   (Int s)    = concat ["mkInt(", s, ")"]
compileExpressionStrict _   (Char s)   = concat ["mkInt(", s, ")"]
compileExpressionStrict _   (String s) = concat ["mkString(", s, ")"]
compileExpressionStrict env (Ap f x)   = concat ["apply(", compileExpressionStrict env f, ",", compileExpressionLazy env x, ")"]
compileExpressionLazy env (Var name) = compileVar (lookupVar name env) name
compileExpressionLazy _   (Con name) = concat ["&b_", name, ""]
compileExpressionLazy _   (Int s)    = concat ["box(mkInt(", s, "))"]
compileExpressionLazy _   (Char s)   = concat ["box(mkInt(", s, "))"]
compileExpressionLazy _   (String s) = concat ["box(mkString(", s, "))"]
compileExpressionLazy env (Ap f x)   = concat ["deferApply(", compileExpressionLazy env f, ",", compileExpressionLazy env x, ")"]
compileVar (Just v) _    = compileVarInfo v
compileVar Nothing  name = error (append "Not in scope: " name)
compileVarInfo (VBox name) = append "&b_" name
compileVarInfo (VArg n)    = concat ["args[", showInt n, "]"]
compileVarInfo (VItem v n) = concat ["item(", compileVarInfo v, ",", showInt n, ")"]
header="#include <assert.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\ntypedef struct Box Box;\ntypedef struct Value Value;\ntypedef struct Partial Partial;\ntypedef void *Function(Box**);\nstruct Box{int state;Function *func;void*vc;Box*fx[];};\nstruct Value{int tag;Box *items[];};\nstruct Partial{int remaining;int applied;Function *func;Box *args[];};\n#define copy(...)memdup(&(__VA_ARGS__), sizeof(__VA_ARGS__))\n#define countof(...)(sizeof(__VA_ARGS__) / sizeof(*(__VA_ARGS__)))\n#define match(box, expectedTag)(((Value*)force(box))->tag == (expectedTag))\n#define item(box, n)(((Value*)(box)->vc)->items[n])\n#define isTrue(value)(!!*(int*)(value))\n#define NO_MATCH(func)fatal(\"Non-exhaustive patterns in function \" #func)\nstatic void fatal(const char *str){fprintf(stderr,\"*** Exception: %s\\n\", str);exit(EXIT_FAILURE);}\nstatic void *memdup(void *ptr, size_t size){void*ret=malloc(size);memcpy(ret,ptr,size);return ret;}\nstatic void *force(Box *box){switch(box->state){\ncase 0:box->state=2;box->vc=box->func(box->vc);box->state=1;\ncase 1:return box->vc;\ndefault:fatal(\"infinite loop\");}}\nstatic void *apply(Partial*f,Box*x){Partial*f2=malloc(sizeof(Partial)+(f->applied+1)*sizeof(Box*));\nmemcpy(f2->args,f->args,f->applied*sizeof(Box*));f2->args[f->applied]=x;\nif(f->remaining>1){f2->remaining=f->remaining-1;f2->applied=f->applied+1;f2->func=f->func;return f2;\n}else return f->func(f2->args);}\nstatic void*deferApply_cb(Box**a){return apply(force(a[0]),a[1]);}\nstatic Box*deferApply(Box*f,Box*x){\nBox*ret=malloc(sizeof(Box)+2*sizeof(Box*));\nret->state=0;\nret->func=deferApply_cb;\nret->vc=ret->fx;\nret->fx[0]=f;\nret->fx[1]=x;\nreturn ret;}\n\nstatic Box*defer(Function*func,void*ctx){\nBox*ret=malloc(sizeof(Box));\nret->state=0;\nret->func=func;\nret->vc=ctx;\nreturn ret;}\n\nstatic Box *box(void *value)\n{\n\tBox *ret = malloc(sizeof(Box));\n\tret->state = 1;\n\tret->func = NULL;\n\tret->vc = value;\n\treturn ret;\n}\n\nstatic int *mkInt(int n)\n{\n\tint *ret = malloc(sizeof(*ret));\n\t*ret = n;\n\treturn ret;\n}\n\nstatic Function f_Nil, f_Cons, f_P;\nstatic Box b_Nil, b_Cons, b_P, b_main;\n\n#define FUNCTION(name, argc) \\\n\tstatic Function f_##name; \\\n\tstatic Partial p_##name = {argc, 0, f_##name}; \\\n\tstatic Box b_##name = {1, NULL, &p_##name}; \\\n\tstatic void *f_##name(Box **args)\n\n#define intop(name, expr) \\\n\tFUNCTION(name, 2) \\\n\t{ \\\n\t\tint a = *(int*)force(args[0]); \\\n\t\tint b = *(int*)force(args[1]); \\\n\t\treturn mkInt(expr); \\\n\t}\n\n#define intop1(name, expr) \\\n\tFUNCTION(name, 1) \\\n\t{ \\\n\t\tint a = *(int*)force(args[0]); \\\n\t\treturn mkInt(expr); \\\n\t}\n\nintop(add,  a + b)\nintop(sub,  a - b)\n\nintop(_lt,  a <  b)\nintop(_le,  a <= b)\nintop(_eq,  a == b)\nintop(_ge,  a >= b)\nintop(_gt,  a >  b)\nintop(_ne,  a != b)\nintop(_and, a && b)\nintop(_or,  a || b)\n\nintop1(negate, -a)\nintop1(not,    !a)\n\nFUNCTION(divMod, 2)\n{\n\tint n = *(int*)force(args[0]);\n\tint d = *(int*)force(args[1]);\n\tint div = n / d;\n\tint mod = n % d;\n\t\n\tif ((mod < 0 && d > 0) || (mod > 0 && d < 0)) {\n\t\tdiv--;\n\t\tmod += d;\n\t}\n\t\n\tBox *pair[2] = {box(mkInt(div)), box(mkInt(mod))};\n\treturn f_P(pair);\n}\n\nstatic void *mkString(const char *str)\n{\n\tif (*str != '\\0') {\n\t\tBox *cons[2] =\n\t\t\t{box(mkInt(*str)), defer((Function*) mkString, (void*)(str + 1))};\n\t\treturn f_Cons(cons);\n\t} else {\n\t\treturn force(&b_Nil);\n\t}\n}\n\nstatic void putStr(Value *v, FILE *f)\n{\n\tif (v->tag == 1) {\n\t\tint c = *(int*)force(v->items[0]);\n\t\tputc(c, f);\n\t\tputStr(force(v->items[1]), f);\n\t}\n}\n\nFUNCTION(error, 1)\n{\n\tfflush(stdout);\n\tfputs(\"*** Exception: \", stderr);\n\tputStr(force(args[0]), stderr);\n\tputc('\\n', stderr);\n\texit(EXIT_FAILURE);\n}\n\nstruct mkStringFromFile\n{\n\tFILE *f;\n\tconst char *name;\n};\n\nstatic void *mkStringFromFile(struct mkStringFromFile *ctx)\n{\n\tint c = fgetc(ctx->f);\n\t\n\tif (c == EOF) {\n\t\tif (ferror(ctx->f))\n\t\t\tperror(ctx->name);\n\t\treturn force(&b_Nil);\n\t}\n\t\n\tBox *cons[2] = {box(mkInt(c)), defer((Function*) mkStringFromFile, ctx)};\n\treturn f_Cons(cons);\n}\n\nint main(void)\n{\n\tstruct mkStringFromFile c_in = {stdin, \"<stdin>\"};\n\tBox *b_in = defer((Function*) mkStringFromFile, copy(c_in));\n\tputStr(apply(force(&b_main), b_in), stdout);\n\treturn 0;\n}\n"
prelude = P 0 "_apply f x=f x;_compose f g x=f(g x);data List a=Nil|Cons a(List a);data P a b=P a b;data B=B;data Maybe a=Nothing|Just a;data Bool=False|True;id x=x;const x _=x;flip f x y=f y x;foldl f z[]=z;foldl f z(x:xs)=foldl f(f z x)xs;foldl1 f(x:xs)=foldl f x xs;foldl1 _[]=error\"foldl1: empty list\";foldr f z[]=z;foldr f z(x:xs)=f x(foldr f z xs);foldr1 f[x]=x;foldr1 f(x:xs)=f x(foldr1 f xs);foldr1 _[]=error\"foldr1: empty list\";map f[]=[];map f(x:xs)=f x:map f xs;filter p[]=[];filter p(x:xs)|p x=x:filter p xs;filter p(x:xs)=filter p xs;zipWith f(x:xs)(y:ys)=f x y:zipWith f xs ys;zipWith f _ _=[];append[]ys=ys;append(x:xs)ys=x:append xs ys;concat=foldr append[];concatMap f=concat.map f;length[]=0;length(_:l)=add 1(length l);take n _|n<=0=[];take _[]=[];take n(x:xs)=x:take(sub n 1)xs;takeWhile p[]=[];takeWhile p(x:xs)|p x=x:takeWhile p xs;takeWhile _ _=[];dropWhile p[]=[];dropWhile p(x:xs)|p x=dropWhile p xs;dropWhile p xs=xs;span p[]=P[][];span p(x:xs)|p x=span_1 x(span p xs);span p xs=P[]xs;span_1 x(P ys zs)=P(x:ys)zs;break p=span(not.p);reverse=foldl(flip(:))[];groupBy _[]=[];groupBy eq(x:xs)=groupBy_1 x eq(span(eq x)xs);groupBy_1 x eq(P ys zs)=(x:ys):groupBy eq zs;maybe n f Nothing=n;maybe n f(Just x)=f x;all p=foldr(&&)True.map p;intersperse _[]=[];intersperse _[x]=[x];intersperse sep(x:xs)=x:sep:intersperse sep xs;intercalate xs xss=concat(intersperse xs xss);isDigit c=c>='0'&&c<='9';isAlphaNum c=c>='0'&&c<='9'||c>='A'&&c<='Z'||c>='a'&&c<='z';isUpper c=c>='A'&&c<='Z';isLower c=c>='a'&&c<='z';showInt n|n<0='-':showInt(negate n);showInt n|n==0=\"0\";showInt n|n>0=reverse(map(add 48)(showInt_1 n));showInt_1 n|n==0=[];showInt_1 n=showInt_2(divMod n 10);showInt_2(P div mod)=mod:showInt_1 div;lines []=[];lines s=lines_1(break((==)'\\n')s);lines_1(P l[])=[l];lines_1(P l(_:s))=l:lines s;interact=id"


Do not repeat yourself Inspired by this challenge

Given a number m, output a program that prints out the string Do not repeat yourself.

Now for the challenging part: Each program the original code prints out has to have the byte at place m*n be the same as m*n + 1 and the same as m*n + 2 .... all the way down to m*n + m - 1.

(In case you can't tell, that means it has to be blocks of identical bytes m long)

Example (that only demonstrates the repetition rule, not the output):

2

aassdd

3

mmmyyy   nnnaaammmeee   iiisssfffrrreeeddd

27

111111111111111111111111111

Scoring:

Your program's score is the x / (min(y, 10)^3), where y is the number of correct programs it outputs, and x is the sum of the lengths of all of the correct programs it outputs and x > 1.  Lowest score wins.

Other notes:

Your code doesn't have to fulfill any such restrictions on letters repeating.
Your programs (that you output) cannot take input of any sort.
The input will always be a positive integer greater than 1.
Your code needs to work for at least one integer greater than 1.

CJam, 3165 / 10³ = 3.165

{
"Do not repeat yourself"]sX/z_&
6)H7+G0+B8+H7+E8+G0+D8+9)C8+9)A7+E8+G0+B9+H7+K7+D8+J7+9)A8+I6+]{c}/
"Do not repeat yourself"]sZ/z_&

"Do not repeat yourself"]s3D&3D&3D&3D&3D&/z_&

"Do not repeat yourself"]s1F&1F&1F&1F&1F&1F&1F&/z_&

"Do not repeat yourself"]sB/z_&

"Do not repeat yourself"]sD/z_&

"Do not repeat yourself"]sF/z_&

"Do not repeat yourself"]sH/z_&

"Do not repeat yourself"]sJ/z_&
}`1>W<N/
e# Uncomment this line to count total length:
e# ee{~,*}%:+p [L]
ri\1$=f*

Works for inputs 1, 2, 3, 5, 7, 11, 13, 15, 17, 19.

Total length is 3165.

The program for input 2 is from here, credits to Super Chafouin.

Example: output for 11

"""""""""""DDDDDDDDDDDooooooooooo           nnnnnnnnnnnooooooooooottttttttttt           rrrrrrrrrrreeeeeeeeeeepppppppppppeeeeeeeeeeeaaaaaaaaaaattttttttttt           yyyyyyyyyyyooooooooooouuuuuuuuuuurrrrrrrrrrrssssssssssseeeeeeeeeeelllllllllllfffffffffff"""""""""""]]]]]]]]]]]sssssssssssBBBBBBBBBBB///////////zzzzzzzzzzz___________&&&&&&&&&&&

Explanation:

"""""""""""..."""""""""""    Push five empty strings, a long string,
                                and five more empty strings.
]]]]]]]]]]]sssssssssss       Collect them all in a list. Put that list in
                             10 more layers of list, for good measure.
                             Convert this to a string, to just get the long one.
BBBBBBBBBBB///////////       Split into chunks of size
                                11/(11/(.../(11/(11/11))))) = 11.
                             This gets us:
                                ["DDDDDDDDDDD" "ooooooooooo" ...]
zzzzzzzzzzz                  Transpose eleven times, i.e. once. We now have:
                                ["Do not..." "Do not..." ... "Do not..."]
___________&&&&&&&&&&&       Push eleven more copies, and get the unique elements.
                             This gets us:
                                ["Do not..."]


Computing a specific coefficient in a quotient of polynomials Context

After "Computing a specific coefficient in a product of polynomials", asking you to compute a specific coefficient of polynomial multiplication, I wish to create a "mirror" challenge, asking you to compute a specific coefficient from polynomial division.

Polynomial division

Let us establish an analogy with integer division. If you have two integers a and b, then there is a unique way of writing a = qb + r, with q, r integers and 0 <= r < b.

Let p(x), a(x) be two polynomials. Then there is a unique way of writing a(x) = q(x)p(x) + r(x), where q(x), r(x) are two polynomials and the degree of r(x) is strictly less than the degree of p(x).

Algorithm

Polynomial division can be performed through an iterative algorithm:

Initialize the quotient at q(x) = 0
While the degree of a(x) is at least as big as the degree of p(x):

let n = degree(a) - degree(p), let A be the coefficient of the term of highest degree in a(x) and P be the coefficient of highest degree in p(x).
do q(x) = q(x) + (A/P)x^n
update a(x) = a(x) - p(x)(A/P)x^n

q(x) is the quotient and what is left at a(x) is the remainder, which for our case will always be 0.

Task

Given two polynomials a(x), p(x) such that there exists q(x) satisfying a(x) = p(x)q(x) (with all three polynomials having integer coefficients), find the coefficient of q(x) of degree k.

(Yes, we are assuming the remainder is 0)

Input

Two polynomials (with integer coefficients) and an integer.

Each input polynomial can be in any sensible format. A few suggestions come to mind:

A string, like "1 + 3x + 5x^2"
A list of coefficients where index encodes exponent, like [1, 3, 5]
A list of (coefficient, exponent) pairs, like [(1, 0), (3, 1), (5, 2)]

An input format must be sensible AND completely unambiguous over the input space.

The integer k is a non-negative integer. You may take it in any of the usual ways. You can assume k is less than or equal to the differences of the degrees of a(x) and p(x), i.e. k <= deg(a) - deg(p) and you can assume deg(a) >= deg(p).

Output

The integer corresponding to the coefficient of x^k in the polynomial q(x) that satisfies the equality a(x) = q(x)p(x).

Test cases

The input order for the test cases is a(x), p(x), integer k.

[12], [4], 0 -> 3
[0, 0, 6], [0, 3], 0 -> 0
[0, 0, 6], [0, 3], 1 -> 2
[0, 70, 70, 17, 70, 61, 6], [0, 10, 10, 1], 0 -> 7
[0, 70, 70, 17, 70, 61, 6], [0, 10, 10, 1], 1 -> 0
[0, 70, 70, 17, 70, 61, 6], [0, 10, 10, 1], 2 -> 1
[0, 70, 70, 17, 70, 61, 6], [0, 10, 10, 1], 3 -> 6
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 0 -> -5
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 1 -> 7
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 2 -> -10
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 3 -> -8
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 4 -> 1
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 5 -> 0
[0, -50, 20, -35, -173, -80, 2, -9, -10, -1], [0, 10, 10, 1], 6 -> -1

This is code-golf so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!

(This is not part of the RGS Golfing Showdown)

MATL, 6 bytes

Y-PiQ)

The inputs contain the coefficients in order of decreasing powers.

Try it online! Or verify all test cases

Explanation

  (De)convolution is the key to success

     % Implicit inputs: two numerical vectors
Y-   % Deconvolution
P    % Flip
i    % Input: integer
Q    % Add 1
)    % Get the entry at that position
     % Implicit display


Finding Pairs for Letters You should write a program or function which given a string as input outputs or returns a string or list of the lowercase letters in the order they find their uppercase pair.

The input is a string consisting of the characters [a-zA-Z] space and newline representing a torus (rectangular grid with wrap around for rows and columns) with some of the letters a-z and for every lowercase letter exactly one of its uppercase equal.

Every lowercase letter has a field of view equal to ord(letter)-97 grid steps i.e. a=0, b=1, ... , z=25 where 0 means you can only see your own cell. Steps (and field of view) are possible in all 8 directions. At every step:

if a lowercase letter sees its uppercase pair (e.g. C for c) it will go straight to it
if a lowercase letter doesn't see its uppercase pair it will move to the bottom right neighbor cell wrapping around if necessary.

There can be multiple letters at the same position. They don't block each other.

You should output or return the lowercase letters in the same order they reach their uppercase pair. If multiple letters reach their pair at the same step they should be outputted in alphabetical order. If a letter newer reaches its pair it shouldn't be outputted at all.

Input

A string received in any reasonable way.
Contains only letters [a-zA-Z] (at most one from each character; at least one pair of letters), spaces and newlines.
Input will form a proper rectangle, i.e. there will be the same number of characters between every newline.
Trailing newline is optional.

Output

A list of lowercase letters in the order they reach their pair.
Output can be in any reasonable data-structure (string, list, array etc.) and can be outputted or returned.
Trailing newline is optional.

Examples

Input is all the rows between Input: and Visualization:. In visualization * marks all cells visited by letters. Other valid visualizations are possible as when a letter sees its pair often multiple shortest paths are possible. Space only lines are empty below. Check correct inputs here.

Input:

D
  d Aa

Visualization:
  *
D* *
  d Aa
*
 *
Output: da
Step numbers: 2 5

Input:

W      B
    A
  b

      a
  w

Visualization:
**     *
W *    B
   *A
  b *
   * *
    * a
  w  * *
**    *
Output: wb
Step numbers: 3 6

Input:

     A

      a

Visualization:
*  *****
**  ****
***  A**
****   *
*****
 *****a
  ******
Output: a
Step numbers: 39

Input:

   i
  f     d

    DI  F
Visualization:

   i
  f *   d
   * *   *
*   **
 ***DI**F
Output: idf
Step numbers: 4 6 6

Input:

  g                 a

        G               W

                    j
             w

                                         A      J

Visualization:
       *         *         * *       *         *
        *         *         * *       *         *
         *         *         * *       *         *
* g       *         a         * *       *
 * *       *         *         * *       *
  * *       *         *         * *       *
   * ***G    *     *****W        * *       *
    *         *   *     *         * *       *
     *         * *       *         * *       *
      *         *         *         * *       *
       *       * *         *         * *       *
        *     *   * j       *         * *       *
         *   w     * *       *         * *       *
*         *         * *       *         * *
 *         *         * *       *         * *
  *         *         * *       *         * *
   *         *         * *       *       A * ***J
    *         *         * *       *         *
     *         *         * *       *         *
      *         *         * *       *         *
Output: gwj
Step numbers: 6 11 28

This is code-golf so the shortest entry wins.

Ruby 319 313 310 304 287 283

F=->s{l=s.split ?\n
b=[]
t={}
[*0...m=l.size].product([*0...n=l[0].size]).map{|y,x|c=l[y][x]
c!=' '&&c>?Z?b<<[c,y,x]:t[c.downcase]=[y,x]}
b.map{|q|c,y,x=q
u,i=t[c]
(m*n).times{|w|e=([u-(y+w)%m,i-(x+w)%n].map &:abs).max
e>c.ord-97||q<<w+e}
q[3]&&[q[3],q[0]]}.compact.sort.map{|a,b|b}}

This is a function that takes as input a string (without trailing newline) and returns an array of the lowercase letters in the correct order.
Here's a version you can run online with tests: http://ideone.com/5jiwLq
I've made a lot of modifications to the code. The history of modifications is available here.
Here's the indented and annotated version to make it easier to see what's going on (also available online):
F=->s{
  l=s.split ?\n
  m=l.size
  n=l[0].size

  # Make an array with lowercase letters and their coords (`b`)
  # Make a hash that for each target (uppercase letter) holds
  # its coordinates
  b=[]
  t={}
  [*0...m].product([*0...n]).map{|y,x|
    c=l[y][x]
    c!=' '&&(c>?Z?b<<[c,y,x]:t[c.downcase]=[y,x])
  }

  # `l` is a function that, given an array of the form
  # [lowercase_letter, y-coord, x-coord] will append to that array
  # the number of steps required for the letter to reach its
  # uppercase correspondent
  l=->q{
    c,y,x=q
    u,i=t[c]
    d=c.ord-97
    (m*n).times{|w|
      e=([u-y,i-x].map &:abs).max
      e<=d&&q<<w+e
      y=(y+1)%m
      x=(x+1)%n
    }
  }

  # apply function `l` to each of the lowercase letters...
  b.map &l

  # ...then sort accordingly and return the array
  b.map{|x|[x[3],x[0]]}.select{|a,b|a}.sort.map{|a,b|b}
}


Average number of strings with Levenshtein distance up to 3 The Levenshtein distance between two strings is the minimum number of single character insertions, deletions, or substitutions to convert one string into the other one.  Given a binary string \$S\$ of length \$n\$, we are a interested in the number of different strings of length \$n\$ which have distance at most \$3\$ from \$S\$.

For example, if \$S = 0000\$ there are four strings with Levenshtein distance exactly \$3\$ from \$S\$, six with distance exactly \$2\$, four with distance exactly \$1\$ and exactly one with distance \$0\$. This makes a total of \$15\$ distinct strings with distance at most \$3\$ from the string \$0000\$. The only string with distance greater than \$3\$ is \$1111\$.

However, this number depends on the value of \$S\$. For example if \$S = 0010\$ then the number of distinct strings with distance at most \$3\$ is \$16\$, in other words all of them.

For this task the input is a value of \$n \geq 3\$. Your code must output the average number of binary strings of length \$n\$ which have Levenshtein distance at most \$3\$ from a uniform and randomly sampled string \$S\$.  Your answer can be output in any standard way you choose but it must be exact.

Examples

n = 3. Average = 8
n = 4. Average = 15 1/2
n = 5. Average = 28 13/16
n = 6. Average = 50 15/16
n = 7. Average = 85 23/64
n = 8. Average = 135 27/32
n = 9. Average = 206 77/256
n = 10. Average = 300 181/256
n = 11. Average = 423 67/1024
n = 12. Average = 577 99/256
n = 13. Average = 767 2793/4096.
n = 14. Average = 997 3931/4096.
n = 15. Average = 1272 3711/16384.

Score

Your score is the highest value of \$n\$ you can reach.

GAP and the automata package

The average number is the number of pairs of words of length \$n\$ with Levenshtein distance up to three, divided by \$2^n\$.

It is not very difficult to construct an nondeterministic finite automaton over the alphabet of pairs of bits that accepts the word \$(a_1,b_1)(a_2,b_2)\dots(a_n,b_n)\$ iff the binary words \$a_1a_2\dots a_n\$ and \$b_1b_2\dots b_n\$ have Levenshtein distance up to three. My version uses 14 states. This automaton can be transformed into a minimal deterministic one, which has 39 states. From its transition function we can get a matrix that describes the number of ways we can get from one state to another. Now counting the number of ways we can get from the initial state to some accepting state is just a matter of multiplication.

The implicit recurrance could be simplified because some values are always equal, and it might be solved to give a closed formula, but it seems to be good enough as is.

LoadPackage("automata");

nfa := Automaton("nondet", 14, 4,
     [[[1,5,9],[2,7,11],3,4,[5,13],[7,13],[7,14],14,
       [9,13],[11,13],[11,14],14,13,14],
      [[2,5,10],[3,7,12],4,0,[7,14],[5,14],0,7,
       [10,14],[12,14],12,0,14,0],
      [[2,6,9],[3,8,11],4,0,[6,14],[8,14],8,0,
       [11,14],[9,14],0,11,14,0],
      [[1,6,10],[2,8,12],3,4,[8,13],[6,13],14,[8,14],
       [12,13],[10,13],14,[12,14],13,14] ],
     [1], [1..14] );

dfa := MinimalizedAut(nfa);

size := NumberStatesOfAutomaton(dfa);;

mat := NullMat(size, size);;
for row in TransitionMatrixOfAutomaton(dfa) do
  for i in [1..size] do
    mat[i][row[i]] := mat[i][row[i]]+1;
  od;
od;

init := 0 * [1..size];;
init[InitialStatesOfAutomaton(dfa)[1]] := 1;;

fin := 0 * [1..size];;
for i in FinalStatesOfAutomaton(dfa) do
  fin[i] := 1;
od;

f := function(n)
  local res, intpart, fraction;
  res := init * mat^n * fin / 2^n;
  intpart := Int(res);
  fraction := res-intpart;
  Print("n = ", n, ". Average = ", intpart);
  if fraction <> 0 then
    Print(" ",fraction);
  fi;
  Print(".\n");
end;

Try it online!

Put it in a file, start gap and read the file with a command like Read("l3.gap");, then try something like f(20); or for i in [0..100] do f(i); od;.

Here are some results:

n = 0. Average = 1.
n = 1. Average = 2.
n = 2. Average = 4.
n = 3. Average = 8.
n = 4. Average = 15 1/2.
n = 5. Average = 28 13/16.
n = 6. Average = 50 15/16.
n = 7. Average = 85 23/64.
n = 8. Average = 135 27/32.
n = 9. Average = 206 77/256.
n = 10. Average = 300 181/256.
n = 11. Average = 423 67/1024.
n = 12. Average = 577 99/256.
n = 13. Average = 767 2793/4096.
n = 14. Average = 997 3931/4096.
n = 15. Average = 1272 3711/16384.
n = 16. Average = 1594 3985/8192.
n = 17. Average = 1968 48645/65536.
n = 18. Average = 2398 65249/65536.
n = 19. Average = 2889 64891/262144.
n = 20. Average = 3443 16339/32768.
n = 30. Average = 13385 268434611/268435456.
n = 40. Average = 34128 68719475971/137438953472.
n = 50. Average = 69670 281474976708241/281474976710656.
n = 60. Average = 124013 36028797018963093/72057594037927936.
n = 70. Average = 201155 295147905179352821071/295147905179352825856.
n = 80. Average = 305098 75557863725914323416001/151115727451828646838272.
n = 90. Average = 439840 309485009821345068724773101/
309485009821345068724781056.
n = 100. Average = 609383 9903520314283042199192993177/
19807040628566084398385987584.
n = 1000. Average = 660694208
669692879491417075592765655662501131600878007315958504652343992731469406953085\
076558248986759809911329746670573470716765741965803557696277249036098418660925\
245910485926514436588817162816398196367372136384565404686473871329212422972447\
846496629816432160699779855408885478776864478289024177325353755091/
133938575898283415118553131132500226320175601463191700930468798546293881390617\
015311649797351961982265949334114694143353148393160711539255449807219683732185\
049182097185302887317763432563279639273474427276913080937294774265842484594489\
5692993259632864321399559710817770957553728956578048354650708508672.
n = 10000. Average = 666066942458
[fractional part removed]

Pari/GP, 51 bytes

All the eigenvalues of the matrix are integers (could I have known or expected that?), and I found this formula for \$n\ge 2\$:

f(n)=(40+6*n-4*n^2)/2^n-83/2+331/12*n-6*n^2+2/3*n^3

Try it online!


Split a list into sized chunks, but not counting items failing predicate Motivation: Sometimes certain items in a list don't count towards your totals. For example, counting plane passengers in rows, where babies sit on a parent's laps.

Challenge: write a program to split a list of items into chunks. Each chunk (except possibly the last) is the same size, where size is defined as the number of items passing a predicate function.

Rules:

Your program must take

a list of items
a positive integer chunk size
a predicate function (takes an item, and returns true or false)

You must return the input list split into chunks
Each chunk is a list of items
Overall the items must remain in the same order, with none disgarded
The number of items passing predicate in each chunk (except possibly the last) should match the input chunk size.
items failing the predicate should not count toward this size
Items failing the predicate are

still included in the output chunks
allocated to the earliest chunk, in the case that a chunk is "full" but the next items are ones failing the predicate

thus the final chunk may not consist solely of items failing the predicate

The final chunk may be of size less than the chunk size because all the items have been accounted for.

Non exhaustive examples:

The simplest example is to consider 1s and 0s, where the predicate function is x ==> x > 0. In this case, the sum of each chunk must match the chunk size.

items: [], size: 2, predicate: x > 0 --> either [] or [[]]
items: [0, 0, 0, 0, 0, 0], size: 2, predicate: x > 0 --> [[0, 0, 0, 0, 0, 0]]
items: [0, 1, 1, 0], size: 2, predicate: x > 0 --> [[0, 1, 1, 0]]
items: [0, 1, 1, 0, 1, 0, 0], size: 2, predicate: x > 0 --> [[0, 1, 1, 0], [1, 0, 0]]
items: [0, 1, 0, 0, 1, 0, 1, 1, 0], size: 2, predicate: x > 0 --> [[0, 1, 0, 0, 1, 0], [1, 1, 0]]

And let's finish with the plane passengers where babies sit on a parent's lap example. A for adult, b for baby, plane row is 3 seats wide, adult always listed before their baby:

items: [A, b, A, b, A, A, A, b, A, b, A, A, b], size: 3, predicate: x => x == A --> [[A, b, A, b, A], [A, A, b, A, b], [A, A, b]]

Brachylog, 37 bytes

hW&t~c.k{↰₂ˢl}ᵐ;WxĖ∧.bhᵐ↰₂ᵐ∧.t↰₂ˢl≤W∧

Try it online!

I was pleasantly surprised to find that this - pretty much a restatement of the question - successfully terminates and produces correct output.

Assumes the predicate is present as predicate 2 below this code. Outputs a list of lists ("chunks"), or false for an empty input.

Explanation:

hW&               % First input is W, the expected "weight" of each chunk
                  %  (i.e. the number of items passing predicate in each chunk)

t                 % Take the second input, the list of items
 ~c.              % Output is a partition of this list
    k{    }ᵐ      % For each partition (chunk) except the last,
      ↰₂ˢ         %   Select the items in the chunk that pass the predicate
         l        %   Get the length of that
                  % (So now we have the list of the "weights" of each chunk)
            ;Wx   % Remove the input expected weight from this list, and
               Ė  %  the result of this should be empty.
                  %  This verifies that the list of weights is either
                  %  composed of all W-values, or is empty (when input is [0 0 0] for eg.)

    ∧.bhᵐ↰₂ᵐ      % And, the first element of each chunk (except the first) should
                  %  pass the predicate. This is another way of saying:
                  %  "Items failing the predicate are allocated to the earliest chunk"

    ∧.t↰₂ˢl≤W     % And, the final chunk (which we haven't constrained so far)
                  %  should have weight ≤ the input expected weight
                  %  This disallows putting everything in the final chunk and calling it a day!

    ∧             % (no further constraints on output)


Make a slow error quine maker! As part of his answer to Make an Error Quine!, @Falko proposed the following algorithm:

  How to create your own solution in 2 minutes?

  Open a new file in an IDE of your choice.
  Bang your head onto the keyboard in front of you.
  Compile.
  Replace the code with the compiler error message.
  Repeat steps 3 and 4 until the code converges.

  I bet such a procedure terminates pretty quickly in most cases!

Task

Your task is to prove him wrong.

Write a full program that satisfies the following:

When compiled or interpreted, it produces an error message that, when compiled or interpreted in turn, also results in an error message.
Repeating step 1 over and over again will eventually encounter a fixed point, i.e., an error quine.

Additional rules

The final error message must have a positive length. However, the previous error messages and the original source code may be empty.
The original source code's length may not exceed 1024 bytes.
Neither the original code or the code generated in any of the steps may produce non-error output.

The output has to be clearly identifiable as an error message, which has to be generated by the compiler/interpreter due to a syntax error, runtime error, undefined reference, etc.
Your program may not receive any input or require any flags to produce the loop.
Your program may rely on a specific implementation of its language or version thereof.

Scoring

Your score is the finite number of steps your source code requires before producing an error quine. The submission with the highest score wins.

The length of the original source code will be used as tie breaker. Shorter is better.

Example

In Chicken, the program

generates the following error message:

TypeError: Cannot read property 'NaN' of undefined

If this error message is, in turn, interpreted, it produces the error message

Error on line 1: expected 'chicken'

which, if interpreted in turn, produces itself.

Thus, the score of the empty Chicken program is 2.

Counterexample

The PHP code

ab<?=c

generates the error message

PHP Parse error:  syntax error, unexpected '?' in Command line code on line 1

which produces itself when interpreted.

However, the second source code prints the message to STDOUT, making this sequence invalid.

Bash, 9223372036854775810

Inspired by Doorknob's answer.

a='"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #"'
i=2**63
eval $a

It should be run with bash < file.sh, or use the same file name for each program, to get rid of the different file names in the error messages.

The first few errors are (with LANG=C):

bash: line 3: 2>/dev/null;if(((i=9223372036854775807)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

bash: line 1: 2>/dev/null;if(((i=9223372036854775806)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

bash: line 1: 2>/dev/null;if(((i=9223372036854775805)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

And finally:

bash: line 1: 2>/dev/null;if(((i=0)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

bash: line 1: 1: command not found

bash: line 1: bash:: command not found

which is an error quine.


Decimal concatenation of squares Premise

One night, I was just contemplating on numbers. I found out about something unique about numbers like 7, 10, 12, 13, and more. They are squares of squares! Meaning, that when squared, are comprised of squares themselves. The OEIS calls them Squares which are a decimal concatenation of two or more squares.

Examples of such numbers include 7 (49 has 22 and 32) 13 (169 has 42 and 32) and 20 (400 has 22 and 02). Other examples include 37, as 1369 is a term as it can be partitioned as 1, 36 and 9. 1444 (382) is a term as it can be partitioned as 1, 4, 4, 4. I asked about this on Math.SE, and it was named after me!

Challenge

Design a program that prints TanMath numbers.  Given the number n (starting at 1), print the nth TanMath number, T(n).

As a code example:

>> 1
>> 7

or

>> 4
>> 13

Reference Python implementation(thanks @MartinBüttner and @Sp3000!):

from math import sqrt

n = input()

def r(digits, depth):
    z = len(digits)
    if z < 1:
        return (depth > 1)
    else:
        for i in range(1, z+1):
            t = int(digits[:i])
            if sqrt(t).is_integer() and r(digits[i:], depth+1):
                return True
        return False

i=0
t=0
while t < n:
    i += 1

    if r(str(i**2), 0):
        t += 1

print i

Here is a list of the first 100 numbers:

  7 10 12 13 19 20 21 30 35 37 38 40 41
  44 50 57 60 65 70 80 90 95 97 100 102 105 107 108 110 112 119 120 121
  125 129 130 138 140 150 160 170 180 190 191 200 201 204 205 209 210
  212 220 223 230 240 250 253 260 270 280 285 290 300 305 306 310 315
  320 325 330 340 342 343 345 348 350 360 369 370 375 379 380 390 397
  400 402 405 408 410 413 420 430 440 441 450 460 470 475 480 487

This is a code golf, so the shortest code wins!

Good luck!

Pyth, 23 21 20 bytes

e.ff!-sMT^R2Z./`^Z2Q

Thanks to @isaacg for golfing off 1 byte!

Try it online.

How it works

                      (implicit) Store the evaluated input in Q.
 .f                Q  Filter; find the first Q positive integers Z such that:
                ^Z2     Compute the square of Z.
               `        Cast to string.
             ./         Compute all partitions of the string.
   f                    Filter; find all partitions T such that:
      sMT                 Cast all elements of T to integer.
         ^R2Z             Compute the squares of all integers in [0, ..., Z-1].
     -                    Remove the squares from the integers in T.
    !                     Compute the logical NOT of the result. This returns True
                          iff all integers in T are squares of numbers less than Z.
                        Keep T if `!' returned True.
                      Keep Z if `!' returned True for at least one T.
e                     Retrieve the last of the Q matches.


Make a valid error maker! We've been twice challenged to make 'error quines' (see Make an error quine! and Make a slow error quine maker!), so why don't we try the opposite?
Instructions

Write a "program" that, when run, produces an error.
Copy the error message into a new program, and run it.
Repeat Step 2 until the program runs without producing an error.

Rules

All of your programs must be run in the same language.
None of your programs can be shorter than 1 byte long.
The error(s) should be printed to STDERR.

Winning criteria
Your score is the number of programs run minus the length in bytes of your initial program. Highest score wins.

An example in monochrome TI-83+/84+ BASIC:
Initial program: {"
This creates a list with a string inside it, throwing an ERR:DATA TYPE.
Program 2: ERR:DATA TYPE
The space causes the interpreter to throw an ERR:SYNTAX.
Program 3: ERR:SYNTAX
The letters are treated as variable multiplication, and the colon as
a newline. This runs successfully.
This chain's score is 3 (number of programs) minus 2 (length in bytes of {", the initial program), totaling 1.

Pip 0.15.05.29, over 10100,000
(Subtracting the 51 bytes of source code is negligible for such a large number.)
This is a version of my answer to Make a slow error quine maker.  Requires the -w flag for warning output.
i:5**6**7d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx

The exact number of steps depends only on the value assigned to i, so it could be arbitrarily large (until the Python interpreter runs out of memory). Also, it would take longer than the age of the universe to complete the above sequence.
Explanation:
Example here uses an i-value of 5 for purposes of explanation.
i:5d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx

After setting i, store a string in d and then attempt to execute the Swap statement. Swap expects two variables (more accurately, lvalues). s is fine, but the second expression is i?dRo--iRsRPdx. If i is true (nonzero, for our purposes), the ternary evaluates to dRo--iRsRPd, which uses d from earlier to form a near-quine--only with i decremented. This expression is not an lvalue, so Pip complains:
Attempting to swap non-lvalue i:4d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx

... which then starts the whole thing over again. (Attempting to swap non-lvalue is a bunch of no-ops: At calculates the ASCII value of t = 10, n-l subtracts newline minus each value of an empty list, and all the lowercase letters are just variables.)
The process continues in like fashion all the way down to:
Attempting to swap non-lvalue i:0d:"i:1d: Ssi?dRo--iRsRPdx"Ssi?dRo--iRsRPdx

When this is run, i is now false. The ternary expression evaluates to the else branch x--which is an lvalue. Thus, swap simply swaps the values of s and x. The program then exits with no output.
(The only thing that's changed from the previous answer is using x, which is a predefined variable, instead of a, which is undefined if there were no command-line arguments and thus triggers a different error when i gets down to zero.)


Display Peter's keyboard pattern Assume an simple keyboard with this layout:

1 2 3 4 5 6 7 8 9 0
A B C D E F G H I J
K L M N O P Q R S T
U V W X Y Z . , ? !

Peter's keyboard pattern can be generated by starting at the top left of the keyboard, and displays the first three characters and a newline. It shifts over one character and displays the second, third, and fourth key. Once it reaches the end of a row it continues at the end of the next row and goes backwards, until it reaches the start of that row and then goes forward on the next row, and so on until it reaches the beginning of the last row.

This is Peter's keyboard pattern:

123
234
345
456
567
678
789
890
90J
0JI
JIH
IHG
HGF
GFE
FED
EDC
DCB
CBA
BAK
AKL
KLM
LMN
MNO
NOP
OPQ
PQR
QRS
RST
ST!
T!?
!?,
?,.
,.Z
.ZY
ZYX
YXW
XWV
WVU

Write a program which accepts no input and displays Peter's keyboard pattern. The program must be smaller than 152 bytes, i.e. the size of the string it outputs.

This is code golf, so the shortest solution wins.

Perl, 63 chars
say for"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"=~/(?=(...))/g

This solution uses the say function (available since Perl 5.10.0 with the -E switch, or with use 5.010).  Without it, the best I can do is 67 chars (and an extra newline at the end of the output):
print"1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU"=~/(?=(...))/g,$,=$/

Earlier 65-char solution:
s//1234567890JIHGFEDCBAKLMNOPQRST!?,.ZYXWVU/;s!(?=(...))!say$1!eg

Replacing say$1 with print$1.$/ lets the code run on older perls, at the cost of 5 extra characters.


Nothing like a good ol' game of ModTen Disclaimer: ModTen is a fictional card game which was created for the sole purpose of this challenge.

The rules of ModTen

ModTen is played with a standard 52-card deck. Because the full rules are yet to be invented, we're going to focus on the hand ranking exclusively.

A winning hand in ModTen. Graphics from Wikipedia.

Card values

The cards have the following values:

2 to 9: worth their face value
Ten: 0 point
Jack: 3 points
Queen or King: 8 points
Ace: 9 points

Hand values

A ModTen hand is made of two cards. The base value of a hand is obtained by multiplying the value of both cards together and keeping the last digit only (i.e. applying a modulo 10).

For instance, the value of 7♥ - Q♣ is "\$6\$", because \$(7\times8)\bmod 10=6\$.
The only other rule in ModTen is that suited cards are worth more than unsuited ones. By convention, we are going to append a "s" to the value if both cards are of the same suit.

For instance, the value of 9♠ - 5♠ will be noted as "\$5\text{s}\$", because \$(9\times5)\bmod 10=5\$ and the cards are suited.

Hand ranking and winner

The above rules result in 18 distinct hand ranks which are summarized in the following table, from strongest to lowest (or rarest to most common). The probabilities are given for information only.

Given two hands, the hand with the lowest rank wins. If both hands are of the same rank, then it's a draw (there's no tie breaker).

 hand rank | hand value(s) | deal probability
-----------+---------------+------------------
     1     | 9s            | 0.30%
     2     | 3s            | 0.60%
     3     | 1s            | 0.90%
     4     | 7s            | 1.21%
     5     | 5s            | 1.51%
     6     | 3             | 1.81%
     7     | 9             | 2.26%
     8     | 8s            | 2.71%
     9     | 6s            | 3.02%
    10     | 1 or 7        | 3.62% each
    11     | 2s or 4s      | 3.92% each
    12     | 5             | 4.98%
    13     | 0s            | 5.43%
    14     | 8             | 8.14%
    15     | 6             | 9.95%
    16     | 2             | 11.76%
    17     | 4             | 13.57%
    18     | 0             | 16.74%

The challenge

Given two ModTen hands, output one of three consistent values of your choice to tell whether:

the first player wins
the second player wins
it's a draw

The following rules apply:

A card must be described by its rank in upper case (2, 3, ..., 9, T, J, Q, K or A) followed by its suit in lower case (c, d, h or s, for clubs, diamonds, hearts and spades).
You may use "10" instead of "T" but any other substitution is prohibited.
As long as the above rules are followed, you may take the hands in any reasonable and unambiguous format. You are allowed to take the rank and the suit as two distinct characters rather than a single string.

Some valid input formats are:

"7c Qh 8s Ks"
[["7c","Qh"], ["8s","Ks"]]
[[['7','c'], ['Q','h']], [['8','s'], ['K','s']]]
etc.

Instead of using 3 consistent distinct values, your output may also be negative, positive or zero. Please specify the output format used in your answer.
This is code-golf.

Test cases

Player 1 wins

["Js","3s"], ["Ks","Kh"]
["7h","9h"], ["9s","7c"]
["Ah","5s"], ["Ts","8s"]
["Ts","8s"], ["Jh","2s"]
["4h","8s"], ["Qh","Ks"]

Player 2 wins

["Th","8d"], ["6s","Kd"]
["Jc","5c"], ["3s","9s"]
["Jc","Jd"], ["9h","Ah"]
["2d","4d"], ["3h","3s"]
["5c","4c"], ["3c","2c"]

Draw

["Js","3s"], ["3d","Jd"]
["Ah","Ac"], ["3d","9s"]
["Qc","Kc"], ["6d","4d"]
["2d","3d"], ["3s","2s"]
["Ts","9c"], ["4h","5d"]

Python 3, 114 110 bytes

lambda m,n:p(*n)-p(*m)
R=b"T 2J45UNK9RL<3SLM;QAK:O>=/678"
v=R.find
p=lambda i,s,j,t:R[s==t::2][v(j)*v(i)%10+3]

Try it online!
@Arnauld proposed the idea of merging the card value and rank table strings. After some attempts I managed to craft a merged string R="T 2J45UNK9RL<3SLM;QAK:O>=/678", which has the same length as the original card value string. The substring R[6:25]="UNK9RL<3SLM;QAK:O>=/" serves as the rank table as well as a card value lookup table for 3, 9, A, K, and Q. The ASCII-value decoding of the new rank table has the same ranking effect as the previous rank table.
Using byte strings as input saves 4 bytes.
Using cmp in Python 2 can reduce the solution to 102 bytes, as shown by @xnor's solution.

Python 3, 165 142 130 129 bytes

lambda m,n:p(*n)-p(*m)
v="T 23456789   J    QA        K".find
p=lambda i,s,j,t:ord("HC92FA51GAB4E893D760"[s==t::2][v(j)*v(i)%10])

Try it online!
-23 bytes thanks to @Jonathan Allan
-2 bytes thanks to @ovs
-1 byte thanks to @mypetlion
Ungolfed:
f = lambda hand1, hand2: get_rank(*hand2) - get_rank(*hand1)
def get_rank(v1, suit1, v2, suit2):
    get_card_value = "T 23456789   J    QA        K".find
    # rank_table = [[17,9,15,5,16,11,14,9,13,6],[12,2,10,1,10,4,8,3,7,0]]
    # rank_table = ("H9F5GBE9D6","C2A1A48370") # Base-18 encoding of ranks
    rank_table = "HC92FA51GAB4E893D760" # Interleaved base-18 encoding

    # ASCII-value decoding has the same ranking effect as base-18 decoding
    return ord(rank_table[suit1 == suit2::2][get_card_value(v2) * get_card_value(v1) % 10])

The function f takes two arguments representing the hand of player 1 and player 2. It returns a positive, negative, or zero value in the case of a player 1 win, a player 2 win, or a draw, correspondingly. Each hand is encoded as a single string, e.g. "7cQh".


highest common factor-fewest iterations Find the highest common factor of two(positive integer) input numbers (not greater than 5000) in the minimum number of iterations.

If you use a loop, it should increment a counter, starting at 0 for the first run. The counter should be the first statement in the loop. If you use more than one loop, they too should have a similar counter.

So

counter_1=0;
counter_2=0;
...
loop{
    counter_1=counter_1 + 1;
    ...
    code
    ...

    loop_nested{
        counter_2=counter_2 + 1;
        ...
        code
        ...
    }
}
total_count=counter_1 + counter_2 + ...

Test cases
first-number second-number-->expected-output

450 425-->25

27 23-->1

1000 1001-->1

36 54-->18

2 4000-->2

4000 2500-->500

2000 4000-->2000

99 75-->3

584 978-->2

3726 4380-->6

The code with the lowest sum of all counters for all test cases wins.
There is no restriction on program length. Of course, you can't use any standard functions. There is no restriction on the language that you use.

Also, please write the sum of counters that your code produces.


I'll time your function, but I don't work weekends My boss needs to know how long it takes to add together two integers. But, I don't like to work weekends, and I think its fair that my code doesn't either. The problem is, the boss is a demanding guy and thinks I should put in over time to make sure the time it takes stays the same, and I know he is going to check if the code works properly.

Can you write me a short program that:

Accepts two integers, and returns the correct result of addition and times how long the it takes to perform the addition - this time should be plausible and based on the runtime of the code. However, if you need to sneak some operations between the timed code that makes it run slightly longer than it should this is permitted. You cannot however just output a fake time.
Doesn't work on weekends in the codes local-time (it can't just return a wrong result, the code needs to break, error, or otherwise fail to execute)
Isn't immediately obvious as to why it doesn't work on weekends

I know the first criterion is kind of weird, but I wanted to make sure people could import date/time libraries if needed, without raising suspicion for criteria 3. However, I'm sure there are some smart folk, so -10 characters to anyone who can do this, without using calendar functions from standard date libraries

Regarding 'standard date/time libraries'

Examples of standard datetime libraries include pythons datetime, javascript date object library, java.util.Date and the like. Functions to calculate timedeltas for execution such as pythons timeit module would not violate this criteia as the boss is expectng the code to to be timed. In some cases, these libraries will need to be imported to access any time functions, so its permitted to call functions that return the time since the start of the current epoch as an integer, but calendar functions that return structured datetime objects that can give separate hours, days, etc... are not allowed.

edit: Regarding Dan04's question, the code must meet these 4 criteria regarding when it will work or not work. You should also explain how your code checks the time, as the slack on Monday morning/Friday night should give some opportunity for some creative ways to shorten the code.

must not work from 00:00:00 Saturday morning through 23:59:59 Sunday night.
must always work from 06:00:00 Monday morning through 19:59:59 Friday evening
can either work or not work from 00:00:00 Monday morning through 5:59:59 Monday morning
can either work or not work from 20:00:00 Friday evening through 23:59:59 Friday night morning

edit2: By immediately obvious it must meet the following 3 criteria:

Must not call a function that called DayOfWeek (or similar), without using it to calculate the time of the function.
Must not use Saturday or Sunday or their abbreviations in English.
Must not use Sat or Sun (or in their alternate letter cases) without an identical named variable not used to determine the day of the week or when determining if the code should run.

Rebmu: 17 (27 - 10, obfuscated) or 30 unobfuscated

Rebmu is specifically designed to play code golf while being readable (for those who get the "trick"), so the obfuscation rule is against its principle.  But:

DnowRjRkILd/7 6[pDT[adJk]]

It works all day on weekdays:

Input Integer: 10
Input Integer: 20
0:00:00.000008

...but on weekends it just does nothing:

Input Integer: 10
Input Integer: 20

Explanation:

Using the unmushing and noticing capital runs of letters are separate words, and the lack of a leading capital run means we're not making a set-word, we get the abbreviated Rebol:

d: now
r j
r k
il d/7 6 [
    p dt [
        ad j k
    ]
]

Un-abbreviating it, what you wind up with is:

;-- save current date and time into "d"
d: now

;-- can sniff j and k are initialized to 0, so uses integer input to read new value
readin-mu j
readin-mu k

;-- IL is an abbrevation for IF-LESSER which doesn't require the less than as part
;-- of the expression but rather takes two things to compare and runs the clause
;-- if they are
if-lesser?-mu d/7 6 [
    print delta-time [
        add j k
    ]
]

Date numbers in Rebol are numbered 1 for Monday up to 7 for Sunday.  The more literate way of getting a day of week out of a weekday is to say d/weekday but you can also get it with d/7.  My preferred solution without changing things just to adapt to this problem would be more like:

rJrKilNOW/weekday 6[pDT[adJk]]

But if were to update the vocabulary for general application to this style of problem, which it probably comes up often enough to not want to fall through to verbose Rebol every time, I'd probably make MON thru SUN be 1 - 7) and abbreviate NOW WEEKDAY, at which point it would look probably more like...

rJrKilNW/wkdySAT[pDT[adJk]]

Notes

As usual, you can make "the program" itself a wee bit shorter if you allow the inputs to be passed to Rebmu as arguments and just accept the evaluation result (here, either a value of type time or NONE) without printing it:

  rebmu/args [DnowILd/7 6[dt[adJk]] [J10 K20]

Also delta-time, dates, image generation, and a crazy number of things are already included in Rebol's half-megabyte, zero-install executable.


Calculate a check digit using the Damm algorithm There are popular check digit algorithms such as Luhn and then there are good ones, for example the Damm algorithm. The only possible reason behind the popularity of algorithms such as Luhn is that there exist code golfed implementations of them. This means that we as a community have the power to change the world by providing golfed implementations of better algorithms.

So this challenge is to change the world by writing a function or a complete program in your language of choice that calculates a check digit using the Damm algorithm. The answer with the smallest number of characters (not bytes) will be chosen as a winner in a few weeks. Note that all helping functions and the declaration of the operation table must be included in the character count. In case of a tie the most popular answer will be chosen.

This algorithm revolves around an operation table that must be a weakly totally anti-symmetric quasigroup of order 10. The operation table that can be found in the Wikipedia article about the Damm algorithm is the one which is to be used in this challenge. For completeness sake I will reproduce it below:

    |   0   1   2   3   4   5   6   7   8   9
----+----------------------------------------
0   |   0   3   1   7   5   9   8   6   4   2
1   |   7   0   9   2   1   5   4   8   6   3
2   |   4   2   0   6   8   7   1   3   5   9
3   |   1   7   5   0   9   8   3   4   2   6
4   |   6   1   2   3   0   4   5   9   7   8
5   |   3   6   7   4   2   0   9   5   8   1
6   |   5   8   6   9   7   2   0   1   3   4
7   |   8   9   4   5   3   6   2   0   1   7
8   |   9   4   3   8   6   1   7   2   0   5
9   |   2   5   8   1   4   3   6   7   9   0

In short (for details see the Wikipedia article) the algorithm works as follows:

You start with a list of digits to be processed and an interim digit which is set to 0.
For every digit in the list you calculate a new interim digit by using the digit as the column index and the previous interim digit as the row index.
The final interim digit is the check digit. If you are validating a number that already has an added check digit the final interim digit is 0 if the number is valid.

Your program or function must accept a string that can contain any characters except null, but it should only concern itself with the digits in the string. It must either print (if a program) or return (if a function) the original string with the calculated check digit appended. If you chose to write a program the program may either accept the input as an argument or as standard input. If the input string is empty or doesn't contain any digits you must return or append a zero.

Some examples:

Input       |   Output
------------+-------------
42          |   427
427         |   4270
2 to 2      |   2 to 29
23 42 76-   |   23 42 76-5
-           |   -0

CJam, 54 characters

q_o{A,s&},{~0"끼´慜䪝膞䝮芜㮜ꡞ靓渏縰蒆㣉倔쵶"2G#bAb+A/T==:T;}/T

There is one unprintable character in there, so you might want to use the permalink below.

Test it here.

Explanation

The interim digit is being tracked in  T, which CJam initialises to 0.

q_o                                  "Read STDIN, duplicate it and print it.";
   {A,s&},                           "Filter out all non-digit characters.";
          {                     }/   "For each digit character.";
           ~                         "Eval to get the digit itself.";
            0                        "Push a zero.";
             "..."2G#b               "Push that long string and interpret the character
                                      codes as the digits of a base-2^16 number.";
                      Ab+            "Get base-10 digits and prepend the 0.";
                         A/          "Split into rows of 10.";
                           T=        "Select row based on interim digit.";
                             =       "Select column based on current digit.";
                              :T;    "Store in T and discard.";
                                   T "Push the interim digit to be printed.";


Golf me a card dealer Frank has been working IT his whole life. Each day he responds to tickets, organizes equipment, and reports to his boss. One day, near the closing time on friday, Frank is doing his final inventory and sorting come cables in the supply closet. Suddenly, the door closes and locks from the outside! Such audacity! Frank shakes the door to try and let anyone know that he's stuck in the closet. Blast, nobody comes to his aid. With no cellphone, and no internet connection, Frank settles in with his laptop. After countless games of solitaire, frank decides to make his own card game....

Challenge:

In this case, you are frank (but not really). Your challenge is to create a dealer that can deal hands of cards, that could be dealt realistically. Your program needs to do 2 things: deal hands of cards according to an input, and take all the hands and reshuffle them. You must do this in the least ammount of bytes possible.

Rules:

Possible cards include all classic numbers and faces (a,2,3,4,5,6,7,8,9,10,j,q,k) and all suits (c,s,h,d), and two jokers (0j).

If a card is dealt, it cannot be dealt again until the program is given the reshuffle command, or it runs out of cards.

valid inputs are 'd' to deal a hand of 6 cards, and 'r' to reshuffle. NOTE that you can only deal out 9 hands before you run out of cards. Your program can either:
Automatically reshuffle,
Or give a 'X' to indicate that the dealer is out of cards.

your program needs to be able to take multiple commands over its running span.

All possible hands need to be able to be dealt in every order. Though, your program does NOT have to be random.

Examples:

We deal twice, the first hand yields the 2 of hearts, a 4 of spades, 9 of clubs, a joker, an ace of spades, and a 6 of diamonds. The second hand yields the 3 of hearts, the 10 of diamonds, the 10 of clubs, the king of clubs, the ace of diamonds, and the queen of spades. this is VALID because this is possible in real life.

  d
  2h4s9c0jas6d
  d
  3h10d10ckcadqs

We deal twice, the first hand yields a mass of 5 cards (indicated by the dashes) and a 6 of hearts. The second hand deals another mass of 5 cards (again, the dashes) and another 6 of hearts. This is INVALID because it cannot happen in real life.

  d
  -----6h
  d
  6h-----

we deal once, reset, and deal again. some of the cards from the first and the second deal match. this is VALID because cardstacks are renewed when shuffled.

  d
  123456
  r

  d
  456789

Scoring:

As with any golf, the lowest byte count wins! Good luck!

Pyth - 42 41 bytes
Will need to restructure this.
VcQ\rj<c9.S++M*+md"jqka"}2T"cshd"m"0j"2lN

Try it online here.
Stops giving cards after 9 deals.