Creative Programming Make a story out of your programming.
Example in JavaScript:

self.book = {
    "story": function() {
        var once = "upon",
            aTime = setTimeout(function() {
                // Code would continue...
            }, 1000)
    }
};

self.book.story();

Stipulations:

Must run error-free before, during, and after it's compiled.
You can only use up to two words for the story per String/name.

JavaScript Example:
var story = "Once upon a"; // Wrong (Using more than two words)
var story = "Onceupona"; // Wrong (Using more than two "words")
var onceUponA = "time"; // Wrong (more than two words as a variable name)
var onceUpon = "a time"; // This is fine
var story = "Once upon"; // This is fine

The story must be a complete sentence (at least).
Having some sort of output (such as "printing" the story itself) is not necessary, but it's a plus.
Bring some creativity into it.

Since there are no length rules, the answer with the most votes / best creativity will win. :)

JavaScript

Not sure how historically accurate this, but it's a mini-history of ECMAScript. Please feel free to suggest improvements.

function story() {
    var IE = {
        from: "Microsoft"
    },
        Netscape = {
            from: "Mozilla"
        };
    var setUp = {
        oncethere: "were two",
        browsers: IE + Netscape
    };
    var parts = {

        And: function() {
            var theyfought = "to be",
                theBest = "browser";
        },
        oneday: function() {
            var they = {
                added: function() {
                    var add = "scripting languages";
                    Netscape.language = add;
                    IE.language = add;
                    return add;
                },
                thought: function() {
                    if (what(they.added) === good) {
                        they.wouldBeat = "the other";
                    }
                }
            };

        },
        andso: function() {
            function callLanguage(name) { return name };
            Netscape.language = callLanguage("Javascript");
            IE.language = callLanguage("JScript");
        },
        butThen: function() {
            var ECMA = "Standards Committee";
            (function standardized(languages) {
                (function into() {
                    return "ECMAScript";
                })();
            })([IE.language, Netscape.language]);

        },
        theEnd: function() {
            return {
                andWe: "all lived",
                happilyEver: "after..."
            };
        },
        what: function(thing) {
            return thing;
        },
        good: true || false
    };
}
story();


GolfScript, CJam, or Pyth? Which language usually produces shorter golfed code: Pyth, CJam or Golfscript?

In asking this, I do not mean which has a prettier syntax or which has the most useful commands, I mean overall, which one is usually the shortest? What types of problems would we expect each language to have an advantage in?

There is no simple answer to this question.

GolfScript almost never beats CJam. It has a lot less built-ins than CJam and the overall syntax is a bit more verbose. For example, print and {+}* become
o and :+ in CJam.

The only exceptions are extremely trivial problems where the fact that GolfScript implicitly reads from STDIN is an advantage and the few occasions where block concatenation is useful (example).

With CJam and Pyth, it's a bit more complicated. Both languages can beat the other in particular challenges, although, by my completely unscientific observation, Pyth seems to have the upper hand on more occasions.

A few particular cases where picking one over the other is rather easy:

Choose Pyth if it has a built-in that CJam lacks and significantly simplifies the task.

For example, Pyth has r<iterable>2, which is Python's swapcase(). If that's useful in a challenge (example), it will be hard to beat with CJam.
On occasions, you have to build the output piece by piece. After finishing the program, CJam implicitly prints the entire stack, so you can just dump the pieces and let the interpreter do the rest.

For example, ascii-art challenges are usually won by CJam.
The length of a single built-in may be a decisive factor in a challenge.

Here, Pyth's C, which is shorter than CJam's 256b, was enough to outgolf CJam.

This would be longer in Pyth, partly because trigonometric functions are 3-character built-ins in Pyth and 2-character built-ins in CJam.

To sum it up, there is no single language that will magically make you win all code golf competitions. You haven't even considered APL, J, K, O, Q, TI-BASIC, Retina, Perl, sed and Mathematica, which all have beaten both CJam and Pyth in a few occasions.

You have several options:

Learn Pyth and CJam. Use the one that's more suited for each task.
Learn the one (first) you like better.

Personally, I'm crazy about stack-based languages, which I find much more easier to write and read.
Learn the one suited better for the challenges you enjoy.

ascii-art is your thing? Go with CJam. Nothing beats array-manipulation? Forget about both and learn J.


