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.


A calculator as a list of numbers and operators

JavaScript (ES6) 53

A function taking an array as input.

Run the snippet in Firefox to test.

f=a=>a.map(t=>t<'0'?o=t:v=eval(v+o+t)|0,v=0,o='+')&&v

// TEST
out=x=>O.innerHTML=x;

input = [5,8,25,"*",9,6,2,"-",104,"/",4,7,"+",6,"%",14];
out(input.join(' ')+' -> '+f(input));

function go() {
  i=I.value.split(/ +/),out(I.value+' -> '+f(i))
}

Your test:<input id=I><button onclick='go()'>GO</button>


Retina, 50 bytes

T`l`L

(:@.*)¶(.+)\1
b$2a
b(.*)a¶\1:NINJA'D
aa
a

Try it online!


An optimization version of the Hadamard problem


Find the largest N digit number in a W by H grid of digits

CJam, 39 36 35 34 bytes

qN/)i\[{zW%_}4*]ff{_,@e<ew:i}e_:e>

Just quickly, before @Dennis wakes up :P

Try it online.

Explanation

The basic algorithm is to take all four rotations of the grid and split each row into chunks of length N (or the row length, whichever's smaller). Then convert the chunks to ints and take the largest.

qN/             Split input by newlines, giving an array of lines
)i\             Drop N from the array and put at bottom
[        ]      Wrap in array...
 {    }4*         Perform 4 times...
  zW%_              Rotate grid anticlockwise and push a copy
                Note that this gives an array of 5 grids [CCW1 CCW2 CCW3 CCW4 CCW4]
ff{         }   For each grid row, mapping with N as an extra parameter...
   _,             Push length of row
     @e<          Take min with N
        ew        Split into chunks
          :i      Convert to ints
e_              Flatten that array
:e>             Take cumulative max


Help the architects visualize the skyline

MATLAB, 219 209 203 bytes
i=input('');x=1;c=0;m(1:4*numel(i))='_';for a=i;b=fix(a);m(1:b,x)='|';s=95;if a~=b;m(b+2,x+2)=95;s='/ \';end;m(b+1,x+(1:3))=s;x=x+(a>0)*3+1;m(1:b,x)='|';x=x+(a<1&c>0);c=a;end;disp(flipud(m(:,1:x-(a<1))))

This unfortunately doesn't work on Octave. Not entirely sure why, seems to be something to do with the disp/flipud bit that breaks.
Also, there is currently no definition of what a 0.5 height building looks like, nor any mention of them, so in this code I assume that they are disallowed.
The following is the code in a slightly more readable way:
i=input(''); %e.g. [0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1 0 0 1 0]
x=1;
c=0;
m(1:4*numel(i))='_';
for a=i;
    b=fix(a);
    m(1:b,x)='|';
    s=95;
    if a~=b;
        m(b+2,x+2)=95;
        s='/ \';
    end;
    m(b+1,x+(1:3))=s;
    x=x+(a>0)*3+1;
    m(1:b,x)='|';
    x=x+(a<1&c>0);
    c=a;
end;
disp(flipud(m(:,1:x-(a<1))))

First we take an input as an array, and do some variable initialisation.
i=input(''); %e.g. [0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1]
x=1;
c=0;

Because the zero height buildings are a pain - they basically end up with a width which is dependent on what they are next to (though what is printed doesn't change), we simplify things by drawing enough ground for all of the buildings. We assume each building will be 4 characters wide (because adjacent buildings merge together) - zero height ones aren't, but the excess will be trimmed later.
m(1:4*numel(i))='_';

Now we draw out each building in turn.
for a=i

First we get the integer part of the height as this will determine how many '|' we need.
    b=fix(a);

Now draw in the wall for this building - if there are two adjacent buildings, the wall for this new one will be in the same column as the wall from the last one.
    m(1:b,x)='|';

Check to see if this is a half height building. If it is, then the roof will be different. For the half heights, the roof is going to be / \ whereas full height ones it will be ___ (Matlab will implicitly replicate this from a single underscore, so save a couple of bytes there). There is an extra bit of roof one row higher for the half height buildings, so that is added as well.
    s=95;
    if a~=b;
        m(b+2,x+2)=95;
        s='/ \';
    end;

Draw in the roof
    m(b+1,x+(1:3))=s;

Now move to the start of the next building and draw in the shared wall (if the wall is too short at this point, it will be made larger when the next building is drawn). Note that zero height buildings are 1 wide, normal buildings are 4 wide, so we simplify what would otherwise be an if-else by treating (a>0) as a decimal number not a Boolean.
    x=x+(a>0)*3+1;
    m(1:b,x)='|';

Next comes a bit of hackery to work with zero height buildings. Basically what this says is if this building was zero height, and the one before that wasn't, it means the place of the next building needs incrementing by 1 because a zero height building sandwiched between two other buildings is effectively twice as wide - this accounts for the extra wall which is normally shared with an adjacent building. We also keep track of this building height for doing this check next time.
    x=x+(a<1&c>0);
    c=a;
end;

Once done, flip the building matrix to be the correct way up, and display it. Note that we also trim off any excess ground here as well.
disp(flipud(m(:,1:x-(a<1))))

So, when we run this script, we are asked for our input, for example:
[0 0 2 1 3.5 0 4 2 4 2 4 6 1 6 0 5 1 0 0 1 0]

It then generates the building and displays the result. For the above input, the following is generated:
                                     ___     ___
                                    |   |   |   |  ___
            _    ___     ___     ___|   |   |   | |   |
           / \  |   |   |   |   |   |   |   |   | |   |
   ___    |   | |   |___|   |___|   |   |   |   | |   |
  |   |___|   | |   |   |   |   |   |   |___|   | |   |___    ___
__|___|___|___|_|___|___|___|___|___|___|___|___|_|___|___|__|___|_


Jelly, 36 35 34 33 32 bytes

2*×5H_2Bị⁾ |
_3”-ẋ”+;;Çsẋ2U3¦ṁµY

TryItOnline!

Builds a nighter™ the other way around to the examples like:

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

How?

2*×5H_2Bị⁾ | - Link 1, pipes & spaces: n      e.g. 7
2*           - 2 raised to the nth power      e.g. 128
  ×5         - multiply by 5                  e.g. 640
    H        - halve                          e.g. 320
     _2      - subtract 2                     e.g. 318
       B     - convert to binary              e.g. [1,0,0,1,1,1,1,1,0]
        ị    - index into (1-based)
         ⁾ | - char list " |"                 e.g. " ||     |"

_3”-ẋ”+;;Çsẋ2U3¦ṁµY - Main link: n            e.g. 7
_3                  - n - 3                   e.g. 4
  ”-                - char list "-"
    ẋ               - repeat                  e.g. "----"
     ”+             - char list "+"
       ;            - concatenate             e.g. "+----"
         Ç          - call last link (1) as a monad
        ;           - concatenate             e.g. "+---- ||     |""
          s         - split into chunks of n  e.g. ["+---- |","|     |"]
           ẋ2       - repeat 2 times          e.g. ["+---- |",
                                                    "|     |",
                                              +-->  "+---- |",
                                              |     "|     |"]
              3¦    - apply to index 3:       |
             U      -    upend                +---  "| ----+"
                ṁ   - mould like n (i.e. repeat to fill)
                 µ  - monadic chain separation
                  Y - join with line feeds

(each byte saved involved fairly non-trivial changes, see the edit history if you're interested, although I just noticed that Link 1 is the same byte count as the more conventional repeat and join: _2⁶ẋ“ ||“|”j)


Shortest, lexicographically smallest generating string

Ruby 1.9, 40 characters

gets;a=?a;a.next!until(a*~/$/)[$_];$><<a

Assumes the input is not terminated by a newline. Also it's probably ridiculously slow for larger results.

$ echo -n "bcabcabca" | ruby genlex.rb
abc
$ echo -n "barfoobarfoobarfoo" | ruby1.9 genlex.rb
arfoob


C# (Visual C# Interactive Compiler), 71 bytes

x=>{for(int i=0,k=0,f=x.Count;i++<1<<f;k%=f)k-=(x[k]*=-1)%f-f;i/=x[k];}

Try it online!

I don't know if the following is valid, since it requires a custom delegate with a signature of unsafe delegate System.Action<int> D(int* a);
 and has to be wrapped in an unsafe block to be used, but here it is anyways:

C# (.NET Core), 64 bytes

x=>f=>{for(int i=0,k=0;i++<1<<f;k%=f)k-=(x[k]*=-1)%f-f;k/=x[k];}

Try it online!

This function takes in an int* and returns a Action; in other words, it is a curried function. The only reason I use pointers is because of codegolf.meta.stackexchange.com/a/13262/84206, which allows me to save bytes by already having a variable already defined with the length of the array.

Saved 9 bytes thanks to @someone


Output an image of your source code (not-quite-a-Quine)

shell

By "Print an image of the source code", I assume that actually printing an image on paper would be acceptable.

#!/bin/sh
lpr $0


LuaLaTeX, 220 211 characters
command:
lualatex -interaction nonstopmode

Not the shortest, but the fanciest. Based on @skillmon's solution

\RequirePackage{tikzducks}\newcount\b\let~\def~\0{red}~\1{orange}~\2{yellow}~\3{green}~\4{blue}~\5{cyan}~\6{violet}~\7{gray}\loop\b\uniformdeviate8\tikz\duck[body=\csname\the\b\endcsname]; \ifnum\b<7\repeat\stop


Python 2, 44 bytes

a,b,c,d=sorted(input())
print min(c-a,d-b)*2

Try it online!

Sorts the input as a,b,c,d, in ascending order, takes the smaller of c-a and d-b, and doubles it. Why does this work?

First, note that when we change an element to maximize to total cyclic sum of distances, it's optimal (or tied for optimal) to change it to equal a neighbor, such as 17, -6, 15, 33 -> 17, 17, 15, 33. That's because its new total distance to its left and right cyclic neighbors is at least the distance between those neighbors, so making these be equal is the best we can do.

Now, deleting one of two adjacent copies of a number gives the same cyclic sum of distances. In the example, this is 17, 15, 33, giving distances 2 + 18 + 16. So instead of replacing one of the four numbers, it's equivalent to just delete it leaving three numbers, and using the sum of their cyclic distances.

Notice that with 3 numbers, the largest distance is the sum of the two smaller ones. This is because if we sort the numbers to have a ≤ b ≤ c, then |a - c| = |a - b| + |b - c|. In other words, we travel between the largest and smallest number twice, using the medium number as a pit stop one of the times. So, the sum of the three distances is just twice the distance between the minimum and maximum, so (c-a)*2.

So, the question is which number we delete to get the smallest distance between the minimum and maximum of the three numbers that remains. Clearly we delete either the smallest or the largest of the numbers. Calling them a, b, c, d in sorted order, deleting a leaves d - b, and deleting d leaves c - a, and the final result is double whichever is smaller.


Java 8, score 846 838 822 816

ௐ->ௐ.map(ˇ->Character.getName(ˇ).length()).sum()

-8 score thanks to @tsh replacing the _1 with ꀊ.
-22 score thanks to @ASCII-only replacing the ꀊ with ˇ and $ with ௐ.
Try it online.
Explanation:
The ௐ and ˇ are used instead of the s and c I would normally use, because lowercase letters are all 20 (i.e. LATIN SMALL LETTER S), but ௐ (TAMIL OM) is 8 and ˇ (CARON) is 5.
ௐ->                         // Method with IntStream parameter and integer return-type
  ௐ.map(ˇ->                 //  Map each character to:
      Character.getName(ˇ)  //   Get the name of the character
               .length())   //   Get the length of that name
   .sum()                   //  And after the map: sum all lengths together,
                            //  and return it as result


Bash+coreutils, 37 bytes

tr ,$2 \\na-z<<<$1|sort|tr \\na-z ,$2

Output:

$ ./alphasort.sh home,oval,cat,egg,network,green bcdfghijklmnpqrstvwxyzaeiouy
cat,green,home,network,egg,oval, $


Retina, 57 49 44 43 41 bytes

So close... :) Pyth...

.(.+).
$0s go M$1$1
+`aa(\w*$)
e$1ow
wo
o

Try it online.

Expects input to be capitalised like Caaat or Coooow.

Explanation

.(.+).
$0s go M$1$1

The regex matches the entire input, and captures the vowels in group 1 (we don't need anchors, because the match cannot fail and will greedily match the entire input). The substitution writes back that input, and appends s go M, followed by twice the vowels. For inputs Caaat and Coooow, we get:

Caaats go Maaaaaa
Coooows go Moooooooo

The output for cows is already correct. We just need to do something about those cats.

+`aa(\w*$)
e$1ow

The + tells Retina to repeat this stage as often as possible. The regex matches two as in the last part of the string (we ensure this with the $ anchor, so that we don't replace things inside Caaats). This will essentially match everything after M, as long as that part still has as. The two as are removed and the entire suffix after it is wrapped in e...ow:

Caaats go Meaaaaow
Caaats go Meeaaowow
Caaats go Meeeowowow

Finally, there are two many ws in the result, so we remove those that precede an o (to make sure we're not messing up the w in Coooows):

wo
o

And we're left with:

Caaats go Meeeooow


javascript: smallest code to convert seconds to time

155 147 characters.

textTime=(t,z,m,x)=>(x=[t/3600,t/60%60,t%60].map((t,i)=>(!z||t|0)&&~~t+["hrs","min","sec"][i]+"."||0).slice(0,2+!m),(z?x.filter(x=>x):x).join(" "))

If the parameters made a little more sense, yes, it would be fewer.

Non-ES6, changing the name and using globals like @C5H8NNaO4 did, at 183 characters:

function t(t,z,m){return(x=[t/3600,t/60%60,t%60].map(function(t,i){return(!z||t|0)&&~~t+["hrs","min","sec"][i]+"."||0}).slice(0,2+!m),(z?x.filter(function(x){return x}):x).join(" "))}


Check for occurences of string in other string

JavaScript 32

Nothing really interesting here...

(p=prompt)().split(p()).length-1

split main purpose is to create an array from a string using the delimiter in argument.


Python 2, 56 bytes

lambda x:('"One more '*x+'LUL'+' and I\'m out"'*x)[1:-1]

Try it online!
It is 1-indexed


Windows Command Prompt - 34, 8, 5 chars, (2 below)

*These ones may or may not be breaking rule 2, but here it is anyway

%~099

Name the file:

&start call echo Hello world!!!&exit -b .cmd

Now lets corrupt the file-system a little - 2 chars (or less if you want)

A1

Name the file (using your preferred unorthodox method):

"&start call echo Hello world!!!&exit&.cmd

How does this work:

Since cmd scripts are invoked with 'cmd.exe /C "%1" %*' the executed command will be:

cmd.exe /C "c:\PATH_TO_THE_SCRIPT\"&start call echo Hello world!!!&exit&.cmd"

which will in the following order:

Fail to execute "c:\PATH_TO_THE_SCRIPT\"
Open a new shell printing Hello world!\n
Exit the original shell


MATL, 24 23 bytes
YOZ}&:"@23XOtt47>)tP=?8M

Accepts  input in the form of an array of string {lower, upper} where the date format is 'MM/DD/YYYY'. Output is in the format MM/DD/YYYY as well.
Try it Online
Explanation
        % Implicitly grab the two inputs
YO      % Convert to serial date format
Z}      % Push them onto the stack separately
&:      % Create an array from [lower...upper] incrementing 1 day
"       % For each day
  @23XO % Get the string version of the date (mm/dd/yyyy)
  tt    % Duplicate twice
  47>)  % Get the numeric parts
  tP=   % Compare numeric part with the flipped version of the numeric part
  ?8M   % If they are the same push it to the stack
        % Implicitly display stack contents


