Regex validating regex Build a regex that will accept a regex string as input and check if it's valid. Basically, your regex should be able to validate itself. (Any invalid regex should not be validated, so you can't use .*. ;))

Your flavor must be fully supported by well known implementations (Perl, sed, grep, gawk, etc), and it must fully support what those implementations support. [Don't worry about the lawyer speak; I'm just trying to remove any possible loopholes for the smart***es.]

I'd code-golf it, but I'm worried it'll give an edge to those who know and use non-feature-rich flavors. Or are my worries unfounded?

Ruby

I tried to match the actual syntax of Ruby's regex flavor as much as possible, but there are a few quirks: it accepts a few lookbehinds that are actually invalid (like (?<=(?<!))), and it recognizes empty character ranges like D-A. The latter could be fixed for ASCII, but the regex is long enough as it is.

\A(?<main>
    (?!
        \{(\d+)?,(\d+)?\} # do not match lone counted repetition
    )
    (?:
        [^()\[\]\\*+?|<'] | # anything but metacharacters
        (?<cclass>
            \[ \^? (?: # character class
                (?: # character class
                    [^\[\]\\-] | # anything but square brackets,  backslashes or dashes
                    \g<esc> |
                    \[ : \^? (?: # POSIX char-class
                        alnum | alpha | word | blank | cntrl | x?digit | graph | lower | print | punct | space | upper
                    ) : \] |
                    - (?!
                        \\[dwhsDWHS]
                    ) # range / dash not succeeded by a character class
                )+ |
                \g<cclass> # more than one bracket as delimiter
            ) \]
        ) |
        (?<esc>
            \\[^cuxkg] | # any escaped character
            \\x \h\h? | # hex escape
            \\u \h{4} | # Unicode escape
            \\c . # control escape
        ) |
        \\[kg] (?:
            < \w[^>]* (?: > | \Z) |
            ' \w[^']* (?: ' | \Z)
        )? | # named backrefs
        (?<! (?<! \\) \\[kg]) [<'] | # don't match < or ' if preceded by \k or \g
        \| (?! \g<rep> ) | # alternation
        \( (?: # group
            (?:
                \?
                (?:
                    [>:=!] | # atomic / non-capturing / lookahead
                    (?<namedg>
                        < [_a-zA-Z][^>]* > |
                        ' [_a-zA-Z][^']* ' # named group
                    ) |
                    [xmi-]+: # regex options
                )
            )?
            \g<main>*
        ) \) |
        \(\?<[!=] (?<lbpat>
            (?! \{(\d+)?,(\d+)?\} )
            [^()\[\]\\*+?] |
            \g<esc>  (?<! \\[zZ]) |
            \g<cclass> |
            \( (?: # group
                (?:
                    \?: |
                    \? \g<namedg> |
                    \? <[!=]
                )?
                \g<lbpat>*
            ) \) |
            \(\?\# [^)]* \)
        )* \)
        |
        \(\? [xmi-]+ \) # option group
        (?! \g<rep> )
        |
        \(\?\# [^)]*+ \) # comment
        (?! \g<rep> )
    )+
    (?<rep>
        (?:
            [*+?] | # repetition
            \{(\d+)?,(\d+)?\} # counted repetition
        )
        [+?]? # with a possessive/lazy modifier
    )?
)*\Z

Unreadable version:

\A(?<main>(?!\{(\d+)?,(\d+)?\})(?:[^()\[\]\\*+?|<']|(?<cclass>\[\^?(?:(?:[^\[\]\\-]|\g<esc>|\[:\^?(?:alnum|alpha|word|blank|cntrl|x?digit|graph|lower|print|punct|space|upper):\]|-(?!\\[dwhsDWHS]))+|\g<cclass>)\])|(?<esc>\\[^cuxkg]|\\x\h\h?|\\u\h{4}|\\c.)|\\[kg](?:<\w[^>]*(?:>|\Z)|'\w[^']*(?:'|\Z))?|(?<!(?<!\\)\\[kg])[<']|\|(?!\g<rep>)|\((?:(?:\?(?:[>:=!]|(?<namedg><[_a-zA-Z][^>]*>|'[_a-zA-Z][^']*')|[xmi-]+:))?\g<main>*)\)|\(\?<[!=](?<lbpat>(?!\{(\d+)?,(\d+)?\})[^()\[\]\\*+?]|\g<esc>(?<!\\[zZ])|\g<cclass>|\((?:(?:\?:|\?\g<namedg>|\?<[!=])?\g<lbpat>*)\)|\(\?#[^)]*\))*\)|\(\?[xmi-]+\)(?!\g<rep>)|\(\?#[^)]*+\)(?!\g<rep>))+(?<rep>(?:[*+?]|\{(\d+)?,(\d+)?\})[+?]?)?)*\Z


Shortest way to reverse a number Write a function (or equivalent subprogram) to accept a single integer valued argument and return a (similarly typed) value found by reversing the order of the base-10 digits of the argument.

For example given 76543 return 34567

HTML 21 7 chars (1 char if I'm cheeky...)

&#8238;n

replace n with your number


Find the Shortest Swype Path Introduction

Lately, I've been getting used to typing with Swype.

I've noticed certain words can be produced by drawing a straight line from your starting letter to your ending letter, or by skipping letters that repeat.

For example, I can type the word balloon by Swyping across the following letters:

b > a > l > o > n.

Challenge

Let us define the Shortest Swype Path, or SSP, as the minimum number of distinguishable line segments needed to type a string.  A line segment is a continuous straight line between any two, or more, letters.  Any change in direction starts a new line segment - though some words may be Swyped by drawing only a single straight line.

Use this simple QWERTY keyboard layout:

q w e r t y u i o p
a s d f g h j k l
  z x c v b n m

In the above example, the word balloon will have an SSP of 4 as detailed in the sequence below:

1) Start at `b` (line segments = 0)
2) slide to `a` (line segments = 1)
3) slide to `l` (line segments = 2)
4) slide to `o` (line segments = 3)
5) slide to `n` (line segments = 4)

The string qwerty has SSP = 1 since no change of direction is required when Swyping this word.

Input

A single word string containing any a-z via STDIN, function argument, or command line.

Output

Print via STDOUT, return, or your languages closest alternative, the number n representing the string's SSP.

One trailing newline optional in outut.  Standard loopholes disallowed.  Shortest submission in bytes wins.

Notes

A change in direction starts a new line segment.
Letters that repeat are only counted once (e.g.: bookkeeper should be treated as bokeper).
Normally, Swpye corrects missed letters by looking at neighboring letters and filling in its best guess.  For this challenge, assume there is no natural language augmentations, predictive text or error correction.
Uppercase A-Z inputs are treated like their lowercase counterparts.
Ignore any numbers 0-9 in the input.
Diagonal paths are allowed - that is, a straight line that covers letters o, k, n, for example, count as 1 segment.  This rule applies to any diagonal slope (e.g.: letters c, h, i are in line).

Examples

Input          Output
---------------------
a                0
aa               0
aaaaaa           0
aaaaaabc         2
in               1
int              2
java             3
qwerty           1
chicago          5
balloon          4
BALLOON          4
typewriter       5
bookkeeper       6
stackexchange    11
2hello7          3
2HELLO7          3

CJam, 78 76 73 68 62 bytes

relA,s-:_2ew{:-},{{i"x8LÑejPG ÀÏi"225b28b=A+Ab}/.-:ma}%e`,

Note that the code contains unprintable characters.

Borrowing @isaacg's clever idea of using RLE to count the paths saved 6 bytes.

Try it online in the CJam interpreter. If the link doesn't work, copy the code from this paste.

How it works

rel      e# Read a token from STDIN and cast it to lowercase.
A,s-     e# Remove all digits.
:_       e# Duplicate each element of the argument (string/array).
2ew      e# Push all overlapping slices of length 2.
{:-},    e# Filter out slices where both elements are equal.
{        e# For each slice:
  {      e#   For each character of the slice:
    i    e#     Push its code point.

    "x8LÑejPG ÀÏi"225b28b

         e#     Convert the string from base 225 to base 28, pushing the array
         e#     [15 7 16 17 18 27 26 8 9 0 3 11 4 6 24 1 22 5 21 10 25 23 12 2 13 14].
         e#     These are the positions on the QWERTY keyboard, starting from the
         e#     upper left corner and going right.

    =    e#     Select the element that corresponds to the code point.

         e#     Arrays wrap around in CJam. Since 'a' has code point 97, the array has
         e#     length 26 and 97 % 26 == 19, 'a' corresponds to the 20th element.

    A+Ab e#     Add 10 and convert to base 10. Example: 8 -> [1 8]
  }/     e#
  .-     e#     Vectorized subtraction. [a b] [c d] -> [a-c b-d]
  :ma    e#     atan2. Pushes the angle of the direction. [y x] -> arctan(y/x)
}%       e#
e`       e# Apply run-length encoding.
,        e# Count the runs.


Tips for golfing in Scratch Scratch is a visual programming language. For the sake of counting bytes, Scratch is usually written in scratchblocks2 syntax.

Post tips that specifically apply to Scratch or scratchblocks2.

Abuse the bool type

In Scratch the true and false values are equivalent to 0 and 1, so you can perform arithmetic operations over them. A practical example would be finding the sign of a number:

define f(n
set[r v]to(<(n)>(0)>-<(n)<(0


Block partition a string Inspiration.

Consider a list l, consisting of numbers. Define a block operation at index i on the list l to be the act of moving 3 consecutive elements starting from i in l to the end.

Example:

l, i (1-indexing) -> l (after applying block operation at index i)
[1,2,3,4,5], 1 -> [4,5,1,2,3]
[1,2,3,4,5,6,7], 3 -> [1,2,6,7,3,4,5]

Given a list consisting of only 0 and 1, your challenge is to partition it so that zeros are at the front, and ones are at the back, using only block operations. Output should be the indices in the order they are applied on the list.

Because this is impossible for the list [1,0,1,0], the list length is guaranteed to be at least 5.

Test cases (1-indexing)

(there are other valid outputs)

[1,1,1,0,0] -> [1]
[0,1,0,1,0] -> [1,2,1,1]
[0,0,0,1,1,1,0,0,0] -> [4]

Use this script to generate more test cases. (only input. The rplc ' ';',' part is used to replace spaces with commas in the output)

Winning criteria

code-challenge is the main winning criteria, and fastest-code is the tie-breaker. In particular:

The solution with the shortest output length (least number of block operations) with the test case (n_elem = 500, random_seed = {secret value}) wins. You should be able to run your solution to completion with the test case (n_elem = 500, random_seed = 123456).
In case of ties, the solution that can handles the largest power-of-2 value of n_elem with random_seed = {secret value} within 10 seconds (for me) wins.
In case of ties, the solution that takes less time on that test case wins.


Kind of meta: get the longest of the shortest answers Your task - if you accept it - is to write a program which helps understanding my proposal on meta by calculating the winner of a code-golf-reversed competition. Of course, answers to this question will be treated as proposed, so your program (if correct) can calculate whether your answer will become the accepted answer.

Rules

The program reads a file with multiple lines of the following format (see example below): [Language] TAB [NumberOfCharacters] TAB [LinkToAnswer]
The file name is passed as an argument to your program or the file is redirected to standard input of your program. It's your choice, please mention the method when giving the answer
It's expected that the input format is correct. There's no need for error handling.
The number of characters is positive. Your program must handle lengths up to 65535. 64k should be enough for everybody :-)
The program outputs those lines on standard output which meet the idea of the meta proposal, that is

the shortest code of a particular programming language wins (reduction phase)
the longest code among all programming languages wins (sorting phase)
in case of a draw, all answers with the same length shall be printed

The order of the output is not important
Although the longest code wins, this is not code-bowling. Your code must be as short as possible for your programming language.
Answers on seldom programming languages which are not attempting to shorten the code deserve a downvote, because they try to bypass the intention of this kind of question. If there's only one answer for a specific programming language, it would be considered as a winner candidate, so you could start blowing its code.

Example input file (separated by single tabs if there should be an issue with formatting):

GolfScript  34  http://short.url/answer/ags
GolfScript  42  http://short.url/answer/gsq
C#  210 http://short.url/answer/cs2
Java    208 http://short.url/answer/jav
C#  208 http://short.url/answer/poi
J   23  http://short.url/answer/jsh
Ruby    67  http://short.url/answer/rub
C#  208 http://short.url/answer/yac
GolfScript  210 http://short.url/answer/210

Expected output (order is not important):

C#  208 http://short.url/answer/poi
C#  208 http://short.url/answer/yac
Java    208 http://short.url/answer/jav

Update

Some programs rely on the fact that there is a single maximum (like the C# 210 character program). Derived from reality, someone can also write a GolfScript program with 210 characters. The output would remain the same. I have added such a GolfScript to the input.

Update 2

As suggested I have retagged (still code-golf as well) and the deadline is 2014-03-06 (which looks like an arbitrary date, but I'll be back to Germany from travelling then).

Final results

I decided to vote like the following:

Answers where the number of characters cannot be confirmed get a comment to explain the count.
Answers which can easily be reduced get a comment, an edit suggestion and go into the result with the lower count value. (Hopefully I have seen that in advance).
Answers which do not compile get a downvote. (Quite a hard task as it turns out).
Answers which are not golfed get a downvote (as described in the rules already).
Answers which produce expected output get an upvote. Due to some answers which do not work as expected, I use 4 different input files and check against the expected result.

Finally, the winner is determined by providing the qualifying answers table as input to my reference program (plus double checking the result manually). If my own answer would be the winning one, I'd exclude it from the list.
In case of several winners, I would have to pick only one. Therefore, some bonuses can be earned:

answers which accept more input than expected (e.g. outside the defined ranges)
answers which use a clever idea of making it short

I have taken a snapshot of the answers on 6th of March 2014, 19:45 UTC+1. The analysis is ongoing. Checking all the answers is harder than expected...

Perl, 195 bytes

while(<>){/(\S+)\t(\d+)\t(.+)/;push@{$a{$1}},$3if$2==$l{$1};$l{$1}=$2,$a{$1}=[$3]if $2<($l{$1}//65536)}$m=(sort{$b<=>$a}values%l)[0];map{$l=$_;map{print"$l\t$m\t$_\n"if$l{$l}==$m}@{$a{$l}}}keys%l

Input is expected in STDIN, result is written to STDOUT:

C#      208     http://short.url/answer/poi
C#      208     http://short.url/answer/yac
Java    208     http://short.url/answer/jav

Ungolfed version

#!/usr/bin/env perl
use strict;
$^W=1;

# hash %language remembers the minimum count for a language
# %language: <language> => <minimum count>
my %language;
# hash %array remembers the URLs for the minimum count of the language
# %array: <language> => [<url>, <url>, ....]
my %array;

while(<>){
    # parse input line (no error checking)
    /(\S+)\t(\d+)\t(.+)/;
    my ($lang, $count, $url) = ($1, $2, $3);
    # add URL, if the count is the current minimum for the language
    if ($count == ($language{$lang}//0)) {
    # better, but longer version:
    # if (defined $language{$lang} and $count == $language{$lang}) {
        push @{$array{$lang}}, $url;
    }
    # create a new entry for the language, if there is a new minimum
    if ($count < ($language{$lang}//65536)) {
    # better, but longer version:
    # if (not defined $language{$lang} or $count < $language{$lang}) {
        $language{$lang} = $count;
        $array{$lang} = [$url];
    }
}

# Sort the minimal values in numerical descending order and
# get the first entry as maximum.
my $maximum = (sort { $b <=> $a } values %language)[0];

# Loop over all URLs of minimal answers for the language,
# but print only the entries for the languages with the largest
# minima.
foreach my $lang (keys %language) {
    foreach my $url (@{$array{$lang}}) {
        if ($language{$lang} == $maximum) {
            print "$lang\t$maximum\t$url\n";
        }
    }
}
__END__


Markov Chain Beatbox Generator Just an idea I had the other day: Making beats following a Markov Chain of predefined sounds.

I remember someone did a beatbox with Google Translate and the German language (follow the link and press listen).

So, the challenge is to build a text input to Google Translate from a given chain. Or you can use musical notes and play it yourself :).

You can make a program reading a line with the number of beats, another with their names and a matrix representation of the probabilities (you can choose the representation).

You may also make a function with those three arguments.

E.g.

[input]

20
pv zk bschk kkkk
[[.1, .4, .5, 0.],
 [.3, .2, .3, .2],
 [0., .3, .2, .5],
 [.1, .8, .1, 0.]]

[output] something like:

pv zk bschk zk pv bschk zk pv zk bschk kkkk pv bschk zk bschk bschk bschk zk kkkk bschk

The starting probability is the same for each beat.

That's not a code-golf challenge because I would like to see some nice solutions (be creative).

Extra points if you invent new beats and/or choose a table of probabilities that gives nice beats most of the time.

If you want, you can use real beats (In many languages it's easy to open .wav files, like the wave module in Python) and generate music! Here are some free sample beats.

I may post a reference implementation if needed.

I made these tracks:

http://soundcloud.com/belisarius/sets/golf-music

Using the following transition matrix:

{{10,  1,  3/2, 2},
 {1/2, 10, 3/2, 2},
 {1/2, 1,  10,  2},
 {1/2, 1,  3/2, 10}}

And the following program in Mathematica:

musicGen[n_, notes_, transMatrix_] :=
 Module[{
          im := IdentityMatrix[Length@notes],
          a  := Array[2^(# - 1) &, Length@notes],
          soundLength = .1  n,
          which
          },
  which[x_] := Position[x, 1][[1, 1]];
  Sound[Join[
    (SoundNote /@ notes[[
        which[#] & /@
         NestList[
          RandomChoice[transMatrix[[which@#]] -> im] &,
          RandomChoice@im,
          n - 1]
        ]]
     )
    ],
   soundLength]
  ]
tm = {{10, 1, 3/2, 2}, {1/2, 10, 3/2, 2}, {1/2, 1, 10, 2}, {1/2, 1, 3/2, 10}}
notesSet = {"Snare", {"Slap", "Shaker"}, {"OpenTriangle", "Maracas"}, "RideBell"};
m = Array[If[#2 == 5 || #2 == #1, 10, #2/2] &, {Length@notesSet,Length@notesSet}];
mg = musicGen[100, notesSet, tm]


Create a universal integer sequence Definition

Let's call an (infinite) integer sequence universal if it contains every finite integer sequence as a contiguous subsequence.

In other words, the integer sequence (a1, a2, …) is universal if and only if, for each finite integer sequence (b1, …, bn), there is an offset k such that (ak+1, …, ak+n) = (b1, …, bn).

The sequence of positive prime numbers, for example, is not universal, among others for the following reasons.

It doesn't contain any negative integers, 1, or composite numbers.
Although it contains 3, it does not contain the contiguous subsequence (3, 3, 3).
Although it contains 2 and 5, it does not contain the contiguous subsequence (2, 5).
Although it contains the contiguous subsequence (7, 11, 13), it does not contain the contiguous subsequence (13, 11, 7).

Task

Pick any single universal integer sequence (a1, a2, …) and implement it in a programming language of your choice, abiding to the following rules.

You can submit a full program or a function.
You have three options for I/O:

Take no input and print or return the entire sequence.
Take an index n as input and print or return an.
Take an index n as input and print or return (a1, …, an).

For I/O options 2 and 3, you may use 0-based indexing if you prefer.
Your submission must be deterministic: if run multiple times with the same input, it must produce the same output.

In addition, unless it's immediately obvious, please prove that the sequence you picked is universal. Your proof may not depend on unproven conjectures.

Standard code-golf rules apply. May the shortest code in bytes win!

Husk, 5 bytes
This prints an infinite list
ΣṖ…İ±

Try it online! or find the first index of your sequence. (Takes a lot of memory for most sequences)
Explanation:
   İ±   Infinite list [1,-1,2,-2,3,-3,4,-4,5,-5...]
  …     Rangify       [1,0,-1,0,1,2,1,0,-1,-2,...]
 Ṗ      Powerset
Σ       Concatenate

In Husk Ṗ behaves nicely for infinite lists. You can see it's behaviour here


Create a memory leak, without any fork bombs Your task is to create a memory leak. This is a program that uses loads of memory, until the computer runs out and has to do some swapping to save itself from running out. The only way that the memory can be released is by killing the program in the task manager or using a command line kill such as taskkill /im yourprogram /f (in Windows) or even restarting the computer. Merely closing the app should not prevent it from continuing to hog memory.

Rules:

Fork bombs of any sort are banned. That means that infamous Bash line :(){ :|:&};: is banned!
The application must be single-threaded only. This implies the fork bomb rule.
The program must not run other programs. This means that you can't just do something like run(memoryfiller.exe). The only exception to this is programs that are bundled with your OS or language, that are not primarily designed to consume memory (i.e. they have another purpose).  This means that things like cat and ln -s are permitted.
You can take up as much memory as you like. The more the better.
Code must be explained fully.

Good luck. This is a popularity contest so the code with the most votes after 10 days from the asking date wins!

Windows

The Win32 API allows you to allocate memory in other processes, and then to read/write that memory remotely. This program has only one thread, which it uses to enumerate each running process on the system, and then repeatedly allocate 1MB buffers in each process until the allocation fails. When it finishes with one process, it moves on to the next. The allocations are not released when the calling program finishes - only when/if each target process finishes. This hangs a 2GB Windows 7 VM in about 10 seconds. It does require running as admin.

To compile: cl /MD leak.cpp /link psapi.lib

#include <windows.h>
#include <psapi.h>

typedef void (*ProcFunc)(DWORD pid);
#define ALLOC_SIZE 0x100000
LPVOID buf;

void ForEachProcess(ProcFunc f)
{
    DWORD aProcesses[1024], cbNeeded;

    if (!EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded))
        return;

    for (unsigned int i = 0; i < cbNeeded / sizeof(DWORD); i++)
        if (aProcesses[i] != 0)
            f(aProcesses[i]);
}

void RemoteLeak(DWORD pid)
{
    HANDLE hProcess = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pid );
    if (hProcess == NULL)
        return;

    for (;;)
    {
        LPVOID ptr = VirtualAllocEx(hProcess, NULL, ALLOC_SIZE,
                                    MEM_COMMIT, PAGE_READWRITE);
        if (ptr == NULL)
            return;

        WriteProcessMemory(hProcess, ptr, buf, ALLOC_SIZE, NULL);
    }
}

int main(void)
{
    buf = malloc(ALLOC_SIZE);
    if (buf == NULL)
        return 0;

    memset(buf, 0xFF, ALLOC_SIZE);

    ForEachProcess(RemoteLeak);

    return 0;
}


Is it a Self-divisor? Task
Write a function or program that takes n as a parameter and prints the first n self-divisors.
Definition of Self-divisor
A positive integer is called a “self-divisor” if every decimal digit of the number is a divisor of the number, that is, the number is evenly divisible by each and every one of its digits.
Example
For example, the number 128 is a self-divisor because it is evenly divisible by 1, 2, and 8. However, 26 is not a self-divisor because it is not evenly divisible by the digit 6. Note that 0 is not considered to be a divisor of any number, so any number containing a 0 digit is NOT a self-divisor. There are infinitely many self-divisors.
Scoring
This is code-golf, so the shortest answer in bytes wins

05AB1E, 16 bytes

05AB1E probably has some sort of slice, but I failed to find it.

∞ʒDSÖß}ʒ0å_}ηs<è

Try it online!

Explanation

∞                [1, 2, 3, ...]
 ʒ               Filter all that satisfies:
  DS                 its DigitS
    Ö                is divisible
     ß}              ßy the original number.
       ʒ         Filter out ^ that satisfies:
        0å_}         0 is å digit of the output.
            ηs<è Trunctuatè by the input.


Bloatware contest: producing 100+ MiB executable Create short source code in your favourite compiled language that compiles into a big (not less than 104857600 bytes) executable file. The program must be runnable (assuming 1GB of free memory) and can do anything (preferrable something simple like a hello world).

Usage of non-obvious tricks is encouraged.

Boring example in C:

int a[1024*1024*25] = { 1 };

int main(){}

Bonus points if it can be "explained" why the executable can't be reduced in size (i.e. all bloat is actually used somehow).

OK, here's another one in C, going for the vaguely defined bonus points:

#define a(x) x,x|1,x|2,x|3,x|4,x|5,x|6,x|7
#define b(x) a(x),a(x|8),a(x|16),a(x|24)
#define c(x) b(x),b(x|32),b(x|64),b(x|96)
#define d(x) c(x),c(x|128),c(x|256),c(x|384)
#define e(x) d(x),d(x|512),d(x|4<<8),d(x|6<<8)
#define f(x) e(x),e(x|2048),e(x|4096),e(x|6144)
#define g(x) f(x),f(x|8192),f(x|4<<12),f(x|6<<12)
#define h(x) g(x),g(x|2<<14),g(x|4<<14),g(x|6<<14)
#define i(x) h(x),h(x|2<<16),h(x|4<<16),h(x|6<<16)
#define j(x) i(x),i(x|2<<18),i(x|4<<18),i(x|6<<18)
#define k(x) j(x),j(x|2<<20),j(x|4<<20),j(x|6<<20)
int u,v,z[]={k(0),k(2<<22),k(4<<22),k(6<<22)}
int main(){for(u=v=0;u<1<<25;u++)v|=u!=z[u];return v;}

Basically, at compile time, it build a ascending sequence of integers from 0 to 225 − 1.  At runtime, it verifies that the sequence indeed contains the expected values, and if not, returns a non-zero error code.

Ps. If I did my math right, the executable should be over 100 MiB.  I'll let you know the exact size once it's done compiling...


A determinant optimization challenge Consider 30 by 30  Toeplitz matrices all of whose entries are 0 or 1. This challenge is a simple optimization challenge to find the matrix with the largest determinant possible.

Input None

Output A 30 by 30 Toeplitz matrix all of whose entries are 0 or 1 along with its determinant.

Score The determinant of the matrix you output. If two people get the same score, the first answer wins.

Leading entries so far

65,455,857,159,975  in Matlab by Nick Alger (roughly (10^13.8)
65,455,857,159,975 in Python by isaacg (roughly 10^13.8)
39,994,961,721,988 in Mathematica by 2012rcampion ( roughly 10^13.6)
39,788,537,400,052 in R by  Flounderer (roughly 10^13.6)
8,363,855,075,832 in Python by Vioz- (roughly 10^12.9)
6,984,314,690,903 in Julia by Alex A. (roughly 10^12.8)

Annoying additional constraints July 16 2015

If it is at all possible, please  use arbitrary or high precision arithmetic to compute the final output determinant so that we can be sure what it really is (it should always be an integer). In python this should be helpful.


Expected number of trailing zeros Input
A bound m <= 4294967295.
Output
Consider values sampled uniformly at random from integers in the range 0 to m, inclusive.
Your output should be the expected (average) number of trailing zeros in the binary representation of the sampled value. Your answer should be exact, for example given as a fraction.
Example

m = 0. The answer is 1. 0 will be sampled with prob 1.
m = 1. The answer is 1/2. 0 with prob 1/2 and 1 with prob 1/2.
m = 2. The answer is 2/3. 0 and 2 have one trailing zero.
m = 3. The answer is 1/2. 0 and 2 have one trailing zero.

Python, 36 bytes

lambda m:(m+1-bin(m).count('1'),m+1)

Try it online!
A formula!
$$ f(m) = 1 - \frac{\text{#ones in bin}(m)}{m+1} = \frac{m+1-\text{#ones in bin}(m)}{m+1}$$


Check over hand values for single-suited Mahjong Mahjong is a tile game that is immensely popular in Asia. It is typically played with four players, and the goal of the game is to be the first person to complete a valid hand using the tiles. In mahjong there are three tile suits plus honour tiles — for this challenge we will only consider hands formed using tiles from a single suit.
Tiles are numbered from 1 to 9, and there are exactly four copies of each tile. A valid hand consists of four sets of three and a pair, for a total of fourteen tiles.
A set of three can be either:

A triplet, three of the same tile (e.g. 444), or
A sequence of three consecutive tiles (e.g. 123 or 678 but not 357). Sequences do not wrap (so 912 is invalid).

A pair is simply two identical tiles (e.g. 55).
The challenge
Given a valid hand of fourteen tiles, determine its score based on the following criteria:
Condition                Description                                 Point/s
-------------------------------------------------------------------------------
Straight                 Contains the sequences 123 456 789          1
Identical sequences      Contains two identical sequences            1
All simples              Only 2-8, no 1s or 9s                       1
All sequences            All sets of three are sequences             1
All triplets             All sets of three are triplets              2
Flush                    Single-suit hand (always applies)           5

(Scoring here is based off Japanese mahjong rules, but heavily simplified to make the spec less messy.)
The score of a hand is the sum of points for the conditions it satisfies. If a hand can be decomposed in more than one way, take the highest scoring decomposition.
The input hand is guaranteed to be valid, i.e. fourteen tiles from 1 to 9 and each tile appearing at most four times, and may be assumed to be already sorted. Input is a list of digits (as a string or a single flat list of integers) via STDIN, function argument or command line. Output may be to STDOUT or return value.
Test cases
22233355777888  ->  8  # 222 333 55 777 888, flush + all simp. + all trip.
11112345678999  ->  6  # 111 123 456 789 99, flush + straight
11123456788999  ->  5  # 111 234 567 88 999, flush only (no straight)
23344455566788  ->  7  # 234 345 456 567 88, flush + all simp. + all seq.
33334444555566  ->  8  # 33 345 345 456 456, flush + all simp. + all seq. + identical seq.
11122233377799  ->  7  # 111 222 333 777 99, flush + all trip. (no identical seq.)
12344556678889  ->  8  # 123 456 456 789 88, flush + all seq. + straight + identical seq.
11344556678999  ->  5  # 11 345 456 678 999, flush only (no identical seq.)
22233344455566  ->  8  # 222 333 444 555 66, flush + all simp. + all trip.
11112233344555  ->  5  # 111 123 234 345 55, flush only

For the fifth example, despite having two pairs of identical sequences, only one needs to be present to attain the point. The decomposition 345 345 345 345 66 would score the same, while 333 345 444 555 66 scores worse.
Scoring
This is code-golf, so the solution in the fewest bytes wins. Standard loopholes apply.

Related challenge: What are you waiting for? (A mahjong solver)


QWERTY Quine Creation Challenge

Create a quine, that instead of outputting it's source, output's it's source QWERTY-sorted.

What is QWERTY sorting?

QWERTY sorting is sorting code by the QWERTY keyboard. Anything higher or more left is greater (q > Q, \ > /) with presedence on higher. To check, find the locations of the two characters to compare. Find which character occurs first in the following table (left to right, up to down). The first character is the smaller one.

qwertyuiop[]\
asdfghjkl;'
zxcvbnm,./
QWERTYUIOP{}|
ASDFGHJKL:"
ZXCVBNM<>?
1234567890-=!@#$%^&*()_+~`

(there is a trailing space and linefeed)

Examples:

Code Golf -> eoodflGC
Programming -> rroiagnmmP

(note trailing space on Code Golf)

Specifications

Only characters in the above list are allowed in the source code!
This is code-golf.
Only Proper Quines are allowed (adapted to QWERTY sort).
Output must be in increasing QWERTY order.

CJam, 25 23 bytes

{`"_~"+{"#$_+~`"`#}$}_~

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

Try it online!

How it works

{                   }_~  Define, copy and execute a code block.

   `                       Create a string representation of the code block.
  "_~"+                    Append that string.
       {          }$       Sort the characters by the following:
        "#$_+~`"`#           Compute the 0-based index of the character in that
                             string. Returns -1 if not found.
                           Since `$' is stable, all characters with tied index -1
                           will appear at the beginning, in their original order.
                           This places {{}} at the beginning, followed by
                           """"##$$___++~~~```.


Valid Through The Ages Inspired by this question on SO, your task is to produce a program that is valid in (at least) two major versions of your chosen language that produce different output.

Rules

Any language that has more than one major version can be used.

For the purposes of this challenge, I would suggest a "major version" is where the first number in the version number changes.

PHP 4 and PHP 5 are different, PHP 5.3 and PHP 5.4 are not.

However, since I don't know the versioning scheme for all languages, if you can argue your case well enough, I'm sure the community will determine if you have been fair in determining "major version" yourself.

The code must be compiled and run with the same flags and input each time

Except to change the version of the language if this is pertinent

Errors don't count as output and answers that produce errors are disqualified (rather than error output is just ignored)
The program should take no input other than that required to make it run.
For each given version, the output should always be the same
The intention is that the change should be a consequence of a change in the language spec rather than the VM spec or environmental metadata

Scoring

code-golf type scoring for length, so +1 for each char/byte
-1 for each character difference in the length of the output.

e.g. Version 1 outputs abcde (5 characters), Version 2 outputs 123abc (6 characters) = -1

Other Rules

Standard exceptions apply - no external programs,web requests etc.
Your program should terminate (within 2 seconds)
Lowest score wins.

"Better" Scoring

Keep your original answers, in the interest of fairness, I'll mark the winner based on the original rules.

Since my original scoring is fundamentally broken, why not re-score / retry with the following scoring system:

code-golf type scoring for length, so +1 for each char/byte
+1 for each character difference in length of output

abcde and 123456 -> +1

-1 for each unique character difference in the output (capped to length of shortest output)

abcde and 123456 -> -5
12345 and 123456 -> -1
12345 and 123455 -> 0

Scores closest to zero win
In the event of a second tie break, simple code-golf score wins.

Revised answer for "better" scoring system
C89 / C99, Score: 0
My program is 52 characters long and uses the same mechanism as in my original answer to achieve the different output. This works because C89 doesnt treat // as a comment:
i=32;main(){putchar(i+++0//**/
+52)&&i<84&&main();}

The results:
$ ./diff2c89
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRS
$ ./diff2c99
TUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~⌂Çüéâäàåç
$ ./diff2c99 | wc
      0       1      52
$ ./diff2c89 | wc
      0       1      52
$ wc diff2.c
      1       2      52 diff2.c

Old answer:
C89 / C99, Score: -Infinity?
I'm not entirely sure if this program doesn't break the rules, but never mind.
This program exploits the fact that in C89 // is not a valid comment but /* ... */ is.
Using the comment trick an other function is executed. In C89 the function just prints "trolololol..." until the stack overflows (so it might finish within 2 seconds).
f1(){printf("ol");f1();}
f2(){printf("oll");}
main(){
    printf("tr");
    void (*f[])() = {f1,f2};
    f[0 //* trollololol */
      +1]();
}

C99
$ ./diffc99
troll

C89
$ ./diffc89
trolololololololololololololololololololololololololololololololololololololololololo
lolololololololololololololololololololololololololololololololololololololololololol
ololololololololololololololololololololololololol ....


Tic Tac Toe: print all possible positions without duplicates Write a program that outputs all possible Tic Tac Toe positions including the corresponding game outcome. Avoid duplicate output of equal positions.

The program takes no input.

Rules:

A position output must consist of 9 characters, using X and O for the taken squares, and an arbitrary non-whitespace character for the blank squares
Each position must be printed in 3 lines/columns, with a blank line as a separator between two positions.
Additional whitespace / blank lines / box drawing characters are welcome
Player X goes first
The outcome can be either of:

X has won
O has won
Draw
Game in progress

You are free to choose a suitable visualization of the position's outcome, e.g. as colored text, or as textual annotation, as long as it is placed near the corresponding position
Positions are considered equal if one can be obtained from the other by rotation or mirroring. Duplicate positions must not be printed. (In other words, print the equality classes only.)
For example, print only one of the following:

X••  ••X  •••  •••
•••  •••  •••  •••
•••  •••  X••  ••X

This is code-golf, so shortest code wins!

Sample output:

•••
•••
••• -

X••
•••
••• -

•X•
•••
••• -

•••
•X•
••• -

[…]

XXO
OOX
XXO /

OXO
XXX
OXO X

Hint: There are 765 positions, with 91 wins for X, 44 wins for O, and 3 draws.

A similar question has been asked before, but this one is different.

Jelly, 192 179 168 bytes
5ĿḢṠµFf0L¬ị⁾-/µ5ĿḢṠµ?
U,µṚ,µ€µ“æɗþƑ’DịFs3,µ€€Fs9s3$€Ṣ
FSµ×’¬
ÑPµA_µọ9n1
,UŒDḢ$€;;ZS€f3,-3
Ç,SS€µṪµṪCµSṠ‘µ?÷Ḣ
Ça3Ŀa4Ŀ
3ṗ9_2s3$€ÇÐf2Ŀ€QḢ€µ;ÑFµ€µ3Ḷ’,“O¤X”yµ€Fs10µs3Gµ€j⁾¶¶

Try it online! (Takes about 30 seconds, so be patient).
How it Works
High level overview:
In intermediate steps, this stores X as 1, unplaced as 0, and O as -1.
The program generates all 3^9 possibilities, then keeps only the valid positions based on meeting the three criteria:

There is 1 or 0 more X than O.
Not both X and O have won.
If X has won, there is 1 more X than O. If O has won, there are an equal number of Os and Xs.

Then, the program replaces each game state with all of its rotations and reflections to get a list of all equivalence classes. This is the operation which takes most of the time.
The first game state is taken from each of the equivalence classes, then who won is calculated.
Where this happens
The lines are numbered for readability
1: 5ĿḢṠµFf0L¬ị⁾-/µ5ĿḢṠµ?          ••calculates who wins (output as -1 or 1) or draw ("-") or in game ("/")
                 µ5ĿḢṠµ?          - if(someone won based on line 5):
   5ĿḢṠ                             - return 1 if X won and -1 if O won
       µ                          - else:
        Ff0L¬ị⁾-/                   - return "/" if the game is in progress and "-" if the game is at a tied end-state
2: U,µṚ,µ€µ“æɗþƑ’DịFs3,µ€€Fs9s3$€Ṣ••outputs the equivalence class to a game state
   U,                             - list of game state [reflected horizontally, unaltered]
     µṚ,µ€                        - for each, replace with the list [reflected vertically,unaltered]
          µ“æɗþƑ’DịFs3,µ€€        - for each, replace with the list [rotated 90 degrees counter-clockwise,unaltered]
                          Fs9s3$€ - reformat into list of game states
                                 Ṣ- Sort
3: FSµ×’¬                         ••outputs truthy iff there is the right number of `X`s to `O`s (condition 1)
   FS                             - d = number of `X`s minus number of `O`s
     µ×’                          - d*(d-1): falsey iff d is 0 or 1
        ¬                         - logical not, to return truthy iff d is 0 or 1
4: ÑPµA_µọ9n1                     ••outputs truthy iff there is the right number of winners (condition 2)
   Ñ                              - the winners. [-3,3] is what we want to return falsy on
    PµA_µ                         - 18 on [-3,3] and 0 otherwise
         ọ9n1                     - not divisible by 9 exactly once: 0 on [-3,3] and 1 otherwise
5: ,UŒDḢ$€;;ZS€f3,-3              ••outputs the number of times each player won.
   ,UŒDḢ$€;;Z                     - the diagonals, rows, and columns of a board
             S€                   - sum of each. Returns -3 or 3 iff the line is only 1s or -1s
               f3,-3              - filter out, keeping only 3s and -3s
6: Ç,SS€µṪµṪCµSṠ‘µ?÷Ḣ             ••return truthy iff the winner corresponds to the respective numbers of X and O (condition 3)
   Ç,SS€                          - list of winners and how many more Xs than Os there are
             µSṠ‘µ?               - if O won, then
        µṪ                          - how many more Xs than Os there are
                                  - else:
          µṪC                       - the complement of how many more Xs than Os there are
                   ÷Ḣ             - deal with no one winning
7: Ça3Ŀa4Ŀ                        ••return truthy iff the game state meets all three conditions
   Ç 3Ŀ 4Ŀ                        - the three conditions: on line 3,4, and 6
    a  a                          - joined by logical ANDs
8: 3ṗ9_2s3$€ÇÐf2Ŀ€QḢ€µ;ÑFµ€µ3Ḷ’,“O¤X”yµ€Fs10µs3Gµ€j⁾¶¶ ••do everything
   3ṗ9_2                        - all possible game states, with -1 for O and 1 for X
        s3$€                    - turn into two-dimensional game boards
            ÇÐf                 - filter based on line 6: if the board meets all three ocnditions
               2Ŀ€Q             - generate the equivalence classes for each and remove repeats based on line 1
                   Ḣ€           - get the first board from each class
                     µ;ÑFµ€     - append the winner to each board based on line 1
   µ3Ḷ’,“O¤X”yµ€                   - map each -1, 0, and 1 to the proper `O`,  `¤`, and `X`.
                Fs10µs3Gµ€         - format each board- winner combos
                          j⁾¶¶     - join the combos by double-newlines


Parse the Markdown-like Markup! The Challenge

In this challenge, you are supposed to write a program or function that takes in a String, which will contain the simplified Markdown-like Markup, and outputs the corresponding HTML Markup.

The Input

You can take input in whatever way you wish to. The type of the input should be String.

The Output

You can output the result in any way you want. Logging to Console or Terminal, printing on screen, returning from function etc. are perfectly valid.

The Rules

Convert each occurrence of *foo* and _foo_ to foo.
Convert each occurrence of **foo** and __foo__ to foo.
Convert each occurrence of <tab or four spaces here>foo\n to
foo
.
Convert each occurrence of #foo\n to
foo
.
Convert each occurrence of ##bar\n to
bar
.
Convert each occurrence of ###bar\n to
bar
.
Convert each occurrence of ####bar\n to
bar
.
Convert each occurrence of #####bar\n to
bar
.
Convert each occurrence of ######bar\n to
bar
.
Convert each occurrence of [foo](https:\\www.bar.com) to foo.
Convert each occurrence of ![foo](https:\\www.bar.com) to .
Convert each occurrence of >foo\n to
foo
.
Convert each occurrence of - foo\n as
foo
 (add
 before the li if the - is the first of its consecutive series and add
 if it is the last.)
Convert each occurrence of n. foo\n (where the first n denotes an Integer such as 12,1729 etc.) as
foo
 (add
 before the li if the element is the first of its consecutive series and add
 if it is the last.)
Although there exist many more rules of conversion, you are supposed to follow only the abovementioned ones (for the sake of simplicity).
You are supposed to output only the corresponding HTML Markup for the given String. No need to add extra elements that are necessary for creating a valid HTML file (like ,  etc.). However, if they are present in the input String, then you will have to output them too, that is, replace < and > with &lt; and &gt;, repspectively.
You must NOT use any built-in! (I doubt whether there exists one)

Note : In the abovementioned rules, foo, bar and https:\\www.bar.com are only placeholders. Your program or function must be flexible enough to work for Strings different than these too.

Scoring

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

Test Cases

"**Hello**" -> "Hello"

"#IsThisAwesome?\n" -> "
IsThisAwesome?
"

">![Image](http:\\www.somewhereontheinternet.com) -> "

"

">Some Content\n- Item1\n- Item2\n- Item3\n" -> "
Some Content

Item1

Item2

Item3

"

"1.Hello\n2.Bye\n3.OK\n" -> "

Hello

Bye

OK

"

Special Thanks to FakeRainBrigand!

This challenge was originally proposed by @FakeRainBrigand in the Sandbox. He granted me the permission to post this challenge on the regular website. Due to unclear and broad specifications, the challenge was closed. Now, it has been reopened with clearer and fewer specs by @Arjun.


Bouncing in an array Introduction

Arrays can also be seen as a field for a bouncing ball. This of course sounds very vague, so here is an example of an input:

[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

The challenge is to output the bounced arrays. These are made from diagonal patterns which bounce at the edges of the field. This path is pointed upwards. The path for the first bounced array (in which the path is directly bounced off the egde), is:

[1, -, -, -, 5, -, -, -, 9]
[-, 8, -, 6, -, 4, -, 2, -]
[-, -, 3, -, -, -, 7, -, -]

From left to right, this would result in [1, 8, 3, 6, 5, 4, 7, 2, 9]. This is our first bounced array. The path for the second bounced array:

[-, 2, -, -, -, 6, -, -, -]
[9, -, 7, -, 5, -, 3, -, 1]
[-, -, -, 4, -, -, -, 8, -]

This results in [9, 2, 7, 4, 5, 6, 3, 8, 1]. The path for the third bounced array is:

[-, -, 3, -, -, -, 7, -, -]
[-, 8, -, 6, -, 4, -, 2, -]
[1, -, -, -, 5, -, -, -, 9]

This results in [1, 8, 3, 6, 5, 4, 7, 2, 9]. So the three bounced arrays are:

[1, 8, 3, 6, 5, 4, 7, 2, 9]
[9, 2, 7, 4, 5, 6, 3, 8, 1]
[1, 8, 3, 6, 5, 4, 7, 2, 9]

Task

Given at least 1 array containing only non-negative integers, with all the arrays having the same length, output all the bounced arrays.

Test cases

Test case 1:

Input:                       Output:
[1, 2, 3, 4, 5]              [1, 7, 3, 9, 5]
[6, 7, 8, 9, 0]              [6, 2, 8, 4, 0]

Input:                       Output:
[1, 2, 3, 4, 5]              [1, 2, 3, 4, 5]

Input:                       Output:
[0, 0, 0, 0, 0, 0, 0, 0]     [0, 9, 0, 9, 0, 9, 0, 100]
[9, 9, 9, 9, 9, 9, 9, 100]   [9, 0, 9, 0, 9, 0, 9, 0]
[0, 0, 0, 0, 0, 0, 0, 0]     [0, 9, 0, 9, 0, 9, 0, 100]

Input:                       Output:
[0, 1, 2, 3, 4, 5]           [0, 7, 14, 9, 4, 11]
[6, 7, 8, 9, 10, 11]         [6, 1, 8, 15, 10, 5]
[12, 13, 14, 15, 16, 17]     [12, 7, 2, 9, 16, 11]

Input:                       Output:
[0, 0, 0, 0, 0, 0]           [0, 2, 2, 6, 2, 6]
[1, 2, 3, 4, 5, 6]           [1, 0, 3, 2, 5, 2]
[2, 2, 2, 2, 2, 2]           [2, 2, 0, 4, 2, 4]
[9, 8, 7, 6, 5, 4]           [9, 2, 3, 0, 5, 2]

This is code-golf, so the submission with the least amount of bytes wins!

Pyth, 17 bytes
>lQC.e.>bkC+_PtQQ

Explanation:
                      implicit: Q=input
>                     First
  l Q                   len(Q) elements of the
  C .e                  Transpose of enumerated map lambda b,k:
       .>                 Rotate the kth element rightwards by
          b
          k               k.
       C +              Transpose of: Q concatenated to
           _ P t Q        itself reversed without first and last elements.
           Q

Try it here.


Hello, World! with semi-common characters As some of you may know, to get a language onto Dennis's wonderful Try It Online!, a Hello, World! program is required. Recently, Dennis pushed up a way to load these programs from the website. Here is a JSON pastebin of the characters used in those programs, by frequency, as of July 27, 2017.

Some of those characters need some love, so your challenge is to output Hello, World! (preferably in a language involved in this process), using only the characters specified below. These characters are all of the characters used between 10 and 99 (inclusive) times, along with the two most common characters, 0 and , because I'm feeling nice.

0 $&*?ABCDEFGIJKLNPQRSTUXYZ\`gjkqwxyz{}÷≤≥=║_

Your usage of the character should be based on its appearance in a normal program, not based on its code point or byte value.

You must use at least one character from that set, so 0-length programs are invalid.

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

JSFiddle to check if your answer is valid

Perl 5, 76 bytes

}{${$_=$`x?B?}{?\w$?}{$_=qq{Lg\LLL$&= w$&RLD=}&qq=y}\LLL$&L _$&RLDA=}=$_=\*G

This uses a feature that has been deprecated, but works locally in my terminal (which is version 5.18.2 as noted). In older versions of Perl ?\w? is a synonym for /\w/ which gives me access to regexp matching and I have enough chars for $& (last match) and $` (text preceding last match). I need these to be able to get the O. I generate this be creating a glob reference ($_=\*G which, cast to a scalar, is something like GLOB(0x7ffb728028d0)). Once that's in $_, ?B? will match the B and $` will contain GLO, I can then match against \w$ which would store O in $& which is inserted into the strings that I'm running stringwise-AND to create the rest of the text, the body of the string is lowercased using \L.

Try it online! - uses /\w/ in place of ?\w? as the version of Perl on TIO is too new.

Perl 5, 65 bytes

This is a bit more cheaty as it relies on the filename on TIO (which is .code.tio), so I don't really think this is competing, but I was happy with the result!

}{${$_=$0}{?\w$?}{$_=qq{Lg\LLL$&= w$&RLD=}&qq=y}\LLL$&L _$&RLDA=}

Try it online!


Generate Brainfuck for the numbers 1–255 Write a program that, for the numbers 1 through 255, prints out BF code that will produce the given number in some byte of the array, plus a newline.

For example, the first four lines of the output could (and most likely will) be:

+
++
+++
++++

The winner will be the smallest: source code + output (in bytes).

Clarifications & Revisions:

BF programs use wrapping cells.
The output BF program must terminate with the only non-zero cell being the cell containing the number.
Programs must be output in ascending order.
Outputting a program for 0 is optional.
Negative data pointers are not allowed. < at the first pointer will do nothing. (leave a comment if it would be more appropriate to have it throw)

Perl 6, 224 + 3964 = 5834 4188 bytes

map {say (.[0]~'['~.[3]~'>'~.[1]~'<]')x?.[1],'>'x?.all,.[2]}o*.min({$_>>.abs.sum+6*?.[1]})>>.&{<- +>[.sign>0]x.abs},classify({0+|(grep(*%%1,(((256 X*^4)X+.[0]%256)X/-.[3]))[0]*.[1]+.[2])%256},[X] |(^27-13 xx 3),-7..-1){^256}

Try it online! (may timeout. Change the ^27-13 to ^25-12 to speed up slightly at the cost of some extra output)

Outputs the shortest code in the form *>[*>*<]>*, where each * is a certain number of +s or -s. There are some extra tweaks like removing the loop if it is not needed, as well as trailing >s.

As far as I can tell, the output is the most golfed for this particular format.

Explanation:

([X] |(^27-13 xx 3),-7..-1)        # Define the search space as the cross product of:
                                        # -13 to 13 for:
                                            # Initialisation     +++>
                                            # Change in target   [*>+++<]
                                            # Last change        >+++
                                        # And -7 to -1 for the change in start [-->*<]
  .classify({                  })  # Group them by calculating
                  (256 X*^4)                         # Each of the multiples of 256
                 (          X+.[0]%256)              # Plus the initialisation
                (                      X/-.[3])      # Divided by the change in start
      grep(*%%1,                               )     # Filter out the whole numbers
                                                [0]  # And take the first value
          # This is the amount of times the inner loop will execute
          # Being Nil, converted to 0 if it is an infinite loop
      *.[1]              # Multiply by the change to the target cell
           +.[2]         # And add the final section
     (          )%256    # And modulo the whole lot by 256
                     +|0 # And floor it just to keep the .0 out
classify(                   ){^256}     # Take the corresponding groups in order
   .map(                             )  # And map each to
        *.min({                    })   # Find the minimum by:
               $_>>.abs.sum             # The sum of the absolute values
                           +6*?.[1]     # Plus 6 if it loops
      >>.*{                   }    # Then map each value to
           <- +>[.sign>0]          # + or - depending on the sign
                         x.abs     # Repeated by the absolute value
   {                    }o              # And pass this to the next code block
    say                       # Print
        (.[0]~'['~.[3]~'>'~.[1]~'<]')             # The loop section
                                     x?.all       # If it is needed
                                           ,.[2]  # And the final part


How many times will you have to golf a quine? For this challenge, you must create a programme which takes an integer x and outputs its source x many times.

Rules

This is codegolf, the aim is to golf your programme to have the least amount of bytes
If you submit a function, the function must take x as  a parameter and either return or print the entirety of your code x many times to STDOUT. The function body must also not be empty
If you submit a lambda, it is not required for you to assign it to a variable
Standard loophole restrictions apply.
Empty programmes are forbidden
Your programme only has to work when x is a whole integer larger than or equal to 0
Your programme may also not directly read any part of its source code

Python 2, 50 bytes

Note the trailing comma and newline.

s='s=%r;print s%%s*input(),\n';print s%s*input(),

Try it online!


shortest possible python pascal triangle code the contest is already finished, so I don't think it's cheating to ask:
I am trying to optimize this small contest: pascal triangle
I started with 4.72 and worked myself up to 7.48.
The best made a 9.05 but in perl, python2 best score is 8.25.
Unfortunately they don't let you look at what others did.
My current solution is the following:

l=[1]
print 1
while(len(l)<31):
 print' '.join(map(str,l+[1]))
 l=[1]+map(lambda x,y:x+y,l,l[1:]+[1])

Now I tried to get rid of the loop in using list comprehension, but I am too new to python to get this done. Can anyone give me a hint for nested list comprehension shortening this code further down?

Thank you for your audience.

This is a bit shorter, but still no good:

l=[1]
while(len(l)<32):
 print' '.join(map(str,l))
 l=[1]+map(int.__add__,l,l[1:]+[0])

And this one comes in at a score of 8.28 (credit to @primo):

l=[1];exec"print' '.join(map(str,l));l=map(sum,zip([0]+l,l+[0]));"*31


Redraw an image with just one closed curve Inspired by vi.sualize.us

Goal

The input is a grayscale image and the output is a black and white image. The output image consists of just one closed curve (loop) that is not allowed to intersect with itself or touch itself. The width of the line shall be constant throughout the whole image. The challenge here is finding an algorithm for doing so. The output just has to represent the input image, but with any artistic freedom. The resolution is not so important but the aspect ratio should stay about the same.

Example

More test images

Python: Hilbert curve (373 361)

I decided to draw a Hilbert curve with variable granularity depending on the image intensity:

import pylab as pl
from scipy.misc import imresize, imfilter
import turtle

# load image
img = pl.flipud(pl.imread("face.png"))

# setup turtle
levels = 8
size = 2**levels
turtle.setup(img.shape[1] * 4.2, img.shape[0] * 4.2)
turtle.setworldcoordinates(0, 0, size, -size)
turtle.tracer(1000, 0)

# resize and blur image
img = imfilter(imresize(img, (size, size)), 'blur')

# define recursive hilbert curve
def hilbert(level, angle = 90):
    if level == 0:
        return
    if level == 1 and img[-turtle.pos()[1], turtle.pos()[0]] > 128:
        turtle.forward(2**level - 1)
    else:
        turtle.right(angle)
        hilbert(level - 1, -angle)
        turtle.forward(1)
        turtle.left(angle)
        hilbert(level - 1, angle)
        turtle.forward(1)
        hilbert(level - 1, angle)
        turtle.left(angle)
        turtle.forward(1)
        hilbert(level - 1, -angle)
        turtle.right(angle)

# draw hilbert curve
hilbert(levels)
turtle.update()

Actually I planned to make decisions on different levels of detail, like "This spot is so bright, I'll stop the recursion and move to the next block!". But evaluating image intensity locally leading to large movements is very inaccurate and looks ugly. So I ended up with only deciding whether to skip level 1 or to draw another Hilbert loop.

Here is the result on the first test image:

Thanks to @githubphagocyte the rendering is pretty fast (using turtle.tracer). Thus I don't have to wait all night for a result and can go to my well-deserved bed. :)

Some code golf

@flawr: "short program"? You haven't seen the golfed version! ;)

So just for fun:

from pylab import*;from scipy.misc import*;from turtle import*
i=imread("f.p")[::-1];s=256;h=i.shape;i=imfilter(imresize(i,(s,s)),'blur')
setup(h[1]*4.2,h[0]*4.2);setworldcoordinates(0,0,s,-s);f=forward;r=right
def h(l,a=90):
 x,y=pos()
 if l==1and i[-y,x]>128:f(2**l-1)
 else:
  if l:l-=1;r(a);h(l,-a);f(1);r(-a);h(l,a);f(1);h(l,a);r(-a);f(1);h(l,-a);r(a)
h(8)

(373 361 characters. But it will take forever since I remove the turte.tracer(...) command!)

Animation by flawr

flawr: My algorithm is slightly modified to what @DenDenDo told me: I had to delete some points in every iteration because the convergence would slow down drastically. That's why the curve will intersect itself.


A backwards relationship Write a program or function that, given two ASCII strings A and B, will produce strings A' and B' where the common substrings are reversed in their place. The process for finding A' is as follows:

A' is initially empty.
If the first character of A is in B, find the longest prefix of A which is a substring of B. Remove this prefix from A and add its reversal to A'.
Otherwise, remove this first character from A and add it to A'.
Repeat steps 2-3 until A is empty.

Finding B' is done similarly.

Example

Let's consider the strings A = "abc bab" and B = "abdabc". For A', this is what happens:

A = "abc bab": The first character "a" is in B and the longest prefix of A found in B is "abc". We remove this prefix from A and add its reversal "cba" to A'.
A = " bab": The first character " " is not in B, so we remove this character from A and add it to A'.
A = "bab": The first character "b" is in B and the longest prefix of A found in B is "b". We remove this prefix from A and add its reversal (which is still "b") to A'.
A = "ab": The first character "a" is in B and the longest prefix of A found in B is "ab". We remove this prefix from A and add its reversal "ba" to A'.
A = "": A is empty, so we stop.

Thus we get A' = "cba" + " " + "b" + "ba" = "cba bba". For B', the process is similar:

B = "abdabc"  ->  "a" in A, remove prefix "ab"
B = "dabc"    ->  "d" not in A, remove "d"
B = "abc"     ->  "a" in A, remove prefix "abc"

Thus we get B' = "ba" + "d" + "cba" = "badcba".

Finally, we return the two strings, i.e.

(A', B') = ("cba bba", "badcba")

Test cases

"abc bab", "abdabc" -> "cba bba", "badcba"
"abcde", "abcd bcde" -> "dcbae", "dcba edcb"
"hello test", "test banana" -> "hello tset", "tset banana"
"birds flying high", "whistling high nerds" -> "bisdr flyhgih gni", "wihstlhgih gni nesdr"

Shortest code in bytes wins.

Haskell, 120 111 bytes

import Data.List
a&b=(a#b,b#a)
[]#_=[]
(a:y)#b=[a]%y where p%(i:w)|reverse(i:p)`isInfixOf`b=(i:p)%w;p%x=p++x#b

Test runs:

λ: "abc bab"&"abdabc"
("cba bba","badcba")

λ: "abcde"&"abcd bcde"
("dcbae","dcba edcb")

λ: "hello test"&"test banana"
("hello tset","tset banana")

λ: "birds flying high"&"whistling high nerds"
("bisdr flyhgih gni","wihstlhgih gni nesdr")


Brainf*** to tinyBF converter You don't need to know these languages to participate. All necessary information has been provided in this question.

You should write a program or function which given a brainfuck (BF) code as input outputs its tinyBF equivalent.

BF has 8 instructions characters: +-><[],. and tinyBF has 4: =+>|. Converting works the following way: starting from the beginning of the BF code each symbol is replaced by on of its two tinyBF counterparts based on the number of = signs in the tinyBF code until that point (i.e. = behaves like a toggle switch).

The converter table (with columns: Brainfuck symbol;  tinyBF symbol(s) when ther are even ='s before; tinyBF symbol(s) when ther are odd ='s before):

BF   even    odd

+      +      =+
-     =+       +
>      >      =>
<     =>       >
[      |      =|
]     =|       |
.     ==      ==
,    |=|    =|=|

(This creates an almost unique tinyBF code. The only conflict occurs if the BF code contains a [] which is generally unused as it creates an infinite void loop.)

Input

An at least 1 byte long valid brainfuck program containing only the characters +-><[],.
Guaranteed not to contain the string []
Trailing newline is optional.

Output

A tinyBF program.
Trailing newline is optional.

Examples

You can convert any BF program to tinyBF with this (1440 byte long) converter (see the Edit section for a small deviation).

Format is Input into Output

++-  into  ++=+
,[.,]  into  |=||==|=|=| or |=|=|==|=|| (both is acceptable check the Edit section)
>++.--.[<]+-,  into  >++===++===|=>|=+=+=|=|
>++-+++++++[<+++++++++>-]<.  into  >++=+=+++++++|=>=+++++++++>=+|>==

Edit

As @Jakube pointed out in the official tinyBF converter in the equivalents of the , BF instruction (|=| and =|=|) the last = signs aren't counted towards the toggle state. Both the official and mine interpretations are acceptable but you have to choose one.

This is code-golf so the shortest entry wins.


Hare Krishna Hare Krishna Krishna Krishna Hare Hare Recently, I've seen Hare Krishna people with their mantra on the emblem and I've found it may be quite interesting to code golf.

The challenge

Write the Hare Krishna mantra, i.e.:

Hare Krishna Hare Krishna
Krishna Krishna Hare Hare
Hare Rama Hare Rama
Rama Rama Hare Hare

Winning criteria

This is code-golf, so shortest code in bytes wins!

Rules

Casing must be preserved.
Text should contain new lines.
Lines may have trailing space(s).
Trailing newline is allowed.
Parsing from web or any other external resource disallowed.

Jelly, 22 bytes

“t,ȧṫÞċḅ»Ḳ“¡¥Ɓc’ṃs4K€Y

Try it online!

How it works

“t,ȧṫÞċḅ»Ḳ“¡¥Ɓc’ṃs4K€Y  Main link. No arguments.

“t,ȧṫÞċḅ»               Use Jelly's dictionary to yield the string
                        "Hare Rama Krishna". Fortunately, the words Rama, Krishna,
                        and hare (lowercase H) are in the dictionary.
         Ḳ              Split at spaces, yielding ["Hare", "Rama", "Krishna"].
          “¡¥Ɓc’        Base-250 literal; yielding 15973600.
                ṃ       Convert 15973600 to base ["Hare", "Rama", "Krishna"]
                        (ternary), where "Krishna" = 0, "Hare" = 1, and "Rama" = 2.
                 s4     Split the resulting string array into chunks of length 4.
                   K€   Join each of the four chunks by spaces.
                     Y  Join the resulting strings by linefeeds.


Right and tfeL truncatable primes A right-truncatable prime is a prime where every prefix is a prime (in base 10).  A left-truncatable prime is exactly the opposite, where every postfix is a prime (primes that start with 0 aren't allowed).  Both of these sequences are finite (There are only 83 Right-truncatables, while there are 4260 Left-truncatables).

You need to write a program that accepts a single number as input, and produces the nth right-truncatable prime.  However, when the program is read arranged backwards, it should produce the nth left-truncatable prime.

To arrange a program backwards, we split the program into words, then reverse the order of the words.  A word can consist of any number of characters.

For example, if the following was your program:

hello world
1234567890

The following would all be allowed as possible backwards arrangements:

Splitting on each character:

0987654321
dlrow olleh

Splitting on whitespace:

1234567890
world hello

Splitting arbitrarily (pipes added for clarity):

hel|lo w|orld
1|23456|7|8|90

908723456orld
1lo whel

When arranging your program backwards, all whitespace must be considered and reversed, just like any other character.

Forward test inputs:

1:  2
2:  3
21: 379
60: 239933
83: 73939133

Backward test inputs:

1:    2
2:    3
39:   647
187:  29173
4260: 357686312646216567629137

Programs should be able to run in a reasonable amount of time (less than a minute)

This is a code-golf, so the program with the fewest bytes wins!

Jelly, 26 23 bytes

Forward

Ñ¶p9¶7ÆR2ĿV€$ÆPÐf$ÐĿFị@

Try it online!

Words

Ñ ¶ p 9 ¶ 7ÆR2ĿV€$ÆPÐf$ÐĿFị@

Backward

7ÆR2ĿV€$ÆPÐf$ÐĿFị@¶9p¶Ñ

Try it online!

Words

7ÆR2ĿV€$ÆPÐf$ÐĿFị@ ¶ 9 p ¶ Ñ

How it works

All Jelly programs consist of links (Jelly's take on functions), which are separated by linefeeds or pilcrows (¶). The last of them is the main link; it is called automatically when the program is run.

The forward program works as follows.

Ñ                   Helper link. Unused.

p9                  Helper link. Take the Cartesian product with [1, ..., 9].

7ÆR2ĿV€$ÆPÐf$ÐĿFị@  Main link. Argument: n

7ÆR                 Yield all primes up to 7.
             ÐĿ
            $ÐĿ     Combine the two quicklinks to the left into a monadic chain,
                    and call it repeatedly until the results are no longer unique.
                    Return the array of all intermediate results.
       $              Combine the two links to the left into a monadic chain.
   2Ŀ               Call the helper link on line 2.
     Ṿ€                 Eval each array in the product. This casts to string
                        before evaluating, thus concatenating both numbers.
        ÆPÐf        Filter by primality; keep only primes.
               F    Flatten the resulting array.
                ị@  Retrieve the element at index n.

The backward program does almost exactly the same; there are only two differences.

The main link is now Ñ, which simply calls the link below it (wrapping around), i.e., the main link of the forward program.
9p instead of p9 return the reversed Cartesian product.


IMP: Implicit multiplication parser Jack likes C programming language, but hates to write expressions like V=a*b*h;
to multiply the values.

He would like to write V=abh; instead,
why should compiler moan about abh symbol being undefined since int a, b, h; are defined, so we can deduce multiplication?

Help him implement a parser that deciphers a single multiplication term,
provided the set of variables defined in current scope is known.

For simplicity, multiplying by number (as in 2*a*b) is not taken into account, only variables appear.

The input is a multiplication term T, fulfilling regexp:

[a-zA-Z_][a-zA-Z_0-9]*

 and a variable set Z  .

A parsing P of the term T over variable set Z is a string fulfilling following:

after removing all occurences of * from P we receive T,
either is a variable name from Z or consists of proper variable names from Z split up by single * characters.

The solution should print all parsings of a term.

Sample:

Vars           a, c, ab, bc
Term           abc
Solution       ab*c, a*bc

Vars           ab, bc
Term           abc
Solution       -

Vars           -
Term           xyz
Solution       -

Vars           xyz
Term           xyz
Solution       xyz

Vars           width, height
Term           widthheight
Solution       width*height

Vars           width, height
Term           widthheightdepth
Solution       -

Vars           aaa, a
Term           aaaa
Solution       aaa*a, a*aaa, a*a*a*a

The input (the list of variables and the term) may be supplied in any way suitable for the language.

The output can be in any sensible form (one parsing per line or a comma-separated list etc.) - but it should be unambiguous and possible to read.

Empty output is acceptable if there is no possible parsing of a term (in the examples I used '-' for clarity).

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

Pyth, 18 chars

mj\*dfqzsTsm^Qkhlz

This solution is adapted from my Interpreting Fish
solution. The problems are actually very similar.

Expects input as such:

aaaa
"a", "aaa"

Gives output like this:

['a*aaa', 'aaa*a', 'a*a*a*a']

Try it here.

sm^Qkhlz: Generates all sequences of variables containing up to the length of the input string number of variables.
fqzsT: Filters out the variable sequences that match the input string
mj\*d: Inserts the * symbol and prints.


Filter out the pseudo-elements! We define the hyper-average of an array / list (of numbers) the arithmetic mean of the sums of its prefixes.

For example, the hyper-average of the list [1, 4, -3, 10] is computed in the following manner:

We get the prefixes: [1], [1, 4], [1, 4, -3], [1, 4, -3, 10].
Sum each: [1, 5, 2, 12].
And now get the arithmetic mean of the elements in this list: (1 + 5 + 2 + 12) / 4 = 5.

A pseudo-element of an array is an element whose value is strictly lower than its hyper-average. Hence, the pseudo-elements of our example list are 1, 4 and -3.

Given a list of floating-point numbers, your task is to return the list of pseudo-elements.

You don't have to worry about floating-point inaccuracies.
The input list will never be empty and it may contain both integers and floats. If mentioned, integers may be taken as floats (with <integer>.0)
You may assume that the numbers fit your language of choice, but please do not abuse that in any way.
Optionally, you may take the length of the array as input as well.
This is code-golf, so standard rules for the tag apply. The shortest code in bytes (in each language) wins!

Test Cases

Input -> Output

[10.3] -> []
[5.4, 5.9] -> [5.4, 5.9]
[1, 4, -3, 10] -> [1, 4, -3]
[-300, -20.9, 1000] -> [-300, -20.9]
[3.3, 3.3, 3.3, 3.3] -> [3.3, 3.3, 3.3, 3.3]
[-289.93, 912.3, -819.39, 1000] -> [-289.93, -819.39]

05AB1E, 9 8 bytes

-1 bytes thanks to Magic Octopus Urn

ηOO¹g/‹Ï

Try it online!

η        # Get prefixes
 O       # Sum each
  O¹g/   # Get the mean ( length(prefix list) equals length(original list) )
      ‹Ï # Keep only the value that are less than the mean

05AB1E, 6 bytes

Using the new ÅA command.

ηOÅA‹Ï

Try it online!

η      # Get prefixes
 O     # Sum each
  ÅA   # Get the mean
    ‹Ï #  Keep only the value that are less than the mean


Golf Me a World Clock Task

Write a program or function that takes as input a time in UTC, and outputs the equivalent time in 5 different cities around the world. The cities displayed are up to the programmer, but the time must be different in each city.

To prevent golfers from using overly obscure city names, the city names used must appear on this list: World Cities*, which corresponds to the list of cities and times found here.

As usual, Standard loopholes are forbidden, including fetching data from an external source.

*The times provided in the pastebin use daylight time and assume that the time is 0:30 UTC.

Example

Given as input 12:30AM, your output might be:

Athens: 3:30AM
London: 1:30AM
New York: 8:30PM
Seoul: 9:30AM
Beijing: 8:30AM

Input

You may take input in any reasonable format. You can choose to take the time as 24-hour time, or 12-hour time with AM and PM. Specify the input format in your answer.

Output

Output may also be in either 12-hour or 24-hour time. The city-time pairs may be in any order and any reasonable format, so long as it is possible to associate each city with the corresponding time.

Daylight Savings Time can safely be ignored (ie. you can either use the offsets from the pastebin above, or you can assume that all times are in daylight time, or alternatively all in standard time)

Scoring

This is code-golf. Happy golfing!

Python 2, 80 79 77 bytes
-1 byte thanks to Surculose Sputum.
24-hour time, input as hours, minutes.

h,m=input();i=h
exec"print'ALCADcaamucgimbroraaasoni'[i-h::5],i%24,m;i+=1;"*5

Try it online!
Example output for 0, 30 (12:30AM):
Accra 0 30
Lagos 1 30
Cairo 2 30
Amman 3 30
Dubai 4 30


Count forth and back then double up Let's count...

Count up to 2 and back to 1
Count up to 4 and back to 1
Count up to 6 and back to 1
... ok you got it...

put all these together and you'll get the following sequence

 {1,2,1,2,3,4,3,2,1,2,3,4,5,6,5,4,3,2,1,2,3,4,5,6,7,8,7,6,5,4,3,2,1,2,3...}

Challenge
Given an integer n>0for 1-indexed (or n>=0 for 0-indexed), output the nth term of this sequence

Test cases

Input->Output

1->1
68->6
668->20
6667->63
10000->84

Rules

your program must be able to compute solutions up to n=10000 in under a minute

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

JavaScript (ES7),  59 ... 44  43 bytes
Saved 1 byte thanks to Titus
Expected input: 1-indexed.
n=>(n-=(r=(~-n/2)**.5|0)*r*2)<++r*2?n:r*4-n

Initially inspired by a formula for A004738, which is a similar sequence. But I ended up rewriting it entirely.
Test cases

let f=

n=>(n-=(r=(~-n/2)**.5|0)*r*2)<++r*2?n:r*4-n

console.log(f(1))     // -> 1
console.log(f(68))    // -> 6
console.log(f(668))   // -> 20
console.log(f(6667))  // -> 63
console.log(f(10000)) // -> 84

How?
The sequence can be arranged as a triangle, with the left part in ascending order and the right part in descending order.
Below are the first 4 rows, containing the first 32 terms:
            1 | 2
        1 2 3 | 4 3 2
    1 2 3 4 5 | 6 5 4 3 2
1 2 3 4 5 6 7 | 8 7 6 5 4 3 2

Now, let's introduce some variables:
 row  | range   | ascending part              | descending part
 r    | x to y  | 1, 2, ..., i                | 4(r+1)-(i+1), 4(r+1)-(i+2), ...
------+---------+-----------------------------+-----------------------------------------
  0   |  1 -  2 |                           1 | 4-2
  1   |  3 -  8 |                   1   2   3 | 8-4  8-5  8-6
  2   |  9 - 18 |           1   2   3   4   5 | 12-6 12-7 12-8  12-9  12-10
  3   | 19 - 32 |   1   2   3   4   5   6   7 | 16-8 16-9 16-10 16-11 16-12 16-13 16-14

We start with 2 elements at the top and add 4 elements on each new row. Therefore, the number of elements on the 0-indexed row r can be expressed as:
a(r) = 4r + 2

The 1-indexed starting position x of the row r is given by the sum of all preceding terms in this arithmetic series plus one, which leads to:
x(r) = r * (2 + a(r - 1)) / 2 + 1
     = r * (2 + 4(r - 1) + 2) / 2 + 1
     = 2r² + 1

Reciprocally, given a 1-indexed position n in the sequence, the corresponding row can be found with:
r(n) = floor(sqrt((n - 1) / 2))

or as JS code:
r = (~-n / 2) ** 0.5 | 0

Once we know r(n), we subtract the starting position x(r) minus one from n:
n -= r * r * 2

We compare n with a(r) / 2 + 1 = 2r + 2 to figure out whether we are in the ascending part or in the descending part:
n < ++r * 2 ?

If this expression is true, we return n. Otherwise, we return 4(r + 1) - n. But since r was already incremented in the last statement, this is simplified as:
n : r * 4 - n


Quine / Reverse Quine Write a complete program that takes a boolean or non-negative integer input. It must:

Output its own source code if the input value is falsy
Output its own source code in reverse if the input value is truthy

Your program cannot be palindromic, nor can it read its own source code by any means.

This is code golf - shortest code in bytes wins.

CJam, 17 16 bytes

{`"_~"+Wq~g#%}_~

Test it here.

A fairly straight-forward modification of the standard quine. Other solutions for 17 bytes:

{`"_~"+q~{W%}&}_~
{`"_~"+q~!2*(%}_~

If I can assume that the input is only 0 or 1 (as a stand-in for a boolean, which there is no dedicated type for in CJam), I get 15 by omitting the g:

{`"_~"+Wq~#%}_~

Explanation

{`"_~"+  e# Standard generalised quine framework. Leaves the source code on the stack.
  W      e# Push a -1.
  q~     e# Read and evaluate input.
  g      e# signum, turning truthy values into 1 (leaving 0 unchanged).
  #      e# Power. -1^0 == 1, -1^1 == -1.
  %      e# Select every Nth element: a no-op for 1 and reverses the string for -1.
}_~


List Sophie Germain primes The Question
A Sophie Germain prime is a prime \$p\$ such that \$2p+1\$ is prime as well. For example, 11 is a Sophie Germain prime because 23 is prime as well. Write the shortest program to calculate Sophie Germain primes in ascending order
Rules

The Sophie Germain primes must be generated by your program, not from an external source.
Your program must calculate all Sophie Germain primes under \$2^{32}-1\$
You must print each distinct Sophie Germain prime your program finds.
The person with the lowest score wins

Scoring

2 points per byte of your code
-10 if you can show a prime generated by your program greater than \$2^{32}-1\$

Pyth, 19 bytes * 2 - 10 = 28

Note that the online compiler/executor doesn't show output because it's an infinite loop.

K1#~K1I&!tPK!tPhyKK

Explained:

K1                      K=1
  #                     While true:
   ~K1                  K+=1
      I                 If
       &                logical AND
        !tPK            K is prime
            !tPhyK      2*K+1 is prime (y is double, h is +1)
                  K     Print K


Plant a tree and watch it grow The trees we are growing have some rules that define how they grow:

Growth Rules:

Trees consist only of branches.
Branches are made up of a combination of the following symbols:  _, \, |, /, & _
A tree starts as a single vertical branch/trunk (|) on the ground (_):

__________________|___________________
The food for branch growth comes from light.

Light starts at an intensity of 2 at each point in the sky and travels straight down.
Each branch is able to eat half the light available to it and the rest passes through to lower branches.
Thus, a branch with no other branches above it will get 1 unit of light-food each season, a branch with 1 branch above it will get .5 units of food each season, and in general a branch with n branches over it will get 1/(2^n) units of food each season.

At the end of each season, the food is totaled starting with the trunk and moving up and converted into new branches and fruit (apply the following rules until the branch turns into fruit or has less than 1 unit of food remaining):

If a branch has less than 1 unit of food at the end of a season, all the food for that branch is stored in that branch until the next season.
If a branch has greater than or equal to 1 unit of food and has room to grow, it randomly grows a new branch using the available growth patterns (see below) and stores the remaining food for the next season.
If a branch has >= 1 unit of food, nowhere to grow, and has offshoot branches, it evenly distributes the food to its offshoot branches
If a branch has >= 1 unit of food, nowhere to grow, and no offshoot branches, it becomes fruit (represented by O)

Here are the possible growth configurations

Growth Configurations:

_    \     |     /   _      _   \   |    /   \    |   /   _
 |    |    |    |   |        \   \   \   \   /   /   /   /     __   \_   |_   _|  _/  __
--- Vertical Branches ---      --- Diagonal Branches ---      --- Horizontal Branches ---

Example potential tree:

                \
                /   /
              \/O  |___//
            \_/  \//O\_/
              \__/|\|_/
                 \|/
__________________|__________________

Input:

Your program should be able to take as input a list of which snapshots of the tree you would like to see.  For example [10,20,50] would mean you'd like to see the tree after 10 seasons, 20 seasons, and 50 seasons.

Output:

For each input season, your program should output the season and then a picture of the tree in that season.  If it helps, you can define a maximum age for the tree, such as 60, so that the maximum height for a tree would be 61, and the maximum width would be 121, and then always show the tree on that scale.  Otherwise, feel free to scale your image to any sized tree.  For example, if the input was [0,1,2,3], your output might be:

Season 0:
_|_

Season 1:
 \
__|__

Season 2:
 _
  \|
___|___

Season 3:

 |_/ _
   \|
____|___

Winner

Each solution must post the output of the coder's favorite run of their program with input of [10,40], along with their source code.  Also, ALL the above criteria must be met in order to qualify.

The winner will be the qualifier with the highest number of votes.

Good luck and merry planting!!!


Cyclic Polyglot Challenge (Cops) Cyclic Polyglot Challenge

This is the cops thread. You can find the robbers thread here.

Cyclic Polyglot

A N-element cyclic polyglot is a complete program that can be run in N different languages. In each language, when the program is run with no input (possibly subject to this exception), it should print the name of a language to STDOUT. Specifically, if the program is run in the Kth language, it should print the name of the (K+1)th language. If the program is run in the Nth language (that is, the final language in an N-element cycle), it should print the name of the first language.

An example might be useful.

a = [[ v = 7, puts('Befunge') ]]
__END__
= print("Ruby")
-->*+:292*++,,@
--3    9
--7    *
--^,:-5<

Running this program with Lua prints the string "Ruby". Running this program in Ruby prints the string "Befunge". Running this program in Befunge prints the string "Lua", completing the cycle. This program constitutes a 3-cycle consisting of Lua, Ruby, and Befunge.

The same language cannot appear twice in a cycle, and different versions of the same language (such as Python 2 and Python 3) cannot appear in the same cycle as one another.

Cops

Your challenge is to write an N-cyclic polyglot, where N is at least 2. Then, you must add, replace, and delete some number of characters to the program to produce an M-cyclic polyglot, where M is strictly greater than N. You should then post the shorter, N-cyclic polyglot (and the languages it runs in), as well as the number of characters you changed to produce the longer polyglot. Your score is N, the number of languages in your shorter cycle.

The robbers will try to identify your longer cycle. If, after seven days, no one has successfully cracked your solution, you should edit your answer declaring that it is safe. You should also post your longer M-cyclic polyglot at this time.

Robbers

Given a cop's N-cyclic polyglot and the number of characters they added to produce a larger polyglot cycle, your goal is to produce that larger cycle. If you can produce a longer cycle by adding, deleting, or replacing as many characters as the cop did or fewer characters, you have cracked the cop's polyglot. Your score is the length of the new cycle you've created. Your new polyglot need not be the same as or even similar to the cop's secret polyglot; it only needs to be larger than their existing one.

Your solution may also be cracked. If another robber comes along and produces a cycle strictly longer than yours, starting from the same cop's polyglot, they have stolen your points.

Valid Programming Languages

Since this challenge indirectly involves guessing programming languages used by other participant's, the definition of a programming language for the purposes of this challenge will be a little more strict than the usual definition. A programming language used in this challenge must satisfy all of the following conditions.

The language must satisfy the usual PPCG requires for a programming language.
The language must have either a Wikipedia article, an Esolangs article, or a Rosetta Code article at the time this challenge was posted.
The language must have a freely available interpreter or compiler.

Final Notes

The code you write should be a standalone program in every language that it is intended to run in. Functions or code snippets are not allowed.
Your program will be given no input through STDIN. Likewise, your program should print nothing to STDERR.
A cop's score is the number of languages in the cycle of the polyglot they posted. The cop should post the languages that the posted polyglot runs correctly in, as well as the number of characters they added to produce a longer polyglot. They are not responsible for posting the languages the longer, hidden polyglot runs in until their answer is safe.
A robber's score is the number of languages the modified polyglot runs in. As with the cop, the robber should post the list of languages the polyglot runs correctly in.
The number of characters changed should be computed in Levenshtein distance.

C (gcc), 126 bytes

M=N+1

Levenshtein(polyglot(M),polyglot(N)) is 36 bytes

#include<stdio.h>
#define print(a) main(){int z[1];if(sizeof(0,z)==4)printf("C(gcc)");else printf("Perl5");}
print("C++(gcc)")

Try it online!


Area of the triangle Another easy challenge for you.
Your task
Write a program or function that takes the input, which contains 3 pairs of x- and y-coordinates and calculates the area of the triangle formed inside them. For those who can't remember how to calculate it, you can find it here.
Example:
1,2,4,2,3,7       # input as x1,y1,x2,y2,x3,y3
7.5               # output

See it at Wolfram Alpha
Some considerations:

The input will be six base 10 positive integers.
You may assume the input is in any reasonable format.
The points will always form a valid triangle.
You can assume the input is already stored in a variable such as t.
The shortest code in bytes wins!

Edit: To avoid any confusion I've simplificated how the input should be dealt without jeopardizing any of the current codes.
Remember that the your program/function must output a valid area, so it can't give a negative number as output

CJam, 18 16 bytes

T(f.-~(+.*:-z.5*

Try it online in the CJam interpreter.

Idea

As mentioned on Wikipedia, the area of the triangle [[0 0] [x y] [z w]] can be calculated as |det([[x y] [z w]])| / 2 = |xw-yz| / 2.

For a generic triangle [[a b] [c d] [e f]], we can translate its first vertex to the origin, thus obtaining the triangle [[0 0] [c-a d-b] [e-a f-b]], whose area can be calculated by the above formula.

Code

T                  e# Push T.
                   e# [[a b] [c d] [e f]]
   (               e# Shift out the first pair.
                   e# [[c d] [e f]] [a b]
    f.-            e# For [c d] and [e f], perform vectorized
                   e# subtraction with [a b].
                   e# [[c-a d-b] [e-a f-b]]
       ~           e# Dump the array on the stack.
                   e# [c-a d-b] [e-a f-b]
        (+         e# Shift and append. Rotates the second array.
                   e# [c-a d-b] [f-b e-a]
          .*       e# Vectorized product.
                   e# [(c-a)(f-b) (d-b)(e-a)]
            :-     e# Reduce by subtraction.
                   e# (c-a)(f-b) - (d-b)(e-a)
              z    e# Apply absolute value.
                   e# |(c-a)(f-b) - (d-b)(e-a)|
               .5* e# Multiply by 0.5.
                   e# |(c-a)(f-b) - (d-b)(e-a)| / 2


Weight of the Least Weighted RoD Path Let A be an m by n rectangular matrix of positive integers, where m and n are also positive integers.
We are interested in RoD ('Right-or-Down') paths from the upper-left cell of A to the lower right cell; in an RoD path, each successive cell of the path is either one cell to the Right of or one cell Down from the previous cell.
Given any such RoD path, we can take the sum of the cells in A in that path.
For example, consider the 4 by 3 matrix:
[ [1, 2, 3, 4],
  [5, 1, 6, 7],
  [8, 2, 1, 1] ]

Then we can consider the RoD path:
1 > 2   3   4
    v
5   1   6   7
    v
8   2 > 1 > 1

which has a sum of 1+2+1+2+1+1=8. It's worth noting that this path has the smallest sum of all possible RoD paths from upper left to lower right in that matrix.
So, the proposed challenge is to provide the shortest function/program in your language of choice that outputs the minimum sum an RoD path from upper left to lower right can have in a given matrix A.
The usual forbidden loopholes are in effect. Your input can be in any reasonable format; your output must be an integer.
This is code-golf; answers are scored by number of bytes.
Test Cases
[ [5] ] -> 5

[ [5, 2] ] -> 7

[ [5],
  [2] ] -> 7

[ [ 9 , 1 , 12, 3 ],
  [ 12, 11, 6 , 11],
  [ 12, 9 , 2 , 11] ] -> 40

[ [ 6 , 8 , 11, 2 ],
  [ 3 , 6 , 7 , 6 ],
  [ 6 , 2 , 8 , 12] ] -> 37

[ [ 4 , 5 , 8 , 4 ],
  [ 6 , 5 , 9 , 4 ],
  [ 2 , 5 , 6 , 8 ] ] -> 31

[ [ 4 , 5 , 15, 18, 30],
  [ 26, 26, 3 , 4 , 5 ],
  [ 7 , 9 , 29, 25, 14],
  [ 16, 1 , 27, 13, 27],
  [ 23, 11, 25, 24, 12],
  [ 17, 23, 7 , 14, 5 ] ] -> 94

[ [ 10, 15, 7 , 2 , 9 ],
  [ 24, 5 , 2 , 1 , 25],
  [ 2 , 12, 14, 30, 18],
  [ 28, 4 , 12, 22, 14],
  [ 15, 21, 21, 11, 4 ],
  [ 21, 15, 21, 29, 9 ] ] -> 103

J, 42 bytes

v(+}.<.}:)&.>/@{.[:</.(2#v=._1+1#.$){.!._]

Try it online!

How it works

v(+}.<.}:)&.>/@{.[:</.(2#v=._1+1#.$){.!._]
                         v=._1+1#.$         Sum of two dimensions - 1; assign to v
                                            (v is a verb)
                      (2#          ){.!._]  Extend the given array in both dimensions
                 [:</.  Extract the antidiagonals as boxed arrays
v             @{.  Take the first `v` antidiagonals
 (       )&.>/     Reduce over unboxed items:
   }.<.}:            Given the right item R, take the minimum of R[1:] and R[:-1]
  +                  Add to the left item

Illustration

1 2 3 4  Input array, dimensions = 3,4
5 1 6 7
8 2 1 1

1 2 3 4 _ _  Extended to 6,6 with filler _ (infinity)
5 1 6 7 _ _
8 2 1 1 _ _
_ _ _ _ _ _
_ _ _ _ _ _
_ _ _ _ _ _

1            Diagonalize and take first 6 rows
5 2
8 1 3
_ 2 6 4
_ _ 1 7 _
_ _ _ 1 _ _

Reduction: left+min(right[1:], right[:-1])
1                                          1  => 8
5 2                               5  2  => 10 7
8 1 3                   8 1 3  => 12 5 11
_ 2 6 4      _ 2 6 4 => _ 4 8 12
_ _ 1 7 _ => _ _ 2 8 _
_ _ _ 1 _ _


Shortest pristine truth machine In this challenge, the goal is to create a pristine truth machine in as few bytes as possible. For reference, a truth machine does the following:

Takes input, which is always 0 or 1
If the input is 0, it is printed and the program terminates
If the input is 1, it is printed forever

A pristine program is one that does not error on its own, but will error if any single substring with a length \$1\le n<p\$ is removed (where \$p\$ is the length of the program).
For example, if the main did not error in some language, it would be pristine if all of the following produced an error:
mai
man
min
ain
ma
mn
in
m
n

The goal of this challenge is to write the shortest program or function (in bytes, per language) which is a pristine truth machine.

Rust, 109 106 bytes

fn t(n:i8)->Result<Box::<Iterator::<Item=i8>>,i8>{if n==0{Err(0)}else{Ok(Box::new(std::iter::repeat(1)))}}

Try it online!
Returns a result whose ok variant is a dynamically typed iterator that always yields one wrapped in a smart pointer so the compiler can know its size. The error variant is simply zero. The code does emit a deprecation warning, so it may randomly stop working at some point in the future. Rust's type inference is too good for me to get a pristine closure, and as verbose as this solution is it is still shorting than fully listing the returned iterator's type and much shorter than using the main function and reading from stdin.
-3 bytes because there is a method to create an endlessly repeating iterator


Consecutive 1-Bits are Incremented Given a pattern (string or array format) of Bits :
[0,1,1,1,0,1,1,0,0,0,1,1,1,1,1,1]

The tasks is to replace any number of consecutive 1-Bits with an ascending number sequence starting at 1.

Input

Pattern (can be received as an string or array) Example:

String: 1001011010110101001
Array: [1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1]

Output

Ascending number sequence (can be returned as an string or array) Example:

String: 1 0 0 1 0 1 2 0 1 0 1 2 0 1 0 1 0 0 1
Array: [1, 0, 0, 1, 0, 1, 2, 0, 1, 0, 1, 2, 0, 1, 0, 1, 0, 0, 1]

Rules

(only apply for strings) Input wont contain spaces between 1 and 0
Assume Input length > 0
(only apply for strings) Output is separated by space (use any other separator if you need as long as is not a number or a letter from the alphabet)

Example:

Given [0,1,1,1,0,1,1,0,0,0,1,1,1,1,1,1]
Output [0,1,2,3,0,1,2,0,0,0,1,2,3,4,5,6]

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

Given 0110101111101011011111101011111111
Output 0 1 2 0 1 0 1 2 3 4 5 0 1 0 1 2 0 1 2 3 4 5 6 0 1 0 1 2 3 4 5 6 7 8

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

Given 11111111111101
Output 1 2 3 4 5 6 7 8 9 10 11 12 0 1

Winning criteria: Codegolf

05AB1E, 4 bytes

γ€ƶ˜

Try it online!
or as a Test Suit

Explanation

γ      # split input into groups of consecutive equal elements
 €ƶ    # multiply each number in each sublist by its 1-based index in the sublist
   ˜   # flatten


MATL, 10 bytes
yt&y)>fYk)

This uses 1-based indexing. Try it online!
Explanation
Consider inputs [4,-2,1,-3,5], 3 as an example.
y     % Take two inputs implicitly. Duplicate 2nd-top element in the stack
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5]
t     % Duplicate top of the stack
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], [4,-2,1,-3,5]
&y    % Duplicate 3rd-top element in the stack
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], [4,-2,1,-3,5], 3
)     % Index: select elements from first input as indicated by second input
      % STACK: [4,-2,1,-3,5], 3, [4,-2,1,-3,5], 1
>     % Greater than, element-wise
      % STACK: [4,-2,1,-3,5], 3, [1,0,0,0,1]
f     % Find: gives indices of non-zero entries
      % STACK: [4,-2,1,-3,5], 3, [1,5]
Yk    % Closest element: gives closest element of each entry in second input
      % ([1,5]) to each entry in the first input (3). In case of a tie it
      % gives the left-most one
      % STACK: [4,-2,1,-3,5], 1
)     % Index: select elements from first input as indicated by second input
      % STACK: 4
      % Implicitly display


TTT: Turing Text Tape Introduction
Ah, INTERCAL...
As much as I'd like encourage everyone to Try it Online, text output is just painful.
According to the docs it uses the "Turing Text Model".
While an... interesting concept, using it is about as much fun as shooting yourself in the foot.
And what do we do with a task like this? Automate it.
The Turing Text Model
The characters INTERCAL knows are printed on a circular tape that can only be moved in the positive direction. Printing is done by passing tape head movement commands in an array to the READ OUT statement.
Every ASCII character is written on the inside of that tape (The outside has the characters for the input on it, duh). This results in the characters' bytes being on the tape in reverse. Also the tape head moves backwards along the character list, because its positioning is based on the outside of the tape.
The head starts at position 0.
Now the magic starts.
I'll be using Truttle1's explanation on how to achieve output.

Set up an array with the output length.
Fill the entries in the array with tape head movement values.

Find the current character's ASCII value in binary
Reverse it and convert back a number n.
Subtract n from the current head postion and modulo by 256 if needed, resulting in a value r
r is the value you need to store in the array
The head is now at position n.

DO READ OUT the array.

PLEASE NOTE

Array is pre-initialized with 0, first index is 1
INTERCAL uses extended 8-bit ASCII characters, hence the tape length of 256.
Between 1/3rd and 1/5th of all lines have to start with PLEASE. Note that in that case you drop the DO for GIVE UP and READ OUT, but not for anything else, as seen in the examples.

Challenge
Given an input string, output a valid INTERCAL program that prints that string and terminates.
Examples
Prints "BUZZ"
DO ,1 <- #4
DO ,1 SUB #1 <- #190
DO ,1 SUB #2 <- #152
PLEASE DO ,1 SUB #3 <- #336
DO READ OUT ,1
PLEASE GIVE UP

Whitespace is optional. The following prints "FIZZ"
DO,1<-#4DO,1SUB#1<-#158DO,1SUB#2<-#208DO,1SUB#3<-#312PLEASEREADOUT,1PLEASEGIVEUP

(Examples shamelessly stolen from Truttle1's FizzBuzz program from the video.)
You can find an ungolfed reference implementation in python 3 here
Rules

No standard loopholes
This is code-golf, shortest code wins.
You can expect input >= 1, ASCII characters only.
The program may not throw any errors apart from ICL774I RANDOM COMPILER BUG and ICL666I COMPILER HAS INDIGESTION. First one happens at random, second one is C-Intercal running out of memory and circumventing that isn't part of the
challenge

Python 3, 157 bytes

t=i=0
p=o='PLEASE'
for c in input():i+=1;k=int(f'{ord(c):08b}'[::-1],2);o+=i%4//3*p+f'DO,1SUB#{i}<-#{t-k&255}';t=k
print(f'DO,1<-#{i}{o}DOREADOUT,1DOGIVEUP')

Try it online!
This prints \$n+3\$ instructions, of which \$\left\lfloor \frac{n+5}{4} \right\rfloor\$ are polite. That ratio just barely fits in the \$[1/5, 1/3]\$ politeness interval for all \$n \geq 1\$.
-1 byte thanks to Neil.