Find The Wordiest Combination Lock I have a combination padlock which has letters instead of numbers. It looks like this: http://pictures.picpedia.com/2012/09/Word_Combination_Padlock.jpg There are 5 reels, each of which has 10 different letters on it.

Most people like to use a word for their combination rather than an arbitrary string of letters. (Less secure, of course, but easier to remember.) So when manufacturing the lock, it would be good to build it to have a combination of letters which can be used to create as many 5-letter English words as possible.

Your task, should you choose to accept it, is to find an assignment of letters to reels which will allow as many words as possible to be created. For example, your solution might be

ABCDEFGHIJ DEFGHIJKLM ZYXWVUTSR ABCDEFGHIJ ABCDEFGHIJ

(If you weren't feeling too imaginative, that is).

For consistency, please use the word list at http://www.cs.duke.edu/~ola/ap/linuxwords

Any 5-letter word in that list is OK, including proper names. Ignore Sino- and L'vov and any other words in the list which contain a non a-z character.

The winning program is the one which produces the largest set of words. In the event that multiple programs find the same result, the first one to be posted wins. The program should run in under 5 minutes.

Edit: since activity has died down, and no better solutions have come out, I declare Peter Taylor the winner! Thanks everyone for your inventive solutions.

1275 words by simple greedy hill-climbing

Code is C#. Solution produced is

Score 1275 from ^[bcdfgmpstw][aehiloprtu][aeilnorstu][acdeklnrst][adehklrsty]$

I'm using that output format because it's really easy to test:

grep -iE "^[bcdfgmpstw][aehiloprtu][aeilnorstu][acdeklnrst][adehklrsty]$" linuxwords.txt | wc

namespace Sandbox {
    class Launcher {
        public static void Main(string[] args)
        {
            string[] lines = _Read5s();
            int[][] asMasks = lines.Select(line => line.ToCharArray().Select(ch => 1 << (ch - 'a')).ToArray()).ToArray();
            Console.WriteLine(string.Format("{0} words found", lines.Length));

            // Don't even bother starting with a good mapping.
            int[] combos = _AllCombinations().ToArray();
            int[] best = new int[]{0x3ff, 0x3ff, 0x3ff, 0x3ff, 0x3ff};
            int bestSc = 0;
            while (true)
            {
                Console.WriteLine(string.Format("Score {0} from {1}", bestSc, _DialsToString(best)));

                int[] prevBest = best;
                int prevBestSc = bestSc;

                // Greedy hill-climbing approach
                for (int off = 0; off < 5; off++)
                {
                    int[] dials = (int[])prevBest.Clone();

                    dials[off] = (1 << 26) - 1;
                    int[][] filtered = asMasks.Where(mask => _Permitted(dials, mask)).ToArray();
                    int sc;
                    dials[off] = _TopTen(filtered, off, out sc);
                    if (sc > bestSc)
                    {
                        best = (int[])dials.Clone();
                        bestSc = sc;
                    }
                }

                if (bestSc == prevBestSc) break;
            }

            Console.WriteLine("Done");
            Console.ReadKey();
        }

        private static int _TopTen(int[][] masks, int off, out int sc)
        {
            IDictionary<int, int> scores = new Dictionary<int, int>();
            for (int k = 0; k < 26; k++) scores[1 << k] = 0;

            foreach (int[] mask in masks) scores[mask[off]]++;

            int rv = 0;
            sc = 0;
            foreach (KeyValuePair<int, int> kvp in scores.OrderByDescending(kvp => kvp.Value).Take(10))
            {
                rv |= kvp.Key;
                sc += kvp.Value;
            }
            return rv;
        }

        private static string _DialsToString(int[] dials)
        {
            StringBuilder sb = new StringBuilder("^");
            foreach (int dial in dials)
            {
                sb.Append('[');
                for (int i = 0; i < 26; i++)
                {
                    if ((dial & (1 << i)) != 0) sb.Append((char)('a' + i));
                }
                sb.Append(']');
            }
            sb.Append('$');
            return sb.ToString();
        }

        private static IEnumerable<int> _AllCombinations()
        {
            // \binom{26}{10}
            int set = (1 << 10) - 1;
            int limit = (1 << 26);
            while (set < limit)
            {
                yield return set;

                // Gosper's hack:
                int c = set & -set;
                int r = set + c;
                set = (((r ^ set) >> 2) / c) | r;
            }
        }

        private static bool _Permitted(int[] dials, int[] mask)
        {
            for (int i = 0; i < dials.Length; i++)
            {
                if ((dials[i] & mask[i]) == 0) return false;
            }
            return true;
        }

        private static string[] _Read5s()
        {
            System.Text.RegularExpressions.Regex word5 = new System.Text.RegularExpressions.Regex("^[a-z][a-z][a-z][a-z][a-z]$", System.Text.RegularExpressions.RegexOptions.Compiled);
            return File.ReadAllLines(@"d:\tmp\linuxwords.txt").Select(line => line.ToLowerInvariant()).Where(line => word5.IsMatch(line)).ToArray();
        }
    }
}


Undefined Behavior Killed My Cat Undefined Behavior Killed My Cat

It's well known that undefined behavior can kill your cat [citation needed].
But can it?

Your Task

Write a program that invokes undefined behavior.
Describe a scenario that starts with the above program being run, resulting in a Felis catus ending its life while in your ownership, as a result of the aforementioned UB.
Estimate the probability for each stage in the scenario.
Calculate the total probability that a single run of the program would kill your cat.

Rules

This is a popularity-contest, so be creative if you can.
This is a programming related challenge, so the chain of events should be mostly within the computer, not in the real world (of course, if has to reach the real world if that's where your cat is).
If you choose a language that doesn't have undefined behavior, use something similar.
No animals may be harmed in the production of your answer.

Scoring

Vote count plus the scenario's total probability (which can't exceed 1).

Example in C:

main(){printf();}

Scenario:

printf called with garbage from the stack - undefined behavior. Probablity: 100%.
The first parameter happens to be the string Your cat is ugly!. Probablity: (1/256)17 = (1.148 * 10-37)%.
Seeing the message, you pick up your gun and shoot your cat. Probability: 3%.
The cat dies. Probability: 93%.

Total probability: (3.202 * 10-39)%.

C

Most answers to this question misinterpreted the question in that it was killing the cat process on a UNIX system. Here is a program which can cause the demise of a biological lifeform of the species Felis Cattus as specificed by the question.

This example runs on Windows, but it could be easily ported to most UNIX operating systems by replacing iexplore -k with the command to launch an installed web browser.

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

int main() {
    char i; // uninitialised
    printf("Redirecting you to a website which will inform you how to properly feed your cat.");
    if (i != 42) {
         system("iexplore -k https://pets.stackexchange.com/questions/tagged/cats+diet");
    } else {
         system("iexplore -k https://cooking.stackexchange.com/questions/tagged/chocolate");
    }
    return 0;
}

This program pretends to provide advise about cat diet to the user.

It will start Internet Explorer and direct the user to pets stackexchange listing lots of helpful questions about how to feed cats. There is, however, a low (1/256) chance that it will send the user to cooking stackexchange instead listing tips how to prepare dishes containing chocolate, which is highly toxic to cats. To make matters worse, it will launch internet explorer in kiosk mode (fullscreen), which hides the address bar and is hard to escape from for a non-tech-savy user.

This clever ruse will coax the user into feeding their cat chocolate believing that it is an appropriate diet for it, thus causing them to inadvertedly kill it.


Each step of the Levenshtein distance In this challenge you will write a program that takes two newline-separated strings, s1 (the first line) and s2 (the second line), as input (STDIN or closest). You can assume that the length of s1 will always be smaller than 30 and bigger than the length of s2. The program should then output each step in the levenshtein distance from s1 to s2.

To clarify what each step in the levenshtein distance means, the program will print n strings, where n is the levenshtein distance between s1 and s2, and the levenshtein distance between two adjacent strings will always be one. The order doesn't matter. The output should be newline-separated and not include s1, only the in-betweens and s2. The program should also run in under one minute on a modern computer.

Examples:

Input:

Programming
Codegolf

Output:

rogramming
Cogramming
Coramming
Coamming
Codmming
Codeming
Codeging
Codegong
Codegolg
Codegolf

Input:

Questions
Answers

Output:

uestions
Aestions
Anstions
Ansions
Answons
Answens
Answers

Input:

Offline
Online

Output:

Ofline
Online

Input:

Saturday
Sunday

Output:

Sturday
Surday
Sunday

Here is a link to a python script that prints out the distance and the steps.

Additional rules:

No use of the internet
Standard loopholes apply

This is code-golf so keep you code short; shortest code wins!

Haskell, 201 194 bytes

l=length
g[]n u=map(\_->"")n
g(b:c)[]u=(u++c):g c[]u
g(b:c)n@(o:p)u|b==o=g c p(u++[o])|1<2=((u++o:c):g c p(u++[o]))!((u++c):g c n u)
a!b|l a<l b=a|1<2=b
p[a,n]=g a n""
f=interact$unlines.p.lines

Longer than expected. Maybe I can golf it down a little bit ...

Usage example:

*Main> f                     -- call via f
Questions                    -- User input
Answers                      -- no newline after second line!
uestions                     -- Output starts here
Aestions
Anstions
Ansions
Answons
Answens
Answers

It's a brute force that decides between changing and deleting if the initial characters differ.


Resolve SAS macro variables The SAS programming language is a clunky, archaic language dating back to 1966 that's still in use today. The original compiler was written in PL/I, and indeed much of the syntax derives from PL/I. SAS also has a preprocessor macro language which derives from that of PL/I as well. In this challenge, you'll be interpreting some simple elements of the SAS macro language.

In the SAS macro language, macro variables are defined using the %let keyword and printing to the log is done with %put. Statements end with semicolons. Here are some examples:

%let x = 5;
%let cool_beans =Cool beans;
%let what123=46.lel"{)-++;

Macro variable names are case insensitive and always match the regular expression /[a-z_][a-z0-9_]*/i. For the purposes of this challenge, we'll say the following:

Macro variables can only hold values consisting entirely of printable ASCII characters except ;, &, and %
There will be no leading or trailing spaces in the values
The values will never be more than 255 characters long
Values may be empty
Brackets and quotes in the values may be unmatched
There can be any amount of space before and after the = in the %let statement and this space should be ignored
There can be any amount of space before the terminal ; in the %let statement and this space should similarly be ignored

When a macro variable is called, we say it "resolves" to its value. Macro variables are resolved by prepending &. There is an optional trailing . that denotes the end of the identifier. For example,

%put The value of x is &X..;

writes The value of x is 5. to the log. Note that two periods are required because a single period will be consumed by &X. and resolve to 5. Also note that even though we defined x in lowercase, &X is the same as &x because macro variable names are case insensitive.

Here's where it gets tricky. Multiple &s can be strung together to resolve variables, and &s at the same level of nesting resolve at the same time. For example,

%let i = 1;
%let coolbeans1 = broseph;
%let broseph = 5;

%put &&coolbeans&i;  /* Prints broseph */
%put &&&coolbeans&i; /* Prints 5 */

The innermost &s resolve first, and resolution continues outward. Variable name matching is done greedily. In the second %put statement, the processor makes the following steps:

&i resolves to 1, and the innermost leading & is consumed, giving us &&coolbeans1
&coolbeans1 resolves to broseph, giving us &broseph
&broseph resolves to 5.

If there are trailing .s, only a single . is consumed in resolution, even if there are multiple &s.

Task

Given between 1 and 10 %let statements separated by newlines and a single %put statement, print or return the result of the %put statement. Input can be accepted in any standard way.

You can assume that the input will always be valid and that the %let statements will preceed the %put statement. Variables that are defined will not be redefined in later %let statements.

If actually run in SAS, there would be no issues with variables resolving to variables that don't exist and everything will be syntactically correct as described above.

Examples

Input:

%let dude=stuff;
%let stuff=bEaNs;
%put &&dude..;

Output:

bEaNs.

Input:

%let __6 = 6__;
%put __6&__6;

Output:

__66__

Input:

%let i=1;
%let hOt1Dog = BUNS;
%put &&HoT&i.Dog are FUNS&i!");

Output:

BUNS are FUNS1!")

Input:

%let x = {*':TT7d;
%put SAS is weird.;

Output:

SAS is weird.

Input:

%let var1   =  Hm?;
%let var11 = var1;
%let UNUSED = ;
%put &&var11.....;

Output:

Hm?....

Note that &&var11 matches var11 since name matching is greedy. If there had been a ., i.e. &&var1.1, then var1 would be matched and the extra 1 wouldn't be part of any name.

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

Python 3, 354 341 336 bytes

import re
S=re.sub
def f(x):
	r=x.splitlines();C=r[-1].strip('%put ');D=0
	while D!=C:
		D=C
		for a in sorted([l.strip('%let ').replace(" ","").split(';')[0].split('=')for l in r[:-1]],key=lambda y:-len(y[0])):
			s=1
			while s:C,s=re.subn('&'+a[0]+'(\.?)',a[1]+'\\1',S('+\.([^\.])','\\1',C),0,re.I)
	return S('+\.?','',C)

Try it online!

edit: some easy shortening

edit: reverse sort by -len(...) instead of [::-1] (5 bytes), thanks to Jonathan Frech!

Ungolfed

import re
S=re.sub # new name for the function re.sub()
def f(x):
    r=x.splitlines() # input string to list of rows
    C=r[-1].strip('%put ') # get the string to put (from the last row)
    D=0
    while(D!=C): # iterate until the result does not change
        D=C
        for a in                                                                                : # iterate over the list of variables
                 sorted(                                                                          ,key=lambda y:len(y[0]),reverse=1) # sort list for greediness by decreasing var.name lengths
                        [l.strip('%let ') # cut the 'let' keyword
                                         .replace(" ","") # erase spaces
                                                         .split(';')[0] # cut parts after ';'
                                                                       .split('=') # create [variable_name,value] list
                                                                                for l in r[:-1]] # for each row but last
            s=1
            while(s): # iterate until the result does not change
                C,s=re.subn( # substitute
                            '&'+a[0]+'(\.?)', # &varname. or &varname
                                                 a[1]+'\\1', # to value. or value
                                                              S('+\.([^\.])','\\1',C), # in the string we can get from C erasing ('s)(.) sequences if the next char is not .
                                                                                0,re.I) # substituting is case insensitive
    return S('+\.?','',C) # erase smileys and one .


Who's Who in the Name-Change Game? Very recently, I changed my SE username because I made this account some years ago and wanted to get back into asking questions. However, I’m still planning to post questions and potentially earn votes. We can imagine a site that has some issues dealing with name changes. The problem: given a list of names, reputation changes, and name changes, can you create a leaderboard of reputation? Assume everyone's reputation starts at 0.

Input comes in any reasonable format, and has two forms: a name change <String, String> and a rep change <String, Number>.

What does any reasonable format mean? When I write questions, it usually means the input can be rearranged or repackaged to work with the way your language takes in input (do you want a list of pairs? two lists? a string? that’s all fine) as long as it doesn’t add information or otherwise offload some of the computational work onto the human.

Name changes change a person’s username to any username not currently in use. For example, if A changes name to D, and B changes name to C, D (previously known as A) could still change their name to A or to B, even though these names have been used before. However, at any given moment the set of names are unique.

Rep changes represent something like getting up/down votes on a post, receiving a bounty, etc. All rep changes are guaranteed to be integers. They might come in the form <“Bob”, 5> or <“Alice”, -53000>. At the end, you must output all usernames that are currently in existence, and their rep counts, in descending order.

Test case:

Alice 5
Bob 7
Bob John
John 113
Alice Cheryl
Daniel 13
John Alice
Alice 12

Result:

Alice 132
Daniel 13
Cheryl 5

Test case, suggested by Unrelated String:

Jimmy Adam
Donald 12
Amelia -11

Result:

Donald 12
Adam 0
Amelia -11

Test case:

CodegoLfer65 12
Bluman 9
CodegoLfer65 n4me
n4me -3

Result:

Bluman 9
n4me 9 (note: these two can be in either order)

Usernames are composed of only [A-Za-z0-9], i.e. alphanumerics. However, the input will not be a number in your language. This means usernames like 144, 015, 0x0F, 1e7 will not appear in the input. Numbers such as 1/3, 2.8 do not appear due to the character specification in the first place.

This question seems heavy on data structures, so golfing languages may not perform as well. Maybe other languages will have a fighting chance? Scoring is by lowest number of bytes, i.e. tag:code-golf .

Python 3, 115 bytes

def f(l):
 r={}
 for n,m in l:q=m*0!=0;r[[n,m][q]]=r.pop(n,0)+[m,0][q]
 return sorted(r.items(),key=lambda i:-i[1])

Try it online!


Alphanumeric Hello World Your goal is to write "Hello, World!" (minus the quotes). This is a popularity-contest, so most up votes  wins. Code length will be used to break ties.
Anything goes, as long as it is within the following rules:

All characters must be either letters or numbers, so you may only use characters in the string "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".
All code you use must be in one file, with the exception of imported modules/classes/whatever they're called in your favourite language.
Only the standard libraries/frameworks for your language of choice are allowed (for example, Python's Math module is allowed, but Numpy, Scipy, and Pygame are not). I will allow TkInter as it is the de facto standard for GUIs in Python.
No input is permitted, be it reading from stdin, reading a file, displying an image, or reading from the web.

+10 brownie points if you figure out how to do it in Java without bending the rules.

On your marks, get set, code!

EDIT: braces ({}), brackets ([]), and parentheses (()) are allowed as this would be pretty much impossible for most languages without them. I'm also removing the character limit rule. Hopefully this will make it more interesting.

EDIT^2: white space is also allowed. My brain isn't working properly, sorry. >.<

Perl

Some say perl is a language full of ascii noise and random symbols like $... That is not true :P

s zzHelloq worldmz and s zqzchr 44ze and s zmzchr 33ze and print

  Let's break this up into subexpressions:
(s zzHelloq worldmz) and (s zqzchr 44ze) and (s zmzchr 33ze) and (print)

 It should be obvious that it executes from left to right as long as every expression returns true. But what on earth is s zqzchr 44ze?
In perl, there is a group of "quote-like operators" which includes  q(str), qw(li st), /regex/, s/from/to/ among other things. It turns out all of these operators can use almost any character as a delimeter, with a couple pecularities: opening parethesis has to be closed by a matching closing parenthesis, and if you wish to use a letter as a delimiter you have to put a space after the operator letter (to disambiguate it from a bareword).
In this case we see three uses of the s/// (regex substitution) operator:
s//Helloq worldm/
s/q/chr 44/e
s/m/chr 33/e
All delimited by the character z. The /e flag on the last two causes the substitution to be interpreted as code to be evaluated, rather literal text.
A fairly well-known fact about perl is that most operations default to operating on the $_ builtin variable unless otherwise specified. All these three substitutions and the print operate on $_ in this case, so first we put the words Hello world into the variable, then we fix the punctuation by using the numeric ascii values of the characters, then we print the contents of the variable.


Walk Across a Keyboard Given a word (or any sequence of letters) as input, you must interpolate between each letter such that each adjacent pair of letters in the result is also adjacent on a QWERTY keyboard, as if you typed the input by walking on a giant keyboard. For example, 'yes' might become 'ytres', 'cat' might become 'cxzawert'.

Rules:

This is the keyboard format you should use:

qwertyuiop
 asdfghjkl
  zxcvbnm

Any pair of keys which is touching in this layout is considered adjacent. For instance, 's' and 'e' are ajacent, but 's' and 'r' are not.
The input "word" will consist of any sequence of letters. It will have only letters, so you don't have do deal with special characters.
The input can be in any convenient form: stdin, a string, a list, etc. Letter case does not matter; you can take whatever is more convenient.
The output can be in any convenient form: stdout, a string, a list, etc. Letter case does not  matter, and it does not need to be consistent.
Any path across the keyboard is valid, except that you cannot cross the previous letter again before getting to the next letter. For example, 'hi' could become 'hji' or 'hjnbgyui', but not 'hbhui'.
A letter is not ajacent with itself, so 'poll' cannot become 'poll'. Instead it would need to become something like 'polkl'.
No output letters are allowed before or after the word. For example, 'was' cannot become 'trewas' or 'wasdfg'.

This is code golf, the shortest answer in bytes wins.

Python 2, 83 bytes

lambda s:re.findall('.*?'.join(s),'qwertyuioplkmnjhbvgfcxdsza'*len(s))[0]
import re

Try it online!

Walks the entire keyboard until the word is written.


Write a function that returns past tense of given verb Challenge

  Write a function which takes an argument which is a verb, and returns the past tense of the verb. (Assume that the verb is regular)

Past tense

Note: consider y as neither consonant nor vowel.

Normally, just adding ed after the end of verb makes the past tense of the verb.

Ex: jump → jumped, ask → asked

However, there are other rules.

If the last character of the given verb is e, just add d.

Ex: love → loved, move → moved
If the verb is ended with a consonant + y, then change y to i, and add ed.

Ex: study → studied, cry → cried
However, if the verb is ended with a vowel + y, then just add ed.

Ex: play → played, stay → stayed
If a verb is ended with a vowel and a consonant, then write the consonant one more time, and add ed.

Ex: stop → stopped, plan → planned
However, if a verb is ended with multiple vowels + a consonant or single vowel + multiple consonants, then just add ed.

Ex: look → looked, jump → jumped

There are more rules but let's care above rules only. For example, according to above rule, visit → visitted.

Winner

Since this is code golf, the shortest code that correctly returns past tenses wins.

Example (JS, 127)

function f(x){return x.replace(/([^aeiouy])y$/,'$1i').replace(/([^aeiouy][aeiou])([^aeiouy])$/,'$1$2$2').replace(/e$/,'')+'ed'}

sed, 76 characters

Does a sed script count as a function for this problem?

s/\([^aeiou]\)y$/\1i/
s/\([^aeiou][aeiou]\)\([^aeiouy]\)$/\1\2\2/
s/e\?$/ed/


Calculate the super root of a number In mathematics, tetration is the next hyper operator after exponentiation, and is defined as iterated exponentiation.

Addition (a succeeded n times)

Multiplication (a added to itself, n times)

Exponentiation (a multiplied by itself, n times)

Tetration (a exponentiated by itself, n times)

The inverse relations of tetration are called the super-root, and the super-logarithm.
Your task is to write a program that, given A and B, prints out the Bnd-order super-root of A.

For example:

if A = 65,536 and B = 4 it prints 2
if A = 7,625,597,484,987 and B = 3 it prints 3

A and B are positive integers and the result must be floating point number with a precision of 5 digits after the decimal point.
The result belongs to the real domain.

Be careful, super-roots may have many solutions.

C — aiming for clarity, didn't attempt to squeeze the code
Considering input:
A: A ∈ ℝ, A ≥ 1.0
B: B ∈ ℕ, B ≥ 1

Then there should usually be only one solution in ℝ, which simplifies the problem considerably.
Code is:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

#define TOLERANCE    1.0e-09

double tetrate(double, int);

int main(int argc, char **argv)
{
    double target, max, min, mid, working;
    int levels;

    if (argc == 3)
    {
        target = atof(argv[1]); // A
        levels = atoi(argv[2]); // B

        // Shortcut if B == 1
        if (levels == 1)
        {
            printf("%f\n", target);
            return 0;
        }

        // Get a first approximation
        max = 2.0;
        while (tetrate(max, levels) < target)
            max *= 2.0;

        min = max / 2.0;

        // printf("Answer is between %g and %g\n", min, max);

        // Use bisection to get a closer approximation
        do
        {
            mid = (min + max) / 2.0;
            working = tetrate(mid, levels);
            if (working > target)
                max = mid;
            else if (working < target)
                min = mid;
            else
                break;
        }
        while (max - min > TOLERANCE);

        // printf("%g: %f = %f tetrate %d\n", target, tetrate(mid, levels), mid, levels);
        printf("%f\n", mid);
    }

    return 0;
}

double tetrate(double d, int i)
{
    double result = d;

    // If the result is already infinite, don't tetrate any more
    while (--i && isfinite(result))
        result = pow(d, result);

    return result;
}

To compile:
gcc -o tet_root tet_root.c -lm

To run:
./tet_root A B

E.g.:
42
$ ./tet_root 65536 4
2.000000

33
$ ./tet_root 7625597484987 3
3.000000

3π
$ ./tet_root 1.340164183e18 3
3.141593

n(2½) ➙ 2 as n ➙ ∞ ? (well known limit)
$ ./tet_root 2 10
1.416190

$ ./tet_root 2 100
1.414214

$ ./tet_root 2 1000
1.414214

Yes!
n(e1/e) ➙ ∞ as n ➙ ∞ ? (upper bounds)
$ ./tet_root 9.999999999e199 100
1.445700

$ ./tet_root 9.999999999e199 1000
1.444678

$ ./tet_root 9.999999999e199 10000
1.444668

$ ./tet_root 9.999999999e199 100000
1.444668

Cool! (e1/e ≅ 1.44466786101...)


Tiling by substitution EDIT: The incorrect A rhomb substitution has been fixed. Apologies to anoyone who had started working on a solution.

Consider the following substitutions, where the substituted rhomb(us) is scaled up and shown in red:

EDIT: Note the anchor points (circle) created where a corner of each new rhomb touches the substituted rhomb. Also note the substitution's anchor point (black circle).

A rhomb (144°, 36°)

... becomes ...

B rhomb (72°, 108°)

 ... becomes ...

Each substitution is made up of some combination of A rhombs and B rhombs, on which the same substitutions can be performed.

A tiling can be created by repeating the substitutions n times.

After n=2 substitutions of A rhomb:

EDIT: The substitution is oriented by aligning the rhomb's anchor point with the substitution's anchor point

In the fewest bytes of code (given input n>=0) draw the tiling after n substitutions, where n=0 is A rhomb

Notes:

The red lines and anchor points shouldn't be included, they only illustrate the substitution.
In each substitution the tiling is scaled up so the rhombs have a constant size.
Any rotation is optional.
Graphical choices (colour, dimensions, cropping etc.) are optional if not exploited for loopholes.

Java, 881 bytes

import java.awt.image.BufferedImage;import static java.lang.Math.*;class J{BufferedImage o=new BufferedImage(999,999,1);java.awt.Graphics g=o.getGraphics();double v=2.5132,w=1.2566,p=PI,s=(p-v)/2,u=(p+w)/2;public static void main(String[]v){new J(Integer.parseInt(v[0]));}J(int i){d(609,391,v,p/4+s,500,i);try{javax.imageio.ImageIO.write(o,"png",new java.io.File("a.png"));}catch(Exception e){}}void d(int x,int y,double o,double q,double l,int r){int m=(int)(2*l*sin((p-o)/2)),a=(int)(x+cos(q)*l),b=(int)(y+sin(q)*l),c=(int)(x+cos(q+o/2)*m),d=(int)(y+sin(q+o/2)*m),e=(int)(x+cos(q+o)*l),f=(int)(y+sin(q+o)*l);if(r-->0){double n=l/(2*sin((v)/2));if(o>w){d(x,y,v,q-s,n,r);d(c,d,v,q+p+s,n,r);d(a,b,w,q+u,n,r);}else{d(x,y,w,q-s,n,r);d(c,d,w,q+p+s,n,r);d(e,f,w,q-p/2,n,r);d(a,b,v,q+p/2-s-s,n,r);}}else{g.drawLine(x,y,a,b);g.drawLine(a,b,c,d);g.drawLine(x,y,e,f);g.drawLine(c,d,e,f);}}}

Ungolfed

import java.awt.image.BufferedImage;

import static java.lang.Math.*;

class Q79373 {
    BufferedImage image = new BufferedImage(999, 999, 1);
    java.awt.Graphics graphics = image.getGraphics();
    double aRad = 2.5132, bRad = 1.2566, pi = PI, aAcuteHalf = (pi - aRad) / 2, bRadHalfPi = (pi + bRad) / 2;

    public static void main(String[] v) {
        new Q79373(Integer.parseInt(v[0]));
    }

    Q79373(int i) {
        draw(609, 391, aRad, pi / 4 + aAcuteHalf, 500, i);
        try {
            javax.imageio.ImageIO.write(image, "png", new java.io.File("a.png"));
        } catch (Exception e) {
        }
    }

    void draw(int x, int y, double rad, double rot, double length, int recDepth) {
        int
                height = (int) (2 * length * sin((pi - rad) / 2)),
                a = (int) (x + cos(rot) * length),
                b = (int) (y + sin(rot) * length),
                c = (int) (x + cos(rot + rad / 2) * height),
                d = (int) (y + sin(rot + rad / 2) * height),
                e = (int) (x + cos(rot + rad) * length),
                f = (int) (y + sin(rot + rad) * length);

        if (recDepth-- > 0) {
            double lengthNew = length / (2 * sin((aRad) / 2));
            if (rad > bRad) {
                draw(x, y, aRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, aRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(a, b, bRad, rot + bRadHalfPi, lengthNew, recDepth);
            } else {
                draw(x, y, bRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, bRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(e, f, bRad, rot - pi / 2, lengthNew, recDepth);
                draw(a, b, aRad, rot + pi / 2 - aAcuteHalf - aAcuteHalf, lengthNew, recDepth);
            }
        } else {
            graphics.drawLine(x, y, a, b);
            graphics.drawLine(a, b, c, d);
            graphics.drawLine(x, y, e, f);
            graphics.drawLine(c, d, e, f);
        }
    }
}

Notes

The results arent 100% acurate thanks to integer precision. I used integers for the coordinates because Graphics::drawLine only takes integers as arguments, and I would've ended up with way more integer casts than I have now.
I'll probably golf a bit more later, still not optimal.

Results

Full image filled

Recursion 1

Recursion 2

Recursion 3


Make a (somewhat) self-referential string You want to make a string where the (1-indexed) character at index n is n. When n is less than 10, this is easy: "123456789". When n is 12, for example, it becomes impossible, since numbers greater than 9 (in base 10) take up more than one character. We can compromise by dividing the string into two-character substrings: "020406081012". Now the index of the end of each substring n is n.

This can be generalized for any d-digit number. Here's an explanation for the "0991021" part of the string for a three-digit number:

Index:     ... * 97  98  99*100 101 102*103 ...
               *           *           *
               *---+---+---*---+---+---*---+
Character: ... * 0 | 9 | 9 * 1 | 0 | 2 * 1 | ...
               *---+---+---*---+---+---*---+

If you haven't figured it out yet, you are to write a program/function that takes a string or integer and output its self-referential string as specified above. You can also output an array of single-digit numbers, chars, or single-character strings.

The given integer will always be positive and divisible by its length (e.g. 126 is divisible by 3; 4928 is divisible by 4). Your program should theoretically work for an arbitrarily large input, but you can assume it is smaller than your language's maximum integer and/or string length.

Some observations if you still don't get it: The length of the output will always be the input itself, and the numbers that appear in the output will be divisible by the number of digits in the input.

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

Test cases

1    => 1
9    => 123456789
10   => 0204060810
105  => 003006009012015018021024027030033036039042045048051054057060063066069072075078081084087090093096099102105
1004 => 00040008001200160020002400280032003600400044004800520056006000640068007200760080008400880092009601000104010801120116012001240128013201360140014401480152015601600164016801720176018001840188019201960200020402080212021602200224022802320236024002440248025202560260026402680272027602800284028802920296030003040308031203160320032403280332033603400344034803520356036003640368037203760380038403880392039604000404040804120416042004240428043204360440044404480452045604600464046804720476048004840488049204960500050405080512051605200524052805320536054005440548055205560560056405680572057605800584058805920596060006040608061206160620062406280632063606400644064806520656066006640668067206760680068406880692069607000704070807120716072007240728073207360740074407480752075607600764076807720776078007840788079207960800080408080812081608200824082808320836084008440848085208560860086408680872087608800884088808920896090009040908091209160920092409280932093609400944094809520956096009640968097209760980098409880992099610001004

C, 64 bytes

l,i;main(n){for(scanf("%d%n",&n,&l);i<n;)printf("%0*d",l,i+=l);}

Takes a single integer as input on stdin.


Find a function with cycles of every length A function is said to have a cycle of length n if there exists an x in its domain such that fn(x) = x and fm(x) ≠ x for 0 < m < n, where the superscript n denotes n-fold application of f. Note that a cycle of length 1 is a fixed point f(x) = x.

Your task is to implement a bijective function from the integers to themselves, which has exactly one cycle of every positive length n. A bijective function is a one-to-one correspondence, i.e. every integer mapped to exactly once. Having exactly one cycle of length n means that there are exactly n distinct numbers x for which fn(x) = x and fm(x) ≠ x for 0 < m < n.

Here is an example of what such a function might look like around x = 0:

x     ... -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7 ...
f(x)  ...  2  4  6 -3 -1  1 -4  0 -2  5  7 -7 -6  3 -5 ...

This excerpt contains cycles of length 1 to 5:

n   cycle
1    0
2   -2  1
3   -4 -3 -1
4   -5  6  3  7
5   -7  2  5 -6  4
...

Note that above I'm using "function" only in the mathematical sense. You may write either a function or a full program in your language of choice, as long as it takes a single (signed) integer as input and returns a single (signed) integer. As usual you may take input via STDIN, command-line argument, function argument etc. and output via STDOUT, function return value or function (out) argument etc.

Of course, many languages don't (easily) support arbitrary-precision integers. It's fine if your implementation only works on the range of your language's native integer type, as long as that covers at least the range [-127, 127] and that it would work for arbitrary integers if the language's integer type was replaced with arbitrary-precision integers.

Standard code-golf rules apply.

MATL, 47 bytes
E|G0<-QXJ:tQ*2/0hStJ<f0))Q2MQ)&:J6M-)2/ttk>Eq*k

Try it online!
General explanation
Function 2 below is the same as used in @Sp3000's answer to the related challenge. Thanks to @Agawa001 for noticing.
The function is the composition of three:

Bijection from Z (the integers) to N (the naturals).
Bijection from N to N with the desired characteristic (one cycle of each length).
Inverse of function 1.

Functions 1 and 3 are used because it's easier (I think) to achieve the desired behaviour in N than in Z.
Function 2 is as follows: upper line is domain, lower line is codomain. Commas are used for clarity:
1,  2  3,  4  5  6,  7  8  9  10  ...
1,  3  2,  6  4  5, 10  7  8   9  ...

The first block (from upper 1 to lower 1) is a cycle of length 1. The second (from 2 3 to 3 2) is a cycle of length 2, etc. In each block, the lower part (image of the function) is the upper part circularly shifted one step to the right.
Function 1 is as follows:
 -5  -4  -3  -2  -1   0  +1  +2  +3  +4  ...
+10  +8  +6  +4  +2  +1  +3  +5  +7  +9  ...

Function 3 is the same as 1 with the two lines swapped.
Examples
The image of 3 is -5. First 3 is mapped to 7 by function 1; then 7 is mapped to 10 by function 2; then 10 is mapped to -5` by function 3.
The length-1 cycle is 0. The length-2 cycle is -1 1. The length-3 cycle is -3 2 -2, etc.
Code explained
Functions 1 and 3 are straightforward.
Function 2 works by finding the lower endpoint of the corresponding input block. For example, if the input to this function is 9 it finds 7 (see blocks above). It then picks the upper endpoint, which is 10 in the example. The circular shift of the block is achieved thanks to MATL's 1-based, modular indexing.
         % FUNCTION 1
         % Implicit input
E|       % Multiply by two. Absolute value
G0<      % 1 if input is negative, 0 otherwise
-        % Subtract
Q        % Add 1
XJ       % Copy to clipboard J. Used as input to the next function

         % FUNCTION 2
:        % Range [1 2 ... J], where J denotes the input to this function
tQ*      % Duplicate, increment by 1, multiply
2/       % Divide by 2
0hS      % Prepend a 0. This is needed in case J is 0
tJ<f     % Duplicate. Find indices that are less than the input J
0)       % Pick the last index.
)        % Apply as index to obtain input value that ends previous block
Q        % Add 1: start of current block
2M       % Push the two arguments to second-to-last function call
Q)       % Add 1 and use as index: end of current block
&:       % Inclusive binary range: generate input block
J        % Push J (input to function 2)
6M-      % Subtract start of block
)        % Apply as index (1-based, modular). This realizes the shifting

         % FUNCTION 3
2/       % Divide by 2
ttk>     % Duplicate. 1 if decimal part is not 0; 0 otherwise
Eq       % Multiply by 2, add 1
*        % Multiply
k        % Round down
         % Implicit display


Output "Fit" numbers "Fit Numbers"

Sam has a "brilliant" idea for compression! Can you help?

Here is a rundown of Sam's compression scheme. First take in a base 10 representation of any natural number strictly smaller than 2^16, and write it as a binary string without any leading zeros.

1 -> 1
9 -> 1001
15 ->1111
13 ->1101
16 -> 10000
17 -> 10001
65535 -> 111111111111111

Now replace any group of one or more zeros with a single zero. This is because the number has gotten leaner. Your binary string now will look like this.

1 -> 1 -> 1
9 -> 1001 -> 101
15 ->1111 -> 1111
13 ->1101 -> 1101
16 -> 10000 -> 10
17 -> 10001 -> 101
65535 -> 111111111111111 -> 111111111111111

Now you convert the binary string back to a base 10 representation, and output it in any acceptable format. Here are your test cases. The first integer represents an input, and the last integer represents an output. Note that some numbers do not change, and thus can be called "fit"

1 -> 1 -> 1 -> 1
9 -> 1001 -> 101 -> 5
15 ->1111 -> 1111 -> 15
13 ->1101 -> 1101 -> 13
16 -> 10000 -> 10 -> 2
17 -> 10001 -> 101 -> 5
65535 -> 1111111111111111 -> 1111111111111111 -> 65535
65000 -> 1111110111101000 -> 11111101111010 -> 16250

You may use any language, but please note that Sam hates standard loopholes. This is code golf so the code can be as short as possible to make room for the "compressed" numbers".

Note:This is NOT an acceptable compression scheme. Using this will promptly get you fired.

Citation-Needed: I do not take credit for this concept. This comes from @Conor O' Brien's blog here see this OEIS of fit numbers. https://oeis.org/A090078

Bash + GNU utilities, 27
dc -e2o?p|tr -s 0|dc -e2i?p

Input read from STDIN.


C: replace AES FIPS-197 SubBytes table by constant-time code In FIPS-197 (the Advanced Encryption Standard, known as AES), it is made heavy use of SubBytes, which could be implemented as

unsigned char SubBytes(unsigned char x) {
static const unsigned char t[256] = {
  0x63,0x7C,0x77,0x7B,0xF2,0x6B,0x6F,0xC5,0x30,0x01,0x67,0x2B,0xFE,0xD7,0xAB,0x76,
  0xCA,0x82,0xC9,0x7D,0xFA,0x59,0x47,0xF0,0xAD,0xD4,0xA2,0xAF,0x9C,0xA4,0x72,0xC0,
  0xB7,0xFD,0x93,0x26,0x36,0x3F,0xF7,0xCC,0x34,0xA5,0xE5,0xF1,0x71,0xD8,0x31,0x15,
  0x04,0xC7,0x23,0xC3,0x18,0x96,0x05,0x9A,0x07,0x12,0x80,0xE2,0xEB,0x27,0xB2,0x75,
  0x09,0x83,0x2C,0x1A,0x1B,0x6E,0x5A,0xA0,0x52,0x3B,0xD6,0xB3,0x29,0xE3,0x2F,0x84,
  0x53,0xD1,0x00,0xED,0x20,0xFC,0xB1,0x5B,0x6A,0xCB,0xBE,0x39,0x4A,0x4C,0x58,0xCF,
  0xD0,0xEF,0xAA,0xFB,0x43,0x4D,0x33,0x85,0x45,0xF9,0x02,0x7F,0x50,0x3C,0x9F,0xA8,
  0x51,0xA3,0x40,0x8F,0x92,0x9D,0x38,0xF5,0xBC,0xB6,0xDA,0x21,0x10,0xFF,0xF3,0xD2,
  0xCD,0x0C,0x13,0xEC,0x5F,0x97,0x44,0x17,0xC4,0xA7,0x7E,0x3D,0x64,0x5D,0x19,0x73,
  0x60,0x81,0x4F,0xDC,0x22,0x2A,0x90,0x88,0x46,0xEE,0xB8,0x14,0xDE,0x5E,0x0B,0xDB,
  0xE0,0x32,0x3A,0x0A,0x49,0x06,0x24,0x5C,0xC2,0xD3,0xAC,0x62,0x91,0x95,0xE4,0x79,
  0xE7,0xC8,0x37,0x6D,0x8D,0xD5,0x4E,0xA9,0x6C,0x56,0xF4,0xEA,0x65,0x7A,0xAE,0x08,
  0xBA,0x78,0x25,0x2E,0x1C,0xA6,0xB4,0xC6,0xE8,0xDD,0x74,0x1F,0x4B,0xBD,0x8B,0x8A,
  0x70,0x3E,0xB5,0x66,0x48,0x03,0xF6,0x0E,0x61,0x35,0x57,0xB9,0x86,0xC1,0x1D,0x9E,
  0xE1,0xF8,0x98,0x11,0x69,0xD9,0x8E,0x94,0x9B,0x1E,0x87,0xE9,0xCE,0x55,0x28,0xDF,
  0x8C,0xA1,0x89,0x0D,0xBF,0xE6,0x42,0x68,0x41,0x99,0x2D,0x0F,0xB0,0x54,0xBB,0x16};
return t[x];}

This function is not arbitrary; it is a reversible mapping, consisting of an inversion in a Galois Field followed by an affine transformation. All the details are in FIPS-197 section 5.1.1 or here section 4.2.1 (under a slightly different name).

One problem with implementation as a table is that it opens to so-called cache-timing attacks.

Thus your mission is to devise an exact replacement for the above SubBytes() function, that exhibits constant-time behavior; we'll assume that's the case when nothing depending on the input x of SubBytes is used  either:

as an array index,
as the control operand of if, while, for, case, or operator ?:;
as any operand of operators &&, ||, !, ==, !=, <, >, <=, >=, *, /, %;
as the right operand of operators >>, <<, *=, /=, %=, <<=, >>=.

The winning entry will be one with the lowest cost, obtained from the number of operators executed in the input-dependent data path, with a weight of 5 for unary operators - and ~ as well as for <<1, >>1, +1, -1; weight of 7 for all other operators, shifts with other counts, or adds/subs of other constants (type casts and promotions are free). By principle, that cost is unchanged by unrolling loops (if any), and independent of the input x. As a tie-breaker, the answer with the shortest code after removing whitespace and comments wins.

I plan to designate an entry as answer as early as I can in year 2013, UTC. I will consider answers in languages that I've some knowledge of, ranking them as a straight translation to C not optimized for size.

Apologies for the initial omission of +1 and -1 in the favored operators, of free casts and promotions, and ranking of size. Note that * is prohibited both when unary, and as multiplication.


What is a good way to deal with tasks that require arrays using Haskell? Often a task requires real arrays. Take for instance the task to implement Befunge or ><>. I tried to use the Array module for this, but it's really cumbersome, as it feels like I'm coding much too verbose. Can anybody help me how to solve such code-golf tasks less verbose and more functional?

The glib answer is: Don't use arrays. The not-so-glib answer is: Try to rethink your problem so that it doesn't need arrays.

Often, a problem with some thought can be done without any array like structure at all. For example, here's my answer to Euler 28:

-- | What is the sum of both diagonals in a 1001 by 1001 spiral?
euler28 = spiralDiagonalSum 1001

spiralDiagonalSum n
    | n < 0 || even n = error "spiralDiagonalSum needs a positive, odd number"
    | otherwise = sum $ scanl (+) 1 $ concatMap (replicate 4) [2,4..n]

What gets expressed in the code here is the pattern of the sequence of numbers as they grow around the rectangular spiral. There was no need to actually represent the matrix of numbers itself.

The key to thinking beyond arrays is to think about what the problem at hand actually means, not how you might represent it as bytes in RAM. This just comes with practice (perhaps a reason I code-golf so much!)

Another example is how I solved the finding maximal paths code-golf. There, the method of passing the partial solutions as a wave through the matrix, row by row, is expressed directly by the fold operation. Remember: On most CPUs, you can't deal with the array as a whole at once: The program is going to have to operate through it over time. It may not need the whole array at once at any time.

Of course, some problems are stated in such a way that they are inherently array based. Languages like ><>, Befunge, or Brainfuck have arrays at their heart. However, even there, arrays can often be dispensed with. For example, see my solution to interpreting Brainfuck, the real core of its semantics is a zipper. To start thinking this way, focus on the patterns of access, and the structure closer to the meaning of problem. Often this needn't be forced into a mutable array.

When all else fails, and you do need to use an array - @Joey's tips are a good start.


Convert this character based table into html one Take a following character table:

-------------------------------------------------------
|       |1233456 | abc    | xyz    |        |         |
|-------|--------|--------|--------|--------|---------|
|       |abcdefgh| 1234567|        | 12345  |         |
|   abc |xyzabcqw|        |        |        |         |
|       |zzzz    |        |        |        |         |
|-------|--------|--------|--------|--------|---------|

It can have a variable number of columns or rows. Column width and row height can vary. Cells can be empty or have text, but the row height is optimized to wrap the text. So, second row has three lines because second cell content in second row is three lines high.

Input is ASCII text as shown in example. Cells can not contain | or - characters. Cell content should be escaped, but no need to worry about rowspan and colspan, since the table structure is always simple (every row same number of columns and every column same number of rows).

Output should be well-formed xhtml. Html table should reflect the table structure, content and line breaks. So, resulting html based on the sample input above is the following:

    1233456
    abc
    xyz

    abc
    abcdefgh
xyzabcqw
zzzz
    1234567

    12345

Shortest code which takes this table and turns it into an xhtml table wins.

Ruby: 233 characters
BEGIN{puts"
";f=[]};if/^[-|]+$/ then if f!=[] then puts"
\n#{f[1..-2].map{|i|"    #{i.join"
"}	"}*$/}\n
\n";f=[]end else$F.each_index{|i|f[i]||=[];f[i]<<CGI.escapeHTML($F[i])if$F[i]>""}end;END{puts"
"}

Sample run:
bash-4.2$ ruby -naF' *\| *' -r cgi -e 'BEGIN{puts"
";f=[]};if/^[-|]+$/ then if f!=[] then puts"
\n#{f[1..-2].map{|i|"    #{i.join"
"}	"}*$/}\n
\n";f=[]end else$F.each_index{|i|f[i]||=[];f[i]<<CGI.escapeHTML($F[i])if$F[i]>""}end;END{puts"
"}' table.txt

    1233456
    abc
    xyz

    abc
    abcdefgh
xyzabcqw
zzzz
    1234567

    12345

(Out of contest CW, due to the shameless amount of used command line options.)


Tips for golfing in Swift What are some tips for code-golfing in Swift? Its focus on safety seems to make it difficult to golf in, but that makes little tips and even more useful. Are there any features in Swift that may help it excel in code-golf in certain applications?

Please post one tip per answer.

Ranges

One thing that is really helpful is creating ranges using the ... or ..< operators

For example

array[0..<n] //first n elements of array
array[k..<n] //kth through nth elements of array
array[k...n] //kth through n-1 elements of array

So, to get the 2nd through 4th values of an array

let myArray = ["ab", "cd", "ef", "gh", "ij", "kl", "mn", "op"]
print(myArray[1..<4]) //["cd", "ef", "gh"]

Practical Use

let a = [3, 1, 4, 1, 5, 9]

Using

for v in a[0...3]{print(v)}

Is 8 bytes shorter than

for n in 0...3{let v=a[n];print(v)}


The Major-Minor Dichotomy Given a list of chords label them as either 'Major' or ' Minor'.

Input

Input will be a list of chords, one per line, made up of 3 notes separated by a space. Each note will consist of the note name in uppercase (A-G) and an optional accidental (# or b). Chords may be in any inversion (i.e. the notes may be in any order).

Output

If the chord is major, output 'Major'. If the chord is minor, output 'Minor'. If the chord is neither major nor minor, output a blank line.

Example

Input

C E G
F Ab C
C Eb Gb
E G B
Db F Ab
Bb G D
D A Gb

Output

Major
Minor

Minor
Major
Minor
Major

Test scripts

As in some of my past questions, I've once again butchered some test scripts originally created by Joey and Ventero to provide some test cases for this question:

bash
Powershell

Usage: ./test [your program and its arguments]

Rewards

Each entry which I can verify that meets the spec, passes the tests and has obviously had some attempt at golfing will receive an upvote from me (so please provide usage instructions with your answer). The shortest solution by the end of 13/10/2012 will be accepted as the winner.

A little theory

For those of you with no musical theory knowledge here's enough information for you to be able to compete.

A major or minor chord is made up of three notes which are separated by a specific pattern of semitones. If we consider the root (bottom note) of the chord to be 0, then a major chord is the pattern 0-4-7 and a minor chord is the pattern 0-3-7. Things are made more awkward by the fact that some notes are a semitone apart and some are a tone apart. The spread of semitones from Ab-G# is as follows:

G#/Ab A A#/Bb B/Cb B#/C C#/Db D D#/Eb E/Fb E#/F F#/Gb G G#/Ab
  0   1   2    3     4    5   6   7    8     9    10  11  12

G#/Ab means that that G# is the same note as Ab. From this we can see that the chord Ab C Eb is a major chord, and that Ab Cb Eb is minor.

To complicate matters further, the chord Eb Cb Ab is considered to be the same as Ab Cb Eb, Cb Eb Ab and Cb Ab Eb and so on. Every one of these variations is still a minor chord.

Python, 160

f='A#BC D EF G3453543'.find
try:
 while 1:x,y,z=sorted(map(lambda x:f(x[0])+f(x[1:])+1,raw_input().split()));print'MMianjoorrr'[f(`y-x`+`z-y`)/14:-1:2]
except:0


Produce a m*n table in HTML Input :
Two decimal integers m and n that respectively give the number of rows and columns of the table.
m and n are greater than or equal to 1.
Output :
A table in HTML that has m rows and n columns.
The table should be displayable by a modern browser of your choice. Most browsers will display everything properly even if tags are not closed. Proper indentation and spacing is optional.
There should be at least one (non-whitespace) printable character in each cell.
Cells on the first line should use  tags while the ones on the following lines should use tags.
Win condition :
This is code-golf so the shortest source-code for each language wins.
Input example :
2 3

Output example :

   A
   A
   A

   A
   A
   A

or :

AAA
AAA

APL (Dyalog Unicode) with MiServer 3.0, 31 30 bytesSBCS

Full program. Prompts stdin for the two-element list [m,n] and prints strict XHTML to stdout.

(⎕NEW _.Table((⎕⍴0)⍬1)).Render

Example session:

      )xload C:\Users\Adam.DYALOG\Documents\MiServer\miserver.dws
C:\Users\Adam.DYALOG\Documents\MiServer\miserver.dws saved Wed Mar  7 17:19:40 2018
      Load ''
Development environment loaded
MiSite "C:/Users/Adam.DYALOG/Documents/MiServer/MS3/" loaded
      (⎕NEW _.Table((⎕⍴0)⍬1)).Render
⎕:
      2 3

0	0	0

0	0	0

Try it online!

Explanation:

(…).Render Render the following HTML element:

 ⎕NEW _.Table (…) a new Table with the following parameters:

  (…) ⍬ 1 the following content, no special styling, 1 header row:

   ⎕⍴0 evaluated input reshapes zero (i.e. an m-row, n-column matrix of zeros)


Summing a sub-square of a quarter of an infinite chessboard Description of the problem

Imagine a quarter of an infinite chessboard, as in a square grid, extending up and right, so that you can see the lower left corner. Place a 0 in there. Now for every other cell in position (x,y), you place the smallest non-negative integer that hasn't showed up in the column x or the row y.

It can be shown that the number in position (x, y) is x ^ y, if the rows and columns are 0-indexed and ^ represents bitwise xor.

Task

Given a position (x, y), return the sum of all elements below that position and to the left of that position, inside the square with vertices (0, 0) and (x, y).

The input

Two non-negative integers in any sensible format. Due to the symmetry of the puzzle, you can assume the input is ordered if it helps you in any way.

Output

The sum of all the elements in the square delimited by (0, 0) and (x, y).

Test cases

5, 46 -> 6501
0, 12 -> 78
25, 46 -> 30671
6, 11 -> 510
4, 23 -> 1380
17, 39 -> 14808
5, 27 -> 2300
32, 39 -> 29580
14, 49 -> 18571
0, 15 -> 120
11, 17 -> 1956
30, 49 -> 41755
8, 9 -> 501
7, 43 -> 7632
13, 33 -> 8022

Perl 6, 19 bytes

{sum [X+^] 0 X..@_}

Try it online!

The sum of the bitwise xor between all numbers in the range 0 to all inputs.


Does the nth char equal the nth from last char? Inspired by Does the start equal the end
Given a string s and an integer n, output a truthy/falsey as to whether the nth char in s equals the nth from the end char in s.
Input
A non-empty string and an integer. You can use 0-based indexing or 1-based indexing. The integer is guaranteed to be valid based on the string. For example, if the string is "supercalifragalistic123", the integer can be from 1 to 23 for 1-based indexing, and 0 to 22 for 0-based indexing. Please note that n can be larger than half the length of s.
Input is limited to printable ASCII.
Output
A truthy/falsey value based on whether the nth value in s equals the nth from last value in s.
Please note that the last char is in position 0 for 0-based indexing and position 1 for 1-based indexing. Think of it as comparing the string to its reverse.
Test Cases
0-indexed
"1", 0         Truthy 1 == 1
"abc", 1       Truthy b == b
"aaaaaaa", 3   Truthy a == a
"[][]", 1      Falsey ] != [
"[][]", 0      Falsey [ != ]
"ppqqpq", 2    Truthy q == q
"ababab", 5    Falsey a != b
"12345", 0     Falsey 1 != 5
"letter", 1    Truthy e == e
"zxywv", 3     Falsey w != x

1-indexed
"1", 1         Truthy 1 == 1
"abc", 2       Truthy b == b
"aaaaaaa", 4   Truthy a == a
"[][]", 2      Falsey ] != [
"[][]", 1      Falsey [ != ]
"ppqqpq", 3    Truthy q == q
"ababab", 6    Falsey a != b
"12345", 1     Falsey 1 != 5
"letter", 2    Truthy e == e
"zxywv", 4     Falsey w != x

JavaScript (ES6), 26 bytes

s=>n=>s[n]==s.substr(~n,1)

Alternatively:

s=>n=>s[n]==s.slice(~n)[0]

This one almost works, but fails when n == 0 (because s.slice(-1,0) == ""):

s=>n=>s[n]==s.slice(~n,-n)

Another 26-byte solution that @RickHitchcock pointed out:

s=>n=>s[n]==s[s.length+~n]


How many syllables in that number? I'd love to take a number and know how many syllables are in it, when spoken in English.
Let's limit this to positive integers which are less than one thousand.
I'm British, so we're going to follow the hundreds column with an 'and' when there are any non-zero digits after it.
The Challenge

Write some code which will accept a positive integer lower than 1000 and output the number of syllables in the words which represent that number in British English.
It DOES NOT need to generate the words to represent the numbers, only the number of syllables they contain.
It's code golf, attempt to achieve this in the fewest bytes.
Use any language you like.
The standard loopholes are forbidden.

Test Cases
|  N  | In words                             | Syllables |
|   1 | one                                  |         1 |
|   2 | two                                  |         1 |
|   3 | three                                |         1 |
|   4 | four                                 |         1 |
|   5 | five                                 |         1 |
|   6 | six                                  |         1 |
|   7 | sev-en                               |         2 |
|   8 | eight                                |         1 |
|   9 | nine                                 |         1 |
|  10 | ten                                  |         1 |
|  11 | el-ev-en                             |         3 |
|  12 | twelve                               |         1 |
|  13 | thir-teen                            |         2 |
|  14 | four-teen                            |         2 |
|  17 | se-ven-teen                          |         3 |
|  20 | twen-ty                              |         2 |
|  21 | twen-ty one                          |         3 |
|  42 | four-ty two                          |         3 |
|  73 | sev-en-ty three                      |         4 |
|  77 | sev-en-ty sev-en                     |         5 |
| 100 | one hund-red                         |         3 |
| 110 | one hund-red and ten                 |         5 |
| 111 | one hund-red and el-ev-en            |         7 |
| 555 | five hund-red and fif-ty five        |         7 |
| 700 | sev-en hund-red                      |         4 |
| 770 | sev-en hund-red and sev-en-ty        |         8 |
| 777 | sev-en hund-red and sev-en-ty sev-en |        10 |
| 999 | nine hund-red and nine-ty nine       |         7 |

Python 2, 84 83 74 67 bytes

lambda n:4*(n>99)+2-n%~9/9-0x55561aaaab/4**(n%100)%4+`n`.count('7')

Thanks to @xnor for golfing off 9 16 bytes!

Try it online!

Python 2, 79 bytes

lambda n:4*(n>99)+([-1]+10*[1]+[3,1]+7*[2]+8*([2]+9*[3]))[n%100]+`n`.count('7')

Straightforward, but longer.

Try it online!


CJam, 121 bytes

5,{_5\-S*\)_'/*"**"@'\*N}%:A['+"+
"]"=*"6**:Lri:M{M(:M;2,{M+2%:J;3,{:I'|J@2\-'.*I'.*?_J"/\\""\/"?JI)3I-?*\++_+'|N}%}%L}*A

Try it online

Takes the input n via STDIN.

I'll add an explanation at some point later. Basically it's all just a bunch of loops in a very naive way. To alternate between the two different body parts, I've got a nested loop over the part and a loop over 0 and 1. Then I just add the outer iterator and the inner one, and use their parity to decide between upwards or downwards pointing triangle.


Implement an integer parser Implement an integer parser in the shortest code possible, with the following restrictions:

The function or program can only take one argument: a string (or equivalent). Assume it to be signed and always valid (don't worry about decimals, etc.). The input may optionally omit the sign, in which it is assumed to be positive.
The function or program must output an integer (or equivalent).
No pattern matching, regular expressions, etc. are allowed. This includes utilities such as tr for *nix.
No string parsing utilities are permitted, even from the standard library. This includes, but is not limited to,  parseInt() from JavaScript, int() in Python, and Int32.parse() from VBScript.
The only permitted predefined string manipulation functions, methods, etc. fall into one of the following categories:

extract a substring (e.g. substr(), slice())
get code point from character, vice versa (e.g. toCodePoint(),  fromCodePoint())
concatenate strings (e.g. append(),  concat(), strcpy())

No external libraries are permitted.
No string parsing utilities are permitted, even from the standard library.
Implicit conversion to string is disallowed (e.g. 1+'' in JavaScript)

Shortest code wins, so happy golfing!

EDIT: Sorry for the confusion, but implicit conversion is also disallowed.

Python 3 (68)

s=input()
n=s<'0'
t=0
for c in s[n:]:t=t*10+ord(c)-48
print(t-t*2*n)

The Boolean n remembers whether the string started with a minus sign by using the lexicographic string ordering, in which '-' is less then the lowest digit '0'. The expression s[n:] casts n to a number (0 or 1), skipping the minus sign if it was there. The expression t-t*2*n is a shortening of [t,-t][n].


Print a Symbolic Negative of your Code (This is a variation on Print a Negative of your Code, which I enjoyed a lot! Thanks to Martin Büttner♦ - almost all of this text is his.)

Let's consider the symbols to be the following printable ASCII characters (note that space is included):

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

And the alphanumerics to be these:

0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

Consider a square of printable ASCII characters for side length N, like the following:

ONE,
{two}
&3,+=
!four
f|ve.

We also require each row and each column to contain at least one symbol and one alphanumeric. (The above example satisfies this.)

We define the symbolic negative of such a square to be a square of the same size where each symbol is replaced with an alphanumeric and vice versa. For example, the following would be a valid symbolic negative of the above example:

[&]OK
a...b
1/100
i@#$%
(R) z

The choice of specific characters is irrelevant as long as they are in the categories above.

The Challenge

Your task is to write a program with square source code with side length N > 1, which prints a symbolic negative of its source code to STDOUT. Trailing spaces must be printed. You may or may not print a single trailing newline.

The usual quine rules also apply, so you must not read your own source code, directly or indirectly. Likewise, you must not assume a REPL environment which automatically prints the value of each entered expression.

The winner is the program with the lowest side length N. In the event of a tie, the submission with the fewest symbols in the source code wins. If there's still a tie, the earliest answer wins.

CJam, 3 × 3 (5 symbols)

[5,
S*3
/N*

Try it online in the CJam interpreter.

How it works

[   e# Unmatched [. Does nothing.
 5, e# Push [0 1 2 3 4].
S*  e# Join the integers, separating by spaces. Pushes "0 1 2 3 4".
  3 e#
/   e# Split into chunks of length 3. Pushes ["0 1" " 2 " "3 4"].
 N* e# Join the chunks, separated by linefeeds. Pushes the output.

Output

0 1
 2
3 4


Find numbers within the Copeland–Erdős constant Background
The Copeland–Erdős constant is the concatenation of "0." with the base 10 representations of the prime numbers in order. Its value is
0.23571113171923293137414...

See also OEIS A033308.
Copeland and Erdős proved that this is a normal number. This implies that every natural number can be found at some point in the decimal expansion of the Copeland-Erdős  constant.
The challenge
Given a positive integer, express it in base 10 (without leading zeros) and output the index of its first appearance within the sequence of decimal digits of the Copeland–Erdős constant.
Any reasonable input and output format is allowed, but input and output should be in base 10. In particular, the input can be read as a string; and in that case it can be assumed not to contain leading zeros.
Output may be 0-based or 1-based, starting from the first decimal of the constant.
The actual results may be limited by data type, memory or computing power, and thus the program may fail for some test cases. But:

It should work in theory (i.e. not taking those limitations into account) for any input.
It should work in practice for at least the first four cases, and for each of them the result should be produced in less than a minute.

Test cases
Output is here given as 1-based.
13       -->         7   # Any prime is of course easy to find
997      -->        44   # ... and seems to always appear at a position less than itself
999      -->      1013   # Of course some numbers do appear later than themselves
314      -->       219   # Approximations to pi are also present
31416    -->     67858   # ... although one may have to go deep to find them
33308    -->     16304   # Number of the referred OEIS sequence: check
36398    -->     39386   # My PPCG ID. Hey, the result is a permutation of the input!
1234567  -->  11047265   # This one may take a while to find

Python 2, 64 bytes

f=lambda n,k=2,m=1,s='':-~s.find(`n`)or f(n,k+1,m*k*k,s+m%k*`k`)

Returns the 1-based index. Test it on Ideone.


Sum of Binary Substrings This challenge is simple, given a decimal number, convert to binary, and calculate the sum of the sub-strings of the binary number, whose length is shorter than the original number. Here is an example:

Input:
  11
Binary:
  11 -> 1011
Substrings:
  101 = 5
  011 = 3
  10  = 2
  01  = 1
  11  = 3
  1   = 1
  0   = 0
  1   = 1
  1   = 1
Sum:
  5+3+2+1+3+1+0+1+1=17
Output:
  17

Your program should take a single decimal integer as input and output the sum of the binary sub-strings, as seen above. You may assume the input will always have more than two digits in its binary representation and that in input will not cause any errors during your program's execution.

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

Test cases:

2  => 1
3  => 2
4  => 3
5  => 5
6  => 7
7  => 9
8  => 7
9  => 10
10 => 14
11 => 17

Jelly, 10 7 bytes

BṡRḄFS_

Try it online!

How it works

BṡRḄFS_  Main link. Input: n

B        Convert n to base 2.
  R      Yield [1, ..., n].
 ṡ       Get all overlapping slices of lengths 1 to n.
         This yields empty arrays if the slice size is longer than the binary list.
   Ḅ     Convert each binary list to integer.
    F    Flatten the resulting, nested list.
     S   Compute the sum of the result.
      _  Subtract n from the sum.


Decimal Time of Day Conversion Introduction
Time is confusing. Sixty seconds to a minute, sixty minutes to an hour, twenty-four hours to a day (and not to mention that pesky am/pm!).
There's no room for such silliness nowadays, so we've decided to adopt the only sensible alternative: decimal days! That is to say, each day is considered 1 whole unit, and anything shorter is written as a decimal fraction of that day. So, for example: "12:00:00" would be written as "0.5", and "01:23:45" might be written as "0.058159".
Because it will take time to get used to the new system, you are tasked with writing a program that can convert between them in both directions.
Challenge
Write a program in the language of your choice, that given a modern time in the ISO-8601 format of "hh:mm:ss", will return the equivalent decimal fraction unit. Likewise, given a decimal fraction, the program should return the time in the modern format initially specified.
You can make the following assumptions:

The modern time input and output can range from "00:00:00" to "24:00:00"
The decimal time input and output can range from "0" to "1", and should be able to accept/output up to at least 5 decimal places (such as "0.12345"). More precision is acceptable
The program should be able to know which conversion direction to perform based on input
You cannot use time related functions/libraries

The winner will be determined by the shortest code that accomplishes the criteria. They will be selected in at least 7 decimal day units, or if/when there have been enough submissions.
Examples
Here's a(n intentionally) poorly written piece of JavaScript code to be used as an example:
function decimalDay(hms) {
    var x, h, m, s;
    if (typeof hms === 'string' && hms.indexOf(':') > -1) {
        x = hms.split(':');
        return (x[0] * 3600 + x[1] * 60 + x[2] * 1) / 86400;
    }
    h = Math.floor(hms * 24) % 24;
    m = Math.floor(hms * 1440) % 60;
    s = Math.floor(hms * 86400) % 60;
    return (h > 9 ? '' : '0') + h + ':' + (m > 9 ? '' : '0') + m + ':' + (s > 9 ? '' : '0') + s;
}
decimalDay('02:57:46'); // 0.12344907407407407
decimalDay('23:42:12'); // 0.9876388888888888
decimalDay(0.5); // 12:00:00
decimalDay(0.05816); // 01:23:45

CJam, 58 56 42 bytes

I am sure this is too long and can be golfed a lot. But here goes for starters:

86400q':/:d_,({60bd\/}{~*i60b{s2Ue[}%':*}?

Try it online here


APL (Dyalog Classic), 29 25 bytes

'|-'[{a,⊖⌽⍉~a←⍪⍨⍵}⍣⎕⍉⍪⍳2]

Try it online!

⍳2 is the vector 0 1

⍪ turns it into a 2x1 matrix

⍉ transposes it, so it becomes 1x2

⎕ evaluated input

{ }⍣⎕ apply a function that many times

⍪⍨⍵ concatenate the argument on top of itself - a 2x2 matrix

a← remember as a

~ negate

⍉ transpose

⌽ reverse horizontally

⊖ reverse vertically

a, concatenate with a on the left

'|-'[ ] use the matrix as indices in the string '|-', i.e. turn 0 into | and 1 into -


Grow words from fertile vocabularies An incremental word chain is a sequence of words of a vocabulary such that each word is the result of either prepending or appending a single character to the previous word, ignoring capitalization. An example of such a chain can be found below.

  I → is → his → hiss

Your task is to write a program that for a given vocabulary finds the longest incremental word chain. The input is provided from standard input a vocabulary as one word per line. The words are composed of the lowercase letters a to z only. The output of your program shall go to standard output and shall be one word per line a longest word chain of the input vocabulary, starting with the shortest word.

This is code golf, the solution with the least character count wins. Different forms of input or output are not possible, but the terms standard input and standard output may be interpreted in a reasonable way for the language you are solving this problem in.

Please demonstrate that your code works by publishing the longest word chain you find on the xz-compressed vocabulary found here. This vocabulary was generated by executing the following series of commands on the file british-english-insane from the SCOWL project in the C locale:

tr 'A-Z' 'a-z' <british-english-insane | sed -n '/^[a-z]*$/p' | sort -u | xz -9e >voc.xz

A solution in polynomial time is possible and highly appreciated.

Ruby, 127

Runs in about 6.5 seconds. Uses a couple of cool tricks. ARGF ($< or stdin, really) is enumerable! If an array is passed as a block argument, it can be "exploded" and assigned to a parameter using {|w,| ... }. Notice the comma.

I found an even shorter solution which uses Array#& (set intersection) to do the lookup of words, but that runs extremely slow, unfortunately.

Thanks to w0lf for shaving off a few characters

D={}
$<.map{|l|D[l.strip!]=l}
puts D.map{|w,|c=[w]
w.chars.all?{w=c[0]
r=D[w.chop]||D[w[1..-1]]
r ?c=[r]+c :p}
c}.max_by &:size

Output

r
ra
rah
rahm
brahm
brahma
brahman
brahmani
brahmanis
brahmanism
brahmanisms

Readable version

D = {}
$<.lines { |l| D[l.strip] = l.strip }

chains = D.map do |word, _|
  chain = [word]

  word.chars.all? do
    word   = c.first
    result = D[w.chop] || D[w[1..-1]]

    result ? chain.unshift(result) : nil
  end
end

puts chains.max_by(&:size)


Cleaning up decimal numbers Background
Sometimes in calculus you're expected to calculate the sum of an infinite series. Sometimes these series are very friendly, like a geometric series, but add anything else onto it and it can quickly get complicated to solve by hand.
Sometimes I like to be lazy - a lot of sums can be found simply by adding the first few terms then making an approximation. Say the sum of the first ten terms is 0.199999983, and the future terms are approaching zero. We can say with a fair degree of certainty that our final answer will be 0.2, or 1/5.
The Challenge
Given a decimal number and an integer as inputs, calculate the best (fully simplified) fractional approximation of the decimal number for all fractions up to a denominator of the given integer. The best fractional approximation will be that which is closest to the decimal number in absolute value.
You may take these inputs any way you like and you may output the numerator and denominator any way you like. The numerator and denominator must always be integers, and you may assume we will deal with only positive numbers because adding a negative sign is trivial.
Test Cases
Input | Output

1.21, 8 | 6/5

3.14159265359, 1000000 | 3126535/995207

19.0, 10000000 | 19/1

3.14159265359, 12 | 22/7

2.7182818, 100 | 193/71

0.8193927511, 22 | 9/11

0.2557463559, 20 | 1/4

0.2557463559, 100 | 11/43

0.0748947977, 225 | 14/187

Scoring
This is code-golf. Shortest code wins!

Python 3, 66 61 bytes

lambda x:Fraction(x).limit_denominator
from fractions import*

Try it online!
The above function takes a floating point number and returns a bound function Fraction.limit_denominator which, in turn, takes the upper bound for the denominator to return a simplified, approximated fraction as requested.
As you can tell, I’m more of an API reader than a golfer.

minus 5 bytes thanks to ovs


Print the Previous Answer! This is an answer-chaining challenge in which each answer builds on the previous answer. Taking no input, you are to output the most recent submission to this thread.

I would HIGHLY suggest sorting by oldest and skipping to the last page to find the most recent answer.

Scoring

The winner will be chosen based on a point system.

Every valid submission from each user is scored 1 point.

But here is the Fun part:

If your submission is shorter (in bytes) than the previous answer (your output), your submissions score is multiplied by the difference in bytes.

This being said, your answer does not have to be shorter than the previous one.

The winner is the user with the highest total point count and will be chosen after 2 weeks of inactivity on this thread.

Rules

Each new answer must be in an UNIQUE language, check the list below before posting an answer.
You must wait at least 1 hour before submitting a new answer if you have just posted.
You may NOT submit two answers in a row, you must wait for TWO more submissions before posting a new answer.
of course, standard loopholes are disallowed
Different versions of languages, e.g. Python 1, Python 2, and Python 3 are considered Different Languages.
Output to stdout or your language's standard for outputting text
Your code must not produce any errors
Check to make sure that no one submitted an answer in the time that you were writing your own, and if so, please adjust and resubmit your code.
Please make sure that your answer is valid
Your output will be the previous answer and ONLY the previous answer. Whitespace and newlines are permitted provided that the output still runs as intended in the previous language.
Please check your output to ensure that it runs correctly.

Notes

I'd like to encourage the use of esoteric languages to keep things interesting
I'd also like to encourage the addition of TIO links to make for easier testing and validation.

Commencement

I will start off this challenge by posting a very simple Python 1 script:

print 1

The next submission should print this code EXACTLY.

Formatting

Please format your post like this:

Answer Number - (language)

    [code]
    (preferably a TIO link)

[Submission Score]
[notes, explanations, whatever you want]

Used Languages:

$.ajax({type:"GET",url:"https://api.stackexchange.com/2.2/questions/161757/answers?site=codegolf&filter=withbody&sort=creation&order=asc",success:function(data){for(var i=0;i<data.items.length;i++){var temp=document.createElement('p');temp.innerHTML = data.items[i].body.split("\n")[0];$('#list').append('
' + temp.innerText || temp.textContent + '');}}})
<base href="https://codegolf.stackexchange.com">

And a special Thank you to all of the other users  who have posted answer-chaining questions, you have made writing this question a breeze.


Creating a quine in as many characters as possible A code-bowling is not the same as a code-golf, in a Code-Bowling, you should solve the challenge in as many characters as possible. The goal of this Code-Bowling is to create a quine in as many characters as possible, but you still should try to remove redundant characters. For example, don't post a HQ9+ solution with 10,000,000 times the + character, because the code still works if you remove them. Also, don't use variables with a name of 100 characters long, because you could easily rename them to a name of one character.
Because this is a popularity-contest, the highest-voted answer wins. With 'redundant characters', I mean characters that can be removed, but the code will still work after removing them.

Brainfuck:  153,191 bytes
This is probably my largest BF binary. It prints it's own source including the intro text which is the Norwegian fairy tail The three billy goats Gruff (De tre bukkene Bruse). You cannot remove the story without removing the generating code so this Quine is designed to tell a story!
bf (A well known interpreter on Debian based linux distros) has too few cells by default so start it with:
bf -c35724 billy-quine.bf

Since StackExchange has a 30K limit I had to put it somewhere else. Beginning of the file follows:
[
Once upon a time there were three billy goats, names Gruff. They were on their
way to eat on the hillside, but they had to cross a bridge. Under the bridge
lived a troll, with eyes as big as saucers, and a nose as long as a poker.

The first goat over the bridge was the youngest Billy Goat Gruff. "Trip, trap,
trip, trap!" he walked across the bridge.

"Who's that tripping over my bridge?" roared the troll.

"I am the smallest Billy Goat Gruff, and I'm going up to the hillside to make
myself fat," said the billy goat, with a tiny voice.

"I'm coming to gobble you up," said the troll.

"Oh, no! please don't eat me. I'm too little!" said the billy goat. "Wait for
the second Billy Goat Gruff. He's much bigger."

"Well, be off with you," said the troll.

A little while later, the second Billy Goat Gruff crossed the bridge. "Trip,
trap, trip, trap, trip, trap" went the bridge.

"Who's that tripping over my bridge?" roared the troll.

"I am the second Billy Goat Gruff, and I'm going up to the hillside to make
myself fat," said the billy goat, with a medium voice.

"I'm coming to gobble you up," said the troll.

"Oh, no! Don't eat me. Wait for the last Billy Goat Gruff. He's much bigger."

"Very well! Be off with you," said the troll.

Next, the big Billy Goat Gruff crossed the bridge. "Trip, trap, trip, trap,
trip, trap!" went the bridge. This billy goat was heavy and the bridge creaked
and groaned under him.

"Who's that tramping over my bridge?" roared the troll.

"I am the big Billy Goat Gruff ," said the billy goat, with a big ugly voice.

"I 'm coming to gobble you up," roared the troll.

"No, you're not!" said the biggest Billy Goat Gruff. "I am bigger than you and
I could crush you into bits and bones."

"No, you're not!" said the biggest Billy Goat Gruff. "I am bigger than you and
I could crush you into bits and bones."

And when the troll saw how big the billy goat was, the troll let him pass. After
that, the three billy goats went to the hillside. They got so fat they could
hardly walk home. And if the fat hasn't fallen off, they're still fat; and so,

Snip, snap, snout. This tale's told out.
]
->>>>++++>++>++>>++++>++>+++>++>++++>++>++>+++++>+++>++>++++++>++>++++>+>+>+++>+>+>++++>+>+++>+>+>++++>++>++++>++>+++>++>++++>++>++>+++>>++++>+>+>+++>+>+>++++>+>+++>+>+>+++++>+++>+++++>+++>++>++>>++++>++>++>+++>+++++>+>+>>+>+>+>+>>>>+>+>>+>+>+++++>+++++>+>+>+>+>+++++>+++++>+>+>++++>++>++>++>++>++>++>++>++>++>++>++>++>++>++>++>++>>+>+>>+>+>>+>+>>>+>+>>>+>+>+>+++++>+>+>+>>+>+>+++++>+++>>>++>++++>++>++>++>++>++>>+>+>>+>+>+>+++++>+++>++>++++>>+>+>+>++++>++>>+>+++++>+++>++>++++>++>>+>+++++>+++>++++++>+>+>>++>++>++>++++>+>+>+>>++>++++++>++>++>+++++>+++>+++++>+++>>+>++++++>++++++>++++++>++++++>+++++>+>+++++>+++++>+>++++>++>++>>>>>>>>+>>>>>>+>+++++>+++>>>>>>>>>>+>++++>>++>+++++>+++>>++>++>++>++>++++++>+>++++>++>>>>>>>>>>+>+++++>+++>>>>>>+>++++>++++>++>++>+++++>+++++>+++>>>+>+++++>++++>>++>+++++>+++>+++>>++++>+++++>+++>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>+>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++++++>>>>>>>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>>>>>>>>>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>+>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>>>>>>++++++>>++++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>>>>++>++++>+>>>>>>>>++>+++++>+++>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++++++>>>>>>>++++++>>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++>++++>+>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>++>+++++>+++>>>>>>+>++++++>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>>>>>>>>>>>++++++>>++>++++>+>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>+>++++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>+>++++++>+++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>++++++>>>>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>++++++>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>+>++++++>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>++++++>>>>>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>++++++>>>++>++++>+>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>+++++>++>++++>+>>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++++++>>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>++>++++>+>>>>>>>>++>+++++>+++>>>>>>>+>++++++>>>>++>++++>+>>>>>>>++>+++++>+++>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++>+++++>++++++>>>>>>>>++++++>++>++++>+>>>>>>>>>>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>++++++>>>>>>>>>>>>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>++>++++>+>>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>>+>++++++>>>>>>>>>>>>>>++++++>>>>>>>>>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>++>++++>+>>>>>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>>>>>++>++++>+>>>>>>>>>>>++>+++++>+++>>>>>>>>>>+>++++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>+>++++++>+++++>+++++>+++++>+++++>++>++++>+>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++>+++++>+++>>>>>>>>>+>++++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>+++++>++++++>+++++....


Tips for Golfing in ECMAScript 6 and above This is similar to other "Tips for golfing in <...>" but specifically targeting the newer features in JavaScript brought up in ECMAScript 6 and above.

JavaScript inherently is a very verbose language, function(){}, .forEach(), converting string to array, array-like object to array, etc, etc are super bloats and not healthy for Golfing.

ES6+, on the other hand, has some super handy features and reduced footprint. x=>y, [...x], etc. are just some of the examples.

Please post some nice tricks that can help shave off those few extra bytes from your code.

NOTE: Tricks for ES5 are already available in Tips for golfing in JavaScript; answers to this thread should focus on tricks only available in ES6 and other future ES versions.

However, this thread is also for users who currently golf using ES5 features. Answers may also contain tips to help them understand and map ES6 features to their style of ES5 coding.

Spread operator ...

The spread operator transforms an array value into a comma separated list.

Use case 1:

Directly use an array where a function expects a list

list=[1,2,3]
x=Math.min(...list)
list=[10,20], a.push(...list) // similar to concat()

Use case 2:

Create an array literal from an iterable (typically a string)

[...'buzzfizz'] // -> same as .split('')

Use case 3:

Declare a variable number of arguments for a function

F=(...x) => x.map(v => v+1)
// example: F(1,2,3) == [2,3,4]

See mozilla doc


Shortest unmatchable regular expression Your mission is to write the shortest valid regular expression that no string can match, empty string included.

Submissions must have this form ("literal notation"):

/pattern/optional-flags

Shortest regexp wins. The regexp size is counted in characters. (including slashes and flags)

Please explain how your regexp works (if it's not trivial)

Thanks, and have fun!

6 chars

Following on the answers of primo and Peter Taylor, and a hint from man perlre:

/(?!)/

This perl-compatible regex matches an empty string which is not followed by another empty string.


How many unique primes? One way to represent a natural number is by multiplying exponents of prime numbers.  For example, 6 can be represented by 2^1*3^1, and 50 can be represented by 2^1*5^2 (where ^ indicates exponention).  The number of primes in this representation can help determine whether it is shorter to use this method of representation, compared to other methods.  But because I don't want to calculate these by hand, I need a program to do it for me.  However, because I'll have to remember the program until I get home, it needs to be as short as possible.

Your Task:

Write a program or function to determine how many distinct primes there are in this representation of a number.

Input:

An integer n such that 1 < n < 10^12, taken by any normal method.

Output:

The number of distinct primes that are required to represent the input, as outlined in the introduction.

Test Cases:

24      -> 2 (2^3*3^1)
126     -> 3 (2^1*3^2*7^1)
1538493 -> 4 (3^1*11^1*23^1*2027^1)
123456  -> 3 (2^6*3^1*643^1)

This is OEIS A001221.

Scoring:

This is code-golf, lowest score in bytes wins!

MATL, 4 3 bytes

-1 byte thanks to Luis Mendo

YFz

Try it online!

YF         Exponents of prime factors
  z        Number of nonzeros

Original answer:

Yfun

Try it online!

A verYfun answer.

          (Implicit input)
Yf         Prime factorization
  u        Unique
   n       Numel
           (Implicit output)


Reproportioning a population by adding fixed sized groups Introduction

Say you have a population of people.  This population is made up of 100 Alices and 25 Bobs. So, 80% of the population are Alices and 20% are Bobs.  We want to change the proportional makeup of the population to be 62% Alices and 38% Bobs.

Rules

You can only add to the population.  You cannot take any away from the starting population.
You can only add in multiples of the original subpopulation size.  So following the above example, you can only add batches of 100 Alices to the group; likewise, you can only add batches of 25 Bobs to the group.
You have a pool of unlimited Alices and Bobs that are not in the population yet.
The algorithm must be able to handle N different name groups (e.g. N=4: Alice, Bob, Carol, David).

Pseudocode framework

# 100 Alices, 25 Bobs, 35 Carols, 60 Davids
starting_population = (100, 25, 35, 60)

# Goal percentages, must sum to 100
reproportion_goal = (10, 20, 30, 40)

# Reproportion the population to meet the goal percentages, following the rules
new_population = reproportion_population(starting_population, reproportion_goal)

Winner

Create an algorithm to re-proportion the population following the rules with an arbitrary starting_population and reproportion_goal.

The winning algorithm will solve the above-quoted problem in the fastest time on a single-core single-CPU i686 system with fixed clock speed.  The algorithm must also solve other reasonable cases through the same code-path.  That is, do not special-case for the example data.

I will use many thousands of iterations to test the timing of the approach.  VM/runtime startup times will not be counted.  The algorithm will be warmed up before timing starts. You can specify the specific version of framework you would like me to run your code under, and if I can reasonably set it up, I will.

Introduction

Say you have a population of people.  This population is made up of 100 Alices and 25 Bobs. So, 80% of the population are Alices and 20% are Bobs.  We want to change the proportional makeup of the population to be 62% Alices and 38% Bobs.

Rules

You can only add to the population.  You cannot take any away from the starting population.
You can only add in multiples of the original subpopulation size.  So following the above example, you can only add batches of 100 Alices to the group; likewise, you can only add batches of 25 Bobs to the group.
You have a pool of unlimited Alices and Bobs that are not in the population yet.
The algorithm must be able to handle N different name groups (e.g. N=4: Alice, Bob, Carol, David).

Pseudocode framework

# 100 Alices, 25 Bobs, 35 Carols, 60 Davids
starting_population = (100, 25, 35, 60)

# Goal percentages, must sum to 100
reproportion_goal = (10, 20, 30, 40)

# Reproportion the population to meet the goal percentages, following the rules
new_population = reproportion_population(starting_population, reproportion_goal)

Winner

Create an algorithm to re-proportion the population following the rules with an arbitrary starting_population and reproportion_goal.

The winning algorithm will solve the above-quoted problem in the fastest time on a single-core single-CPU i686 system with fixed clock speed.  The algorithm must also solve other reasonable cases through the same code-path.  That is, do not special-case for the example data.

I will use many thousands of iterations to test the timing of the approach.  VM/runtime startup times will not be counted.  The algorithm will be warmed up before timing starts. You can specify the specific version of framework you would like me to run your code under, and if I can reasonably set it up, I will.

Dates (deadline and winner)

Deadline for submissions is before March 14, 2016.  I will post benchmarks by March 20.  Feel free to answer after these dates, but I can't commit to re-benchmarking submissions after March 14.

C

void reproportion(
        const unsigned int n,
        const unsigned int *const starting_population,
        const unsigned int *const reproportion_goal,
        unsigned int *const new_population)
{
    unsigned int unit = 1U;

    for(unsigned int i = 0U; i != n; ++i) {
        unit *= starting_population[i];
    }

    for(unsigned int i = 0U; i != n; ++i) {
        new_population[i] = reproportion_goal[i] * unit;
    }
}

This assumes that the original subpopulation sizes are greater than zero. starting_population = { 0, 1, 2 } and reproportion_goal = { 0, 50, 50 } would give the incorrect result of new_population = { 0, 0, 0 }. If the original subpopulation size can be zero, unit *= starting_population[i]; should be preceded by if(starting_population[i] != 0U).

Call this function from within your program like so:

#include <stdio.h>

int main(void)
{
    unsigned int starting_population[] = { 1, 2, 31, 4 };
    unsigned int reproportion_goal[] = { 25, 25, 40, 10 };
    unsigned int new_population[4];

    reproportion(4, starting_population, reproportion_goal, new_population);

    for(int i = 0; i < 4; ++i) {
        printf("%d ", new_population[i]);
    }
}