The number of reachable snake orientations This challenge is not about the game Snake.

Imagine a 2d snake formed by drawing a horizontal line of length n.  At integer points along its body, this snake can rotate its body by 90 degree. If we define the front of the snake to be on the far left to start with, the rotation will move the back part of the snake and the front part will stay put. By doing repeated rotations it can make a lot of different snake body shapes.

Rules

One part of the snake's body can't overlap another.
It has to be possible to reach the final orientation without any parts of the snake's body overlapping in between. Two points that touch are counted as overlapping in this problem.
I regard a snake and its reverse as being the same shape.

Task

  Up to rotation, translation and mirror symmetry, what is the total
  number of different snake body shapes that can be made?

Example of a rotation of part of the snakes body. Imagine n=10 and the snake is in its start orientation of a straight line. Now rotate at point 4 90 degrees counter-clockwise. We get the snake from  4 to 10 (the tail of the snake) lying vertically and the snake from 0 to 4 lying horizontally. The snake now has one right angle in its body.

Here are some examples thanks to Martin Büttner.

We start with the horizontal snake.

Now we rotate from position 4.

We end up after the rotation in this orientation.

Now let us consider this orientation of a different snake.

We can now see an illegal move where there would be an overlap caused during the rotation.

Score

Your score is the largest n for which your code can solve the problem in less than one minute on my computer.

When a rotation happens it will move one half of the snake with it. We do have to worry about whether any of this part which is rotated might overlap a part of the snake during the rotation.  For simplicity we can assume the snake has width zero.  You can only rotate at a particular point in snake up to 90 degrees clockwise of counter clockwise. For, you can never full fold the snake in two as that would have involved two rotations at the same point in the same direction.

Shapes that can't be made

A simple example of a shape that can't be made is a capital T.   A more sophisticated version is

(Thank you to Harald Hanche-Olsen for this example)

In this example all the adjacent horizontal lines are 1 apart as are the vertical ones. There is therefore no legal move from this position and as the problem is reversible there is therefore no way to get there from the starting position.

Languages and libraries

You can use any language which has a freely available compiler/interpreter/etc. for Linux and any libraries which are also freely available for Linux.

My machine
The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. As a consequence, only use easily available free software and please include full instructions how to compile and run your code.

Python 3 - provisional score: n=11 (n=13 with PyPy*)
Since there have been no answers in the first week, here is an example in Python to encourage competition. I've tried to make it reasonably readable so that inefficiencies can be identified easily to give ideas for other answers.
Approach

Start with the straight snake and find all the positions that can be legally reached in one move.
Find all the positions that can be legally reached from those positions, that haven't already been identified.
Repeat until no more can be found, and return the number of positions found altogether.

Code
(now with some doctests and asserts after my incorrect first attempt)
'''
Snake combinations

A snake is represented by a tuple giving the relative orientation at each joint.
A length n snake has n-1 joints.
Each relative orientation is one of the following:

0: Clockwise 90 degrees
1: Straight
2: Anticlockwise 90 degrees

So a straight snake of length 4 has 3 joints all set to 1:

(1, 1, 1)

x increases to the right
y increases upwards

'''

import turtle

def all_coords(state):
    '''Return list of coords starting from (0,0) heading right.'''
    current = (1, 0)
    heading = 0
    coords = [(0,0), (1,0)]
    for item in state:
        heading += item + 3
        heading %= 4
        offset = ((1,0), (0,1), (-1,0), (0,-1))[heading]
        current = tuple(current[i]+offset[i] for i in (0,1))
        coords.append(current)
    return coords

def line_segments(coords, pivot):
    '''Return list of line segments joining consecutive coords up to pivot-1.'''
    return [(coords[i], coords[i+1]) for i in range(pivot+1)]

def rotation_direction(coords, pivot, coords_in_final_after_pivot):
    '''Return -1 if turning clockwise, 1 if turning anticlockwise.'''
    pivot_coord = coords[pivot + 1]
    initial_coord = coords[pivot + 2]
    final_coord = coords_in_final_after_pivot[0]
    initial_direction = tuple(initial_coord[i] - pivot_coord[i] for i in (0,1))
    final_direction = tuple(final_coord[i] - pivot_coord[i] for i in (0,1))
    return (initial_direction[0] * final_direction[1] -
            initial_direction[1] * final_direction[0]
            )

def intersects(arc, line):
    '''Return True if the arc intersects the line segment.'''
    if line_segment_cuts_circle(arc, line):
        cut_points = points_cutting_circle(arc, line)
        if cut_points and cut_point_is_on_arc(arc, cut_points):
            return True

def line_segment_cuts_circle(arc, line):
    '''Return True if the line endpoints are not both inside or outside.'''
    centre, point, direction = arc
    start, finish = line
    point_distance_squared = distance_squared(centre, point)
    start_distance_squared = distance_squared(centre, start)
    finish_distance_squared = distance_squared(centre, finish)
    start_sign = start_distance_squared - point_distance_squared
    finish_sign = finish_distance_squared - point_distance_squared
    if start_sign * finish_sign <= 0:
        return True

def distance_squared(centre, point):
    '''Return the square of the distance between centre and point.'''
    return sum((point[i] - centre[i]) ** 2 for i in (0,1))

def cut_point_is_on_arc(arc, cut_points):
    '''Return True if any intersection point with circle is on arc.'''
    centre, arc_start, direction = arc
    relative_start = tuple(arc_start[i] - centre[i] for i in (0,1))
    relative_midpoint = ((relative_start[0] - direction*relative_start[1])/2,
                         (relative_start[1] + direction*relative_start[0])/2
                         )
    span_squared = distance_squared(relative_start, relative_midpoint)
    for cut_point in cut_points:
        relative_cut_point = tuple(cut_point[i] - centre[i] for i in (0,1))
        spacing_squared = distance_squared(relative_cut_point,
                                           relative_midpoint
                                           )
        if spacing_squared <= span_squared:
            return True

def points_cutting_circle(arc, line):
    '''Return list of points where line segment cuts circle.'''
    points = []
    start, finish = line
    centre, arc_start, direction = arc
    radius_squared = distance_squared(centre, arc_start)
    length_squared = distance_squared(start, finish)
    relative_start = tuple(start[i] - centre[i] for i in (0,1))
    relative_finish = tuple(finish[i] - centre[i] for i in (0,1))
    relative_midpoint = tuple((relative_start[i] +
                               relative_finish[i]
                               )*0.5 for i in (0,1))
    determinant = (relative_start[0]*relative_finish[1] -
                   relative_finish[0]*relative_start[1]
                   )
    determinant_squared = determinant ** 2
    discriminant = radius_squared * length_squared - determinant_squared
    offset = tuple(finish[i] - start[i] for i in (0,1))
    sgn = (1, -1)[offset[1] < 0]
    root_discriminant = discriminant ** 0.5
    one_over_length_squared = 1 / length_squared
    for sign in (-1, 1):
        x = (determinant * offset[1] +
             sign * sgn * offset[0] * root_discriminant
             ) * one_over_length_squared
        y = (-determinant * offset[0] +
             sign * abs(offset[1]) * root_discriminant
             ) * one_over_length_squared
        check = distance_squared(relative_midpoint, (x,y))
        if check <= length_squared * 0.25:
            points.append((centre[0] + x, centre[1] + y))
    return points

def potential_neighbours(candidate):
    '''Return list of states one turn away from candidate.'''
    states = []
    for i in range(len(candidate)):
        for orientation in range(3):
            if abs(candidate[i] - orientation) == 1:
                state = list(candidate)
                state[i] = orientation
                states.append(tuple(state))
    return states

def reachable(initial, final):
    '''
    Return True if final state can be reached in one legal move.

    >>> reachable((1,0,0), (0,0,0))
    False

    >>> reachable((0,1,0), (0,0,0))
    False

    >>> reachable((0,0,1), (0,0,0))
    False

    >>> reachable((1,2,2), (2,2,2))
    False

    >>> reachable((2,1,2), (2,2,2))
    False

    >>> reachable((2,2,1), (2,2,2))
    False

    >>> reachable((1,2,1,2,1,1,2,2,1), (1,2,1,2,1,1,2,1,1))
    False

    '''
    pivot = -1
    for i in range(len(initial)):
        if initial[i] != final[i]:
            pivot = i
            break

    assert pivot > -1, '''
        No pivot between {} and {}'''.format(initial, final)
    assert initial[pivot + 1:] == final[pivot + 1:], '''
        More than one pivot between {} and {}'''.format(initial, final)

    coords_in_initial = all_coords(initial)
    coords_in_final_after_pivot = all_coords(final)[pivot+2:]
    coords_in_initial_after_pivot = coords_in_initial[pivot+2:]
    line_segments_up_to_pivot = line_segments(coords_in_initial, pivot)

    direction = rotation_direction(coords_in_initial,
                                   pivot,
                                   coords_in_final_after_pivot
                                   )

    pivot_point = coords_in_initial[pivot + 1]

    for point in coords_in_initial_after_pivot:
        arc = (pivot_point, point, direction)
        if any(intersects(arc, line) for line in line_segments_up_to_pivot):
            return False
    return True

