Underground geek rock band names We have a group of stealthy computer-savvy geeks who are also musicians with a very subversive element to their songs that the authorities in their totalitarian country just can't stand, and are itching to show up at one of the concerts, fire off rubber bullets and tear gas at the audience, and arrest the band members and as may other fans as their paddy vans can carry and "disappear" them.

However, the authorities are a bit slow to act, and will only show up to the second concert held under the same band name (case, accent and whitespace-length insensitive).  They are also not very tech-savvy, so can't reverse-engineer the decoder (see later).  Since they are working from memory, they'll forget a name after five years, so a repeat after that time won't attract their attention.

One of these tech-savvy band members comes up with an algorithm that - given the date of a concert - generates a (hopefully) unique cool-sounding and pronounceable band name using the latin alphabet (A-Z) plus Space.  They also create a decoder that they distribute to fans, which, given a band name and a date, returns some output indicating that this is indeed a code-generated name of our subversive band, or some other output indicating that the band name entered is that of some other band (or a sting set up by the authorities to catch fans they want to arrest).

The decoder does not output any valid names, as the authorities are just tech-savvy enough themselves to obtain a copy and use that to generate possible names if it can output them, but don't have time to check all the names of the hundreds of other bands that appear and disappear (sometimes with their assistance) from time to time against it.

Your Task:

Produce these two complementary pieces of code - the name generator and the name checker.

As this is a popularity contest, we're looking for cool-sounding, pronounceable band names for the English-speaking world, not random unpronounceable text.  Any programming language is OK, as the fans are all very tech-savvy like us.  Please provide a sample of the cool names your generator generates.

If it can be shown that an algorithm produces a duplicate for any two dates in a 5-calendar-year period, then that will be considered a disqualification. (Disqualification is a far better fate than what the authorities would do to them).

Pyth
Encoder:
Jf-\'T'jdm@JdjswlJ

Takes two arguments: a dictionary on one line, and the date, in DDMMYYYY form on the next.
Filters out words with apostrophes from the dictionary, then converts the current date into a number with base equal to the dictionary length, and then chooses words from the filtered dictionary with indexes of the digits, and prints them out, space separated.
Today's result:
$ pyth -c "Jf-\'T'jdm@JdjswlJ" <<< '/usr/share/dict/words
30102014'
Annam pals

Future results:
31102014
Antarctica economical

01112014
Abernathy carousels

02112014
Acadia unsnarled

03112014
Actaeon oversimplifying

04112014
Adela dugouts

0511204
Adolph Maude

To decode, run the date through the program and see if the output matches the name given. I'm not going to list any more band names, but from how the program works it should be clear there are no repeats.


Shuffle string of digits Challenge

You have been given a string of digits 0-9.1 Your task is to shuffle this string, but every index must have a different value than it did before the string was shuffled.

For example:

In : 287492
Out: 892247

If this is not possible, return false or something similar. (null, undefined, etc.)

In : 131
Out: false

There is no upper bound on the length of the string, but you can assume you have unlimited computation time.

Your function must pass the following tests:

shuffle('2')                   => false
shuffle('88')                  => false
shuffle('794588888')           => false
shuffle('344999')              => for example, '999434'
shuffle('172830560542976539')  => for example, '271038650425697395'

Shortest code wins, and good luck!

1 More specifically, the string would match /^[0-9]+$/.

K (ngn/k), 37 32 bytes

