Generating a Student Timetable Introduction

You are the computer science teacher in a large high school and have been tasked to create a system to generate the student timetables. You must, given a JSON dictionary of student names and the subjects they are taking, you must generate a timetable for each of the students.

Specifications

Each student takes seven subjects (English Literature, English Language and Maths are compulsory but don't count towards the seven subjects):

Subject name - Abbreviation

Art - Ar
Biology - Bi
Business Studies - Bu
Chemistry - Ch
Computer Science - CS
French - Fr
Geography - Gg
History - Hi
IT - IT
Mandarin - Cn
Music - Mu
PE - PE
Physics - Ph
Spanish - Sp

Compulsory:

English Language - La
English Literature - Li
Maths - Ma

Other:

Tutor - Tu
Free - Ac

All abbreviations must be in the same case as above.

Each day has ten periods of lessons. A lesson can either span a single period or a double period. There must be three lessons of each subject with each having one double lesson (double period length) and two single lessons. The only exception to this rule is English Language which only occurs once a week and is a double.

There must be only one lesson of the same subject a day.

A school day is Monday to Friday.

Between periods 3 and 4 and between periods 5 and 6, there is a break. Lessons must not be placed over a break. From period six inclusive on a Wednesday to the end of the day, there are free periods. Period 1 on a Tuesday is Tutor period. Period 10 on a Friday is also Tutor. Period 10 on a Thursday is a free period.

Lessons must not be split into multiple groups meaning that people studying the same subject must be together in those subjects. Students may have any number of frees.

You must use the subject's abbbreviation in the timetable.

Data input

The JSON data must either be read from a local file or placed as a string variable in your code. The file will be a list of students with their names and a list of subjects. For example:

[
{"name":"Sarah","subjects":["physics","it","biology","history","art","business studies","french"]},
{"name":"Jim","subjects":["history","business studies","biology","computer science","geography","chemistry"]},
{"name":"Mary","subjects":["it","computer science","biology","physics","chemistry","art"]},
{"name":"Chris","subjects":["biology","chemistry","physics","french","computer science","geography"]}
]

Your program should then generate a timetable for each of the students, fitting all of the subjects in.

If there are multiple solutions, choose the first.

Note: The JSON file above has not been tested to see if it has a valid answer, it was just created to describe the formatting.

Output

The output must be a JSON file or CSV with the format detailed in your answer. You can either make a file for each of the students or have the timetables for all students in the same file.

Winning

The winning code is the shortest that successfully creates working timetables.

NodeJS

Edit
The algorthim is much faster now!
There is definitely no solution for the given example!

I tried some algorithms to generate a time table and I am pretty sure that your example has no solution.
So I changed the example to
students.json:

[
{"name":"Sarah","subjects":["physics","it","biology","history","art","business studies","french"]},
{"name":"Jim","subjects":["history","business studies","biology","computer science","geography","chemistry"]},
{"name":"Mary","subjects":["it","computer science","biology","physics","chemistry","art"]},
{"name":"Chris","subjects":["biology","chemistry","physics","french","computer science","geography"]}
]

(I only deleted the pe)
which generates this timeTable.json

 {
 "mon":
   [["Bi"],["Bi"],["Ar","Gg"],["La"],["La"],["Ch"],["Ch"],["CS"],["CS"],["Ph"]],
 "tue":
   [["Tu"],["Bi"],["Ar","Gg"],["Ma"],["Ma"],["Ch"],["CS"],["Ph"],["Ph"],["Bu"]],
 "wed":
   [["Bi"],["Ar","Gg"],["Ar","Gg"],["Li"],["Li"],["Fr"],["Fr"],["IT"],["IT"],["Hi"]],
 "thu":
   [["Li"],["Ma"],["Ch"],["CS"],["Bu"],["Ph"],["Fr"],["IT"],["Hi"],["Ac"]],
 "fri":
   [["Li"],["Ma"],["Fr"],["Bu"],["Bu"],["IT"],["Hi"],["Hi"],[],["Tu"]]
 }

And yes my programm is very long but I think code which is shortened afterwards makes it really hard to read and nowadays it isn't important to save bytes but time!
If you have any suggestions or you found a bug => comment!
You can start the file (timeTable.js) with node timeTable.js students.js

    var fs = require('fs');

console.log('Timetable');
var json = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));

var backTracks = 0;
var lessons =
    ["art","biology","business studies","chemistry","computer science","french","geography","history","it","mandarin","music","pe","physics","spanish"];
var abbr = ["Ar","Bi","Bu","Ch","CS","Fr","Gg","Hi","IT","Cn","Mu","PE","Ph","Sp"];
var single = [2,2,2,2,2,2,2,2,2,2,2,2,2,2];
var double = [1,1,1,1,1,1,1,1,1,1,1,1,1,1];

var days = ["mon","tue","wed","thu","fri"];
var nrOfStudents = json.length;
var q = 0;

// convert json into correct position
for (var i = 0; i < json.length; i++) {
    var subjects = json[i].subjects;
    for (var s = 0; s < subjects.length; s++) {
        var pos = lessons.indexOf(subjects[s].toLowerCase());
        if (pos >= 0) {
            subjects[s] = pos;
        }
    }
}

// Special lessons
var timeTable = {"mon":[],"tue":[],"wed":[],"thu":[],"fri":[]};
timeTable.tue[0] = ["Tu"];
timeTable.fri[9] = ["Tu"];
timeTable.thu[9] = ["Ac"];
// one english double (Monday 4-5)
timeTable.mon[3] = ["La"];
timeTable.mon[4] = ["La"];
// one double two single for math and literature (Tue 4-5,Wed 4-5,Thu 1,2,Fri 1,2)
timeTable.tue[3] = ["Ma"];
timeTable.tue[4] = ["Ma"];
timeTable.wed[3] = ["Li"];
timeTable.wed[4] = ["Li"];
timeTable.thu[0] = ["Li"];
timeTable.thu[1] = ["Ma"];
timeTable.fri[0] = ["Li"];
timeTable.fri[1] = ["Ma"];

var timeTableBackup = {0:[],1:[],2:[],3:[],4:[]};

for (var i = 0; i < 5; i++) {
    var day = timeTable[days[i]];
    for (var j = 0; j < 10; j++) {
        if (!(j in day) || !Array.isArray(day[j])) {
            day[j] = [];
        }
    }
}

// sort subjects
var sortedSubs = [];
// 14 subjects
for (var i = 0; i < 14; i++) {
    sortedSubs[i] = {t:0,students:[],n:i};
}

for (var i = 0; i < json.length; i++) {
    var subjects = json[i].subjects;
    var student = json[i].name;
    for (var s = 0; s < subjects.length; s++) {
        sortedSubs[subjects[s]].t ++;
        sortedSubs[subjects[s]].n = subjects[s];
        sortedSubs[subjects[s]].students.push(student);
    }
}
console.log(sortedSubs);

sortedSubs = sortByKey(sortedSubs,"t");

var k = sortedSubs.length-1;
// remove all subs that weren't choosen by anyone
while(sortedSubs[k].t == 0) {
    var sub = sortedSubs.pop();
    single[sub.n] = 0;
    double[sub.n] = 0;
    k--;
}

var goBack = false;
var start = false;
var d = 0;
while (d < 5) {
    // 10 lessons per day
    var l = 0;
    while(l < 10) {
        var day = timeTable[days[d]];
        // if there is no subject
        if (day[l].length == 0) {
            var next = false;
            var s = start === false ? 0 : start;
            var firstChoice = false;
            while (!next && s < sortedSubs.length) {
                if (possibleToAdd(day,l,s)) { // different lessons on one day and possiblity to add lesson
                    goBack = false;
                    next = true;
                    if (!firstChoice) firstChoice = s;
                    // get the number of students that don't have this lesson
                    var except = nrOfStudents - sortedSubs[s].t;
                    if (except > 0) {
                        // get the first lesson which none of the students have
                        var breaked = false;
                        var tempL;
                        for (var ss = s+1; ss < sortedSubs.length; ss++) {
                            if (sortedSubs[ss].t <= except && possibleToAdd(day,l,ss)) {
                                var intersection = arrIntersect(sortedSubs[s].students,sortedSubs[ss].students);
                                // no student has both classes
                                if (intersection.length == 0) {
                                    if (!breaked) { // fill the current lesson (s) only once
                                        tempL = addLesson(day,l,s);
                                    }
                                    tempL = addLesson(day,l,ss);
                                    breaked = true;
                                }
                            }
                        }

                        if (breaked) {
                            l = tempL;
                        } else { // it wasn't possible to have two classes at this time
                            next = false;
                            var found = false;
                            // maybe there are other lessons which can be added => found = true
                            for (var z = s+1; z < sortedSubs.length; z++) {
                                if (possibleToAdd(day,l,z)) {
                                    found = true;
                                    break;
                                }
                            }
                            // otherwise fill this lesson with the first choice
                            if (!found) {
                                l = addLesson(day,l,firstChoice);
                            }
                        }
                    } else {
                        // everyone has this lesson :)
                        // on day lesson no. l: subject no. s
                        l = addLesson(day,l,s);
                    }
                } else {
                    if (start) goBack = true;
                }
                s++;
            }
            start = false;
        }
        // Friday last lesson
        if ((d == 4 && l == 9) || goBack) {
            // how many lessons are missing?
            var sum = double.reduce(function(pv, cv) { return pv + cv; }, 0)*2 + single.reduce(function(pv, cv) { return pv + cv; }, 0);
            if (sum > 0) {
                remove = removeLesson(d,l);
                if (remove) {
                    backTracks++;
                    if (backTracks % 50000 == 0) {
                        console.log('backTracks: '+backTracks+'...');
                    }
                    d = remove.back.day;
                    l = remove.back.lesson;
                    start = remove.start;
                } else {
                    console.log('I could not find a solution for this problem :( ');
                    console.log('backtracks: '+backTracks);
                    process.exit();
                    l = 10;
                    d = 5;
                }
            } else {
                l = 10;
                d = 5;
            }
        } else {
            l++;
        }
    }
    d++;
}

function removeLesson(d,l) {
    var day = timeTable[days[d]];
    var back = true;
    // what is the latest subject
    var latestSub = sortedSubs[sortedSubs.length-1].n;

    // backtrack
    while(back) {
        // if there is no lesson before => back to the last lesson the day before
        if (l == -1) {
            if (d == 0) {
                return false; // not possible at all
            }
            d--;
            day = timeTable[days[d]];
            l = day.length-1;
        }

        // if there is a non default lesson
        if (day[l].length > 0 && parseInt(day[l][0]) == day[l][0]) {
            // if the latestSub isn't part of this lesson we don't need to backtrack more
            if (day[l].indexOf(latestSub) < 0) { back = false; }
            var intersection = [];
            // if we are not in the first lesson => get double lessons
            if (l > 0) {
                intersection = arrIntersect(day[l],day[l-1]);
            }
            // if there are double lessons
            if (intersection.length > 0) {
                for (var i = 0; i < day[l].length; i++) {
                    // check if current lesson is a double lesson
                    if (intersection.indexOf(day[l][i]) >= 0) {
                        double[day[l][i]]++;
                    } else {
                        single[day[l][i]]++;
                    }
                }
                // remove all single lessons the lesson before
                for (var i = 0; i < day[l-1].length; i++) {
                    if (intersection.indexOf(day[l-1][i]) < 0) {
                        single[day[l-1][i]]++;
                    }
                }
                day[l] = [];
                l--;
            } else {
                for (var i = 0; i < day[l].length; i++) {
                    single[day[l][i]]++;
                }
            }
            // delete the day if the current lesson was the least possible solution
            if (back) {
                day[l] = [];
            }
        } else {
            l--;
        }
    }
    var start = false;
    // get start subject for this lesson d,l
    for (var s = 0; s < sortedSubs.length-1; s++) {
        if (day[l].indexOf(sortedSubs[s].n) >= 0) {
            start = ++s;
            day[l] = [];
            break;
        }
    }
    if (!start) {
        console.log('there is a bug');
        process.exit();
    }
    return {back:{day:d,lesson:l},start:start};
}