Random Move 2x2 Scrambling A simple way to scramble a 2x2x2 Rubik's cube is to make a sequence random moves. This is not how official scrambles are done, but can get pretty close to a uniform distribution of all possible scramble states. Due to the way a 2x2 only has two layers, doing one turn on one face is equivalent (without considering the puzzle's orientation in space) to doing the same direction turn on the opposite face. For example, turning the top face clockwise moves all the pieces in relation to each other the same way turning the bottom face clockwise does. So scrambles only need to turn the top (U), right (R), and front (F) faces.
For this challenge, your program must generate a string that represents a sequence of 16 moves. A move is represented by a face, one of the letters U, R, F, followed by a direction: clockwise (empty string or space  ), counterclockwise (apostrophe '), or 180 degrees (2). The turn and direction should be chosen uniformly at random, however two consecutive moves cannot turn the same face, For example a scramble cannot contain R' R2. So the first move should have a 1/3 chance for each face, but there should be a 50/50 chance for the chosen face after the first move. Moves are separated by a space.
Example scramble:
U  F' R2 F' R' F  R  F2 U' F  R2 F  U2 F' U2 F2

Python 3.8, 84 83 82 bytes
-2 bytes thanks to dingledooper!

import random as R
print(*[(R:=c([*{*"FUR"}-{R}]))+c(" '2")for c in[R.choice]*16])

Try it online!


05AB1E/GolfScript/Jelly 11 6 bytes / 3 languages = 2

"'İ*@'

Both 05AB1E and GolfScript have the nice property that they do implicit prints of strings, so we only lose 3 bytes on them (because 05AB1E doesn't need the closing quote).

Also, my first 05AB1E, GolfScript, and Jelly programs.


My source is in order, is yours? Your challenge is to write a program, function, etc. that calculates if the passed string is "in order". That means that the characters of the string have character codes that are in order from smallest to largest.  The smallest char code must be the first. By that I mean lowest unicode codepoints to highest. It doesn't matter what code page you language uses.

You must return one value if the input is "in order" and another if it is not. The values must be distinct, but there is no other restriction on the output values. For example, you may print/return/output true for !1AQaq¡± (in order) and false for aq!QA.  The two distinct values don't need to be truthy or falsy or anything like that, just two distinct values. Repeated strings (eg. aa) are in order.

You only need to support up to unicode U+007E (~) (ascii 126)

However, the characters of your program must itself be in order. Good luck and happy code-golfing!

Brachylog, 2 bytes

.o

Try it online!

Explanation

.o
.   Assert that {the input} equals the output of the last command in the program
 o  Sort {the input}

As a full program, an assertion failure gives false., any successful run that doesn't violate any assertions gives true.


How can this code be more "golfed"? I'm not sure if this is the right place to ask, but I found this similar question so I'll go ahead.
I'm very new to code golfing, so keep your smothered laughs and throw-up emoji's to yourselves please ;). Anyway, someone recently posted a challenge (that was shortly deleted) to draw a 16x16 pixel image of the Old Man from the original Legend of Zelda, who gives you the wooden sword.
This guy:
Here's my code (643 characters):
from PIL import Image,ImageColor
g=ImageColor.getrgb
r=range
l=[list('0000033333300000000023233232000000003313313300000000331331330000000042333324000000042222222240000044220000224400044224222242244034424422224424433444442222444443344404422440444304440444444044400444044444404440004044444444040000004444444400000004433443344000'[i*16:i*16+16])for i in r(16)]
i=Image.new('RGB',(16,16),color='black')
for j in r(16):
    for k in r(16):
        t=k,j
        v=l[j][k]
        if v=='2':
            i.putpixel(t,g('white'))
        if v=='3':
            i.putpixel(t,g('#FFC864'))
        if v=='4':
            i.putpixel(t,g('red'))
i.show()

It's bad, I know. Anyway, anyone care to share some tips on shortening it?

Splitting the string into rows of 16 and then using two nested loops to go over each pixel is taking a lot of bytes to do. It would be easier to just loop over the original string and use (index%16,index//16) to point at a specific row and column.
Also, instead of specifying a background color you can just draw every single pixel, which is shorter when using hyper-neutrino's advice to use a list of colors. You can also use #000 and #FFF instead of black and white (1 byte shorter each).
Bonus tip: (16,16) can become [16]*2 (1 byte shorter)
Combining this with knosmos huge save by using data compression and makonede's suggestion to use as imports we can get this down to 353 bytes:

import base64,zlib
from PIL import Image,ImageColor as C
i=Image.new('RGB',[16]*2)
for j in range(256):i.putpixel((j%16,j//16),C.getrgb(['#000','#000','#FFF','#FFC864','red'][int(zlib.decompress(base64.a85decode(b"Garp%d1+#J#QrG=W9sOr.gFe$difq+:dD#Fi'\\kVYS/be9`DBVETlH%2Un>#OH/p!dpQBq?eAD\\o?Ok%[FUW>EJ8;cLZ6ZbI2XaB#r3e")).decode("u8")[j])]))
i.show()


Answer to life, the universe, and everything Task
Given a String as input, your task is to output 42 only if the input String happens to be exactly the following :
abbcccddddeeeeeffffffggggggghhhhhhhhiiiiiiiiijjjjjjjjjjkkkkkkkkkkkllllllllllllmmmmmmmmmmmmmnnnnnnnnnnnnnnoooooooooooooooppppppppppppppppqqqqqqqqqqqqqqqqqrrrrrrrrrrrrrrrrrrsssssssssssssssssssttttttttttttttttttttuuuuuuuuuuuuuuuuuuuuuvvvvvvvvvvvvvvvvvvvvvvwwwwwwwwwwwwwwwwwwwwwwwxxxxxxxxxxxxxxxxxxxxxxxxyyyyyyyyyyyyyyyyyyyyyyyyyzzzzzzzzzzzzzzzzzzzzzzzzzz

It may output any other value, produce an error or not output at all, if the input does not equal the aforementioned String.

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

Golfscript, 20

26,{.97+\{.}*}%=42`*

with new line, 21 chars (by Nabb)

26,{).[96+]*}%n+=42`*

Actually Nabb beat mine, here is original solution for with new line, 22 chars

26,{.97+\{.}*}%n+=42`*

This is simply generating source string and just comparing it against string from stdin.


Monday Mini-Golf #3: Anagram distance Monday Mini-Golf: A series of short code-golf challenges, posted (hopefully!) every Monday.
(Sorry this one's a little late.)

I'm sure most of you folks have heard of Levenshtein distance, an algorithm for calculating the distance between two strings. Well, this challenge is about implementing a similar algorithm of my own invention*, called anagram distance. The main difference is that the order of the characters doesn't matter; instead, only the characters that are unique to one string or the other are measured.

Challenge

The goal of the challenge is to write a program or function that takes in two strings and returns the anagram distance between them. The main way to do this is to use the following logic:

Convert both strings to lowercase and (optionally) sort each one's characters alphabetically.
While the strings contain at least one equal character, remove the first instance of this character from each string.
Add the lengths of the remaining strings and return/output the result.

Example

If the inputs are:

Hello, world!
Code golf!

Then, lowercased and sorted, these become: (by JS's default sort; note the leading spaces)

 !,dehllloorw
 !cdefgloo

Removing all of the characters that are in both strings, we end up with:

,hllrw
cfg

Thus, the anagram distance between the original two strings = 6 + 3 = 9.

Details

The strings may be taken in any sensible format.
The strings will consist only of printable ASCII.
The strings themselves will not contain any whitespace other than regular spaces. (No tabs, newlines, etc.)
You need not use this exact algorithm, as long as the results are the same.

Test-cases

Input 1:

Hello, world!
Code golf!

Output 1:

9

Input 2:

12345 This is some text.
.txet emos si sihT 54321

Output 2:

0

Input 3:

All unique characters here!
Bdfgjkmopvwxyz?

Output 3:

42

Input 4:

This is not exactly like Levenshtein distance,
but you'll notice it is quite similar.

Output 4:

30

Input 5:

all lowercase.
ALL UPPERCASE!

Output 5:

8

Scoring

This is code-golf, so shortest valid code in bytes wins. Tiebreaker goes to submission that reached its final byte count first. The winner will be chosen next Monday, Oct 12. Good luck!

Edit: Congrats to the winner, @isaacg, using Pyth (again) for an astounding 12 bytes!

*If this algorithm has been used elsewhere and/or given another name, please let me know! I wasn't able to find it with a 20-minute search.

Pyth, 12 bytes

ls.-M.prR0.z

Test suite

The operation in question is equivalent to Pyth's bagwise subtraction operator, .-, applied in both directions. You could call it bagwise xor, I suppose.

The solution is:

.z: get input as list of 2 strings.

rR0: convert both to lowercase.

.p: Form all permutations, i.e. normal and reversed.

.-M: Map the .- operation over each ordering.

s: Concatenate the results.

l: Print the length.


A doubly linked list that only stores 1 pointer per element A favorite puzzle of mine. Not massively difficult but a tad interesting.

The Objective

Using a low level language (C/C++/similar level) - create a doubly linked list of elements that only stores a single pointer instead of storing both a previous and next element pointer as you normally would.

You must be able to find each element in your linked list, starting from either the first element you created, or the most recently created element.

You must use malloc(sizeof(*node)) or similar to store each element (the addresses are likely to be non-sequential as a result)

The Restrictions

The data type you use to store your value must be the length of a function pointer (No using long values to store 2 pointer addresses one after another)
You may not use any external libraries (only the standard libc methods are permitted if you're using C/C++, apply the spirit of this rule to other languages)
You may not store any additional metadata elsewhere (or in the list elements themselves) to solve this. The list element may only contain two fields - the 'data' value and the value you will use to find the previous and next elements. It may look something like:

    struct node
    {
       int myValue;
       struct node* prevAndNextNode;
    }

Golf or Challenge?

You can either find the most elegant/interesting solution, or the shortest. Take your pick!

Have fun ;)

This is an xor linked list:

struct node {
  int myValue;
  uintptr_t xor_prev_and_next;
  node *next(node *prev) {
    return (node*)((uintptr_t)prev ^ xor_prev_and_next);
  }
  node *prev(node *next) {
    return (node*)((uintptr_t)next ^ xor_prev_and_next);
  }
}

struct list {
  node *first;
  node *last;
  int sum_forwards() {
    int sum = 0;
    node *prev = NULL;
    node *curr = first;
    while (curr) {
      sum += curr->myValue;
      prev, curr = curr, curr->next(prev);
    }
    return sum;
  }
}


Detect ASCII-art windows made of M and S characters A Window is an ASCII-art square with odd side length of at least 3, with a single character border around the edge as well as vertical and horizontal strokes in the middle:

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

An MS Window is a window where the border is made only of the characters M and S. Your task is to write a program (or function) that takes a string and outputs a truthy value if the input is a valid MS Window, and a falsey value if it is not.

Specifications

You may take the input as a newline-separated string or an array of strings representing each line.
The border of an MS Window may contain a mix of M and S characters, but the inside will always be composed of spaces.
You can choose to detect only windows with trailing newlines, or only windows without trailing newlines, but not both.

Test Cases

Truthy:

MMM
MMM
MMM

SMSMS
M M S
SMSMM
S S M
SMSMS

MMMMMMM
M  S  M
M  S  M
MSSSSSM
M  S  M
M  S  M
MMMMMMM

Falsey:

Hello, World!

MMMM
MSSM
MS M
MMMM

MMSMM
M S.M
sSSSS
M S M
MMSMM

MMMMMMM
M  M  M
MMMMMMM
M  M  M
MMMMMMM

MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM
M M M M
MMMMMMM

MMSSMSSMM
M   M   M
S   S   S
S   S  S
MMSSMSSMM
S   S   S
S   S   S
M   M   M
MMSSMSSMM


Primality Testing in Manufactoria Background

Manufactoria is a game about programming. The player must use a form of two-dimensional programming language to complete tasks.  If you've never heard of it, the easiest way to learn is to try out the first few levels of the game.

Challenge

Your challenge is to create a program which tests the primality of a number.

The input will be a series of N blue markers in the queue.  If N is prime, then your program should accept it (move the robot to the finish).  If N is composite, then your program should reject it (drop it on the floor somewhere).

Submission Options

Since this is a more complex challenge than the typical Manufactoria challenge, I have decided to allow more ways to submit your answers.

Vanilla

I have created a 13x13 custom level to build and test submissions.  The custom testing level is as follows.

  13x13 custom level

The game only allows 8 test cases on a custom level, but your creation should be theoretically able to handle any natural number N, limited only by the available memory.  For informational purposes, the test cases provided in the custom level are as follows:

1 -> reject
2 -> accept
4 -> reject
5 -> accept
7 -> accept
9 -> reject
11-> accept
15-> reject

Expanded Grid

Some users may want more room than a 13x13 grid.  Here is a link to an in-game 15x15 custom level, created by changing a number in the URL:

  15x15 custom level

Sadly, larger custom levels don't work, as the additional cells are inaccessible.

The Manufactoria Esolang

There has been an adaption of Manufactoria into an ASCII-based language.  If you want a different way to design/test your creation, or if you are unable to fit your final solution onto the game board, you can use this esolang. You can find information on this esolang here:

  Manufactoria esolang

There are a few discrepancies between the esolang and the actual game.  For example, conveyor crossings are handled differently.  Try to avoid taking advantage of these discrepancies.

A Faster Way to Test

The game is very slow when it comes to programs which take several thousands of steps to complete.  My proof-of-concept solution took 28042 steps to reject 15.  Even at the 50x speedup in-game, that simply takes too long.

I found this very helpful website.  Simply copy-paste the link to your answer, and you can test your answer with specific inputs.  The 28042-step process took under a second.

One thing to note is that it will often say something like "incorrectly accepted" even if your machine worked properly.  This is because the webpage only knows the test cases.  For example, it would say that my solution "incorrectly accepted" the number 3, even though my machine was actually correct.

How to Win

The scoring criteria is the number of parts (cells occupied).  This is code golf, so the submission with the fewest parts wins.

For those interested, my benchmark solution has 96 parts and fits on the 13x13 grid.  Finding a better algorithm could lead to colossal improvements, since I know I used a sub-optimal algorithm.

53 parts - 11x11 grid
I just learned to play Manufactoria 2 days ago, so it is probably not very golf-optimized, but at least it solves the problem. It implements trial division of course, via repeated subtraction. All divisors from 2 to N-1 are checked. The time complexity should be O(N^3), I believe.

Solution Link
I was very disappointed to have to use a conveyor belt :)


Complexity-free Kolmogorov(-Smirnov) In statistics, sometimes it's useful to know whether two data samples come from the same underlying distribution. One way to do this is to use the two-sample Kolmogorov-Smirnov test.
Your task will be to write a program that reads in two unsorted nonnegative integer arrays and calculates the main statistic used in the test.

Given an array A and a real number x, define the distribution function F by
F(A,x) = (#number of elements in A less than or equal to x)/(#number of elements in A)

Given two arrays A1 and A2, define
D(x) = |F(A1, x) - F(A2, x)|

The two-sample Kolmogorov-Smirnov statistic is the maximum value of D over all real x.
Example
A1 = [1, 2, 1, 4, 3, 6]
A2 = [3, 4, 5, 4]

Then:
D(1) = |2/6 - 0| = 1/3
D(2) = |3/6 - 0| = 1/2
D(3) = |4/6 - 1/4| = 5/12
D(4) = |5/6 - 3/4| = 1/12
D(5) = |5/6 - 4/4| = 1/6
D(6) = |6/6 - 4/4| = 0

The KS-statistic for the two arrays is 1/2, the maximum value of D.
Test cases
[0] [0] -> 0.0
[0] [1] -> 1.0
[1, 2, 3, 4, 5] [2, 3, 4, 5, 6] -> 0.2
[3, 3, 3, 3, 3] [5, 4, 3, 2, 1] -> 0.4
[1, 2, 1, 4, 3, 6] [3, 4, 5, 4] -> 0.5
[8, 9, 9, 5, 5, 0, 3] [4, 9, 0, 5, 5, 0, 4, 6, 9, 10, 4, 0, 9] -> 0.175824
[2, 10, 10, 10, 1, 6, 7, 2, 10, 4, 7] [7, 7, 9, 9, 6, 6, 5, 2, 7, 2, 8] -> 0.363636

Rules

You may write a function or a full program. Input may be via STDIN or function argument, and output may be via STDOUT or return value.
You may assume any unambiguous list or string format for the input, as long as it is consistent for both arrays
On the off-chance that your language has a builtin for this, you may not use it.
Answers need to be correct to at least 3 significant figures
This is code-golf, so the program in the fewest bytes wins

APL (29 24)

(Thanks to Zgarb for the extra inspiration.)

{⌈/|-⌿⍺⍵∘.(+/≤÷(⍴⊣))∊⍺⍵}

This is a function that takes the arrays as its left and right arguments.

      8 9 9 5 5 0 3 {⌈/|-⌿⍺⍵∘.(+/≤÷(⍴⊣))∊⍺⍵} 4 9 0 5 5 0 4 6 9 10 4 0 9
0.1758241758

Explanation:

{⌈/                                maximum of
   |                               the absolute value of
    -⌿                             the difference between
      ⍺⍵∘.(         )∊⍺⍵          for both arrays, and each element in both arrays
            +/≤                    the amount of items in that array ≤ the element
               ÷                   divided by
                (⍴⊣)              the length of that array
                          }


Hide a Brainf*** greeting in other code The goal is to write a program (anything except explicit brainfuck) which prints Barney Stinson's best rule:

  New is always better.

when interpreted normally, but

  Legen... wait for it... dary!

When processed with a Brainfuck interpreter.

May the most popular bro win. You have 72 hours to be legendary.

C#

So I decided to get a little more... creative with my entry. The Brainfuck code is embedded into the C# as the various operators (not in comments or in hardcoded strings), while the C# code itself operates on a similar principal to the way Brainfuck prints characters (meaning there are no hardcoded strings, and C# generates each individual character as an integer then casts it to a char when printing).

I'm sure I could have made this more elegant, but it took me long enough to finish as it is.

Everything was tested on this JavaScript Brainfuck interpreter by Cal Henderson and with Visual Studo 2012's C# compiler (targeted at .NET framework v4.0).

using System;

namespace Polyglot
{
    internal static class Program
    {
        private static void Main()
        {
            var a = new short[50];

            short _1 = 72;
            short _2 = 0;
            short _3 = 0;
            short _4 = 0;
            short _5 = 0;
            short _6 = 0;
            short _7 = 97;
            short _8 = 0;
            short _9 = 0;
            short _10 = 0;
            short _11 = 0;
            short _12 = 0;
            short _13 = 0;
            short _14 = 0;
            short _15 = 0;
            short _16 = 46;
            short _19 = 0;
            short _20 = 0;
            short _21 = 0;

            if( 0 >= 0 )
            {
                ++_1;
                ++_1;
                ++_1;
                ++_1;
            }

            a[ -1 < 0 ? 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 : 0 + 1 > 1 ? 0 : 0 ] = 9001;

            if( 7 < 42 )
            {
                ++_1;
                ++_1;
            }

            Console.Write( (char)_1 );

            _2 = 101;
            _1 += 1 + 1 + 1 + 1 + 1;

            _3 = 42 > 7 ? 110 + 9 : 1 + 1;

            a[ -1 < 0 ? 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 : 0 > 0 ? 0 : 0 ] = 9001;

            if( 1 < 2 )
                _4 = 32;

            Console.Write( (char)_2 );

            ++_1;
            _5 = 105;

            Console.Write( (char)_3 );

            --_1;

            _6 = 115;

            Console.Write( (char)_4 );

            ++_1;
            ++_1;
            ++_1;
            _1 += 1 + 1 + 5;

            Console.Write( (char)_5 );

            --_1;
            --_1;

            if( 42 > 41 )
            {
                ++_1;
                ++_1;
                ++_1;
            }

            a[ -1 < 0 ? 0 : 10 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 > 5 ? 0 : 0 ] = 9001;

            if( 42 < 9001 )
                Console.Write( (char)_6 );

            Console.Write( (char)_4 );
            Console.Write( (char)_7 );

            if( 12 > 11 && 11 > 10 )
            {
                _8 = 108;
                _9 = _3;
            }
            else
            {
                ++_1;
                ++_1;
                ++_1;
            }

            a[ -1 < 0 ? 1 + 1 + 1 + 1 + 1 + 1 : 1 > 2 ? 0 : 0 ] = 9001;

            if( _4 < _1 )
            {
                ++_1;
                Console.Write( (char)_8 );
            }
            else if( _4 > _19 && _2 > _20 )
            {
                ++_21;
                ++_21;
                ++_21;
                ++_21;
                ++_21;
                _21 += (short)( _21 + 36 );
            }

            a[ -7 < 9 ? 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 : 4 > 8 ? 9 : 9 ] = (short)( 12 < 10 ? -_4 : _9 );
            Console.Write( (char)_9 );

            if( _4 > _9 )
            {
                ++_1;
                ++_1;
                ++_1;
            }

            a[ -9 < 7 ? 10 - 1 - 1 - 1 - 1 : 6 > 7 ? 0 : 0 ] = _21;

            if( 1 < 0 )
                return;
            else
            {
                ++_1;
                Console.Write( (char)_7 );
            }

            _10 += 5 + 4 + 1 + 2 + 8 + 9 + 1 + 91;
            Console.Write( (char)_10 );

            if( 10 > _4 ) ++_21; else a[ -0 < 0 ? 5 + 6 + 1 + 2 + 3 + 9 : 1 > 2 ? 0 : 9 ] = 50;

            if( _21 <= _4 )
                _11 = 58 + 57;

            Console.Write( (char)_11 );

            if( _2 <= _8 )
                Console.Write( (char)_4 );
            else if( 1 >= 2 )
                return;
            else if( 42 >= _4 )
                _1 += ++_21;
            else
            {
                a[ -99 < --_1 ? --_1 - _1 : 44 > 12 ? 9 : 7 ] = (short)( _2 < _4 ? _21 : 6 );
                throw new Exception();
            }

            switch( _4 )
            {
                case 32:
                    var x = (char)( (short)( _4 + 66 ) );
                    Console.Write( x );
                    break;
                default: break;
            }

            _12 += (short)( ++_12 + ( ++_1 ) + 1 + 1 + 1 );
            Console.Write( (char)_12 );

            _13 += (short)( 39 + 38 + 39 );
            Console.Write( (char)_13 );

            if( _12 < _13 )
                Console.Write( (char)_13 );

            if( _13 >= _4 )
            {
                _14 = (short)( 500 - ( - ( 50 ) ) - ( --_1 ) - 90 - ( -4 ) - 267 );
                Console.Write( (char)_14 );
            }

            switch( _1 )
            {
                case 52:
                    _15 += (short)( ++_1 + ( ++_21 ) );
                    break;
                default:
                    _15 += (short)( 15 + ( ++_1 ) + 2 );
                    break;
            }

            Console.Write( (char)_15 );

            if( _16 <= 3521 && _21 < _4 )
                Console.WriteLine( (char)_16 );

            _16 = (short)( Int16.Parse( "54" ) % 2 );
            _20 = (short)( Int16.Parse( "99" ) / ( _1 > _4 ? 3 : 0 ) );
            _1 = (short)( 02.23 );

            if( _16 > 9 || _20 >= 52 )
                _1 += (short)( ( ++_1 ) + _21 );

            a[ -0 < 0 ? -52 - ( --_20 ) : 1 > 0 ? 1 : 2 ] = (short)( _12 < _19 ? Int16.Parse( "19" ) : 44 );
            _12 -= (short)f( --_19 / 19.467d );

            if( _12 > _14 )
                _19 += (short)( _19 + 1 + _3 + 5 );

            a[ -904 < 409 ? 4 + ( ++_4 ) + 4 : 49 > 50 ? 49 : 50 ] = (short)( 50 < 99 ? _4 + 669.2452 : 0 );

            if( 44 > ++_4 )
                a[ -9 < 6 ? 6 + ( ++_4 ) : 9 > 2 ? 44 : 8 ] = 3;
        }

        private static double f( double x )
        {
            return x < 12 ? x + 13.22 : x < 6 ? x + 90.45 : 5555;
        }
    }
}

This is the original Brainfuck code I wrote for this challenge:

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

When running the C# code through a Brainfuck interpreter, you end up with the following commands (notice the addition of the square brackets at the beginning, these are from the array declaration and don't do anything, since the cell under the memory pointer in the array will already be 0):

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


CJam, 53 52 47 bytes

l~"X    0'ò"2/Dfb+:%"gÇâì6Ô¡÷Ç8nèS¡a"312b2b=

There's unprintables, but the two strings can be obtained by

[88 9 48 5 39 5 29 1 242]:c
[8 103 199 226 236 54 212 15 161 247 199 56 110 232 83 161 97]:c

respectively. This also shows that the code points are below 256.

This is a modulo chain answer, where we apply the following modulos to the input integer, in order:

[1153 629 512 378 242 136]

Since this list contains integers greater than 255, the list is encoded using two chars each. The decoding is done by 2/Dfb, which splits the string into chunks of length two and converts each from a base 13 number (e.g. 88*13 + 9 = 1153). However, there are two exceptions to the decoding:

The last number (136) is not included (see below),
The second-last number is represented by a single char, since the number (242) is less than 256 and splitting an odd-length array into chunks of size 2 will leave a size 1 array at the end. Thanks to @MartinBüttner for this tip!

Once the modulos have reduced the input integer to a relatively small number, we perform a lookup from a table. This table is encoded via the second string, which is converted to a base 312 number then decoded to base 2, which we index. Since CJam's array indexing wraps, we can leave out the final modulo as mentioned earlier.

Try it online | Test suite


Detect the newest file and pass it to a process Challenge

Detect the newest file in a specific folder and pass it as an argument to another process. The first argument to your program will be the folder, and the second argument will be the full path to the process.

Please specify the platform(s) your code works on.

Examples

Windows

newestfile "C:\Public_domain_movies\" "C:\Mplayer\mplayer.exe"

Linux

./newestfile /home/user /bin/ls

Zsh - 15

Only tested on Linux, but it should work on other platforms too.

$2 $1/*(.om[1])


Length-terminated sequences We all know the age-old debate - should strings be length-prefixed or should they be null-terminated? Well, you've run into a blob of binary data and apparently whoever made it decided that the best solution would be a compromise and length-terminated their strings.

For the purposes of this challenge, a length-terminated sequence is a series of one or multiple integers such that the last item in the sequence is equal to the number of items in the sequence, and no prefix of the sequence is also a valid length-terminated sequence. For example, [1], [15, 2], and [82, 19, 42, 111, 11, 6] are all valid length-terminated sequences. [15] is not a valid length-terminated sequence (it hasn't been terminated), and neither is [15, 2, 3] (it should have ended at the 2).

Your task is to write a program or function that takes a list of integers, and outputs all the valid length-terminated sequences within that list. For example, for the input list [7, 6, 5, 4, 3, 2, 1], valid length-terminated sequences would be [1], [3, 2], [5, 4, 3] and [7, 6, 5, 4].

You must output all valid length-terminated sequences found in the input, in any order. The order may vary between runs of your program. You must output no length-terminated sequences not found within the input, and no sequences found within the input that aren't valid length-terminated sequences.
If some length-terminated sequence occurs multiple times within the input, it should also be output multiple times. The sequence [9, 8, 3] occurs twice in the input [9, 8, 3, 9, 8, 3] (once starting with the first number, and again starting at the fourth number) and should thus be output twice.
A number may be part of more than one length-terminated sequence. For example, the input [9, 9, 2, 4] contains both the length-terminated sequences [9, 9, 2, 4] and [9, 2] and they should both be output.
You may assume all numbers are between 0 and 127 (both inclusive).
You may assume the input contains no more than 126 numbers.
You may not make any further assumptions about the input, including the assumption that the input contains at least one valid length-terminated sequence.
You may take input or produce output by any of the default methods. Input and output formats are flexible (within reason) and the input format need not be the same as the output format. However, the your input and output formats must not depend on the input, and must not vary between runs of your program.
This is code-golf - make your code as small as possible.

Examples

[input] -> [output], [output], ...
[7, 6, 5, 4, 3, 2, 1] -> [7, 6, 5, 4], [5, 4, 3], [3, 2], [1]
[90, 80, 70] -> (no output)
[1, 2, 3, 4, 5] -> [1]
[100, 0, 2, 2, 2, 0, 0, 2, 4] -> [0, 2], [2, 2], [2, 2], [0, 0, 2, 4], [0, 2]
[] -> (no output)
[54, 68, 3, 54, 68, 3] -> [54, 68, 3], [54, 68, 3]
[4, 64, 115, 26, 20, 85, 118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37, 113, 64, 81, 99, 30, 83, 70] -> [85, 118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14], [118, 9, 109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37], [109, 84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13, 33, 55, 119, 54, 19], [84, 64, 48, 75, 123, 99, 32, 35, 98, 14, 56, 30, 13], [14, 56, 30, 13, 33, 55, 119, 54, 19, 23, 112, 58, 79, 79, 45, 118, 45, 51, 91, 116, 7, 63, 98, 52, 37, 113, 64, 81, 99, 30], [45, 118, 45, 51, 91, 116, 7]

Python 2, 67 bytes

f=lambda l:l and[l[:x]for i,x in enumerate(l)if-~i==x][:1]+f(l[1:])

Try it online!


Iron particles around a magnet There are some iron particles on a board. We pass a current carrying wire through that board and the particles form circles. Show these circles if input given is the position of the wire.
Consider the board to be a grid of size 7x7 (fixed)
No extra white spaces are allowed.
Input can be 0-indexed or 1-indexed. (0-indexed in examples)
Examples
input:3,3 # 'X' is wire here but can be shown by anything other than '\/|-'
output:
/-----\
|/---\|
||/-\||
|||X|||
||\-/||
|\---/|
\-----/

input:1,2
output:
|/-\|||
||X||||
|\-/|||
\---/||
-----/|
------/
-------

input:0,0
output:
X||||||
-/|||||
--/||||
---/|||
----/||
-----/|
------/

input:0,3
output:
|||X|||
||\-/||
|\---/|
\-----/
-------
-------
-------

input:3,0
output:
---\|||
--\||||
-\|||||
X||||||
-/|||||
--/||||
---/|||

This is code-golf so shortest code wins.


Write a program that downloads itself Write a program that connects to this site, downloads the very answer in which it is posted, extracts its own source code and prints it out. The output must be identical to the source code. Shortest code (in bytes) wins.

Rules:

No URL shorteners allowed.
The answer must have a regular format - a heading with the language name and size, optional description, code block, optional description and explanation. No unnatural delimiters allowed.
The output must originate from the actual code block posted on the site.
The functionality must not depend on the position in the answer list; it should work even if there are multiple pages and the answer it not on the first one.
New: special note for answers that are supposed to be run in a browser: it  is ok to require running them on the codegolf domain (to obey the same-origin policy) but the domain and path should be included in the solution in order to make it fair.

Bash + coreutils + Lynx browser, 61 bytes
Thanks to @FDinoff for the tips:
lynx -dump codegolf.stackexchange.com/posts/28164/body|grep 2


Convert a logical expression to conjunctive normal form Goal:

Write a complete program or function which takes a formula in propositional logic (henceforth referred to as a logical expression or expression) and outputs that formula in conjunctive normal form. There are two constants, ⊤ and ⊥ representing true and false, a unary operator ¬ representing negation, and binary operators ⇒, ⇔, ∧, and ∨ representing implication, equivalence, conjunction, and disjunction, respectively which obey all of the usual logical operations (DeMorgan's law, double negation elimination, etc.).

Conjunctive normal form is defined as follows:

Any atomic expression (including ⊤ and ⊥) is in conjunctive normal form.
The negation of any previously constructed expression is in conjunctive normal form.
The disjunction of any two previously constructed expressions is in conjunctive normal form.
The conjunction of any two previously constructed expressions is in conjunctive normal form.
Any other expression is not in conjunctive normal form.

Any logical expression can be converted (non-uniquely) into a logically equivalent expression in conjunctive normal form (see this algorithm). You do not need to use that particular algorithm.

Input:

You may take input in any convenient format; e.g., a symbolic logical expression (if your language supports it), a string, some other data structure. You do not need to use the same symbols for true, false, and the logical operators as I do here, but your choice should be consistent and you should explain your choices in your answer if it's not clear. You may not accept any other input or encode any additional information in your input format. You should have some way of expressing an arbitrary number of atomic expressions; e.g. integers, characters, strings, etc.

Output:

The formula in conjunctive normal form, again in any convenient format. It need not be in the same format as your input, but you should explain if there are any differences.

Test cases:

P ∧ (P ⇒ R) -> P ∧ R
P ⇔ (¬ P) -> ⊥
(¬ P) ∨ (Q ⇔ (P ∧ R)) -> ((¬ P) ∨ ((¬ Q) ∨ R)) ∧ ((¬ P) ∨ (Q ∨ (¬ R)))

Notes:

If the input expression is a tautology, ⊤ would be a valid output. Similarly, if the input expression is a contradiction, ⊥ would be a valid output.
Both your input and output formats should have a well-defined order of operations capable of expressing all possible logical expressions. You may need parentheses of some sort.
You may use any well-defined choice of infix, prefix, or postfix notation for the logical operations. If your choice differs from the standard (negation is prefix, the rest are infix), please explain that in your answer.
Conjunctive normal form is not unique in general (not even up to reordering). You need only to output a valid form.
However you represent atomic expressions, they must be distinct from the logical constants, operators, and grouping symbols (if you have them).
Built-ins which compute conjunctive normal form are allowed.
Standard loopholes are forbidden.
This is code-golf; shortest answer (in bytes) wins.

You're going to hate me....

Mathematica, 23 bytes

#~BooleanConvert~"CNF"&

The input will use True and False instead of ⊤ and ⊥, but otherwise will look very similar to the notation of the question: all of the characters ¬, ⇒, ⇔, ∧, and ∨ are recognized in Mathematica (when input with UTF-8 characters 00AC, F523, 29E6, 2227, and 2228, respectively), and parentheses act as you would expect.

By default, the output will use Mathematica's preferred symbols: for example, the last test case will output (! P || ! Q || R) && (! P || Q || ! R) instead of ((¬ P) ∨ ((¬ Q) ∨ R)) ∧ ((¬ P) ∨ (Q ∨ (¬ R))). However, changing the function to

TraditionalForm[#~BooleanConvert~"CNF"]&

will make the output look pretty and conforming to these usual symbols:


Minimum number of transactions so everyone has paid the same On a road trip, N people pay for fuel. Each pays a different amount. At the end of the trip, calculate the minimum number of transactions so that each person has paid the same amount.

e.g. on the road trip, these people pay for fuel

Dave - $50
John - $25
George - $5
Barry - $0

After the road trip:

Barry pays Dave $20
George pays John $5
George pays Dave $10

Added: The output of the program should list the transactions.

Bonus points if the solution is written in Visual Basic.

Python, 308 Characters

I chose not to go after the bonus because the last time I used VB was over a decade ago, and I am still suffering from the PTSD ;-)

I didn't try and golf this very much because I'm not sure if that's the goal.  This code is guaranteed to return a solution with the minimum number of transactions.

def t(p):
 a=sum(p)/float(len(p))
 q=[([],p)]
 l=len(p)
 r=range(l)
 while q:
  n=q.pop(0)
  g=1
  for i in r:
   d=n[1][i]-a
   if d>0:
    g=0
    for j in r:
     if n[1][j]<a:
      v=min(d,a-n[1][j])
      y=list(n[1])
      y[i]-=v
      y[j]+=v
      if i!=j:q+=[(n[0]+[(j,i,v)],y)]
  if g:return n[0]

Usage

The t function takes a list of the amounts that each person paid.  Using the example from the question:

> print t([50,25,5,0])
[(2, 0, 15.0), (3, 0, 15.0), (3, 1, 5.0)]

So the solution is for person 2 (George) to pay person 0 (Dave) $15 and for person 3 (Barry) to pay 0 (Dave) $15 and also to pay 1 (John) $5.


Find the First Bracket Match This was one of a series of challenges leading up to Brain-Flak's birthday. Find out more here.

Challenge
For this challenge your objective will be to find the very first pair of matching brackets in a fully matched string of ()[]{}<> brackets. To borrow DJMcMayhem's definition of a fully matched string:

For the purpose of this challenge, a "bracket" is any of these characters: ()[]{}<>.

A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as
()
[]{}

Or if every subelement inside of it is also matched.
[()()()()]
{<[]>}
(()())

Subelements can also be nested several layers deep.
[(){<><>[()]}<>()]
<[{((()))}]>

A string is considered "Fully matched" if and only if each pair of brackets has the correct opening and closing bracket in the right order.

Input
Input will consist of a single nonempty string or char array containing only the characters ()[]{}<>, and is guaranteed to be fully matched. You may take input in any reasonable manner that corresponds with our i/o defaults.
Output
The output of your program or function will be the index of the bracket which closes the first one. Output must be either 0 or 1 indexed. Again, output may be in any reasonable manner that corresponds with our i/o defaults.
Test Cases
Input       0-indexed   1-indexed
()          1           2
(<>)        3           4
<[]{<>}>    7           8
{}{}{}{}    1           2
[[]<>[]]    7           8

This is code-golf, fewest bytes wins!

Brain-Flak, 685, 155, 151, 137 bytes

(())({<{}({}()<(()()()())>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>
([{}()]{})(({})){{}({}[()])(<()>)}{}(<>)<>{{}<>{}({}<>)}{}(<>[]<>)>()}<>)

Try it online!

136 bytes of code, plus one byte for -a. One indexed.

530 bytes golfed off! That's probably the largest golf I've ever done.

14 bytes saved thanks to Riley!

This abuses a formula of the opening/closing parenthesis: if you take the ASCII values, increment it by one, and take modulo of 4, the openers (({[<) will always get 0 or 1, whereas the closers ()}]>) will always get 2 or 3.

Explanation:

#Push 1
(())

#While true
({<

    #Pop stack height
    {}

    #Compute (TOS + 1) % 4
    ({}()<(()()()())>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})

    #Decrement if positive
    (({})){{}({}[()])(<()>)}{}

    #Push 0 onto alternate
    (<>)

    #Toggle back
    <>

    #Pop two zeros from alternate if closer
    {{}<>{}({}<>)}{}

    #Push height of alternate stack
    (<>[]<>)

#Make each time through evaluate to 1
>()

#Endwhile
}

#Push the number of loops onto the offstack
<>)


Count digits in a string, check if there its a fibonnaci number There's a question with a comment with some code thats far too long.
For a site that has counting fetish, this code just seems so wrong.
Solve this meta-riddle, and explain it with a rhyme.
Winner is the shortest code in a fortnights time.

The challenge:

Open a file as input.
Count and output the number of digits (0,1,...9) and non-digits (everything else).
If the number of digits and non-digits are consecutive fibonnacci numbers, with the number of digits is fibonnacci number f(n) and the number of non-digits is f(n-1)  the file is "valid", otherwise it is "Invalid"
Output this information as exactly as shown below.

Example 1:

Digits: 34 Nondigits: 21
Valid program

Example 2:

Digits: 33 Nondigits: 21
Invalid program

Ruby, 151

d=[0,0];$<.read.chars{|c|d[c>?/&&c<?:?0:1]+=1};puts"Digits: %d Nondigits: %d"%d
a=b=1;while b<d[0];b=a+a=b end;print ([b,a]==d)??V:"Inv","alid program"


Convert a decimal integer to binary only using arithmetic operators There are 10 types of people in the world, those who understand binary and those who do not.

Where are you? Let's see!

Challenge

Your task is to convert a decimal integer to binary, only using a set of arithmetic operators (+, -, *, / and %). You can use conditional statements, loops and variables. (No bitwise operator/No Builtin methods or function).

Input

A decimal integer.

Output

The binary number.

Examples

2 -> 10
6 -> 110
etc...

The shortest code wins.

Python 2, 30 bytes

f=lambda n:n and n%2+10*f(n/2)

Try it online!


Determining the winner of a Chess game Challenge

Being someone who plays far too much chess in his spare time, I thought I'd set a code golf challenge inspired by the game of chess (with a software flavour), for those interested.

  The challenge is to determine the winner of a game of standard chess given a PGN (Portable Game Notation) file as input -- or in the case of a draw/stalemate, be able to recognise it.

  Write a full program that takes via the standard input stream a PGN file except the final result string and outputs the winner of the game. (See the Wikipedia article for a simple description of the text format.) The program should determine the winner from the provided move information and output 1-0 for White winning, 0-1 for Black winning, and 1/2-1/2 for a draw (by stalemate). Mutually agreed draws and resignations should be denoted ? since they cannot be differentiated on this basis alone. White is always assumed to move first.

  Note that the Result metadata tag nor the game result at the end of the PGN block itself is to be included in any input, as this must be determined by the program's algorithm. The checkmate symbol (usually #) is also never present. All other metadata and comments are valid input to the program.

Example (from Wikipedia page):

Input:

[Event "F/S Return Match"]
[Site "Belgrade, Serbia Yugoslavia|JUG"]
[Date "1992.11.04"]
[Round "29"]
[White "Fischer, Robert J."]
[Black "Spassky, Boris V."]
[Result "1/2-1/2"]

1. e4 e5 2. Nf3 Nc6 3. Bb5 {This opening is called the Ruy Lopez.} 3... a6
4. Ba4 Nf6 5. O-O Be7 6. Re1 b5 7. Bb3 d6 8. c3 O-O 9. h3 Nb8  10. d4 Nbd7
11. c4 c6 12. cxb5 axb5 13. Nc3 Bb7 14. Bg5 b4 15. Nb1 h6 16. Bh4 c5 17. dxe5
Nxe4 18. Bxe7 Qxe7 19. exd6 Qf6 20. Nbd2 Nxd6 21. Nc4 Nxc4 22. Bxc4 Nb6
23. Ne5 Rae8 24. Bxf7+ Rxf7 25. Nxf7 Rxe1+ 26. Qxe1 Kxf7 27. Qe3 Qg5 28. Qxg5
hxg5 29. b3 Ke6 30. a3 Kd6 31. axb4 cxb4 32. Ra5 Nd5 33. f3 Bc8 34. Kf2 Bf5
35. Ra7 g6 36. Ra6+ Kc5 37. Ke1 Nf4 38. g3 Nxh3 39. Kd2 Kb5 40. Rd6 Kc5 41. Ra6
Nf2 42. g4 Bd3 43. Re6 1/2-1/2

Output: ?
(since it was a mutually agreed draw)

Rules

Other than mentioned in the problem statement, there are no further restrictions. You may write the program in any compiled/interpreted programming language. The code for the program must be complete, i.e. compile without any modifications or external reference.

The aim as always is to solve the task with the smallest number of characters of code.

(Saying that, I can't promise to accept the answer with the shortest code. I'll also be looking at elegance of the code and time complexity of the algorithm, especially in the case of verbose language, and hope others will do the same!)

My Solution

I'll be attempting an F# solution while this question is open -- will post it here when I have something.

Format

Please post your answers in the following format for the purpose of easy comparison:

  Language

  Number of characters: ???

  Fully golfed code:

(code here)

  Clear (ideally commented) code:

(code here)

  Any notes on the algorithm/clever shortcuts the program takes.

Ruby 1.9

Number of characters: 93

Assuming that all inputs are valid games, and that games always end in checkmates or stalemates (as per Noldorin's response in the comments), then we only need to check who played the last move and whether it was a checkmate or not.

Golfed code:

*a,b,c=$<.read.gsub(/{[^}]*}|;.*$/,"").split;puts c=~/#/?(b=~/[^.]\.$/?"1-0":"0-1"):"1/2-1/2"

Ungolfed code:

# read entire input
game = $<.read
# strip comments
game = game.gsub(/{[^}]*}|;.*$/,"")
# split the input and get the last two words
*rest, second, last = game.split
# check if the last move has a checkmate symbol
if last =~ /#/
# if so, then determine whether the last move is white or black based
# on the number of periods in the second-to-last word
  puts second =~ /[^.]\.$/ ? "1-0" : "0-1"
else
# if not, then it's a draw
  puts "1/2-1/2"
end


Implement Smokey's !!/coffee command. (Part 2) Like the previous SmokeDetector challenge? This one is for you too ;)

Note: SmokeDetector is a bot that detects spam and offensive posts on the network and posts alerts to chat.

What to implement
Smokey's !!/coffee command uniformly at random picks one of these words (sorts of coffee):

Espresso
Macchiato
Ristretto
Americano
Latte
Cappuccino
Mocha
Affogato
jQuery

adds it to the message:
"brews a cup of $COFFEE_SORT for $USERNAME"
Your task is to implement the function that takes a username as any reasonable input format, randomly (uniformly at random) picks $COFFEE_SORT, and prints to the screen:

brews a cup of $COFFEE_SORT for $USERNAME

Rules
Regular code-golf — the shortest answer in bytes wins ;)
Good luck!

Jelly, 60 bytes
“¦ƘÇ=X⁸ẓÇsŻY»⁶“¢p ɼƁỴŒ?Ọi^gċ{çØLƲ`ẆĿJ$ȮȷẈv&ẋȧ>ċ8½c»ḲX⁶“Ƙa»⁶³

Try it online!
If you write a nilad while there's an argument Jelly just dumps it into STDOUT, which is really nice for this challenge because you don't need to worry about maintaining the list of output characters but rather just dump the outputs piece by piece.
Explanation
“¦ƘÇ=X⁸ẓÇsŻY»⁶“...»ḲX⁶“Ƙa»⁶³  Main Link
“¦ƘÇ=X⁸ẓÇsŻY»                 "brews a cup of coffee for"
             ⁶                " " (dumps previous string to output)
              “...»           compressed string with space-separated coffee types
                   Ḳ          split on spaces
                    X         choose a random value
                     ⁶        " " (dumps the coffee type to output)
                      “Ƙa»    "for" (dumps the space to output)
                          ⁶   " " (dumps "for" to output)
                           ³  get the command line argument (implicit output)

It's the same length to compress " for" as to place a space and then compress "for". Unfortunately Jelly compressed strings don't seem to support trailing spaces, which unlike most situations actually matters here.


Jelly, 15 bytes

LŒ!ðŒcIṠ;ị"Pð€S

Try it online!

How it works

LŒ!ðŒcIṠ;ị"Pð€S   input
L                 length
 Œ!               all_permutations
   ð        ð€    for each permutation:
    Œc                take all unordered pairs
      I               calculate the difference between
                      the two integers of each pair
       Ṡ              signum of each difference
                      (positive -> 1, negative -> -1)
        ;             append:
         ị"             the list of elements generated by taking
                        each row according to the index specified
                        by each entry of the permutation
           P          product of everything
              S   sum

Why it works -- mathy version

The operator det takes a matrix and returns a scalar. An n-by-n matrix can be thought of as a collection of n vectors of length n, so det is really a function that takes n vectors from ℤn and returns a scalar.

Therefore, I write det(v1, v2, v3, ..., vn) for det [v1 v2 v3 ... vn].

Notice that det is linear in each argument, i.e. det(v1 + λw1, v2, v3, ..., vn) = det(v1, v2, v3, ..., vn) + λ det(w1, v2, v3, ..., vn). Therefore, it is a linear map from (ℤn)⊗n to ℤ.

It suffices to determine the image of the basis under the linear map. The basis of (ℤn)⊗n consists of n-fold tensor products of the basis elements of ℤn, i.e. e.g. e5 ⊗ e3 ⊗ e1 ⊗ e5 ⊗ e1. Tensor products that include identical tensors must be sent to zero, since the determinant of a matrix in which two columns are identical is zero. It remains to check what the tensor products of distinct basis elements are sent to. The indices of the vectors in the tensor product form a bijection, i.e. a permutation, in which even permutations are sent to 1 and odd permutations are sent to -1.

For example, to find the determinant of [[1, 2], [3, 4]]: note that the columns are [1, 3] and [2, 4]. We decompose [1, 3] to give (1 e1 + 3 e2) and (2 e1 + 4 e2). The corresponding element in the tensor product is (1 e1 ⊗ 2 e1 + 1 e1 ⊗ 4 e2 + 3 e2 ⊗ 2 e1 + 3 e2 ⊗ 4 e2), which we simplify to (2 e1 ⊗ e1 + 4 e1 ⊗ e2 + 6 e2 ⊗ e1 + 12 e2 ⊗ e2). Therefore:

det [[1, 2], [3, 4]]
= det(1 e1 + 3 e2, 2 e1 + 4 e2)
= det(2 e1 ⊗ e1 + 4 e1 ⊗ e2 + 6 e2 ⊗ e1 + 12 e2 ⊗ e2)
= det(2 e1 ⊗ e1) + det(4 e1 ⊗ e2) + det(6 e2 ⊗ e1) + det(12 e2 ⊗ e2)
= 2 det(e1 ⊗ e1) + 4 det(e1 ⊗ e2) + 6 det(e2 ⊗ e1) + 12 det( e2 ⊗ e2)
= 2 (0) + 4 (1) + 6 (-1) + 12 (0)
= 4 - 6
= -2

Now it remains to prove that the formula for finding the parity of the permutation is valid. What my code does is essentially find the number of inversions, i.e. the places where an element on the left is bigger than an element on the right (not necessarily consecutively).

For example, in the permutation 3614572, there are 9 inversions (31, 32, 61, 64, 65, 62, 42, 52, 72), so the permutation is odd.

The justification is that each transposition (swapping two elements) either adds one inversion or takes away one inversion, swapping the parity of the number of inversions, and the parity of the permutation is the parity of the number of transpositions needed to achieve the permutation.

Therefore, in conclusion, our formula is given by:

Why it works -- non-mathy version

where σ is a permutation of n the group of all permutations on n letters, and sgn is the sign of the permutation, AKA (-1) raised to the parity of the permutation, and aij is the (ij)th entry in the matrix (i down, j across).


Generate an aperiodic integer sequence Your task is to build a piece of code that generates an aperiodic sequence of integers, either by outputting one every time it iterates, or by taking an integer n and returning the nth number in that sequence.

Now, the sequence 1, 2, 3, 4, 5, 6, ... is itself aperiodic, so I'm going to introduce a few limitations to the definition of "aperiodic" used in this problem to weed out the trivial cases:

The sequence must not be periodic modulo any integer m > 1. So a sequence like the powers of 2 would repeat 2, 4, 8, 6 all the time modulo 10, and therefore not count. (It would also repeat 0 modulo 2.)
The sequence must not become periodic after a certain number of operations - e.g. 1 2 4 8 6 2 4 8 6 ... is still considered periodic even though 1 never appears again.
The generation code must only use integers. So a piece of code that calculated the nth digit of pi (without calculating it in some integer form first) would not be acceptable.

Now, obviously every sequence performed with limited computer memory will eventually either be periodic or run out of memory, but if you can prove that your function, given infinite memory and time, will never loop back to a previous state, then it is acceptable.

The shortest code that does the above wins.

Golfscript, 2 characters
`,

(stringify (`) the number and count (,) the digits)
J, 3 characters
#q:

is the count (#) of the prime factors (q:) of its input.
The vector form involves more bookkeeping, but that's not our contestant:
#@q:L:0&.<

the first 40 terms are: 0 1 1 2 1 2 1 3 2 2 1 3 1 2 2 4 1 3 1 3 2 2 1 4 2 2 3 3 1 3 1 5 2 2 2 4 1 2 2 4
see more at OEIS
The sequence is 1 at every prime position, 2 at every prime multiple of a prime, 3 at every prime multiple of a product of two primes...

If you are not convinced this is aperiodic, here are plenty of other sequences:
##:

(the number of bits = floor of the base-2 logarithm)
+/#:

(count of 1-bits in the binary representation of the number). This (reduced under any modulus)
#b#:
+/b#:

(the same in base-b)
<.^.
>.^.
<.b^.
>.b^.

(floor or ceiling of the (natural) log - this time without stringification)
*./#:
+./b#:
*./b#:

(GCD or LCM of all base-b digits (except GCD of bits won't work))
1{#:!
9{#:!
({#:@!)

(second/tenth/nth highest bit of the factorial of n)
(=<.&.%:)

(Is the number equal its floor under the square root operation? Is the number equal the square of the floor of its square root? Is the number a square?)


Round away from zero Round away from zero

Inspired by Round towards zero.

Given a number input via any reasonable method, round the number "away from zero" - positive numbers round up, and negative numbers round down.

If you intend to take the input as a string (via STDIN, for example), you should be able to handle numbers with or without the decimal point. If you take it as a number, it should at least be able to handle floating-point precision (double precision not required) or rational numbers.

You can output a floating-point number with the decimal point (e.g. 42.0) if desired. (Or even have some test cases output floating-point and some output integer, if it makes your answer shorter.)

Standard loopholes are not allowed, etc etc.

Test cases

-99.9 => -100
-33.5 => -34
-7    => -7
-1.1  => -2
0     => 0
2.3   => 3
8     => 8
99.9  => 100
42.0  => 42
-39.0 => -39

Sandbox Link

Excel, 13 bytes

=ROUNDUP(A1,)

Alternative

=EVEN(A1*2)/2


Help me with differential calculus! I love programming and know every language, but I suck at math. Unfortunately, my school requires that computers students must take a year of calculus. There's a test next week, and I don't know any of the formulas for derivatives!

Please help me find the formulas. I need a cheat sheet - a program (as short as possible so my teacher won't notice it) that takes an expression (like 4*x^3-2) as input and outputs the derivative. (I don't care if the input and output uses command line arguments, STDIN, STDOUT, or whatever, since I'm doing all of the calculation in my head anyway.)

The test covers the following types of functions:

Constants, like -3 or 8.5
Power functions, like x^0.5 or x^-7
Exponential functions, like 0.5^x or 7^x (the base is always positive)
A constant multiplied by a  function, like 3*x^5 or -0.1*0.3^x
The sum and difference of multiple functions, like -5*x^2+10-3^x

My teacher always formats his questions in the exact same way, as shown above. He also doesn't use any fractions, numbers like pi or e, or really big numbers (bigger than 1,000). He never uses parentheses, and always shows multiplication using an asterisk (*). The only variable used is always x.

On the other hand, my teacher is pretty lenient about answers. They don't need to be simplified at all or formatted exactly as shown above, as long as it's clear what the answer is saying.

While I can use any language, remember that I can't figure out derivatives by myself. So if the program uses built-in functions to deal with equations or calculate derivatives, I won't be able to use it.

During the test, I won't have access to the Internet or any files other than the program on the cheat sheet.

Note: This scenario is entirely fictional. In real life, cheating and helping others cheat is wrong and should never be done.


The Tic Tac Toe Dictionary A TicTacToe game can be represented by a string denoting the sequence of positions as the players make their move.

0 1 2
3 4 5
6 7 8

Assume X always plays first.

So a string of "012345678" denotes the game

X O X
O X O
X O X

Notice, the game is already won when Player X marks 6, at that point the game ends, granting a win to X. (ie, ignore the remaining moves once a player wins)

Your challenge (code) is to print all the games (sorted order) and its results.

The Format

<movesequence>:<result>\n

eg:

012345678:X
012345687:X
012345768:X
...

Denote X for the 1st player winning, O for the second player, and D for Draws.

There will be 9! (362880) games.

Here is some data to verify your results.

'X' Wins: 212256
'O' Wins: 104544
Draws : 46080

This is a codegolf, and runtime should be within a minute. Have Fun!

EDIT: Removed excess details, and just print it on stdout. No need to create a file.


A simple number system Let me tell you about a simple number system. (which I made up just for this challenge)

This system contains the functions (), [], {}, and <>.

1. ()

When () is given no arguments, it evaluates to 0.

When () is given one or more arguments, it evaluates to the sum of the arguments.

2. []

When [] is given no arguments, it evaluates to -1.

When [] is given one or more arguments, it evaluates to the first argument minus the sum of the other arguments.

3. {}

When {} is given no arguments, it evaluates to 1.

When {} is given one or more arguments, it evaluates to the product of those arguments.

4. <>

When <> is given no arguments, it evaluates to 1.

When <> is given one or more arguments, it evaluates to the first argument integer divided by the product of the other arguments.

Your task

Given a string that contains a valid number (that means brackets are balanced, no division by 0s, etc.) in this simple number system, print its value.

Test cases

() -> 0
(()()) -> 0
([][]) -> -2
({}<>) -> 2
({}[]) -> 0
[] -> -1
[[][]] -> 0
[()<>] -> -1
{()} -> 0
{([]<>)} -> 0

Remember, this is code-golf, so the code with the fewest bytes wins.

Haskell, 357 306 277 251 228 224 188 185 180 bytes

A token-based parser with an explicit stack. (%) takes a token stack and a character and either pushes (opcode,defaultnumber) or (0,number) for ({[<, or pops topmost numbers and one opcode and pushes the answer for )}]>. Opcodes are encoded by a ascii enumeration hack.

Kudos to @ChristianSievers for his great answer that I borrowed some ideas from.

One-liner!

s%c|elem c"([<{",g<-div(fromEnum c)25=(g,[0,0,1,-1,1]!!g):s|(a,(o,n):b)<-span((==0).fst)s=(0,[foldr1(flip$[(+),quot,(-),(*)]!!(o-1))$snd<$>a,n]!!(0^length a)):b
snd.head.foldl(%)[]

Now with less error-handling!
Usage:

*Main> map (snd.head.foldl(%)[]) ["()","(()())","([][])","({}<>)","({}[])","[]","[[][]]","[()<>]","{()}","{([]<>)}"]
[0,0,-2,2,0,-1,0,-1,0,0]

Thanks @ChristianSievers for saving 14+3 bytes!

Thanks @Zgarb for saving some+4 bytes!


HRNG - Human Random Number Generator You know it: keyboard or mouse input is just too mainstream to create Random Numbers through human behavior.

Create the most unique (Pseudo)Random Number Generator that create its numbers through human behavior.

Web-API's are not restricted! Anyone should use the code provided, so any special hardware is restricted. (I think we can assume that everyone has a smartphone)
The number should be a 256 bit number.

Example: use the Google Map's API to get current traffic to create the Random Number.

This is a popularity-contest, so most votes wins!

Mathematica on Mac OS X

Mod[Tr /@ IntegerDigits[
  Floor[2^15 AudioData@SystemDialogInput@"RecordSound"]
, 2], 2]

Opens up a dialog box that lets you record a sound snippet through the computer's microphone, then converts the resulting digital audio data to a list of bits (roughly 50,000 bits per second of audio). Generate random numbers through white noise, singing your favorite tune, exclaiming "Serenity now!", or just yelling at the top of your lungs!


shortest code to encrypt a string Using a language of your choice write a program that takes a string as an input, and returns the string encrypted.

Algorithm:

You should assume that each character is always encoded in a byte and is ASCII-based. The extended ASCII codes are mapped to whatever is the default code page in use by the system.

You should encrypt the code in the following way:
code of first character +1, code of second character +2, code of third character +3 .....

Extended ASCII codes are based on this table:
http://www.asciitable.com/

Shortest code wins.

BrainFuck: 21
>,[+<[->+>+<<]>.>+>,]

Assumes EOF=zero
echo -n 'My secret password is 123456!' | beef encrypt.bf
==> N{#wjiym}*{mv36HJLNPR>


Golf Your Favorite Minecraft Tool In Minecraft, the default item textures are all reasonably simple 16×16 pixel images, which makes them seem ideal for golfing.

Below are simplified textures of the five "core" diamond tools in Minecraft: pickaxe, shovel, axe, sword, and hoe.

The images shown are enlarged to show their detail. Click on an image to view its correctly sized 16×16 pixel version.

To make golfing easier, I've modified each of them from the originals to only use the five same 24-bit RGB colors:

R=75 G=82 B=73 for the background.
R=51 G=235 B=203 for the diamond tool heads.
R=14 G=63 B=54 for the diamond outlines.
R=137 G=103 B=39 for the wooden handle core.
R=40 G=30 B=11 for the wooden handle outlines.

Choose your favorite tool out of the five and write a program that outputs its simplified 16×16 pixel texture in any common lossless truecolor image format (such as bpm, png, ppm, etc.).

So, for example, if you chose the axe, you would write a program that outputs this image:

No input should be taken and a web connection should not be required. The image can be output as a file with the name of your choice, or the raw image file data can be output to stdout, or you can simply display the image.

You only need to choose one of the five images. The program that outputs any one of the five images in the fewest number of bytes is the winner.

You may write programs for more than one of the images, but only the one with the minimum number of bytes counts towards your score. If there's a tie, the highest voted post wins.

If you enjoy PPCG and play Minecraft, I invite you to come join our trial Minecraft server. Just ask in the dedicated chatroom.

Minecraft 18w11a (.mcfunction), 757 bytes
fill ~ ~ ~ ~15 ~ ~15 ice
fill ~13 ~ ~13 ~7 ~ ~11 cyan_wool
fill ~12 ~ ~14 ~10 ~ ~8 cyan_wool
fill ~12 ~ ~13 ~10 ~ ~11 diamond_block
fill ~11 ~ ~12 ~9 ~ ~10 diamond_block
fill ~10 ~ ~11 ~8 ~ ~9 diamond_block
fill ~3 ~ ~4 ~1 ~ ~2 dirt
setblock ~3 ~ ~4 oak_planks
setblock ~2 ~ ~3 oak_planks
clone ~3 ~ ~4 ~1 ~ ~2 ~4 ~ ~5
setblock ~4 ~ ~5 oak_planks
setblock ~4 ~ ~7 ice
setblock ~6 ~ ~5 ice
clone ~6 ~ ~5 ~4 ~ ~7 ~7 ~ ~8
setblock ~9 ~ ~10 diamond_block
setblock ~4 ~ ~4 dirt
setblock ~3 ~ ~5 dirt
setblock ~7 ~ ~7 dirt
setblock ~6 ~ ~8 dirt
setblock ~1 ~ ~2 ice
fill ~12 ~ ~9 ~12 ~ ~8 ice
setblock ~11 ~ ~8 ice
fill ~8 ~ ~13 ~7 ~ ~13 ice
setblock ~7 ~ ~12 ice
fill ~ ~ ~ ~15 ~ ~15 light_gray_concrete replace ice
fill ~ ~ ~ ~9 ~ ~10 dark_oak_bark replace dirt

Of course someone had to answer the question with Minecraft. Place answer inside of a datapack, and run with /function <packname>:<filename>. The shovel is drawn relative to you in the +X and +Z direction. Colors are wrong but I'll count that as a language limitation ;)
But the shovel is actually made out of wood and diamonds!!!!
Output


Darts meets Codegolf I think everyone is familiar with darts, some people dont understand the scores so for those people here is a usefull link on that.

The board

A dartboard can be compared to a pie cut in 20 pieces.
Each piece is divided in 4 sections.

a small outer ring called double (points x2)
a big ring called single (points x1)
another small ring called triple (points x3)
another big ring called single (points x1)

In the middle of the board are 2 more rings, a green and red one (classic board)

Red ring, center of the board called bullseye or double bull and is good for 50 points. This one counts as a double  and because of that its allowed to checkout with it.
Green ring, called bull, single bull or simply 25 and counts as a single.

Challenge

Find all checkout possibilties with 3 darts or less.
The user can enter an integer and you will have to check if its possible to get the score to 0 with 3 darts (or fewer).

Examples

example 1:

Input: 170
Output: T20, T20, Bullseye

Example 2:

Input: 6
Output: D3;
        S3,S1,D1;
        S2,D2;
        S2,S2,D1;
        D2,D1;
        S4,D1;
        D1,D1,D1;
        S1,S1,D2;
        T1,S1,D1;

Example 3:

Input: 169
Output: No possible checkout!

Rules

Basic dart rule, you must end with a double (outer ring of the board or bullseye)
No use of external resources.
Hard coding of possible checkouts is allowed but remember this is codegolf, it wont get your code short ;)
Cells to hit will be displayed in format C+N where C = T for Triple, D for double and S for single.

bullseye can be called bullseye or DB, DBull or something simular.

Possible checkouts

To get you started, The highest possible checkout is 170.
169,168,166,165,163,162,159 are not possible in 3 darts.
The lowest possible checkout is 2.

In addition

This isnt a requirement, add in a possibility to show all possible checkouts for all scores.  Basicly because I wonder how many combinations are possible :P

Winner will be the one with the shortest code.

Happy coding.

MATLAB (299 249 241 chars)

This is my first serious golfing. My first attempt (136 chars) gives the correct result, but not with the correct formatting. It gives all possibilities looking at the number of points for each dart. This means that single 20 and double 10 do have a separate entry, however, they are both displayed as 20. Of course the last dart is always a double.

function f(x);u=[1:20 25].';y=[u;2*u; 3*u(1:end-1)];v=combvec([combnk(y,2);[y y];[zeros(62,1) y];[0 0]].',y(22:42).').';v(sum(v,2)==x,:)

In the second attempt the formatting is improved, which has of course increased the number of characters:

function f(x);h=.1;u=h+[1:20,25].';y=[u;2*u;3*u(1:20)];v=combvec([combnk(y,2);[y,y];h*ones(62,1),y];[h,h]].',y(22:42).').';t='SDT';r=@fix;strrep(arrayfun(@(x)[t(int8((x-r(x))/h)),num2str(h*r(x)/(x-r(x)))],v(sum(r(v),2)==x,:),'un',0),'S0','')

Improved from 299 to 249 characters, while at the same time even improving the output formatting. For this improved version the output for the example cases is:

f(170):

'T20'    'T20'    'D25'

f(6):

'S1'    'S3'    'D1'
'S1'    'T1'    'D1'
'S2'    'D1'    'D1'
'S2'    'S2'    'D1'
'D1'    'D1'    'D1'
''      'S4'    'D1'
''      'D2'    'D1'
'S1'    'S1'    'D2'
''      'S2'    'D2'
''      'D1'    'D2'
''      ''      'D3'

f(169):

Empty cell array: 0-by-3

Additional:

According to my calculation skills there are a grand total of 42336 possibilities to end the dart game.


Find the nearest biquadratic number A biquadratic number is a number that is the fourth power of another integer, for example: 3^4 = 3*3*3*3 = 81

Given an integer as input, output the closest biquadratic number.

Here are the first 15 double-squares:

1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000, 14641, 20736, 28561, 38416, 50625

This is code-golf so fewest bytes in each language wins

This is OEIS A000583

Python 3, 35 bytes

lambda n:int((n**.5-.75)**.5+.5)**4

Try it online!

How it works

The value n at which the output switches from (k − 1)4 to k4 satisfies √(√n − 3/4) + 1/2 = k, or n = ((k − 1/2)2 + 3/4)2 = (k2 − k + 1)2 = ((k − 1)4 + k4 + 1)/2, which is exactly the first integer that’s closer to k4.

(Works for all n ≤ 4504699340341245 = (81924 + 81934 − 7)/2 > 252, after which floating-point roundoff starts to break it, even though it works mathematically for all n.)


Find all \$k\$-smooth pairs Introduction
In number theory, we say a number is \$k\$-smooth when its prime factors are all at most \$k\$. For example, 2940 is 7-smooth because \$2940=2^2\cdot3\cdot5\cdot7^2\$.
Here, we define a \$k\$-smooth pair as two consecutive integers which both are \$k\$-smooth. An example of 7-smooth pair will be \$(4374,4375)\$ because \$4374=2\cdot3^7\$ and \$4375=5^4\cdot7\$. Fun fact: This is actually the largest 7-smooth pair.
Størmer proved in 1897 that for every \$k\$, there are only finitely many \$k\$-smooth pairs, and this fact is known as Størmer's Theorem.
Challenge
Your task is to write a program or function that, given a prime number input \$k\$, outputs or returns all \$k\$-smooth pairs without duplicate (order within the pair does not matter) in any order you want.
Please be noted that for prime numbers \$p\$ and \$q\$, assuming \$p<q\$, all \$p\$-smooth pairs are also \$q\$-smooth pairs.
Sample I/O
Input: 2
Output: (1, 2)

Input: 3
Output: (1, 2), (2, 3), (3, 4), (8, 9)

Input: 5
Output: (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (8, 9), (9, 10), (15, 16), (24, 25), (80, 81)

Input: 7
Output: (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 10), (14, 15),
        (15, 16), (20, 21), (24, 25), (27, 28), (35, 36), (48, 49), (49, 50), (63, 64),
        (80, 81), (125, 126), (224, 225), (2400, 2401), (4374, 4375)

Restriction
The program or function should theoretically terminate in finite time for all inputs. Standard loopholes are disallowed by default.
Winning Criteria
As this is a code-golf challenge, shortest valid submission for each language wins.

JavaScript (ES7),  234  232 bytes
Finds the solutions by solving Pell equations of the form \$x^2-2qy^2=1\$, where \$q\$ is a \$P\$-smooth square free number.
This is an implementation of Derrick Henry Lehmer's procedure, derived from Størmer's original procedure.
Returns an object whose keys and values describe the \$P\$-smooth pairs.

P=>[...Array(P**P)].map((_,n)=>(s=(n,i=0,k=2)=>k>P?n<2:n%k?s(n,i,k+1):s(n/k,i,k+i))(n,1)&&(_=>{for(x=1;(y=((++x*x-1)/n)**.5)%1;);(h=(x,y)=>k--&&h(X*x+n*Y*y,X*y+Y*x,x&s(x=~-x/2)&s(x+1)?r[x]=x+1:0))(X=x,Y=y,k=P<5?3:-~P/2)})(),r={})&&r

Try it online!
How?
The helper function \$s\$ tests whether a given integer \$n\$ is a \$P\$-smooth number when it's called with \$i=0\$, or a square free1 \$P\$-smooth number when it's called with \$i=1\$.
s = (
  n,
  i = 0,
  k = 2
) =>
  k > P ?
    n < 2
  :
    n % k ?
      s(n, i, k + 1)
    :
      s(n / k, i, k + i)

We look for all square free1 \$P\$-smooth numbers in \$[1..P^P-1]\$, where \$P^P\$ is used as an upper bound for \$P!\$.
P=>[...Array(P ** P)].map((_, n) => s(n, 1) && (...))

For each number \$n\$ found above, we look for the fundamental solution of the Pell equation \$x^2-ny^2=1\$:
(_ => {
  for(x = 1; (y = ((++x * x - 1) / n) ** .5) % 1;);
  ...
})()

(the above code is the non-recursive version of my answer to this other challenge)
Once the fundamental solution \$(x_1,y_1)\$ has been found, we compute the solutions \$(x_k,y_k)\$ with \$k\le max(3,(P+1)/2)\$, using the recurrence relations:
$$x_{k+1}=x_1x_k+ny_1y_k\\
y_{k+1}=x_1y_k+y_1x_k
$$
For each \$x_k\$, we test whether \$x_k\$ is odd and both \$(x_k-1)/2\$ and \$(x_k+1)/2\$ are \$P\$-smooth. If so, we store them in the object \$r\$.
( h = (x, y) =>
  k-- &&
  h(
    X * x + n * Y * y,
    X * y + Y * x,
    x &
    s(x = ~-x / 2) &
    s(x + 1) ?
      r[x] = x + 1
    :
      0
  )
)(X = x, Y = y, k = P < 5 ? 3 : -~P / 2)

1: Because it does not test the primality of the divisors, the function \$s\$ will actually be truthy for some non-square free numbers, even when it's called with \$i=1\$. The idea is to filter out most of them so that not too many useless Pell equations are solved.


How much does this Integer score? The Challenge
Given an integer, calculate its score as described below.
The score is calculated by raising each digit of the input Integer to the power n, where n denotes the index of the digit in Input (beginning with 1) when counted from left to right (the index of leftmost digit should be 1), and then summing them all together. If the original number happens to be prime, then add the largest digit of the input integer to the score, else subtract the smallest digit of the input integer from it.
Input
Your program should take an integer as input. You can take the input in whatever way you want to.
Output
Output the score of the input integer through whatever medium your programming language supports. Function return is also allowed.

Test Cases
 5328   ->  (5^1)+(3^2)+(2^3)+(8^4)-2 = 4116
 3067   ->  (3^1)+(0^2)+(6^3)+(7^4)+7 = 2627
 7      ->  (7^1)+7                   = 14

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

Mathematica, 63 bytes

s+Max@If[PrimeQ[s=Tr[d^Range@Length[d=IntegerDigits@#]]],d,-d]&

Pure function taking a positive integer as input and returning an integer. Directly performs the indicated computation, with all the long Mathematica command names that requires. Perhaps the one innovation is noticing that, if d is the list of digits of the input, then the last addition/subtraction is the same as adding Max[d] if the initial sum was prime, and adding Max[-d] if not.


Naïve Markov Chain Word Generation There are many ways to generate random words. You can take random syllables from a set, you can use n-tuples, probably neural networks (what can't they do?), alternating between consonants and vowels, etc. The method this challenge is based off of is by far the worst. It uses a Markov chain to generate random words. If you are familiar Markov chains, you probably know why this method is so terrible.

If you want to read about Markov chains, click here.

Your program will take an input one or more words and generate a single random word, through the method of a weighted Markov chain. Since that probably makes sense to no one but me, here is an explanation through the use of a picture of the Markov chain with the input of abba:

(All edge weights are the same for all pictures) Your program will output the path through a Markov chain based on the input text. As you can see, there is a 1/2 chance it will output a, 1/8 chance of aba, 1/16 chance of abba, 1/32 chance of ababa, etc.

Here are some other example Markov chains:

yabba dabba doo

wolfram

supercalifragilisticexpialidocious

If you want more examples, use this. (I worked way too hard on it)

Details of challenge:

Input can be taken as a list of strings, or as a space, comma, or newline separated string
You may assume that all the words will be entirely lowercase with no punctuation (ASCII 97-122)
You may write either a program or a function
To test, you could probably input the examples and see if all inputs line up with the Markov chains

This is code-golf, so your program is scored in bytes.

Let me know if any part of this is unclear, and I will try to make it make more sense.

Pyth, 38 32 bytes

VQJK1FZacN1k XKH]Z=KZ;WJ=JO@HJpJ

Thanks to FryAmTheEggman for 5 bytes!
To be honest I started writing Python answer when I noticed somebody posted a very similiar one so I decided to challenge myself with something new so I rewrote my answer (which was basically Pietu's answer) in Pyth.

Input is an array of strings ["Mary" , "had" , "a" , "little"]


Help! I forgot my password! Help! I just logged into Stack Exchange, but I forgot what my password is! I need a way to work it out before I log off.

Luckily, I'm an excellent hacker. Not only was I able to find my password's hash, but I also found Stack Exchange's hashing algorithm! It takes the ASCII value of each digit multiplied by that digit's place, then sums all those values together. For example:

"135" -> 1*49 + 2*51 + 3*53 = 310

I remember that my password is 3 digits long, and that each character is a number between 0 and 5 inclusive (such that it will match the regex: ^[0-5]{3}$), but that's still too many possibilities to guess. I need a program that can convert a hash back into potential passwords, but despite being an expert hacker, I can't code to save my life! I was able to write these tests out by hand though:

input -> output
288   -> 000                      // lowest possible hash
290   -> 200, 010
298   -> 022, 050, 103, 131, 212, 240, 321, 402, 430, 511
318   -> 555                      // highest possible hash

Can one of you write a program for me that will take in a hash and print all the possible passwords I could have used?

The input will always be able to produce at least one valid password. Any output format is allowed, as long as the strings can be clearly identified. I'm also not concerned about leading zeroes, so if a potential password is 001, I'll also accept 01 or 1.

Please help me from being locked out of Stack Exchange!

Scoring

This is code-golf, so the shortest answer in each language wins!

05AB1E, 9 bytes

5Ý3ãʒÇƶOQ

Try it online!

Returns list of lists of digits.


Tips for golfing in C What general tips do you have for golfing in C? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C (e.g. "remove comments" is not an answer). Please post one tip per answer. Also, please include if your tip applies to C89 and/or C99 and if it only works on certain compilers.

Use bitwise XOR to check for inequality between integers:

if(a^b) instead of if(a!=b) saves 1 character.


Grid ASCII art code golf Challenge

Create the shortest program that meets the requirements

Requirements

The code must generate a 5x5 grid of 0s, like so:

00000
00000
00000
00000
00000

The code must accept an input (column, row, character). The grid must change accordingly:

Start:

00000
00000
00000
00000
00000

Input:

(2,5,*)

Output:

0*000
00000
00000
00000
00000

(Note: the bottom-left corner is position 1,1.)
The program must return an error message other than the grid if the row/column input is not 1,2,3,4, or 5. This can be any message of your choice (as long as it's not the grid), so 0 is an acceptable error-output.
The program must work with all printable ASCII characters (of a US keyboard).

THE WINNER

The winner will be the person who has the shortest code and fulfills all requirements. If more than one answer works and has the same (shortest) length, the person who answered first will be the winner.

Dyalog APL, 17 13 10 bytes

Prompts for an enclosed array containing (row, column) and then for a character. Gives INDEX ERROR on faulty input.
⊖⍞@⎕⊢5 5⍴0

Try it online!
⊖ flip upside-down the result of
⍞ inputted-character
@ replacing the content at position
⎕ evaluated-input (enclosed row, column)
⊢ of
5 5⍴ 5×5 array of
0 zeros


Pairs with Sum divisible by 5 You will be given two integers \$M\$ and \$N\$. Find the number of pairs \$(x,y)\$ such that \$1 \le x \le M\$, \$1 \le y \le N\$ and \$(x+y)\mod5 = 0\$.
For example, if \$M = 6\$ and \$N = 12\$, pairs which satisfies such conditions are, \$(1,4), (4,1), (1,9), (2,3), (2,8), (3,2), (3,7), (3,12), (4,6), (6,4), (4,11), (5,5), (5,10), (6,9)\$
Total \$14\$.
Sample
Input : 6 12
Output: 14

Input : 11 14
Output: 31

Input : 553 29
Output: 3208

Input : 2 2
Output: 0

Input : 752486 871672
Output: 131184195318

This is a code-golf challenge so code with lowest bytes wins!
Update
Jonathan Allan's solution has the smallest code size, 5 bytes. However, it doesn't produce an answer for the last given test.
I have decided to go with the next answer with the shortest size that produces the correct answer for the largest test, there is a tie between two golfers who competed neck-to-neck.
I proudly present the winners of this challenge Lyxal and Kevin Cruijssen with only 7 bytes code! Congratulations!
As many of you, I found Arnauld's answer most helpful in finding the correct solution. So, I am accepting Arnauld's answer.
Thank you, Golfers!

Python 2, 32 bytes

lambda m,n:(m*n+abs(m%5-~n%5))/5

Try it online!

Adapts an idea from Arnauld. We estimate that \$1/5\$ of the \$mn\$ pairs will satisfy the mod-5 condition. Th actual value may be one higher depending on the mod-5 values of \$m\$ and \$n\$, and we bump up \$mn\$ a bit so that these make it pass the next multiple of 5.

34 bytes

lambda m,n:m*n/5+(0<-m%5*(-n%5)<5)

Try it online!

34 bytes

lambda m,n:m*n/5+(m*n%5+m%5+n%5)/9

Try it online!

36 bytes

lambda m,n:m*n/5+((5-m%5)*(5-n%5)<5)

Try it online!

36 bytes

lambda m,n:m*n/5+(abs(m%5+n%5*1j)>4)

Try it online!

36 bytes

lambda m,n:m*n/5+(m%5*5/4+n%5*5/4>5)

Try it online!

36 bytes

lambda m,n:m*n/5+(m%5+n%5+m*n%5/4>5)

Try it online!


Looping Random Number Generator I'm not even sure if this is even possible, but I think it's worth a shot.

The Challenge

Code/conceptualize a pseudo-random number generator that has the potential to produce results evenly spaced out with similar frequencies... with a twist. The random number generator has to 'loop' back after Foo iterations to its beginning state then produce the exact same results. Foo is a variable of all positive integers.

For example, if the iterations amount is 4 and the random numbers generated after 4 iterations are {93,5,80,13}, then the next 4 iterations will produce {93,5,80,13}, as will the next 4 after that and so on.

Limitations

Random numbers can't be pre-defined. For example, the algorithm can't simply iterate over {1,2,3,4,...int.MaxValue}, up to the iteration amount then go back to the first value.
Similar to Limitation 1, random numbers can't be cached so a set of numbers can't be generated, saved, then repeatedly returned.
Similar to Limitation 2, the random number generator can't be 'forced' back to a certain state. Beginning seed numbers and whatnot cannot be saved.
The RNG can't use the number of iterations its run.

In other words, the Generator has to arrive back at its beginning state solely through consecutive calculations.

Objective

Shortest code wins!

J

I think the simplest solution to this would be the slightly bendy

   p =: 0
   random =: 3 : '(p =: y | >: p) } ?. y # 0'

That is used like this:

   random 5
0.329284
   random 5
0.335644
   random 5
0.985972
   random 5
0.0583756
   random 5
0.038363
   random 5
0.329284

This can be easily modified to provide integers, just change the 0 to whatever value you want as a maximum. Alternatively, one might write the following code:

   p =: 0
   random =: 4 : '(p =: y | >: p) } ?. y # x'

Used like this:

   10 random 5
8
   10 random 5
6
   10 random 5
5
   10 random 5
4
   10 random 5
6
   10 random 5
8

How this works

   This uses the J primitive ?.: the statically seeded random number generator; as opposed to ?: the dynamically seeded random number generator. This makes sure the outcome is always the same when run with the same arguments. p is just a simple array pointer here, that gets incremented with every run of the function, up to a maximum of y: the left argument. Every time this code is executed, a list of y random numbers is generated (to comply with the rules). Yes, I do realize this is very much on the edge of the phrasing of the question and that it is most likely against the spirit of the question.


Find the prime factors In this task, you have to write a program, that computes the prime factors of a number. The input is a natural number 1 < n < 2^32. The output is a list of the prime factors of the number in the following format. Exponents must be omitted if they are 1. Only output prime numbers. (Assuming the input is 131784):

  131784 = 2^3 * 3 * 17^2 * 19

Using the same amount of whitespace is not required; whitespace may be inserted wherever appropriate. Your program should complete in less then 10 minutes for any input. The program with the shortest amount of characters wins.


Sum the powers that be A simple but hopefully not quite trivial challenge:

Write a program or function that adds up the kth powers dividing a number n. More specifically:

Input: two positive integers n and k (or an ordered pair of integers, etc.)
Output: the sum of all of the positive divisors of n that are kth powers of integers

For example, 11! = 39916800 has six divisors that are cubes, namely 1, 8, 27, 64, 216, and 1728. Therefore given inputs 39916800 and 3, the program should return their sum, 2044.

Other test cases:

{40320, 1} -> 159120
{40320, 2} -> 850
{40320, 3} -> 73
{40320, 4} -> 17
{40320, 5} -> 33
{40320, 6} -> 65
{40320, 7} -> 129
{40320, 8} -> 1
{46656, 1} -> 138811
{46656, 2} -> 69700
{46656, 3} -> 55261
{46656, 4} -> 1394
{46656, 5} -> 8052
{46656, 6} -> 47450
{46656, 7} -> 1
{1, [any positive integer]} -> 1

This is code golf, so the shorter your code, the better. I welcome golfed code in all kinds of different languages, even if some other language can get away with fewer bytes than yours.

05AB1E, 9 bytes

DLImDŠÖÏO

Try it online!

Explanation

Example input 46656, 3

D          # duplicate first input
           # STACK: 46656, 46656
 L         # range [1 ... first input]
           # STACK: 46656, [1 ... 46656]
  Im       # each to the power of second input
           # STACK: 46656, [1, 8, 27 ...]
    D      # duplicate
           # STACK: 46656, [1, 8, 27 ...], [1, 8, 27 ...]
     Š     # move down 2 spots on the stack
           # STACK: [1, 8, 27 ...], 46656, [1, 8, 27 ...]
      Ö    # a mod b == 0
           # STACK: [1, 8, 27 ...], [1,1,1,1,0 ...]
       Ï   # keep only items from first list which are true in second
           # STACK: [1, 8, 27, 64, 216, 729, 1728, 5832, 46656]
        O  # sum
           # OUTPUT: 55261


Most creative way to reverse a positive integer Provided an input as an unsigned integer:

13457

Your function/subroutine should return:

75431

Since this is a popularity contest, be creative. Creative solutions use unusual or clever techniques to accomplish given task.

Constraints:

You cannot use arrays.
You cannot use strings.
No RTL Override (&#8238)

Brownie points for using creative arithmetics.

Since this is a popularity contest, I suggest not using the modulo (%) operator in your code.

About Leading zeroes:

If the input is:

12340

Then the output:

4321

would be acceptable.

Mathematica, no modulo!
n = 14627;
length = Ceiling[Log[10, n]];
img = Rasterize[n, RasterSize -> 400, ImageSize -> 400];
box = Rasterize[n, "BoundingBox", RasterSize -> 400, ImageSize -> 400];
width = box[[1]]; height = box[[3]];
ToExpression[
 TextRecognize[
  ImageAssemble[
   ImageTake[img, {1, height}, #] & /@
    NestList[# - width/length &, {width - width/length, width},
     length - 1]]]]

Let's break it down.
First we use some "creative arithmetics" to find out how many digits are in the number: length = Ceiling[Log[10, n]];
Next, we Rasterize the number to a nice large image:

Now we query for the bounding box of that image, and populate the width and height (actually using the baseline offset instead of the image height, because MM adds some whitespace below the baseline in the image).
Next, NestList recursively subtracts the width of the image divided by the length of the string to enable ImageTake to pluck characters from the end of the image one by one, and those are reassembled by ImageAssemble to this image:

Then we pass that on to the TextRecognize function for optical character recognition, which at this image size and rasterization quality is able to impeccably recognize the final output and give us the integer:
72641

Logarithms and OCR - It's like chocolate and peanut butter!
New and improved
This version pads out the number to deal with the obstinate behavior of TextRecognize with small numbers, and then subtracts out the pad at the end. This even works for single-digit numbers!
Though, why you would run a reverse routine on a single number is a mystery to me. But just for the sake of completeness, I even made it work for inputs of zero and one, which would normally break because the floored log doesn't return 1 for them.
n = 1;
pad = 94949;
length = If[n == 1 || n == 0, 1, Ceiling[Log[10, n]]];
img = Rasterize[n + (pad*10^length), RasterSize -> 400,
   ImageSize -> 400];
padlength = length + 5;
box = ImageDimensions[img];
width = box[[1]]; height = box[[2]];
reversed =
  ImageResize[
   ImageAssemble[
    ImageTake[img, {1, height}, #] & /@
     NestList[# - width/padlength &, {width + 1 - width/padlength,
       width}, padlength - 1]], 200];
recognized = ToExpression[TextRecognize[reversed]];
(recognized - pad)/10^5