def display(snake):
    '''Display a line diagram of the snake.

    Accepts a snake as either a tuple:

    (1, 1, 2, 0)

    or a string:

    "1120"

    '''
    snake = tuple(int(s) for s in snake)
    coords = all_coords(snake)

    turtle.clearscreen()
    t = turtle.Turtle()
    t.hideturtle()
    s = t.screen
    s.tracer(0)

    width, height = s.window_width(), s.window_height()

    x_min = min(coord[0] for coord in coords)
    x_max = max(coord[0] for coord in coords)
    y_min = min(coord[1] for coord in coords)
    y_max = max(coord[1] for coord in coords)
    unit_length = min(width // (x_max - x_min + 1),
                      height // (y_max - y_min + 1)
                      )

    origin_x = -(x_min + x_max) * unit_length // 2
    origin_y = -(y_min + y_max) * unit_length // 2

    pen_width = max(1, unit_length // 20)
    t.pensize(pen_width)
    dot_size = max(4, pen_width * 3)

    t.penup()
    t.setpos(origin_x, origin_y)
    t.pendown()

    t.forward(unit_length)
    for joint in snake:
        t.dot(dot_size)
        t.left((joint - 1) * 90)
        t.forward(unit_length)
    s.update()

def neighbours(origin, excluded=()):
    '''Return list of states reachable in one step.'''
    states = []
    for candidate in potential_neighbours(origin):
        if candidate not in excluded and reachable(origin, candidate):
            states.append(candidate)
    return states

def mirrored_or_backwards(candidates):
    '''Return set of states that are equivalent to a state in candidates.'''
    states = set()
    for candidate in candidates:
        mirrored = tuple(2 - joint for joint in candidate)
        backwards = candidate[::-1]
        mirrored_backwards = mirrored[::-1]
        states |= set((mirrored, backwards, mirrored_backwards))
    return states

def possible_snakes(snake):
    '''
    Return the set of possible arrangements of the given snake.

    >>> possible_snakes((1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1))
    {(1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1)}

    '''
    reached = set()
    candidates = set((snake,))

    while candidates:
        candidate = candidates.pop()
        reached.add(candidate)
        new_candidates = neighbours(candidate, reached)
        reached |= mirrored_or_backwards(new_candidates)
        set_of_new_candidates = set(new_candidates)
        reached |= set_of_new_candidates
        candidates |= set_of_new_candidates

    excluded = set()
    final_answers = set()
    while reached:
        candidate = reached.pop()
        if candidate not in excluded:
            final_answers.add(candidate)
            excluded |= mirrored_or_backwards([candidate])

    return final_answers

def straight_derived_snakes(length):
    '''Return the set of possible arrangements of a snake of this length.'''
    straight_line = (1,) * max(length-1, 0)
    return possible_snakes(straight_line)

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    import sys
    arguments = sys.argv[1:]
    if arguments:
        length = int(arguments[0])
    else:
        length = int(input('Enter the length of the snake:'))
    print(len(straight_derived_snakes(length)))

Results
On my machine the longest snake that can be calculated in under 1 minute is length 11 (or length 13 with PyPy*). This is obviously just a provisional score until we find out what the official score is from Lembik's machine.
For comparison, here are the results for the first few values of n:
 n | reachable orientations
-----------------------------
 0 | 1
 1 | 1
 2 | 2
 3 | 4
 4 | 9
 5 | 22
 6 | 56
 7 | 147
 8 | 388
 9 | 1047
10 | 2806
11 | 7600
12 | 20437
13 | 55313
14 | 148752
15 | 401629
16 | 1078746
17 | MemoryError (on my machine)

Please let me know if any of these turn out to be incorrect.
If you have an example of an arrangement that should not be able to be unfolded, you can use the function neighbours(snake) to find any arrangements reachable in one step, as a test of the code. snake is a tuple of joint directions (0 for clockwise, 1 for straight, 2 for anticlockwise). For example (1,1,1) is a straight snake of length 4 (with 3 joints).
Visualisation
To visualise a snake you have in mind, or any of the snakes returned by neighbours, you can use the function display(snake). This accepts a tuple like the other functions, but since it is not used by the main program and therefore does not need to be fast, it will also accept a string, for your convenience.
display((1,1,2,0)) is equivalent to display("1120")
As Lembik mentions in the comments, my results are identical to OEIS A037245 which does not take into account intersections during rotation. This is because for the first few values of n there is no difference - all shapes that do not self-intersect can be reached by folding a straight snake. The correctness of the code can be tested by calling neighbours() with a snake that cannot be unfolded without intersection. Since it has no neighbours it will contribute only to the OEIS sequence, and not to this one. The smallest example I am aware of is this length 31 snake that Lembik mentioned, thanks to David K:
(1,1,1,1,2,1,2,1,1,1,1,1,1,2,1,1,1,2,1,1,2,2,1,0,1,0,1,1,1,1)
display('111121211111121112112210101111') gives the following output:

Tip: If you resize the display window and then call display again, the snake will be fitted to the new window size.

I'd love to hear from anyone who has a shorter example with no neighbours. I suspect that the shortest such example will mark the smallest n for which the two sequences differ.

*Note that each increment of n takes very roughly 3 times as long, so increasing from n=11 to n=13 requires almost 10 times the time. This is why PyPy only allows increasing n by 2, even though it runs considerably faster than the standard Python interpreter.


Find the beats in an MP3 file In this challenge, your task is to take an simple recording in mp3 format and find the time offsets of the beats in the file. Two example recordings are here:

https://dl.dropboxusercontent.com/u/24197429/beats.mp3
https://dl.dropboxusercontent.com/u/24197429/beats2.mp3

Here is the third recording with much more noise than the two previous:

https://dl.dropboxusercontent.com/u/24197429/noisy-beats.mp3

For example, the first recording is 65 seconds long and contains exactly (unless I miscounted!) 76 beats. Your job is to devise a program that takes such an mp3 file as input and outputs a sequence of the time offsets in milliseconds of the beats in the file. A beat is defined to occur, of course, when the guitarist playing plucks one or more strings.

Your solution must:

Work on any mp3 file of similar "complexity". It can fail on to noisy recordings or to quickly played melodies -- I don't care.
Be fairly precise. Tolerance is +/- 50 ms. So if the beat occurs at 1500 ms and your solution reports 1400, then that is unacceptable.
Use only free software. Calling ffmpeg is allowed as is using any freely available third party software for your language of choice.

The winning criteria is ability to successfully detect beats despite noise in the supplied files. In case of a tie, the shortest solution wins (length of 3rd party code isn't added to the count).

Python 2.7 492 bytes (beats.mp3 only)

This answer can identify the beats in beats.mp3, but will not identify all notes on beats2.mp3 or noisy-beats.mp3. After the description of my code, I'll go into detail as to why.

This uses PyDub (https://github.com/jiaaro/pydub) to read in the MP3. All other processing is NumPy.

Golfed Code

Takes a single command line argument with the file name. It will output each beat in ms on a separate line.

import sys
from math import *
from numpy import *
from pydub import AudioSegment
p=square(AudioSegment.from_mp3(sys.argv[1]).set_channels(1).get_array_of_samples())
n=len(p)
t=arange(n)/44.1
h=array([.54-.46*cos(i/477) for i in range(3001)])
p=convolve(p,h, 'same')
d=[p[i]-p[max(0,i-500)] for i in xrange(n)]
e=sort(d)
e=d>e[int(.94*n)]
i=0
while i<n:
 if e[i]:
  u=o=0
  j=i
  while u<2e3:
   u=0 if e[j] else u+1
   #u=(0,u+1)[e[j]]
   o+=e[j]
   j+=1
  if o>500:
   print "%g"%t[argmax(d[i:j])+i]
  i=j
 i+=1

Ungolfed Code

# Import stuff
import sys
from math import *
from numpy import *
from pydub import AudioSegment

# Read in the audio file, convert from stereo to mono
song = AudioSegment.from_mp3(sys.argv[1]).set_channels(1).get_array_of_samples()

# Convert to power by squaring it
signal = square(song)
numSamples = len(signal)

# Create an array with the times stored in ms, instead of samples
times = arange(numSamples)/44.1

# Create a Hamming Window and filter the data with it. This gets rid of a lot of
# high frequency stuff.
h = array([.54-.46*cos(i/477) for i in range(3001)])
signal = convolve(signal,h, 'same') #The same flag gets rid of the time shift from this

# Differentiate the filtered signal to find where the power jumps up.
# To reduce noise from the operation, instead of using the previous sample,
# use the sample 500 samples ago.
diff = [signal[i] - signal[max(0,i-500)] for i in xrange(numSamples)]

# Identify the top 6% of the derivative values as possible beats
ecdf = sort(diff)
exceedsThresh = diff > ecdf[int(.94*numSamples)]

# Actually identify possible peaks
i = 0
while i < numSamples:
 if exceedsThresh[i]:
  underThresh = overThresh = 0
  j=i
  # Keep saving values until 2000 consecutive ones are under the threshold (~50ms)
  while underThresh < 2000:
   underThresh =0 if exceedsThresh[j] else underThresh+1
   overThresh += exceedsThresh[j]
   j += 1
  # If at least 500 of those samples were over the threshold, take the maximum one
  # to be the beat definition
  if overThresh > 500:
   print "%g"%times[argmax(diff[i:j])+i]
  i=j
 i+=1

Why I miss notes on the other files (and why they are incredibly challenging)

My code looks at changes in signal power in order to find the notes. For beats.mp3, this works really well. This spectrogram shows how the power is distributed over time (x axis) and frequency (y axis). My code basically collapses the y axis down to a single line.

Visually, it's really easy to see where the beats are. There's a yellow line that tapers off again and again. I highly encourage you to listen to beats.mp3 while you follow along on the spectrogram to see how it works.

Next I'll go to noisy-beats.mp3 (because that's actually easier than beats2.mp3.
.
Once again, see if you can follow along with recording. Most of the lines are fainter, but still there. However, in some spots, the bottom string is still ringing when the quiet notes start. That makes finding them especially hard, because now, you have to find them by changes in frequency (the y axis) rather than just amplitude.

beats2.mp3 is incredibly challenging. Here's the spectrogram

In the first bit, there some lines, but some notes really bleed over the lines. To reliably identify notes, you'd have to start tracking the pitch of the notes (fundamental and harmonics) and seeing where those change. Once the first bit is working, the second bit is twice as hard as the tempo doubles!

Basically, to reliably identify all of these, I think it takes some fancy note detection code. Seems like this would be a good final project for someone in a DSP class.


Detect if your program has been mutated Write a program that terminates without an error.

If any single byte is substituted by any other byte the program should output

CORRUPTED

Do not read your source code from a file
Your program should not produce any other output

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

Edit: removed "NOT CORRUPTED" requirement

A Pear Tree, 76 bytes

$@='NOT ';print"$@CORRUPTED"__DATA__ =®®”print"$@CORRUPTED"__DATA__ =®®”Ê®›~

This program contains a few stray octets that aren't valid UTF-8. As such, it's shown as it looks in Windows-1252. (By default, if A Pear Tree sees a non-ASCII octet in a string literal or the like it treats it as an opaque object and doesn't try to understand it beyond being aware of what its character code is; this behaviour can be changed via an encoding declaration but the program doesn't have one. So the program is logically in "unspecified ASCII-compatible character set". All the non-ASCII octets are in comments anyway, so it doesn't really matter.)

Explanation

A Pear Tree checksums the program, looking for the longest substring that has a CRC-32 of 00000000. (If there's a tie, it picks the octetbetically first.) Then the program gets rotated to put it at the start. Finally, the program gets interpreted as a language that's almost a superset of Perl, defining a few things that are undefined in Perl to work the same way as in Python (and with a few minor changes, e.g. print prints a final newline in A Pear Tree but not in Perl). This mechanism (and the language as a whole) was designed for polyglot and radiation-hardening problems; this isn't the former, but it's definitely the latter.

In this program, we have two notable substrings that CRC-32 to 00000000; the entire program does, and so does print"$@CORRUPTED"__DATA__ =®® by itself (which appears twice). As such, if the program is uncorrupted, it'll set $@ to NOT  and then print it followed by CORRUPTED. If the program is corrupted, then the CRC-32 of the program as a whole will fail to match, but one of the shorter sections will remain uncorrupted. Whichever one is rotated to the start of the program will just print CORRUPTED, as $@ will be the null string.

Once the string's been printed, __DATA__ is used to prevent the rest of the program running. (It crosses my mind writing this that __END__ could be used instead, which would clearly save two bytes. But I may as well post this version now, because I've spent a bunch of time verifying it, and a modified version would have to be re-verified due to the CRC changes; and I haven't put a huge amount of effort into golfing the "payload" yet, so I want to see if anyone has other improvements in the comments that I can incorporate at the same time. Note that # doesn't work in the situation where a character is corrupted into a newline.)

You might be wondering how I managed to control the CRC-32 of my code in the first place. This is a fairly simple mathematical trick based on the way that CRC-32 is defined: you take the CRC-32 of the code, write it in little-endian order (the reverse of the byte order that's normally used by CRC-32 calculation programs), and XOR with 9D 0A D9 6D. Then you append that to the program, and you'll have a program with a CRC-32 of 0. (As the simplest example possible, the null string has a CRC-32 of 0, thus 9D 0A D9 6D also has a CRC-32 of 0.)

Verification

A Pear Tree can handle most sorts of mutations, but I'm assuming "changed" means "replaced with an arbitrary octet". It's theoretically possible (although unlikely in a program this short) that there could be a hash collision somewhere that lead to the wrong program running, so I had to check via brute force that all possible octet substitutions would leave the program working correctly. Here's the verification script (written in Perl) that I used:

use 5.010;
use IPC::Run qw/run/;
use warnings;
use strict;
undef $/;
$| = 1;
my $program = <>;
for my $x (0 .. (length $program - 1)) {
    for my $a (0 .. 255) {
        print "$x $a    \r";
        my $p = $program;
        substr $p, $x, 1, chr $a;
        $p eq $program and next;
        alarm 4;
        run [$^X, '-M5.010', 'apeartree.pl'], '<', \$p, '>', \my $out, '2>', \my $err;
        if ($out ne "CORRUPTED\n") {
            print "Failed mutating $x to $a\n";
            print "Output: {{{\n$out}}}\n";
            print "Errors: {{{\n$err}}}\n";
            exit;
        }
    }
}

say "All OK!    ";


Sum of integers in string, separated by non-numericals such as 'a' and 'Y' Create a program which sums all integers found in a string which is set as a variable in the program (thus, the program doesn't have to handle any input). The integer numbers are separated by non-numericals (anything but 0, 1, 2, 3, ..., 9).

Examples:

e7rde f  ,fe 43 jfj 54f4sD = 7+43+54+4=108
5 = 5
64 545,5445-32JIFk0ddk = 64+545+5445+32+0=6086
0ab0 = 0+0 = 0

Extra notes:

Unicode support is not necessary, but allowed
-n (where n is an integer) is not counted as a negative n, but as a hyphen followed by n.

The answer may be printed on the screen (but not required).

Shortest answer (in characters) win.

Ruby 1.9, 21 characters

eval a.scan(/\d+/)*?+

To print the solution to stdout, 2 additional characters are required:

p eval a.scan(/\d+/)*?+

And to read from stdin instead of using a predefined variable, another 3 characters have to be used:

p eval gets.scan(/\d+/)*?+

For Ruby 1.8, replace ?+ with "+" to get a working solution in 22 characters.


0.0000000000000000001 Notice the pattern in the below sequence:

0.1, 0.01, 0.001, 0.0001, 0.00001 and so on, until reaching 0.{one hundred zeros}1

Then, continued:

0.2, 0.02, 0.002, 0.0002, 0.00002 and so on, until reaching 0.{two hundred zeros}2

Continued:

0.3, 0.03, etc, until 0.{three hundred zeros}3

Continued:

0.4, 0.04, etc, until 0.{four hundred zeros}4

Sped up a bit:

0.10, 0.010, etc.  until 0.{one thousand zeros}10

Sped up some more:

0.100, 0.0100...

You get the idea.

The input your code will receive is an integer, the number of terms, and the output is that many number of terms of the sequence.

Input and output formats are unrestricted, and separators are not required.

Trailing zeros are necessary.

Standard loopholes apply.

The outputs of some nth terms are given below:

nth term -> number
-------------------
1        -> 0.1
102      -> 0.2
303      -> 0.3
604      -> 0.4
1005     -> 0.5
1506     -> 0.6
2107     -> 0.7
2808     -> 0.8
3609     -> 0.9
4510     -> 0.10

05AB1E, 23 bytes

Online compiler can't show all terms for high N but it works fine offline.

Lvy2°*>F„0.0N×yJ,¼¾¹Qiq

Explanation

                          # implicit input X
Lv                        # for each y in range [1 .. X]
  y2°*>F                  # for each N in range [0 .. y*100+1)
        „0.               # push the string "0."
           0N×            # push 0 repeated N times
              y           # push current y
               J,         # join and print
                 ¼¾¹Qiq   # quit the program after X terms printed

Try it online!


Zipper multiplication Introduction

Let's define a new arithmetical operation, which I call zipper multiplication.
To zipper multiply two nonnegative integers, you add leading zeros to make the lengths match, multiply the corresponding base-10 digits of the numbers, add leading zeros to the results to get 2-digit numbers, concatenate them, and finally drop leading zeros.

Here's an example with A = 1276 and B = 933024:

1. Add leading zeros
 A = 001276
 B = 933024

2. Multiply digit-wise
 A = 0  0  1  2  7  6
 B = 9  9  3  0  2  4
 ->  0  0  3  0 14 24

3. Pad to 2 digits
 -> 00 00 03 00 14 24

4. Concatenate
 -> 000003001424

5. Drop leading zeros
 -> 3001424

The operation is extended to all integers with the usual sign rules: positive times negative is negative, negative times negative is positive and so on.

The task

Your inputs are two integers, and your output is their zipper multiplication.
You should be able to handle arbitrarily large inputs.
Input and/or output can be in string format (and indeed must be, if your language doesn't support arbitrarily large integers).
Note that -0 is not a valid input or output.

Rules and scoring

You can write a full program or a function, and the lowest byte count wins.

Test cases

0 0 -> 0
302 40 -> 0
302 -40 -> 0
-4352 448 -> -122016
0 6623 -> 0
0 -6623 -> 0
20643 -56721 -> -1000420803
63196 21220 -> 1203021800
1276 933024 -> 3001424
-1276 933024 -> -3001424
-1276 -933024 -> 3001424
5007204555 350073039 -> 12001545
-612137119 -8088606033 -> 816060042000327
3389903661 -6619166963 -> -18180881090018543603
-23082746128560880381 1116941217 -> -8050600723200060807
-668336881543038127783364011867 896431401738330915057436190556 -> -485448120906320001351224000900090235004021121824000900403042
402878826066336701417493206805490000415 312487283677673237790517973105761463808 -> 120004325656161618004242182118140007280900200921180018080025285400000000320040

Jelly, 11 10 bytes

ƓDUz0P€Uḅ³

Try it online!

I couldn't get this down to 10 bytes by myself, but @Pietu1998 pointed me to an atom I'd missed, this giving this 10-byte solution. Unusually for Jelly, this one takes input from standard input (in the form 1276,933024), not from the command line (this enables the use of the ³ command, which returns the command line argument, defaulting to 100).

Explanation:

ƓDUz0P€Uḅ³
Ɠ           read standard input
 D          convert to base 10
  U         reverse elements
   z0       transpose, padding the end with zeroes
     P€     take the product of each (€) inner list
       U    reverse elements back
        b³  convert from base 100

The use of base 100 is a simple way to implement the "pad to 2 digits, then convert to base 10" technique. The only other subtle thing here is the reversing; we want to pad with zeroes at the start of the number, but Jelly's z command pads at the end, so reversing the lists means that z will pad correctly.


The handshake problem The handshake problem is the classic problem that for n people in a room, if they all shake hands, what's the total number of handshakes that occur.

You code should take an input of any number and output the number of handshakes, both in base ten.

Also the code should not let non-integers through. You should output a falsey in this case. The only expected inputs are positive whole integers and positive real numbers - you don't need to worry about complex numbers or strings as inputs.
This should mean that you should expect n >= 0

Test cases

(N:handshakes)
0:0
10:45
20:190
10.5:0
1337:893116

Normal golfing rules apply and shortest code wins.
If your code isn't self explanatory, please explain.

Jelly and 05AB1E are the winners, both at 2 bytes

JavaScript ES6, 16

n=>n%1?0:~-n*n/2

Test

f=n=>n%1?0:~-n*n/2

function test()
{
  var i=I.value
  O.textContent=f(i)
}
<input id=I oninput=test()>


Can you cancel the stackoverflow exception in the following code? The following code will produce a run-time error, stackoverflow exception.

class Foo
{
    //static Foo foo = new Foo(); // you are not allowed using this approach
    //static readonly Foo foo = new Foo(); // you are not allowed using this approach
    Foo foo = new Foo();
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}

The objective is to cancel the exception without

removing, modifying or commenting out the existing code,
using the approaches mentioned (and their variants in access modifiers, public, private, etc) as the given comments,
using try-catch-finally or its variants,
using attributes,
using compilation condition,

You are only allowed to add your own code inside the Foo class. How do you cancel the exception at run-time?

Here, another try:

class Foo
{
    //static Foo foo = new Foo(); // you are not allowed using this approach
    //static readonly Foo foo = new Foo(); // you are not allowed using this approach
    Foo foo = new Foo();
    MWAHAHAHA, THIS LINE GIVES A COMPILE ERROR! NO STACKOVERFLOW EXCEPTION ANYMORE! LOL
}
class Program
{
    static void Main(string[] args)
    {
        new Foo();
    }
}


Normalized Malbolge to Malbolge translator In this task, you will write a program/function that takes a Normalized Malbolge program and outputs the resulting Malbolge program. (This is a secret tool that all Malbolge programmers are using!)

Input

A data structure that (somehow) represents a Normalized Malbolge program.

Output

A data structure that represents the resulting Malbolge program.

Examples

jpoo*pjoooop*ojoopoo*ojoooooppjoivvvo/i<ivivi<vvvvvvvvvvvvvoji
(=BA#9"=<;:3y7x54-21q/p-,+*)"!h%B0/.~P<<:(8&66#"!~}|{zyxwvugJ%

jjjj*<jjjj*<v
('&%#^"!~}{XE

jjjjjjjjjjjjjjjjjjjjjjj*<jjjjjjjjjjjjjjjjjjjjjjjj*<v
('&%$#"!~}|{zyxwvutsrqpnKmlkjihgfedcba`_^]\[ZYXWVT1|

How to convert

Iterate over the normalized Malbolge program, performing the following steps for each character:

Replace the characters in the string *jpovi</ with the corresponding character in '(>DQbcu. (That is, map * to ', j to (, and so on.)
Then subtract the current position of the program counter (i.e. the number of characters before the current one) from the character's ASCII code.
If the resulting ASCII code is less than 33, increment it by 94 and repeat until it is at least 33.
Append the resulting character to the output.

Rules

This is a code-golf contest; the shortest answer wins.
No standard loopholes please.
The default I/O methods are allowed.
Input will only contain the characters *jpovi</.

Malbolge Unshackled (20-trit rotation variant), 7,784e6 bytes

Size of this answer exceeds maximum postable program size (eh), so the code is located in my GitHub repository.

How to run this?

This might be a tricky part, because naive Haskell interpreter will take ages upon ages to run this. TIO has decent Malbogle Unshackled interpreter, but sadly I won't be able to use it (limitations).

The best one I could find is the fixed 20-trit rotation width variant, that performs very well, converting 0,5 characters per second.

To make the interpreter a bit faster, I've removed all the checks from Matthias Lutter's Malbolge Unshackled interpreter.

My modified version can run around 6,3% faster.

#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

const char* translation = "5z]&gqtyfr$(we4{WP)H-Zn,[%\\3dL+Q;>U!pJS72Fh"
        "OA1CB6v^=I_0/8|jsb9m<.TVac`uY*MK'X~xDl}REokN:#?G\"i@";

typedef struct Word {
    unsigned int area;
    unsigned int high;
    unsigned int low;
} Word;

void word2string(Word w, char* s, int min_length) {
    if (!s) return;
    if (min_length < 1) min_length = 1;
    if (min_length > 20) min_length = 20;
    s[0] = (w.area%3) + '0';
    s[1] = 't';
    char tmp[20];
    int i;
    for (i=0;i<10;i++) {
        tmp[19-i] = (w.low % 3) + '0';
        w.low /= 3;
    }
    for (i=0;i<10;i++) {
        tmp[9-i] = (w.high % 3) + '0';
        w.high /= 3;
    }
    i = 0;
    while (tmp[i] == s[0] && i < 20 - min_length) i++;
    int j = 2;
    while (i < 20) {
        s[j] = tmp[i];
        i++;
        j++;
    }
    s[j] = 0;
}

unsigned int crazy_low(unsigned int a, unsigned int d){
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    int position = 0;
    unsigned int output = 0;
    while (position < 10){
        unsigned int i = a%3;
        unsigned int j = d%3;
        unsigned int out = crz[i+3*j];
        unsigned int multiple = 1;
        int k;
        for (k=0;k<position;k++)
            multiple *= 3;
        output += multiple*out;
        a /= 3;
        d /= 3;
        position++;
    }
    return output;
}

Word zero() {
    Word result = {0, 0, 0};
    return result;
}

Word increment(Word d) {
    d.low++;
    if (d.low >= 59049) {
        d.low = 0;
        d.high++;
        if (d.high >= 59049) {
            fprintf(stderr,"error: overflow\n");
            exit(1);
        }
    }
    return d;
}

Word decrement(Word d) {
    if (d.low == 0) {
        d.low = 59048;
        d.high--;
    }else{
        d.low--;
    }
    return d;
}

Word crazy(Word a, Word d){
    Word output;
    unsigned int crz[] = {1,0,0,1,0,2,2,2,1};
    output.area = crz[a.area+3*d.area];
    output.high = crazy_low(a.high, d.high);
    output.low = crazy_low(a.low, d.low);
    return output;
}

Word rotate_r(Word d){
    unsigned int carry_h = d.high%3;
    unsigned int carry_l = d.low%3;
    d.high = 19683 * carry_l + d.high / 3;
    d.low = 19683 * carry_h + d.low / 3;
    return d;
}

// last_initialized: if set, use to fill newly generated memory with preinitial values...
Word* ptr_to(Word** mem[], Word d, unsigned int last_initialized) {
    if ((mem[d.area])[d.high]) {
        return &(((mem[d.area])[d.high])[d.low]);
    }
    (mem[d.area])[d.high] = (Word*)malloc(59049 * sizeof(Word));
    if (!(mem[d.area])[d.high]) {
        fprintf(stderr,"error: out of memory.\n");
        exit(1);
    }
    if (last_initialized) {
        Word repitition[6];
        repitition[(last_initialized-1) % 6] =
                ((mem[0])[(last_initialized-1) / 59049])
                    [(last_initialized-1) % 59049];
        repitition[(last_initialized) % 6] =
                ((mem[0])[last_initialized / 59049])
                    [last_initialized % 59049];
        unsigned int i;
        for (i=0;i<6;i++) {
            repitition[(last_initialized+1+i) % 6] =
                    crazy(repitition[(last_initialized+i) % 6],
                        repitition[(last_initialized-1+i) % 6]);
        }
        unsigned int offset = (59049*d.high) % 6;
        i = 0;
        while (1){
            ((mem[d.area])[d.high])[i] = repitition[(i+offset)%6];
            if (i == 59048) {
                break;
            }
            i++;
        }
    }
    return &(((mem[d.area])[d.high])[d.low]);
}

unsigned int get_instruction(Word** mem[], Word c,
        unsigned int last_initialized,
        int ignore_invalid) {
    Word* instr = ptr_to(mem, c, last_initialized);
    unsigned int instruction = instr->low;
    instruction = (instruction+c.low + 59049 * c.high
            + (c.area==1?52:(c.area==2?10:0)))%94;
    return instruction;
}

int main(int argc, char* argv[]) {
    Word** memory[3];
    int i,j;
    for (i=0; i<3; i++) {
        memory[i] = (Word**)malloc(59049 * sizeof(Word*));
        if (!memory) {
            fprintf(stderr,"not enough memory.\n");
            return 1;
        }
        for (j=0; j<59049; j++) {
            (memory[i])[j] = 0;
        }
    }
    Word a, c, d;
    unsigned int result;
    FILE* file;
    if (argc < 2) {
        // read program code from STDIN
        file = stdin;
    }else{
        file = fopen(argv[1],"rb");
    }
    if (file == NULL) {
        fprintf(stderr, "File not found: %s\n",argv[1]);
        return 1;
    }
    a = zero();
    c = zero();
    d = zero();
    result = 0;
    while (!feof(file)){
        unsigned int instr;
        Word* cell = ptr_to(memory, d, 0);
        (*cell) = zero();
        result = fread(&cell->low,1,1,file);
        if (result > 1)
            return 1;
        if (result == 0 || cell->low == 0x1a || cell->low == 0x04)
            break;
        instr = (cell->low + d.low + 59049*d.high)%94;
        if (cell->low == ' ' || cell->low == '\t' || cell->low == '\r'
                || cell->low == '\n');
        else if (cell->low >= 33 && cell->low < 127 &&
                (instr == 4 || instr == 5 || instr == 23 || instr == 39
                    || instr == 40 || instr == 62 || instr == 68
                    || instr == 81)) {
            d = increment(d);
        }
    }
    if (file != stdin) {
        fclose(file);
    }
    unsigned int last_initialized = 0;
    while (1){
        *ptr_to(memory, d, 0) = crazy(*ptr_to(memory, decrement(d), 0),
                *ptr_to(memory, decrement(decrement(d)), 0));
        last_initialized = d.low + 59049*d.high;
        if (d.low == 59048) {
            break;
        }
        d = increment(d);
    }
    d = zero();

    unsigned int step = 0;
    while (1) {
        unsigned int instruction = get_instruction(memory, c,
                last_initialized, 0);
        step++;
        switch (instruction){
            case 4:
                c = *ptr_to(memory,d,last_initialized);
                break;
            case 5:
                if (!a.area) {
                    printf("%c",(char)(a.low + 59049*a.high));
                }else if (a.area == 2 && a.low == 59047
                        && a.high == 59048) {
                    printf("\n");
                }
                break;
            case 23:
                a = zero();
                a.low = getchar();
                if (a.low == EOF) {
                    a.low = 59048;
                    a.high = 59048;
                    a.area = 2;
                }else if (a.low == '\n'){
                    a.low = 59047;
                    a.high = 59048;
                    a.area = 2;
                }
                break;
            case 39:
                a = (*ptr_to(memory,d,last_initialized)
                        = rotate_r(*ptr_to(memory,d,last_initialized)));
                break;
            case 40:
                d = *ptr_to(memory,d,last_initialized);
                break;
            case 62:
                a = (*ptr_to(memory,d,last_initialized)
                        = crazy(a, *ptr_to(memory,d,last_initialized)));
                break;
            case 81:
                return 0;
            case 68:
            default:
                break;
        }

        Word* mem_c = ptr_to(memory, c, last_initialized);
        mem_c->low = translation[mem_c->low - 33];

        c = increment(c);
        d = increment(d);
    }
    return 0;
}

It's working!


2D Pathfinding with Momentum You are piloting a spaceship, outfitted with an engine that can accelerate you at 1km/s^2 in the direction the ship is facing (you have very good inertial dampers).  You also have thrusters which can rotate you 180 degrees in 1s (rotating 45 degrees takes 0.25s, etc.).
You see on your scanner another ship, and decide to rendezvous with it.  You'll need to plot a course which brings you within 1km of it while your speed is within 1km/s of its speed.
Specifications
Write a function which takes the following pieces of data as inputs:
other_location - The location of the other ship in kms.  You may assume that this is no more than 100 units away from the origin for optimization, but your entry should be able to handle larger distances (even if it takes a long time).
other_acceleration - The other ship is accelerating at a constant rate no more than 0.5km/s^2 (their inertial dampers aren't quite as good).  You may take this in whatever form you wish - facing + acceleration, or separated into x and y components).  The other ship starts at a speed of 0.
You always start at [0,0], facing the positive direction on the x axis.
Your function's output is significantly more constrained.  You must return a list of actions your ship will take.  There are three possible actions.

Acceleration.  You accelerate in the direction your ship is facing for an amount of time you specify.

Rotation.  You rotate to face a direction you specify.

Drift.  You do nothing for the amount of time you specify.

Your output must have the listed data, but it can be in any format you wish.  Please make it human-readable; this isn't code golf.
At the end of the final action in your list, your ship must be within 1km of the other ship and its speed must be within 1km/s of the other ship's speed.  Note that if you accelerate from a stop for 1s, you will have moved 0.5kms.
Scoring Criteria
I will run each entry on my machine, a i7-9750H 2.6 GHz Windows 10 laptop.  Ideally, there will be straightforward installation instructions for your language; please specify whatever build command I need to run it.
The score of an entry on a particular input will be the product of the time it takes to run and the time that it takes for your ship to intercept the other ship squared.  Entries may be non-deterministic, but I will run any non-deterministic entry 10 times on each input and take the worst score.
The winner will be the entry that has the lowest total score across the inputs.
Example inputs
Here are a bunch of sample inputs (that I'll use as the test set, though I might add some more if some programs are very quick).  Feel free to post preliminary outputs/scores for each of these (run on your machine), but note that it's a standard loophole to tailor your program to these inputs.
other_location (x, y), other_acceleration (x, y)
[10,0], [0,0]
[6,-3], [0,0.5]
[-2,8], [0.1,-0.2]
[5,5], [0.3,0.3]
[15,18], [0.1, 0.3]
[20,5], [0.2,-0.2]

Example output
For the first example input ([10,0], [0,0]), these are all valid outputs:
[Accelerate, 1], [Drift, 8.5]
[Accelerate, 2.7], [Rotate, 180], [Accelerate, 2.7]
[Accelerate, 2], [Rotate, [-1,0]], [Drift, 2], [Accelerate, 2]

For the second example input ([6,-3], [0,0.5]), this is a valid output:
[Accelerate, 2.23], [Rotate, 180], [Accelerate, 2.23], [Rotate, -90],
[Accelerate, 11.5], [Drift, 5.5]
// The first 3 actions put me directly behind the moving ship (actually
// at [5.9729, 0]) in 5.96s (the other ship is now at [6,5.8804] and
// moving [0, 2.98]), the remainder catch up to it.
// Total time for this route: 22.96s

MATLAB
Try it online
function tf=Intercept(p,a)
X=@(t,a,v,x).5*a*t.^2+v.*t+x;
t=0;
while 1

    a1=(0:0.01:1)';
    a2=1-a1;
    theta2=-360:360;

    x1=X(t,a(1),0,p(1));
    y1=X(t,a(2),0,p(2));
    theta1=atan(y1/x1)*180/pi;
    T=(t-abs(theta1)/180-abs(theta2-theta1)./180);
    T(T<0)=0;
    x2=0.5*a1.^2*cosd(theta1).*T.^2+0.5*a2.^2*cosd(theta2).*T.^2+a1.*a2*cosd(theta1).*T.^2+a1.*cosd(theta1)*T.*abs(theta2-theta1)/180;
    y2=0.5*a1.^2*sind(theta1).*T.^2+0.5*a2.^2*sind(theta2).*T.^2+a1.*a2*sind(theta1).*T.^2+a1.*sind(theta1)*T.*abs(theta2-theta1)/180;
    x=x1-x2;
    y=y1-y2;
    vx=a(1)*t-(a1*cosd(theta1)*T+a2*cosd(theta2).*T);
    vy=a(2)*t-(a1*sind(theta1)*T+a2*sind(theta2).*T);
    V=sqrt(vx.^2+vy.^2);
    D=sqrt(x.^2+y.^2);

    [ida1,idtheta2]=find(D<1&V<1,1);

    if ~isempty(idtheta2)
        a1=a1(ida1);
        theta2=theta2(idtheta2);
        break
    end

    t=t+0.01;

end
if length(theta2) > 1
    return
end
tf=t;
t1=abs(theta1/180);
t3=abs(theta2-theta1)/180;
t3=t3-0*(t3>1);
t2=a1.*(tf-t1-t3);
t4=tf-t3-t2-t1;
x1=a(1)/2*tf^2+p(1);
y1=a(2)/2*tf^2+p(2);
v1=a*tf;
x2=cosd(theta1)/2.*t2.^2+cosd(theta1).*t2.*(t3+t4)+cosd(theta2)./2.*t4.^2;
y2=sind(theta1)/2.*t2.^2+sind(theta1).*t2.*(t3+t4)+sind(theta2)./2.*t4.^2;
v2=[cosd(theta1)*t2+cosd(theta2)*t4;sind(theta1)*t2+sind(theta2)*t4];
V=vecnorm(v1'-v2);
P=vecnorm([x1;y1]-[x2;y2]);
cmds=[theta1,t1,t2,theta2-theta1,t3,t4,tf];
fprintf('Turn %.2f degrees in %.2f seconds\nAccelerate for %.2f seconds\nTurn %.2f degrees in %.2f seconds\nAccelerate for %.2f seconds\nMission Time: %.2f seconds\n\n',cmds);
fprintf('x1=%.2f, x2=%.2f\ny1=%.2f, y2=%.2f\nv1=[%.2f %.2f], v2=[%.2f %.2f]\nV=%.2f\nD=%.2f\n',x1,x2,y1,y2,v1,v2,V,P);

Explanation:
My methodology is to start by assuming the total mission length \$t\$ starting from 0 (in the case where we already fit the parameters at \$t\$=0) and apply a standard mission profile. The mission has 4 stages:

turn towards where the target will be at time \$t\$
accelerate towards the target
turn to an angle that will cancel velocities so that we are within parameters by time \$t\$
accelerate for the remaining time

Using this profile, there are 4 time values to be concerned about. \$t_1\$ is the first turn, \$t_2\$ is the first burn, \$t_3\$ is the second turn, and \$t_4\$ is the last burn. \$t_1\$ is known since the initial angle can be easily calculated. \$t_2\$ and \$t_4\$ are calculated as percentages \$a_1\$ and \$a_2\$ of \$(t_2+t_4)\$, in order to reduce them to \$a_1(t_2+t_4)\$ and \$(1-a_1)(t_2+t_4)\$, thus making both values a function of \$a_1\$. \$t_3\$ is a function of the second turn angle \$\theta_2\$. The next thing is to calculate the x and y positions and velocities at time \$t\$ as a function of \$a_1\$ and the second angle \$\theta_2\$, the only other unknown. I know that these are limited to a specific range of 0:1 and -360:360  respectively, so I calculate all possible positions as a function of \$a_1\$ and \$\theta_2\$ and find the first one that fits the criteria. If none fit, then \$t\$ is increased by 0.01 and the process is repeated. This method takes advantage of the vectorized computing capabilities of MATLAB. And honestly, it's probably the first code golf challenge where MATLAB is more ideal.
I also have some test code that has all of the test cases already, and times it as well according to your scoring criteria. Since the output of the program is the total mission time, and tic/toc calculates time since tic was called at time toc, this calculates the score as well.
% % Test Intercept*
*edited so that toc comes after the function call, so that time is calculated after the function finishes and not before. Oversight on my part.
tic
(Intercept([10,0], [0,0])*toc)^2;

tic
(Intercept([6,-3], [0,0.5])*toc)^2

tic
(Intercept([-2,8], [0.1,-0.2])*toc)^2

tic
(Intercept([5,5], [0.3,0.3])*toc)^2

tic
(Intercept([15,18], [0.1, 0.3])*toc)^2

tic
(Intercept([20,5], [0.2,-0.2])*toc)^2


Magnetic pull in an array Background

I have a row of powerful magnets and a bunch of metal objects between them.
Where will the magnets pull them?

Input

Your input is an array of non-negative integers, which will contain at least one 1.
You can use any reasonable format.

The 0s of the array represent empty space, and the 1s represent fixed magnets.
All other numbers are metal objects, which are pulled by the magnets.
Every object gets pulled towards the nearest magnet (if there's a tie, the object is pulled to the right), and it travels in that direction until it hits the magnet or another object.
In the end, all the objects have clustered around the magnets.
The order of the objects is preserved.

Output

Your output is the array where every object has been pulled as close to the nearest magnet as possible.
It should have the same format as the input.

Example

Consider the array

[0,0,2,0,1,1,0,2,0,3,0,5,0,1,0]

The leftmost 2 gets pulled towards the first pair of magnets, as does the second 2.
The 3 has a magnet four steps away in both directions, so it gets pulled to the right.
The 5 also gets pulled to the right, and it goes between the 3 and the magnet.
The correct output is

[0,0,0,2,1,1,2,0,0,0,0,3,5,1,0]

Rules and scoring

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

Test cases

[0,1,0] -> [0,1,0]
[1,0,2,0,0,1,0] -> [1,2,0,0,0,1,0]
[7,0,5,0,0,1,0] -> [0,0,0,7,5,1,0]
[1,0,3,0,1,0,3,0,1] -> [1,0,0,3,1,0,0,3,1]
[1,0,0,0,0,0,0,7,3] -> [1,7,3,0,0,0,0,0,0]
[1,2,3,4,5,6,7,8,9,10,11,0,0,0,1] -> [1,2,3,4,5,6,7,0,0,0,8,9,10,11,1]
[12,3,0,0,1,0,1,3,0,0,6,12,0,0,0,1] -> [0,0,12,3,1,0,1,3,6,0,0,0,0,0,12,1]

Pyth, 28 20

o@.e?bhaDk_x1QkQ~hZQ

Thanks @ThomasKwa for golfing 6 bytes!

This abuses stable sorting by assigning to all the values 1 or greater in the list the index of the nearest 1 (ties broken to the rightmost 1) and then sorting the list by these values. Zeroes are given their own index as their sort value.

Test Suite

Verification Suite

Explanation:

o@.e?bhaDk_x1QkQ~hZQ  ##  implicit: Q = eval(input())
o                  Q  ##  Sort Q using the values of the lambda below
 @              ~hZ   ##  select the value from the matching index of the enumerate
  .e           Q      ##  enumerate with b = value, k = index
    ?b                ##  ternary on b
      haDk_x1Q        ##  if true, this thing
              k       ##  otherwise use the index as the sort weight
          _x1Q        ##  the indices of 1 in Q, given in reverse order
                      ##  (the reverse makes it sort to the right because of stable sorts)
       aDk            ##  sort those indices by |index - k|
      h               ##  take the first value

Example:

Take the test case [1,0,3,0,1,0,3,0,1], for example. When we apply the enumeration, the zeros will all get their own index as a sort value, so I'll skip those, and do a one and a three.

For the first one, we get the indices of ones: [0, 4, 8]. Then reverse it, and sort by the absolute value of the indices minus the index of the one, which happens to be zero here. So we get [0, 4, 8] back again. The first value is 0 so we use that.

For the three, we get the reversed indices and do the same sorting but using two as the index of the three, so both the 0 and the 4 give the same value for the absolute difference, so we get: [4, 0, 8] and we take the 4.

Then the final "sorting values" array will be [0, 1, 4, 3, 4, 5, 8, 7, 8]. Thanks to the stable sort, the ties are broken by the order that the values originally appeared, so we get the final array we want.


Generate a heap of boxes (The text asks how many boxes there are in the picture)

Now you are required to generate such a problem and its answer.

Input

an integer n
(optionally) random source of two values, in case you don't want to use the default random.

Output can be

a 3D array A[n][n][n] of booleans, where A[i][j][k] => (i==0 || A[i-1][j][k]) && (j==0 || A[i][j-1][k]) && (k==0 || A[i][j][k-1]) (assuming 0-index)
where && is logical AND, || is logical OR, and => is "implies" (if X is true, then Y is true).

Basically this says that if you have a box at some position then for each coordinate that coordinate must be either 0 or also have a box if that coordinate is one less. So no holes in any direction that gets you closer to the origin.
a 2D array B[n][n] of integers, where B[i][j] means how many k satisfy A[i][j][k]

Basically this is the height of the stacks where these heights can't become lower in any direction that gets you closer to the origin.
Besides the array, the amount of boxes (how many i,j,k satisfy A[i][j][k])

Every valid output should have nonzero probability to be outputted.

Example: (Here use 2D output format for convenience)

1 => [[0]] 0 or [[1]] 1
2 => [[0,0],[0,0]] 0
     [[1,0],[0,0]] 1
     [[1,0],[1,0]] 2
     [[1,1],[0,0]] 2
     [[1,1],[1,0]] 3
     [[1,1],[1,1]] 4
     [[2,0],[0,0]] 2
     [[2,0],[1,0]] 3
     [[2,0],[2,0]] 4
     [[2,1],[0,0]] 3
     [[2,1],[1,0]] 4
     [[2,1],[1,1]] 5
     [[2,1],[2,0]] 5
     [[2,1],[2,1]] 6
     [[2,2],[0,0]] 4
     [[2,2],[1,0]] 5
     [[2,2],[1,1]] 6
     [[2,2],[2,0]] 6
     [[2,2],[2,1]] 7 or
     [[2,2],[2,2]] 8

So for input 2 your program should randomly return one of the 20 possible outputs, and if run enough times every one of them should be returned at some point.

Your program must terminate.

Winning criteria

This is code-golf, shortest code in bytes win!

Perl 5, -ap 121 bytes / 56 bytes

This 121 byte solution has a uniform distribution over all valid arrangements of boxes. It tries to be somewhat efficient but still times out on TIO for size 4 or more

#!/usr/bin/perl -ap
@a=((0 x$_.$")x$_.$/)x$_."";s%0%/0(|.{@F}|(\X{@F}\X){@F})\G/+${$z="$`1$'"}++||push@a,$z;0%eg for@a;$_=$a[rand@a];$\=y/1//

Try it online!

If you don't care about uniformity it's of course easy to go shorter, e.g. this 56 bytes solution is very biased towards the origin (it probably gives more nice pictures for the motivating example though)

#!/usr/bin/perl -a
say map{\@$_[rand@;+1,$#{$_-1}];@;-$#$_.$"}@;for@;=1..$_

Try it online!

(checked for size 2 and 3 that it indeed generates all possible outputs)


Compile Regexes (By Substitution) Your task is to compile regexes... by specifying a substitution for each character in a regex.

Regexes

The regexes support these

REGEX       = (LITERAL REGEX / GROUP REGEX / STAR REGEX / ALTERNATIVE)
LITERAL     = 1 / 0
GROUP       = '(' REGEX ')'
STAR        = (LITERAL / GROUP) '*'
ALTERNATIVE = '('REGEX ('|' REGEX)*')'

Why only 1 or 0? It is for simplification. The regex thus has only the following characters:

*()|10

It is interpreted as follows:

* is Kleene star (repeat left group or literal 0 or more times).
| is alternation (match if either the regex to the left or the regex to the right matches).
() is grouping.
1 matches character 1.
0 matches character 0.

How to compile?

You specify six code snippets: one to replace each regex character. For example, if your answer is:

  * : FSAGFSDVADFS
  | : GSDGSAG
  ( : GSDG
  ) : GDSIH
  1 : RGIHAIGH
  0 : GIHEBN

Then you replace each regex with its respective code snippet, so:

(0|11)*

is turned into:

GSDGGIHEBNGSDGSAGRGIHAIGHRGIHAIGHGDSIHFSAGFSDVADFS

What is the resulting program supposed to do?

Your program will:

Take the input.
Output a truthy value if the regex matches whole input.
Else output a falsy value.

Input outside 01 is consindered undefined behavior. Input can be empty.

Additional rules

For a given regex character, the resulting snippet must always be the same.
There is no prefix or suffix character added afterwards.
The regex is guaranteed to be nonempty.

Scoring

The least combined snippet is the winner. So the score for the example case would be calculated as follows:

FSAGFSDVADFS + GSDGSAG + GSDG + GDSIH + RGIHAIGH + GIHEBN

12 + 7 + 4 + 5 + 8 + 6 = 42

Snails, 48 bytes
0 -> )0(\0!(l.)(~
1 -> )0(\1!(l.)(~
( -> )0({{(
) -> )0}}(~
| -> )0}|{(
* -> )0),(~
If we had to search for partial matches rather than matching only the full input, then it would be very easy. 0 would become \0, 1 would become \1, * would become ,, and the others would map to themselves. Instead there are a lot of shenanigans to prevent matches from starting somewhere other than the beginning or ending somewhere other than the end. !(l.) is an assertion that will fail if the beginning of the match is not at the beginning of the input. ~ matches a cell outside of the input, so it is added to all the characters that are allowed to be at the end of the regex. If there is another regex character following, it is canceled out by a numerical quantifier 0 which requires it to be matched 0 times, essentially commenting it out. To allow * (,) to work correctly despite the dummy out-of-bounds test being in the way, the language's bracket matching rules are heavily used. From the documentation:

Matching pairs of parentheses () or curly braces {} will behave as expected (like parentheses in regex), but it is also possible to leave out one half of a pair and have it inferred, according to the following rules. ) or } groups everything to the left until the nearest unclosed group opening instruction of the same type(( or { respectively), or the beginning of the pattern if none exists. It closes any unclosed opening instructions of the opposite type in the middle of this range. An otherwise unmatched ( or { is closed by the end of the pattern.

Clear as mud, right?


Intercommunication between threads So glad I found this cool site. Wanted to try sharing a coding challenge a friend gave me, an interview question. Usually it is written in java, but you can use whatever language you want, just have fun!

Challenge: write efficiently and securely a program that creates an array of n threads that communicate with each other, where each thread, for simplicity, represents a number between 1,...,100. Oh, and it has to be randomly initialized.

Here comes the fun part: each thread looks at its neighbours(i-1,i+1) and:

If its number is smaller than the number of both of his neighbours(i-1,i+1), it increments itself.
If its number is larger than the numbers of both of his neighbours, it decrements itself.
If its number is equal or between the numbers of its neighbours, it keeps the number the same.

So far not fun, right? So let's also make it a circular array! (the first element in the array and the last element in the array are neighbours) the tricky parts are: each thread should not change its number before its neighbors finished checking it.

The program performs m rounds of checks.

Input: For program logic, you can take the input from the user, or define it, doesn't matter.

Output: first line should print the starting state of the array. Second line should print all of the numbers in the array after each thread did one check. Third line should print the numbers in all of the array after each thread did a second test(second round) and so on.

Might be quite tricky in the beginning, but have fun with it!
The winner will be the one who can write the shortest code, and in case of a tie, cool algorithmic tricks or functional utilization of the java language will be awarded extra points!

First post here, will try to post more cool stuff for you to enjoy!
Really like this site.

I posted it a while ago, but forgot my credentials while being abroad so I couldn't log in to the site and fix the previous post. Hoping that this one is according to the standards of the site and more than that, I really hope you'll enjoy this cool coding gamexercise.

Good luck to all and most importantly - enjoy!

As kevin well-said: Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.

05AB1E, 35 bytes
FтLΩˆ}>µ¯©=´vy®N<N>‚èy.SDPiн+ë\}ˆ}¼

Takes n as first input, and m as second. Doesn't use any threads, since 05AB1E has none.
Try it online.
Explanation:

F    }               # Loop the (implicit) input `n` amount of times:
 тL                  #  Push a list in the range [1,100]
   Ω                 #  Pop and push a random value from this list
    ˆ                #  Pop and add it to the global array
>                    # Increase the second (implicit) input `m` by 1
 µ                   # Loop until the counter_variable is equal to that:
  ¯                  #  Push the global array
   ©                 #  Store it in the register (without popping)
    =                #  Print it with trailing newline (without popping)
     ´               #  And clear the global array
   v                 #  Loop over each item of the array that is still on the stack:
      N<             #   Get the index-1
        N>           #   And the index+1
          ‚          #   Pair them together
     ®     è         #   Index both into the previous array we stored in the register
                     #   (NOTE: 05AB1E has automatic wrap-around when indexing)
            y.S      #   Compare both of them to the current integer `y`
                     #   (-1 if `y` is larger; 1 if `y` is smaller; 0 if equal)
               D     #   Duplicate this pair
                Pi   #   If the product is 1 (only true for [1,1] and [-1,-1]):
                  н  #    Only leave the first element of the duplicated pair
    y              + #    And add it to the current integer `y`
                 ë   #   Else:
                  \  #    Discard the duplicated pair, so `y` is at the top of the stack
                 }ˆ  #   After the if-else: add it to the global array
   }¼                #  After the inner loop: increase the counter_variable by 1


Most efficient table storage for determining recurrence The goal of this challenge is to implement a storage and retrieval pattern that will most quickly determine if a set of recurrence definitions fall within a date range.

Consider the schema:  Event -|--has one or many--<- Schedules

Schedule is a record defining a recurrence, e.g. (these are just samples)

Monthly, every month
Monthly, first Wednesday of every month
Monthly, Monday and Tuesday of every 3rd month from start date
Monthly, Monday and Tuesday of every May, June and July
Weekly, every Tuesday through Saturday
Weekly, Monday every 3rd week from start date

The types of supported schedules should be (definitive list):

Pattern

Daily
Weekly, every [X] weeks on [set of 1-7 days]
Monthly, every [Xth] day of every [Y] months
Monthly, every [1st-4th-last] [weekday] of every [Y] months
Yearly, on [month] [day of month] every [X] years
Yearly, on [1st-4th-last] [weekday] of [month]
Monthly, every [Xth] day of [set of months]
Monthly, every [1st-4th-last] [weekday] of [set of months]

End date (Start is always a single date)

No end date (for simplicity, you could omit this since we can use year 2999)
A single date
A number of [X] occurences

To win, the answer must define:

Table schema
SQL query or function (any RBDMS) to test a date range against the entire table

Determination of winner:

test data: 10,000 events will be created randomly; 20 special test cases will be added as well
test case: 100 random date ranges (min:1 max:32 days), 5 fixed date ranges (min:1 max:32 days)
test execution: Test will be repeated 3 times
proof of correctness: All answers must be correct
6: speed: Quickest execution wins

Example test case:

---------
Schedules
---------
Event A: Weekly, Every Monday starting 1 Jan 2015
Event A: Monthly, Every [31st] day of every [1] month starting 1 Jan 2015
  (e.g. Event A is a backup schedule)
Event B: Monthly, Every [1st] day of every [1] month starting 1 Jan 2015
Event C: Yearly, Every [10th] day of every [3] months starting 1 Jan 2015
  (e.g. quarterly summary report)
Event D: Weekly, Every [Tue,Wed,Fri] starting 1 Jan 2015
Event E: Weekly, Every [Tue,Wed,Fri] starting 1 Jan 2015 ending 3 July 2015
(assume no end dates unless stated)

-----
Query
-----
What events occur between 1 July 2015 and 31 July 2015 (inclusive)

---------------
Expected Result
---------------
(shown in date order)
01 July: Event B
01 July: Event E
03 July: Event E  << last occurrence due to end date
06 July: Event A
10 July: Event C
13 July: Event A
20 July: Event A
27 July: Event A
31 July: Event A
(a lot of event D's every Tue/Wed/Fri in July)

T-SQL

Given that the speed of the query is the most important part of the challenge, I have created a table that is an expansion of the events so that each event has all of it's occurrence dates stored.  The query is then just a simple WHERE DATE BETWEEN query and will perform extremely quickly.

This of course is built towards the query speed and not for the maintenance of the data.  Building and populating the table will take a fair amount of time depending on the amount of dates that the events cover.

The parsing of the records assume the the Days and Months are all abbreviated

View

A simple view to give a list of numbers up to 1e8

CREATE View [dbo].[Tally] as
WITH
    E1(N) AS (select 1 from (values (1),(1),(1),(1),(1),(1),(1),(1),(1),(1))dt(n)),
    E2(N) AS (SELECT 1 FROM E1 a, E1 b), --10E+2 or 100 rows
    E4(N) AS (SELECT 1 FROM E2 a, E2 b), --10E+4 or 10,000 rows max
    E8(N) AS (SELECT 1 FROM E4 a, E4 b), --10E+4 or 100,000,000 rows max
    cteTally(N) AS
    (
        SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
    )
SELECT N FROM cteTally;
GO

Functions

A couple of inline table functions to parse and expand the Event input records.

CREATE FUNCTION ParseEvent (@InputString VARCHAR(1000)) RETURNS TABLE AS RETURN
    -- Parse rest of the components
    SELECT
        EventName,
        ScheduleType,
        StartDate,
        EndDate,
        CASE WHEN ScheduleType = 'Weekly' THEN
            SUBSTRING(Remainder,7,CHARINDEX(' weeks ',Remainder)-7)
        END WeeklyX,
        CASE WHEN ScheduleType = 'Weekly' THEN
            SUBSTRING(Remainder,CHARINDEX(' on ',Remainder)+4,999)
        END WeeklyDays,
        CASE WHEN ScheduleType = 'Monthly' and Remainder like '% day of %' THEN
            SUBSTRING(Remainder,7,CHARINDEX(' day ',Remainder)-7)
        END MonthlyDayOfMonth,
        CASE WHEN ScheduleType = 'Monthly' and Remainder like '% of every %' THEN
            REPLACE(SUBSTRING(Remainder,CHARINDEX(' of every',Remainder)+10,999),' months','')
        END MonthlyX, -- Y
        CASE WHEN ScheduleType = 'Monthly' and Remainder not like '% of every %' THEN
            SUBSTRING(Remainder,CHARINDEX(' of ',Remainder)+4,999)
        END MonthlyMonths,
        CASE WHEN ScheduleType = 'Yearly' THEN
            CASE WHEN Remainder like '% every %' THEN
                SUBSTRING(Remainder,4,CHARINDEX(' ',Remainder,4)-4) -- length 3 ?
            ELSE
                SUBSTRING(Remainder,CHARINDEX(' of ',Remainder)+4,999) -- Right(Remainder,3) ?
            END
        END YearlyMonth,
        CASE WHEN ScheduleType = 'Yearly' and Remainder like '% every %' THEN
            SUBSTRING(Remainder,CHARINDEX(' ',Remainder,4)+1,CHARINDEX(' ',Remainder,CHARINDEX(' ',Remainder,4)+1)-CHARINDEX(' ',Remainder,4)-1) -- Can we assume 3 ??
        END YearlyDayOfMonth,
        CASE WHEN ScheduleType = 'Yearly' and Remainder like '% every %' THEN
            REPLACE(SUBSTRING(Remainder,CHARINDEX(' every ',Remainder)+7,9999),' years','')
        END YearlyX,
        CASE WHEN (ScheduleType = 'Yearly' and Remainder like '% of %') OR
            (ScheduleType = 'Monthly' and remainder not like '% day %') THEN
            SUBSTRING(Remainder,CHARINDEX(' ',Remainder)+1,CHARINDEX(' of ',Remainder)-CHARINDEX(' ',Remainder)-1)
        END WeekDayOccurance
        FROM
        -- Get the start and end dates
        (SELECT
            EventName,
            ScheduleType,
            CAST(SUBSTRING(Remainder, CHARINDEX('Starting',Remainder)+9, IIF(CHARINDEX('Ending',Remainder)=0,999,CHARINDEX('Ending',Remainder) - (CHARINDEX('Starting',Remainder) + 9))) AS DATE)  StartDate,
            CAST(IIF(CHARINDEX('Ending',Remainder)=0,'31 Dec 2999',SUBSTRING(Remainder, CHARINDEX('Ending',Remainder) + 7, 999)) AS DATE) EndDate,
            RTRIM(STUFF(Remainder,CHARINDEX('Starting',Remainder),999,'')) Remainder
        FROM
            -- Get the schedule type
            (SELECT EventName,
                LTRIM(LEFT(Remainder, CHARINDEX(',',Remainder)-1)) ScheduleType,
                LTRIM(STUFF(Remainder, 1, CHARINDEX(',',Remainder), '')) Remainder
            FROM
                -- Get the event name
                ( SELECT
                    LEFT(@InputString, CHARINDEX(':',@InputString)-1) EventName,
                    STUFF(@InputString, 1, CHARINDEX(':',REPLACE(@InputString,'Daily ','Daily, ')), '') Remainder
                ) EventName
            ) ScheduleType
        ) StartEndDate
;
GO

CREATE FUNCTION ExpandEvent (
        @EventName VARCHAR(100),
        @ScheduleType VARCHAR(20),
        @StartDate DATE,
        @EndDate DATE,
        @WeeklyX VARCHAR(10),
        @WeeklyDays VARCHAR(50),
        @MonthlyDayOfMonth VARCHAR(10),
        @MonthlyX VARCHAR(10),
        @MonthlyMonths VARCHAR(50),
        @YearlyMonth VARCHAR(50),
        @YearlyDayOfMonth VARCHAR(10),
        @YearlyX VARCHAR(10),
        @WeekDayOccurance VARCHAR(50)
    ) RETURNS TABLE RETURN
WITH AllDays AS (
    SELECT *
    FROM (
        SELECT
            DENSE_RANK() OVER (ORDER BY DATEPART(year,D)) - 1 YearCount
            ,DENSE_RANK() OVER (ORDER BY DATEPART(year,D), DATEPART(month,D)) - 1 MonthCount
            ,DENSE_RANK() OVER (ORDER BY DATEPART(year,D), DATEPART(week,D)) - 1 WeekCount
            ,CASE DATEPART(month,D)
                WHEN 1 THEN 'Jan'
                WHEN 2 THEN 'Feb'
                WHEN 3 THEN 'Mar'
                WHEN 4 THEN 'Apr'
                WHEN 5 THEN 'May'
                WHEN 6 THEN 'Jun'
                WHEN 7 THEN 'Jul'
                WHEN 8 THEN 'Aug'
                WHEN 9 THEN 'Sep'
                WHEN 10 THEN 'Oct'
                WHEN 11 THEN 'Nov'
                WHEN 12 THEN 'Dec'
            END MonthAbrev
            ,DATEPART(day,D) MonthDay
            ,CASE DATEPART(weekday,D)
                WHEN 1 THEN 'Sun'
                WHEN 2 THEN 'Mon'
                WHEN 3 THEN 'Tue'
                WHEN 4 THEN 'Wed'
                WHEN 5 THEN 'Thu'
                WHEN 6 THEN 'Fri'
                ELSE 'Sat'
            END DayOfWeek
            ,DENSE_RANK() OVER (PARTITION BY DATEPART(year,D),DATEPART(month,D),DATEPART(weekday,D) ORDER BY D) DayWeekMonthOccurance
            ,COUNT(*) OVER (PARTITION BY DATEPART(year,D),DATEPART(month,D),DATEPART(weekday,D)) DayWeekMonthMax
            ,D
        FROM (
            SELECT DATEADD(day,t.N,@StartDate) D
            FROM (SELECT TOP(DATEDIFF(day,@StartDate,@EndDate) + 1) N - 1 N FROM Tally) T
            ) Days
        ) AllDays
    )
SELECT @EventName E, D FROM AllDays
WHERE (@ScheduleType = 'Daily')
    OR (WeekCount % @WeeklyX = 0 and @weeklyDays like '%'+DayofWeek+'%' and @ScheduleType = 'Weekly')
    OR (MonthDay = SUBSTRING(@MonthlyDayOfMonth,1,LEN(@MonthlyDayOfMonth)-2) and MonthCount % @MonthlyX = 0 and @ScheduleType = 'Monthly' and @MonthlyDayOfMonth IS NOT NULL and @MonthlyX IS NOT NULL)
    OR (MonthDay = SUBSTRING(@MonthlyDayOfMonth,1,LEN(@MonthlyDayOfMonth)-2) and @MonthlyMonths like '%'+MonthAbrev+'%' and @ScheduleType = 'Monthly' and @MonthlyDayOfMonth IS NOT NULL and @MonthlyMonths IS NOT NULL
    OR (DayWeekMonthOccurance = CASE WHEN @WeekDayOccurance like 'last %' THEN DayWeekMonthMax ELSE LEFT(@WeekDayOccurance,1) END and DayOfWeek = RIGHT(@WeekDayOccurance,3) and MonthCount % @MonthlyX = 0 and @ScheduleType = 'Monthly' and @WeekDayOccurance IS NOT NULL and @MonthlyX IS NOT NULL)
    OR (DayWeekMonthOccurance = CASE WHEN @WeekDayOccurance like 'last %' THEN DayWeekMonthMax ELSE LEFT(@WeekDayOccurance,1) END and DayOfWeek = RIGHT(@WeekDayOccurance,3) and @MonthlyMonths like '%'+MonthAbrev+'%' and @ScheduleType = 'Monthly' and @WeekDayOccurance IS NOT NULL and @MonthlyMonths IS NOT NULL)
    OR (@YearlyMonth like '%'+MonthAbrev+'%' and MonthDay = @YearlyDayOfMonth and YearCount % @YearlyX = 0 and @ScheduleType = 'Yearly' and @YearlyMonth IS NOT NULL and @YearlyDayOfMonth IS NOT NULL and @YearlyX IS NOT NULL)
    OR (DayWeekMonthOccurance = CASE WHEN @WeekDayOccurance like 'last %' THEN DayWeekMonthMax ELSE LEFT(@WeekDayOccurance,1) END and DayOfWeek = RIGHT(@WeekDayOccurance,3) and @YearlyMonth like '%'+MonthAbrev+'%' and @ScheduleType = 'Yearly' and @WeekDayOccurance IS NOT NULL and @YearlyMonth IS NOT NULL)
;
GO

Table

The search table for the event dates

CREATE TABLE SearchEvents (
    ID BIGINT IDENTITY (1,1) NOT NULL PRIMARY KEY,
    EventName VARCHAR(100) NOT NULL,
    EventDate DATE NOT NULL
    );

Table Population

An example of populating the SearchEvents table.  This example shows each of the Event patterns that are acceptable and will likely error if that format is deviated from.  Note the Months and Days are abbreviated.  The ending date is not required and will default to 31 Dec 2999.  But I would suggest that it is set.

INSERT INTO SearchEvents
SELECT Ex.E, Ex.D
FROM (VALUES
    ('Event A: Daily, Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event B: Weekly,  every 2 weeks on Mon,Tue Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event C: Monthly, every 2nd day of every 2 months Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event D: Monthly, every 3rd day of Jun,Jul,Dec,Jan Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event E: Monthly, every 2nd Tue of every 3 months Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event F: Monthly, every last Wed of Jun,Nov Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event B: Yearly, on Jun 10 every 1 years Starting 3 Jun 2010 Ending 5 Dec 2020')
    ,('Event H: Yearly, on 3rd Wed of Jun Starting 3 Jun 2010 Ending 5 Dec 2020')
)A(S) CROSS APPLY (SELECT * FROM parseEvent(S)) P
    CROSS APPLY (SELECT * FROM ExpandEvent(
        EventName,
        ScheduleType,
        StartDate,
        EndDate,
        WeeklyX,
        WeeklyDays,
        MonthlyDayOfMonth,
        MonthlyX,
        MonthlyMonths,
        YearlyMonth,
        YearlyDayOfMonth,
        YearlyX,
        WeekDayOccurance
    )) Ex

Indexing

The important part, indexing of the date field

CREATE INDEX SE_EventDate_IDX ON SearchEvents(EventDate) INCLUDE (EventName);
GO

Query

An example query

SELECT EventName, EventDate
FROM SearchEvents
WHERE EventDate BETWEEN CAST('1 Jan 2015' AS DATE) AND CAST('31 Dec 2015' AS DATE)
ORDER BY EventDate

This executed with the following stats on my machine.  1 years worth of events from ten years of data.

SQL Server parse and compile time:
   CPU time = 0 ms, elapsed time = 1 ms.

(435 row(s) affected)
Table 'SearchEvents'. Scan count 1, logical reads 5, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 98 ms.
SQL Server parse and compile time:
   CPU time = 0 ms, elapsed time = 0 ms.

 SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 0 ms.


Race for the Steward Badge Backstory
If you visit the Steward Badge Page, you will see no one has received one of these badges from PPCG yet. However, there are two users:
DJMcMayhem & Martin Ender , that are only a few reviews away from this badge!
Challenge
Your challenge, is to write a program or function that when run, outputs DJMcMayhem's review count from the Low Quality reviews & Martin Ender's review count from First Posts reviews.
Your code needs to be dynamic so you should not hard-code the values of the current count. You should actually go and fetch the counts from those pages.
Your output should be the users name and the count, with some delimiter in between each value, and there is no input.
Examples
DJMcMayhem, Count] [Martin Ender, Count]

DJMcMayhem, Count, Martin Ender, Count

DJMcMayhem Count Martin Ender Count

DJMcMayhem
Count
Martin Ender
Count

etc.....

No extraneous info is allowed.
Rules
Standard loopholes are not allowed.
This is code-golf, so the shortest code in bytes for each language wins!
Sandbox post

Red, 259 bytes

c:"https://codegolf.stackexchange.com/review/"t: copy c
d:"low-quality-posts/stats"e:"first-posts/stats"
f: func[s q][parse find s q[thru{-count">^M^/}any" "copy n to" "(print[q n])]]
f read to-url append c d"DJMcMayhem"
f read to-url append t e"Martin Ender"

Try it online!

Unfortunately doesn't work in TIO - results in timeout, although works normally in Red console.


Render an ASCII maze look! It's an ASCII maze! Soo coolzors, amazeballs and stuff.

+-+-----+---+
| |     |   |
| |  ++   | |
| |  ++ +-+ |
|       |   |
+-------+ | |
|         | |
+---------+-+

But, but, but... it's a pain to work out which direction all the parts of the maze are going. I just want to draw the layout and the maze make itself sooper kul without loads of time.

What if I could just draw this in...

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

That would be soo sweet!

The rules (Because rules is cools):

Write code to convert a string into an ascii maze and output the result.
Any non-whitespace character will be read as a wall.
Each char of wall will decide which character to be based on it's neighbours (only in North, South, East and West directions).

If a char has no non-whitespace neighbours, it will be a plus sign (+).
If a char has neighbours in both vertical (North-South) and horizontal (East-West) directions, it will be a plus sign (+).
If a char has neighbours only in a vertical (North-South) direction, it will be a pipe symbol (|).
If a char has neighbours only in a horizontal (East-West) direction, it will be a minus sign (-).

The Input can be a single string (with lines separated by newline characters, or an array of strings).
All input characters will be printable ASCII characters, you don't need to deal with extended charsets.
Use any old language you please.
If there is white space before a line, it should be the same amount on each line. Any white space after each line of output is fine.
Attempt to solve it with the smallest number of bytes.

Test cases:

1: Frame

Input:

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

Output:

+--------+
|        |
|        |
|        |
+--------+

2: Classic maze

Input:

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

Output:

--------+-------+
        |       |
| --+-+ | ----+ |
|   | | |     | |
| + | | +---- | |
|   | |       | |
+-- | +----+- | |
|   | |    |  | |
| --+ | ++ | -+
|     | ++    |
+-----+-++----+--

3: Green eggs, man.

Input:

I do not like green eggs and ham.
I do not like them, sam I am.
Would you like them here or there?
I would not like them anywhere!

Output:

| ++ +++ ++++ +++++ +++- -++ ----
| ++ +++ ++++ +++++ +++ + +++
+-+++ +++ ++++ ++++ ++++ ++ +++---
| +++-+ +++ ++++ ++-+ +++++++++

4: Icicles

Input:

Word Icicle!
Word Icicle
Word  cicle
 ord  cicle
 ord   icle
 ord   i le
 or    i le
 or    i l
 or      l
 or
  r

Output:

++++ ++++++-
++++ ++++++
++++  +++++
 +++  +++++
 +++   ++++
 +++   | ++
 ++    | ++
 ++    | |
 ++      |
 ++
  |

APL (Dyalog Unicode), 57 35 bytesSBCS

–22 thanks to a novel solution by ngn.
Anonymous tacit function taking a character matrix as argument.
{⊃'+-|+'↓⍨2⊥5 4 2⊃¨⊂⍱∘⌽⍨' '≠,⍵}⌺3 3

Try it online!
{…}⌺3 3 on each 3-by-3 neighbourhood, apply the following function:
 ,⍵ ravel (flatten)
 ' '≠ Boolean where non-space
 ⍱∘⌽⍨ that NOR it's reverse (incl. neither top NOR bottom, neither left NOR right)
 5 4 2⊃¨⊂ pick 5th, 4th, and 2nd element from that entire list
  i.e. empty self, no vertical, no horizontal
 2⊥ evaluate in base-2 (binary)
  i.e. ≥4:empty self; 3:no neighbours; 2:no horizontal neighbours; 1:no vertical; 0: has both
 '+-|+'↓⍨ drop that many elements from this string
  i.e. empty self:; alone:+; vertical neighbour(s) only:|+; horizontal:-|+; both:+-|+
 ⊃ pick the first element (pad with space if non are available)
  i.e. empty self: ; alone:+; vertical neighbour(s) only:|; horizontal:-; both:+

Old solution
Anonymous tacit function taking a character matrix as argument.
{' +-|+'⊃⍨1⍳⍨(' '=5⊃,⍵),(∧/,⊢)∨/2 2⍴1⌽' '≠(9⍴0 1)/,⍵}⌺3 3

Try it online!
{…}⌺3 3 on each 3-by-3 neighbourhood, apply the following function:
 ,⍵ ravel (flatten)
 (…)/ filter using the following mask:
  9⍴0 1 cyclically reshape [0,1] to length 9 (selects N, W, E, S)
 ' '≠ Boolean where non-space
 1⌽ rotate one step left; [W,E,S,N]
 2 2⍴ reshape to 2-by-2 matrix; [[W,E],[S,N]]
 ∨/ row-wise OR reduction: [horizontal,vertical]
 (…) apply the following tacit function:
  ⊢ the identity; [horizontal,vertical]
  ∧/, preceded by its AND reduction; [both,horizontal,vertical]
 (…), prepend the following:
  ,⍵ ravel (flatten) the neighbourhood
  5⊃ pick the 5th element (itself)
  ' '= Boolean if space (i.e. empty)
 Now we have [empty,both,horizontal,vertical]
 1⍳⍨ index of leftmost 1 (gives 5 if no neighbours at all)
 ' +-|+'⊃⍨ use that to pick symbol


Find the optimal starting move of Chomp Chomp is a two-player game with a setup of a rectangle of pieces. Each player takes a turn removing any piece, along with all pieces above it and to its right. Whoever takes the bottom-left piece loses. It can be proven fairly easily that the first player always has a winning move (except with a 1-by-1 rectangle); find it.

Input is the dimensions of the rectangle (two numbers)
Output is the location of the winning move (two numbers)
If there is more than one winning move, then you can output any of them.

This is code golf; shortest code (any language) wins.

Examples

Note: The outputs are just the two numbers; the ASCII art below is just to demonstrate what the numbers mean.

Input: 5 3 (indices 1-based starting from lower-left corner)

Output: 4 3

XXX--
XXXXX
XXXXX

Input: 4 4

Output: 2 2

X---
X---
X---
XXXX

Bonus

Subtract 15 characters from your score if you output all of the winning moves. Each pair of numbers must be separated by a newline.

Python 2 3, 141-15=126
def win(x,y):w([y]*x)
w=lambda b,f=print:not[f(r+1,c+1)for r,p in enumerate(b)for c in range(p)if(r+c)*w(b[:r]+[min(i,c)for i in b[r:]],max)]

Brute-force minimax search. For every possible move, we recursively see if the opponent can win after we make that move. Pretty weakly golfed; someone else should be able to do much better. This feels like a job for APL.

win is the public interface. It takes the dimensions of the board, converts it to a board representation, and passes that to w.
w is the minimax algorithm. It takes a board state, tries all moves, builds a list whose elements correspond to winning moves, and returns True if the list is empty. With the default f=print, building the list has a side effect of printing the winning moves. The function name used to make more sense when it returned a list of winning moves, but then I moved the not in front of the list to save a space.
for r,p in enumerate(b)for c in xrange(p) if(r+c): Iterate over all possible moves. 1 1 is treated as not a legal move, simplifying the base case a bit.
b[:r]+[min(i,c)for i in b[r:]]: Construct the state of the board after the move represented by coordinates r and c.
w(b[:r]+[min(i,c)for i in b[r:]],max): Recurse to see whether the new state is a losing state. max is the shortest function I could find that would take two integer arguments and not complain.
f(r+1,c+1): If f is print, prints the move. Whatever f is, it produces a value to pad the list length.
not [...]: not returns True for empty lists and False for nonempty.

Original Python 2 code, completely ungolfed, including memoization to handle much larger inputs:
def win(x, y):
    for row, column in _win(Board([y]*x)):
        print row+1, column+1

class MemoDict(dict):
    def __init__(self, func):
        self.memofunc = func
    def __missing__(self, key):
        self[key] = retval = self.memofunc(key)
        return retval

def memoize(func):
    return MemoDict(func).__getitem__

def _normalize(state):
    state = tuple(state)
    if 0 in state:
        state = state[:state.index(0)]
    return state

class Board(object):
    def __init__(self, state):
        self.state = _normalize(state)
    def __eq__(self, other):
        if not isinstance(other, Board):
            return NotImplemented
        return self.state == other.state
    def __hash__(self):
        return hash(self.state)
    def after(self, move):
        row, column = move
        newstate = list(self.state)
        for i in xrange(row, len(newstate)):
            newstate[i] = min(newstate[i], column)
        return Board(newstate)
    def moves(self):
        for row, pieces in enumerate(self.state):
            for column in xrange(pieces):
                if (row, column) != (0, 0):
                    yield row, column
    def lost(self):
        return self.state == (1,)

@memoize
def _win(board):
    return [move for move in board.moves() if not _win(board.after(move))]

Demo:
>>> for i in xrange(7, 11):
...     for j in xrange(7, 11):
...         print 'Dimensions: {} by {}'.format(i, j)
...         win(i, j)
...
Dimensions: 7 by 7
2 2
Dimensions: 7 by 8
3 3
Dimensions: 7 by 9
3 4
Dimensions: 7 by 10
2 3
Dimensions: 8 by 7
3 3
Dimensions: 8 by 8
2 2
Dimensions: 8 by 9
6 7
Dimensions: 8 by 10
4 9
5 6
Dimensions: 9 by 7
4 3
Dimensions: 9 by 8
7 6
Dimensions: 9 by 9
2 2
Dimensions: 9 by 10
7 8
9 5
Dimensions: 10 by 7
3 2
Dimensions: 10 by 8
6 5
9 4
Dimensions: 10 by 9
5 9
8 7
Dimensions: 10 by 10
2 2


Pyth, 12 bytes

f}hQ_XsjT;H1

Try it online!

f: Count up from 1 to find the first number such that:
X ... H1: Increment or insert the value 1 into the dictionary H at index
sjT;: sum of base ten digits of current number
_: values of dictionary
}hQ: check whether input + 1 is contained within.

The first time this is true, exactly input numbers must have the same digit sum as the current number, for the first time.


Make your program sequential! Your task, if you choose to accept it, is simple.

Objective

You must make a program that, when run, prints some (as many as you want) terms in a sequence that you choose. The sequence must be a valid OEIS sequence. The twist is that when you take the characters from your code that make up your sequence, string them together and run them in the same language, you should get the formula for the nth of your sequence for your sequence.

Example

Let's say I made this program:

abcdefghij

and chose the sequence of squares: http://oeis.org/A000290

and I chose it to print the first 5 terms of the sequence, the output should be:

1, 4, 9, 16, 25

Note: the output is flexible, you can choose what delimiter you want separating the terms, but the delimiter should be noticeable so that each of the terms of the sequence can be differentiated.

Now, the character at index 1 is a. The character at index 4 is d. The character at index 9 is i. So my new program would be:

adi

and it would have to print the formula for the nth term for my sequence, which is:

n^2

Simple!

Other things

You must print a minimum of 5 terms.
You may choose to 0- or 1-index.
Repeated numbers means repeated characters.
If your sequence isn't in order (e.g. it goes backwards), then your code still follows it (e.g. your code is written backwards).
You must use and only use the numbers in bounds of your answer, even if it has already gone out of bounds. You cannot use numbers from the same sequence you did not print.
If your sequence does not officially have a formula, you may use the first 3 letters of the name stated on the OEIS website (e.g. the fibonacci sequence would print fib and the lucas-lehmer sequence would print luc).

Remember, this is code-golf, so shortest answer, in bytes, wins!

Python 2, 35 Bytes

I decided to use the obvious sequence A000027, which essentially has the formula n ;) If you run the following code:

#print'n'
n=1
exec'print n;n+=1;'*8

You get the output:

1
2
3
4
5
6
7
8

And if you take the 8 characters from my source code (0-indexed), you get this:

print'n'

Which simply prints n.

If you were hoping for a more exciting answer, here's a Python 2 solution for n^2, i.e. A000290:

#p  r    i      n        t          '            n              ^                2                  '
n=1
exec'print n*n;n+=1;'*10


Help me fill my wallet! A while ago I purchased a new wallet which is able to hold 8 cards (4 on both side). However, I seem to have way more cards than that and I need to make choices on which ones I want to carry with me. Some cards I use more often than others, but the cards I prefer to carry with me are not necessarily the ones I use most.

The challenge

Given a stack of cards, return the layout of my wallet in the best way possible w.r.t. my preferences and restrictions. The layout should be as follows:

__ __ (row 1)
__ __ (row 2)
__ __ (row 3)
__ __ (row 4)

Currently I posess the following cards - stacks will always consist of a selection from these:

1 identity card (ID)
1 driver's license (DL)
2 credit cards (CC)
5 debit cards (DC)
1 public transport card (PC)
1 gym access card (GC)
9 membership cards from random stores and warehouses (MC)

I have some preferences and restrictions:

Cards sorted by priority: ID, DL, CC, DC, PC, GC, MC
Cards sorted by usage frequency: CC, DC, PC, GC, MC, ID, DL
For safety reasons, the total number of debit cards and credit cards in my wallet can be at most 1 more than the sum of all other cards that will go in my wallet ( NDC+NCC ≤ NID+NDL+NPC+NGC+NMC+1 ).
If present, my identity card and driver's licence should always go in row 1. This does not mean that other cards may not occupy spots in row 1.
The most frequently used cards from the stack should always go in row 4.

Rules

No 2 cards can occupy the same spot.
Higher priority cards are always prefered over lower priority ones, unless the DC/CC restriction kicks in.
ID/DL at row 1 overrules the frequency rule: if only ID is provided, it will go in row 1 and row 4 will be empty!
Input formatting can be done in any way you like, as long as the order of the input stack is retained. e.g. ID,CC,PC,MC,MC,MC,DL may also be supplied as e.g. 1ID 1CC 1PC 3MC 1DL 0DC 0GC or ID CC PC MC MC MC DL.
Output formatting does have a few restrictions: rows must all start at a new line, columns must be delimited in some way. Empty spots may be presented any way you like, as long as it does not mess up the 4x2 layout.
There can be more than one solution/order, it's up to you which one you provide as output.
You may assume that cards of the same type will always be grouped at input.
Apart from the above, standard code-golf rules and loopholes apply.

Bonus

You are allowed to remove 15% of your bytecount if you also return any cards that did not go in the wallet. Print "It fits!" in case of no remaining cards. This additional output should be clearly separated from the returend layout.

Examples

Input:

ID, DL, CC, GC, MC

2 possible outputs:

ID DL      DL ID
__ __  or  __ MC
MC __      __ __
CC GC      GC CC

optional: It fits!

Input:

ID, CC, DC, PC, GC, MC, MC, MC, MC, MC

2 possible outputs:

ID MC      GC ID
MC MC  or  MC PC
PC GC      MC MC
CC DC      DC CC

optional: e.g. (MC, MC)  or  (2MC)

Input:

DC, DC, CC, CC, GC, DL

2 possible outputs:

DL __      GC DL
__ __  or  DC __
GC DC      __ __
CC CC      CC CC

optional: e.g. (DC)  or  (1DC)

Input:

CC, DC, DC, DC

2 possible outputs:

__ __      __ __
__ __  or  __ __
__ __      __ __
CC __      __ CC

optional: e.g. (DC, DC, DC)  or  (3DC)

Input:

CC, CC, MC, MC, MC, MC, MC, MC, PC, DC, DC, DC, DC, DC, GC

2 possible outputs:

MC MC      MC DC
PC GC  or  DC GC
DC DC      PC MC
CC CC      CC CC

optional: e.g. (DC, DC, DC, MC, MC, MC, MC)  or  (3DC, 4MC)

Input:

MC, MC, MC, MC, MC, MC, MC

2 possible outputs:

__ MC      MC MC
MC MC  or  MC MC
MC MC      MC __
MC MC      MC MC

optional: It fits!

Input:

ID, CC

2 possible outputs:

ID __      __ ID
__ __  or  __ __
__ __      __ __
CC __      CC __

optional: It fits!

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

Java 10, 385 384 382 bytes

C->{String[]R=new String[8],F={"CC","DC","PC","GC","MC"};int c=C.size(),i=1,s=0;c=c>8?8:c;for(var q:C)if("DCC".contains(q))s++;for(;s>c- --s;c=(c=C.size())>8?8:c)i=C.remove(F[i])?i:0;for(c=0,i=8;i>0&c<5;c++)for(;i>0&C.remove(F[c]);)R[--i]=F[c];if(C.remove("ID"))R[c=0]="ID";if(C.remove("DL"))R[c<1?1:0]="DL";for(i=0;i<8;)System.out.print((R[i]!=null?R[i]:"__")+(i++%2>0?"\n":" "));}

Although it wasn't too difficult, I can see why it was unanswered. Especially that rule regarding "NDC+NCC ≤ NID+NDL+NPC+NGC+NMC+1" costs quite a lot of bytes at the moment..
And since it's been about 2.5 year since this challenge has been posted, OP might have got another wallet by now anyway.. ;p
-1 byte thanks to @Jakob.
Try it online.
Explanation:
C->{                       // Method with String-List parameter and String return-type
  String[]R=new String[8], //  String-array of size 8
          F={"CC","DC","PC","GC","MC"};
                           //  Frequency-order String-array
  int c=C.size(),          //  Size of the input-List
      i=1,                 //  Index integer, starting at 1
      s=0;                 //  Count-integer, starting at 0
  c=c>8?8:c;               //  If the size is larger than 8, set it to 8
  for(var q:C)             //  Loop over the cards of the input-List
    if("DCC".contains(q))  //   If the card is a DC or CC:
      s++;                 //    Increase the counter by 1
  for(;s>                  //  Loop as long as the amount of DC/CC is larger
         c- --s;           //  than the other amount of cards + 1
      c=(c=C.size())>8?8:c)//    Recalculate the size after every iteration
    i=C.remove(F[i])?i:0;  //   If the List still contains a DC, remove it
                           //   Else: remove a CC instead
  for(c=0,                 //  Reset `c` to 0
      i=8;i>0              //  Loop as long as there is still room in the wallet,
      &c<5;                //  and we still have cards left
      c++)                 //    Go to the next card-type after every iteration
    for(;i>0               //   Inner loop as long as there is still room in the wallet,
        &C.remove(F[c]);)  //   and we still have a card of the current type left
      R[i--]=F[c];         //    Put a card of the current type in the wallet
  if(C.remove("ID"))R[c=0]="ID";
                           //  Add the 'ID' card to the first row if present
  if(C.remove("DL"))R[c<1?1:0]="DL";
                           //  Add the 'DL' card to the first row if present
  for(i=0;i<8;)            //  Loop over the wallet
    System.out.print(      //   Print:
      (R[i]!=null?         //    If the current slot contains a card:
        R[i]               //     Append this card
       :                   //    Else:
        "__")              //     Append an empty slot ("__")
      +(i++%2>0?"\n":" "));//    Append the correct delimiter (space or new-line)
  return r;}               //  And finally return the result

Java 10, 390.15 (459 bytes - 15% bonus)
C->{String r="",R[]=new String[8],F[]={"CC","DC","PC","GC","MC"},t=r;int c=C.size(),i=1,s=0;for(var q:C)if("DCC".contains(q))s++;for(;s>(c>8?8:c)- --s;c=C.size())if(C.remove(F[i]))t+=F[i]+",";else i=0;for(c=0,i=8;i>0&c<5;c++)for(;i>0&&C.remove(F[c]);)R[--i]=F[c];if(C.remove("ID")){t+=R[0]+",";R[c=0]="ID";};if(C.remove("DL")){t+=R[c=c<1?1:0]+",";R[c]="DL";}for(i=0;i<8;)r+=(R[i]!=null?R[i]:"__")+(i++%2>0?"\n":" ");return r+"\n"+(C.size()>0?t+C:"It fits!");}

Try it online.