Generate Realistic Maps I drew this map of the regions of an imaginary word in a few minutes in MS Paint:

I think that being able to generate maps like this programmatically would be really cool.
Challenge
Write a program that takes in positive integers W and H, and a non-empty set of positive integers S.
Generate a standard true color image that is W pixels wide by H pixels tall.
For each integer i in S, draw a planar region in the image whose area in pixels is proportional to i, using a color different from any neighboring regions. Specifically, the number of pixels in the region should be W * H * i / sum(S), rounded either up or down to ensure that every pixel in the image belongs to a region.
A planar region is a set of pixels with the property that any pixel in the region can be reached from any other by staying within the region and only moving orthogonally (and not diagonally). My map above has 10 planar regions.
All the pixels in a planar region must be the same color, which must be different than the color of any neighboring regions. Regions may be the same color if they are not neighbors.
Otherwise, there are no limitations on how you shape, position, or color your regions. This is a popularity-contest. The goal is to create a program that makes realistic maps of imaginary worlds, physical or political, with any geography, at any scale.
Naturally, please show off your best output images, not just your code.
Details

Take input from file, command line, stdin, or similar. Save the image in any standard format or display it to the screen.
Your program should be deterministic for identical inputs. That is, the output image should always be the same for some particular H, W, and S. (Note that S is a set, not a list, so its ordering doesn't matter.) Otherwise you may employ randomness where desired, though you are not required to (but I highly suggest it).
The output image geography does not need to "scale" for different values of W or H (though it could). It may be completely different.
You may randomly assign colors, disregarding the neighbor-color rule, as long as there at least 32 random color possibilities, since it would be unlikely for two neighbors to get colored the same.
The regions stop at the image boundaries. There is no wrap around.
Regions may contain zero pixels (and thus be nonexistent), as would be the case when there are more regions than pixels.

Example Input
A valid submission might have generated my map above with the parameters:
W = 380
H = 260
S = {233, 420, 1300, 3511, 4772, 5089, 9507, 22107, 25117, 26744}

These S values are the exact same as the number of pixels in each region but that need not be the case. Remember that S is a set, so it is not necessarily always sorted.

I agree with the others, This was a surprisingly difficult challenge. Partially due to the requirement to have adjacently connected pixels of the same region type, but also due to the aesthetic challenge to make the regions look like a map of countries.

Here is my attempt... it is horribly inefficient but seems to produce reasonable output. Continuing the trend of using common input for comparison purposes:

Parameters : 380 260 233 420 1300 3511 4772 5089 9507 22107 25117 26744

Parameters : 380 260 8 5 6 7 8 4 5 6 7 9 4 6 9 5 8 7 5

Dark Age of Camelot 213 307 1 1 1

My larger example: (640 480 6 1 7 2 9 3 4 5 6 1 9 8 7 44 3 1 9 4 5 6 7 2 3 4 9 3 4 5 9 8 7 5 6 1 2 1 2 1 2 6 7 8 9 63 3)

An example with more countries: 640 480 6 1 7 2 9 3 4 5 6 1 9 8 7 44 3 1 9 4 5 6 7 2 3 4 9 3 4 5 9 8 7 5 6 1 2 1 2 1 2 6 7 8 9 63 5 33 11 88 2 7 9 5 6 2 5 7

package GenerateRealisticMaps;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import javax.imageio.ImageIO;

public class GenerateRealisticMaps
{
    private static final Random rand = new Random(3);
    private static final Color[] paletteizedColours = new Color[100];

    // create colour palette
    static
    {
        paletteizedColours[0] = new Color(0xFF000000);
        for (int i = 1; i < paletteizedColours.length; i++)
        {
            paletteizedColours[i] = Color.getHSBColor(rand.nextFloat(), rand.nextFloat(), 0.5f + rand.nextFloat() * 0.4f);
        }
    }

    /**
     * Represents a pixel that is the boundary of a region
     * @author default
     *
     */
    public static class BoundaryPixel
    {
        public BoundaryPixel(int x, int y, int otherRegionId)
        {
            super();
            this.x = x;
            this.y = y;
            this.otherRegionId = otherRegionId;
        }

        int x;
        int y;
        int otherRegionId;
    }

    /**
     * Group of adjacent pixels that represent a region (i.e. a country in the map)
     * @author default
     *
     */
    public static class Region
    {
        static private int masterId = 0;

        Region(int desiredSize)
        {
            this.desiredSize = desiredSize;
            id = ++masterId;
        }

        int desiredSize;
        int size = 0;
        int id;
        List<BoundaryPixel> boundary = new ArrayList<GenerateRealisticMaps.BoundaryPixel>();

    }

    /**
     * Container of regions
     * @author default
     *
     */
    public static class Regions
    {
        List<Region> regionList = new ArrayList<GenerateRealisticMaps.Region>();
        Map<Integer, Region> regionMap = new HashMap<Integer, GenerateRealisticMaps.Region>();
    }

    public static void main(String[] args) throws IOException
    {
        int width = Integer.parseInt(args[0]);
        int height = Integer.parseInt(args[1]);
        int[] s = new int[args.length - 2];

        // read in the region weights
        int sum = 0;
        for (int i = 0; i < args.length - 2; i++)
        {
            sum += s[i] = Integer.parseInt(args[i + 2]);
        }

        int totalPixels = width * height;

        double multiplier = ((double) totalPixels) / sum;

        // convert region weights to pixel counts
        int runningCount = 0;
        for (int i = 0; i < s.length - 1; i++)
        {
            runningCount += s[i] = (int) (multiplier * s[i]);
        }
        s[s.length - 1] = totalPixels - runningCount;

        Regions regions = new Regions();
        int[][] map = new int[width][height];

        // initialise region starting pixels
        for (int v : s)
        {
            Region region = new Region(v);
            regions.regionList.add(region);
            regions.regionMap.put(region.id, region);

            int x;
            int y;
            do
            {
                x = rand.nextInt(width);
                y = rand.nextInt(height);
            } while (map[x][y] != 0);

            map[x][y] = region.id;
            region.size++;

        }

        // initialise a "height" map that provides cost to claim a unclaimed region. This allows for more natural shaped countries
        int[][] heightMap = new int[width][height];
        for (int i = 0; i < width; i++)
        {
            for (int j = 0; j < height; j++)
            {
                heightMap[i][j] = rand.nextInt(50);
            }
        }

        boolean equal = false;

        // main loop
        do
        {
            growRegions(map, heightMap, width, height, regions);

            // determine whether regions have reached their desired size
            equal = true;
            for (Region region : regions.regionList)
            {
                equal = equal && region.size == region.desiredSize;
            }

            if (equal)
            {
                HashMap<Integer, Set<Integer>> commonIsolatedRegions = new HashMap<Integer, Set<Integer>>();
                int isolatedRegionId = 0;
                int[][] isolatedRegions = new int[width][height];
                List<Integer> isolatedRegionSize = new ArrayList<Integer>();
                isolatedRegionSize.add(-1); // add dummy entry at index 0 since region ids start at 1

                // go though each pixel and attempt to identify an isolated region from that point if it as not
                // yet been identified... i.e. an enclosed area.
                for (int i = 0; i < width; i++)
                {
                    for (int j = 0; j < height; j++)
                    {
                        if (isolatedRegions[i][j] == 0)
                        {
                            isolatedRegionId++;

                            Point point = new Point(i, j);
                            int size = identifyEnclosedArea(map, isolatedRegions, width, height, point, isolatedRegionId);

                            // add this isolated region id to the group of isolated regions associated with the region at this pixel
                            Set<Integer> isolatedRegionSet = commonIsolatedRegions.get(map[i][j]);
                            if (isolatedRegionSet == null)
                            {
                                isolatedRegionSet = new HashSet<Integer>();
                                commonIsolatedRegions.put(map[i][j], isolatedRegionSet);
                            }
                            isolatedRegionSet.add(isolatedRegionId);
                            isolatedRegionSize.add(size);
                        }
                    }
                }

                // only keep the largest isolated region in each group. Mark the other members in the group areas as unclaimed.
                for (Region region : regions.regionList)
                {
                    Set<Integer> isolatedRegionSet = commonIsolatedRegions.get(region.id);

                    // find the largest isolatedRegion mapped to this region
                    int largestIsolatedRegionId = -1;
                    int largestIsolatedRegionSize = -1;
                    for (Integer isolatedRegionIdentifier : isolatedRegionSet)
                    {
                        if (isolatedRegionSize.get(isolatedRegionIdentifier) > largestIsolatedRegionSize)
                        {
                            largestIsolatedRegionSize = isolatedRegionSize.get(isolatedRegionIdentifier);
                            largestIsolatedRegionId = isolatedRegionIdentifier;
                        }
                    }
                    // remove the largest isolated region (i.e. retain those pixels)
                    isolatedRegionSet.remove(largestIsolatedRegionId);

                    if (isolatedRegionSet.size() > 0)
                    {
                        equal = false;

                        // for all remaining isolated regions mapped to this region, convert to unclaimed areas.
                        for (Integer isolatedRegionIdentifier : isolatedRegionSet)
                        {
                            for (int i = 0; i < width; i++)
                            {
                                for (int j = 0; j < height; j++)
                                {
                                    if (isolatedRegions[i][j] == isolatedRegionIdentifier)
                                        map[i][j] = 0;
                                }
                            }
                        }
                    }
                }
            }

        } while (!equal);

        saveOutputImage("out.final.png", map);
    }

    /**
     * Renders and saves the output image
     *
     * @param filename
     * @param map
     * @throws IOException
     */
    public static void saveOutputImage(String filename, int[][] map) throws IOException
    {

        final int scale = 1;
        final int width = map.length;
        final int height = map[0].length;
        BufferedImage image = new BufferedImage(width * scale, height * scale, BufferedImage.TYPE_INT_RGB);

        Graphics2D g = (Graphics2D) image.getGraphics();

        for (int j = 0; j < height; j++)
        {
            for (int i = 0; i < width; i++)
            {
                g.setColor(paletteizedColours[map[i][j]]);
                g.fillRect(i * scale, j * scale, scale, scale);
            }
        }

        ImageIO.write(image, "png", new File(filename));
    }

    /**
     * Grows the regions of the world. Firstly by unclaimed cells and then by distributing cells amongst the regions.
     *
     * @param map
     *            cell to region map
     * @param heightMap
     *            the "height" cost of unclaimed cells. Used to give more natural shapes.
     * @param width
     * @param height
     * @param regions
     */
    public static void growRegions(int[][] map, int[][] heightMap, int width, int height, Regions regions)
    {
        // reset region sizes
        for (Region region : regions.regionList)
        {
            region.size = 0;
            region.boundary.clear();
        }

        // populate corners with adjacent pixel region id... these pixels cannot ever be "grown" into.
        map[0][0] = map[1][0];
        map[width - 1][0] = map[width - 1][5];
        map[width - 1][height - 1] = map[width - 2][height - 1];
        map[0][height - 1] = map[1][height - 1];

        int i, x, y, dx = 0, dy = 0, currHeight, currentId = -1, pixelRegionId;
        Region currRegion = null;
        ;

        // calculate initial region sizes
        for (y = 0; y < height; y++)
        {
            for (x = 0; x < width; x++)
            {
                if (map[x][y] > 0)
                    regions.regionMap.get(map[x][y]).size++;
            }
        }

        // expand regions into surrounding unclaimed pixels.
        // construct a list of region boundary pixels in the process.
        for (y = 1; y < height - 1; y++)
        {
            for (x = 1; x < width - 1; x++)
            {
                int cellId = map[x][y];
                if (cellId > 0)
                {
                    if (cellId != currentId)
                    {

                        currRegion = regions.regionMap.get(map[x][y]);
                        currentId = currRegion.id;
                    }

                    currHeight = heightMap[x][y]++;

                    for (i = 0; i < 4; i++)
                    {
                        switch (i)
                        {
                        case 0:
                            dx = x - 1;
                            dy = y;
                            break;
                        case 1:
                            dx = x + 1;
                            dy = y;
                            break;
                        case 2:
                            dx = x;
                            dy = y - 1;
                            break;
                        case 3:
                            dx = x;
                            dy = y + 1;
                            break;
                        }
                        pixelRegionId = map[dx][dy];
                        switch (pixelRegionId)
                        {
                        // unclaimed cell...
                        case 0:
                            if (heightMap[dx][dy] < currHeight)
                            {
                                map[dx][dy] = currRegion.id;
                                currRegion.size++;
                            }
                            break;
                        // claimed cell...
                        default:
                            if (pixelRegionId != currRegion.id)
                            {
                                currRegion.boundary.add(new BoundaryPixel(dx, dy, pixelRegionId));
                            }
                            break;
                        }
                    }
                }
            }
        }

        HashMap<Integer, List<BoundaryPixel>> neighbourBorders = new HashMap<Integer, List<BoundaryPixel>>();

        // for all regions...
        for (Region region : regions.regionList)
        {
            // that are less than the desired size...
            if (region.size < region.desiredSize)
            {
                neighbourBorders.clear();

                // identify the boundary segment per neighbour of the region
                for (BoundaryPixel boundaryPixel : region.boundary)
                {
                    List<BoundaryPixel> neighbourBorderSegment = neighbourBorders.get(boundaryPixel.otherRegionId);
                    if (neighbourBorderSegment == null)
                    {
                        neighbourBorderSegment = new ArrayList<GenerateRealisticMaps.BoundaryPixel>();
                        neighbourBorders.put(boundaryPixel.otherRegionId, neighbourBorderSegment);
                    }
                    neighbourBorderSegment.add(boundaryPixel);
                }

                out:
                // for each neighbour...
                for (int id : neighbourBorders.keySet())
                {
                    Region neighbourRegion = regions.regionMap.get(id);
                    int surplusPixelCount = neighbourRegion.size - neighbourRegion.desiredSize;
                    // that has surplus pixels...
                    if (surplusPixelCount > 0)
                    {
                        // and convert the border segment pixels to the current region...
                        List<BoundaryPixel> neighbourBorderSegment = neighbourBorders.get(id);
                        int index = 0;
                        while (surplusPixelCount-- > 0 && index < neighbourBorderSegment.size())
                        {
                            BoundaryPixel boundaryPixel = neighbourBorderSegment.get(index++);
                            map[boundaryPixel.x][boundaryPixel.y] = region.id;
                            region.size++;
                            regions.regionMap.get(boundaryPixel.otherRegionId).size--;
                            // until we reach the desired size...
                            if (region.size == region.desiredSize)
                                break out;
                        }
                    }
                }
            }

            // if region contains more pixels than desired...
            else if (region.size > region.desiredSize)
            {
                // and the region has neighbours
                if (region.boundary.size() > 0)
                {
                    // choose a neighbour to off load extra pixels to
                    Region neighbour = regions.regionMap.get(region.boundary.remove(rand.nextInt(region.boundary.size())).otherRegionId);

                    ArrayList<BoundaryPixel> adjustedBoundary = new ArrayList<>();
                    // iterate over the boundary neighbour's boundary pixels...
                    for (BoundaryPixel boundaryPixel : neighbour.boundary)
                    {
                        // and then for those pixels which are of the current region, convert to the neighbour region
                        if (boundaryPixel.otherRegionId == region.id)
                        {
                            map[boundaryPixel.x][boundaryPixel.y] = neighbour.id;
                            neighbour.size++;
                            region.size--;
                            // stop when we reach the region's desired size.
                            if (region.size == region.desiredSize)
                                break;
                        }
                        else
                        {
                            adjustedBoundary.add(boundaryPixel);
                        }
                    }
                    neighbour.boundary = adjustedBoundary;
                }
            }
        }

    }

    /**
     * identifies the area, starting at the given point, in which adjacent pixels are of the same region id.
     *
     * @param map
     * @param isolatedRegionMap
     *            cells identifying which area that the corresponding map cell belongs
     * @param width
     * @param height
     * @param point
     *            the starting point of the area to be identified
     * @param isolatedRegionId
     *            the id of the region to assign cells with
     * @return the size of the identified area
     */
    private static int identifyEnclosedArea(int[][] map, int[][] isolatedRegionMap, int width, int height, Point point, final int isolatedRegionId)
    {
        ArrayList<Point> stack = new ArrayList<Point>();
        final int EXPECTED_REGION_ID = map[point.x][point.y];
        stack.add(point);
        int size = 0;

        while (stack.size() > 0)
        {
            Point p = stack.remove(stack.size() - 1);
            int x = p.x;
            int y = p.y;
            if (y < 0 || y > height - 1 || x < 0 || x > width - 1 || isolatedRegionMap[x][y] > 0)
                continue;
            int val = map[x][y];
            if (val == EXPECTED_REGION_ID)
            {
                isolatedRegionMap[x][y] = isolatedRegionId;
                size++;
                stack.add(new Point(x + 1, y));
                stack.add(new Point(x - 1, y));
                stack.add(new Point(x, y + 1));
                stack.add(new Point(x, y - 1));
            }
        }

        return size;
    }

}

Explanation (from comments)

The algorithm is pretty simple: Firstly initialise the map with random weights, choose random seed pixels for each of the country regions. Secondly "grow" each region by attempting to claim unclaimed adjacent pixels. This occurs when the weight of the current pixel exceeds the unclaimed weight.

Each pixel in a region increases its weight each growth cycle. Additionally if a region has neighbours then if the current region being considered has less pixels than desired, then it will steal pixels from its neighbour if the neighbour has more pixels than desired. If the current region has more pixels than its neighbour then it randomly chooses a neighbour and then give all the surplus pixels to that neighbour. When all regions are of the correct size, then the third phase occurs to identify and convert any regions that have been split and are no longer continuous.

Only the largest split of the region is kept and the other splits are converted into unclaimed pixels and the second phase starts again. This repeats until all pixels in a region are adjacent and all regions are of the correct size.


Find highest scoring matrix without property X This challenge is partly an algorithms challenge, partly an optimization challenge and partly simply a fastest code challenge.

A cyclic matrix is fully specified by its first row r. The remaining rows are each cyclic permutations of the row r with offset equal to the row index. We will allow cyclic matrices which are not square so that they are simply missing some of their last rows. We do however always assume that the number of rows is no more than the number of columns. For example, consider the following 3 by 5 cyclic matrix.

10111
11011
11101

We say a matrix has property X if it contains two non-empty sets of columns with non-identical indices which have the same (vector) sum. The vector sum of two columns is simply an element-wise summation of the two columns.  That is the sum of two columns containing x elements each is another column containing x elements.

The matrix above trivially has property X as the first and last columns are the same. The identity matrix never has property X.

If we just remove the last column of the matrix above then we get an example which does not have property X and would give a score of 4/3.

1011
1101
1110

The task

The task is to write code to find the highest scoring cyclic matrix whose entries are all 0 or 1 and which does not have property X.

Score

Your score will be the number columns divided by the number of rows in your best scoring matrix.

Tie Breaker

If two answers have the same score, the one submitted first wins.

In the (very) unlikely event that someone finds a method to get unlimited scores, the first valid proof of such a solution will be accepted.  In the even more unlikely event that you can find a proof of optimality of a finite matrix I will of course award the win too.

Hint

Getting a score of 12/8 is not too hard.

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.

Leading entries

36/19 by Peter Taylor (Java)
32/17 by Suboptimus Prime (C#)
21/12 by justhalf (Python 2)

16/9 20/11 22/12 28/15 30/16 32/17 34/18 36/19 (Java)

This uses a number of ideas to reduce the search space and cost. View the revision history for more details on earlier versions of the code.

It's clear that wlog we can consider only circulant matrices in which the first row is a Lyndon word: if the word is non-prime then it must have property X, and otherwise we can rotate without affecting the score or property X.
Based on heuristics from the observed short winners, I'm now iterating through the Lyndon words starting at the ones with 50% density (i.e. the same number of 0 and 1) and working out; I use the algorithm described in A Gray code for fixed-density necklaces and Lyndon words in constant amortized time, Sawada and Williams, Theoretical Computer Science 502 (2013): 46-54.
An empirical observation is that the values occur in pairs: each optimum Lyndon word that I've found scores the same as its reversal. So I get about a factor of two speedup by only considering one half of each such pair.
My original code worked with BigInteger to give an exact test. I get a significant speed improvement, at the risk of false negatives, by operating modulo a large prime and keeping everything in primitives. The prime I've chosen is the largest one smaller than 257, as that allows multiplying by the base of my notional vector representation without overflowing.
I've stolen Suboptimus Prime's heuristic that it's possible to get quick rejections by considering subsets in increasing order of size. I've now merged that idea with the ternary subset meet-in-the-middle approach to test for colliding subsets. (Credit to KennyTM for suggesting trying to adapt the approach from the integer subset problem; I think that xnor and I saw the way to do it pretty much simultaneously). Rather than looking for two subsets which can include each column 0 or 1 times and have the same sum, we look for one subset which can include each column -1, 0, or 1 times and sum to zero. This significantly reduces the memory requirements.
There's an extra factor of two saving in memory requirements by observing that since each element in {-1,0,1}^m has its negation also in {-1,0,1}^m it's only necessary to store one of the two.
I also improve memory requirements and performance by using a custom hashmap implementation. To test 36/19 requires storing 3^18 sums, and 3^18 longs is almost 3GB without any overhead - I gave it 6GB of heap because 4GB wasn't enough; to go any further (i.e. test 38/20) within 8GB of RAM would require further optimisation to store ints rather than longs. With 20 bits required to say which subset produces the sum that would leave 12 bits plus the implicit bits from the bucket; I fear that there would be too many false collisions to get any hits.
Since the weight of the evidence suggests that we should look at 2n/(n+1), I'm speeding things up by just testing that.
There's some unnecessary but reassuring statistical output.

import java.util.*;

// Aiming to find a solution for (2n, n+1).
public class PPCG41021_QRTernary_FixedDensity {
    private static final int N = 36;
    private static int density;
    private static long start;
    private static long nextProgressReport;

    public static void main(String[] args) {
        start = System.nanoTime();
        nextProgressReport = start + 5 * 60 * 1000000000L;

        // 0, -1, 1, -2, 2, ...
        for (int i = 0; i < N - 1; i++) {
            int off = i >> 1;
            if ((i & 1) == 1) off = ~off;
            density = (N >> 1) + off;

            // Iterate over Lyndon words of length N and given density.
            for (int j = 0; j < N; j++) a[j] = j < N - density ? '0' : '1';
            c = 1;
            Bs[1] = N - density;
            Bt[1] = density;
            gen(N - density, density, 1);
            System.out.println("----");
        }

        System.out.println("Finished in " + (System.nanoTime() - start)/1000000 + " ms");
    }

    private static int c;
    private static int[] Bs = new int[N + 1], Bt = new int[N + 1];
    private static char[] a = new char[N];
    private static void gen(int s, int t, int r) {
        if (s > 0 && t > 0) {
            int j = oracle(s, t, r);
            for (int i = t - 1; i >= j; i--) {
                updateBlock(s, t, i);
                char tmp = a[s - 1]; a[s - 1] = a[s+t-i - 1]; a[s+t-i - 1] = tmp;
                gen(s-1, t-i, testSuffix(r) ? c-1 : r);
                tmp = a[s - 1]; a[s - 1] = a[s+t-i - 1]; a[s+t-i - 1] = tmp;
                restoreBlock(s, t, i);
            }
        }
        visit();
    }

    private static int oracle(int s, int t, int r) {
        int j = pseudoOracle(s, t, r);
        updateBlock(s, t, j);
        int p = testNecklace(testSuffix(r) ? c - 1 : r);
        restoreBlock(s, t, j);
        return p == N ? j : j + 1;
    }

    private static int pseudoOracle(int s, int t, int r) {
        if (s == 1) return t;
        if (c == 1) return s == 2 ? N / 2 : 1;
        if (s - 1 > Bs[r] + 1) return 0;
        if (s - 1 == Bs[r] + 1) return cmpPair(s-1, t, Bs[c-1]+1, Bt[c-1]) <= 0 ? 0 : 1;
        if (s - 1 == Bs[r]) {
            if (s == 2) return Math.max(t - Bt[r], (t+1) >> 1);
            return Math.max(t - Bt[r], (cmpPair(s-1, t, Bs[c-1] + 1, Bt[c-1]) <= 0) ? 0 : 1);
        }
        if (s == Bs[r]) return t;
        throw new UnsupportedOperationException("Hit the case not covered by the paper or its accompanying code");
    }

    private static int testNecklace(int r) {
        if (density == 0 || density == N) return 1;
        int p = 0;
        for (int i = 0; i < c; i++) {
            if (r - i <= 0) r += c;
            if (cmpBlocks(c-i, r-i) < 0) return 0;
            if (cmpBlocks(c-i, r-1) > 0) return N;
            if (r < c) p += Bs[r-i] + Bt[r-i];
        }
        return p;
    }

    private static int cmpPair(int a1, int a2, int b1, int b2) {
        if (a1 < b1) return -1;
        if (a1 > b1) return 1;
        if (a2 < b2) return -1;
        if (a2 > b2) return 1;
        return 0;
    }

    private static int cmpBlocks(int i, int j) {
        return cmpPair(Bs[i], Bt[i], Bs[j], Bt[j]);
    }

    private static boolean testSuffix(int r) {
        for (int i = 0; i < r; i++) {
            if (c - 1 - i == r) return true;
            if (cmpBlocks(c-1-i, r-i) < 0) return false;
            if (cmpBlocks(c-1-i, r-1) > 0) return true;
        }
        return false;
    }

    private static void updateBlock(int s, int t, int i) {
        if (i == 0 && c > 1) {
            Bs[c-1]++;
            Bs[c] = s - 1;
        }
        else {
            Bs[c] = 1;
            Bt[c] = i;
            Bs[c+1] = s-1;
            Bt[c+1] = t-i;
            c++;
        }
    }

    private static void restoreBlock(int s, int t, int i) {
        if (i == 0 && (c > 0 || (Bs[1] != 1 || Bt[1] != 0))) {
            Bs[c-1]--;
            Bs[c] = s;
        }
        else {
            Bs[c-1] = s;
            Bt[c-1] = t;
            c--;
        }
    }

    private static long[] stats = new long[N/2+1];
    private static long visited = 0;
    private static void visit() {
        String word = new String(a);

        visited++;
        if (precedesReversal(word) && testTernary(word)) System.out.println(word + " after " + (System.nanoTime() - start)/1000000 + " ms");
        if (System.nanoTime() > nextProgressReport) {
            System.out.println("Progress: visited " + visited + "; stats " + Arrays.toString(stats) + " after " + (System.nanoTime() - start)/1000000 + " ms");
             nextProgressReport += 5 * 60 * 1000000000L;
        }
    }

    private static boolean precedesReversal(String w) {
        int n = w.length();
        StringBuilder rev = new StringBuilder(w);
        rev.reverse();
        rev.append(rev, 0, n);
        for (int i = 0; i < n; i++) {
            if (rev.substring(i, i + n).compareTo(w) < 0) return false;
        }
        return true;
    }

    private static boolean testTernary(String word) {
        int n = word.length();
        String rep = word + word;

        int base = 1;
        for (char ch : word.toCharArray()) base += ch & 1;

        // Operating base b for b up to 32 implies that we can multiply by b modulo p<2^57 without overflowing a long.
        // We're storing 3^(n/2) ~= 2^(0.8*n) sums, so while n < 35.6 we don't get *too* bad a probability of false reject.
        // (In fact the birthday paradox assumes independence, and our values aren't independent, so we're better off than that).
        long p = (1L << 57) - 13;
        long[] basis = new long[n];
        basis[0] = 1;
        for (int i = 1; i < basis.length; i++) basis[i] = (basis[i-1] * base) % p;

        int rows = n / 2 + 1;
        long[] colVals = new long[n];
        for (int col = 0; col < n; col++) {
            for (int row = 0; row < rows; row++) {
                colVals[col] = (colVals[col] + basis[row] * (rep.charAt(row + col) & 1)) % p;
            }
        }

        MapInt57Int27 map = new MapInt57Int27();
        // Special-case the initial insertion.
        int[] oldLens = new int[map.entries.length];
        int[] oldSupercounts = new int[1 << 10];
        {
            // count = 1
            for (int k = 0; k < n/2; k++) {
                int val = 1 << (25 - k);
                if (!map.put(colVals[k], val)) { stats[1]++; return false; }
                if (!map.put(colVals[k + n/2], val + (1 << 26))) { stats[1]++; return false; }
            }
        }
        final long keyMask = (1L << 37) - 1;
        for (int count = 2; count <= n/2; count++) {
            int[] lens = map.counts.clone();
            int[] supercounts = map.supercounts.clone();
            for (int sup = 0; sup < 1 << 10; sup++) {
                int unaccountedFor = supercounts[sup] - oldSupercounts[sup];
                for (int supi = 0; supi < 1 << 10 && unaccountedFor > 0; supi++) {
                    int i = (sup << 10) + supi;
                    int stop = lens[i];
                    unaccountedFor -= stop - oldLens[i];
                    for (int j = oldLens[i]; j < stop; j++) {
                        long existingKV = map.entries[i][j];
                        long existingKey = ((existingKV & keyMask) << 20) + i;
                        int existingVal = (int)(existingKV >>> 37);

                        // For each possible prepend...
                        int half = (existingVal >> 26) * n/2;
                        // We have 27 bits of key, of which the top marks the half, so 26 bits. That means there are 6 bits at the top which we need to not count.
                        int k = Integer.numberOfLeadingZeros(existingVal << 6) - 1;
                        while (k >= 0) {
                            int newVal = existingVal | (1 << (25 - k));
                            long pos = (existingKey + colVals[k + half]) % p;
                            if (pos << 1 > p) pos = p - pos;
                            if (pos == 0 || !map.put(pos, newVal)) { stats[count]++; return false; }
                            long neg = (p - existingKey + colVals[k + half]) % p;
                            if (neg << 1 > p) neg = p - neg;
                            if (neg == 0 || !map.put(neg, newVal)) { stats[count]++; return false; }
                            k--;
                        }
                    }
                }
            }
            oldLens = lens;
            oldSupercounts = supercounts;
        }

        stats[n/2]++;
        return true;
    }

    static class MapInt57Int27 {
        private long[][] entries;
        private int[] counts;
        private int[] supercounts;

        public MapInt57Int27() {
            entries = new long[1 << 20][];
            counts = new int[1 << 20];
            supercounts = new int[1 << 10];
        }

        public boolean put(long key, int val) {
            int bucket = (int)(key & (entries.length - 1));
            long insert = (key >>> 20) | (((long)val) << 37);
            final long mask = (1L << 37) - 1;

            long[] chain = entries[bucket];
            if (chain == null) {
                chain = new long[16];
                entries[bucket] = chain;
                chain[0] = insert;
                counts[bucket]++;
                supercounts[bucket >> 10]++;
                return true;
            }

            int stop = counts[bucket];
            for (int i = 0; i < stop; i++) {
                if ((chain[i] & mask) == (insert & mask)) {
                    return false;
                }
            }

            if (stop == chain.length) {
                long[] newChain = new long[chain.length < 512 ? chain.length << 1 : chain.length + 512];
                System.arraycopy(chain, 0, newChain, 0, chain.length);
                entries[bucket] = newChain;
                chain = newChain;
            }
            chain[stop] = insert;
            counts[bucket]++;
            supercounts[bucket >> 10]++;
            return true;
        }
    }
}

The first one found is

000001001010110001000101001111111111

and that's the only hit in 15 hours.

Smaller winners:

4/3:    0111                       (plus 8 different 8/6)
9/6:    001001011                  (and 5 others)
11/7:   00010100111                (and 3 others)
13/8:   0001001101011              (and 5 others)
15/9:   000010110110111            (and 21 others)
16/9:   0000101110111011           (and 1 other)
20/11:  00000101111011110111       (and others)
22/12:  0000001100110011101011     (and others)
24/13:  000000101011101011101011   (and others)
26/14:  00000001101110010011010111 (and others)
28/15:  0000000010000111100111010111 (and others)
30/16:  000000001011001110011010101111 (and probably others)
32/17:  00001100010010100100101011111111 (and others)
34/18:  0000101000100101000110010111111111 (and others)


Approximate the Fransén-Robinson constant Given an input n, output the value of the Fransén-Robinson constant with n digits after the decimal place, with rounding.

Rules

You may assume that all inputs are integers between 1 and 60.
You may not store any related values - the constant must be calculated, not recalled.
Rounding must be done with the following criteria:

If the digit following the final digit is less than five, the final digit must remain the same.
If the digit following the final digit is greater than or equal to five, the final digit must be incremented by one.

You must only output the first n+1 digits.
Standard loopholes apply.

Test Cases

>>> f(0)
3

>>> f(1)
2.8

>>> f(11)
2.80777024203

>>> f(50)
2.80777024202851936522150118655777293230808592093020

>>> f(59)
2.80777024202851936522150118655777293230808592093019829122005

>>> f(60)
2.807770242028519365221501186557772932308085920930198291220055

Mathematica, 44 39 36 25 UTF-8 bytes

-5 bytes thanks to Sp3000
-3 bytes thanks to kennytm
-11 bytes thanks to senegrom

Crossed out 44 is still regular 44!!

N[∫1/x!{x,-1,∞},#+1]&

Example:

f=N[∫1/x!{x,-1,∞},#+1]&
f[2]

Outputs 2.81.

Explanation

N[               , # + 1]
  ∫1/x!{x,-1,∞}

First step takes Numeric of the rest, with # (first parameter) + 1 precision. ! (factorial) does what you'd expect. {x, -1, Infinity} sets the bounds for the (strangely formatted) Integral.


Distinguish English and Spanish with regular expressions The task is to to compete for the shortest regex (in bytes) in your preferred programming language which can distinguish between English and Spanish with minimum 60% 90% accuracy.
Silvio Mayolo's submission (pinned as Best Answer) has secured his spot as the winner of original contest against any chance of being contested.  In order to provide room for further submissions, he has generously allowed the scoring requirement to be pushed to 90% accuracy.
Links to wordlists have been replaced due to concerns voiced in the comments.
The following word lists (based on these) must be used: English, Spanish
The Spanish wordlist is already transliterated into ASCII, and there is no word present in either which is also present in the other.
A naive approach to distinguishing Spanish from English might be to match if the word ends in a vowel:
[aeiou]$ i 9 bytes
Here's a live example, where 6 of 8 words are successfully identified, for 75% accuracy:

const regex = /[aeiou]$/i;

const words = [
  'hello',
  'hola',
  'world',
  'mundo',
  'foo',
  'tonto',
  'bar',
  'barra'
];

words.forEach(word => {
  const match = word.match(regex);
  const langs = ['English', 'Spanish'];
  const lang = langs[+!!match];
  console.log(word, lang);
});

Any Language, 0.3677 (60.6064%, 1 byte)
a

No, I'm not joking. The single-character regular expression a successfully identifies Spanish words over English given your input files 60.6064% of the time, which makes it a valid submission.
Here's a complete, runnable Perl script that checks the percentage of this regular expression, assuming you've downloaded english.json and spanish.json into the same folder as the script.
#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

my @english;
my @spanish;

my $fh;
open $fh, '<', 'english.json';
while (<$fh>) {
    push @english, $1 if /"(\w+)"/;
}
close $fh;

open $fh, '<', 'spanish.json';
while (<$fh>) {
    push @spanish, $1 if /"(\w+)"/;
}
close $fh;

my $correct = 0;
my $total = 0;

my $re = qr/a/;

for (@english) {
    $total++;
    $correct++ unless /$re/;
}
for (@spanish) {
    $total++;
    $correct++ if /$re/;
}

say "$correct / $total (@{[100*$correct/$total]}%)";


Draw a graph of \$y=(-n)^x\$ Challenge

Given an input of an integer, \$n\$ (where \$0<n<50\$), output the graph of \$y=\mathrm{Re}((-n)^x)\$ from \$x = -3\$ to \$x = 3\$ inclusive.

Where \$\mathrm{Re}(p)\$ is the real part of the complex number \$p\$.

Note that \$\mathrm{Re}((-n)^x) = n^x \cos{(\pi x)}\$

Output

The output may be in any form you wish (e.g. an image or a window etc.). ASCII art is disallowed.

The graph does not need to have axes (to allow languages without built-in graphing functions to compete).

If an image is output, it each side must be longer than 500 pixels. Similarly, the plot must fill the image as best it can.

The minimum interval between plots is 0.05.

Vector graphics are allowed.

Examples

For an input of 2:

For an input of 1:

You must put your corresponding outputs in your answer (n = 1 and n = 2).

Winning

The shortest code in bytes wins.

TI-Basic, 26 21 bytes
~3→Xmin
3→Xmax
Prompt N
DrawF N^Xcos(πX

Output for N=2:


Password Bishop Goodness Derived from this, now deleted, post.

Given a string, answer (truthy/falsy or two consistent values) if it constitutes a good Bishop password, which is when all the following conditions are met:

it has at least 10 characters
it has at least 3 digits ([0-9])
it is not a palindrome (identical to itself when reversed)

You get 0 bytes bonus if your code is a good Bishop password.

Warning: Do not use Bishop goodness as a measure of actual password strength!

Examples

Good Bishop passwords

PPCG123GCPP
PPCG123PPCG
PPCG123gcpp
0123456789
Tr0ub4dor&3

Not Good Bishop passwords

PPCG123 (too short)
correct horse battery staple (not enough digits)
PPCG121GCPP (palindrome)
 (too short and not enough digits)
abc121cba (too short and palindrome)
aaaaaaaaaaaa (palindrome and not enough digits)
abc99cba (everything wrong)

Python 2, 61 59 54 51 bytes

lambda s:sum(map(str.isdigit,s))>2<s[:9]<s<>s[::-1]

Try it online!

-5 bytes, thanks to Erik the Outgolfer

-3 bytes, thanks to xnor


Verify Cyclic Difference Sets A cyclic difference set is a set of positive integers with a unique property:

Let n be the largest integer in the set.
Let r be any integer (not necessarily in the set) greater than 0 but less than or equal to n/2.
Let k be the number of solutions to (b - a) % n = r where a and b are any members of the set.  Each solution is an ordered pair (a,b).  (Also note that this version of modulo makes negative numbers positive by adding n to it, unlike the implementations in many languages.)
Finally, if and only if this is a cyclic difference set, the value of k does not depend on your choice of r.  That is, all values of r give the same number of solutions to the above congruence.

This can be illustrated with the following example:

Cyclic difference set: {4,5,6,8,9,11}
0 < r <= 11/2, so r = 1,2,3,4,5
r=1: (4,5) (5,6) (8,9)
r=2: (4,6) (6,8) (9,11)
r=3: (5,8) (6,9) (8,11)
r=4: (4,8) (5,9) (11,4)  since (4-11)%11=(-7)%11=4
r=5: (4,9) (6,11) (11,5)

Each value of r has the same number of solutions, 3 in this case, so this is a cyclic difference set.

Input

Input will be a list of positive integers.  Since this is a set property,  assume that input is not sorted.  You can assume that n is at least 2, although k may be zero.

Output

Your program/function should output a truthy value if the set is a cyclic difference set, or a falsey value otherwise.

Test Cases

Valid cyclic difference sets:

10,12,17,18,21
7,5,4
57,1,5,7,17,35,38,49
1,24,35,38,40,53,86,108,114,118,135,144,185,210,254,266,273
16,3,19,4,8,10,15,5,6
8,23,11,12,15,2,3,5,7,17,1

(data source, although their convention is different)

Invalid cyclic difference sets:

1,2,3,4,20
57,3,5,7,17,35,38,49
3,4,5,9
14,10,8

Jelly, 14 7 bytes

_þ%ṀṬSE

Try it online!

How it works

_þ%ṀṬSE  Main link. Argument: A (array of unique elements / ordered set)

_þ       Subtract table; yield a 2D array of all possible differences of two
         (not necessarily distinct) elements of A.
  %Ṁ     Take the differences modulo max(A).
    Ṭ    Untruth; map each array of differences modulo max(A) to a Boolean array
         with 1's at the specified indices. Note that all 0's in the index array
         are ignored, since indexing is 1-based in Jelly.
     S   Take the sum of these arrays, counting occurrences.
      E  Test if all resulting counts are equal.


Close(st) Binary Boxes Challenge:
Given a list of non-negative integers, determine by how much you should increase each item to create the closest binary box with the resulting integer-list.
What is a binary box?
A binary box is where the first and last rows consists of 1-bits; the first and last columns consist of 1-bits; and everything else (if applicable) consists of 0-bits. Some examples of binary boxes, with their corresponding integer-list below it:
                                             111
              1111                           101                           1111111
      111     1001        11      11111      101                           1000001
11    101     1001        11      10001      101         1111111           1000001
11    111     1111        11      11111      111         1111111   1   11  1111111

[3,3] [7,5,7] [15,9,9,15] [3,3,3] [31,17,31] [7,5,5,5,7] [255,255] [1] [3] [127,65,65,127]

Example I/O:

If the input is [0,2], the output would be [3,1], because [3,3] is the closest binary box to reach by increasing numbers: [0+3,2+1].
If the input is [3,4,1], the output would be [4,1,6], because [7,5,7] is the closest binary box to reach by increasing numbers: [3+4,4+1,1+6].
If the input is [2], the output would be [1], because [3] is the closest binary box to reach by increasing numbers: [2+1].

Challenge rules:

The goal is to find the closest binary box. If the input is [1,2,3] the output should be [2,1,0]; so [62,31,60] wouldn't be allowed as output, even though it does form a binary box as well.
I/O can be taken in any reasonable format. Can be a list/array/stream of integers; read one by one from STDIN; etc. You are not allowed to take the input-integers as binary-strings.
The input-integers are guaranteed to be non-negative; and the output-integers may not be negative.
If the input is already a binary-box of itself, you can choose to output a corresponding list of 0s, or the result for the next binary-box in line. I.e. input [3,3,3] may result in both [0,0,0] or [4,2,4].

The first/last rows of the binary-boxes with binary 111...111 form the OEIS sequences A000042 (literal) and A000225: \$a(n)=2^n-1\$ (as base-10 integers).
The middle rows of the binary-boxes with binary 100...001 form the OEIS sequences A000533 (literal) and A083318: \$a(n)=2^n+1\$ (as base-10 integers).
General rules:

This is code-golf, so shortest answer in bytes wins.
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.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code (i.e. TIO).
Also, adding an explanation for your answer is highly recommended.

Test cases:
Input:  [0,2]
Output: [3,1]

Input:  [3,4,1]
Output: [4,1,6]

Input:  [2]
Output: [1]

Input:  [3,3,3]
Output: [0,0,0] OR [4,2,4]

Input:  [1,27,40]
Output: [62,6,23]

Input:  [7,20,6,44,14]
Output: [120,45,59,21,113]

Input:  [7,20,6,33,14]
Output: [56,13,27,0,49]

Input:  [7,2,6,3,14]
Output: [8,7,3,6,1]

Input:  [1,0,1]
Output: [0,1,0]

Input:  [1,2,3]
Output: [2,1,0]

Input:  [0]
Output: [1]

Input:  [6,6,6]
Output: [9,3,9]

APL (Dyalog Extended), 47 46 48 bytes

{x←0⋄⍵{x≡|x⊢←⍺-⍨⊥(1@1)∘⌽∘⍉⍣4⊢0×⍵:x⋄⍺∇⍵⍪0}⊤⍵+~×⍵}

Try it online!
A dfn which takes a vector as its right argument.
Outputs a list of 0's if the input is already a binary-box.
+2 bytes after a fix.(Thanks, Arnauld)
Explanation
{x←0⋄⍵{x≡|x⊢←⍺-⍨⊥(1@1)∘⌽∘⍉⍣4⊢0×⍵:x⋄⍺∇⍵⍪0}⊤⍵+~×⍵}
 x←0                                             set var x to 0(required for extended)
      {x≡|x⊢←⍺-⍨⊥(1@1)∘⌽∘⍉⍣4⊢0×⍵:x⋄⍺∇⍵⍪0}        call the following recursive function with
                                          ⍵+~×⍵  add !(signum(input)) to itself
                                                 (special casing for [0])
                                         ⊤       converted to binary matrix
     ⍵                                           and the input list as right arg
                                :                If:
                             0×⍵                 the matrix converted to zeroes
                 (1@1)∘⌽∘⍉⍣4⊢                    with 1s added on each side
                ⊥                                convert from binary
             ⍺-⍨                                 subtract from the input
          x⊢←                                    assign to x
       x≡|                                       if x matches its absolute value
                                 x               then return x
                                  ⋄⍺∇⍵⍪0         otherwise add a row of zeroes, and try again


Draw an ASCII-art rainbow Draw an ASCII-art rainbow!
Input
An integer between 0 and 1000, inclusive.
Examples
Input 0:

/\
||

Input 1:
 _
/ \
| |

Input 2:
 __
/  \
|  |

Input 3:
 ___
/   \
|   |

The first row is a space followed by n underscores.
The second row is a slash followed by n spaces, and a backslash.
The third row is a pipe followed by n spaces, and a pipe.
Trailing spaces are allowed.
This is code-golf. Shortest code wins.

i386 (16-bit mode) Bootsector, 512 bytes
All i386 bootsectors have to be 512 bytes, so... Without the padding required by i386, it is 137 bytes. Since I can't easily post a TIO link, here's a screenshot of it running:

This code registers the BIOS interrupt int 0x69 to take the number in the bx register and use it as input. Thus, doing
mov bx, 3
int 0x69

is equivalent to the last test case. The disassembled, Intel-syntax source is:
[org 0x7c00]

xor ax, ax
mov es, ax
cli
mov dx, interrupt
mov [es:0x69*4], dx
mov ax, cs
mov [es:0x69*4+2], ax
sti

xor bx, bx
int 0x69
call newline
mov bx, 1
int 0x69
call newline
mov bx, 2
int 0x69
call newline
mov bx, 3
int 0x69
cli
hlt

interrupt:
or bx, bx
jz special
push bx
mov ax, 0x0e20
int 0x10
mov al, '_'
.loop1:
int 0x10
dec bx
jnz .loop1
call newline
mov al, '/'
int 0x10
mov al, ' '
pop bx
push bx
.loop2:
int 0x10
dec bx
jnz .loop2
mov al, '\'
int 0x10
call newline
mov al, '|'
int 0x10
pop bx
mov al, ' '
.loop3:
int 0x10
dec bx
jnz .loop3
mov al, '|'
int 0x10
iret

newline:
mov ax, 0x0e0d
int 0x10
mov al, 0x0a
int 0x10
ret

special:
mov si, s
mov ah, 0x0e
.sloop:
lodsb
int 0x10
or al, al
jnz .sloop
iret

s: db '/', '\', 10, 13, '|', '|'

times 510-($-$$) db 0
dw 0xaa55

(Bit verbose, I know, but hey, it's assembly.)


How many contiguous "strings" can you find in a set of strings? Consider the set of 16-character strings containing only the 95 printable ASCII characters. There are 9516 ≈ 4.4×1031 such strings.

Imagine these strings are put into a list and sorted lexicographically (which is the way most languages will sort a list of strings). What is the largest contiguous slice of this list you can find such that every string is a valid program in your programming language of choice whose output is the sole word string?

All output should go to the same place for all programs; use stdout or a similar alternative.
An optional trailing newline may be a part of the output, but otherwise nothing besides string should be printed for any of your 16-character programs. There is no input and all programs should run without erroring. The program does not have to terminate.

The list of length 16 strings does not "loop-around" from ~~~~~~~~~~~~~~~~ to                  (16 spaces).

Give your starting string and ending string and explain why every program-string that's in between them lexicographically outputs string.

The submission with the largest slice wins.

///, 6634204313747905 > 958

From

string/.~~~~~/0

to

string/0     /.~

This relies on the program not being required to terminate. I started from a core-range of 958 much like the other solutions, from

string//

to

string//~~~~~~~~

However, in this case, // is not a comment. In /// everything that's not a slash is just printed (hence this always prints string before doing anything else). A slash then starts a substitution pattern of the form /pattern/replacement/. If only one or two / are found, then the program simply terminates. However, the above range obviously also includes strings with three or more slashes. The trick here is that the pattern to be searched for is empty, and substitutions are performed iteratively until the pattern cannot be found any more. Since the empty string can always be found, this substitution never terminates, and hence the program never gets around to print anything after the initial string.

But since this doesn't rely on // being a comment, we can actually go a bit further! E.g. the previous and next string around this range, respectively, are:

string/.~~~~~~~~
string/0

These still don't contain a full substitution instruction so they also only print string and then terminate. Let's see how far we can go! I'll focus on the upper end of the range (the lower end works analogously). What if we get another /? The first time this happens is

string/0       /

But that's still not a valid replacement pattern, so all is well. It looks like we need three slashes to break the magic. The first time we get three slashes is at

string/0      //

What now? Well, the pattern to be searched for is 0 (and a bunch of spaces), to be replaced with an empty string. That pattern is never found, so the substitution completes immediately. But luckily, there is nothing to print afterwards in the source code, so the result is still only string. Neat. :)

So we need a valid substitution instruction and more source code afterwards to not print string:

string/0     //

And this is indeed the first code that doesn't work to spec, as it prints string followed by a space. So the last code that works is

string/0     /.~

We can apply the same argument to the beginning of the range, the last failing code being

string/.~~~~~//~

such that the first code that works is

string/.~~~~~/0


Output the HTML colors The 16-color CGA palette (also known as the HTML colors) is a set of 16 colors used by early graphics adapters. The goal of this challenge is to output all 16 of them, in hex format (RRGGBB), in ascending order by hex value, separated by newlines. Thus, the output should be exactly this:

000000
000080
0000FF
008000
008080
00FF00
00FFFF
800000
800080
808000
808080
C0C0C0
FF0000
FF00FF
FFFF00
FFFFFF

A single trailing newline is allowed, but not required.

Jelly, 31 29 27 bytes

“×Ɗ¡‘ŒP»Ṫ¦209ṗ€3Fd⁴ịØHs3ṢQY

Try it online!

How it works

“×Ɗ¡‘ yield the code points of the characters between the quotes in Jelly's SBCS, which are 0x11 = 17, 0x91 = 145, and 0x00 = 0.

ŒP constructs the powerset of the array of code points, yielding

[[], [17], [145], [0], [17, 145], [17, 0], [145, 0], [17, 145, 0]]

The last two entries correspond to combinations that contain both 80 and FF, so we have to discard them.

»Ṫ¦209 consists of three parts:

Ṫ (tail) removes the last array of code points, i.e., [17, 145, 0].
»209 takes the maximum of each integer in the remainder of the powerset and 0xD1 = 209, replacing all of them with 209.
¦ (sparse) iterates over the elements of the remainder of the powerset. If the corresponding index is found in [17, 145, 0], the element is replaced with all 209's. If not, it is left untouched.

¦ isn't modular, so this modifies only the last array (index 0) in the remainder of the powerset. The indices 17 and 145 are too large and have no effect.

The result is as follows.

[[], [17], [145], [0], [17, 145], [17, 0], [209, 209]]

ṗ€3 computes the third Cartesian power of each array, i.e., the array of all 3-tuples of elements of each array.

Fd⁴ flattens the result and computes quotient and remainder of each integer divided by 16.

ịØH indexes (1-based) into "0123456789ABCDEF, so 0x11, 0x91, 0x00, and 0xD1 get mapped to "00", "80", "FF", and "C0" (resp.).

s3ṢQ splits the character pairs into 3-tuples, sorts the tuples, and deduplicates.

Finally, Y joins the unique tuples, separating by linefeeds.


Number of distinct tilings of an n X n square with free n-polyominoes The newest "nice" OEIS sequence, A328020, was just published a few minutes ago.

Number of distinct tilings of an n X n square with free n-polyominoes.

This sequence counts tilings up to symmetries of the square. The sequence has six terms, but I'd like to see if folks here can extend it further.
Example
For n=4 there are 22 such grids, as shown in this image from the OEIS.

Credit: Jeff Bowermaster, Illustration of A328020(4).
Challenge
Like this previous challenge, the goal of this challenge is to compute as many terms as possible in this sequence, which begins 1, 1, 2, 22, 515, 56734 and where the n-th term is the number of tilings of the n X n grid with n-polyominoes.
Run your code for as long as you'd like. The winner of this challenge will be the user who posts the most terms of the sequence, along with their code to generate it. If two users post the same number of terms, then whoever posts their last term earliest wins.

C, 7 terms

The seventh term is 19846102. (The first six are 1, 1, 2, 22, 515, 56734, as stated in the question).

#include <stdio.h>
#include <string.h>
#include <stdint.h>

#define N 7
#define ctz __builtin_ctzl

typedef uint64_t u64;

static u64 board[N*N] = { 0 };
static u64 adjacency_matrix[N*N] = { 0 };
static u64 count = 0;

static u64 check_symmetry()
{
    static const u64 symmetries[7][3] = {
        { 0,     +N, +1 },
        { N-1,   -1, +N },
        { N-1,   +N, -1 },
        { N*N-1, -1, -N },
        { N*N-1, -N, -1 },
        { N*N-N, +1, -N },
        { N*N-N, -N, +1 },
    };

    int order[N];

    for (u64 i = 0; i < 7; ++i) {
        u64 start = symmetries[i][0];
        u64 dcol = symmetries[i][1];
        u64 drow = symmetries[i][2];
        memset(order, 0xFF, N*sizeof(int));

        for (u64 row = 0, col = 0; col < N || (col = 0, ++row < N); ++col) {
            u64 base = board[col + N*row];
            u64 symmetry = board[start + dcol*col + drow*row];
            u64 lex = 0;

            while (order[lex] != symmetry && order[lex] != -1)
                ++lex;
            order[lex] = symmetry;

            if (lex < base)
                return 0;

            if (base < lex)
                break;
        }
    }

    return 1;
}

static void recurse(u64 mino, u64 cell, u64 occupied, u64 adjacent, u64 forbidden)
{
    if (cell >= N) {
        ++mino;

        if (mino == N) {
            count += check_symmetry();
            return;
        }

        u64 next = ctz(~occupied);
        board[next] = mino;
        recurse(mino, 1, occupied | 1ul << next, adjacency_matrix[next], 0);
        return;
    }

    adjacent &= ~occupied & ~forbidden;
    while (adjacent) {
        u64 next = ctz(adjacent);
        adjacent &= ~(1ul << next);
        forbidden |= 1ul << next;
        board[next] = mino;
        recurse(mino, cell + 1, occupied | 1ul << next, adjacent | adjacency_matrix[next], forbidden);
    }
}

int main(void)
{
    for (u64 i = 0; i < N*N; ++i) {
        if (i % N)
            adjacency_matrix[i] |= 1ul << (i - 1);
        if (i / N)
            adjacency_matrix[i] |= 1ul << (i - N);
        if (i % N != N - 1)
            adjacency_matrix[i] |= 1ul << (i + 1);
        if (i / N != N - 1)
            adjacency_matrix[i] |= 1ul << (i + N);
    }

    recurse(0, 2, 3, 4 | 3 << N, 0);
    printf("%ld\n", count);
}

Try it online! (for N=6, since N=7 would time out.)

On my machine, N=6 took 0.171s, and N=7 took 2m23s. N=8 would take a few weeks.


Output a googol copies of a string I am interested in seeing programs which don't ask for any input, print a googol copies of some nonempty string, no less, no more, and then stop. A googol is defined as \$10^{100}\$, i.e., 1 followed by a hundred 0's in decimal.
Example output:
111111111111111111111111111111111111111111111111111111111111111111111111...

or
Hello world
Hello world
Hello world
Hello world
Hello world
Hello world
...

The string can also be entirely composed of white space or special symbols. The only exception to identical copies of a fixed string is if your language decorates the output in some way that can not be prevented, but could be trivially undone in a wrapper script, like prepending a line number to each line. The wrapper script in such cases need not be provided.
You can assume your computer will never run out of time, but other than that, your program must have a reasonable demand of resources. Also, you must respect any restrictions that the programming language of your choice poses, for example, you can not exceed a maximum value allowed for its integer types, and at no point more than 4 GB of memory must be needed.
In other words, the program should in principle be testable by running it on your computer. But because of the extent of this number you will be expected to prove that the number of copies of the string it outputs is exactly 10^100 and that the program stops afterwards. Stopping can be exiting or halting or even terminating due to an error, but if so, the error must not produce any output that could not easily be separated from the program's output.
This is code-golf,  so the solution with the fewest bytes wins.
Example solution (C, ungolfed, 3768 bytes)
#include <stdio.h>

int main() {
  int a00, a01, a02, a03, ..., a99;
  for(a00 = 0; a00 < 10; a00++)
  for(a01 = 0; a01 < 10; a01++)
  for(a02 = 0; a02 < 10; a02++)
  for(a03 = 0; a03 < 10; a03++)
  ...
  for(a99 = 0; a99 < 10; a99++)
    puts("1");
  return 0;
}

Fuzzy Octo Guacamole, 13 12 11 10 bytes
9+ddpp![g]

Explanation:
9+ddpp![g]
9+           # push 9 and increment, giving 10
  dd         # duplicate, twice. now you have [10,10,10]
    pp       # raise a 10 to the 10th power, then raise that to the 10th again. That ends up being 10^100.
      ![ ]   # for loop, `!` sets the counter to the top of stack
        g    # prints an ASCII art goat.

Sample of the goat printed:
                  ___.
                 //  \\
                ((   ""
                 \\__,
                /6 (%)\,
               (__/:";,;\--____----_
                ;; :";,:";`;,";,;";`,`_
                  ;:,;;";";,;":,";";,-Y\
                   ;,;,;";";,;":;";"; Z/
                   / ;,";";,;";,;";;"
                  / / |";/~~~~~\";;"
                 ( K  | |      || |
                  \_\ | |      || |
                   \Z | |      || |
                      L_|      LL_|
                      LW/      LLW/


Calculate \$ \lfloor n \log_2(n) \rfloor \$, exactly Given an integer \$ n \ge 2 \$, you need to calculate \$ \lfloor n \log_2(n) \rfloor \$, assuming all integers in your language are unbounded.
However, you may not ignore floating-point errors - for example, in python lambda n:int(n*math.log2(n)) is an invalid solution, because for example for n=10**15, int(n*math.log2(n)) is 49828921423310432, while the actual answer is 49828921423310435.
Rules

You can assume the input is an integer \$ n \ge 2 \$
You may use any reasonable I/O method
Standard loopholes are disallowed

Test cases
2 -> 2
3 -> 4
4 -> 8
5 -> 11
6 -> 15
7 -> 19
8 -> 24
9 -> 28
10 -> 33
100 -> 664
1000 -> 9965
10000 -> 132877

10 brownie points for beating my 4 byte 05AB1E answer.
This is code golf, so the shortest answer wins. Good luck!

Python 3, 25 bytes

lambda n:len(bin(n**n))-3

Try it online!
If the answer is \$x\$, then \$x+1 > n\log{n} \ge x\$ holds true, which means \$2^{x+1} > n^n \ge 2^x\$. So we can simply count the number of bits in the binary representation of \$n^n\$.


Draw an ASCII key signature Given an input of a note, output an ASCII drawing of the corresponding major
key on the treble clef.

Here are all the major keys (that don't include double-sharps or double-flats)
and their corresponding key signatures:

Circle of fifths deluxe 4 by Wikipedia user Just plain Bill, copyright CC BY-SA 3.0

If the input is a key with sharps, draw the following ASCII art with the
appropriate number of sharps:

   #
-#-------
      #
----#----
  #
-------#-
     #
---------

---------

And if the input is a key with flats:

---------
  b
----b----
      b
-b-------
   b
-----b---
       b
---------

Here is a concise summary of the possible inputs as well as how many sharps or
flats they use:

   0   1   2   3   4   5   6   7
#  C   G   D   A   E   B   F#  C#
b  C   F   Bb  Eb  Ab  Db  Gb  Cb

All five lines of dashes must always be drawn, but there may be any number of
dashes per line such that the sharps or flats have at least one column of
padding on each side, as long as each line of dashes has the same length. For
example, these are all also acceptable outputs for the input Ab:

---------   ------   ---------   ----------------
  b           b           b          b
----b----   ----b-   -------b-   ------b---------

-b-------   -b----   ----b----   ---b------------
   b           b           b          b
---------   ------   ---------   ----------------

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

In the case of C major, which has no sharps nor flats, any positive number of dashes per
line (even one) is acceptable.

Any amount of leading or trailing whitespace is fine, as are trailing spaces on
each line. Extra leading spaces are okay as long as there are the same number
on each line.

You may take input in lowercase or require that inputs without a sharp or flat contain a trailing space, if you so desire.

Since this is code-golf, the shortest solution in bytes will win.

Python 2, 206 197 178 175 168 161 bytes

Thanks to Mr. Xcoder for -12 bytes!

This is a function which returns the result as a 2D list of characters. If the input does not contain a sharp/flat, it should be padded with a space.

def f(k,r=range(10)):n="CGDAEB".find(k[0])+7*' #'.find(k[1]);return[[(' -'[i%2],'b#'[n>0])[0<j<=abs(n)and`i`==(n*"1403625"+"5263748")[j-1]]for j in r]for i in r]

Try it online!


Drawing convex polyiamonds Description
OEIS sequence A096004 gives the

Number of convex triangular polyominoes [polyiamonds] containing n cells.

It begins:
1, 1, 1, 2, 1, 2, 2, 3, 2, 2, 2, 3, 2, 3, 3, 5

For example, a(8)=3 with the following three convex polyiamonds:
Input: 8
Output:
  *---*---*---*---*
 / \ / \ / \ / \ /
*---*---*---*---*

    *---*---*
   / \ / \ /
  *---*---*
 / \ / \ /
*---*---*

    *---*
   / \ / \
  *---*---*
 / \ / \ / \
*---*---*---*

Requirements
The goal of this challenge is to write a program that takes in an integer n (in any reasonable format) and outputs ASCII art of all convex polyiamonds with n cells (in any orientation), with each polyiamond separated by two newlines.
Your program must be able to handle up to a(30) in under 60 seconds.

Scoring
This is a code-golf challenge, so fewest bytes wins.

Ruby, 202 bytes

->n{(r=[*0..n]).product(r,r,r).map{|i|p,b,c,d=i;b>c||c>d||b+c+d>p||p*p-b*b-c*c-d*d!=n||0.upto(p-d<<1){|j|s=" "*j+"*---\\ / "[j%2*4,4]*p*2;(k=b*4-j)>0&&s[0,k]=" "*k;puts s[0,[p*4+1-j,p*4+1-c*4+j].min]}}}

Try it online!

Uses formula per the OEIS sequence: search for solutions where n = p**2 - b**2 -c**2 - d**2.

n =the number of triangular tiles

p =the side length of a large equilateral triangle (pointing downwards)

b,c,d =the side length of three smaller equilateral triangles, which are removed from the corners of the large equilateral triangle to get the required shape.

Some additional conditions (per OEIS) are needed to avoid duplicates:
b<=c<=d and b+c+d<=p


Random subset generator Randomly choose one out of k-length, ordered subset of characters in a string, while only storing a limited number of characters. The subset must be chosen with equal probability and may contain repeated characters. Do this without generating all possible permutations and assume k is at most the length of the string. For example, the string daddy has 7 subsets of length two: da, dd, dy, ad, ay, yd, ya. The function should return any one of them with the probability of 1/7.

Pyth - 5 bytes
While we're arguing about the nomenclature, I'm just guessing at the rules based on the example to just mean pick one from all unique permutations of length n of the string.
O{.PF

Try it online here.


What is the reverse (binary) bit number? So you are given a POSITIVE base 10 (decimal) number. Your job is to reverse the binary digits and return that base 10 number.

Examples:

1 => 1 (1 => 1)
2 => 1 (10 => 01)
3 => 3 (11 => 11)
4 => 1 (100 => 001)
5 => 5 (101 => 101)
6 => 3 (110 => 011)
7 => 7 (111 => 111)
8 => 1 (1000 => 0001)
9 => 9 (1001 => 1001)
10 => 5 (1010 => 0101)

This is a code-golf challenge, so the solution that uses the least bytes wins.

This is A030101 in the OEIS.

Python, 29 bytes

lambda n:int(bin(n)[:1:-1],2)

Try it online!

This is an anonymous, unnamed function which returns the result.

First, bin(n) converts the argument to a binary string. We would ordinarily reverse this with the slice notation [::-1]. This reads the string with a step of -1, i.e. backwards. However, binary strings in Python are prefixed with an 0b, and therefore we give the slicing's second argument as 1, telling Python to read backwards terminating at index 1, thus not reading indexes 1 and 0.

Now that we have the backwards binary string, we pass it to int(...) with the second argument as 2. This reads the string as a base 2 integer, which is then implicity returned by the lambda expression.


Is it a strong word? They say that hate is a strong word. I wanted to find out why, so I had a good look at the word.

I noticed that every consonant had a vowel after it. That made it look quite strong to me, so I decided that that's what makes a word strong.

I want to find more strong words, so I'll need a program for it!

Finding strong words

Strong words are words where every consonant (letters in the set BCDFGHJKLMNPQRSTVWXZ) is followed by a vowel (letters in the set AEIOUY). That's it. Nothing else matters.

If the word starts with a vowel, you don't have to worry about any of the letters before the first consonant. If the word has no consonants in it at all, it's automatically a strong word!

Some examples of strong words are agate, hate and you. agate is still a strong word because although it starts with a vowel, every consonant is still followed by a vowel. you is a strong word because it has no consonants.

There is no restriction on length for strong words.

The challenge

Write a program or function that takes a non-empty string as input, and outputs a truthy value if it is a strong word or a falsy value if it is not.

Clarifications

You may decide to take the input in either lowercase or uppercase. Specify which in your answer.
Words will not contain punctuation of any kind. They will only contain plain letters in the set ABCDEFGHIJKLMNOPQRSTUVWXYZ.
Instead of truthy and falsy values, you may choose two distinct and consistent values to return for true and false. If you do this, specify the values you have picked in your answer.

You may alternatively output a falsy value for a strong word and a truthy one for a non-strong word.

Test cases

Input      -> Output
hate       -> true
love       -> true
popularize -> true
academy    -> true
you        -> true
mouse      -> true
acorn      -> false
nut        -> false
ah         -> false
strong     -> false
false      -> false
parakeet   -> false

Scoring

Since this is code-golf, the answer with the least bytes wins!

JavaScript (ES6), 36 28 27 bytes

Saved 1 byte by inverting the result, as suggested by LarsW

Takes input in lowercase. Returns false for a strong word and true for a non-strong word.

s=>/[^aeiouy]{2}/.test(s+0)

How?

We append a 0 (non-vowel) at the end of the input string and look for two consecutive non-vowel characters. This allows us to cover both cases that make a word not strong:

it contains two consecutive consonants
or it ends with a consonant

Test cases

let f =

s=>/[^aeiouy]{2}/.test(s+0)

;[
  "hate", "love", "popularize", "academy", "you", "mouse", "a", "euouae",
  "acorn", "nut", "ah", "strong", "false", "parakeet"
]
.forEach(s => console.log(s + ' --> ' + f(s)))


Missy Elliot, XKCD and ASCII Bytes Inspired by the following XKCD comic:

In Missy Elliot's "Work It", part of the chorus goes as follows:

Is it worth it, let me work it

I put my thing down, flip it and reverse it

Bearing that in mind, I propose the following code golf challenge:

Create code that does, in order:

Takes 8-bit ASCII input from STDIN; e.g n (Hex 6E, or Bin
01101110)
Shifts each byte's 8 bits down 1 bit level (I believe it's called a
bitwise shift down), e.g 01101110 becomes 00110111 ("put my
thing down");
Inverts each byte's bits, e.g 00110111 becomes 11001000 ("flip
it");
Reverses the bits for each byte, e.g 11001000 becomes 00010011
("reverse it");
If a byte's value is less than 32, then perform (95 + [byte value]),
or in other words, (126-(31-[byte value])), on the byte before
converting back to ASCII... If the byte value is still less than 32, repeat step 5
If a byte's value is greater than 126, then perform ([byte value] - 95), or in other words, (32+([byte value]-127)), on the byte before
converting back to ASCII... IF the value is still greater than 126, repeat step 6.
Display the newly converted string as ASCII.

An example of this code in action:

(The input, is it worth it?)

workit missy ("missy" being the input, "workit" is the function)

Now behind the scenes...

(let me work it... Into binary)

01101101 01101001 01110011 01110011 01111001

(Put my thing down... Bitwise)

00110110 00110100 00111001 00111001 00111100

(...Flip it...)

11001001 11001011 11000110 11000110 11000011

(... And reverse it!)

10010011 11010011 01100011 01100011 11000011

(Converted back to Decimal)

147 211 99 99 195

(Perform the necessary math)

147-95 211-95 99 99 195-95 => 52 116 99 99 100

(Convert back to ASCII and display, the output)

4tccd

Rules

Shortest code wins... simple as that...
Input can be via function, by prompt or whatever works for you, so long as you can make Rule 1 "work it" for you... ;)
I am not after reversibility, so long as you can make the code do what I have asked it to do, I'll be happy...

Best of luck!

APL  50  45

⎕UCS n+95×¯1++⌿126 31∘.≥n←2⊥⊖~(8/2)⊤⌊.5×⎕UCS⍞

Takes input on the keyboard, e.g.:

      ⎕UCS n+95×¯1++⌿126 31∘.≥n←2⊥⊖~(8/2)⊤⌊.5×⎕UCS⍞
missy
4tccd


Add a feature to a programming language Your task is to tack on a feature to a programming language, either by implementing a very clever library, or by processing the input text and/or tweaking the compilation process.

Ideas:

Add PHP-style presentation interleaving to C (e.g. <?c printf("Hello,"); ?> world!).
Add a null coalescing operator to one of those languages that isn't C#.
Add macros to PHP.
Add goto to JavaScript.
Add pattern matching to language X.
Add namespace support to a language that doesn't have it.
Make C look like PHP.
Make Haskell look like Pascal.
... (feel free to post ideas in the comment section)

Rules:

Bring something to the table.  Don't just say "Template Haskell" to add metaprogramming facilities to Haskell.  This isn't StackOverflow.
The entire implementation should fit in one screenful (not counting the example).
Do not host code on an external site specifically for this task.
The most impressive or surprising feature wins.

Don't worry about implementing the feature 100% correctly.  Far from it!  The main challenge is figuring out what you want to do and viciously cutting away details until your planned undertaking becomes feasible.

Example:

Add a lambda operator to the C programming language.

Initial approach:

  Okay, I know I'd want to use libgc so my lambdas will solve the upward and downward funarg problems.  I guess the first thing I'd need to do is write/find a parser for the C programming language, then I'd need to learn all about C's type system.  I'd have to figure out how to make sense of it as far as types go.  Would I need to implement type inference, or should I simply require that the formal parameter be typed as given?  What about all those crazy features in C I don't know about yet?

It's quite clear that implementing lambda in C correctly would be a huge undertaking.  Forget about correctness!  Simplify, simplify.

Better:

  Screw upward funargs, who needs 'em?  I might be able to do something tricky with GNU C's nested functions and statement expressions.  I wanted to show off an amazing syntactic transformation on C with terse, hacky code, but I won't even need a parser for this.  That can wait for another day.

Result (requires GCC):

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

#define lambda(d,e)({d;typeof(e)f(d){return(e);};f;})

#define map(F,A)({typeof(F)f=(F);typeof(*(A))*a=(A);({int i,l=((int*)(a))[-1]; \
typeof(f(*a))*r=(void*)((char*)malloc(sizeof(int)+l*sizeof(*r))+sizeof(int));  \
((int*)r)[-1]=l;for(i=0;i<l;i++)r[i]=f(a[i]);r;});})

#define convert_to(T) lambda(T x, x)
#define print(T, fmt) lambda(T x, printf(fmt "\n", x))

int main(void)
{
    int *array = 1 + (int[]){10, 1,2,3,4,5,6,7,8,9,10};
    map(print(int, "%d"), array);

    double *array2 = map(lambda(int x, (double)x * 0.5), array);
    map(print(double, "%.1f"), array2);

    long *array3 = map(convert_to(long), array2);
    map(print(long, "%ld"), array3);

    long product = 1;
    map(lambda(int x, product *= x), array);
    printf("product: %ld\n", product);

    return 0;
}

That was easy, wasn't it?  I even threw in a map macro to make it useful and pretty.

OOP syntax in Haskell

import Prelude hiding ((.))
a . b = b a

Objects can have properties:

[1,5,3,2].length -- 4
[1,5,3,2].maximum -- 5
'a'.succ -- 'b'

...and methods:

"Hello world!".take(5) -- "Hello"
"Hello world!".splitAt(2) -- ("He","llo world!")
"Hello world!".map(toUpper) -- "HELLO WORLD!"


How many Jimmys can fit? In this simple but fun challenge, you were asked to determine if Jimmy would fall of their platform.  Jimmy has three body parts /, o, and \ arranged like this

/o\

Platforms are represented with -.  Jimmy will fall off their platform iff they have two or more body parts that are not directly above a platform.

Some examples:

   /o\
- -------

Jimmy will balance since all their body parts are above a -.

   /o\
    ------   ---

Jimmy will balanced since two body parts are above -s.

 /o\
-- ----  --

Jimmy will balance even though they are split between two platforms

  /o\
   -

Jimmy will not balanced since two body parts are not above a platform.

Your task is to write a program that takes a platform as a lengthed container containing only -s and s (e.g. a string) and outputs the number of Jimmys that can be placed on the platform such that none of them will fall and none of them will overlap.  A Jimmy may have one of their body parts to the left of the beginning of the string or the right of the end of the string.

This is code-golf so answers are scored in bytes with fewer bytes being the aim.

Test cases

Inputs

-  -  -

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

Respective outputs

0
0
1
1
2
2
2
3

JavaScript (ES6),  45 41  40 bytes
Saved 4 bytes thanks to @Shaggy

s=>(0+s+0).split(/.--|-.-|--./).length-1

Try it online!


Pascal's Triangle (Sort of) Most everyone here is familiar with Pascal's Triangle. It's formed by successive rows, where each element is the sum of its two upper-left and upper-right neighbors. Here are the first 5 rows (borrowed from Generate Pascal's triangle):

    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1
  . . .

Collapse these rows to the left

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
. . .

Sort them in ascending order

1
1 1
1 1 2
1 1 3 3
1 1 4 4 6
. . .

Read this triangle by rows

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

Given an input n, output the nth number in this series. This is OEIS 107430.

Rules

You can choose either 0- or 1-based indexing. Please state which in your submission.
The input and output can be assumed to fit in your language's native integer type.
The input and output can be given by any convenient method.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

JavaScript (ES6), 79 bytes

0-indexed.

f=(n,a=[L=1])=>a[n]||f(n-L,[...a.map((v,i)=>k=(x=v)+~~a[i-1-i%2]),L++&1?k:2*x])

Demo

f=(n,a=[L=1])=>a[n]||f(n-L,[...a.map((v,i)=>k=(x=v)+~~a[i-1-i%2]),L++&1?k:2*x])

console.log([...Array(79).keys()].map(n => f(n)).join(', '))

How?

f = (                       // f = recursive function taking:
  n,                        //   n = target index
  a = [L = 1]               //   a[] = current row, L = length of current row
) =>                        //
  a[n] ||                   // if a[n] exists, stop recursion and return it
  f(                        // otherwise, do a recursive call to f() with:
    n - L,                  //   n minus the length of the current row
    [                       //   an array consisting of:
      ...a.map((v, i) =>    //     replace each entry v at position i in a[] with:
        k =                 //       a new entry k defined as:
        (x = v) +           //       v +
        ~~a[i - 1 - i % 2]  //       either the last or penultimate entry
      ),                    //     end of map()
      L++ & 1 ?             //     increment L; if L was odd:
        k                   //       append the last updated entry
      :                     //     else:
        2 * x               //       append twice the last original entry
    ]                       //   end of array update
  )                         // end of recursive call

This algorithm directly generates the sorted rows of Pascal's Triangle. It updates n according to the length of the previous row until a[n] exists. For instance, 6 iterations are required for n = 19:

 L | n  | a[]
---+----+------------------------
 1 | 19 | [ 1 ]
 2 | 18 | [ 1, 1 ]
 3 | 16 | [ 1, 1, 2 ]
 4 | 13 | [ 1, 1, 3, 3 ]
 5 |  9 | [ 1, 1, 4, 4, 6 ]
 6 |  4 | [ 1, 1, 5, 5, 10, 10 ]
                        ^^


Hexagon-In or Hexagon-Out? There is a great story to tell about regular hexagons found for example in honeycombs. But this busy bee needs your help in telling him which point is inside or outside his honeypot. So, given a regular hexagon as pictured below, centered at the origin and with edge size l, determine if a set of coordinates (x,y) are inside, exactly on the edge or outside of my regular hexagon.

Input, output and rules

The rules are:

Input and output methods follow the default rules.
Input consists of three integers: x,y,l.
x and y are of any convenient signed integer format. l is positive (never 0).
Your program must output/return a 1 if the point (x,y) is inside the regular hexagon, -1 if it's outside or 0 if it's exactly on the edge.
This is a code-golf, so shortest code wins. In case of a tie, the earliest post wins.
For output to stdout: leading/trailing spaces or newlines in the output are permitted.
Standard loopholes apply.

Test cases

Here are some test cases:

0,0,1        --> 1
0,1,1        --> -1
0,-1,1       --> -1
1,0,1        --> 0
-1,0,1       --> 0
-1,-1,1      --> -1
1,1,1        --> -1
-2,-3,4      --> 1
32,45,58     --> 1
99,97,155    --> -1
123,135,201  --> 1

JavaScript (ES6) 77 83

(a,b,l,h=Math.sqrt(3)*l,x=a<0?-a:a,y=b<0?-b:b)=>y|x!=l?2*y<h&x/l+y/h<1?1:-1:0

Test

f=(a,b,l,h=Math.sqrt(3)*l,x=a<0?-a:a,y=b<0?-b:b)=>y|x!=l?2*y<h&x/l+y/h<1?1:-1:0

// TEST

function go() {
  C.width=400;C.height=300;
  var l=+I.value, x,y, cols={0:'#ff0',1:'#0f0','-1':'#888'},
  ctx = C.getContext("2d")
  ctx.translate(200,150)
  ctx.strokeStyle='#000'
  ctx.lineWidth=1;
  ctx.beginPath();
  ctx.moveTo(0,-150);ctx.lineTo(0,150);ctx.moveTo(-200,0);ctx.lineTo(200,0);
  ctx.stroke();
  ctx.strokeStyle='#f00'
  ctx.beginPath();
  ctx.moveTo(l*10,0);ctx.lineTo(l*5,l*Math.sqrt(3)*5);ctx.lineTo(-l*5,l*Math.sqrt(3)*5)
  ctx.lineTo(-l*10,0);ctx.lineTo(-l*5,-l*Math.sqrt(3)*5);ctx.lineTo(l*5,-l*Math.sqrt(3)*5)
  ctx.closePath();
  ctx.stroke();

  for(y=-14;y<15;y++)
    for(x=-19;x<20;x++) {
      ctx.beginPath();
      ctx.moveTo(x*10,y*10-3);ctx.lineTo(x*10,y*10+3);
      ctx.moveTo(x*10-3,y*10);ctx.lineTo(x*10+3,y*10);
      ctx.strokeStyle=cols[f(x,y,l)]
      ctx.stroke()
    }
}

go()
#C {
  border: 1px solid #000
}
L <input id=I value=15><button onclick="go()">GO</button>

<canvas id=C width=400 height=300></canvas>


Draw a Fibonacci Network! What are Fibonacci networks?

In 1202, an Italian mathematician known as Fibonacci posed the following problem:
"A male and a female rabbit are born at the beginning of the year. We assume the following conditions:
1.After reaching the age of two months, each pair produces a mixed pair, (one male, one female), and then another mixed pair each month thereafter.
2.No deaths occur during the year."
How many rabbits will there be at the end of the year?

Sources for graph and problem statement
Challenge
Your challenge is to write a program/function to draw an ASCII art to output or a text file, or a graphical picture to a file/screen of a graph with following settings:

At 0th tick, there is one newly-born node.

Every newly born node creates a normal node after one tick after being born and gets deactivated.

A normal node creates a normal node and a newly-born node one tick after its birth and gets deactivated.

Your program will get the non-negative value n as input, and will draw the graph at the nth tick. Note that your program can draw newly-born nodes and normal nodes differently, but this is not necessary.
Rules

You must not use any built-in Fibonacci sequence function or mathematical constants or similar.

If your program outputs to a file, it must be either a text file in a suitable and viewable format and encoding, or an image file in a suitable and viewable format with recognizable colors (for example, an image format that can be uploaded to SE).

Your program can draw graph in any size, any shape and any alignment but the nodes and connections must be recognizable. Tree-shaped graphs (like the graph in "What are Fibonacci networks?" section) are recommended, but not necessary.

Common code golf rules apply to this challenge.

Examples
Input: 2
Possible Output:
*
|
*
| \
* *

Input: 0
Possible Output:
*

Input: 5
Possible Graphical Output:

This is a codegolf. Shortest code wins. Good luck!


Sort a list and write some English! Your boss managed to read the secret hidden message. He didn't end up firing you, though, he just made you a secretary and forbade you from writing code.

But you're a programmer. You need to write code. You must code.

Therefore, your code needs to look as similar to English as possible, make sense, and look as little like code as possible. Your code should take a list of integers (either in a function, or STDIN), and return that list sorted (returning it, or STDOUT).

Any language can be used, but I'm looking for the most creative solution, (kudos if your code looks like a business letter).

This is a popularity contest!

GolfScript

Dear Boss Man.
It came to my attention that my keyboard needs replacement; the keys required  to write the
symbols ~ $ ` . and } are not functioning properly.
It's very difficult to work like this! Please instruct the IT department to exchange the faulty
keyboard as soon as possible.
Sincerely,
Dennis

Try it online!
How it works

 Undefined tokens (e.g., most English words) are noops in GolfScript.

 . ; duplicates the input string and discards the copy.

  ~ $ evaluates the input string and sorts the resulting array.

 ` inspects the array (for pretty printing).

  . and duplicates the output string and discards the copy.

 } is a "super comment" since it is unmatched; everything following it is ignored.


Smallest Multiple to "Palindromize" Goal:
Given any non-zero natural number a, find the smallest non-zero natural
number b such that a•b is palindromic, e.g. it reads the same forwards and backwards. Input a through any reasonable means (STDIN, function argument, etc.), And output b through any reasonable means (STDOUT, function return value.)
Notes:

Input will not always have a solution (multiples of 10), so you must create an error, or display -1/0

Input validation is not necessary, assume a is a natural number.

Standard loopholes apply (Hardcoding, using a language created after this challenge)

Examples:
a=34, b=8 (272)
a=628, b=78 (48984)
a=15, b=35 (525)
a=33, b=1 (33)
a=20, (Error, -1, or 0)

Pyth, 10 9 bytes
&eQf_I`*Q

Try it online.
Explanation
&eQf_I`*QT    Implicitly append T, and take input in Q.
 eQ           Calculate input mod 10.
&             Logical and, only evaluate the following if result ≠ 0.
   f          Starting from 1, find the first integer T for which...
      `       ...the string representation of...
       *QT    ...input multiplied by T...
    _I        ...is equal to its reverse.


How to swap elements in a vector using an anonymous function in Octave? Swapping two elements in a vector/matrix is very simple in Octave:

x='abcde';
x([4,1])=x([1,4])
x =
   dbcae

Unfortunately, I have yet to find a way to do this inside an anonymous function. While the function below is syntactically correct, it only gives back the two elements that are swapped, not the entire x vector:

f=@(x)(x([4,1])=x([1,4]))
f(x)
ans =
     ad

Is there a way to achieve the desired behavior using anonymous functions in a golfy way? Can several elements be swapped this way using an anonymous function?

I could create an indexing vector: f=@(x)x([4,2,3,1,5]), but creating such a vector dynamically will likely take a lot of bytes too.

Argument List
f=@(x,y=x([4 1])=x([1 4]))x;

Try it online!


Find a thumbnail in a mosaic After the last Ludum Dare (LD) game programming contest a friend of mine made a nice mosaic of all the LD game thumbnails:

After searching for my own game I quickly gave up and decided to solve it like a real programmer... by writing code that finds my game thumbnail.

This is the thumbnail of my game:

More examples can be found by going to the Ludum Dare list of games.

So what is the challenge? Write a program that has the following input:

<filename_mosaic> <amount_of_tiles_x> <amount_of_tiles_y> <filename_target>

For example using the images above:

mosaic.jpg 59 43 target.png

The output should be the index of the target image. For the mosaic and screenshot above the correct index is:

48,18

The following (non-golfed) code provides a working example:

public class MosaicFinder {

    //Start with java MosaicFinder mosaic.jpg  59 43 target.png
    public static void main(String[] args)  throws Exception {
        String mosaicFilename = args[0];
        int tilesX = Integer.parseInt(args[1]);
        int tilesY = Integer.parseInt(args[2]);
        String targetFilename = args[3];

        BufferedImage mosaic = ImageIO.read(new File(mosaicFilename));
        int tileHeight = mosaic.getHeight()/tilesY;
        int tileWidth = mosaic.getWidth()/tilesX;

        BufferedImage tofind = ImageIO.read(new File(targetFilename));

        //Translate target.png to correct size:
        BufferedImage matchCanvas = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_INT_RGB);
        AffineTransform at = AffineTransform.getScaleInstance((tileWidth*1.0)/tofind.getWidth(), (tileHeight*1.0)/tofind.getHeight());
        ((Graphics2D)matchCanvas.getGraphics()).drawRenderedImage(tofind, at);

        int bestIndexX = 0, bestIndexY = 0;
        BigInteger lowest = null;
        for(int x = 0; x<tilesX;x++) {
            for(int y = 0; y<tilesY;y++) {
                //For all tiles:
                BigInteger error = BigInteger.ZERO;
                for(int x1 = 0; x1<tileWidth;x1++) {
                    for(int y1 = 0; y1<tileHeight;y1++) {
                        int rgb1 = matchCanvas.getRGB(x1, y1);
                        int rgb2 = mosaic.getRGB((x*tileWidth)+x1, (y*tileHeight)+y1);
                        int r1 = (rgb1 >> 16) & 0xFF;
                        int r2 = (rgb2 >> 16) & 0xFF;
                        error = error.add(BigInteger.valueOf(Math.abs(r1-r2)));

                        int g1 = (rgb1) & 0xFF;
                        int g2 = (rgb2) & 0xFF;
                        error = error.add(BigInteger.valueOf(Math.abs(g1-g2)));

                        int b1 = rgb1 & 0xFF;
                        int b2 = rgb2 & 0xFF;
                        error = error.add(BigInteger.valueOf(Math.abs(b1-b2)));
                    }
                }
                if(lowest == null || lowest.compareTo(error) > 0) {
                    lowest = error;
                    bestIndexX = (x+1);
                    bestIndexY = (y+1);
                }
            }
        }
        System.out.println(bestIndexX+","+bestIndexY);
    }
}

This is a visual example of the code running:

This contest is a code-golf contest, the shortest code wins the challenge.

Update: It seems stackexchange messes up the images a bit, on my blog you can find the source images for the examples in correct resolution.
Also: I've fixed the amount of images from 42 to 43

Current best: David Carraher, Mathematica (280)

Mathematica - 280 247
No need to scale the target to the tile size.  The key is to match the average color for the target and for each tile.  Closest match wins.
In principle, it would be possible for the routine to choose the wrong match, but the test case suggests that this approach is surprisingly robust. The mean colors of target and selected tile were almost a perfect match: a distance of 0.00296966 away from the target mean color in RGB colorspace "cube" with edges of length 1.
Ungolfed 364 chars
f[{m_, tilesx_, tilesy_, targ_}] :=
 Module[{mosaic = Import[m],target = Import[targ], mDim = ImageDimensions[mosaic],

 (* find the average RGB colors for the target *)
 meanTargetPixelColor = Mean[Flatten[ImageData[target], 1]], m, t},
 m = ImagePartition[mosaic, {mDim[[1]]/tilesx, mDim[[2]]/tilesy}];

 (*Find the color distances between target mean rob and each mosaic tile
 Select the tile that best matches the average pixel color.*)
 t = SortBy[{#, EuclideanDistance[Mean[Flatten[ImageData[#], 1]],
 meanTargetPixelColor]} & /@ Flatten[m], Last][[1, 1]];
 Reverse[Position[m, t][[1]]]]

Example
Assuming that mosaic and targethold the respective filenames.
f[{mosaic, 59, 43, target}]

{48,18}

Golfed 247
f@{p_,x_,y_,s_}:=Module[{k=Flatten,i=Import,z=i@p,w,m,t,r},r=ImageDimensions@z;
w=Mean[k[ImageData[i@s],1]];m=ImagePartition[z,{r[[1]]/x,r[[2]]/y}];
Reverse[Position[m,SortBy[{#,EuclideanDistance[Mean[k[ImageData@#,1]],w]}&/@k@m,Last][[1,1]]][[1]]]]