{$[|/x=r:x[,/|2 0N#<x]@<<x;0;r]}

Try it online!

{ } function with argument x

$[ ; ; ] if-then-else

<x "grade" - the sorting permutation for x

<<x "rankings" - the inverse of the sorting permutation

2 0N# split in two halves (or when length is odd - only approximately)

| swap the halves

,/ concatenate

x[ ] use as indices in x

..@<<x use <<x as indices in the previous result (a@b is alternative syntax for a[b])

r: assign to r - the potential result

x=r boolean list of which elements of x are equal to their counterparts in r

|/ or-reduction, i.e. "any?"


Avoid duplicate entries using a sign change This anecdote contains the following intriguing exchange:

  "Fine, Fred," Avi interrupted. "Then how would you change this to
  avoid duplicate entries?"

  "Oh, just change that one there to a negative one."

While this claim is not accurate in context, I do wonder if there's some plausible code for which that makes sense.

Your challenge is to write code (a program, a function, whatever) that fits this criteria:

Merges two input lists into one, keeping duplicates. [edit: You can optionally assume that they are integers, and/or that the lists themselves are unique. You can't assume the integers are positive (the one answer that does this is grandfathered in).]
A literal "1" appears somewhere in the code. If you change this to a literal "-1", the code does the same thing but removing duplicates.
The code does not simply branch off of the 1/-1. We're not looking for if (1 < 1) removeDuplicates() or [do_nothing, merge_with_dups, merge_without_dups][1].call(), for example.

Input and output can be in any reasonable format you choose. One example might be

[1,2],[2,3]->[1,2,2,3] before the sign change, and [1,2,3] after.

This is a popularity contest. It is not code golf, unless you want to show off. I'll accept the highest-voted answer in about two weeks.

JavaScript

Take a conventional algorithm and write it with a bug:

function merge(a, b) {
  var ai = 0, bi = 0, oi = 0;
  var o = [];
  while (ai < a.length && bi < b.length) {
    var v = a[ai] < b[bi] ? a[ai++] : b[bi++];
    if (v !== o[oi + 1]) {
      o[oi++] = v;
    }
  }
  while (ai < a.length) o[oi++] = a[ai++];
  while (bi < b.length) o[oi++] = b[bi++];
  return o;
}

This code contains exactly one literal 1. If it is changed to -1, then duplicates will be removed. It can be used on any comparable values.


Reducing Leibniz perl code in characters This Perl code is supposed to calculate the Leibniz formula. The original problem is here.

The input format is:

T
<T test cases, each on their own line>

Each test case is a number < 10^7. The output format should be the same, minus the first line.

For example, an input:

2
10
20

And for output:

0.760459904732351
0.77290595166696

My first solutions, at 62 and 61 characters respectively.

for(1..<>){$s=0;map{$s+=($_&1||-1)/(2*$_-1)}1..<>;print"$s\n"}

for(1..<>){$s=0;$s+=($_&1||-1)/(2*$_-1)for 1..<>;print"$s\n"}

Edit: The best solution so far is 53 characters, by @teebee:

<>;print${\map$a-=(-1)**$_/(2*$_-1),1..$_},$a=$/for<>

Perl 53 bytes

You can save two more strokes:

<>;print${\map$a-=(-1)**$_/(2*$_-1),1..$_},$a=$/for<>


Shortest simple regex matching a binary word Task

Define a simple regex as a non-empty regular expression consisting only of

characters 0 and 1,
grouping parentheses ( and ),
one-or-more repetition quantifier +.

Given a non-empty string of 0s and 1s, your program should find the shortest simple regex matching the full input string. (That is, when matching a simple regex, pretend it’s bookended by ^ and $.) If there are multiple shortest regexes, print any or all of them.)

code-golf, so the shortest submission (in bytes) wins.

Test cases

1 -> 1
00 -> 00 or 0+
010 -> 010
1110 -> 1+0
01010 -> 01010
0101010 -> 0(10)+ or (01)+0
011111 -> 01+
10110110 -> (1+0)+
01100110 -> (0110)+ or (01+0)+
010010010 -> (010)+
111100111 -> 1+001+ or 1+0+1+
00000101010 -> 0+(10)+ or (0+1)+0
1010110001 -> 1(0+1+)+ or (1+0+)+1

JavaScript (ES6), 488 341 bytes

s=>[s.replace(/(.)\1+/g,'$1+'),...[...Array(60)].map((_,i)=>`(${(i+4).toString(2).slice(1)})+`),...[...Array(1536)].map((_,i)=>`${i>>10?(i>>8&1)+(i&2?'+':''):''}(${i&1}${i&4?i>>4&1:i&16?'+':''}${i&8?''+(i>>7&1)+(i&64?i>>5&1:i&32?'+':''):''})+${i&512?(i>>8&1)+(i&2?'+':''):''}`)].filter(r=>s.match(`^${r}$`)).sort((a,b)=>a.length-b.length)[0]

Explanation: Since six regexes can express all possible binary words, and the longest two are nine characters long, it suffices to check those and all shorter regexes. One candidate is obviously the string with "run length encoding" (i.e. all digit runs replaced with appropriate +s), but also strings with one set of ()s need to be checked. I generate 1596 such regexes (this includes duplicates and useless regexes but they'll just be eliminated) and test all 1597 to see which is the shortest match. The generated regexes fall into two types: \(\d{2,5}\)\+ (60 regexes) and (\d\+?)?\(\d[\d+]?(\d[\d+]?)?\)(\d\+?)? (1536 regexes as I avoid generating regexes with both leading and trailing digit).


Calculate the Mean mean of two numbers disclaimer: the Mean mean is made up by me
Define the arithmetic mean of \$n\$ numbers as
$$M_1(x_1,...,x_n)=\frac{x_1+x_2+...+x_n}{n}$$
Define the geometric mean of \$n\$ numbers as
$$M_0(x_1,...,x_n)=\root{n}\of{x_1x_2...x_n}$$
Define the harmonic mean of \$n\$ numbers as
$$M_{-1}(x_1,...,x_n)=\frac{n}{\frac{1}{x_2} + \frac{1}{x_2} + ... + \frac{1}{x_n}}$$
Define the quadratic mean of \$n\$ numbers as
$$M_2(x_1,...,x_n)=\root\of{\frac{x_1^2+x_2^2+...+x_n^2}{n}}$$
The Mean mean (\$M_M\$) is defined as follows:
Define four sequences (\$a_k, b_k, c_k, d_k\$) as $$a_0=M_1(x_1,...,x_n),\\b_0=M_0(x_1,...,x_n),\\c_0=M_{-1}(x_1,...,x_n),\\d_0=M_2(x_1,...,x_n),\\
a_{k+1}=M_1(a_k,b_k,c_k,d_k),\\b_{k+1}=M_0(a_k,b_k,c_k,d_k),\\c_{k+1}=M_{-1}(a_k,b_k,c_k,d_k),\\d_{k+1}=M_2(a_k,b_k,c_k,d_k)$$
All four sequences converge to the same number, \$M_M(x_1,x_2,...,x_n)\$.
Example
The Mean mean of 1 and 2 is calculated as follows: start with $$a_0 = (1+2)/2 = 1.5, b_0 = \root\of{1 * 2} = \root\of2 \approx 1.4142,\\ c_0 = \frac2{\frac1{1}+\frac1{2}} = \frac4{3} \approx 1.3333, d_0 = \root\of{\frac{1^2+2^2}2} = \root\of{\frac5{2}} \approx 1.5811.$$
Then
$$a_1 = \frac{1.5+1.4142+1.3333+1.5811}4 \approx 1.4571,\\ b_1 = \root^4\of{1.5*1.4142*1.3333*1.5811} \approx 1.4542,\\ c_1 = \frac4{\frac1{1.5}+\frac1{1.4142}+\frac1{1.3333}+\frac1{1.5811}} \approx 1.4512,\\ d_1 = \root\of{\frac{1.5^2+1.4142^2+1.3333^2+1.5811^2}4} \approx 1.4601.$$
The further calculation of the sequences should be clear. It can be seen that they converge to the same number, approximately \$1.45568889\$.
Challenge
Given two positive real numbers, \$a\$ and \$b\$ (\$a<b\$), calculate their Mean mean \$M_M(a,b)\$.
Test cases
1 1 => 1
1 2 => 1.45568889
100 200 => 145.568889
2.71 3.14 => 2.92103713
0.57 1.78 => 1.0848205
1.61 2.41 => 1.98965438
0.01 100 => 6.7483058

Notes

Your program is valid if the difference between its output and the correct output is not greater than 1/100000 of the absolute value of the difference between input numbers.
The output should be a single number.

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

Wolfram Language (Mathematica), 52 bytes

#//.x_:>N@{M@x,E^M@Log@x,1/M[1/x],M[x^2]^.5}&
M=Mean

Try it online!

In my first approach I used these builtins
Mean GeometricMean  HarmonicMean and RootMeanSquare

Here are some substitutions for saving bytes

HarmonicMean -->  1/Mean[1/x]  by @Robin Ryder (3 bytes saved)
GeometricMean --> E^Mean@Log@x by @A. Rex (2 bytes saved)
RootMeanSquare --> Mean[x^2]^.5 by @A. Rex (4 bytes saved)

finally we can assign Mean to M (as proposed by @ovs) and save 5 more bytes


Determine the "Luck" of a string Given a string, return that string's "luck".

A string's luck, as I completely just made up for the purpose of this challenge, is an integer, determined as so:

The base luck for a string is 1.
For each consecutive letter it shares with the word "lucky" (case insensitive), multiply the luck by 2. For instance, if your string was "lumberjack" or "smack" you'd multiply by 4. (More specifically, 2^number of consecutive characters shared.)

The shared letters have to be in the same consecutive order it appears in "lucky" but can start anywhere in the word for the same value ("luc" has the same 8* multiplier as "cky").
If the word has multiple occurrences where it shares consecutive characters with lucky, use the longest consecutive string of the characters.

For ANY letter it shares with the word "omen" subtract 2 from the luck.

It can match a character any amount of times, in any order. For instance the string "nnnnnomemenn" loses 24 luck (12 matching letters)

Example:

luck("lucky")
>>32

2^5 (5 consecutive letters) = 32

luck("firetruck")
>>6

2^3 - 2 (3 consecutive letters from uck, e shared with omen)

luck("memes")
>>-7

1 - 8 (base amount, 4 shared with "omen")

This is code golf, so the answer with the fewest bytes wins.

You can input and output any way you'd like - write a function, use standard input, etc.

For functions, assume whatever data type would make sense for that language. (For example, in JavaScript, you'd be passed a String and return a Number)

Edit: You can assume any input is lowercase.

JavaScript (ES7), 123 112 107 bytes

s=>2**[5,4,3,2,1,0].find((i,_,a)=>a.some(j=>s.includes("luckyL".substr(j,i))))-2*~-s.split(/[omen]/).length

Edit: Saved 11 bytes thanks to @Titus by assuming that the letter L does not appear in the input. Saved 5 bytes thanks to @Oriol. ES6 version for 125 114 109 bytes:

f=
s=>(1<<[5,4,3,2,1,0].find((i,_,a)=>a.some(j=>s.includes("luckyL".substr(j,i)))))-2*~-s.split(/[omen]/).length
;
<input oninput=o.textContent=f(this.value)>


Convert singular to plural There are two forms of nouns, singular and plural. The conversion between these two is quite easy.

Normally, you end it with s. ex. car => cars.

If it ends with s,x,z,ch or sh, end it with es. ex. bus=>buses.

If it ends with y with a consonant just before it, change the y to ies. ex. penny => pennies.

If it ends with f or fe, change it to ves. ex. knife => knives.

If it ends with o with a consonant just before it, change it to oes. ex.potato => potatoes.

Task
You will be given a singular noun. You have to convert the given noun to plural and output it.

Rules

You will not be given irregular nouns, like mouse and moose.

You will not be given exceptions, such as safe (safes; violating #4), piano (pianos; violating #5) and o (oes, violating #5).

You will not be given words which have two or more possible plural forms, such as mosquito (mosquitos or mosquitoes) and roof (roofs or rooves).

You will not be given uncountable nouns.

y doesn't count as a vowel.

Examples
car => cars
bus => buses
potato => potatoes
knife => knives
penny => pennies
exception => exceptions
wolf => wolves
eye => eyes
decoy => decoys
radio => radios

Mathematica, 9 bytes
Pluralize

Yes, there is a built-in for this!
Sample output
Pluralize["car"]

cars

Pluralize /@ {"bus", "potato", "knife", "penny", "exception", "wolf", "eye"}

{"buses", "potatoes", "knives", "pennies", "exceptions", "wolves", "eyes"}


The Great British Cake Off I hear somebody was very selfish on their birthday, demanding cake from everyone and there were no plans to share! 🎂

It's bound to be somebody's birthday today, so why not bake them a cake. Use your favourite programming language to make a delicious cake, with a nice "Happy Birthday" message as the output. (Might I suggest Chef!)

Your cake should

Mimic a real world recipe (if you can link to it, brilliant!)

a list of newline separated ingredients suitable for making a cake
a newline separated list of steps for the method
how many people it serves

Stay as close to correct ingredient ratios as possible.
Output minimally "Happy Birthday" when served.

The best cakes will be:

Delicious  - since this is a popularity-contest, the community will decide what is delicious
Personalised - try baking a custom happy birthday message to somebody specific. (If you can't find a PPGC user, why not a celebrity?)
Balanced - Try to use a suitable number of ingredients for the amount of servings the recipe prepares. 1000 eggs, serves 1 for one serving is probably just a teensy bit big, huge, absolutely colossal!
Outlandish - You can bake more than just a basic sponge, for example, include some icing, a drizzle, serve with sauce, decorations, etc.
Visually appealing - images are good either in the source code as ascii or in the output. The first "byte" is with the eyes after all.

And don't forget, good bakers don't cut corners and do things properly. (Don't just use no-op code to make it look like a recipe then print, make sure your code means something)  I encourage voters to view these recipes negatively.

Happy Baking!


99 Bottles of beer, 99 languages The goal is to write a simple "99 Bottles of Beer" program .. that is valid in at least 2 distinct languages (e.g. not Python 2 and Python 3). It must be a complete file that will run or compile.

Interesting answers should be up-voted, but compactness also counts. (Of course, language diversity is the main goal.)

EDIT: I would say that to have normal C code that does the same thing with C++ and Objective-C counts as derivative. The code should do clever stuff so that lines have different meanings with different languages.

C, Perl, PHP, Python, Ruby

Update: I've put together a jsfiddle that helps visualize the path through the code for each of the five languages: http://jsfiddle.net/wK6bD/4/embedded/result/

An alternative version, that removes all comments, and compresses all insignificant strings, regex and replacement patterns: http://jsfiddle.net/wK6bD/5/embedded/result/

And I saved a byte while I was at it. Turns out C had an unnecessary semi-colon ;)

#/*<?php ob_clean();"
s='''*/include<stdio.h>
main($y){char*$s,$t[3],$u[3]/*';'''
def printf(a,*b):import sys;sys.stdout.write(a%b)
for y in range(99,-1,-1):
  '''
99.downto(0){|y|$y=y;"/*=;#*/;
for($y=100;$y--;){
  #/*"
  $u=(($t=$y)+99)%100;'*/
  sprintf($t,"%d",$y);sprintf($u,"%d",($y+99)%100);
  #//';#'''
  printf("%s bottle%s of beer on the wall, %s bottle%s of beer.\n%s",
    #/* -- THIS LINE ENDS WITH CR --
    y//1or'No more','s'[:y!=1],y or'no more','''s*/
    +$y>0?$t:"No more",$s=$y!=1?"s":"",$y>0?$t:"no more",$s,$y>0?
    #//'''[:y!=1],y and'''
    "Take one down and pass it around":
    #//'''[6:38]or
    "Go to the store and buy some more");
  printf(", %s bottle%s of beer on the wall.\n\n",
    #/* -- THIS LINE ENDS WITH CR --
    y//1-1and~-y%100or'no more','''s*/
    +$y!=1?$u:"no more",$y!=2?"s":"");}
    #/*?><?php "
    %w;q(*/
    }//";#'''[:y!=2])

Please Note: This file needs to be saved with mixed line endings. All lines should be terminated with LF (char 10, a.k.a. unix-style), except for the two lines marked -- THIS LINE ENDS WITH CR --, which should be terminated with CR (char 13, a.k.a. mac-style). I recommend using notepad++, or other text editor which allows you to manually edit line endings.

For PHP, it is assumed that output_buffering is enabled. According to the documentation, this is hardcoded to be Off when using the CLI, regardless of ini settings, so it needs to be explicitly (re)enabled:

$ php -d output_buffering=4096 bottles.pl.php.py.rb.c

This enables a 4kb buffer, which is the 'recommended' value. If you're using one of the supplied inis this will already be set, so it should run as-is from any web server.

The total file size is 823 bytes (not counting the comments about the line endings), an average of 164.6 bytes per language.

Versions Tested
C - gcc 4.8.1, cl 15.00
Perl - 5.16.2
PHP - 5.4.16
Python - 2.7.6, 3.3.4
Ruby - 1.8.7, 1.9.3

Output is identical for all five languages (see below).

Perl, PHP

<?php '>#'
;for($i='no more';100>($a="$i bottle".(2^($i+=1)?'s':'').' of beer');$o="
Take one down and pass it around, $b.

".ucfirst($f="$b, $a.$o")){$b="$a on the wall";}print"$f
Go to the store and buy some more, $b.";

I like this one because of how short it is, so I'm leaving it. It also demonstrates how much of a Perl-wanna-be PHP is ;)

Sample Usage:

$ perl bottles
99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.

98 bottles of beer on the wall, 98 bottles of beer.
Take one down and pass it around, 97 bottles of beer on the wall.

...

2 bottles of beer on the wall, 2 bottles of beer.
Take one down and pass it around, 1 bottle of beer on the wall.

1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.


Getting a Highscore in Kuku Kube First of all, this is more a challenge, than a serious programming question, I would like to share.

Some of you might know the game Kuku kube, where you have to identify a square in a grid, which has a different colour than the others and click it.

You can find it under http://kuku-kube.com/ .

As this seems to be an ideal exercise for our image processing students, I want to see, which way is the best to get the highest score.

My code so far:

from pymouse import PyMouse
import time
b=time.time()
m=PyMouse()
start=(2912,895)
tl=(2695,387)
br=(3129,814)
def click():
    m.click(start[0],start[1])
    time.sleep(0.1)
    while time.time()-b<60:
        for i in range(0,9):
            for l in range(0,9):
                m.click(2696+i*53.625,390+l*53.125)
                time.sleep(0.004)

click()

gets me to about 370-ish. Is it possible to get more? Use image processing?

High-score wins!

Javascript (Cheating), Score = limitless?

I realized that the game timer was using setInterval, which is a very unreliable way of keeping time.  With that in mind, since js is single threaded, if we simply hog the thread, the timer can't update.  As a result, you can essentially get any score you want.  If you perform 1000 clicks in a single function call without releasing the thread, you guarantee a score of at least 60000 (in fact I did this and got 180000).  This is obviously cheating because the game lasts longer than 60 seconds, though the game doesn't realize it.  For this reason, any js solution at all is really sort of cheating.  Though the time increase is minimal for code that completes quickly, you can still potentially delay the timer for as long as your code runs.

var factor = 1000;

function findAndClick() {
  var array = document.getElementById("box").children;

  for(var j = 0; j < factor; j++){
      var one = array[0].style.cssText;
      var two = array[1].style.cssText;

      var color;
      if(one != two){
        color = array[2].style.cssText;
      } else {
        color = one;
      }

      for (var i=0; i < array.length; i++) {
        if (array[i].style.cssText != color) {
          array[i].click();
          break;
        }
      }
    }
}
$(".play-btn").click();
setInterval(findAndClick, 0);

Javascript (REALLY Cheating), Score = limitless?

The game's object is actually global.  As a result, you can tweak various properties to your advantage.  The easiest of which is to just set your score to whatever you want it to be:

$(".play-btn").click();
Game.lv = 1000000;


Am I code-golfing properly? I am curious if I am Code Golfing properly. I set the challenge for myself to make a small hashing program into a single statement in Python. I first started off with:

from itertools import permutations
from string import ascii_lowercase
from random import sample

def test():
    chars = sample(ascii_lowercase, 9)
    sums = list(map(h, permutations(chars)))
    if len(set(sums)) == len(sums):
       print("unique results for permutations of given string")
    else:
       print("duplicate entries present in test results")

def h(s):
    r = 0
    for i in range(len(s)):
        r += ord(s[i]) << (i * len(s))
    return r

test()

I then made the function recursive:

def h(s, i=0):
    if i < len(s) - 1: return h(s, i+1) + ord(s[i]) << (i * len(s))
    else: return ord(s[i]) << (i * len(s))

I tried shortening it with a lambda for repeating code (it didn't work):

def h(s, i=0, f=lambda s,i: ord(s[i]) << (i * len(s))):
    if i < len(s) - 1: return h(s, i+1) + f(s,i)
    else: return f(s,i)

Finally I ended up with a lambda:

h=lambda s,i=0:h(s,i+1)+ord(s[i])<<(i*len(s))if i<len(s)-1 else ord(s[i])<<(i*len(s))

I wanted the program to be one statement, so first I came up with:

def test():
    chars = sample(ascii_lowercase, 9)
    sums = list(map((lambda s,i=0,f=lambda s,i,f:f(s,i+1,f)+ord(s[i])<<(i*len(s))if i<len(s)-1 else ord(s[i])<<(i*len(s)):f(s,i,f)), permutations(chars)))
    if len(set(sums)) == len(sums):
       print("unique results for permutations of given string")
    else:
       print("duplicate entries present in test results")

And lastly I ended up with:

print((lambda x=list(map((lambda s,i=0,f=lambda s,i,f:f(s,i+1,f)+ord(s[i])<<(i*len(s))if i<len(s)-1 else ord(s[i])<<(i*len(s)):f(s,i,f)), permutations(sample(ascii_lowercase, 9)))): "unique results for permutations of given string" if len(set(x)) == len(x) else "duplicate entries present in test results")())

Is this how codegolf problems are worked out? I've never really done this sort of thing, so right now I just want to know if I am doing it right.

Amendment: This program does all the work for you; so I will here refer to the function: As input, the program takes in all the permutations of a given string; here the string is nine characters randomly picked from ascii_lowercase. The output is a human-readable string defining whether the result of each permutation of the given string is a duplicate of another result for a different string. If there are no duplicates for all permutations, the program indicates success. Nine characters was picked as being the largest length of characters readily computed repeatedly on my box.

Amendment II As pointed out by a studious reader, the intended purpose described is not obtained through the accompanying code. The test case is obviously inadequate.

There is no 'right' way to golf. You've done well, and the process you've used is fairly standard. Making the program into one statement isn't usually a requirement though.

If it helps, here's how I would approach golfing down your program...

In the hashing function, the for statement can be replaced with a sum:

def h(s):
    r = 0
    r = sum(ord(s[i]) << (i * len(s)) for i in range(len(s)))
    return r

This can then be defined as a lambda function:

h = lambda s: sum(ord(s[i]) << (i * len(s)) for i in range(len(s)))

And now we remove unnecessary spaces and brackets:

h=lambda s:sum(ord(s[i])<<i*len(s)for i in range(len(s)))

As Sp3000 pointed out, this can be shortened further with enumerate:

h=lambda s:sum(ord(x)<<i*len(s)for i,x in enumerate(s))

Moving on to the test function, we merge its first two lines:

def test():
    sums = list(map(h, permutations(sample(ascii_lowercase, 9))))
    ...

Since both functions are only used once, we can move everything inline:

sums = list(map(lambda s:sum(ord(x)<<i*len(s)for i,x in enumerate(s)), permutations(sample(ascii_lowercase, 9))))
...

This is shorter as a list comprehension:

sums = [sum(ord(x)<<i*len(s)for i,x in enumerate(s)) for s in permutations(sample(ascii_lowercase, 9))]

Next, we give it a shorter name and remove unnecessary spaces again:

x=[sum(ord(x)<<i*len(s)for i,x in enumerate(s))for s in permutations(sample(ascii_lowercase,9))]

The if statement can be moved inside the print function:

print('unique...' if len(set(x)) == len(x) else 'duplicate...')

However, it's usually shorter to use and/or:

print(len(set(x)) == len(x) and 'unique...' or 'duplicate...')

Since len(x) doesn't change, we can calculate and hardcode its value:

print(len(set(x)) == 362880 and 'unique...' or 'duplicate...')

After removing unnecessary spaces and switching around the comparison, we get:

print(len(set(x))<362880and'duplicate...'or'unique...')

This lets us move everything into one statement:

print(len(set([sum(ord(x)<<i*len(s)for i,x in enumerate(s))for s in permutations(sample(ascii_lowercase,9))]))<362880and'duplicate...'or'unique...')

And now we can use a set comprehension instead:

print(len({sum(ord(x)<<i*len(s)for i,x in enumerate(s))for s in permutations(sample(ascii_lowercase,9))})<362880and'duplicate...'or'unique...')

The result is 210 bytes, excluding imports. The next step would probably be to golf down the imports or the long strings.


Help me Shut the Box The inspiration for this challenge should be ridiculously obvious at the time of posting.

The Task

You must create a Shut the Box style program (not function, program). The basics of shut the box are:

Players attempt to shut the box by turning a set of levers labelled 1-9. They must do so by flipping levers. The sequence of events of each turn are as follows:

The current position of the levers are shown.

On a new game, the position of the levers should be displayed as 123456789.
On a game with shut levers, all shut levers are displayed as -. For example, on a game that has 1, 5, and 9 shut, the output would be -234-678-.

The di(c)e (is|are) rolled.

If levers 7, 8, and 9 are all off, only one six-faced die is thrown. Otherwise, 2 six-faced dice are thrown.

The player is prompted to choose how many levers they wish to flip.

If the player chooses a number >9 or <0, the game ends.
If the player chooses an already shut lever, the game ends.

The player selects that many levers.

If the sum of the levers does not equal the value of the di(c)e thrown, the game ends.

If all the levers are shut, congratulations, you win. Otherwise, go back to step 1.

Rules for the Program

On each turn, you should output the current positions of levers.
You must output the value of the roll with the phrase You rolled: (note the space).
You must prompt (and wait) for the number of levers to switch with the phrase How many levers to flip: (note the space).
You must prompt (and wait) for as many levers as the player specified with the phrase Which lever to flip: (note the space).
You must flip the specified levers.
If at any point the game ends, you must output Game Over.
If the player finishes a turn with no levers open, you must output You win!

Example Games

123456789
You rolled: 5
How many levers to flip: 5
Which lever to flip: 1
Which lever to flip: 2
Which lever to flip: 3
Which lever to flip: 4
Which lever to flip: 5
Game Over

123456789
You rolled: 5
How many levers to flip: 3
Which lever to flip: 2
Which lever to flip: 2
Which lever to flip: 1
Game Over

123456789
You rolled: 12
How many levers to flip: 2
Which lever to flip: 3
Which lever to flip: 9
12-45678-
You rolled: 6
How many levers to flip: 2
Which lever to flip: 2
Which lever to flip: 4
1---5678-
You rolled: 11
How many levers to flip: 2
Which lever to flip: 5
Which lever to flip: 6
1-----78-
You rolled: 8
How many levers to flip: 1
Which lever to flip: 8
1-----7--
You rolled: 8
How many levers to flip: 2
Which lever to flip: 1
Which lever to flip: 7
---------
You win!

Python 3, 348
Saved 5 bytes thanks to Mathias Ettinger.
Saved 7 bytes thanks to DSM.
Ooof, this is a long one. I also hate that there's not a good way to do test cases.
from random import*
*l,='123456789'
q=['-']*9
r=randint
p=print
f=' to flip: '
while l!=q:
 p(*l,sep='');t=r(1,6)+r(1,6)*(l[6:]!=q[6:]);p('You rolled: %s'%t);d={int(input('Which lever'+f))for _ in' '*int(input('How many levers'+f))}
 if len(set(d))-len(d)+1-all(str(x)in l for x in d)+t-sum(d):exit('Game Over')
 for x in d:l[x-1]='-'
p('You win!')


Triangular Ulam spiral We've had a couple of challenges about the Ulam spiral. But that's not enough.

In this challenge we will plot a triangular Ulam spiral (as opposed to the usual, square Ulam spiral). Here's a sketch of what the spiral looks like.

As we know, the Ulam spiral arranges all natural numbers in an outward spiral, and marks only those that are prime. So in the above sketch only the numbers that appear in black (the primes) would be shown.

The challenge

Accept a number N as input and display the triangular Ulam spiral up to that number.

Input can be stdin or function argument.
The spiral should turn in the positive direction (that is, counter-clockwise), as in the above figure.
Any of the 120-degree turns of the above figure would be valid, and the turn may be different for different inputs. But the lowest side of the implied triangles should be horizontal, as the only allowed turns are (multiples of) 120 degrees.
The code should run theoretically (given enough time and memory) for any N up to what is allowed by any intermediate calculations you do with your default data type. double is enough; no need for large integer types.
All built-in functions allowed.
I won't accept my own answer (not that I think it would be the shortest anyway...).

Output formats

Choose any of the following.

Display a graph with a marker (dot, circle, cross, whatever you prefer) at prime numbers, and nothing at non-prime numbers. Scale need not be the same for the two axes. That is, the implied triangles need not be equilateral. Axes, grid lines and axis labels are optional. Only the markers at the prime numbers are required.

An example output for N = 12 would be as follows (compare with the above sketch). The second plot is a more interesting example, corresponding to N = 10000.

Produce an image file with the above, in any well known image format (such as png, tiff, bmp).
Display the spiral as ASCII art, using a single character of your choice for primes and blank space for non-primes, with a blank space to separate number positions in the same row. Leading or trailing spaces or newlines are allowed. For example, the N = 12 case using o as character would be

             o
            · ·
           · o ·
            o · ·
           · o · o

where of course only the o mark at primes would actually be displayed. The · at non-primes is shown here for reference only.

Winning criterion

The actual reward is seeing for yourself those amazing patterns Code golf, shortest code wins.

CJam, 49 42 bytes

Lri{)mp0S?}%{1$,)/(a@Wf%z+\L*}h;eeSff*W%N*

Input as a single integer in STDIN. Output as an ASCII grid with 0 for primes. The rotation of the spiral is not consistent: the largest number of the spiral will always be on the bottom row.

Test it here.

Explanation

The basic idea is to represent the triangle as a ragged 2D array while doing the computation. You get this array by reversing the lines and aligning all rows to the left:

   4
  5 3
 6 1 2
7 8 9 A

Would be represented as

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

Since we've mirrored the line, we want to roll up the spiral in a clockwise manner. That's convenient, because all we need to do is rotate the triangle counter-clockwise and prepend the next sublist in order. We can rotate the ragged array by reversing all lines and transposing it:

                                                           [[B C D E F]
[[7 8 9 A]         [[A 9 8 7]           [[A 2 3 4]          [A 2 3 4]
 [6 1 2]   reverse  [2 1 6]   transpose  [9 1 5]   prepend  [9 1 5]
 [5 3]      ---->   [3 5]      ------>   [8 6]      ---->   [8 6]
 [4]]               [4]]                 [7]]               [7]]

So here is the code. One detail I'd like to draw attention to is the last bit that creates the triangular layout. I think that's rather nifty. :)

L     e# Push an empty array. This will become the spiral.
ri    e# Read input and convert to integer N.
{     e# Map this block over 0 to N-1...
  )   e#   Increment to get 1 to N.
  mp  e#   Test for primality.
  0S? e#   Select 0 or a space correspondingly.
}%
{     e# While the list we just created is not empty yet...
  1$  e#   Copy the spiral so far.
  ,)  e#   Get the number of lines and increment.
  /   e#   Split the list into chunks of that size.
  (a@ e#   Pull off the first chunk, wrap it in an array, pull up the spiral.
  Wf% e#   Reverse the lines of the spiral.
  z   e#   Transpose the spiral.
  +   e#   Prepend the new line.
  \L* e#   Swap with the remaining chunks and join them back together into a single list.
}h
;     e# Discard the empty list that's left on the stack.
ee    e# Enumerate the spiral. This turns each line into a pair of 0-based index
      e# and the line itself.
Sff*  e# Multiply each element of each pair with a space. For the enumeration index i,
      e# this produces a string of i spaces - the required indentation (keeping in
      e# mind that our spiral is still upside down). For the line itself, this
      e# riffles the cells with spaces, creating the required gaps between the cells.
      e# All of this works because we always end the spiral on the bottom edge.
      e# This ensures that the left edge is always complete, so we don't need
      e# different indentation such as in the N=12 example in the challenge.
W%    e# Reverse the lines to make the spiral point upwards.
N*    e# Join the lines with linefeeds.


Find all Super Powers A positive number is said to be super power when it is the power of at least two different positive integers. Write a program that lists all super powers in the interval [1, 264) (i.e. between 1 (inclusive) and 264 (exclusive)).

Sample Output

1
16
64
81
256
512
.
.
.
18443366605910179921
18444492376972984336
18445618199572250625

Constraints:

The program should not take more than 10 secs.
There are 67385 super powers below 264.
The shortest code wins.


Not just a four fours puzzle In this variant of the Four fours puzzle your should use up to x x's (and no other number) and a defined set of operations to reach every number from 0 to 100. If x = 4 then you can use up to four 4s and this question becomes the classic four fours puzzle (except you can use up to four 4s rather than having to use exactly four of them).  We assume 1 < x <= 9.

In this version, only the following operators are allowed:

Addition (+), Subtraction (-), Multiplication (*), Division (/). Note this is real division, so that 5/2 = 2.5.
Exponentiation (e.g. 4^4) as this would involve no extra symbols if written normally by hand.
You can make new integers by concatenating xs. E.g. you can make the integers 4, 44, 444, 4444.

You may also use parentheses  to group numbers simply in order to control the order of evaluation of the operators.  You can't for example combine parentheses with concatenation as in (4/4)(4/4) = (1)(1) = 11.

No other symbols may be used and standard order of operations applies.

Your program should generate, given an x in the defined range and an n between 0 and 100 inclusive, a correct solution for that input if it exists. Otherwise your code must output something to indicate no such solution exists.

You must be able to run your submission to completion on your machine for any input values of x and n in the allowed range. This is code golf, so shortest solution wins.

This old related question uses more operators (and only 4s) and hence all numbers from 0 to 100 are solvable which won't be true for this challenge.

Input and output

Your code takes two integers x and n as input and should output a solution (or an indication there is no solution) in any human readable format you find convenient.  Input 4 6 would mean "Using up to four 4s, make the number 6" for example. So if the input is 4 6 the output could be (4+4)/4+4.

Python 3, 265 bytes

def f(x,n):
 for e in g(x,x-(x>7)):
  try:
   if eval(e)==n:return e
  except:1
g=lambda x,d:{str(x)*-~i for i in range(d)}|{s%(a,b)for a in g(x,d-1)for b in g(x,d-a.count(str(x)))for s in'%s**%s (%s/%s) (%s+%s) (%s-%s) %s*%s %s/%s'.split()['**'in a+b:]}if d else{}

Try it online!

Works for all numbers in the reference linked by Engineer Toast.

Runs up to x=8 on tio, x=9 takes a couple of minutes on my machine.

The function g returns a set of all combinations with at most x number of x's. f then loops through them and returns the first which evaluates to the number n.

The number of possible values i found for each x are:

x  possible numbers
------
2  5
3  17
4  35
5  56
6  83
7  101
8  101
9  101

All the numbers above can be generated from (a+b), (a-b), (a+b), a*b, a/b, (a/b), and a^b.
a+b and a-b do not give more numbers.

a^b is also only used once, as otherwise huge numbers are created (this is also verified in the reference document above)

An alternate version which short-circuits as soon as it finds a solution (not as golfed):

This is much faster as for x=7..9 all numbers can be created.

Python 3, 338 289 bytes

def f(x,n,d=-1):
 d=[d,x][d<0];X=str(x);r=set()
 for E in{X*-~i for i in range(d)}|{s%(a,b)for a in[0]*d and f(x,n,d-1)for b in f(x,n,d-a.count(X))for s in'%s**%s (%s/%s) (%s+%s) (%s-%s) %s*%s %s/%s'.split()['**'in a+b:]}:
  try:e=eval(E)
  except:e=-1
  if e==n:exit(E)
  r|={E}
 return r

Try it online!


"Finish work" as early as possible Background

Imagine for a moment that you have a mind-numbingly boring job.
Every morning, you are given a collection of tasks that you should work on that day.
Each task has a certain duration, and once started, it must be completed in one go.
Your boss will not tolerate idling, so if there are tasks that you could still complete before going home, you must work on one of them (you can choose which one).
Conversely, if all remaining tasks would require you to work overtime, you get to go home early!
Thus your goal is to minimize the length of your workday by clever scheduling.

Fun fact: this is one variant of the lazy bureaucrat scheduling problem, and it is NP-hard (source).

Input

You have two inputs: the number of "time units" in your workday (a positive integer L), and the collection of tasks (a non-empty array of positive integers T, representing task durations).
They can be taken in any order, and in any reasonable format.
The array T may contain tasks with duration more than L, but it is guaranteed to contain at least one task with duration at most L.

Output

A valid schedule is a subset of tasks S ⊆ T such that sum(S) ≤ L, and every task not in S (counting multiplicities) has duration strictly more than L - sum(S).
Your output shall be the smallest possible sum of a valid schedule.
In other words, you shall output the minimal number of time units you must work today.

Example

Consider the inputs

L = 9
T = [3,4,4,4,2,5]

One way of scheduling your day is [4,4]: you finish two tasks in 8 time units, and have 1 unit left.
Since no 1-unit tasks are available, you can go home.
However, the schedule [2,5] is even better: you work for 7 time units, and then all remaining tasks would take 3 or more time units.
The schedule [2,4] is not valid, since after working for 6 time units, you'd still have enough time to finish the 3-unit task.
7 units turns out to be optimal, so the correct output is 7.

Rules and scoring

You can write either a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
There is no time bound, so brute forcing is perfectly acceptable.

Test cases

These are given in the format L T -> output.

 1 [1,2] -> 1
 6 [4,1] -> 5
 7 [7,7,9] -> 7
 9 [3,4,4,4,2,5] -> 7
20 [6,2,3,12,7,31] -> 17
42 [7,7,7,7,8,8,8] -> 36
42 [7,7,7,7,7,8,8,8] -> 35
42 [7,7,7,7,7,7,8,8,8] -> 36
16 [1,2,3,4,5,6,7,8,9,10] -> 13
37 [15,27,4,1,19,16,20,26,29,18] -> 23
22 [24,20,8,8,29,16,5,5,16,18,4,9] -> 18
80 [10,22,11,2,28,20,27,6,24,9,10,6,27,2,15,29,27] -> 71
59 [26,28,5,4,7,23,5,1,9,3,7,15,4,23,7,19,16,25,26] -> 52

Jelly, 20 bytes

³œ-;⁴Ṃ;¹S>⁴
ŒPÇÐfS€Ṃ

Try it online!

TIO is fast enough to finish the last test cases within its 60 second time limit, even if just barely.

Background

The algorithm is both simple and inefficient:

We generate all subsets of T, counting multiplicities.
We filter the the subsets, keeping only those those subsets S that satisfy one of the following criteria:

S is different from T, and the sum of the elements of S and the minimal element not in S is larger than L.
S and T are identical.

The filtered T (let's call it T') now contains all lists of task that do just enough work (or even some overtime).
Of all S in T', pick the one with the lowest sum.

How it works

ŒPÇÐfS€Ṃ     Main link. Left input: T (list). Right input: L (integer).

ŒP           Powerset; generate all subsets of T.
   Ðf        Filter them...
  Ç            applying the helper link.
     S€      Compute the sum of each kept subset.
       Ṃ     Take the minimum.

³œ-;⁴Ṃ;¹S>⁴  Helper link. Input: A (subset of T)

³œ-          Multiset subtraction; remove the elements of A from T, counting
             multiplicities.
   ;⁴        Append L to the resulting list.
     Ṃ       Take the minimum.
             If S == T, the difference was empty and the minimum is L.
      ;¹     Prepend the minimum to A.
        S    Compute the sum.
         >⁴  Compare it with L.
             If S == T, the comparison will return 1.


Directory Structure Graphical Treefication Convert a classical directory structure like this:

config.yml
drafts
    begin-with-the-crazy-ideas.textile
    on-simplicity-in-technology.markdown
includes
    footer.html
    header.html

Into this

.
├── config.yml
├── drafts
|   ├── begin-with-the-crazy-ideas.textile
|   └── on-simplicity-in-technology.markdown
└── includes
    ├── footer.html
    └── header.html

Four spaces specify a nested folder or file of the above dir.
Nested categories levels allowed can vary.

Update

filenames: valid Linux filenames without spaces and linefeeds: any byte except NUL, / and spaces, linefeeds
drawing characters:

| vertical line (U+007C)
─ box drawings light horizontal (U+2500)
├ box drawings light vertical and right (U+251C)

Winner: Shortest Code in Bytes wins!

JavaScript (ES6), 237 128 bytes

f=(s,r=`.\n`+s.replace(/^ */gm,"$&└── "),q=r.replace(/^(.*)( |└)(?=.+\n\1[|└])/m,(_,i,j)=>i+`|├`[+(j>' ')]))=>q==r?r:f(s,q)

Where \n represents the literal newline character. Explanation: r is created from s by prepending the . line and inserting the └── at the end of each line's indent. This is now correct for the last line of the input, but each └ must be "extended" upwards as far as possible. This is the job of q, which searches for a └ and recursively replaces the spaces directly above it with |s unless it reaches another └ which gets turned into ├ instead. The recursion ends when no further replacements can be made. Note that if the character above the └ is a space or a └ then the text to the left of the └ is always the same as that on the previous line so I can just use \1 to test that the one character is above the other.


Downhill Maze Solver A downhill maze is given as a series of rows of space separated digits from 0 to 9 inclusive, plus one "S" and one "X", where the S denotes the start and the X denotes the finish.  In a downhill maze, you may only go to a space that is adjacent to you to the north, south, east, or west (no diagonals), and you may only go to spaces with a value less than or equal to the value you are currently on.

The program should output a path to navigate through the maze in the same format as the input, only all traversed spaces should have a "." in them, and all unvisited spaces should have a "#" in them.  The starting and ending cells should also keep their "S" and "X", respectively.  You can assume there is always a solution to the maze.

Example input:

3 3 3 3 2 1 S 8 9
3 1 1 3 3 0 6 8 7
1 2 2 4 3 2 5 9 7
1 2 1 5 4 3 4 4 6
1 1 X 6 4 4 5 5 5

Example output:

. . . . # # S . #
. # # . . # # . .
. # # # . # # # .
. # # # . # # # .
. . X # . . . . .

C# - 463

Accepts input via STDIN, and should produce an optimal path, tested for the given test case, but not otherwise. Assumes there is always a solution.

I'm in a bit of a hurry, I have a deadline in 7 hours, but this just looked like too much fun to miss out on. I'm also out of practice. It could be very embarrassing if this goes wrong, but it's reasonably golfed.

using C=System.Console;class P{static void Main(){var S=C.In.ReadToEnd().Replace("\r","").Replace('X','+');int s=S.IndexOf('S'),e=S.IndexOf('+'),w=S.IndexOf('\n')+1,L=S.Length,i,j=L;var K=new int[L];for(K[s]=s+2;j-->0;)for(i=0;i<L;i+=2){System.Action<int>M=z=>{if((z+=i)>=0&z<L&&S[z]<=S[i]&K[z]<1&K[i]>0&(i%w==z%w|i/w==z/w))K[z]=i+1;};M(2);M(-2);M(w);M(-w);}for(w=e;w!=s+1;w=i){i=K[w]-1;K[w]=-1;}for(;++j<L;)C.Write(j%2<1?K[j]<0?j==s?'S':j==e?'X':'.':'#':S[j]);}}

Code with comments:

using C=System.Console;

class P
{
    static void Main()
    {
        var S=C.In.ReadToEnd().Replace("\r","").Replace('X','+'); // read in the map, replace X with + because + < 0
        int s=S.IndexOf('S'),e=S.IndexOf('+'),w=S.IndexOf('\n')+1,L=S.Length,i,j=L; // find start, end, width, length

        var K=new int[L]; // this stores how we got to each point as loc+1 (0 means we havn't visited it)

        for(K[s]=s+2; // can't risk this being 0
            j-->0;) // do L passes
            for(i=0;i<L;i+=2) // each pass, look at every location
            {
                // if a whole load of bouds checks, point new location (i+z) at i
                System.Action<int>M=z=>{if((z+=i)>=0&z<L&&S[z]<=S[i]&K[z]<1&K[i]>0&(i%w==z%w|i/w==z/w))K[z]=i+1;};
                // try and move in each direction
                M(2);
                M(-2);
                M(w);
                M(-w);
            }

        for(w=e;w!=s+1;w=i) // find route back
        {
            i=K[w]-1; // previous location
            K[w]=-1; // set this so we know we've visited it
        }

        for(;++j<L;) // print out result
            C.Write(j%2<1?K[j]<0?j==s?'S':j==e?'X':'.':'#':S[j]); // if K < 0, we visit it, otherwise we don't
    }
}


Sum a Cubically cube's faces Manually summing a Cubically cube's faces is tedious and time-consuming, sorta like writing code in Cubically itself.

In Most efficient cubifier, I asked you to translate ASCII to Cubically source. One of the answers there uses a cube initialization sequence and then modifies the resulting cube based on the sums of the pre-initialized cube. This method has been used in many Cubically-related programs since. When testing a new initialization sequence, one has to add up all the values on all the faces, which usually takes two or three minutes.

Your task is to automate this process for us!

You will take two inputs, an integer n and a string c. These may be read from command line arguments, function arguments, standard input, a file, or any combination of those. c will be a Cubically memory cube of size n as pretty-printed by the interpreter.

The Cubically interpreter dumps its cube to STDERR upon program termination, formatted nicely for simple viewing. Run an empty program in the Cubically interpreter and open the debug section to see the cube dump of an initialized cube. Add an argument 4 to see a 4x4x4, or 5 to see a 5x5x5, etc.

If n is 3, c will follow this format (the integers will be variable):

   000
   000
   000
111222333444
111222333444
111222333444
   555
   555
   555

Spaces, newlines, and all. If n is 4, c will look like this (also with variable integers):

    0000
    0000
    0000
    0000
1111222233334444
1111222233334444
1111222233334444
1111222233334444
    5555
    5555
    5555
    5555

Et cetera.

Your program will output six integers. The first integer will be the sum of all the numbers on the top face.

   000
   000          top face
   000
111222333444    left, front, right, and back faces, respectively
111222333444
111222333444
   555
   555          bottom face
   555

The second integer will be the sum of the left face, the third the front, the fourth the right, the fifth the back and the sixth the bottom.

So if n was 3 and c was this:

   242
   202
   242
000131555313
010121535343
000131555313
   424
   454
   424

Your program would output 20 1 14 43 24 33.

Additional rules:

The output integers must be delimited by non-integer characters. You may also choose to return an array.
You may assume that the input is correct - n is an integer and c is a cube from Cubically's debugging output. So if n was 3.0 and c was foo bar, your program could break and still be valid.
Your program only needs to work for n > 1 and n < 1260. It may (attempt to) handle larger or smaller cube sizes, but it is not necessary.

This is code-golf, so the shortest code wins! If you need help, feel free to ask in the Cubically chatroom.

Jelly, 16 14 13 bytes

3 bytes thanks to Erik the Outgolfer.

ḟ⁶ỴV€€sS€ẎsS€

Try it online!


Period 2 Reversed Quine Your task is to write a program that outputs its own source code in reverse. However, when the reversed code is run, it should output the source code, facing the correct direction.

Example

Say your program is abc. When run, it should output cba. cba, when run, should output abc.

Rules

Your program should follow all the rules of a proper quine (except for outputting the source code).
Palindromes are disallowed.

Random note:
I am aware of this but I believe that this challenge is different because the transformed code must have the same properties.

RProgN, 3 bytes
1
2

Thanks to @MartinEnder for reminding me about this answer.
Try it online!
How it works
This exploits a potential flaw in our definition of proper quine:

It must be possible to identify a section of the program which encodes a different part of the program. ("Different" meaning that the two parts appear in different positions.)
Furthermore, a quine must not access its own source, directly or indirectly.

That's obviously the case here, as the output is the reverse of the code and the code is not a palindrome.
RProgN – reverse programmer notation – uses a LIFO stack and prints the items on it in the order they are popped. The two tokens 1 and 2, separated by spaces and/or newlines, get popped in reverse order and are printed separated by a newline.
This prints the reversed program
2
1

which, in turn, prints the original one.
!enilno ti yrT


Convert the Binary Champernowne Constant to Decimal The Champernowne constant is a transcendental decimal number whose digits are the concatination of all positive integers.

C10 =  0.12345678910111213141516...10

The binary version of this is

C2 = 0.1101110010111011110001...2

Write a program that prints C2 in decimal.  The program should never halt.  It should continue printing digits such that given infinite time and memory, it will print an infinite number of correct digits.

To illustrate this, you must account for integer overflow, since integer overflow will either cause an error or print incorrect digits, even with infinite memory available.

To test your code, here are the first 150 digits of this number.

0.862240125868054571557790283249394578565764742768299094516071214557306740590516458042038441438618133400466718933678923129464456214392016383510596824661

Shortest code wins.

Python 119 bytes

import sys
r=i=n=0
while 1:
 i+=1
 for b in bin(i)[2:]:n+=1;r=r*10+int(b)*5**n;~n%4or sys.stdout.write(('0.'+`r`)[n/4])

Given unlimited memory, this will run indefinitely, although it does slow down quite a bit after the first few thousand digits.

Each binary bit is treated as its corresponding power of 5, i.e:
0.1 ⇒ 5, 0.01 ⇒ 25, 0.001 ⇒ 125, 0.0001 ⇒ 625, etc.

Which lends itself nicely to a decimal conversion, as:
1/2 = 0.5, 1/4 = 0.25, 1/8 = 0.125, 1/16 = 0.0625, etc.

The variable r stores a running total of all bits so far (increasing by a factor of 10 each iteration), and every four bits the next digit is output. This is mathematically correct, because log2(10) ≈ 3.321928
which means that every 3.32 or so binary bits will produce one decimal digit. 10/3 is a better upper bound, but I chose 4 for sake of brevity.

Ruby 80 bytes

r=i=n=0
$><<gsub(/./){"0.#{r=r*10+$&.to_i*5**n+=1}"[n/4,n%4/3]}while$_='%b'%i+=1

Same algorithm as above. It's been a while since I've golfed Ruby, so I may be missing a few tricks.

GolfScript 53 bytes

0:µ.{).2base{5µ):µ?*@10*+.'0.'\+µ4/<µ(4/>print\}/.}do

Once again, same algorithm. This is one of the first things I've ever written in GolfScript, so I'm fairly certain that it can be reduced further. I've chosen to use µ (char 181) as a variable name, because it saves a whitespace in the expression µ4/.


Take me to your leaderboard Have you ever found a good challenge to answer, answered it and then found out somebody posted a solution with a better score in the same language?

Challenge

Write a program/function that takes a PPCG question ID and outputs a leaderboard.

A leaderboard consists of the rank, the language, the score, the author and the URL of each answer. This can be output as a newline delimited string, a list of strings, a "dictionary", etc..

Rank

The rank of an answer is its position in the score hierarchy (lowest first).
Answers with shared scores must have the same rank.

Language

The name of the language is always between the last # on the first line and the first ,.
It may be a link to documentation, which must be handled by taking the user-facing text.

Score

The score of a answer is the last number on the first line.
It may be a decimal number.

Author

The author of an answer is the display name of the user that posted it.

URL

The URL of an answer will go straight to the answer.
URL shorteners are disallowed.

Specifications

Standard I/O rules apply.
Standard loopholes are forbidden.
This challenge is not about finding the shortest approach in all languages, rather, it is about finding the shortest approach in each language.
Your code will be scored in bytes, usually in the encoding UTF-8, unless specified otherwise.
Explanations, even for "practical" languages, are encouraged.

Test cases

Note that these show example output formats which need not be strictly followed. These examples were taken at the time of sandboxing, they might be outdated.

Input: 28821

1. PCRE flavor, score 40 by jimmy23013 (https://codegolf.stackexchange.com/a/31863)

Input: 92944

1. Jelly, score 12 by Dennis (https://codegolf.stackexchange.com/a/92958)
2. Befunge-98, score 38 by Hactar (https://codegolf.stackexchange.com/a/98334)
3. ><>, score 41 by Sp3000 (https://codegolf.stackexchange.com/a/92980)
4. TovTovTov, score 810147050 by Yaniv (https://codegolf.stackexchange.com/a/93048)

Input: 47604*

1. Pyth, score 28.08 by Jakube (https://codegolf.stackexchange.com/a/47642)
2. APL, score 39.6 by jimmy23013 (https://codegolf.stackexchange.com/a/47606)

Input: 133793

1. Lua, score 9.06 by TehPers (https://codegolf.stackexchange.com/a/135775)
2. C# (.NET Core), score 10.20 by Kamil Drakari (https://codegolf.stackexchange.com/a/135764)
3. Cubically, score 86.98 by Kamil Drakari (https://codegolf.stackexchange.com/a/137695)

*Note that this challenge has 3 answers, however the GolfScript answer doesn't have a comma in the header which makes it undefined behaviour.

In a few better formats:

28821, 92944, 47604, 133793

28821 92944 47604 133793

28821
92944
47604
133793

This challenge was sandboxed.

C# (.NET Core), 1059 1049 1033 998 973 bytes

Saved 53 bytes thanks to @TheLethalCoder.
Saved 25 bytes thanks to @Mr. Xcoder.

using HtmlAgilityPack;namespace System.Linq{n=>{var u="http://codegolf.stackexchange.com/";var l=new Collections.Generic.List<Tuple<string,float,string,string>>();foreach(var x in new HtmlWeb().Load(u+"questions/"+n).GetElementbyId("answers").Descendants("div").Where(p=>(p.Attributes["id"]?.Value??"").Contains("answer-"))){var b=x.Descendants().First(p=>(p.Attributes["class"]?.Value)=="post-text");var h=b.Descendants().ElementAt(1).InnerText;l.Add(new Tuple<string,float,string,string>(h.Split(',',' ')[0],float.Parse(h.Split(' ').Reverse().First(p=>float.TryParse(p.Replace('.',','),out var y)).Replace('.', ',')),b.ParentNode.Descendants("td").Last(p=>(p.Attributes["class"]?.Value)=="post-signature").Descendants("div").Reverse().ElementAt(1).Descendants("a").First().InnerText,u+"a/"+x.Attributes["id"].Value.Split('-')[1]));}var s=new string[l.Count];for(var i=0;i<l.Count;){var m=l[i];s[i]=++i+$". {m.Item1}, score {m.Item2} by {m.Item3} ({m.Item4})";}return s;}}

Uses the HTMLAgilityPack.

There are probably better solutions to this using the StackOverflow API, but this is a raw HTML solution.

Ungolfed code: (Unchanged for readability & reference)

n =>
{
    // Retrieve the HTML of the question page with ID n
    var doc = new HtmlWeb().Load("https://codegolf.stackexchange.com/questions/" + n);
    // Get all the answers
    var answers = doc.GetElementbyId("answers").Descendants("div").Where(d => (d.Attributes["id"]?.Value ?? "").Contains("answer-"));

    // Format: Language, Score, Author, URL
    var l = new Collections.Generic.List<Tuple<string, float, string, string>>();

    // Loop over every answer element
    foreach (var a in answers)
    {
        // Get the content of the answer post
        var b = a.Descendants().First(d => (d.Attributes["class"]?.Value ?? "") == "post-text");
        // Get the header
        var h = b.Descendants().ElementAt(1);
        // Dummy variable for the TryParse
        float y;
        // Create a new Tuple
        var v = new Tuple<string, float, string, string>(
            h.InnerText.Split(',', ' ')[0], // The language
            float.Parse(h.InnerText.Split(' ').Reverse().First(x => float.TryParse(x.Replace('.',','), out y)).Replace('.', ',')), // The score of the answer
            b.ParentNode.Descendants("td").Last(d => (d.Attributes["class"]?.Value ?? "") == "post-signature").Descendants("div").Reverse().ElementAt(1).Descendants("a").First().InnerText, // The author
            "https://codegolf.stackexchange.com/a/" + a.Attributes["id"].Value.Split('-')[1] // The url to the answer
            );
        l.Add(v); // Add the tuple to the collection
    }
    var s = new string[l.Count]; // An array to save the leadboard content
    for (var i = 0; i < l.Count;i++)
    {
        var m = l[i]; // The current element
        s[i] = $"{i+1}. {m.Item1}, score {m.Item2} by {m.Item3} ({m.Item4})"; // Format the data
    }
    return s;
}


Duct tape can fix anything Overview

This challenge was inspired by this StackOverflow Meta post.  In it, @hakre says:

  I've seen a project really written by Stackoverflow (a noob copies together from SO here and SO there), attribution normally never is done which results in rights termination under CC. (sic)

Your mission is to make the most interesting program you can -- without ever writing a single line of code.  You can only use code which is already written for you, both in questions and answers from StackOverflow.  All you can do is duct tape it all together the best you can.  And of course, it's very important that we provide appropriate attribution so that we don't get our rights terminated.

Rules

You must include links to the questions/answers you used in your answer.
You may not modify the code you find, with the following exceptions:

a. You may rename variables, functions, and methods.  (This doesn't mean you can change a method invocation, by changing, say scanner.nextInt() to scanner.nextLine() and claiming that you're changing a method name.  The change must be in the definition or reference to the same entity.)

b. You may adjust indentation appropriately.

c. You can assume that the proper modules are loaded for the code snippets to work.  (e.g., import statements for Java and Python, using statements for C# and C++, and their equivalents in all languages)  If the code snippet includes the imports for you, you can move them to the top of the code.

d. If the language requires the code to be in some kind of method body to execute (e.g., public static void main(String[] args) for Java, static int Main(string[] args) for C#, and so on), you can wrap your code in the appropriate method.  But the contents of that main method must remain unmodified.
You must supply an explicit list of any variable/method/function/class rename-ings performed.
You can't take snippets of snippets (meaning if you take a code block from a post, you take the whole thing)
Provide a brief description of what the code does for people who aren't intimate with the language you're using.
Popularity contest, so the most upvotes wins!

Boring Five Minute Example (Python 3)

Description: Reads a bunch of log files from the current directory and randomizes the lines in them (exciting, right? This would totally win a popularity contest)

Source

import glob
import random

for file in glob.glob('log-*-*.txt'):
    # Etc.
    with open(file) as f:
        content = f.readlines()
        # shuffle the list in place
        random.shuffle(content)

        # print it
        print(content)

Legal Modifications

Renamed fname to file from link 1
Renamed b to content from link 2

Attributions

https://stackoverflow.com/a/3277516/1435657
https://stackoverflow.com/a/16737991/1435657
https://stackoverflow.com/a/4918520/1435657

C - one operation calculator

Let's have this for a start.
It's actually quite hard to find pieces of C programs that aren't whole programs. I had most trouble with declarations.

// http://stackoverflow.com/a/2911978 Block #1 (changed i to a)
static int a = 10;
// http://stackoverflow.com/a/2911978 Block #1 (changed i to b)
static int b = 10;
// http://stackoverflow.com/a/442647 Block #1 (changed c to op)
unsigned char op = (unsigned char)-1;
// http://stackoverflow.com/q/3711048 Inline block #1
int main()
// http://stackoverflow.com/a/14902422 Inline block #1
{
// http://stackoverflow.com/q/217074 Inline block #2 (changed i to a)
scanf("%d", &a)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/q/217074 Block #2 (changed c to op)
scanf("%c", &op)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/q/217074 Inline block #2 (changed i to b)
scanf("%d", &b)
// http://stackoverflow.com/a/23353870 Inline block #2
;
// http://stackoverflow.com/a/4173188 Block #2
int result = 0;
result = (op == '*') ? a * b : result;
result = (op == '/') ? a / b : result;
result = (op == '+') ? a + b : result;
result = (op == '-') ? a - b : result;
printf("%d",result);
// http://stackoverflow.com/a/3245525 Block #2
printf("\n");  /* prints newline */
// http://stackoverflow.com/q/4138649 Inline block #1
return 0;
// http://stackoverflow.com/a/14902422 Inline block #2
}

Takes a simple integral operation like 3+151 or 41/2 on stdin and outputs the result to stdout.


Interpret numbers very literally To interpret a positive integer very literally, write it in English words (without "and"), replace hyphens with spaces, replace each resulting word with its number value, and concatenate the results into a single number.
To write a positive integer more than 99 but less than 1000 in English words, prefix its last two digits written in English with [first digit in English]hundred  with a trailing space.
To write a positive integer more than 999 but less than 1 million in English words, use the following syntax: [part before the last 3 digits in English]thousand[last 3 digits in English], all separated by spaces.
The task is to input a positive integer (less than 1 million) and output it, interpreted very literally.
Examples
1 -> 1                       (one)
10 -> 10                     (ten)
16 -> 16                     (sixteen)
23 -> 203                    (twenty three)
111 -> 110011                (one hundred eleven)
123 -> 1100203               (one hundred twenty three)
1234 -> 110002100304         (one thousand two hundred thirty four)
12345 -> 1210003100405       (twelve thousand three hundred forty five)
123456 -> 110020310004100506 (one hundred twenty three thousand four hundred fifty six)
1056 -> 11000506             (one thousand fifty six)
101101 -> 11001100011001     (one hundred one thousand one hundred one)
110110 -> 1100101000110010   (one hundred ten thousand one hundred ten)

Feel free to add more test cases if necessary.
This is tagged code-golf, so the shortest code wins.

Python 2, 76 bytes

f=lambda n,k=1000:n>19and(f(n/k,k/10)+`k-k%4*5`)*(n>=k)+f(n%k,k/10)or`n`[:n]

Try it online!

Test suite from Chas Brown.

A fully recursive solution that splits on place values k=1000, k=100, and k=10. The separator for the place values is computed as k-k%4*5, which maps

1000 -> 1000
100  -> 100
10   -> 0

By stopping when n<=19, we avoid one-word numbers in the teens being split up.


Matrices Generated Using Rectangles Input is an r by c matrix of non-negative integers (you may input r and c as other parameters if this helps with golf). This may be inputted as a 2D array or, if you prefer, a 1D array (though taking in r this time is necessary). Strings separated by spaces to distinguish rows and newlines to distinguish columns are also fine (below, the test cases have multiple spaces to distinguish rows for clarity -- you do not have to do this).
Consider a matrix of zeros. A move consists of replacing a rectangle of numbers with a rectangle of some positive integer (not zero). For example, these are all valid first moves:
0 0 0 0
0 2 0 0
0 0 0 0
0 0 0 0

0 3 0 0
0 3 0 0
0 3 0 0
0 3 0 0

1 1 1 0
1 1 1 0
0 0 0 0
0 0 0 0

These are not valid first moves:
0 0 0 0
0 2 0 0
0 0 0 0
0 2 0 0

0 1 0 0
0 2 0 0
0 0 0 0
0 0 0 0

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0

Make golfed code to answer the following the question:
Given an r by c matrix, what is the smallest possible number of turns taken to construct this?
Test Cases:
1 1 1 1
1 2 2 2
1 2 3 3
1 2 3 4
1 2 3 4
> 4

1  2  3  4  5
6  7  8  9  10
11 12 13 14 15
> 15

3 3 3 3 3 3
3 2 2 2 2 3
3 2 1 1 2 3
3 2 1 1 2 3
3 2 2 2 2 3
3 3 3 3 3 3
> 3

1 1 1 1 1 1
1 2 2 2 2 1
1 2 0 0 2 1
1 2 0 0 2 1
1 2 2 2 2 1
1 1 1 1 1 1
> 8

0 0 0 0
0 0 0 0
0 0 0 0
0 0 0 0
> 0

1 1 1 1
1 3 3 1
2 3 3 2
2 2 2 4
> 4

Python 2, 333 bytes

lambda g,l=len:min(i for i in r(l(g)*l(g[0])+1)if g in o(l(g[0]),l(g),[[0]*l(g[0])for _ in" "*l(g)],set(sum(g,[])),i))
o=lambda w,h,g,s,I:I and sum([o(w,h,n,s,I-1)for n in[[[x<=j<=X<[]>Y>=i>=y and S or E for j,E in e(R)]for i,R in e(g)]for x in r(w)for X in r(x,w)for y in r(h)for Y in r(y,h)for S in s]],[])or[g]
r=range
e=enumerate

Try it online!

This only works in theory, because in practice, it takes way too long if you have more than about 5 elements in the grid.

Since this is code-golf, I apologize for the inefficiency, but efficiency would require more thought and FAR more bytes.

This code does the same thing at the cost of 5 bytes, but short-circuits, meaning that a larger grid with a small answer may finish somewhat earlier... the difference in viable search space is negligible, but just in case you wanted to test it a bit more.

The reason this is so slow is because it looks from \$0\$ up to \$W\times H\$, generating every possible \$W\times H\$ grid that can be achieved with the elements of the grid with that many steps being used.


Toggle, Print, Repeat This challenge is loosely inspired by the unimplemented esolang Pada.

Consider an array of 8 bits, all initialised to zero. We'll introduce a very minimalistic instruction set to print arbitrary strings. There are two instructions, both of which take a parameter N which is the index of a bit:

t N for toggle: This changes the value of bit N.
p N for print: This interprets all 8 bits as a byte, starting from bit N and wrapping around the end. The character corresponding to this byte is printed to STDOUT.

Let's look an example. We want to print :=. Naively we achieve this as follows (0-based bit indices):

t 2    [0 0 1 0 0 0 0 0]
t 3    [0 0 1 1 0 0 0 0]
t 4    [0 0 1 1 1 0 0 0]
t 6    [0 0 1 1 1 0 1 0]
p 0    [0 0 1 1 1 0 1 0] == 58 == ':'
t 5    [0 0 1 1 1 1 1 0]
t 6    [0 0 1 1 1 1 0 0]
t 7    [0 0 1 1 1 1 0 1]
p 0    [0 0 1 1 1 1 0 1] == 61 == '='

But instead, we can make use of the cyclic feature of p and save two instructions:

t 2    [0 0 1 0 0 0 0 0]
t 3    [0 0 1 1 0 0 0 0]
t 4    [0 0 1 1 1 0 0 0]
t 6    [0 0 1 1 1 0 1 0]
p 0    [0 0 1 1 1 0 1 0] == 58 == ':'
t 1    [0 1 1 1 1 0 1 0]
p 7    [0 1 1 1 1 0 1 0] == [0 0 1 1 1 1 0 1] == 61 == '='
                      ^

So p 7 simply starts reading the byte value from the last bit instead of the first.

The Challenge

Given a non-empty string of printable ASCII characters (0x20 to 0x7E, inclusive), produce an optimal list of instructions (one line per instruction) to print that string with the above system. If there are multiple optimal solutions (which will almost always be the case), generate only one of them.

You may choose between 0-based and 1-based indexing for the bits, but please state your choice.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter. If you don't print the result to STDOUT, it should still be a single newline-separated string.

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

Test Cases

Each test case is a single line containing the input string, followed by the optimal number of instructions, followed by one possible solution.

You should not output the instruction count in your solution - this is only included here so you can check the correctness of your code if it prints a different instruction list.

?
7 instructions
t 2
t 3
t 4
t 5
t 6
t 7
p 0

:=
7 instructions
t 2
t 3
t 4
t 6
p 0
t 1
p 7

0123456789
26 instructions
t 2
t 3
p 0
t 7
p 0
t 6
t 7
p 0
t 7
p 0
t 5
t 6
t 7
p 0
t 7
p 0
t 6
t 7
p 0
t 7
p 0
t 2
t 3
p 3
t 2
p 3

9876543210
28 instructions
t 2
t 3
t 4
t 7
p 0
t 7
p 0
t 0
t 7
p 5
t 4
p 5
t 0
t 5
p 0
t 7
p 0
t 5
t 6
t 7
p 0
t 7
p 0
t 6
t 7
p 0
t 7
p 0

Hello, World!
39 instructions
t 1
t 4
p 0
t 3
t 7
p 2
t 1
t 6
p 2
p 2
t 0
t 1
p 2
t 0
t 1
t 3
p 2
t 6
t 7
p 2
t 0
t 2
t 6
t 7
p 1
t 0
t 1
t 5
p 0
t 2
t 7
p 3
t 2
t 6
p 0
t 4
p 0
t 1
p 3

The quick brown fox jumps over the lazy dog.
150 instructions
t 1
t 3
t 5
p 0
t 1
t 2
p 1
t 1
t 3
t 7
p 0
t 1
t 5
t 7
p 0
t 1
t 3
t 7
p 0
t 5
p 0
t 3
t 4
t 5
p 0
t 4
t 6
p 0
t 4
p 0
t 1
t 4
t 6
t 7
p 0
t 1
t 6
p 0
t 3
p 0
t 0
t 5
p 4
t 0
t 7
p 0
t 1
p 1
t 3
t 5
t 6
t 7
p 0
t 1
t 5
t 6
p 0
t 4
t 7
p 0
t 1
t 2
p 3
t 5
t 6
t 7
p 2
t 1
t 2
t 6
p 0
t 0
p 7
t 0
t 7
p 5
t 3
t 4
t 6
t 7
p 0
t 6
t 7
p 0
t 1
t 3
t 6
t 7
p 0
t 1
t 4
t 5
t 6
t 7
p 0
t 4
p 4
t 6
p 0
t 1
t 6
p 4
t 5
t 6
t 7
p 0
t 1
t 3
t 5
p 0
t 1
p 1
t 1
t 3
t 7
p 0
t 1
t 5
t 7
p 0
t 1
t 4
t 5
p 0
t 1
p 3
t 3
t 7
p 1
t 1
t 5
p 0
t 1
t 3
t 4
t 7
p 0
t 1
t 5
p 0
t 4
t 6
t 7
p 0
t 4
p 0
t 1
t 4
t 7
p 0

The test cases were generated with this CJam reference implementation.

Ruby, 171

->w{s=[0]*8
w.chars.flat_map{|c|z=0..7
*m,i=z.map{|j|z.select{|k|s[k]!=z.map{|i|c.ord[i]}.rotate(j)[k]}<<j}.min_by &:size
m.map{|m|s[m]=1-s[m];"t #{7-m}"}+["p #{i}"]}*?\n}

A Ruby function that's only double the size of the reference implementation. :)

Try it online: http://ideone.com/ysYyFP

The program is pretty straighforward: it starts off with the 8 bits set to 0 and iterates through the characters. At each step, it takes the shortest route from the current state to a state that would allow printing the character. It returns a string in the specified format.

The initial (less golfed) version of the program is available here.


Tips for golfing in Pyth Pyth is a Python-inspired procedural programming language, created by PPCG user isaacg.

What general tips do you have for golfing in Pyth? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Pyth.

One tip per answer, please.

Write the code in Python first
Pyth is so similar to Python that it is pretty easy to translate Python programs to Pyth. However, because Pyth is a single-letter-per-command language, it is sometimes hard to write straight Pyth. By writing in Python first, there is less to think about at a time (since Python is a pretty easy language to code in).


Can we spell a third number? You are given two strings, each consisting of the English word for a number between 1 and 13:
one, two, three, four, five, six, seven, eight, nine, ten, eleven, twelve, thirteen

Your program or function must find out whether it's possible to spell at least one other word from the same list without using any of the letters used in the two input words.
You can follow this link to see a naive, ungolfed implementation along with the table of all possible I/O.
Examples

If the input is ['six', 'four'], we can spell 'ten', 'eleven' or 'twelve' so the answer is yes.

If the input is ['five', 'seven'], we can only spell 'two' but the answer is still yes.

If the input is ['one', 'six'], we cannot spell any other number so the expected answer is no.

Rules

You may take the words in any reasonable format. They can be in either lower case ('one'), upper case ('ONE') or title case ('One'), but it must be consistent.
You may be given twice the same word.
The order of the words is not guaranteed (i.e. your code must support both ['four', 'six'] and ['six', 'four']).
You may return either truthy / falsy values (inverting the meaning is permitted) or two distinct and consistent values of your choice.
This is code-golf.

J, 19 bytes
Takes input as six four. As the input range is limited, I just deleted characters while the output stayed the same. :-) Reads like "if there is no e in the input, or if there are no t and o in the input, … then we can spell another number."
e.e`to`for`si-.~&><

Try it online!
e.e`to`for`si-.~&><
                &>< boxing stuff
  e`to`for`si       for each e, to, for, si:
             -.~      delete from the input any character from the list
e.                  is the input still in the results, i.e. is there any
                      case were no character got deleted?


Generate the Temple Skyline Sequence Consider the following process:

Take some non-negative integer N.
e.g. N = 571

Express it in binary with no leading zeroes. (Zero itself is the only exception, becoming 0.)
e.g. 571 = 1000111011 in binary

Break apart consecutive runs of ones and zeroes in this binary representation.
e.g. 1000111011 → 1, 000, 111, 0, 11

Sort the runs from longest to shortest.
e.g. 1, 000, 111, 0, 11 → 000, 111, 11, 1, 0

Overwrite all the digits in each run with alternating 1's and 0's, always starting with 1's.
e.g. 000, 111, 11, 1, 0 → 111, 000, 11, 0, 1

Concatenate the result to get a new binary number.
e.g. 111, 000, 11, 0, 1 → 1110001101 = 909 in decimal

When you plot the values produced by this process you get a pretty neat graph:

And it's hopefully apparent why I'm calling the resulting sequence the Temple Skyline sequence:

Challenge
Write a program or function that takes in a non-negative integer N and prints or returns the corresponding Temple Skyline sequence number. Your input and output should both be in decimal.
e.g. If the input is 571 the output should be 909.
The shortest code in bytes wins.
For reference, here are the terms in the sequence from N = 0 to 20:
0   1
1   1
2   2
3   3
4   6
5   5
6   6
7   7
8   14
9   13
10  10
11  13
12  12
13  13
14  14
15  15
16  30
17  29
18  26
19  25
20  26

Here are the terms from 0 to 1023.

CJam, 25 23 22 bytes

ri1e>2be`z($W%a\+ze~2b

Just a bit of run-length encoding. -1 thanks to @MartinBüttner.

Try it online / Test suite.

Explanation

ri        Read n from input as int
1e>       Take max with 1 (special case for n = 0)
2b        Convert n to binary
e`        Run length encode
z         Zip, giving a pair [<counts> <10101.. array>]
($W%      Drop the counts array and sort decending
a\+z      Add it back to the 10101.. array and re-zip
e~        Run length decode
2b        Convert from binary


Number of domino tilings Write a program or function that given positive n and m calculates the number of valid distinct domino tilings you can fit in a n by m rectangle. This is sequence A099390 in the Online Encyclopedia of Integer Sequences. You may take input in as function argument(s), CLA or on stdin, in any reasonable format. You must return or print a single integer as output.

Each tiling must not leave any gaps, and every distinct tiling is counted, including rotations, reflections, etc. For example, the tilings for 2x3 are:

|--    |||    --|
|--    |||    --|

Example inputs/outputs:

1,  9 -> 0
2,  2 -> 2
2,  3 -> 3
4,  4 -> 36
4,  6 -> 281
6,  6 -> 6728
7, 10 -> 53175517

Your program should theoretically work for any n and m, but if your program requires too much memory or your data type overflows it's excused. Your program must work correctly for any n, m <= 8 however.

Shortest code in  bytes wins.

Matlab, 292
I am sure this can be shortened a lot just by porting it into another language.
The basic idea is bruteforcing: I came up with kind of an enumeration of all ways how to place m*n/2 domino bricks on an m*n board. But this enumeration also includes many invalid tilings (bricks that overlap or go outside of the board.) So the program constructs all those tilings, and only counts the valid ones. The runtime complexity is about O(2^(m*n/2) * m*n). Memory is not a problem for the 8x8 as it only needs O(m*n) memory. But the time needed for 8x8 is about 20 days.
Here the fully commented version that explains what is going on.
PS: If anyone knows how to make the Matlab syntax highlighting work, please include the corresponding tag in this answer!
function C=f(m,n)
d = ceil(m*n/2);%number of dominoes
%enumeration: %the nth bit in the enumeration says whether the nth
% domino pice is upright or not. we enumerate like this:
% firt piece goes top left:
% next piece goes to the left most column that has an empty spot, in the
% top most empty spot of that column
C=0;%counter of all valid tilings
for e=0:2^d-1 %go throu all enumerations
    %check whether each enumeration is valid
    A = ones(m,n);
    %empty spots are filled with 1
    %filled spots are 0 (or if overlapping <0)
    v=1;%flag for the validity. hte grid is assumed to be valid until proven otherwise
    for i=1:d %go throu all pieces, place them in A
        %find the column where to place:
        c=find(sum(A)>0,1);
        %find the row where to place:
        r=find(A(:,c)>0,1);
        %find direction of piece:
        b=de2bi(e,d);
        if b(i)
            x=0;y=1;
        else
            x=1;y=0;
        end
        %fill in the piece:
        try
            A(r:r+y,c:c+x)=A(r:r+y,c:c+x)-1;
        catch z
            v=0;break;
        end
        %check whether A has no overlapping pieces
        if any(A(:)<0)
            v=0;break;
        end
    end
    %if valid, count it as valid
    if v && ~norm(A(:))
        disp(A)
        C=C+1;
    end
end

Here the fully golfed one:
function C=f(m,n);m=4;n=6;d=ceil(m*n/2);C=0;for e=0:2^d-1;A=ones(m,n);v=1;for i=1:d;c=find(sum(A)>0,1);r=find(A(:,c)>0,1);b=de2bi(e,d);if b(i);x=0;y=1;else;x=1;y=0;end;try;A(r:r+y,c:c+x)=A(r:r+y,c:c+x)-1;catch z;v=0;break;end;if any(A(:)<0);v=0;break;end;end;if v && ~norm(A(:));C=C+1;end;end


Illustrate football team formations on a pitch Football is the sport where players kick the ball, not carry it. Some confused individuals might call this soccer.

A football team has one goalkeeper, and 10 players out on the pitch. There are many formations used in football, that dictates where each player should be (the player of course moves around, but it's the base position).

The most common formation is 4-4-2, which means that there are 4 defenders, 4 midfielders and two attackers. Other formations are ("defenders, midfielders, attackers" or "defenders, midfielders, midfielders, attackers"):

4-4-2
4-3-3
5-3-2
3-4-3
3-5-2
4-5-1
5-4-1
4-4-1-1
4-3-1-2
4-1-2-3
4-1-3-2
4-3-2-1
3-4-1-2
3-3-3-1

The challenge is to take two inputs, one for each of the two teams and output a overview of the players on the field.

In general: Most information about the layout of the ASCII-art can be found in the figures (a picture says more than 1000 words). Only the way to place the 10 players on the field is explained in detail:

The keeper and the penalty area takes up 3 rows of ASCII-characters

Layout and number of spaces can be found in the figure below

There is no empty row between the penalty area and the defenders
If there are 3 numbers in the formation (e.g. 4-4-2, 4-3-3 etc. Not 4-3-2-1):

There is no empty row between the defenders and the midfielders
There is one empty row between the midfielders and the attackers

If there are 4 numbers in the formation (e.g. 4-3-2-1, 3-3-3-1 etc. Not 4-4-2):

There is no empty row between the defender and the first row of midfielders
There is no empty row between the first row of midfielders and the second
There is no empty row between the second row of midfielders and the attackers

There is no empty rows between the attackers and the center line
The team on the upper half are marked as x, and the team on the second half are marked as o.
Each row of players shall be distributed on the pitch as shown in the figures below. The number of spaces can be seen in the figure.

The following figure does not represent a valid formation, but is used to illustrate the layout and number of required spaces between each player. The input for this would be 2 3 4 5 and 5 4 2:

+-----------------+
|     |  x  |     |
|     +-----+     |
|     x     x     |
|    x   x   x    |
|  x   x   x   x  |
|  x  x  x  x  x  |
+-----------------+
|     o     o     |
|                 |
|  o   o   o   o  |
|  o  o  o  o  o  |
|     +-----+     |
|     |  o  |     |
+-----------------+

Valid examples:

Input:
4 4 2, 5 3 1 1

+-----------------+
|     |  x  |     |
|     +-----+     |
|  x   x   x   x  |
|  x   x   x   x  |
|                 |
|     x     x     |
+-----------------+
|        o        |
|        o        |
|    o   o   o    |
|  o  o  o  o  o  |
|     +-----+     |
|     |  o  |     |
+-----------------+

Input:
3 5 2, 4 4 1 1

+-----------------+
|     |  x  |     |
|     +-----+     |
|    x   x   x    |
|  x  x  x  x  x  |
|                 |
|     x     x     |
+-----------------+
|        o        |
|        o        |
|  o   o   o   o  |
|  o   o   o   o  |
|     +-----+     |
|     |  o  |     |
+-----------------+

Rules:

Input can be on any convenient format, separated however you want. Format can be a single string (5311), comma separated digits (5,3,1,1), etc.

The input should not contain any other information than the two formations

The output should look exactly as the sample figures, but trailing spaces and newlines are OK.
You can assume only valid input is given (only formations in the list will be used).
Full program or function

This is code golf, so the shortest code in bytes win.

Python 2, 401 377 bytes

def g(x,o):
 r=lambda r:["|"+"  x"*5+"  |","|        x        |","|     x     x     |","|    x   x   x    |","|  x   x   x   x  |"][r%5];d="+"+"-"*17+"+";h=[d,"|     |  x  |     |","|     +-----+     |"]+map(r,x);b=map(lambda r:r.replace("x","o"),[s for s in h[:3]]+map(r,o))[::-1];e="|"+" "*17+"|"
 if len(x)-4:h.insert(5,e)
 if len(o)-4:b.insert(1,e)
 print"\n".join(h+[d]+b)

Ungolfed version with test environment here!
Function that takes two lists of the format [defenders, midfielders, midfielders, attackers] while the one midfielder number is optional. Team X (top) comes first, team O (bottom) second.


Tic Tac Toe encoder/decoder James Bond is about to start a new mission and you are his computer scientist friend. As Tic Tac Toe is becoming more and more popular you decide that nothing would be more underhanded than a Tic Tac Toe encoder/decoder™.

For each line the decoder will follow the following steps:

Convert from 'O','X' and ' ' [space] to trinary

' ' -> 0
'O' -> 1
'X' -> 2

Convert from trinary to decimal
Convert from decimal to letter

Example: "XO "

210
21
v

The encoder will do the reverse.

As code is much more precise than words, see the reference answer below in which I give an example (very long) implementation of the problem in Python:

Your decoder should be able to decode all the messages encoded with my encoder correctly and my decoder should be able to decode all the messages encoded with your encoder.

This is code-golf, the shortest wins.

Additional informations

0 must be converted to a, the alphabet ends with a whitespace, so 26-> ' ' [whitespace]
"XXX" is the max, it translates to "222" that translates to 26.
As in Tic Tac Toe the max line lenght is 3.
X -> 2 means X should be replaced by 2
Encoder/Decoder

The encoder goes from plaintext to code.
The decoder goes from code to plaintext.

C++, 168 + 135 = 303 bytes

EDIT: saved one byte by requiring uppercase input

I like doing these in C++ because I get to do all sorts of fun nastiness I would never ever do in C++ code.

Encoder (168):

Takes a string of uppercase letters and spaces as an argument.

#include<cstdio>
int main(int h,char**c){c[0][3]=0;for(c++;h=**c;c[0]++){h=h&32?26:h-65;for(int d=2,e;d+1;d--){h=(h-(e=h%3))/3;c[-1][d]=e&2?88:e*47+32;}printf(c[-1]);}}

Readable:

#include<cstdio>
int main(int h,char**c)
{
    c[0][3]=0;
    for(c++;h=**c;c[0]++)
    {
        h=h&32?26:h-65;
        for(int d=2,e;d+1;d--)
        {
            h=(h-(e=h%3))/3;
            c[-1][d]=e&2?88:e*47+32;
        }
        printf(c[-1]);
    }
}

Decoder (135):

Takes a string of X, O, and space as an argument.

#include<cstdio>
int b=9,v;int main(int h,char**c){for(c++;h=**c;c[0]++){v+=(h&16?2:h&1)*b;b/=3;if(!b)putchar(v==26?32:v+97),v=0,b=9;}}

Readable:

#include<cstdio>
int b=9,v;
int main(int h,char**c)
{
    for(c++;h=**c;c[0]++)
    {
        v+=(h&16?2:h&1)*b;
        b/=3;
        if(!b)putchar(v==26?32:v+97),v=0,b=9;
    }
}


Index of a multidimensional array Lower level languages, such as C and C++ actually have no concept of multidimensional arrays. (Other than vectors and dynamic arrays) When you create a multidimensional array with

int foo[5][10];

This is actually just syntactic sugar. What C really does is create a single contiguous array of 5 * 10 elements. This

foo[4][2]

is also syntactic sugar. This really refers to the element at

4 * 10 + 2

or, the 42nd element. In general, the index of element [a][b] in array foo[x][y] is at

a * y + b

The same concept applies to 3d arrays. If we have foo[x][y][z] and we access element [a][b][c] we are really accessing element:

a * y * z + b * z + c

This concept applies to n-dimensional arrays. If we have an array with dimensions D1, D2, D3 ... Dn and we access element S1, S2, S3 ... Sn the formula is

(S1 * D2 * D3 ... * Dn) + (S2 * D3 * D4 ... * Dn) + (S3 * D4 ... * Dn) ... + (Sn-1 * Dn) + Sn

The challenge

You must write a program or function that calculates the index of a multidimensional array according to the formula above. Input will be two arrays. The first array is the dimensions, and the second array is the indices. The length of these two arrays will always be equal and at least 1.

You can safely assume that every number in the arrays will be an non-negative integer. You can also assume that you will not get a 0 in the dimension array, although a 0 might be in the indices. You can also assume that indices will not be larger than the dimensions.

Test IO

Dimensions: [5, 10]
Indices: [4, 2]
Output: 42

Dimensions: [10, 10, 4, 62, 7]
Indices: [1, 2, 3, 4, 5]
Output: 22167

Dimensions: [5, 1, 10]
Indices: [3, 0, 7]
Output: 37

Dimensions: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6]
Indices: [3, 1, 5, 5, 3, 0, 5, 2, 5, 4]
Output: 33570178


Implement a Useless interpreter Your task is to build an interpreter to the Useless language:

Here are the functional requirements:

All the described commands should be accepted by the interpreter.
NO., NOOP and INCLUDE-xxx must be honored.
DONTUSEME(n) must have its base date to be easily configurable to something more reasonable for testing purposes.
INCLUDE-xxx must be able to generate any command with a roughly equal probability. If it generates a DONTUSEME(n), he should randomly choose a small value for n.
DONTUSEME(n) windows should survive the NO. instruction. Tip: spawn a new process for those windows.
BOOM! and KABOOM! must do something bad and scary, and KABOOM! must be worse than BOOM!. But this must not be taken too seriously, so it should not be something destructive, overly-disruptive or hard to be undone. Please, do not, do not, and do not make these instructions run a rm -rf \ command, run a fork bomb, install malware, corrupt data in the file system, or post or download inappropriate content from the internet, or any other thing clearly abusive.
TURINGVSALONZO should run as if it in fact was doing what it should do. Tip: Make it randomly decide if it would sleep for a random very long time, or a random short time, or forever.
All the other predefined instructions should do something other than the aforementioned instructions and different one to the another, but never something worse than BOOM! or KABOOM!. What they do exactly is up to you, but a simple implementation would just output an error message or some other text.
You should provide an easy way for the user to provide the program that would be run by the interpreter. i.e. Reading plaintext from a file or from stdin is ok. Reading it from an encrypted file somewhere in the internet is not.

Optional:

You might invent some new commands if you want, but they should be subject to the same rules as the others are. Do not use this to circumvent the restrictions in BOOM! and KABOOM! or to defeat DONTUSEME(n). And if you do invent new commands, explain what they do.
You should think about what the interpreter do if it receives input with unknown commands (or even completely unparseable random bytes gibberish).
Although no instruction should defeat the DONTUSEME(n) command, you might add a kill switch for it. Just don't expose that in the language.

We have a few non-functional requirements to avoid abuses:

Your entry must be as complete and autocontained as possible. This means that it should not be simply some sort of installer or clearly incomplete program. This way, downloading and using libraries like jQuery or packages from maven central is ok, but downloading arbitrary code and packages from your custom server is not.
Your entry should not get any content from this very page or from some mirror or copy of this page in order to do some sort of reflection or for any other purpose. This is essential to avoid some program that try to read other entrants answers to this question or try to disrupt the question or answers in any way.
Your interpreter should be immutable and not self-modify or modify its input file. But, creating a mutant copy of the interpreter or of the input file without altering the original is ok.

And finally, considering that:

The programs in the answers are expected to be pretty useless even if fully conformant;
The language is (on purpose) very underspecified, and the answerers have a lot of liberties to take and are incentived to take them;
The requirements and the possible implementations have a lot of subjective points;
The objective with this is to just get some fun and creativity.

Then, this is a popularity-contest, and the most upvoted answer fully conformant to the rules wins! So, you don't need to golf or obfuscate your answer (but you might do that if you want). Just be sure to post something original and creative to deserve the upvotes, i.e. please don't post lame boring entries.

HTML + Javascript + jQuery + jQuery UI

The input should be given in the text area and should be formatted as each command in a line. The commands are not case sensitive. All of the commands were fully implemented. I hope that you enjoy.

You can try it at http://jsfiddle.net/bCBfk/

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
    <title>Useless interpreter</title>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">

Type here your program input:

      <textarea id="input" style="width: 400px; height: 150px;"></textarea>

        <button id="bt">Run the program</button>
        Running the program...

Here is the program output:

      <button id="cc" style="display: none;">Clear the output</button>

It has one new command:

   It is the 42 command which calculates the answer of the life, the universe and everything. The only quirk is that it takes 7.5 million years to finish.

Other spoilers:

   This entry has several features:

  You will really hate the FAIL command.
  BOOM! will screw up you "execution unit". At least the windows from DONTUSEME(n) are able to survive this.
  KABOOM! is really dangerous to world in several bad ways.
  DONTUSEME(n) always opens infinite unclosable empty windows, one each 0.8 seconds. But there is a hidden kill switch.
  DONTUSEME(n) survives NO., FAIL and even BOOM!. I just couldn't make it survive the KABOOM! though. The reason is that popup windows won't work as this is not the result of a click (and popups created by other ways are long banned in all major browsers), and could not use iframes too because of a violation of same-origin policy.
  INCLUDE-xxx can create any instruction, including DONTUSEME(n) or another INCLUDE-yyy instruction.
  If INCLUDE-xxx does generates an INCLUDE-yyy instruction, the yyy name is generated at random. If you grab the name of the generated command with firebug or something similar, you can use it.
  It handles malformed syntax and incomplete or empty input.