16 languages, 1363 bytes
 #define ip"MemuL tulaS",,,,,,,,,,"!",@++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.@,kc"Kaixo Mundua!"v#!
#define print(A,B,C)main(){printf("Helo Byd!");}//ss                                                                          ;ooooooooooooooooooo"Moni Dziko Lapansi!"<[-
#ifdef __cplusplus//p                                                                                ;;];;
#include<cstdio>//ffffffffff?
#define print(A,B,C)int main(){printf("Halo Dunya!");}//ssp
#endif//;  [;;;;;;;;;     "!etejivs vardzoP"]
#ifdef __OBJC__//;;;;;
#define print(A,B,C)main(){printf("Hallo Welt!");}//ss
#endif//\
"""echo" "Salom Dunyo!";"exit";puts"Moien Welt!";\
__END__
#define B//\
"""#;;;;;
print(["Hai dunia!","Hej Verden!","Halo Dunia!"][(int(1>0)is 1)+~int(-1/2)*2])
#define s eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejiiiiiiiijeeeeeeeeeeeeeejiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiijeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeejeejijiiiiiiiiiijeeeeeeeeeeejiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiij
#define U   !"!dlereW ollaH"<           ;
#define T@,kc"Sannu Duniya!?%?"

Try it online!
(use "switch languages" to change language)

Python 3 = Halo Dunia! (Indonesian)

Python 2 = Hej Verden! (Danish)

Python 1 = Hai dunia! (Malay)

C (gcc) = Helo Byd! (Welsh)

C++ (gcc) = Halo Dunya! (Sundanese)

Objective C (clang) = Hallo Welt! (German)

Brainfuck = Hello World! (English, obviously)

Befunge-93 = Salut Lume! (Romanian)

Ruby = Moien Welt! (Luxemburgish)

Bash = Salom Dunyo! (Uzbek)

Befunge-98 (PyFunge) = Kaixo Mundua! (Basque)

Unefunge-98 (PyFunge) = Sannu Duniya! (Hausa)

Cardinal = Hallo Wereld! (Dutch)

Alphuck = Ciao mondo! (Italian)

><> = Moni Dziko Lapansi! (Chichewa)

Fission = Pozdrav svijete! (Croatian)

Any golfing tips are welcome (especially on the Brainfuck)!!
Thanks to @JonathanFrech for -1 byte! Also, thanks to @ovs for -40 bytes!
How (general ideas, I actually forgot specifics)??
The languages can be put into four groups:

Macro: C, C++, Objective C
Comment: Python3, Python2, Python1, Ruby, Bash
Dimensional: Befunge-93, Befunge-98, Unefunge-98, Cardinal, ><>, Fission
Vulgar: Brainfuck, Alphuck

The Macro languages see # as the start of a preprocessor directive. These are used for three reasons: to house code for other groups, to distinguish among Macro languages, and to actually define a macro. All three use // as comment, so after that we store code for the other groups. Also, the backslash continues the comment in these languages.
The Comment languages see # as the start of a comment. The quirk here is the triple quotes, which distinguish the Pythons from Ruby from Bash. And to distinguish Python 1 from 2 from 3, we use a distinguishing feature in all three, along with an array of outputs. Oh yeah, there's also that __END__. This is used to end the code for some (can't remember exactly which ones) of the Comment languages.
The Dimensional languages are distinguished in a way that is hard to explain. One has to know the specifics of each language to figure it out. For example, # is only a skip in the fungeoids, while it does various different things in the other languages. The code is strewn about everywhere for these languages.
And finally, we arrive at the Vulgar languages. These two ignore everything that isn't in their set of valid characters. A balancing act has to be played with these languages and the others, as the code already contains characters in the character sets.
Edit: Wow... Somehow I only now realized Brainfuck did not seem to work, so that's fun!


A083569: Smallest m not occurring earlier such that m+n is prime

Haskell, 87 86 83 80 74 69 bytes

Thanks to xnor for suggesting some changes that saved 3 bytes!

f n=[m|m<-[1..],all((>0).mod(n+m))[2..n+m-1],all((/=m).f)[1..n-1]]!!0

Try it online!

I'm new to Haskell, and Haskell golfing, feedback is appreciated!

Explanation

We define a function f n.  We define f n to be the first element !!0 of the list:

[m|m<-[1..],all((>0).mod(n+m))[2..n+m-1],all((/=m).f)[1..n-1]]

Broken down that is:

[m|          # Numbers m
m<-[1..],    # From the integers greater than 0
all          # Forall x
(>0).mod(n+m)# n+m mod x is not zero
[2..n+m-1]   # from the integers from 2 to n+m-1
all          # Forall
((/=m).f)    # when f is applied the result is not m
[1..n-1]     # from the integers from 1 to n-1


Python 2, 102 101 97 91 bytes

from random import*
exec"x=''.join(x.title()for x in sample(f,4));print(x,57*len(x)/10);"*5

Assumes the dictionary as a list named f.

Can be tested by saving the file as dict.txt and calling

f = open('dict.txt').readlines()


Vitsy, 49 bytes

I thought you handed this one to me on a plate, but I found an unresolved bug to work around. Didn't hurt me, though.

lmN
3^43/*P*
2^*P*
**
v:++2/uV3\[V}-]V3\*12/^v*3/

Basically, with the input being a certain length for different functions, you spoon feed me my method syntax for doing this stuff. So, yay, success!

Explanation, one line at a time:

lmN
l   Get the length of the stack.
 m  Go to the line index specified by the top item of the stack (the length).
  N Output as a number.

3^43/*P*
3^
          Put to the power of 3.
  43/*    Multiply by 4/3.
      P*  Multiply by π

2^*P*
2^     Put to the second power.
  *    Multiply the top two items.
   P*  Multiply by π

**
**     Multiply the top three items of the stack.

v:++2/uV3\[V}-]V3\*12/^v*3/
v                            Save the top item as a temp variable.
 :                           Duplicate the stack.
  ++                         Sum the top three values.
    2/                       Divide by two.
      u                      Flatten the top stack to the second to top.
       V                     Capture the top item of the stack (semiperimeter)
                             as a permanent variable.
        3\[   ]              Do the stuff in the brackets 3 times.
           V}-               Subtract the semiperimeter by each item.
               V             Push the global var again.
                3\*          Multiply the top 4 items.
                   12/^      Square root.
                       v*    Multiply by the temp var (the depth)
                         3/  Divide by three.

Input is accepted as command line arguments in the exact reverse as they appear in the question, with no trailing zeroes.

Try it online!

As an aside, here's something that's currently in development.

Java w/ Vitsy Package

Note that this package is work in progress; this is just to show how this will work in the future (documentation for this is not yet uploaded) and it is not golfed, and is a literal translation:

import com.VTC.vitsy;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;

public class Volume {
    public static void main(String[] args) {
        Vitsy vitsyObj = new Vitsy(false, true);
        vitsyObj.addMethod(new Vitsy.Method() {
            public void execute() {
                vitsyObj.pushStackLength();
                vitsyObj.callMethod();
                vitsyObj.outputTopAsNum();
            }
        });
        vitsyObj.addMethod(new Vitsy.Method() {
            public void execute() {
                vitsyObj.push(new BigDecimal(3));
                vitsyObj.powerTopTwo();
                vitsyObj.push(new BigDecimal(4));
                vitsyObj.push(new BigDecimal(3));
                vitsyObj.divideTopTwo();
                vitsyObj.multiplyTopTwo();
                vitsyObj.pushpi();
                vitsyObj.multiplyTopTwo();
            }
        });
        vitsyObj.addMethod(new Vitsy.Method() {
            public void execute() {
                vitsyObj.push(new BigDecimal(2));
                vitsyObj.powerTopTwo();
                vitsyObj.multiplyTopTwo();
                vitsyObj.pushpi();
                vitsyObj.multiplyTopTwo();
            }
        });
        vitsyObj.addMethod(new Vitsy.Method() {
            public void execute() {
                vitsyObj.multiplyTopTwo();
                vitsyObj.multiplyTopTwo();
            }
        });
        vitsyObj.addMethod(new Vitsy.Method() {
            public void execute() {
                vitsyObj.tempVar();
                vitsyObj.cloneStack();
                vitsyObj.addTopTwo();
                vitsyObj.addTopTwo();
                vitsyObj.push(new BigDecimal(2));
                vitsyObj.divideTopTwo();
                vitsyObj.flatten();
                vitsyObj.globalVar();
                vitsyObj.push(new BigDecimal(3));
                vitsyObj.repeat(new Vitsy.Block() {
                    public void execute() {
                        vitsyObj.globalVar();
                        vitsyObj.rotateRight();
                        vitsyObj.subtract();
                    }
                });
                vitsyObj.globalVar();
                vitsyObj.push(new BigDecimal(3));
                vitsyObj.repeat(new Vitsy.Block() {
                    public void execute() {
                        vitsyObj.multiplyTopTwo();
                    }
                });
                vitsyObj.push(new BigDecimal(1));
                vitsyObj.push(new BigDecimal(2));
                vitsyObj.divideTopTwo();
                vitsyObj.powerTopTwo();
                vitsyObj.tempVar();
                vitsyObj.multiplyTopTwo();
                vitsyObj.push(new BigDecimal(3));
                vitsyObj.divideTopTwo();
            }
        });
        vitsyObj.run(new ArrayList(Arrays.asList(args)));
    }
}


PowerShell, 131 117 bytes

param($n)' '*$n+" |"
$n..1|%{" "*$_+"/$(' '*++$i)\";$x="*-$('-'*++$i)*"}
$x
,("| $('o '*$n)|")*$i
$x
" /$('_'*--$i)\"

Try it online!

Line breaks added for clarity, but they could just as easily be ; (it's the same byte count either way).

We're basically brute-force building the rocket one line at a time. We start by taking input $n, then construct a string of $n spaces and the nose antenna. We then loop from $n down to 1, using a triangular number trick with $i to get the appropriate number of middle spaces for the nose cone. Including the construction of the joiner into the loop allows us to re-use ++$i to both create the joiner and increment for our triangular number, saved into $x for later use.

We then use array-multiplication with the comma operator to construct the body of the rocket, then $x onto the pipeline again for the bottom. Finally we output the engine part with the appropriate _ in between.

All of those strings are left on the pipeline, and default implicit output gives us newlines for free.

-14 bytes thanks to VisualMelon.


Python 3, 159 158 152 144 136 135 132 bytes

def t(i,a=1):
 while'-'<l[i]!='/':i+=1;a=0
 if a:l[i]='(';i=t(t(i+1));l[i-1]=')'
 return-~i
*l,=input()
t(0)
print(eval(''.join(l)))

Try it online!

Doesn't allow negative numbers (though -0-5- works of course) and requires python operators.


C, 349 295 277 267 255 bytes

N,i;__int128 n=2,b,o,l[999];P(m){i<N&&P(m<2?l[i++]=n:n%m?m-1:n++);}main(r){for(P(scanf("%d",&N));r|!b;)for(++n,b=i=N;i--&&b;){for(b=n-1,r=0;~b&1;b/=2)++r;for(o=1;b--;o=o*l[i]%n);for(b=o==1;r--;o=o*o%n)b|=o>n-2;for(o=r=1;++o<n;r&=n%o>0);}printf("%llu",n);}

Takes 1-based input on stdin, e.g.:

echo "1" | ./millerRabin

It certainly isn't going to discover any new values in the sequence any time soon, but it gets the job done. UPDATE: now even slower!

Slightly faster and shorter, with inspiration from Neil A's answer (a^(d*2^r) == (a^d)^(2^r))
Significantly slower again after realising that all solutions to this challenge will be odd, so there is no need to explicitly enforce that we only check odd numbers.
Now using GCC's __int128, which is shorter than unsigned long long while also working with larger numbers! Also on little-endian machines, the printf with %llu still works fine.

Less-minified

N,i;
__int128 n=2,b,o,l[999];
P(m){i<N&&P(m<2?l[i++]=n:n%m?m-1:n++);}
main(r){
    for(P(scanf("%d",&N));r|!b;)
        for(++n,b=i=N;i--&&b;){
            for(b=n-1,r=0;~b&1;b/=2)++r;
            for(o=1;b--;o=o*l[i]%n);
            for(b=o==1;r--;o=o*o%n)b|=o>n-2;
            for(o=r=1;++o<n;r&=n%o>0);
        }
    printf("%llu",n);
}

(Outdated) Breakdown

unsigned long long                  // Use the longest type available
n=2,N,b,i,d,p,o,                    // Globals (mostly share names with question)
l[999];                             // Primes to check (limited to 999, but if you
                                    // want it to be "unlimited", change to -1u)
m(){for(o=1;p--;o=o*l[i]%n);}       // Inefficiently calculates (l[i]^p) mod n

// I cannot possibly take credit for this amazing prime finder;
// See https://codegolf.stackexchange.com/a/5818/8927
P(m){i<N&&P(m<2?l[i++]=n:n%m?m-1:n++);}

main(r){
    for(
        P(scanf("%llu",&N));        // Read & calculate desired number of primes
        r|!b;){                     // While we haven't got an answer:
        n=n+1|1;                    // Advance to next odd number
        for(b=1,i=N;i--&&b;){       // For each prime...
            for(d=n-1,r=0;~d&1;d/=2)++r; // Calculate d and r: d*2^r = n-1
            // Check if there exists any r such that a^(d*2^r) == -1 mod n
            // OR a^d == 1 mod n
            m(p=d);
            for(b=o==1;r--;b|=o==n-1)m(p=d<<r);
            // If neither of these exist, we have proven n is not prime,
            // and the outer loop will keep going (!b)
        }
        // Check if n is actually prime;
        // if it is, the outer loop will keep going (r)
        for(i=r=1;++i<n;r&=n%i!=0);
    }
    printf("%llu",n);               // We found a non-prime; print it & stop.
}

As mentioned, this uses 1-based input. But for n=0 it produces 9, which follows the related sequence https://oeis.org/A006945. Not any more; now it hangs on 0.

Should work for all n (at least until the output reaches 2^64) but is incredibly slow. I have verified it on n=0, n=1 and (after a lot of waiting), n=2.


APL, 21 characters
'01'[-(16/¯2)⊤-2⊥⍎¨⍞]

I used Dyalog APL for this, with ⎕IO set to 0, allowing us to index arrays starting at 0 rather than 1.
Explanation, from right to left:

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

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


Jelly, 1 byte

’

Output is 0 for a match, non-zero for a non-match.

Try it online!

How it works

This makes advantage of the overly liberal output format. Repeating ’ M times simply decrements the input M times, so the result will be zero if and only if the input is LM, where L = 1.


OK, I said I'd put my comments into a more comprehensible form so here they are.

Don't separate commands. Having to use ; every time you want to use a different command is costly. My recommendation on the interpreter side is to parse one character at a time and read more if the command necessitates it.
Add regex (to be honest, I don't know much regex -- it's somewhere on my list of things to learn -- but it seems logical to add it)
On the topic of not separating commands with ;, allow for whitespace to be removeable.
Add loops of some sort.
Add conditionals and conditional tests (equals, not, and, or, etc.)
Add a newline reserved character (n, perhaps?)
Add reserved characters for variables
You have uppercase and lowercase commands, why not add a capitalization one (one that capitalizes the string as if it were a sentence and maybe also capitalizes proper nouns that it can identify).
Add a command to count how many instances of a string are in another.
Add a length command to get the length of a string.
Add a terminate/break command.
Add an equivalent of Python's ord and chr functions.
Add a split at numerical value command (splits at a certain length), and add an alternative to that which splits at every multiple of the numerical value (e.g. for a string of length 10 at 3,6,9 if given the argument 3).
Add a duplication command (akin to Python's "String"*x)

You'll notice that some of these involve numbers -- I think that even for String challenges having a way of working with numbers is good. Perhaps have a stack for storing numbers that is accessed when certain commands are used (e.g. the length command pushes the length onto the number stack and then the split at numerical value uses this length to split the stack).

I'll add more ideas as I think of them, but I feel like my suggestions are pushing this in the direction of a more general-purpose golf language. Hopefully this input helps regardless of whether you use it or not.


bash (24 bytes)
using brace expansion
echo N {N,,S}E S {S,,N}W

is the same length as hard coding
echo N NE E SE S SW W NW

however it becomes more interesting when outputing more points of the compass
echo N NNE NE ENE E ESE SE SSE S SSW SW WSW W WNW NW NNW

brace expansion
echo N {{N,,E}N,,{E,,S}S}E S {{S,,W}S,,{W,,N}N}W

otherwise if order could be changed, (17 bytes), the trick is that without quotes the empy string parameter disappears
echo {N,,S}{W,,E}


Shortest Longest Common Subsequence Code

Python - 665 644

Indentation levels:

1: space
2: tab
3: tab + space
4: 2 tabs
5: 2 tabs + space

The code defines a function o, which takes a list of strings as arguments and returns one of the LCS's for the strings.

def o(t):
 t=[[y for y in x if y in reduce(lambda x,y:x.intersection(y),t,set(t[0]))]for x in t];l=map(len,t);C=[0]*reduce(lambda x,y:x*-~y,l,1);y=lambda z:[x-1for x in z];m=len(t);e=enumerate
 def g(h):
    r,x=0,1
    for k,j in e(h):r+=-~j*x;x*=-~l[k]
    return r
 def f(h):
    i=len(h)
    if i==m:
     b=g(h);c=t[0][h[0]]
     for k,j in e(h):
         if t[k][j]!=c:break
     else:C[b]=1+C[g(y(h))];return
     r=0
     for k,_ in e(h):a=h[:];a[k]-=1;r=max(r,C[g(a)])
     C[b]=r;return
    for j,_ in e(t[i]):f(h+[j])
 def p(h):
    if min(h)==-1:return''
    v=C[g(h)]
    for k,_ in e(h):
        a=h[:];a[k]-=1
        if v==C[g(a)]:return p(a)
    return p(y(h))+t[0][h[0]]
 f([]);return p(y(l))

Test code:

tests = [
"""
a
ab
""",
"""
aaaaxbbbb
bbbbxcccc
ccccxaaaa
""",
"""
hxbecqibzpyqhosszypghkdddykjfjcajnwfmtfhqcpavqrtoipocijrmqpgzoufkjkyurczxuhkcpehbhpsuieqgjcepuhbpronmlrcgvipvibhuyqndbjbrrzpqbdegmqgjliclcgahxoouqxqpujsyfwbdthteidvigudsuoznykkzskspjufgkhaxorbrdvgodlb
qnnprxqpnafnhekcxljyysobbpyhynvolgtrntqtjpxpchqwgtkpxxvmwwcohxplsailheuzhkbtayvmxnttycdkbdvryjkfhshulptkuarqwuidrnjsydftsyhuueebnrjvkfvhqmyrclehcwethsqzcyfvyohzskvgttggndmdvdgollryqoswviqurrqhiqrqtyrl
""",
"""
riikscwpvsbxrvkpymvbbpmwclizxlhihiubycxmxwviuajdzoonjpkgiuiulbjdpkztsqznhbjhymwzkutmkkkhirryabricvhb
jnrzutfnbqhbaueicsvltalvqoorafnadevojjcsnlftoskhntashydksoheydbeuwlswdzivxnvcrxbgxmquvdnfairsppodznm
kzimnldhqklxyezcuyjaiasaeslicegmnwfavllanoolkhvqkjdvxrsjapqqwnrplcwqginwinktxnkfcuuvoyntrqwwucarfvjg
""",
"""
rblartqkfggrjpiipuzzypkycnyckkcqceeujiyy
yfpnedyjtiwrhyuktripdwyvgkblzodeufkelhub
ywcyboxwqkibwvredkrbdsyudkulpvmhixeqxynh
bnxwahbzhwjxkotnvbxrojkkldtsodtjmvdrmbgr
""",
"""
bwfscmotshoczmduwaev
coywaaizdaxjovipsmeh
dobzcpoiedenzlfdjpiu
bbhfeqscvvbwkuoxdoge
drqrzwbcpcsvneodelja
""",
"""
nqrualgoedlf
jgqorzglfnpa
fgttvnogldfx
pgostsulyfug
sgnhoyjlnfvr
wdttgkolfkbt
""",
"""
epopyfuhgowedpiqpgfj
ddxyestqynpwmytxhozm
ptubgzyqqksieoovuezv
tovotqmnhgzttfpywjgr
aomvytkgaijlgqzkljls
vzvxpaixrnprxvenbbuo
syfuwxlpcyontqlmfvib
arxleuomstkjegpduwcx
xgqrxaopouvkvwgbzewn
yggunddigctgpnuztzai
izroomywwztdymqszsuo
kiawjnxjncdtufhkrjsp
"""
]

for s in tests:
 print o(s.strip().split())

Time it takes to run the tests on my computer:

$ time python 52808-shortest-longest-common-subsequence-code-golfed.py
a
x
hecbpyhogntqtpcqgkxchpsieuhbncvhuqndbjqmclchqyfhtdvgoysuhrrl
icsvllvanlktywuar
krkk
code
golf

        9.03 real         8.99 user         0.03 sys


Mathematica (version 9), 165 bytes

The nice, short ConvexHullMesh function that Greg Martin used was only introduced in Mathematica version 10, so I thought I'd make an attempt without it, using my ancient Mathematica version 9. I managed to get it slightly shorter, though! It's a function that takes and returns a list of strings (with ., # and o as the symbols).

""<>#&/@("o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"#/.{0->"."})&[Characters@#/.{"."->0,"#"->1}]&

Explanation:

First, Characters@# /. {"."->0, "#"->1} turns the input into a matrix of 0s and 1s.
"o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"# then uses Mathematica's powerful (but extremely byte-heavy…) image processing capabilities to first fill in the island's convex hull (which is the shape you'd get if you stretched a piece of string around it), and then take its boundary. We then multiply this matrix by the string "o" to get a matrix of 0s and "o"s (thanks to Mathematica's impressive adaptability about types), and add this to "#" times the matrix of the island.
Finally, ""<>#& /@ (... /. {0->"."}) turns this matrix of "o"s, "#"s and 0s into a matrix of "o"s, "#"s and "."s, and joins each row into a string.

When we test this on example B, we get the output

{"....oo..",
 "...o##o.",
 "..o####o",
 ".o###..o",
 "o#####o.",
 "o#####o.",
 ".o##oo..",
 "..oo...."}

[Edit, thanks to Greg Martin:] If we're allowed to use arrays of characters instead of lists of strings, we can trim this down to 144 bytes:

"o"MorphologicalTransform[MorphologicalComponents[#,Method->"ConvexHull"],Max[#(1-#[[2,2]])CrossMatrix@1]&]+"#"#/.{0->"."}&[#/.{"."->0,"#"->1}]&


I really wanted a rhombus, but all I got was this stupid rectangle

HTML + JavaScript (ES6), 34 + 353 = 387 bytes

Input should be given in the format [125,50].

[w,h]=eval(prompt(c=C.getContext("2d"))).sort();d=q=>(c.strokeStyle=q,b);l=(x,y=Z)=>x?c.lineTo(x,y)||l:c.stroke();b=(x,y=H,r)=>(c.beginPath(),r?c.arc(x,y,Math.sqrt(r),0,2*Math.PI):c.moveTo(x,y),l);b(Z=300,Z)(W=Z+w)(W,H=Z+h)(Z,H)(Z)();d`red`(Z,H,s=w*w+h*h)();b(W,Z,s)();b(Z)(W)();b(Z+w/2-h,Z+h/2-w)(H+w/2,W+h/2)();d`lime`(Z)(W-s/2/w)(W)(Z+s/2/w,H)(Z,H)()
<canvas id=C width=800 height=800>

Just a lot of math and drawing... The rectangle is drawn sideways if the height is greater than the width, which I believe is allowed.


Write a program to display directory treehouse

bash, 61 58 54 bytes

find "$1" -exec ls -Fd {} \;|perl -pe's|.*?/(?!$)|  |g'

Takes input as a command line argument, outputs on STDOUT.

Note that the spaces near the end before the |g are actually a tab character (SE converts them to spaces when displaying posts).

find              crawl directory tree recursively
"$1"              starting at the input directory
-exec             and for each file found, execute...
ls -Fd {} \;      append a trailing slash if it's a directory (using -F of ls)
|perl -pe         pipe each line to perl
'
s|                replace...
.*?/              each parent directory in the file's path...
(?!$)             that doesn't occur at the end of the string...
|    |            with a tab character...
g                 globally
'

Thanks to @Dennis for 4 bytes!


Advanced Code Golf - Write a small HTTP server

Bash+netcat: 354 characters

Two script files are used.
No URL decoding, thus file names with spaces and special characters not supported.
Single threaded, so concurrent requests may fail.
Tested on Linux, works nicely with Firefox and Opera.

webserver.sh (33 characters):
while :;do nc -lp36895 -e./w;done

w (321 characters):
read m p v
p=/var/www$p
t=text/plain
[[ -r $p ]]||s='500 Server Error'
[[ -e $p ]]||s='404 Not Found'
[[ $m != GET ]]&&s='405 Not Supported'
[[ $s||-d $p ]]||case ${p##*.} in
txt);;html)t=text/html;;*)t=application/octet-stream;;esac
echo "$v ${s-200 Ok}
Content-Type:$t
"
[[ $s ]]&&echo $s||{ [[ -d $p ]]&&echo||cat $p;}

Sample run:
bash-4.2$ ./webserver.sh

Sample visit (Firefox 19.0):


Resize rasterized text and make it look non-pixellated

Ruby, with RMagick

The algorithm is very simple—find patterns of pixels that look like this:

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

and add triangles to make them look like this:

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

Code:

#!/usr/bin/ruby

require 'rmagick'
require 'rvg/rvg'
include Magick

img = Image.read(ARGV[0] || 'img.png').first
pixels = []
img.each_pixel{|px, x, y|
    if px.red == 0 && px.green == 0 && px.blue == 0
        pixels.push [x, y]
    end
}

scale = ARGV[2].to_f || 5.0
rvg = RVG.new((img.columns * scale).to_i, (img.rows * scale).to_i)
    .viewbox(0, 0, img.columns, img.rows) {|cnv|
    # draw all regular pixels
    pixels.each do |p|
        cnv.rect(1, 1, p[0], p[1])
    end
    # now collect all 2x2 rectangles of pixels
    getpx = ->x, y { !!pixels.find{|p| p[0] == x && p[1] == y } }
    rects = [*0..img.columns].product([*0..img.rows]).map{|x, y|
        [[x, y], [
            [getpx[x, y  ], getpx[x+1, y  ]],
            [getpx[x, y+1], getpx[x+1, y+1]]
        ]]
    }
    # WARNING: ugly code repetition ahead
    # (TODO: ... fix that)
    # find this pattern:
    # ?X
    # XO
    # where X = black pixel, O = white pixel, ? = anything
    rects.select{|r| r[1][0][1] && r[1][1][0] && !r[1][2][1] }
        .each do |r|
            x, y = r[0]
            cnv.polygon x+1,y+1, x+2,y+1, x+1,y+2
        end
    # OX
    # X?
    rects.select{|r| r[1][0][1] && r[1][3][0] && !r[1][0][0] }
        .each do |r|
            x, y = r[0]
            cnv.polygon x+1,y+1, x+0,y+1, x+1,y+0
        end
    # X?
    # OX
    rects.select{|r| r[1][0][0] && r[1][4][1] && !r[1][5][0] }
        .each do |r|
            x, y = r[0]
            cnv.polygon x+1,y+1, x+0,y+1, x+1,y+2
        end
    # XO
    # ?X
    rects.select{|r| r[1][0][0] && r[1][6][1] && !r[1][0][1] }
        .each do |r|
            x, y = r[0]
            cnv.polygon x+1,y+1, x+2,y+1, x+1,y+0
        end
}
rvg.draw.write(ARGV[1] || 'out.png')

Outputs (click any to view image by itself):

1.333

1.5

2

3

4


More coding expressions like while(!(succeed = try()))?

How about:

~wish&~want;

or

Penny.Earned = Penny.Save();


$($);

May not meet your conditions, but I like it. (And it does crash your browser.)

More information about this: Why does $($) crash my page?


ROT-128 oscillating quine (Mutual Quine)

GolfScript, 64 48 bytes

{ºî»`'.~'+.{128^}%\](}.~û:n;à§®þ§«®û±²¸Þý¥ÜÝ¨ý®þ

Thanks to @MartinBüttner for golfing off 16 bytes!

Try it online!

Output

û:n;à§®þ§«®û±²¸Þý¥ÜÝ¨ý®þ{ºî»`'.~'+.{128^}%\](}.~

Try it online!

Verification

$ LANG=en_US

$ cat quine.gs
{ºî»`'.~'+.{128^}%\](}.~û:n;à§®þ§«®û±²¸Þý¥ÜÝ¨ý®þ
$ golfscript quine.gs
û:n;à§®þ§«®û±²¸Þý¥ÜÝ¨ý®þ{ºî»`'.~'+.{128^}%\](}.~
$ golfscript quine.gs | golfscript
{ºî»`'.~'+.{128^}%\](}.~û:n;à§®þ§«®û±²¸Þý¥ÜÝ¨ý®þ
$ diff -s quine.gs <(golfscript quine.gs | golfscript)
Files quine.gs and /dev/fd/63 are identical


JavaScript 782 725 characters

first post, be gentle!

The program is now called via the wrapped function. Eg: (function(e,f,g){...})(100,200,10).

function C(e,f,g,c,a,d){if(0>g-a||g+a>e||0>c-a||c+a>f)return d;for(var b in d)if(Math.sqrt(Math.pow(d[b].x-g,2)+Math.pow(d[b].y-c,2))<2*a)return d;d.push({x:g,y:c});for(b=0;b<Math.PI;)XX=Math.cos(b)*a*2+g,YY=Math.sin(b)*a*2+c,d=C(e,f,XX,YY,a,d),b+=.01;return d}
(function(e,f,g){var c=e+f,a,d;for(a=[];a.length<g;)a=d=c,a=C(e,f,a,d,c,[]),c-=.01;console.log("Highest possible radius: "+Math.round(100*c)/100);e='<svg width="'+e+'" height="'+f+'"><rect width="'+e+'" height="'+f+'" style="fill:red" />';for(var b in a)console.log("Circle "+b+" Focus: ("+Math.round(100*a[b].x)/100+", "+Math.round(100*a[b].y)/100+")"),e+='<circle cx="'+a[b].x+'" cy="'+a[b].y+'" r="'+c+'" fill="blue" />';console.log(e+"</svg>")})(400,300,13);

Test 1

(function(e,f,g){...})(200,200,4)

Highest possible radius: 49.96
Circle 1 Focus: (49.97, 49.97)
Circle 2 Focus: (149.91, 49.97)
Circle 3 Focus: (149.99, 149.91)
Circle 4 Focus: (50.05, 149.91)
<svg width="200" height="200"><rect width="200" height="200" style="fill:blue;" /><circle cx="49.97000000021743" cy="49.97000000021743" r="49.960000000217434" fill="white" /><circle cx="149.9100000006523" cy="49.97000000021743" r="49.960000000217434" fill="white" /><circle cx="149.98958489212322" cy="149.90996831285986" r="49.960000000217434" fill="white" /><circle cx="50.04958489168835" cy="149.90996831285986" r="49.960000000217434" fill="white" /></svg>

Obviously we would expect the radius to be exactly 50, but for reasons discussed in the question's comments, I couldn't reasonably make it happen. The SVG looks like this...

Test 2

(function(e,f,g){...})(100,400,14)

Highest possible radius: 26.55
Circle 1 Focus: (26.56, 26.56)
Circle 2 Focus: (79.68, 26.56)
Circle 3 Focus: (132.8, 26.56)
Circle 4 Focus: (185.92, 26.56)
Circle 5 Focus: (239.04, 26.56)
Circle 6 Focus: (292.16, 26.56)
Circle 7 Focus: (345.28, 26.56)
Circle 8 Focus: (372.63, 72.1)
Circle 9 Focus: (319.52, 73.25)
Circle 10 Focus: (265.47, 72.64)
Circle 11 Focus: (212.35, 73.25)
Circle 12 Focus: (159.23, 72.64)
Circle 13 Focus: (106.11, 73.25)
Circle 14 Focus: (52.99, 72.64)
<svg width="400" height="100"><rect width="400" height="100" style="fill:blue;" /><circle cx="26.560000000311106" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="79.68000000093332" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="132.80000000155553" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="185.92000000217774" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="239.04000000279996" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="292.16000000342217" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="345.2800000040444" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="372.6271770491687" cy="72.09972230654316" r="26.550000000311105" fill="white" /><circle cx="319.5195599732359" cy="73.24663493712801" r="26.550000000311105" fill="white" /><circle cx="265.47097406711805" cy="72.63752174440503" r="26.550000000311105" fill="white" /><circle cx="212.35454341475625" cy="73.25330971030218" r="26.550000000311105" fill="white" /><circle cx="159.23097406587362" cy="72.63752174440503" r="26.550000000311105" fill="white" /><circle cx="106.11454341351183" cy="73.25330971030218" r="26.550000000311105" fill="white" /><circle cx="52.99097406462921" cy="72.63752174440503" r="26.550000000311105" fill="white" /></svg>

And the SVG looks like this...

Test 3

(function(e,f,g){...})(400,400,3)

Highest possible radius: 101.68
Circle 1 Focus: (101.69, 101.69)
Circle 2 Focus: (298.23, 153.98)
Circle 3 Focus: (154.13, 298.19)
<svg width="400" height="400"><rect width="400" height="400" style="fill:blue;" /><circle cx="101.69000000059772" cy="101.69000000059772" r="101.68000000059772" fill="white" /><circle cx="298.2343937547503" cy="153.97504264473156" r="101.68000000059772" fill="white" /><circle cx="154.13153961740014" cy="298.19269546075066" r="101.68000000059772" fill="white" /></svg>

And the SVG looks like this...

They aren't all pretty.

How it works

Ungolfed code below. This program has two assumptions:

One circle will always be in the corner. This seems like a pretty safe bet.
Every circle will always be touching another circle. I don't see why they wouldn't be.

The program starts by calculating a large radius based on the box dimensions. It then tries to fit one circle in the corner of the box. If that circle fits, it extends a diameter line from that circle and tries to create a circle at the end of the line. If the new circle fits, another line will be extended from the new circle. If it doesn't fit, the line will swing 360 degrees, checking for open spaces. If the box fills up before the desired number of circles are created, the radius is reduced and it all starts over again.

Ungolfed Code (snippet)

// this functions attempts to build a circle
// at the given coords. If it works, it will
// spawn additional circles.
function C(x, y, X, Y, r, cc){

 // if this circle does not fit in the rectangle, BAIL
 if(X-r < 0 || X+r > x || Y-r < 0 || Y+r > y)
  return cc;

 // if this circle is too close to another circle, BAIL
 for(var c in cc){
  if( Math.sqrt(Math.pow(cc[c].x - X, 2) + Math.pow(cc[c].y - Y, 2)) < (r*2) )
   return cc;
 }

 // checks passed so lets call this circle valid and add it to stack
 cc.push({"x": X, "y": Y});

 // now rotate to try to find additional spots for circles
 var a = 0; // radian for rotation
 while(a < Math.PI){
  XX = Math.cos(a)*r*2 + X;
  YY = Math.sin(a)*r*2 + Y;
  cc = C(x, y, XX, YY, r, cc);
  a += .01; // CHANGE FOR MORE OR LESS PRECISION
 }

 return cc;
}

// this function slowly reduces the radius
// and checks for correct solutions
// also prints svg graphic code

(function B(x, y, n){

 var r = x + y; // pick a big radius
 var X, Y; // these are the coords of the current circle. golf by combining this with `var r..`?
 var cc = []; // array of coordinates of the circles

 // while we cant fit n circles, reduce the radius and try again
 while(cc.length < n){
  X = Y = r;
  cc = C(x, y, X, Y, r, []);
  r-=.01; // CHANGE FOR MORE OR LESS PRECISION
 }

 console.log('Highest possible radius: ' + Math.round(r*100)/100);
 var s = '<svg width="' + x + '" height="' + y + '"><rect width="' + x + '" height="' + y + '" style="fill:red" />';
 for(var c in cc){
  console.log('Circle '+c+' Focus: (' + Math.round(cc[c].x*100)/100 + ', ' + Math.round(cc[c].y*100)/100 + ')');
  s += '<circle cx="' + cc[c].x + '" cy="' + cc[c].y + '" r="' + r + '" fill="blue" />';
 }
 s += '</svg>';
 console.log(s);
 document.write(s);
})(150, 150, 5);


Pyth, (67 bytes) / 2 = 33.5

L_,*lbJ*FeCbsm*hd/JedbM?&hHstH?GymgtG-XdKH_1_!dlH,01,TT*100cFghQstQ

This qualifies for the bonus even though I had to manually implement arbitrary precision rationals.

(I wish Pyth5 was already a thing).

Input from STDIN in the format A, H, L

Demonstration.

Corrected to output percentage. Percentage is as acurate as possible, due to use of integer math until the last step.

At the high level, the first segment, L_,*lbJ*FeCbsm*hd/Jedb, is a helper function which takes a list of rationals in the form of 2 element lists, and outputs their average as an (unreduced) rational.

The second segment, M?&hHstH?GymgtG-XdKH_1_!dlH,01,TT, recusively calculates the probability of victory.

The third segment, cFghQstQ formats the input to fit the function and performs the final division.

On the second example case, the final unreduced 2-tuple is too long to fit on the screen:

[83158592487544376524800000000000000000000, 1079462498636393349120000000000000000000000]

Fortunately, Pyth does have arbitrary precision integers.


Mathematica, 33 bytes

So close to Pyth...

l/Tr[l={#,#2(x=100Pi*I),1/x/#3}]&

This is an unnamed function, which takes R, L and C as its three arguments and returns a list of complex numbers as the result (in the required order VR, VL, VC). Example usage:

l/Tr[l={#,#2(x=100Pi*I),1/x/#3}]&[1, 1, 0.00001]
(* {0.0548617 + 0.22771 I, -71.5372 + 17.2353 I, 72.4824 - 17.463 I} *)


GolfScript, 11 10 bytes

21;;3#9];6

Uses # as padding character.

12 o'clock

6
;
]
9
#
3
;
;
1
2

Try it online!

How it works.

6 is pushed on the stack, ; discards it.
] wraps the stack in an array (does not affect output).
9 and 3 are pushed on the stack, ; and ; discard them.
Finally, 1 and 2 are pushed on the stack, and implicitly printed without separation.

3 o'clock

6
;
]
9
#
3
;
;
1
21;;3#9];6

Try it online!

How it works

6 is pushed on the stack, ; discards it.
] wraps the stack in an array (does not affect output).
9 and 3 are pushed on the stack, ; and ; discard them.
1 and 21 are pushed on the stack, ;; discards them.
3 is pushed on the stack.
# begins a comment until the end of the line.

6 o'clock

6
;
]
9
#
3
;
;
1
2
1
;
;
3
#
9
]
;
6

Try it online!

How it works

6 is pushed on the stack, ; discards it.
] wraps the stack in an array (does not affect output).
9 and 3 are pushed on the stack, ; and ; discard them.
1, 2 and 1 are pushed on the stack.
; and ; discard the last 1 and 2.
3 and 9 are pushed on the stack.
] and ; wrap the stack in an array and discard it, clearing the stack.
6 is pushed on the stack.

9 o'clock

#########6
#########;
#########]
#########9
##########
#########3
#########;
#########;
#########1
6;]9#3;;12

Try it online!

How it works

All lines but the last are comments.
6 is pushed on the stack, ; discards it.
] wraps the stack in an array (does not affect output).
9 is pushed on the stack.
# begins a comment until the end of the line.


Python 2, 59 bytes

n=input()
c=~n%2
while c<n:print`n%10`*n+`c%10`*c;n-=1;c+=1

Try it online!

Prints like:

55555
44441
33322

It looks kind-of redundant to update n-=1;c+=1 where sum n+c remains unchanged. I feel like there's a better way, but I haven't seen it so far. Bounty is up for grabs!

60 bytes

n=input()
b=a=n/2
while n-b:b+=1;print`a%10`*a+`b%10`*b;a-=1

Try it online!

Prints like:

22333
14444
55555

Based on ideas by @newbie.


JavaScript (Node.js), 482 bytes

This is a brute-force solution, it starts at 01 and checks every neighbouring cell checking for empty cells (--) or the desired number and following the path to completion or impossibility. If the desired number exists and isn't a neighbour it shortcuts this solution. Takes a few seconds for the largest grid.

This probably isn't particularly interesting, but I thought I'd try my hand at making a solution before looking at the answers linked on Rosetta Code and I enjoyed tackling a slightly more difficult challenge!

Finds all solutions when many exist. The body is a function that accepts a two dimensional array and the footer processes the input to the desired format, and returns the result to the desired format too. Happy to provide more information (and a less golfed implementation if there's interest).

f=a=>{F=(D,n,j)=>[Z=[].concat(...D),z=Z.indexOf(j),z>-1&&[x=z%w,y=z/w|0],z>-1&&[[x-1,y-1],[x,y-1],[x+1,y-1],[x-1,y],[x+1,y],[x-1,y+1],[x,y+1],[x+1,y+1]]][n];C=q=>q.map(Q=>Q.slice());w=a[0][L='length'];l=F(a,0).filter(c=>c!='XX')[L];R=[];r=(s,d)=>{let n=`0${+s+1}`.slice(-2);N=F(d,2,n);n>l?R.push(C(d)):~F(d,1,s)?(p=F(d,3,s),p.filter(P=>P==N+'')[L]?r(n,C(d)):!~F(d,1,n)?p.map(I=>{[x,y]=I,(x<0||x>w-1||y<0||y>d[L]-1)||d[y][x]=='--'&&(D=C(d),r(D[y][x]=n,D))}):0):0};r('01',a);return R}

Try it online!


APL, 77

p←?3⋄d[e[?⍴e←(⍳3)~p,c←⍞⍳⍨⎕←d←3↑⎕A]]←'_'⋄⎕←d⋄⎕←'You','lost' 'won!'[(c=p)=5=⍴⍞]

Needs ⎕IO←0. Tested on Dyalog.

Explanation

p←?3                       ⍝ p(rize) is a random number between 1 and 3
⎕←d←3↑⎕A                   ⍝ d(oors) is the string 'ABC'; output it
c←d⍳⍞                      ⍝ ask for one of the letters; c(hoice) is its position
o←e[?⍴e←(⍳3)~p,c]          ⍝ o(pen) is a random position except for p and c
d[o]←'_'                   ⍝ replace the o position in the d string with a '_'
⎕←d                        ⍝ output the modified d string
w←(c=p)=5=⍴⍞               ⍝ get choice, if it's stick (5 chars) and c=p, or neither, (w)in
⎕←'You','lost' 'won!'[w]   ⍝ print the result

Examples

      p←?3⋄d[e[?⍴e←(⍳3)~p,c←⍞⍳⍨⎕←d←3↑⎕A]]←'_'⋄⎕←d⋄⎕←'You','lost' 'won!'[(c=p)=5=⍴⍞]
ABC
A
AB_
stick
You lost
      p←?3⋄d[e[?⍴e←(⍳3)~p,c←⍞⍳⍨⎕←d←3↑⎕A]]←'_'⋄⎕←d⋄⎕←'You','lost' 'won!'[(c=p)=5=⍴⍞]
ABC
A
AB_
stick
You won!


Jelly, 27 25 bytes
2 bytes thanks to Jonathan Allan.
²IH;Pµ;ÆḊ
+2ḶḤ‘Œcg/ÐṂÇ€Ṣḣ

Try it online!
Outputs the first n 1-indexed triples [b, a, c], sorted by increasing b and then a.
Uses the algorithm from Wikipedia:

This generates all primitive triples for all unique coprime pairs of odd integers m > n > 0.
Explanation
+2ḶḤ‘Œcg/ÐṂÇ€Ṣḣ    Main link. Argument: n
+2                   Add 2 to n, to get enough results.
  Ḷ                  Get integers [0, 1, ..., n+1].
   Ḥ                 Double to get [0, 2, ..., 2n+2].
    ‘                Increment to get [1, 3, ..., 2n+3].
     Œc              Get all ordered pairs [[1, 3], [1, 5], ..., [2n+1, 2n+3]].
       g/            GCD of each pair.
         ÐṂ          Grab the pairs with minimal GCD (which is 1).
           Ç€        Call the helper link on each pair to get the triples.
             Ṣ       Sort the triples first by a, then by b, then by c.
              ḣ      Get the last n.

²IH;Pµ;ÆḊ    Helper link. Argument: pair [m, n]
²              Square to get [m², n²].
 I             Increments: get [m²-n²].
  H            Halve: get [(m²-n²)/2], i.e. [b].
    P          Product: get mn, i.e. a.
   ;           Append to get [b, a].
     µ         Begin a new monadic chain with argument [b, a].
       ÆḊ      Get the length of the vector, i.e. c.
      ;        Append to get [b, a, c].


K, 4 bytes

#,/\

In K, ,/ will join all the elements of a list. The common idiom ,// iterates to a fixed point, flattening an arbitrarily nested list completely. ,/\ will iterate to a fixed point in a similar way, but gather a list of intermediate results. By counting how many intermediate results we visit before reaching the fixed point (#), we get the answer we want: the maximum nesting depth.

"Count of join over fixed-point scan".

In action:

 (#,/\)'(,1
        1 2 3
        ,1 2 3
        (3;(3;,3;3);3)
        ,((,1;2);(3;,4)))
1 1 2 3 4


JavaScript (ES6) 318 321
Edit Bug fix (managing leading 0s) and golfed more
Credit for the camel case trick @Core1024
With input/output via popup
alert((n=prompt(),w='ZéroUnDeuxTroisQuatreCinqSixSeptHuitNeufDixOnzeDouzeTreizeQuatorzeQuinzeSeizeDix-septDix-huitDix-neufVingtTrenteQuaranteCinquanteSoixante'.match(/[A-Z][^A-Z]+/g),
u=n%10,s=u-1|n>80?d='-':' et ',n>99?'Cent':n<21?w[n|0]:n<70?w[18+n/10|0]+(u?s+w[u]:''):(n<80?w[24]:w[4]+d+w[20])+(n-80?s+w[n%20]:'s')))

As a testable function
F=n=>(
  w='ZéroUnDeuxTroisQuatreCinqSixSeptHuitNeufDixOnzeDouzeTreizeQuatorzeQuinzeSeizeDix-septDix-huitDix-neufVingtTrenteQuaranteCinquanteSoixante'
  .match(/[A-Z][^A-Z]+/g),
  u=n%10,s=u-1|n>80?d='-':' et ',
  n>99?'Cent':
  n<21?w[n|0]:
  n<70?w[18+n/10|0]+(u?s+w[u]:''):
  (n<80?w[24]:w[4]+d+w[20])+(n-80?s+w[n%20]:'s')
)

To Test In FireFox console or FireBug
for (i = 0; i < 100; console.log(r),i+= 10)
  for (j=0, r=''; j < 10; j++)
    r+=(i+j)+':'+F(i+j+'')+", "; // specific: input is a string
F('100')

Test Output

0:Zéro, 1:Un, 2:Deux, 3:Trois, 4:Quatre, 5:Cinq, 6:Six, 7:Sept, 8:Huit, 9:Neuf,
10:Dix, 11:Onze, 12:Douze, 13:Treize, 14:Quatorze, 15:Quinze, 16:Seize, 17:Dix-sept, 18:Dix-huit, 19:Dix-neuf,
20:Vingt, 21:Vingt et Un, 22:Vingt-Deux, 23:Vingt-Trois, 24:Vingt-Quatre, 25:Vingt-Cinq, 26:Vingt-Six, 27:Vingt-Sept, 28:Vingt-Huit, 29:Vingt-Neuf,
30:Trente, 31:Trente et Un, 32:Trente-Deux, 33:Trente-Trois, 34:Trente-Quatre, 35:Trente-Cinq, 36:Trente-Six, 37:Trente-Sept, 38:Trente-Huit, 39:Trente-Neuf,
40:Quarante, 41:Quarante et Un, 42:Quarante-Deux, 43:Quarante-Trois, 44:Quarante-Quatre, 45:Quarante-Cinq, 46:Quarante-Six, 47:Quarante-Sept, 48:Quarante-Huit, 49:Quarante-Neuf,
50:Cinquante, 51:Cinquante et Un, 52:Cinquante-Deux, 53:Cinquante-Trois, 54:Cinquante-Quatre, 55:Cinquante-Cinq, 56:Cinquante-Six, 57:Cinquante-Sept, 58:Cinquante-Huit, 59:Cinquante-Neuf,
60:Soixante, 61:Soixante et Un, 62:Soixante-Deux, 63:Soixante-Trois, 64:Soixante-Quatre, 65:Soixante-Cinq, 66:Soixante-Six, 67:Soixante-Sept, 68:Soixante-Huit, 69:Soixante-Neuf,
70:Soixante-Dix, 71:Soixante et Onze, 72:Soixante-Douze, 73:Soixante-Treize, 74:Soixante-Quatorze, 75:Soixante-Quinze, 76:Soixante-Seize, 77:Soixante-Dix-sept, 78:Soixante-Dix-huit, 79:Soixante-Dix-neuf,
80:Quatre-Vingts, 81:Quatre-Vingt-Un, 82:Quatre-Vingt-Deux, 83:Quatre-Vingt-Trois, 84:Quatre-Vingt-Quatre, 85:Quatre-Vingt-Cinq, 86:Quatre-Vingt-Six, 87:Quatre-Vingt-Sept, 88:Quatre-Vingt-Huit, 89:Quatre-Vingt-Neuf,
90:Quatre-Vingt-Dix, 91:Quatre-Vingt-Onze, 92:Quatre-Vingt-Douze, 93:Quatre-Vingt-Treize, 94:Quatre-Vingt-Quatorze, 95:Quatre-Vingt-Quinze, 96:Quatre-Vingt-Seize, 97:Quatre-Vingt-Dix-sept, 98:Quatre-Vingt-Dix-huit, 99:Quatre-Vingt-Dix-neuf,
"Cent"


Python 2, 24 bytes

lambda n:`n*1L`in`n**2L`

Try it online!

For the first time in history, Python 2's appending an L to the repr of longs is a feature rather than a bug.

The idea is to check if say, 76^2=5776 ends in 76 by checking if 76L is a substring of 5776L. To make the L appear for non-huge numbers, we multiply by 1L or have 2L as the exponent, since an arithmetic operation with a long with produces a long.


C & C++, 1922 1216 bytes/chars (BMP only 1451 1005 bytes/chars)

This is the "shortest" solution that came to mind that is both valid C and C++ and that supports all of Unicode version 6.1, not just the BMP:

int s[]={-74,-68,31054,-50,-49,-48,-47,-46,-44,-43,-39,-38,-37,-34,-33,-32,-30,-29,-28,-27,-26,-25,-24,-23,-22,-17,-16,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,19,20,27,28,29,53195,31,34,36,42,49,50,52,54,58,59,62,64,66,73,81,98,102,103,140,194,263,275,290,1066,1222,1230,2685,2732,2890,3379,6009,21254,22391,30996,53209};
char l[]="l5Hf`7HIAH2IH@IH7IJFIFHJIJKHLJKFHFJFIJIHIJKIJHJFHNFJ@IH?IHJIK1IBHFJHILDI!HI4HpIFKFHWZ-HIHKFH<IDHIFJHc&H9IQ4IJBIH(Ie+H{)Hh<HI.Hn I@H$I@HPCHRAHPAHPCHRAHPAHP;HJAHPAHPAHPDHIHNKFHIHPEHJHPAHRFHIHrKHKZFLJHPEHLdx'HJKHEILIHICHM$IHOILT,HIM~8IX=IoBIFH/IAHFIJDILIJIUDIk|BHTDHt5Hv*H\\5HYBHI9HY5HYEHFIBHI>HY5HY5HY5HY5HY5HY5HY5HY5HY3H[6HICHY6HICHY6HICHY6HICHY6HICHIG";
char u[]="i5Hm8HIBH^3IJAIJ7IHFIKHFIHIFHJEHIHIFHKHIHEIHIJIHIFHFIHKOEJAIJ@IFJIFH1IOHIHJIEHDIsIKVIFHFIHI:HI@H_JFHK=IMJIHJ#Ha:IQ3IHBIJ)IR,Hy,HIMz IQ%IQAHPCHRAHPAHPCHSEIPAHjEHTEHTEHTDHSEHqLKFHJFHJKDHNEIEHJEHRHMgw'HbIFHJEIEHIJPFH$IPIL\"8IX=IoBIK0IRFIHDILIJIUCI}5Hu*H\1775HY5HY5HYIHFJHJEHIAHY5HYHIEHJAHIBHZHIEHIDHIKBHZ5HY5HY5HY5HY5HY5H]6H^6H^6H^6H^6H^G";
int x(int a,char*p){int c=0,i=0,b=-1;while(c>0||s[*p-32]){if(!c)c=s[*p-32]<0?-s[*p++-32]:1,i=s[*p++-32];b+=i,--c;if(a==b)return 1;}return 0;}

Please note that "shortest" in this case does not mean that the solution is in any way efficient; it simply means that it is the shortest source code solution. It does not require any Unicode support in the standard library, and in fact does not use the standard library at all. (Which I now understand is what code golf means ... I'm a newbie around here, what can I say.)

To build the lower and upper case data tables I worked as follows:

Downloaded UnicodeData.txt.
Extracted a list of all lines that included the text ";Ll;" or ";Lu;" to indicate a lower case letter or upper case letter respectively.
Built two vectors of code points using the data from step 2.
Converted each absolute code point value to a relative value, the difference between the previous code point and this code point. Because it is convenient for the difference to always be a positive integer (not zero or negative), I use -1 as the value of the first previous code point. In this way zero will not appear anywhere in the sequence.
Used a form of run length encoding to compress runs of identical values into a pair of values. If the next value appears two or more times consecutively, replace the sequence with the negative of the length of the sequence and the value. Otherwise the value only appears once, so just use it as is.
Terminated the compressed vector with zero to mark the end of the sequence.
I noticed there were 96 unique values in the run length encoded vectors, so I built an array of the unique integers and used the index into that array for the lower and upper case vectors.

The above process compressed the vector of lower case code points from 1751 unique values to 350 mostly small non-unique values. In like fashion, the upper case code point vector went from 1441 values to 331 values.

Next I wrote the unique value vector out as a comma separated list of integers suitable for including in source code. I assumed int was 32 bits to avoid using long so that I could save an additional four characters / bytes of source code. Then I wrote out the lower and upper case vectors as strings, where each character in the string has a code 32 greater than its index into the unique integer array. This saves about half the characters necessary to encode the lower & upper case array through omission of comma characters. Three of the characters used have to be escaped (\", \, and \177). They are assigned to unique integers that only appear once in the data so as to minimize the size of the string literals.

What I wound up with was a global array of integers, two global arrays of characters, and a function. An array named s for the unique signed integers, an array named u for the character based upper case code point indexes, and another array named l for the character based lower case code point indexes. The function x takes code point a and pointer to an array of characters p and returns 1 if the code point is in the decompressed / normalized array of code points or 0 otherwise.

If you want to determine if code point cp is lower case, you call "x(cp, l)". If you want to determine if it is upper case, you call "x(cp, u)".

Since the point to this exercise is to make the smallest code to accomplish the task, I never save the decompressed / normalized data. I decompress it piecemeal as I need it every time I call it.

It would be possible to terminate the while loop early if the code point I'm checking has already been passed by during decompression. That would add extra code so I didn't bother, deciding I'd rather pay the speed penalty.

I admit the code is ugly. I did not write it this way originally. Here is the C++ version that I derived the compact C version from:

const int Ii[] = {-74,-68,31054,-50,-49,-48,-47,-46,-44,-43,-39,-38,-37,-34,-33,-32,-30,-29,-28,-27,-26,-25,-24,-23,-22,-17,-16,-13,-12,-11,-10,-9,-8,-7,-6,-5,-4,-3,-2,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,16,19,20,27,28,29,53195,31,34,36,42,49,50,52,54,58,59,62,64,66,73,81,98,102,103,140,194,263,275,290,1066,1222,1230,2685,2732,2890,3379,6009,21254,22391,30996,53209};
const char Ll[] = "l5Hf`7HIAH2IH@IH7IJFIFHJIJKHLJKFHFJFIJIHIJKIJHJFHNFJ@IH?IHJIK1IBHFJHILDI!HI4HpIFKFHWZ-HIHKFH<IDHIFJHc&H9IQ4IJBIH(Ie+H{)Hh<HI.Hn I@H$I@HPCHRAHPAHPCHRAHPAHP;HJAHPAHPAHPDHIHNKFHIHPEHJHPAHRFHIHrKHKZFLJHPEHLdx'HJKHEILIHICHM$IHOILT,HIM~8IX=IoBIFH/IAHFIJDILIJIUDIk|BHTDHt5Hv*H\\5HYBHI9HY5HYEHFIBHI>HY5HY5HY5HY5HY5HY5HY5HY5HY3H[6HICHY6HICHY6HICHY6HICHY6HICHIG";
const char Lu[] = "i5Hm8HIBH^3IJAIJ7IHFIKHFIHIFHJEHIHIFHKHIHEIHIJIHIFHFIHKOEJAIJ@IFJIFH1IOHIHJIEHDIsIKVIFHFIHI:HI@H_JFHK=IMJIHJ#Ha:IQ3IHBIJ)IR,Hy,HIMz IQ%IQAHPCHRAHPAHPCHSEIPAHjEHTEHTEHTDHSEHqLKFHJFHJKDHNEIEHJEHRHMgw'HbIFHJEIEHIJPFH$IPIL\"8IX=IoBIK0IRFIHDILIJIUCI}5Hu*H\1775HY5HY5HYIHFJHJEHIAHY5HYHIEHJAHIBHZHIEHIDHIKBHZ5HY5HY5HY5HY5HY5H]6H^6H^6H^6H^6H^G";

bool isXx(int cp, const char* Xx)
{
    int count = 0, step = 0, code = -1;

    while ((count > 0) || (Ii[*Xx-32] != 0))
    {
        if (count == 0)
        {
            count = (Ii[*Xx-32] < 0) ? -(Ii[*(Xx++)-32]) : 1;
            step = Ii[*(Xx++)-32];
        }

        code += step;
        --count;

        if (cp < code)
            break;

        if (cp == code)
            return true;
    }

    return false;
}

inline bool isLl(int cp)
{
    return isXx(cp, Ll);
}

inline bool isLu(int cp)
{
    return isXx(cp, Lu);
}

In the end, the compact version takes 1922 1216 bytes (including CR+LF end of line sequences). The original version only takes 2271 1578 bytes.

To put this in context of the other solutions that only support the BMP, the equivalent compact version only takes 1451 1005 bytes (or 1800 1367 bytes for the original version).


There's a nice polynomial expression modulo 7 for the third side given two sides a and b.

$${3(a^3b - ab^3) \mod 7}$$

or factored

$${3ab(a^2-b^2) \mod 7}$$

The modulo 7 maps to a remainder in {0,1,2,3,4,5,6}.

I explain why it works in this Math SE answer, though I do think there probably is a cleaner argument I'm missing. The only other two-term polynomial that works is

$${(3a^5b^5 - a^3b) \mod 7}$$

which I originally found by transforming my bit-bashing into arithmetic operations, then did a brute-force search over polynomials of this form to find the nicer one.

Please feel free to add ports of this into your favorite language; this is a CW post.

J, 9 by Synthetica

7|3***+*-

See my post

Dyalog APL, 9 by ngn (typo fixed by Adám)

7|3×××+×-

Blatantly stolen from above J answer.

TI-Basic, 14 by Timtech

7fPart((A³B-AB³)/21

Pyth, 16 by FryAmTheEggman

M%*3-*H^G3*^H3G7

Defines a function g of two values.

Golfscript, 18 by Peter Taylor (old polynomial)

~1$*.5?3*@.*@*- 7%

CJam, 18 by Martin Büttner (ported from Peter's GolfScript) (old polynomial)

l~1$*_5#3*@_*@*m7%

Mathematica, 20 by Martin Büttner

Mod[+##(#-#2)3##,7]&

Yes, that's a unary plus, and no, there's no shorter way that doesn't use a unary plus.

dc, 21 by Toby Speight

sb7+d3^lb*rlb3^*-3*7%

I have to add 7 to a to ensure the difference is always positive (dc has a signed % operator).

Julia, 24 23 by Martin Büttner

f(a,b)=3a*b*(a^2-b^2)%7

CoffeeScript, 28 26 by rink.attendant.6

x=(a,b)->3*a*b*(a*a-b*b)%7

JavaScript (ES6), 28 26 by rink.attendant.6

x=(a,b)=>3*a*b*(a*a-b*b)%7

Essentially the same as CoffeeScript.

Python 28, by xnor

lambda a,b:3*a*b*(a*a-b*b)%7

Bash, 31

Nothing special:

echo $[3*($1**3*$2-$1*$2**3)%7]

or alternatively:

echo $[3*$1*$2*($1*$1-$2*$2)%7]

Another (longer but perhaps interesting) approach.

Nim, 36 by Sillesta

proc(x,y:int):int=3*x*y*(x*x-y*y)%%7

Java 7, 46 44 by rink.attendant.6

int f(int a,int b){return(a*a-b*b)*a*b*3%7;}

Java 8, 25 23 by Kevin Cruijssen

a->b->(a*a-b*b)*a*b*3%7

PHP, 49 47 by rink.attendant.6

function x($a,$b){echo($a*$a-$b*$b)*3*$a*$b%7;}

Batch, 52 unclemeat

set/aa=(3*(%1*%1*%1*%2-%1*%2*%2*%2)%%7+7)%%7
echo %a%

CMD does not support true modulus natively (so can't handle negative numbers) - hence %%7+7)%%7.

LESS (as a parametric mixin), 62 60 by rink.attendant.6

.x(@a,@b){@r:mod(3*@a*@b*(@a*@a-@b*@b),7);content:~"'@{r}'"}

See my post below.

05AB1E, 10 8 by Emigna (-2 bytes by Kevin Cruijssen)

nÆs`3P7%

Try it online.

Haskell, 31 27 25 by Generic Display Name

a#b=3*a*b*(a*a-b*b)`mod`7

Try it online!

Excel, 27 by by Wernisch

=MOD(3*(A1^3*B1-A1*B1^3),7)

Excel VBA, 25 by Taylor Scott

?3*[A1^3*B1-A1*B1^3]Mod 7

Forth (gforth) 41 by reffu

: f 2>r 2r@ * 2r@ + 2r> - 3 * * * 7 mod ;

Try it online!

C#, 23 by Kevin Cruijssen

a=>b=>(a*a-b*b)*a*b*3%7


Jelly, 8 bytes

ÆlÐĿĊḊi1

Try it online! or verify all test cases.

Background

We start by successively taking natural logarithms of the input and the subsequent results until the result no longer changes. This works because the extension of the natural logarithm to the complex plane has a fixed point; if z = e-W(-1) ≈ 0.318 + 1.337i – where W denotes the Lambert W function – we have log(z) = z.

For input n, after computing [n, log(n), log(log(n)), …, z], we first apply the ceiling function to each of the results. Jelly's implementation (Ċ) actually computes the imaginary part of complex number instead†, but we're not interested in these anyway.

Once the kth application of log yields a value less than or equal to 1, Ċ will return 1 for the first time. The 0-based index of that first 1 is the desired result.

The straightforward implementation (compute 1-based index, decrement) fails because of edge case 0, which does not have a 1 in its list of logarithms. In fact, for input 0, the sequence of logarithms is

[0, None]

This is because Jelly's logarithm (Æl) is overloaded; it first tries math.log (real logarithm), then cmath.log (complex logarithm), and finally "gives up" and returns None. Fortunately, Ċ is similarly overloaded and simply returns it argument if it cannot round up or take an imaginary part.

Likewise, input 1 returns

[1, 0, None]

which may create problems in other approaches that do or do not involve Ċ.

One way to fix this problem is apply Ḋ (dequeue; removes first element) to the array of logarithms. This maps

0ÆlÐĿ -> [0, None]    -> [None]
1ÆlÐĿ -> [1, 0, None] -> [0, None]

so neither list has a 1 now. This way, finding the index of the first 1 will return 0 (not found), which is the desired output for inputs 0 and 1.

How it works

ÆlÐĿĊḊi1  Main link. Argument: n (non-negative integer)

  ÐĿ      Apply the following link until the results are no longer unique.
Æl          Natural logarithm.
          Return the array of all unique results.
    Ċ     Round all resulting real numbers up to the nearest integer. This takes
          the imaginary part of complex numbers and does nothing for non-numbers.
     Ḋ    Dequeue; remove the first item (n) of the array of results.
      i1  Find the first index of 1 (0 if not found).

† This is one of the only three atoms in Jelly that are overloaded in a non-obvious manner.


Python 3, HyperNeutrino

from random import*
def r(i):
    s=len(i)//2;L,R=i[:s][::-1],i[s:][::-1];o=[]
    while L and R:s=randint(1,len(L));o+=L[:s];L,R=R,L[s:]
    return o+L+R

Try it online!
Proof of Same Character Set


Javascript tips: 2 to the power of x multiplied by n

17 bytes:

puzzle=n=>x=>n<<x

This uses the fact that 2 * 2^n = 2^(n + 1). Also, by our rules, using currying instead of taking multiple arguments the usual way is allowed. Also, I don't think the let is needed.


V, 17 16 15 bytes

i[´.¶ ]<esc>ògó$X|p

<esc> is 0x1b.

And the hexdump:

00000000: 695b b42e b620 5d1b f267 f324 587c 70    i[... ]..g.$X|p

Explanation

i                       " Insert
[                       " a [
´.                      " 4 .s
¶<space>                " 6 spaces
]<esc>                  " and a ]. Then return to normal mode
ò                       " Recursively do:
 gó                     "  Sleep for 100 milliseconds
 $                      "  Go to the ]
 X                      "  Delete the character to the left of the ]
 |                      "  Go to the [
 p                      "  And paste the deleted character right after the [
                        " Implicit ending ò


Any REPL with caret XOR operation, 5 bytes

11^11

11^11 is of course 0. The only other possibilities are 1^11 or 11^1 which are 10, or 1111 which produces itself.


Score with test 1: 38.6%, Score with test 2: 4.9%

Compressor

Jelly, 97 bytes

ṡ2ṢŒɠżQƊ1ị>ɗƇ3NÞḣ8Ṫ€,‘ɼ$€Ẏœṣ;@W}ɗjƭƒ
7©ṛ⁸“i</*jpov”iⱮ’Ç31¡
“i</*jpov”iⱮḅ8b256,ÇĖF€LÞḢL;L};÷/$ʋ,ḷɗ

Try it online!

Decompressor

Jelly, 44 bytes

ḅ256ḃ8
ḣ3s2ṚṣḢ}©¥jƭƒṫ5µṛ®n8Ɗ¿‘
ḢĿị“i</*jpov”

Try it online!

Explanation

Uses two different methods and picks the one with the shortest output.

Method 1: Convert the input from base 8 to base 256
Method 2: Repeatedly finds the 8 most common sublists of length 2 and replaces them with an integer between 8 and 255. The dictionary is stored at the beginning of the output.

The first byte of the output indicates the method used.

Input to compressor is a string of Malbolge. Output is a list of integers between 0 and 255. This could easily be encoded in Jelly’s code page if preferred. Input and output to/from decompressor mirror the compressor.


Generate TeX to typeset Sierpinski Triangle Fractal

Python 2, 32 bytes

exec"print'x'"+".join('{^_}')"*5

Try it online!


Mathematica, 18 bytes, up to ~168.15 trillion dimensions

Pi^(a=.5#)/a!#2^#&

Anonymous function. Takes two numbers as input, and returns an inexact number as output. Works with any number of dimensions. Outputs 1. for n = 0. Uses the formula from Volume of an n-ball on Wikipedia.

Explanation

We are attempting to compute πn/2/Γ(n/2 + 1)·Rn, or N[Pi^(n/2)/Gamma[n/2 + 1] R^n] in Mathematica. In our case, # (first argument) is n and #2 (second argument) is R. This leaves us with N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &, which can be golfed as follows:

N[Pi^(#/2)/Gamma[#/2 + 1] #2^#] &
Pi^(.5#)/Gamma[.5# + 1] #2^# &    (* replace exact with approximate numbers*)
Pi^(.5#)/(.5#)! #2^# &            (* n! == Gamma[n + 1] *)
Pi^(a=.5#)/a! #2^# &              (* replace repeated .5# *)
Pi^(a=.5#)/a!#2^#&                (* remove whitespace *)

and thus, our original program.


Haskell, 12 bytes

(<*>).map(,)

Try it online!


C and C++ (gcc), 117 107 bytes

-10 bytes thanks to @Steadybox!

#include<stdio.h>
int f(int a,int b){auto c=.5;a-b&&printf("%d %d",c?b<a?b:a:a>b?a:b,c?a-b>0?a-b:b-a:a+b);}

Explanation: In C, auto c=.5 declares an integer variable with the auto storage class (which is the default), which is then initialized to 0, whereas in C++11 it declares a double, which is initialized to 0.5. So the variable's value will be truthy in C++ and falsy in C.

C - max language: Try it online!

C++ - min language: Try it online!


Generate a number by using a given list of numbers and arithmetic operators

Python 2.7 / 478 chars

L=[17,5,9,17,59,14]
O={'+':7,'-':3,'*':5,'/':1}
N=569
P=eval("{'+l+y,'-l-y,'*l*y,'/l/y}".replace('l',"':lambda x,y:x"))
def S(R,T):
 if len(T)>1:
  c,d=y=T.pop();a,b=x=T.pop()
  for o in O:
   if O[o]>0 and(o!='/'or y[0]):
    T+=[(P[o](a, c),'('+b+o+d+')')];O[o]-=1
    if S(R,T):return 1
    O[o]+=1;T.pop()
  T+=[x,y]
 elif not R:
  v,r=T[0]
  if v==N:print r
  return v==N
 for x in R[:]:
  R.remove(x);T+=[x]
  if S(R,T):return 1
  T.pop();R+=[x]
S([(x,`x`)for x in L],[])

The main idea is to use postfix form of an expression to search. For example, 2*(3+4) in postfix form will be 234+*. So the problem become finding a partly permutation of L+O that evalates to N.

The following version is the ungolfed version. The stack stk looks like [(5, '5'), (2, '5-3', (10, ((4+2)+(2*(4/2))))].

L = [17, 5, 9, 17, 59, 14]
O = {'+':7, '-':3, '*':5, '/':1}
N = 569

P = {'+':lambda x,y:x+y,
     '-':lambda x,y:x-y,
     '*':lambda x,y:x*y,
     '/':lambda x,y:x/y}

def postfix_search(rest, stk):
    if len(stk) >= 2:
        y = (v2, r2) = stk.pop()
        x = (v1, r1) = stk.pop()
        for opr in O:
            if O[opr] > 0 and not (opr == '/' and v2 == 0):
                stk += [(P[opr](v1, v2), '('+r1+opr+r2+')')]
                O[opr] -= 1
                if postfix_search(rest, stk): return 1
                O[opr] += 1
                stk.pop()
        stk += [x, y]
    elif not rest:
        v, r = stk[0]
        if v == N: print(r)
        return v == N
    for x in list(rest):
        rest.remove(x)
        stk += [x]
        if postfix_search(rest, stk):
            return True
        stk.pop()
        rest += [x]
postfix_search(list(zip(L, map(str, L))), [])