function addLesson(day,l,s) {
    // is a double lesson possible?
    if (double[sortedSubs[s].n] > 0 && l != 2 && l != 4 && l+1 < 10 && (day[l+1].length == 0 || parseInt(day[l+1][0]) == day[l+1][0])) {
        double[sortedSubs[s].n]--;
        for (var i = l; i <= l+1; i++) {
            if (Array.isArray(day[i])) {
                day[i].push(sortedSubs[s].n);
            } else {
                day[i] = [sortedSubs[s].n];
            }
        }
        l++;
    } else if (single[sortedSubs[s].n] > 0) { // put it into a single lesson
        single[sortedSubs[s].n]--;
        if (Array.isArray(day[l])) {
            day[l].push(sortedSubs[s].n);
        } else {
            day[l] = [sortedSubs[s].n];
        }
    } else {
        console.log('ERROR');
        process.exit();
    }
    return l;
}

function possibleToAdd(day,l,s) {
    // it is not allowed to have the same lesson twice on a day
    var notSet = true;
    for (var i = 0; i < l; i++) {
        if (day[i].indexOf(sortedSubs[s].n) >= 0) {
            notSet = false;
            break;
        }
    }
    if (!notSet) return false;

    // no double lesson 3+4 and (starting with 1)
    if (double[sortedSubs[s].n] > 0 && l != 2 && l != 4 && l+1 < 10 && (day[l+1].length == 0 || parseInt(day[l+1][0]) == day[l+1][0])) {
        return true;
    } else if (single[sortedSubs[s].n] > 0) {
        return true;
    } else {
        return false;
    }
}

function arrIntersect(array1,array2) {
    return array1.filter(function(n) {
        return array2.indexOf(n) != -1
    });
}

function sortByKey(array, key) {
    return array.sort(function(a, b) {
        var x = a[key];
        var y = b[key];
        return ((x < y) ? 1 : -1);
    });
}

// convert lesson numbers into abbr
for (var d = 0; d < 5; d++) {
    var day = timeTable[days[d]];
    // 10 lessons per day
    for (var l = 0; l < 10; l++) {
        for (var ll = 0; ll < day[l].length; ll++) {
            if (parseInt(day[l][ll]) == day[l][ll]) {
                day[l][ll] = abbr[day[l][ll]];
            }
        }
    }
}

console.log(timeTable);
console.log('Backtracks: '+backTracks);

fs.writeFile("timeTable.json", JSON.stringify(timeTable), function(err) {
    if(err) {
        console.log(err);
    } else {
        console.log("The file was saved (timeTable.json)!");
    }
});


Solve the BattleBlock Theater Puzzle The game BattleBlock Theater occasionally contains a puzzle which is a generalised version of Lights Out. You've got three adjacent blocks, each of which indicates a level between 1 and 4 inclusive with bars, e.g.:

|
||||
||

If you touch a block, then that block as well as any adjacent block will increment its level (wrapping back from 4 to 1). The puzzle is solved when all three blocks show the same level (it doesn't matter which level). Since, the order you touch the blocks in doesn't matter, we denote a solution by how often each block is touched. The optimal solution for the above input would be 201:

|    --> || --> |||     |||
||||     |      ||      |||
||       ||     ||  --> |||

The game very easily generalises any number of blocks, although for some numbers, not all configurations are solvable.

The Challenge

Given a sequence of block levels, return how often each block needs to be touched to solve the puzzle. E.g. the above example would be given as 142 and could yield 201 as a result. If there is no solution, return some consistent output of your choice, which is distinguishable from all potential solutions, e.g. -1 or an empty string.

You may write a function or program, take input via STDIN, command-line argument or function argument, in any convenient list or string format, and similarly output via a return value or by printing to STDOUT.

Your code should return correct results for all test cases within a minute on a reasonable machine. (This is not a completely strict limit, so if your solution takes a minute and ten seconds, that's fine, but if it takes 3 minutes, it isn't. A good algorithm will easily solve them in seconds.)

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

Examples

Solutions are not unique, so you may get different results.

Input                          Output

1                              0
11                             00
12                             No solution
142                            201
434                            101
222                            000
4113                           0230
32444                          No solution
23432                          10301
421232                         212301
3442223221221422412334         0330130000130202221111
22231244334432131322442        No solution
111111111111111111111222       000000000000000000000030
111111111111111111111234       100100100100100100100133
412224131444114441432434       113013201011001101012133

As far as I know, there are exactly 4 solutions for each input where the number of blocks is 0 mod 3, or 1 mod 3, and there are 0 or 16 solutions where it is 2 mod 3.

Python 2, 115 bytes
n=input()
for F in range(4):
 t=[F];b=0;exec"x=(-n[b]-sum(t[-2:]))%4;t+=x,;b+=1;"*len(n)
 if x<1:print t[:-1];break

This is the golfed version of the program I wrote while discussing the problem with Martin.
Input is a list via STDIN. Output is a list representing the last solution found if there is a solution, or zero if there isn't. For example:
>>>
[1, 4, 2]
[2, 1, 1]
>>>
[1, 2]
0
>>>
map(int,"3442223221221422412334")
[2, 3, 3, 2, 1, 3, 2, 0, 0, 2, 1, 3, 2, 2, 0, 0, 2, 2, 3, 1, 1, 3]

Pyth, 32 29 bytes
V4J]NVQaJ%_+s>J_2@QN4)I!eJPJB

The obligatory port. Thanks to @Jakube for the 3 byte saving.
Input method is the same as above, try it online.

Explanation (long and full of logic!)
First, two basic observations:

Observation 1: It doesn't matter which order you touch the blocks

Observation 2: If you touch a block 4 times, it's equivalent to touching it once

In other words, if there is a solution then there is a solution where the number of touches is between 0 and 3 inclusive.
Since modulo 4 is so nice, let's do that with the blocks too. For the rest of this explanation, block level 0 is equivalent to block level 4.
Now let's denote a[k] to be the current level of block k and x[k] to be the number of times we touch block k in a solution. Also let n be the total number of blocks. As @Jakube has noted, a solution must satisfy:
  a[0]   + x[0] + x[1]
= a[1]   + x[0] + x[1] + x[2]
= a[2]          + x[1] + x[2] + x[3]
= a[3]                 + x[2] + x[3] + x[4]
...
= a[n-1]                                     ...  + x[n-2] + x[n-1] + x[n]
= a[n]                                       ...           + x[n-1] + x[n]
= C

where C is the final level all blocks end up on, between 0 and 3 inclusive (remember we're treating level 4 as level 0) and all equations above are really congruences modulo 4.
Now here's the fun part:

Observation 3: If a solution exists, a solution exists for any final block level 0 <= C <= 3.

There are three cases based on the number of blocks modulo 3. The explanation for each of them is the same — for any number of blocks, there exists a subset of blocks which, if you touch each of them once, increases all block levels by exactly 1.
0 mod 3 (touch every third block starting from the second):
    .X. / .X. / .X.

1 mod 3 (touch every third block starting from the first):
    X. / .X. / .X. / .X

2 mod 3 (touch every third block starting from either the first or second):
    X. / .X. / .X. / .X.
    .X. / .X. / .X. / .X

This explains why there are 4 solutions for 0 mod 3 and 1 mod 3, and usually 16 solutions for 2 mod 3. If you have a solution already, touching the blocks as above gives another solution which ends up at a higher block level (wrapping around).
So what does this mean? We can pick any final block level C we want! Let's pick C = 0, because this saves on bytes.
Now our equations become:
0 = a[0] + x[0] + x[1]
0 = a[1] + x[0] + x[1] + x[2]
0 = a[2] + x[1] + x[2] + x[3]
0 = a[3] + x[2] + x[3] + x[4]
...
0 = a[n-1] + x[n-2] + x[n-1] + x[n]
0 = a[n] + x[n-1] + x[n]

And rearrange:
x[1] = -a[0] - x[0]
x[2] = -a[1] - x[0] - x[1]
x[3] = -a[2] - x[1] - x[2]
x[4] = -a[3] - x[2] - x[3]
...
x[n] = a[n-1] - x[n-2] - x[n-1]
x[n] = a[n] - x[n-1]

So what we can see is, if we have x[0], then we can use all the equations except the last to find out every other x[k]. The last equation is an additional condition we must check.
This gives us an algorithm:

Try all values for x[0]
Use the above equations to work out all of the other x[k]
Check if the last condition is satisfied. If so, save the solution.

That gives the solution above.
So why do we sometimes get no solution for 2 mod 3? Let's take a look at these two patterns again:
X. / .X. / .X. / .X.
.X. / .X. / .X. / .X

Now consider the equations at those positions, i.e. for the first one:
0 = a[0] + x[0] + x[1]
0 = a[3] + x[2] + x[3] + x[4]
0 = a[6] + x[5] + x[6] + x[7]
0 = a[9] + x[8] + x[9] + x[10]

Add them up:
0 = (a[0] + a[3] + a[6] + a[9]) + (x[0] + x[1] + ... + x[9] + x[10])

For the second one:
0 = a[1] + x[0] + x[1] + x[2]
0 = a[4] + x[3] + x[4] + x[5]
0 = a[7] + x[6] + x[7] + x[8]
0 = a[10] + x[9] + x[10]

Add them up again:
0 = (a[1] + a[4] + a[7] + a[10]) + (x[0] + x[1] + ... + x[9] + x[10])

So if (a[1] + a[4] + a[7] + a[10]) and (a[0] + a[3] + a[6] + a[9]) are not equal, then we have no solution. But if they are equal, then we get 16 solutions. This was for the n = 11 case, but of course this generalises to any number that is 2 mod 3 — take the sum of every third element starting from the second, and compare to the sum of every third element starting from the first.
Now finally, is it possible to figure out what x[0] has to be instead of trying all of the possibilities? After all, since we restricted our target level C to be 0, there is only one x[0] which gives a solution in the 0 mod 3 or 1 mod 3 case (as 4 solutions / 4 final levels = 1 solution for a specific final level).
The answer is... yes! We can do this for 0 mod 3:
 .X..X
.X..X.

Which translates to:
0 = a[2] + x[1] + x[2] + x[3]   -> 0 = (a[2] + a[5]) + (x[1] + ... + x[5])
0 = a[5] + x[4] + x[5]          /

0 = a[1] + x[0] + x[1] + x[2]   -> 0 = (a[1] + a[4]) + (x[0] + x[1] + ... + x[5])
0 = a[4] + x[3] + x[4] + x[5]   /

Subtracting gives:
x[1] = (a[2] + a[5]) - (a[1] + a[4])

Similarly for 1 mod 3 we can do this pattern:
 .X..X.
X..X..X

Which gives:
x[0] = (a[2] + a[5]) - (a[0] + a[3] + a[6])

These of course generalise by extending the indices by increments of 3.
For 2 mod 3, since we have two subsets which cover every block, we can actually pick any x[0]. In fact, this is true for x[0], x[1], x[3], x[4], x[6], x[7], ... (basically any index not congruent to 2 mod 3, as they are not covered by either subset).
So we have a way of picking an x[0] instead of trying all possibilities...
... but the bad news is that this doesn't save on bytes (124 bytes):
def f(n):s=[];L=len(n);B=sum(n[~-L%3::3])-sum(n[-~L%3::3]);x=A=0;exec"s+=B%4,;A,B=B,-n[x]-A-B;x+=1;"*L*(L%3<2or B<1);print s


Recursively count lines of code, excluding empty lines and comments Requirement: Write a program (in any language) that counts the number of lines of code in files matching *.sh in the directory tree starting from the directory that the program is executed in, excluding lines that are empty, only contain whitespace, or are just single-line comments (a line which the first character that is not a whitespace character is #). Files will only contain printable ASCII characters.

Output: A single integer representing the total count (can be followed by a newline too).

Here is an expanded solution in Python:

import os, sys

def recurse(dir = './'):
    count = 0

    for file in os.listdir(dir):
        if not os.path.isfile(dir + file):
            count += recurse(dir + file + '/')
        elif file.endswith('.sh'):
            with open(dir + file, 'r') as f:
                for line in f.read().split('\n'):
                    if (not line.strip().startswith('#')) and (not line.strip() == ''):
                        count += 1

    return count

sys.stdout.write(recurse())

PowerShell, 47 46 bytes

ls *.sh -r|gc|%{$o+=!($_-match'^\s*(#|$)')};$o

Try it online! (will always return 0 since there aren't any files)

Try it online! (here's a link that populates a dummy file so you can see the process)

-1 byte thanks to Neil

ls is alias for Get-ChildItem, specifying *.sh with the -recurse parameter, then we get-content of files. For each of those lines |%{...}, we accumulate into our $output a one if the Boolean !(...) statement is truthy. Inside the statement is a simple regex -match against the whitespace-only/comment/blank lines. Finally we leave $o on the pipeline.

The implicit Write-Output that happens at program completion adds a trailing newline, but that shouldn't matter in this case because the variable $o itself doesn't have a trailing newline nor does the actual return variable. It's a quirk of the shell, not a quirk of the program. For example, saving this to a script and executing that script in a pipeline will not have a newline.


What is your star-sign? Write a program that takes a birth date (month and day-of-month) as input and outputs the corresponding sign, element and quality of the western zodiac.  For the purposes of this challenge, these are defined exactly as in the table in the linked wikipedia page:

Sign           Date Range                    Element    Quality

Aries          March 21 to April 19          Fire       Cardinal
Taurus         April 20 to May 20            Earth      Fixed
Gemini         May 21 to June 21             Air        Mutable
Cancer         June 22 to July 22            Water      Cardinal
Leo            July 23 to August 22          Fire       Fixed
Virgo          August 23 to September 22     Earth      Mutable
Libra          September 23 to October 23    Air        Cardinal
Scorpio        October 24 to November 20     Water      Fixed
Sagittarius    November 21 to December 22    Fire       Mutable
Capricorn      December 23 to January 20     Earth      Cardinal
Aquarius       January 21 to February 21     Air        Fixed
Pisces         February 22 to March 20       Water      Mutable

Rules

The sign, element and quality will be calculated from the input date exactly according to the wikipedia table.
I am giving some freedom over input date format (see Input section below).  You must clearly state in your answer what format you are using.
If an invalid date is provided (unparsable date, or month or day-of-month out of range), the program will exit with the message Invalid date.
The program must correctly handle leap years.  i.e. if Feb 29th is the input, then output must correctly be Pisces, Water, Mutable.
Your language's Date libraries/APIs are allowed, but any APIs that specifically calculate signs of the zodiac are banned.
Standard “loopholes” which are no longer funny
This is code-golf, so the shortest answer in bytes wins.

Input

The program may read the input date from STDIN, command-line, environment variables or whatever method is convenient for your language of choice.
This is not primarily an exercise in datestring-parsing, so the input string may be provided in whatever format you choose, as long as it consists of only month and day-of-month components and not other values (such as year or time).  E.g. Jul 24 or 24th of July or 7/24 or 24/07 or whatever format is convenient.  If input not matching your choice of input format is entered, then the Invalid date error must be thrown.

Output

The program will output to STDOUT, dialog box or whatever display method is convenient for your language of choice.
The output format will be the sign, element and quality separated by a comma and a space: Sign, Element, Quality

Examples

Input                 Output
1/1                   Capricorn, Earth, Cardinal
2/29                  Pisces, Water, Mutable
7/24                  Leo, Fire, Fixed
13/1                  Invalid date
2/31                  Invalid date
-1/-1                 Invalid date
1st of Golfember      Invalid date

JavaScript, 285 bytes

(My first answer here after lurking here for a while)

d=prompt(m=prompt(e='MutableCardinalFixedAirWaterFireEarthCapricornAquariusPiscesAriesTaurusGeminiCancerLeoVirgoLibraScorpioSagittarius'.match(/[A-Z][a-z]+/g)));alert(m>0&m<13&d>0&d<29-~'202121221212'[--m]?e[n=7+m%12+(d>18-~'121012333413'[m])]+', '+e[n%4+3]+', '+e[n%3]:'Invalid date')

The first prompt() is the month in numerical form, and the second prompt() is the day of the month (Ignore the text of the prompt). Leading zeroes are optional for both. The output is displayed with alert(). (Thanks to bitpwner, Snack, edc65, and core1024 for helping shorten the code.)

Try it above using Stack Snippets or at http://jsfiddle.net/8vq89/5/.

Code with whitespace and comments to explain the confusing parts added:

var m = prompt(), d = prompt(),
e = 'MutableCardinalFixedAirWaterFireEarthCapricornAquariusPiscesAries\
TaurusGeminiCancerLeoVirgoLibraScorpioSagittarius'.match(/[A-Z][a-z]+/g);
alert(m > 0 && m < 13 && d > 0
      & d < 29 - ~'202121221212'[--m] /* ~ is bitwise NOT, which yields -(x + 1). It also
                                         converts a string to a number. Subtracting that
                                         number from 29 gives the number of days in the
                                         month given. */
      ? e[n = 7 + // 7 is added to skip over the 7 qualities and elements in array e.
      m % 12 // The modulus allows dates near the end of December to wrap around to January.
      + (d > 18 - ~'121012333413'[m])] + ', ' +
      e[n % 4 + 3] + /* Qualities and elements follow a pattern, so the modulus determines
                        which one it is. 3 is added to skip over the 3 qualities. */
      ', ' + e[n % 3] : 'Invalid date')


Did you hear about alphametics? Task

The letters spell out actual words, but if you replace each letter with a digit from 0–9, it also “spells” an arithmetic equation. The trick is to figure out which letter maps to each digit. All the occurrences of each letter must map to the same digit, no digit can be repeated, and no “word” can start with the digit 0.

Input

HAWAII + IDAHO + IOWA + OHIO = STATES

Output

510199 + 98153 + 9301 + 3593 = 621246

Input

I + LOVE + YOU = DORA

Output

1 + 2784 + 975 = 3760

    Input

SEND + MORE = MONEY

Output

9567 + 1085 = 10652

Rules

Standard loopholes apply.
shortest code wins.
addition only

Appendix

for other Inputs you gotta keep in mind you can only have 10 different characters(to assign values 0-9)

JavaScript (ES7), 104 bytes

f=(s,o,c=s.match(/[A-Z]/))=>c?[...2**29+'4'].some(i=>o&1<<i?0:f(r=s.split(c).join(i),o|1<<i))&&r:eval(s)

Demo

f=(s,o,c=s.match(/[A-Z]/))=>c?[...2**29+'4'].some(i=>o&1<<i?0:f(r=s.split(c).join(i),o|1<<i))&&r:eval(s)

console.log(f('I + LOVE + YOU == DORA'))

Formatted and commented

f = (                               // f = recursive function taking:
  s,                                //   s = input string
  o,                                //   o = bitmask of used digits
  c = s.match(/[A-Z]/)              //   c = next alphabetical character in s
) =>                                //       (either null or a single-element array)
  c ?                               // if c is not null:
    [...2**29 + '4'].some(i =>      //   for each character i of '5368709124'
      o & 1 << i ?                  //     if this digit was already used:
        0                           //       ignore this iteration
      :                             //     else:
        f(                          //       do a recursive call to f() with:
          r = s.split(c).join(i),   //         all characters c replaced with i
          o | 1 << i                //         the updated bitmask
        )                           //       end of recursive call
    ) && r                          //   end of some(): if successful, return r
  :                                 // else:
    eval(s)                         //   evaluate this fully numerical expression


Sometimes I need a Lossless Screenshot Resizer Sometimes I need to write more documentation than just comments in code. And sometimes, those explanations need screenshots. Sometimes the conditions to get such a screenshot are so weird that I ask a developer to take a screenshot for me. Sometimes the screenshot does not fit my specifications and I have to resize it so that it looks nicely.

As you can see, the circumstances for a need for the magic "Lossless Screenshot Resizer" are very unlikely. Anyway, for me it seems I need it every day. But it doesn't exist yet.

I've seen you here on PCG solve awesome graphical puzzles before, so I guess this one is rather boring for you...

Specification

The program takes a screenshot of a single window as input
The screenshot does not make use of glass effects or similar (so you don't need to deal with any background stuff that shines through)
The input file format is PNG (or any other lossless format so that you don't have to deal with compression artifacts)
The output file format is the same as the input file format
The program creates a screenshot of different size as output. Minimum requirement is shrinking in size.
The user shall specify the expected output size. If you can give hints about the minimum size your program can produce from the given input, that's helpful.
The output screenshot must not have less information if interpreted by a human. You shall not remove text or image content, but you shall remove areas with background only. See examples below.
If it is not possible to get the expected size, the program should indicate that and not simply crash or remove information without further notice.
If the program indicates the areas which will be removed for verification reasons, that should increase its popularity.
The program may need some other user input, e.g. to identify the starting point for optimization.

Rules

This is a popularity contest. The answer with most votes on 2015-03-08 gets accepted.

Examples

Windows XP screenshot. Original size: 1003x685 pixels.

Example areas (red: vertical, yellow: horizontal) that can be removed without losing any information (text or images). Note that the red bar isn't contiguous. This example doesn't indicate all possible pixels that could potentially be removed.

Losslessly resized: 783x424 pixels.

Windows 10 screenshot. Original size: 999x593 pixels.

Example areas which can be removed.

Losslessly resized screenshot: 689x320 pixels.

Note that it is ok that the title text ("Downloads") and "This folder is empty" are not centered any more. Of course, it would be nicer if it is centered, and if your solution provides that, it should become more popular.

Python
the function delrows deletes all but one duplicate rows and returns the transposed image, applying it twice also deletes the columns and transposes it back. Additionally threshold controls how many pixels can differ for two lines to be still considered the same
from scipy import misc
from pylab import *

im7 = misc.imread('win7.png')
im8 = misc.imread('win8.png')

def delrows(im, threshold=0):
    d = diff(im, axis=0)
    mask = where(sum((d!=0), axis=(1,2))>threshold)
    return transpose(im[mask], (1,0,2))

imsave('crop7.png', delrows(delrows(im7)))
imsave('crop8.png', delrows(delrows(im8)))

Flipping the comparator in mask from > to <= will instead output the removed areas which are mostly blank space.

golfed (because why not)
Instead of comparing each pixel it only looks at the sum, as a side effect this also converts the screenshot to greyscale and has trouble with sum-preserving permutations, like the down-arrow in the address bar of the Win8 screenshot
from scipy import misc
from pylab import*
f=lambda M:M[where(diff(sum(M,1)))].T
imsave('out.png', f(f(misc.imread('in.png',1))),cmap='gray')


Collatz Conjecture (OEIS A006577) This is the Collatz Conjecture (OEIS A006577):

Start with an integer n > 1.
Repeat the following steps:

If n is even, divide it by 2.
If n is odd, multiply it by 3 and add 1.

It is proven that for all positive integers up to 5 * 260, or about 5764000000000000000, n will eventually become 1.

Your task is to find out how many iterations it takes (of halving or tripling-plus-one) to reach 1.

Relevant xkcd :)

Rules:

Shortest code wins.
If a number < 2 is input, or a non-integer, or a non-number, output does not matter.

Test cases

2  -> 1
16 -> 4
5  -> 5
7  -> 16

GolfScript, 24 23 21 20 18 chars

~{(}{3*).2%6\?/}/,

Assumes input on stdin. Online test


Convert 1, 2, 3, 4, 5, 6, 7, 8, and 9 to "one", "two", "three", etc Winner: professorfish's bash answer! An entire 9 bytes! Wow!
You may continue to submit your answer, however you can no longer win. Original post kept for posterity:

Your goal is to convert a whole number between 1-9 into the word it represents.

You will not need to worry about decimals
The user will input a number. Assume that they will never enter anything 10 or higher
The user must type the number at some point, however the method the program reads it does not matter. It can be with stdin, reading a text file, etc, however the user must press the 9 button on their keyboard (for example) at some point
It is not case sensitive (ie, "one", "One", "oNe", "OnE", etc are all acceptable)
HTTP/etc requests are allowed, however any code executed by the server the request is made to counts towards the byte count of your final code (e.g. if I had a C++ program make a HTTP request, the PHP code used in the HTTP request counts)
Anything that can compile and run is acceptable

This contest has ended on June 27th, 2014 (7 days from posting).
This is a code-golf, so the shortest code wins

Python 2, 64
print' ottffssennwhoiieiieoruvxvgn  ere ehe  e   nt'[input()::9]

This is what the string looks like with some extra whitespace (try reading vertically):
o t t f f s s e n
n w h o i i e i i
e o r u v x v g n
    e r e   e h e
    e       n t

As explained in the comments below, [input()::9] starts at the given index and selects every ninth subsequent character.


ASCII topology pt 1: Can I count on you? I have a serious problem. I have some text files where I keep my very important numbers -- all of the important ones! And twos, and threes..

These numbers were so important that I couldn't entrust them to those newfangled decimal or binary number systems. I kept each number encoded in unary, as so:

            +--+
            |  |
+---+  +----+  |
|   |  |       |
+---+  +-------+
   ~/two.txt

Simple and reliable: two ASCII loops for the number 2. Unfortunately, these things tend to get tangled up over time and now I have a hard time figuring out how many loops are in each file. Here are some examples that I worked out by hand:

One:

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

Three:

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

Four:

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

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

Five:

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

Can you help me count my loops?

Here are the rules:

Since I store everything in ASCII-encoded unary, space efficiency is very important to me. Therefore, this is code golf. The smallest program in bytes wins.
Loops are drawn with the characters +, -, |. Every corner in the loop is drawn unambiguously: exactly one of the characters above and below the +
will be |, and exactly one to the right or left will be -.  Two + marks
are never adjacent.
Strands may pass over and under each other. When strands cross, you'll be able to see the "under" strand immediately on both sides of the "over" strand.
Your program should take a string representation of the loop (either from stdin or as a function parameter) and produce a number (either to stdout or as a return value).
Line lengths may not be uniform in the loop drawing and there may be trailing spaces on each line.
You may assume that there is at least one loop in the input.

I'm counting on you!

SnakeEx - 98 bytes with Javascript, 44 without

This looked like a good problem to try my language from the Fortnightly Challenge on:

m:({e<>PE}\-[|\-]*<T>\+|[|\-]*<T>)+`\+
e:\+

The best place to try this out is my online interpreter.

SnakeEx matches patterns in text by using "snakes" that move around the text matching regexes. The code reads kind of like a regex, except:

The <T> instruction. That is a direction command that branches the snake left and right from its current direction.
{e<>PE} is like a subroutine call. It that spawns a snake with definition e moving forward (<>) and with parameters P (piggyback - the spawning snake follows the new snake) and E (exclusive - don't match anything that's already been matched). This exclusive check is the only thing that stops the snake from looping infinitely.
The prefix ` at the end indicates that what follows should be matched only if it has already been matched, which we can use to force the loop to close.

Because SnakeEx is like regex and doesn't technically output the results as desired by itself, I guess we need to wrap it in some Javascript calling the interpreter:

function e(s){return snakeEx.run('m:({e<>PE}\\-[|\\-]*<T>\\+|[|\\-]*<T>)+`\\+\ne:\\+',s,1).length}

Edit: fixed it up to work with blutorange's additional test cases


Non-repeating random numbers Find the shortest way to generate a random number between 0-9 without repeating the last generated number.  Here is an example written in javascript.

var n=t=0;
while(n==t){
  t=Math.floor(Math.random()*9);
}
n=t;

I don't know if it is possible, but it would be interesting if there is a solution using only one variable.

To clarify the solution can be in any language. Based on the comments I am going to disallow using arrays since apparently that makes it very easy and this is code-golf so the shortest answer wins.

Pyth, 7 bytes

e=+ZhO9

Try it online: Demonstration

Explanation

          implicit: Z = 0
     O9   Generate a random int from [0, 1, ..., 8]
    h     add 1
 =+Z      add this to Z and update Z
e         print Z modulo 10


Who is the rightful ruler? Who will rule the realm?

You are given a family tree which contains: name, sex, date of birth, date of death and a list of heirs, for each family member. You may use any convenient (nested) list format to represent the tree. The following examples will use JSON. Determine who will rule the realm and in which order.
The succession rules are the following:

When a king dies the realm goes to its oldest legit male child.
If there is none it passes to the oldest legit female child.
In case the king had no heirs the realm goes to the oldest legit king's brother
If there are no male brothers the realm will go to the oldest legit king's sister
If all legit relatives are dead the realm goes to the closest bastard, applying the above rules
If no legit nor bastard relatives are alive print LINE EXTINCT

We define a legit son as one who has the same "house" name as its father.

Examples:

Input
{}

Output
LINE EXTINCT

Input

{
    "name" : "Maegor",
    "house" : "Targaryen",
    "birth" : 12,
    "death" : 48,
    "sex" : "male",
    "heirs" : []
}

Output 12-48: Maegor, LINE EXTINCT

Input

{
    "name" : "Jaehaerys",
    "house" : "Targaryen",
    "birth" : 34,
    "death" : 103,
    "sex" : "male",
    "heirs" : [
        {
        "name" : "Viserys",
        "house" : "Targaryen",
        "birth" : 77,
        "death" : 129,
        "sex" : "male",
        "heirs" : []
        }
    ]
}

Output 34-103: Jaehaerys, 103-129: Viserys, LINE EXTINCT

Input

{
        "name" : "Eddard",
        "house" : "Stark",
        "birth" : 263,
        "death" : 299,
        "sex" : "male",
        "heirs" : [
            {
            "name" : "Robb",
            "house" : "Stark",
            "birth" : 283,
            "death" : 300,
            "sex" : "male",
            "heirs" : []
            },
            {
             "name" : "Jon",
             "house" : "Snow",
             "birth" : 284,
             "death" : 384,
             "sex" : "male",
             "heirs" : []
            },
            {
             "name" : "Sansa",
             "house" : "Stark",
             "birth" : 286,
             "death" : 320,
             "sex" : "female",
             "heirs" : []
            },
            {
             "name" : "Arya",
             "house" : "Stark",
             "birth" : 289,
             "death" : 350,
             "sex" : "female",
             "heirs" : []
            },

            {
             "name" : "Brann",
             "house" : "Stark",
             "birth" : 290,
             "death" : 315,
             "sex" : "male",
             "heirs" : []
            },
            {
             "name" : "Rickon",
             "house" : "Stark",
             "birth" : 295,
             "death" : 319,
             "sex" : "male",
             "heirs" : []
            }

        ]
    }

Output: 263-299: Eddard, 299-300: Robb, 300-315: Brann, 315-319: Rickon, 319-320: Sansa, 320-350: Arya, 350-384: Jon, LINE EXTINCT

Note that the output can be formatted in any way you wish, its only requirements is that it contains the time of reign and the name of the reigning king during those years.
I've used kings from the ASOIAF as demonstrative example, however the code needs to be valid for all input.

You may assume that no twins will be born.

This is a code golf challenge, so the shortest code in bytes wins

Good luck!!!

PHP, 664 bytes

I'm not sure if 664 bytes fit for code golfing, but here it is:

$k=json_decode($argv[1]);$s=[];$f='array_shift';$r='heirs';$e='death';$y='year';function s
($k,&$e){uasort($e,function($a,$b)use($k){$c=$a->{$h='house'};$d=$b->$h;$e=$k->$h;if($c==$e
&&$d!=$e)return-1;elseif($c!=$e&&$d==$e)return 1;elseif($a->sex<$b->sex)return 1;elseif($a
->sex>$b->sex)return -1;else return$a->birth-$b->birth;});}function d(&$e,$y){foreach($e
as$i=>$h)if($h->death<=$y)unset($e[$i]);};($x=(array)$k)&&$k->$y=$k->birth;$l=[];while($x)
{$l[]=$k;$z=$k->$e;s($k,$k->$r);d($k->$r,$k->$e);if($k->$r){$s=$k->$r;$k=$f($s);}else{s($k
,$s);d($s,$k->$e);$k=$f($s);}if(!$k)break;$k->$y=$z;}foreach($l as$k)
echo"{$k->$y}-{$k->$e}: $k->name, ";echo"LINE EXTINCT";

It receives the JSON string input as the first command line argument.

The algorithm follows the steps described in the challenge (starts from the king, then sorts the heirs and then the siblings to find the next king).

Demo


Build a readability index The Flesch-Kincaid readability algorithm depends on the measures of word count and syllable count, neither of which is entirely objective, or easily automatable using a computer. For example, does "code-golf", with the hyphen, count as one word or two? Is the word "million" two or three syllables? In this task, you will need to approximate, as counting exactly will take too much time, space, and most importantly, code.

Your task is to build the smallest possible program (i.e. a function) in any language that will take an English reading passage (assumed to be in complete sentences), and calculate the Flesch Reading Ease index to a tolerance of eight points (to account for variations in syllable counting and word counting). It is calculated as follows:

FRE = 206.835 - 1.015 * (words per sentence) - 84.6 * (syllables per word)

Your program must be aligned to the reference passages below, whose indices were calculated using manual counting:

I would not, could not, in the rain.
Not in the dark, not on a train.
Not in a car, not in a tree.
I do not like them, Sam, you see.
Not in a house, not in a box.
Not with a mouse, not with a fox.
I will not eat them here or there.
I do not like them anywhere!

Index: 111.38 (64 syllables in 62 words in 8 sentences)

It was a bright cold day in April, and the clocks were striking thirteen.
Winston Smith, his chin nuzzled into his breast in an effort to escape
the vile wind, slipped quickly through the glass doors of Victory Mansions,
though not quickly enough to prevent a swirl of gritty dust from entering
along with him.

Index: 65.09 (74 syllables in 55 words in 2 sentences)

When in the Course of human events, it becomes necessary for one people to
dissolve the political bands which have connected them with another, and to
assume among the powers of the earth, the separate and equal station to
which the Laws of Nature and of Nature's God entitle them, a decent respect
to the opinions of mankind requires that they should declare the causes
which impel them to the separation.

Index: 3.70 (110 syllables in 71 words in 1 sentence)

If you have any other passages for which you have manually counted the syllables and words and calculated the index, you may show them as verification.

Perl 120 bytes

#!perl -pa0
s@\w+|([.!?])@$s+=$#-,lc($&)=~s![aeiou]+\B|([aeiouy]$)!$y+=1-$#-/3!ger@ge}
{$_=206.835-1.015*@F/$s-84.6*$y/@F

Sample I/O:

$ perl flesch-kincaid.pl < input1.dat
110.730040322581

$ perl flesch-kincaid.pl < input2.dat
65.6097727272728

$ perl flesch-kincaid.pl < input2.dat
1.71366197183096

Counting of syllables is done by assuming that each vowel cluster is a single syllable, except for lone vowels at the end of a word, which are only counted two thirds of the time; a heuristic that seems to be fairly accurate.


Creating a function over multiple lines I'm attempting to create a function over multiple lines.
Parameters of the challenge:

Function returns 'barbarian'
Only 2 characters per line
40 lines maximum.
I keep trying to use a fat arrow to declare my function, but fat arrows don't seem to work if you don't have them connected.

Source of Challenge: https://www.codewars.com/kata/multi-line-task-plus-plus-hello-world
My current work:
f=
(
)=>

'\
b\
a\
r\
b\
a\
r\
i\
a\
n\
s\
'

This works, but the ')=>' is 3 characters long. I really just want to know how it is possible to even stretch out the creation of a function. I can't find any info on it anywhere as it's obviously not very practical.

35 Lines

f=
0[
c=
'\
c\
o\
n\
s\
t\
r\
u\
c\
t\
o\
r'
][
c]
`
r\
e\
t\
u\
r\
n\
'\
b\
a\
r\
b\
a\
r\
i\
a\
n'
`

Try it online!

Uses the fact that 0 is a number, the constructor of 0 is Number, and the constructor of Number is Function.

32 Lines

0[
c=
'\
c\
o\
n\
s\
t\
r\
u\
c\
t\
o\
r'
][
c]
`
f=
_\
=>
'\
b\
a\
r\
b\
a\
r\
i\
a\
n'
`(
)

Try it online!

This essentially runs

Function(`
f=
_=>
'barbarian'`)()

which uses the IIFE structure. Added bonus is that we can line-break some parts in the function body to reduce the line count.

24 Lines

f=
''
[
'\
t\
r\
i\
m'
][
'\
b\
i\
n\
d'
]`
b\
a\
r\
b\
a\
r\
i\
a\
n`

Try it online!

Inline version:

f=''['trim']['bind']`
barbarian`

Since all we want is to return a string, we can get away with a string method bound to a string. By using trim, we can also safely leave a beginning newline.


Am I an Automorphic Number? An Automorphic number is a number which is a suffix of its square in base 10.  This is sequence A003226 in the OEIS.

Your Task:

Write a program or function to determine whether an input is an Automorphic number.

Input:

An integer between 0 and 10^12 (inclusive), that may or may not be an Automorphic number.

Output:

A truthy/falsy value indicating whether or not the input is an Automorphic number.

Examples:

0           -> truthy
1           -> truthy
2           -> falsy
9376        -> truthy
8212890625  -> truthy

Scoring:

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

Python 2, 24 bytes

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

Try it online!

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

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


BrainF***-optimize a series of numbers An often-used trick in BF-golfing is something I call "multiply then add."  Let's say that you want to initialize the memory to contain a series of numbers, like 87 75 68 96.  The simplest way to do this is to simply write out a long series of 326 + signs.  A better method, however is below.

++++++++++[>+++++++++>+++++++>+++++++>++++++++++<<<<-]>--->+++++>-->----

(I write this by hand, I hope it works correctly)

The basic idea is that you create a series of numbers (9,7,7,10), multiply them by a constant (10), and then add another series of numbers (-3,5,-2,-4).  My invented form of notation writes this as (10;9,7,7,10;-3,5,-2,-4) which directly corresponds to the BF code.

There is a lot of importance placed in how the numbers are divided.  If I were to pick a larger constant, then the first series of numbers would be much smaller, yet there will tend to be larger remainders after the multiplication.  If I were to pick a smaller constant, then the first series would be larger, but the second series smaller.

Your goal is to write the shortest program to find the best possible way to write a series of numbers in BF using the multiply-then-add strategy.

Your program will recieve a series of non-negative integers.  It should find the best way to generate these numbers.

For example, lets say that it receives the series (3,16,8,4), as an easy example.  The best way to represent this is by the set of numbers (4;1,4,2,1;-1,0,0,0), which is what your program is expected to output (the exact formatting isn't as important).  This corresponds to the following program:

++++[>+>++++>++>+<<<<-]>->>>


Lua: Render a chess board in smallest code I'm creating a simple challenge here as a first test of the community's reactions. Please let me know if this challenge is the kind of thing you guys like or what I can improve... :)

The task is this: Render a chess board in Lua in smallest code possible.

Here is an example solution: http://tinybrain.de/145

As you can see, there is definitely room for getting smaller than 657 bytes (# of bytes are printed on the page). All the information you need for coding should be on the page or, hopefully, on tinybrain.de. Mailed questions totally welcome too. Lua API overview: http://tinybrain.de:8080/tb/debug.php?cmd=144

I am not demanding your chess board to have the exact same colors or even the same size. It should look like a chess board, that's all.

You need to register on TinyBrain.de to submit and test code. (Sorry, hope that is OK... It's free and I'm not a data peddler, so no harm there... :)

Edit: For testing your code locally (without any registration or Internet connection), you can download the TinyBrain runtime (magic.jar). Here is the link: http://tinybrain.de:8080/magic.jar

For a fancy ASCII art solution:

print("/"..("-"):rep(32).."\\")for y=0,15 do print("|"..("....    "):rep(5):sub(1+(y-y%2)*2%8):sub(1,32).."|")end print("\\"..("-"):rep(32).."/")

At 145 characters.

For a small ASCII art solution:

for i=1,8 do print(("# "):rep(9):sub(i,i+7))end

At 47 characters.


Create the slowest growing function you can in under 100 bytes Your job is to create the slowest growing function you can in no more than 100 bytes.

Your program will take as input a nonnegative integer, and output a nonnegative integer. Let's call your program P.

It must meet the these two criterion:

Its source code must be less than or equal to 100 bytes.
For every K, there is an N, such that for every n >= N, P(n) > K. In other words, lim(n->∞)P(n)=∞. (This is what it means for it to be "growing".)

Your "score" is the growth rate of your program's underlying function.

More specifically, program P is grows slower than Q if there is a N such that for all n>=N, P(n) <= Q(n), and there is at least one n>=N such that P(n) < Q(n). If neither program is better than the other, they are tied. (Essentially, which program is slower is based on the value of lim(n->∞)P(n)-Q(n).)

The slowest growing function is defined as the one that grows slower than any other function, according to the definition in the previous paragraph.

This is growth-rate-golf, so the slowest growing program wins!

Notes:

To assist in scoring, try to put what function your program calculates in the answer.
Also put some (theoretical) input and outputs, to help give people an idea of how slow you can go.

Brachylog, 100 bytes

llllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll

Try it online!

This is probably nowhere near the slowness of some other fancy answers, but I couldn't believe noone had tried this simple and beautiful approach.

Simply, we compute the length of the input number, then the length of this result, then the length of this other result... 100 times in total.

This grows as fast as log(log(log...log(x), with 100 base-10 logs.

If you input your number as a string, this will run extremely fast on any input you could try, but don't expect to ever see a result higher than 1 :D


Can the number be split into powers of 2? Yesterday while playing with my kid I noticed the number in his toy train:

So we have $$4281$$ that can be split into $$4-2-8-1$$ or $$2^2-2^1-2^3-2^0$$

So simple challenge: given a non-negative number as input, return consistent truthy and falsey values that represent whether or not the string representation of the number (in base 10 and without leading zeroes) can be somehow split into numbers that are powers of 2.

Examples:

4281      truthy (4-2-8-1)
164       truthy (16-4 or 1-64)
8192      truthy (the number itself is a power of 2)
81024     truthy (8-1024 or 8-1-02-4)
101       truthy (1-01)
0         falsey (0 cannot be represented as 2^x for any x)
1         truthy
3         falsey
234789    falsey
256323    falsey (we have 256 and 32 but then 3)
8132      truthy (8-1-32)

Tests for very large numbers (not really necessary to be handled by your code):
81024256641116  truthy (8-1024-256-64-1-1-16)
64512819237913  falsey

This is code-golf, so may the shortest code for each language win!

05AB1E, 9 8 bytes
Ýos.œåPZ

-1 byte thanks to @Emigna by using Z (max) for the list of 0s and 1s to mimic an any command for 1 (truthy).
Try it online or verify all test cases. (NOTE: The т in the header is 100 to only get the first 100 power of 2 numbers, instead of the first input amount of power of 2 numbers. It works with the input amount of power of 2 as well, but is pretty inefficient and might timeout on TIO if the input is large enough.)
Explanation:

Ý            # Create a list in the range [0,n], where n is the (implicit) input
             # (or 100 in the TIO)
             #  i.e. 81024 → [0,1,2,3,...,81024]
 o           # Raise 2 to the `i`'th power for each `i` in the list
             #  → [1,2,4,8,...,451..216 (nr with 24391 digits)]
  s          # Swap to take the input
   .œ        # Create each possible partition of this input
             #  i.e. 81024 → [["8","1","0","2","4"],["8","1","0","24"],...,["8102","4"],["81024"]]
     å       # Check for each if it's in the list of powers of 2
             #  → [[1,1,0,1,1],[1,1,0,0],...,[0,1],[0]]
      P      # Check for each inner list whether all are truthy
             #  → [0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0]
       Z     # Take the maximum (and output implicitly)
             #  → 1 (truthy)


APL (Dyalog Extended), 9 8 bytesSBCS

(⍳12)√○1

Try it online! (⎕PP←34 is Print Precision: 34 digits; ⎕FR←1287 is Float Representation: 128-bit decimal)

○1 \$π×1\$

(…)√ take the following roots of that:

 ⍳12 ɩndices 1 through 12


Advent Challenge 2: The Present Vault Raid! << Prev Next >>

Challenge

Now that Santa has finally figured out how to get into his present vault, he realises that somehow the elves got in there before him and stole some of his presents! They haven't figured out how to leave the vault yet though, so Santa has to try and catch them all. Santa and the elves both have infinite energy to run around but unfortunately the elves have a higher infinity of energy, so if they end up running in loops everywhere, the elves have gotten free.

Given a graph of n nodes and e edges with a walk existing between any two nodes, and the positions of the elves and Santa, determine how many elves Santa can catch before he gets tired.

The chase is turn-based. Each cycle, the elves first all move simultaneously (they can move through each other and onto the same node as well), and then Santa will move. If Santa moves onto the same node as an elf, then he has caught that elf. Each elf may only move from one node to its neighbour in one step. The same goes for Santa in the beginning, but for every elf he has caught, Santa can take one extra step. So, if Santa has caught an elf, then he can move from a node to its neighbour's neighbour. This means he could move to a node and then back. However, since Santa is running too quickly during this time period, he will not catch any elves that passes in the intermediate steps (so if he is on A, A is connected to B, B is connected to C, there is an elf on B, and Santa moves from A -> B -> C, the elf has not yet been caught). However, Santa doesn't have to move that many steps at once; he moves up to 1 + (number of elves caught) each turn.

Note that all of the elves must move each turn, and if an elf moves onto Santa's node, they get caught.

All entities (elves, Santa) will be on distinct nodes in the beginning.

Specifications and Rules

Your program should theoretically work for input of any size. The input will be given as a graph, the positions of the elves, and the position of Santa. You may take the graph in any reasonable format (list of nodes + list of edges, list of edges, adjacency matrix, cycle notation, etc), and you may take the positions in any reasonable format that works with your graph input format (index in the list of nodes, etc). The output should be a single positive integer indicating the maximum number of elves that Santa can catch.

Test Cases

These are given as lists of edges and node numbers for positions.

Input -> Output
[(0, 1), (1, 2)], [0, 2], 1 -> 2 # Easy win for Santa, the elves get themselves caught :P
[(0, 1), (1, 2), (2, 3), (3, 0)], [0, 1], 2 -> 2 # The elf opposite of Santa cannot escape but the other one can always just run away each turn, until Santa catches the first elf. Then he can easily just catch the rest.
[(0, 1), (1, 2), (2, 3), (3, 0)], [1], 0 -> 0 # Santa will never catch up
[(0, 1), (1, 2), (2, 3), (3, 0), (1, 4), (4, 5), ..., (10, 11), (11, 3)], [2, 6], 0 -> 2 # The first elf moves to either 1 or 3 and then gets caught. Then, Santa can use his 2-step move to catch up to the second elf no matter what.

I think Santa can catch either no elves or all the elves, so this challenge might just be "can he catch an elf" hint hint

Rules

Standard Loopholes Apply
This is a code-golf challenge, so the shortest answer in bytes wins
No answers will be accepted

Happy Golfing!

Note: I drew inspiration for this challenge series from Advent Of Code. I have no affiliation with this site

You can see a list of all challenges in the series by looking at the 'Linked' section of the first challenge here.

Wolfram Language (Mathematica), 129 bytes

Block[{a=#},Clear@f;s_~f~e_:=If[s==e,1,s~f~e=0;s~f~e=Min[(hMax[#~f~h&/@a@s,Boole[h==s]])/@a@e]];Tr[Max[(e#3~f~e)/@#2]^#2]]&

Try it online!

Similar approach to my answer to this question.

The function takes 3 arguments as input: adjacency list represented as an association (tool to generate adjacency list from edge list), elves position and santa position.

Note that Clear[f] is necessary, because function submissions must be reusable.

The code below is ungolfed code with partial explanation. More explanation later.

reverseBoole = # != 0 &

(* Or@@{a, b} === reverseBoole[booleOr[Boole[{a, b}]]] *)
booleOr = Max

booleAnd = Min

(* Boole@f[s, e] = Santa can catch Elf ? *)

mainfunc = Block[{adjlist = #},
  Clear[f];
  f[s_, e_] := If[ s == e, f[s, e] = 1,
    f[s, e] = Boole[False];
    f[s, e] = booleAnd[
      (e1  booleOr[
        ( s1  f[s1, e1] ) /@ adjlist[s],
        Boole[e1 == s]
      ]) /@ adjlist[e]
    ]
  ];
  If [ 0 == booleOr[ ( e  f[#3, e] ) /@ #2 ] , 0, Length[#2] ]
]&


A game of locks and keys There are n boxes, numbered 1-n. Each box is locked, such that it can be opened by only one corresponding type of key (also numbered 1-n). These keys are randomly scattered in the boxes (one box may have any number of keys, one key may have any number of duplicates), and then all boxes are shut. A treasure (numbered 0) has also been locked in many of the boxes.

You have hired a locksmith to retrieve all the treasure. He charges for each box he cracks open. There is no charge for opening a box for which the key is already available.

Input is the contents of each box. You can decide the format of the input.

Output the minimum cost required to get the treasures.

Notes

Your algorithm may take a long time, but that is irrelevant.
Shortest code wins.
No need to bother about invalid input.

Sample data

Here line i represents the keys present in box i.

Input

2 0
3
4 0
5 6 0
6
0

Output

1

Input

2 0
3 0

4 0
6
5 0

Output

3

Input

2 4 0
3 0

1 0
6
5 0

Output

2

Input

1
3 4

2 6
5

Output

0

CJam, 59 52 50 49 45 43 42 bytes

qN/ee::~e!{_0+{0a&}#>W%_{1$|(z@-},,\;}%:e<

Thanks to @MartinBüttner for golfing off 3 bytes and paving the way for 4 more!

Try it online in the CJam interpreter.

How it works

qN/      e# Read all input and split it at linefeeds.
ee       e# Enumerate the lines.
         e# STACK: [[0 "i0 i1 ..."] [1 "j0 j1 ..."] ...]
::~      e# Apply ~ (bitwise NOT/evaluate) to each item of the pairs.
         e# STACK: [[-1 i0 i1 ...] [-2 j0 j1 ...] ...]
e!       e# Push all unique permutations of the resulting array.
{        e# For each permutation:
  _0+    e#   Push a copy and append 0 to it.
  {0a&}# e#   Find the first index of an element that contains 0.
  >      e#   Discard all previous elements of the array.
  W%     e#   Reverse the resulting array.
         e#   We now have a (partial) permutation that contains
         e#   all treasures and ends with a treasure.
  _      e#   Push a copy. The original (which contains lists, but no
              numbers) will serve as accumulator.
  {      e#   Filter; for each list in the array:
    1$|  e#     Push a copy of the accumulator and perform set union.
    (    e#     Shift out the first element (bitwise NOT of 0-based index).
    z    e#     Apply absolute value to push the 1-based index.
    @-   e#     Perform set difference with the former state of the
         e#     accumulator. This pushes an empty list iff the 1-based
         e#     index was already in the accumulator, i.e., iff we already
         e#     had a key.
  },     e#   Keep the element if we did not have the key.
  ,      e#   Count the kept elements.
  \;     e#   Discard the accumulator from the stack.
}%       e#
:e<      e# Get the minimum of all results.


Fizzbuzz in any base Challenge

Input:

An integer \$b\$ between 2 and 62 (inclusive).

Output:

Count from \$1\$ to the equivalent of \$5000_{10}\$ in base \$b\$, using any reasonable representation for the digits.

However:

If the number is divisible by \$\lfloor b÷2+1\rfloor\$ (rounded down, e.g base 7 would be 7/2=3.5, 3.5+1=4.5, rounded to 4), then output 'Fizz' instead of the number.
If the number is divisible by \$\lceil b÷3+3\rceil\$ (rounded up, e.g 11/3=3.666, 3.666+3=6.666, rounded to 7), then output 'Buzz'.
As you can probably guess, if your number is divisible by both, output 'Fizzbuzz'.

Examples

Using [0-9], [A-Z] and [a-z] as the digits

(I've only included the first 10 values to keep the examples short - normally there'd by 4990 more items in each sequence)

Input: 10 (so 'Fizz' = 6 and 'Buzz' = 7)

Output: 1, 2, 3, 4, 5, Fizz, Buzz, 8, 9, 10

Input: 2 (so 'Fizz' = 2 and 'Buzz' = 4)

Output: 1, Fizz, 11, Fizzbuzz, 101, Fizz, 111, Fizzbuzz, 1001, Fizz

(I've included the first 50 values of the following to better show how they work)

Input: 55 (so 'Fizz' = \$28_{10}\$ = \$s_{55}\$ and 'Buzz' = \$22_{10}\$ = \$m_{55}\$)

Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, a, b, c, d, e, f, g, h, i, j, k, l, Buzz, n, o, p, q, r, Fizz, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N

Rules

Standard loopholes are forbidden
This is Code Golf, so shortest answer in bytes wins
Input and output can be through console, or function arguments/returns
Leading/trailing white space is fine, as are empty lines
Spaces between 'Fizz' and 'Buzz' are disallowed
Any capitalization variant of 'Fizz'/'Buzz'/'Fizzbuzz' is fine.
Outputs should be separated by newlines.
If you return a array of base 10 'digits' instead of representing them with characters, then they have to be in the correct order!

JavaScript (ES6),  117  116 bytes
Outputs comma-delimited digits, each digit being expressed as a decimal quantity (e.g. \$19_{20}\$ is \$19\$ and \$21_{20}\$ is \$1,1\$).
b=>(g=n=>n>1?g(n-1)+`
`+((s=n%(b+2>>1)?'':'Fizz',n%(b/3+3.9|0)?s:s+'Buzz')||(g=n=>n?[...g(n/b|0),n%b]:s)(n)):1)(5e3)

Try it online!
(limited to 100 so that TIO's output does not blow up)


Random pair of primes Given a positive input \$n\$, output a random pair of primes whose difference is \$n\$. It's fine if there's another prime between them.
Every pair should possibly appear and the program should have zero possibility to fall into infinite loop.
It's promised that such pair exist, but not always infinite, so beware. You also shouldn't assume it's infinite for even \$n\$ until a proof exist.
Test cases:
2 -> [3,5], [11,13], [29,31], etc.
3 -> [2,5]
4 -> [3,7], [19,23], etc.
7 -> Undefined behavior

Shortest code win.

05AB1E, 13 bytes
Generates a random integer \$k\$ until both \$k\$ and \$k+n\$ are prime.
[Î‚[>₄Ω#}DpP#

Try it online! Runs the program 1000 times and shows the unique results.
Commented:
[              # loop:
 Î‚            # push [0, input]
   [    }      # loop:
    >          #   increment both integers
     ₄Ω        #   draw a random digit of 1000
       #       #   if this is 1, stop the loop
         D     # duplicate the current pair
          p    # for both integers: are they prime?
           P   # take the product
            #  # if both are prime, end the main loop

Old answer that always just generates one random integer, 22 bytes:
∞+∞ø.ΔpP}D[₄Ω#>}DpP_i\

Try it online! Runs the program 100 times to demonstrate different outputs.
∞+∞ø.ΔpP} finds the first valid pair.
[₄Ω#>} is a loops which increments the pair and has a \$50\%\$ probability to stop at every iteration.
DpP_i\ removes the new pair if any of the numbers is not prime.


Is there a shorter way to assign one of two variables in Python? This is a tips question for golfing in python.

In multiple golfs I've done in Python, a fixed value is assigned to one of two variables chosen by a Boolean. The chosen variable is overwritten by the given value, and the other is unchanged.

17 chars:

if b:y=z
else:x=z

Assigning a conditional value is easy, but assigning to a conditional variable seems clunky. I'm wondering if there's a shorter way I'm missing.

This would be easy if x,y were instead a list L, but assume the context requires referring to the variables enough that writing L[0] and L[1] is prohibitive. Converting takes too long:

20 chars:

L=[x,y];L[b]=z;x,y=L

The fastest way I know is with a Python 2 exec, which is bizarre:

16 chars, Python 2:

exec"xy"[b]+"=z"

Tuple-choosing seems to be longer:

18, 19, 18, 18 chars:

x,y=b*(x,z)or(z,y)
x,y=[z,x,y,z][b::2]
y,x=[y,z,x][b:b+2]
y,x,*_=[y,z,x][b:]   # Python 3

Is there some shorter method or character-saving optimization? You can assume b is 0 or 1, not just Falsey or Truthy, and also make assumptions about the data types and values if it helps.

12 chars/assignment + 9 chars of overhead

V=vars()     # do once at the start of the program
V["xy"[b]]=z

Note that this only works at global scope, it does not work inside a function.


Golfing: How many unit-length squares in a list of 2d coordinates? Given a list of 2d (x, y) coordinates, determine how many unit squares (edge length 1 unit) can be formed using the coordinates.

Input will be an array of 0 or more pairs of coordinates: e.g. in JavaScript: numofsq([[0,0], [1,0], [1,1], [0,1]])
No duplicate coordinates in input
Input order will be random (random 2d coordinates).
Coordinate form: [x-coordinate, y-coordinate] (duh)
Order of coordinates: [0,0], [1,0], [1,1], [0,1] and [0,0], [0,1], [1,1], [1,0] denote the same unit square (to be counted just once)
Coordinates can be negative or positive integers (duh)
Function will return just the number of unit squares possible, 0 or more.

Test cases:

Input Coordinates Pairs                                               Expected Output
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2]                              2
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1]                3
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0]         4
[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0], [9,9]  4

Spoiler Alert: Solution stuff here-onwards [JS]

Non-Golfed, quick and dirty, brute-force approach (included to provide some directions).

//cartesian distance function
function dist(a, b) {
    if (b === undefined) {
        b = [0, 0];
    }
    return Math.sqrt((b[0] - a[0]) * (b[0] - a[0]) + (b[1] - a[1]) * (b[1] - a[1]));
}

//accepts 4 coordinate pairs and checks if they form a unit square
//this could be optimized by matching x,y coordinates of the 4 coordinates
function isUnitSquare(a) {
    var r = a.slice(),
        d = [],
        c = [],
        i,
        j = 0,
        counter = 0;

    for (i = 1; i < 4; i++) {
        if (dist(a[0], a[i]) === 1) {
            d.push(a[i]);
            r[i] = undefined;
            counter++;
        }
    }
    r[0] = undefined;
    c = d.concat(r.filter(function(a) {return undefined !== a}));

    if (dist(c[0], c[1]) === 1) {j++};
    if (dist(c[1], c[2]) === 1) {j++};
    if (dist(c[2], c[0]) === 1) {j++};
    return counter === 2 && j === 2;
}

//a powerset function (from rosetta code)
//however, we will need only "sets of 4 coordinates"
//and not all possible length combinations (sets of 3 coords or
//sets of 5 coords not required). Also, order doesn't matter.
function powerset(ary) {
    var ps = [[]];
    for (var i=0; i < ary.length; i++) {
        for (var j = 0, len = ps.length; j < len; j++) {
            ps.push(ps[j].concat(ary[i]));
        }
    }
    return ps;
}

//so to capture only sets of 4 coordinates, we do
var res = powerset([[0,0], [0,1], [1,1], [1,0], [0,2], [1,2], [2,2], [2,1], [2,0]])
          .filter(function (a) {return a.length === 8;});

//and a little bit of hoopla to have a nice set of sets of 4 coordinates.
//(Dizzy yet? Wait for the generalized, 3D, cube of any edge length version ;))
var squareQuads = res.map(function(ary) {
    return ary.join().match(/\d\,\d/g)
       .map(function(e) {
           return [+e.split(',')[0], +e.split(',')[1]];
        });
});

//Finally, the last bit
var howManyUnitSquares = 0;
squareQuads.map(function(quad) {
    if (isUnitSquare(quad)) {
        howManyUnitSquares++;
    }
});

console.log(howManyUnitSquares);

//Cleaning up and putting those in-line stuff into a function
function howManySquares(r) { //r = [[x,y], [x,y], [x,y], [x,y], ......];
    var res = powerset(r)
          .filter(function (a) {return a.length === 8;});
    var squareQuads = res.map(function(ary) {
        return ary.join().match(/\d\,\d/g)
               .map(function(e) {
                   return [+e.split(',')[0], +e.split(',')[1]];
                });
    });

    var answer = 0;
    squareQuads.map(function(quad) {
        if (isUnitSquare(quad)) {
            answer++;
        }
    });

    return answer;
}

APL(Dyalog), 30

+/{(2-/⍵)≡2-/,⍳2 2}¨,∘.,⍨⍣2⊂¨⎕

Well, in most cases, readability and char count is proportional.

Sample Output

⎕:
      (0 0)(0 1)(1 0)(1 1)(0 2)(1 2)(2 2)(2 1)(2 0)
4

Explaination

So, 4 points forms a unit square if and only if their relative positions are (1,1),(1,2),(2,1),(2,2)
{(2-/⍵)≡2-/,⍳2 2} is a function that return 1 or 0 (true/false) given a set of 4 points as input based on whether they are in relative positions and sorted in the order (1,1),(1,2),(2,1),(2,2):
⍳2 2 Generate a 2×2 matrix of the points (1,1),(1,2),(2,1),(2,2)
, Unravel that matrix to an array of points
2-/ Pair-wise subtraction reduce: (1,1) - (1,2) ; (1,2) - (2,1) ; (2,1) - (2,2), which gives the array [(0,-1),(-1,1),(0,-1)]
(2-/⍵) Pair-wise subtraction reduce on the input
≡ Check if the two arrays equal

The main program
⎕ Takes input and evals it. Things like (0 0)(0 1)(1 0)(1 1) evaluates to a nested array (Equivalent of [[0,0],[0,1],[1,0],[1,1]] in JS)
⊂¨ For every point (¨), enclose it in a scalar (⊂) ([[[0,0]],[[0,1]],[[1,0]],[[1,1]]])
∘.,⍨⍣2 For every pair of elements of the array, concatenate them to form a new array. ([ [[0,0],[0,0]],[[0,0],[0,1]]...) Repeat once. This gives all sets of 4 points that can be made using the given points. In some of these sets, the same point would be used multiple times, but these would not be unit squares so no need to waste keystrokes to remove them. (, concatenates 2 arrays, ∘. means "do that for every pair of elements", ⍨ means "use right operand as both left and right operands", and ⍣2 means "do this twice")
, As the previous operation would give a 4-dimensional array (note that nested arrays and multi-dimensional arrays are different things in APL), we have to unravel it to get an array of sets (of 4 points).
¨ For each of the sets,
{...} execute the aforementioned function. The result would be an array of 0s and 1s indicating whether the set is a unit square. Note that because the function also check ordering, duplicates are eliminated.
+/ Finally, sum resulting array to get the count.


How much is my dice matrix worth? Input

A non-empty binary matrix consisting of 3x3 sub-matrices put side by side.

Task

Your task is to identify valid dice patterns (as described below) among the 3x3 sub-matrices. Each valid pattern is worth the value of the corresponding dice. Invalid patterns are worth 0.

Output

The sum of the valid dice values.

Dice patterns

$$\begin{align}
&1:\pmatrix{\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0}
&&2:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,\color{gray}0}\\
&3:\pmatrix{1,\color{gray}0,\color{gray}0\\\color{gray}0,1,\color{gray}0\\\color{gray}0,\color{gray}0,1}\text{or}\pmatrix{\color{gray}0,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,\color{gray}0}
&&4:\pmatrix{1,\color{gray}0,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,\color{gray}0,1}\\
&5:\pmatrix{1,\color{gray}0,1\\\color{gray}0,1,\color{gray}0\\1,\color{gray}0,1}
&&6:\pmatrix{1,\color{gray}0,1\\1,\color{gray}0,1\\1,\color{gray}0,1}\text{or}\pmatrix{1,1,1\\\color{gray}0,\color{gray}0,\color{gray}0\\1,1,1}
\end{align}$$

Example

The expected output for the following matrix is 14 because it contains the dice 5, 6 and 3, followed by an invalid pattern (from left to right and from top to bottom).

$$\pmatrix{1,0,1,1,1,1\\
0,1,0,0,0,0\\
1,0,1,1,1,1\\
1,0,0,0,0,0\\
0,1,0,0,1,0\\
0,0,1,0,1,0}$$

Rules

Both the width and the height of the matrix are guaranteed to be multiples of 3.
You must ignore sub-matrices that are not properly aligned on the grid (see the 3rd test case). More formally and assuming 0-indexing: the coordinates of the top-left cell of each sub-matrix to be considered are of the form \$(3x, 3y)\$.
This is code-golf.

Test cases

// 0
[ [ 1,0,0 ],
  [ 0,0,1 ],
  [ 1,0,0 ] ]

// 2
[ [ 0,0,1 ],
  [ 0,0,0 ],
  [ 1,0,0 ] ]

// 0 (0 + 0)
[ [ 0,0,1,0,1,0 ],
  [ 0,0,0,1,0,0 ],
  [ 0,0,1,0,1,0 ] ]

// 9 (3 + 3 + 3)
[ [ 1,0,0,0,0,1,1,0,0 ],
  [ 0,1,0,0,1,0,0,1,0 ],
  [ 0,0,1,1,0,0,0,0,1 ] ]

// 6 (6 + 0)
[ [ 1,0,1 ],
  [ 1,0,1 ],
  [ 1,0,1 ],
  [ 1,0,1 ],
  [ 1,0,0 ],
  [ 1,0,1 ] ]

// 14 (5 + 6 + 3 + 0)
[ [ 1,0,1,1,1,1 ],
  [ 0,1,0,0,0,0 ],
  [ 1,0,1,1,1,1 ],
  [ 1,0,0,0,0,0 ],
  [ 0,1,0,0,1,0 ],
  [ 0,0,1,0,1,0 ] ]

// 16 (1 + 2 + 3 + 4 + 0 + 6)
[ [ 0,0,0,1,0,0,1,0,0 ],
  [ 0,1,0,0,0,0,0,1,0 ],
  [ 0,0,0,0,0,1,0,0,1 ],
  [ 1,0,1,1,1,1,1,0,1 ],
  [ 0,0,0,1,0,1,1,0,1 ],
  [ 1,0,1,1,1,1,1,0,1 ] ]

Python 3, 195 189 bytes

-6 bytes thanks to @Jo King

lambda m:sum({16:1,257:2,68:2,273:3,84:3,325:4,341:5,455:6,365:6}.get(int(''.join(str(e)for c in m[3*i:][:3]for e in c[3*j:][:3]),2),0)for i in range(len(m)//3)for j in range(len(m[0])//3))

Try it online! (189)
Try it online! (195)

Human readable version:

# 3x3 part matrix to dice, beginning at coordinates 3*i, 3*j
def single_matrix_to_dice(matrix, i, j):
    # Example: matrix = [[0, 0, 0], [0, 1, 0], [0, 0, 0]], i=0, j=0 (result is 1)

    matrix_string = ''.join(
        str(e) for column in matrix[3*i:3*i+3]
        for entry in column[3*j:3*j+3]
    ) # Slicing the matrix so that only the valid entries remain, here '000010000'

    # Interpreting the matrix string as binary number, here 16
    binary_number = int(matrix_string,2)

    # binary representations of all valid dice rolls
    dct = {16:1,257:2,68:2,273:3,84:3,325:4,341:5,455:6,365:6}

    return dct.get(binary_number, 0)

def f(matrix):
    return sum(
        single_matrix_to_dice(matrix, i, j) for i in range(len(m)//3)
        for j in range(len(m[0])//3))
    ) # len(m)/3 would generate a float, so len(m)//3 is used


A Chrestomathy of Obscurity You should complete four tasks in a language which:

must return no results* when searched for on this (codegolf.se) website, for example ToffeeScript;
must have a page listed at Esolang, Rosetta Code or Wikipedia;
be a distinct language, rather than a distinct version (e.g. python 2.1 would be valid iff python satisfied the first two criteria).

*The exception being this hit for ToffeeScript.

The four tasks you should complete are:

1) Write a tweetable (<140 characters) description/promotion of your chosen language.

2) Print "Hello World! This is written in <programming language name>."

3) Print all the odd numbers in a user specified range. (e.g. a stdin of 20 25 should return 21 23 25).

4) Write a program which you feel best demonstrates an interesting feature of your chosen language.

Scoring:

This is a popularity contest
Bonus of 10 points if listed in two of the above directories, 25 if in all three.
Score is the summation of votes received at midnight UTC on July 1 2015, plus the bonuses.

Clarifications:

Task 1) can be a tweetable program but plain text is also acceptable.
Many languages do not have an existing interpreter; solutions to these are fine, but will be taken in good faith.
The second criterion for language choice forbids pages whose creation dates after this post. If, for a given language, X, a solution to a problem exists on Rosetta Code but it does not have a distinct page of its own somewhere, it is still acceptable.

BlooP

Bonus: 10

There are pages for BlooP on Esolangs and Wikipedia. A PPCG search for BlooP returns no results. If you're feeling particularly loopy, you can try it out on repl.it.

Task 1: The Tweet

  BlooP: Nothing but bounded loops. ;) #programming #goodtimes

This uses standard Twitter styling including hashtags and emoticons. This would appeal to any Twitter user.*

Task 2: The Hello World

DEFINE PROCEDURE ''GREETING'' [N]:
BLOCK 0: BEGIN
  PRINT['Hello World! This is written in BlooP.']
BLOCK 0: END.

GREETING[0];

As you can see, this is a prime golfing language.*

Task 3: The Odd Numbers

DEFINE PROCEDURE ''IS-ODD'' [N]:
BLOCK 0: BEGIN
  OUTPUT <= 0;
  CELL(0) <= 2;
  LOOP AT MOST N+1 TIMES:
  BLOCK 1: BEGIN
    IF N+1 = CELL(0), THEN:
    BLOCK 2: BEGIN
      OUTPUT <= 1;
      ABORT LOOP 1;
    BLOCK 2: END;
    CELL(0) <= CELL(0) + 2
  BLOCK 1: END;
BLOCK 0: END.

DEFINE PROCEDURE ''ODDS-IN-RANGE'' [A,B]:
BLOCK 0: BEGIN
  CELL(0) = A;
  LOOP AT MOST B TIMES:
  BLOCK 1: BEGIN
    IF CELL(0) > B, THEN:
    ABORT LOOP 1;
    IF IS-ODD[CELL(0)] = 1, THEN:
    PRINT[CELL(0)];
    CELL(0) <= CELL(0) + 1;
  BLOCK 1: END;
BLOCK 0: END.

ODDS-IN-RANGE[20,25];

The only available operators in BlooP are assignment (<=), addition, multiplication, greater than, less than, and equals. Because of its painfully verbose syntax, it's actually pretty easy to tell what's going on even without a deep understanding of the language.

Task 4: The Interesting

Note: My snippet for this task is subject to change should I come up with something more interesting.

DEFINE PROCEDURE ''MINUS'' [M,N]:
BLOCK 0: BEGIN
  IF M < N, THEN:
  QUIT BLOCK 0;
  LOOP AT MOST M + 1 TIMES:
  BLOCK 1: BEGIN
    IF OUTPUT + N = M, THEN:
    ABORT LOOP 1;
    OUTPUT <= OUTPUT + 1;
  BLOCK 1: END;
BLOCK 0: END.

DEFINE PROCEDURE ''FIB''[N]:
BLOCK 0: BEGIN
  IF N < 1, THEN:
  QUIT BLOCK 0;
  OUTPUT <= 1;
  IF N < 3, THEN:
  QUIT BLOCK 0;
  OUTPUT <= FIB[MINUS[N,1]] + FIB[MINUS[N,2]];
BLOCK 0: END.

FIB[10];

Behold, the Fibonacci numbers.

*May not be true


Calculate the Kronecker Product Related, but very different.

In the examples below, \$A\$ and \$B\$ will be \$2\times2\$ matrices, and the matrices are one-indexed.
A Kronecker product has the following properties:
A⊗B =  A(1,1)*B   A(1,2)*B
        A(2,1)*B   A(2,2)*B

     =  A(1,1)*B(1,1)   A(1,1)*B(1,2)   A(1,2)*B(1,1)   A(1,2)*B(1,2)
        A(1,1)*B(2,1)   A(1,1)*B(2,2)   A(1,2)*B(2,1)   A(1,2)*B(2,2)
        A(2,1)*B(1,1)   A(2,1)*B(1,2)   A(2,2)*B(1,1)   A(2,2)*B(1,2)
        A(2,2)*B(2,1)   A(2,2)*B(1,2)   A(2,2)*B(2,1)   A(2,2)*B(2,2)

Challenge: Given two matrices, \$A\$ and \$B\$, return \$A\otimes B\$.

The size of the matrices will be at least \$1\times1\$. The maximum size will be whatever your computer / language can handle by default, but minimum \$5\times5\$ input.
All input values will be non-negative integers
Builtin functions that calculate Kronecker products or Tensor/Outer products are not allowed
In general: Standard rules regarding I/O format, program & functions, loopholes etc.

Test cases:
A =
     1     2
     3     4
B =
     5     6
     7     8
A⊗B =
     5     6    10    12
     7     8    14    16
    15    18    20    24
    21    24    28    32

B⊗A =
     5    10     6    12
    15    20    18    24
     7    14     8    16
    21    28    24    32
------------------------
A =
     1
     2
B =
     1     2

A⊗B =
     1     2
     2     4
------------------------
A =
    16     2     3    13
     5    11    10     8
     9     7     6    12
     4    14    15     1

B =
     1     1
     0     1

A⊗B  =
    16    16     2     2     3     3    13    13
     0    16     0     2     0     3     0    13
     5     5    11    11    10    10     8     8
     0     5     0    11     0    10     0     8
     9     9     7     7     6     6    12    12
     0     9     0     7     0     6     0    12
     4     4    14    14    15    15     1     1
     0     4     0    14     0    15     0     1

B⊗A =
    16     2     3    13    16     2     3    13
     5    11    10     8     5    11    10     8
     9     7     6    12     9     7     6    12
     4    14    15     1     4    14    15     1
     0     0     0     0    16     2     3    13
     0     0     0     0     5    11    10     8
     0     0     0     0     9     7     6    12
     0     0     0     0     4    14    15     1
------------------------

A = 2
B = 5
A⊗B = 10

CJam, 13 bytes

{ffff*::.+:~}

This is an unnamed block that expects two matrices on top of the stack and leaves their Kronecker product in their place.

Test suite.

Explanation

This is just the Kronecker product part from the previous answer, therefore I'm here just reproducing the relevant parts of the previous explanation:

Here is a quick overview of CJam's infix operators for list manipulation:

f expects a list and something else on the stack and maps the following binary operator over the list, passing in the other element as the second argument. E.g. [1 2 3] 2 f* and 2 [1 2 3] f* both give [2 4 6]. If both elements are lists, the first one is mapped over and the second one is used to curry the binary operator.
: has two uses: if the operator following it is unary, this is a simple map. E.g. [1 0 -1 4 -3] :z is [1 0 1 4 3], where z gets the modulus of a number. If the operator following it is binary, this will fold the operator instead. E.g. [1 2 3 4] :+ is 10.
. vectorises a binary operator. It expects two lists as arguments and applies the operator to corresponding pairs. E.g. [1 2 3] [5 7 11] .* gives [5 14 33].

ffff*  e# This is the important step for the Kronecker product (but
       e# not the whole story). It's an operator which takes two matrices
       e# and replaces each cell of the first matrix with the second matrix
       e# multiplied by that cell (so yeah, we'll end up with a 4D list of
       e# matrices nested inside a matrix).
       e# Now the ffff* is essentially a 4D version of the standard ff* idiom
       e# for outer products. For an explanation of ff*, see the answer to
       e# to the Kronecker sum challenge.
       e# The first ff maps over the cells of the first matrix, passing in the
       e# second matrix as an additional argument. The second ff then maps over
       e# the second matrix, passing in the cell from the outer map. We
       e# multiply them with *.
       e# Just to recap, we've essentially got the Kronecker product on the
       e# stack now, but it's still a 4D list not a 2D list.
       e# The four dimensions are:
       e#   1. Columns of the outer matrix.
       e#   2. Rows of the outer matrix.
       e#   3. Columns of the submatrices.
       e#   4. Rows of the submatrices.
       e# We need to unravel that into a plain 2D matrix.
::.+   e# This joins the rows of submatrices across columns of the outer matrix.
       e# It might be easiest to read this from the right:
       e#   +    Takes two rows and concatenates them.
       e#   .+   Takes two matrices and concatenates corresponding rows.
       e#   :.+  Takes a list of matrices and folds .+ over them, thereby
       e#        concatenating the corresponding rows of all matrices.
       e#   ::.+ Maps this fold operation over the rows of the outer matrix.
       e# We're almost done now, we just need to flatten the outer-most level
       e# in order to get rid of the distinction of rows of the outer matrix.
:~     e# We do this by mapping ~ over those rows, which simply unwraps them.


Elixir Array Syntactic Sugar In Elixir, (linked) lists are in the format [head | tail] where head can be anything and tail is a list of the rest of the list, and [] - the empty list - is the only exception to this.

Lists can also be written like [1, 2, 3] which is equivalent to [1 | [2 | [3 | []]]]

Your task is to convert a list as described. The input will always be a valid list (in Elixir) containing only numbers matching the regex \[(\d+(, ?\d+)*)?\]. You may take the input with (one space after each comma) or without spaces. The output may be with (one space before and after each |) or without spaces.

For inputs with leading zeroes you may output either without the zeroes or with.

Input must be taken as a string (if writing a function), as does output.

Examples

[] -> []
[5] -> [5 | []]
[1, 7] -> [1 | [7 | []]]
[4, 4, 4] -> [4 | [4 | [4 | []]]]
[10, 333] -> [10 | [333 | []]]

related, not a duplicate as this in part involves adding mode ] to the end. Additionally, the Haskell answer here is quite different to the one there.

Haskell, 50 bytes

f.read
f(a:b)='[':show(a+0)++'|':f b++"]"
f _="[]"

Try it online!

The +0 lets the Haskell type checker know that we are dealing with lists of numbers, so read will parse the input string for us.


Square-unspiral the string! Given a string, first square it as follows:

First, write the string.

abcde

Next, write the string rotated one left.

abcde
bcdea

Keep doing this until you have written len(string) lines.

abcde
bcdea
cdeab
deabc
eabcd

Now, read from the string like this:

----+
+--+|
|+>||
|+-+|
+---+

Which gives:

abcdeabcdcbaedcbcdeabaede

Print this string.

Test cases

abcdef -> abcdefabcdedcbafedcbcdefabcbafedefaf
cena! -> cena!cenanec!anena!cec!a!
ppcg -> ppcgppcppgcpcgpg
abc -> abcabacbc
ab -> abab
a -> a
 ->

Please comment if a test case is incorrect.

Remember, this is code-golf, so the code with the smallest number of bytes wins.

JavaScript (ES7), 83 80 78 77 bytes

s=>s.repeat(l=s.length).replace(/./g,_=>s[(c-=--i**.5-l&1||-1)%l],c=-1,i=l*l)

Bonus ES3-compliant program:

for(s=prompt(r=""),c=-1,l=s.length,i=l*l;i;)r+=s[(c-=l-Math.sqrt(i--)&1||-1)%l];alert(r)

Explanation

This takes advantage of the fact that the output for e.g. a length 5 string can be represented as:

abcdeabcd cbaedcb cdeab aed e
012345678 7654321 23456 543 4

where each digit represents an index in the string (starting at 0), modulo the length of the string. In other words, if n is the length of the string, we increment the index 2n - 1 times, then decrement it 2(n - 1) - 1 times, then increment it 2(n - 2) - 1 times, etc. This can be simplified to the following algorithm:

Start the index i at -1.
For each integer x in the range [n2..1]:

If floor(sqrt(x)) is of the same parity (even/odd) as n, increment i.
Otherwise, decrement i.
Add the character at index i mod n to the output.

This works because floor(sqrt(x)) switches parities after 2n - 1 iterations, then 2(n - 1) - 1 iterations, etc.