Read n random lines from a potentially huge file This challenge is about reading random lines from a potentially huge file without reading the whole file into memory.

Input

An integer n and the name of a text file.

Output

n lines of the text file chosen uniformly at random without replacement.

You can assume that n is in the range 1 to the number of lines in the file.

Be careful when sampling n numbers at random from the range that the answer you get is uniform. rand()%n in C is not uniform for example. Every outcome must be equally likely.

Rules and restrictions

Each line of the text file will have the same number of characters and that will be no more than 80.

Your code must not read any of the contents of text file except:

Those lines it outputs.
The first line to work out how many characters per line there are in the text file.

We can assume each character in the text file takes exactly one byte.

Line separators are assumed to be 1 byte long. Solutions may use 2 bytes long line separators only if they specify this need. You may also assume the last line is terminated by a line separator.

Your answer should be a complete program but you can specify the input in any way that is convenient.

Languages and libraries

You can use any language or library you like.

Notes

There was a concern about calculating the number of lines in the file. As nimi points out in the comments, you can infer this from the file size and the number of chars per line.

Motivation

In chat some people asked if this is really a "Do X without Y" question. I interpret this to ask if the restrictions are unusually artificial.

The task of randomly sampling lines from huge files is not uncommon and is in fact one I sometimes have to do. One way to do this is in bash:

shuf -n <num-lines>

This is however very slow for large files as it reads in the whole file.

Ruby, 104 94 92 90 bytes
File name and number of lines are passed into the command line. For example, if the program is shuffle.rb and the file name is a.txt, run ruby shuffle.rb a.txt 3 for three random lines.
-4 bytes from discovering the open syntax in Ruby instead of File.new
f=open$*[0]
puts [*0..f.size/n=f.gets.size+1].sample($*[1].to_i).map{|e|f.seek n*e;f.gets}

Also, here's a 85-byte anonymous function solution that takes a string and a number as its arguments.
->f,l{f=open f;puts [*0..f.size/n=f.gets.size+1].sample(l).map{|e|f.seek n*e;f.gets}}


Is it a Harshad Number? A Harshad number is a number that is divisible by the sum of its digits.  This is obviously dependent on what base the integer is written in.  Base 10 Harshad numbers are sequence A005349 in the OEIS.

Your Task:

Write a program or function that determines whether a given integer is a Harshad number in a given base.

Input:

A positive integer <10^9, and a base between 2 and 36, OR, a positive integer in its base, using lowercase letters for the numbers from 11-36 and a base between 2 and 36.  You only have to handle one of these options.

Output:

A truthy/falsy value indicating whether the first input is a Harshad number in the base of the second input.

Examples:

27,10 ----------> truthy
8,5 ------------> truthy
9,5 ------------> falsy
1a,12 OR 22,12 -> truthy

Scoring:

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

Jelly, 4 bytes

bSḍḷ

Try it online!

How it works

bSḍḷ  Main link. Arguments: n (integer), k (base)

b     Convert n to base k.
 S    Take the sum.
   ḷ  Left; yield n.
  ḍ   Test for divisibility.


PKCS#7 padding validation In cryptography, PKCS#7 padding is a padding scheme which adds a number of bytes N ≥ 1, where the value of each added byte is equal to N.

For example, Hello, World!, which has 13 bytes, is the following in hex:

48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21

If we choose to PKCS#7 pad to length 16, then the result is:

48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 03 03 03

And if we choose to pad to length 20, then the result is:

48 65 6C 6C 6F 2C 20 57 6F 72 6C 64 21 07 07 07 07 07 07 07

Note that in the first example we add three 03 bytes, and in the second we add seven 07 bytes.

Your task will be to validate whether a string (or integer array) has correct PKCS#7 padding. That is, if the last byte of the input string is N, then your program should check that the last N bytes of the string are equal to N.

Input

A single nonempty ASCII string containing characters between code points 1 and 127 inclusive. If you wish, you may take input as an array of integers instead.

Output

A truthy value if the input string has valid PKCS#7 padding, otherwise a falsy value.

Both functions and full programs are acceptable. This is code-golf, so the aim is to minimise the number of bytes in your code.

Test cases

The integer array version of inputs is presented here — the string version would have unprintable characters for many of the following test cases:

Truthy:

[1]
[1, 1]
[2, 1]
[2, 2]
[5, 6, 5, 3, 3, 3]
[1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2]
[95, 115, 80, 32, 71, 7, 122, 49, 13, 7, 7, 7, 7, 7, 7, 7, 7]
[27, 33, 54, 65, 97, 33, 52, 55, 60, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
[15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15]

Falsy:

[2]
[1, 2]
[5, 5, 5, 5]
[5, 6, 5, 4, 4, 4]
[3, 3, 3, 94, 3, 3]
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 127]
[50, 39, 94, 105, 49, 29, 74, 102, 2, 106, 44, 7, 7, 7, 7, 7, 7]
[26, 27, 59, 25, 122, 110, 20, 30, 114, 6, 9, 62, 121, 42, 22, 60, 33, 12]

Python, 47 34 33 bytes

lambda s:s[-1:]*s[-1]==s[-s[-1]:]

s[-1] is the last member of the list s. Checks that the last s[-1] members of the input array s are the same as an array of s[-1] repeated that many times.

Takes input as an array of integers. This is a lambda expression; to use it, assign it by prefixing lambda with f=.

Try it on Ideone!

To test:

>>> f=lambda s:s[-1:]*s[-1]==s[-s[-1]:]
>>> f([27, 33, 54, 65, 97, 33, 52, 55, 60, 1, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10])
True
>>> f([50, 39, 94, 105, 49, 29, 74, 102, 2, 106, 44, 7, 7, 7, 7, 7, 7])
False

Saved 13 bytes thanks to Leaky Nun!

Saved a byte thanks to Dennis!


Calculate prime gaps Finding primes is a programming rite of passage and very frequently the first serious program someone creates (usually with trial division).
But primes alone are already worn out. A next far more interesting thing is to get the prime gaps: the so-far-longest gaps between consecutive primes. These are quite rare and "precious". A first few pairs and their differences are:
2 3 1
3 5 2
7 11 4
23 29 6
89 97 8
113 127 14
...

My father used to calculate these by hand for fun up to 10k. Let's see how short a code you can get.
Write a program which goes through primes and produces a line of output every time the difference between two consecutive primes is bigger than that of any two previous consecutive primes.
Your output can either be the two primes followed by their gap, or just the gap.  If you choose the later add 10 to your overall score.
For instance, between 3 and 5, there is a gap 2 units wide. The gap between 5 and 7 is also 2, but that's old news, we don't care any more. Only when you see a new biggest gap, you report it. This reflects how the primes are getting less and less frequent, as the gaps become wider and wider.
Rules:

no builtin functions for prime testing, prime generation or prime gaps
no retrieving http://oeis.org/A002386 or similar (I can smell you cheaters from far away :) )
no precomputed arrays
keep printing until your internal integer type fails on you

Answers are scored in characters, plus the potential 10 penalty. With lower scores being the goal.
You can also show off versions with builtin functions if they are interesting. Be creative.

EDIT:
Most of the answers are brilliant and deserve more recognition. However, so far, a GolfScript entry with 48 characters is the shortest.

Python, 121 110 109 108 104 103 characters
p,n,m=[2],3,0
while 1:
 if all(n%x for x in p):
  c=n-p[0]
  if m<c:m=c;print(p[0],n,c)
  p=[n]+p
 n+=1

First time I tried to answer here, I hope I did it right... not sure I even counted the characters right.
Hmmm, I could save another character on the print by downgrading to Python 2.x...


Build a program to analyze coin flip sequence choices In a puzzle in an old book of mine, a game is defined in which two players choose sequences of coin flips that they believe will appear first when a coin is repeatedly flipped. (It was actually odd and even dice rolls, but this little detail doesn't matter in terms of problem equivalence.)

It is noted that if player 1 chooses TTT and player 2 chooses HTT, that player 2 has a 7/8 chance of winning the game, since the only way TTT can come before HTT is if the first three flips are all tails.

Your job is to create a program or function that will deduce the probability that one of two chosen sequences will comes first. Your program will take two lines of input (or two strings as arguments), each representing a sequence of length 10 or less:

HTT
TTT

And output the probability that the first player will win, in either fraction or decimal form:

7/8
0.875

The shortest code to do this in any language wins.

Python 3 (139 136 134 132 126 115 143)

Uses Conway's Algorithm as described at here. Handles all sequence pairs as long as the first is not a terminating subsequence of the second (as per instructions).

def f(a,b):c=lambda x,y=a:sum((x[~i:]==y[:i+1])<<i for i in range(len(x)));return 0 if b in a else(1/(1+(c(a)-c(a,b))/(c(b,b)-c(b))),1)[a in b]

Thanks xnor for shaving 6 bytes off. Thanks Zgarb for spotting a bug with subsequences.


Translate Java methods to fields So, recently, I found myself reformatting my code for Vitsy to using anonymous class instances for commands rather than the normal method approach. For those who don't know, anonymous class instance syntax looks something like this:

...
private abstract static class SomeClass {
    public abstract void someMethod();
}

public final SomeClass someField = new Command() {
    public void someMethod() {
        // Some implementation
    }
};
...

So what's your job, I hear you asking? Well, it's quite simple.

The Challenge

Given a class name, its inner method, and string of zero to many conventional methods, turn them into anonymous class instances, retaining the program instructions therein. For formatting purposes, I have labelled the input and output below for what must be considered (anything in <> needs to be retained in the output).

Conventional method syntax

<visibility modifier> void <method name>(){<implementation>}

Resulting instance declaration

<visibility modifier> final <class name> <method name>=new <class name>(){public void <inner method name>(){<implementation>}};

The Rules

You may not use any builtins for this challenge (if there are builtins for this, the lang creators have done a bad and they should feel bad).
You must retain the method name, the visibility modifier (public, private, (nothing), protected) and the implementation.
Do not worry about proper tabs/formatting. As long as it is Java compile-able, you're fine.
You may assume that all code inside of <implementation> is valid.
You may assume that there is nothing but methods in the string given.
Do not translate any methods that are not void.
Do not translate any methods with a parameter.
Input may be in any convenient format for your language.

Examples

>>> toAnonymousClass("ClassName", "innerMethod", "public void method1(){}")
public final ClassName method1=new ClassName(){public void innerMethod(){}};

>>> toAnonymousClass("ClassName2", "secondInnerMethod", "private void method2(){return;}protected int method3(){return 4;/*guaranteed to be random*/}")
private final ClassName2 method2=new ClassName2(){public void secondInnerMethod(){return;}};protected int method3(){return 4;/*guaranteed to be random*/}

Note here that the void method is translated with the visibility modifier (private) retained, but the int method is not translated as it has a different return type (int).

>>> toAnonymousClass("Clazz", "inMethod", "void method4(int param){}")
void method4(int param){}

method4 is not translated, as it accepts a parameter (int param).

>>> toAnonymousClass("Moar", "again", "void method5(){}")
final Moar method5=new Moar(){public void again(){}};

Another example of visibility modifier retainment - if it has no modifier, have no modifier on the output.

Finally, the big test case:

>>> toAnonymousClass("Hi", "rand", "private void method2(){return;}protected int method3(){return 4;/*guaranteed to be random*/}public void method1(){}void method4(int param){}void method5(){}")
private final Hi method2=new Hi(){public void rand(){return;}};protected int method3(){return 4;/*guaranteed to be random*/}public final Hi method1=new Hi(){public void rand(){}};void method4(int param){}final Hi method5=new Hi(){public void rand(){}};

Retina, 95 bytes

Byte count assumes ISO 8859-1 encoding.

+`^((.+)¶(.+)¶(.+¶)*)(\w+ )?(void )(\w+)(..{.*})
$1$5final $2 $7=new $2(){public $6$3$8};
\w+¶

The code contains a trailing newline.

Takes input separated by newlines. Class name on the first line, inner method name on the second line, methods on following lines.
For example:

Hi
rand
private void method2(){return;}
protected int method3(){return 4;/*guaranteed to be random*/}
public void method1(){}
void method4(int param){}
void method5(){}

Try it online!


Printing ascending ASCII, Cops This is the cops' thread. The robbers' thread goes here.

Write a program or function consisting only of printable ASCII characters (that excludes tab and newline) that outputs at least 5 printable ASCII characters in ascending order (from space to tilde / 32 to 126). Characters can be outputted several times, as long as they are adjacent to each other. A single trailing newline is accepted. You must provide the full output, and for every 6 characters in your code you must provide one character in your code, at the position it appears. If your code has 5 or less characters, then you have to reveal only the length. You shall not reveal more than 1 character per 6 in your code.

So if your code alphaprinter outputs the alphabet from a-z, then you need to reveal 2 characters of your code (use underscore for the others), for instance:

al__________  // or
__p__p______  // or
__________er

Rules / specifications:

You cannot append trailing white spaces that doesn't have a function.
You can not use comments (but the robbers can use comments when cracking the code)
Built-in cryptographic primitives (includes any rng, encryption, decryption, and hash) aren't allowed.
In languages where the default output are like in MATLAB: ans =, then that's accepted, as long as it's clearly stated and shown that ans = is outputted. It should also be clearly stated whether this is part of the "ascending output" or not.
The output must be deterministic
Using a non-free language is not accepted
The output doesn't have to be consecutive characters. Both abcde and abcdg are valid outputs.
The characters do not need to be distinct as long as the output contains at least 5 characters. aaaaa and aaacc are valid.
Answers that assumes a REPL environment are not considered to be valid programs or functions and are therefore not allowed.
STDERR is not considered valid output, but data may written to STDERR.

If the revealed characters are underscores, then you must identify it as shown below.
In this case, the second and sixth character are revealed underscores, while the others are unknown.

_____________
 |   |

Note: The robbers only need to find a code that produces the same output. The language, the length of the robbers solution, and the position of the revealed characters must also match.

Your score is the number of characters in your code. The winner will be the submission with the lowest score that hasn't been cracked in 7 days.
Only submissions that are posted in 2015 (UTC) are eligible for the win. Submissions that are posted later than this are welcome, but can not win.

In order to claim the win you need to reveal the full code (after 7 days).

Your post should be formatted like this (nn is the number of characters):

Language, nn characters

Output:

abcdefghijklmnopqrstuvwxyz

Code (12 characters):

al__________

If the code is cracked, insert [Cracked](link to cracker) in the header.
If the submission is safe, insert "Safe" in the header and reveal the full code in your answer. Only answers that have revealed the full code will be eligible for the win.

Perl, 46 characters (safe)

Output:

((()))*++,---../00011123445556667779::;;<<==??@@AAACEFGHHHIKKMMNOOOPPQQQRRSSSVWXXYY[[[\]]]^^^```aaeeffggghjjjnpppqqrttuwxxyzz{{{

Code:

print _______________________________________;

I somehow managed to delete the original in the space of a week, but I think this is right:

   print chr()x(($i=($i*41+7)%97)&3)for(40..123);


Watch 'em fall like dominoes You live inside a terminal that is 80 characters wide. You are bored, so you decide to play dominoes. No, not the boring kind that look like Scrabble, the fun kind where you spend an hour setting them to watch them fall in a second.

In terminals, dominoes look like this:

|   upright domino
\   left-tilted domino
/   right-tilted domino
__  fallen domino

As we all know, if a tilted domino touches an upright one, the second domino gets tilted as well. The only exception to this is if two tilted dominoes touch it:

|\ --> \\        /| --> //        /|\ --> /|\

Adjust your terminal's gravitational constant so this transition takes 100 ms.

If a tilted domino is supported by another domino or the terminal's walls, its journey ends.

None of the tilted dominoes in

\||||____||||/__                /|\    /\    /|\                __\||||____||||/

(80 characters) will move, since the two outmost tilted dominoes are supported by the terminal's walls and all others are supported by other dominoes.

However, if the space in the tilting direction is empty, the domino falls down:

| \\ --> |__\        // | --> /__|

Terminal. Gravitational constant. You get the point…

Finally, there's a slight wind from the left, so right-tilted dominoes fall faster than left-tilted ones:

|/ \| --> |__\|

Task

Write a program/function that shows an animation of playing dominoes in a terminal.

Your code should do the following:

Read a string from input, representing the initial state of the dominoes.

This string will contain no more than 80 characters and consist solely of the dominoes described above and empty spaces.
Print the state and wait for 100 ms.
Transform the state as explained above.
If the state changed, go back to 2.

Additional rules

The length of the input string does not affect the terminal's width; even if the string is shorter than 80 characters, the walls of the terminal are still 80 characters apart.
Each time step 2 is executed, the state should get printed to the same location, overwriting the previous state.
Since some languages are incapable of waiting exactly 100 ms, feel free to wait any amount between 50 and 1000 ms.
Standard code-golf rules apply.

Examples

For the initial state

 ||\/||

print the following (one over the other):

 ||\/||
 |\\//|
 \\\///
__\\//__

For the initial state

/||||\

print the following

/||||\
//||\\
///\\\

For the initial state

/|||\

print the following

/|||\
//|\\

For the initial state

|/ \|/ \|/ \|/ \|

print the following:

|__\|__\|__\|__\|

For the initial state (80 characters)

\||||____||||/__                /|\    /\    /|\                __\||||____||||/

print the following

\||||____||||/__                /|\    /\    /|\                __\||||____||||/

Retina, 87 86 85 bytes

Thanks to Dennis for saving 1 byte.

^.{0,79}$
$0
:`^
<ESC>c
(`/ | \\
__
/\|(?!\\)
//a
(?<!/)\|\\
\\
$
aaaaa
a
aaaa
(a+)+b|a
<empty>

<ESC> should be replaced by the actual control character (0x1B). <empty> represents an empty trailing line. You can then run the above code from a single file with the -s flag.

The code requires a terminal which supports ANSI escape codes. I can't suppress the line feed in Retina's output so I need to clear the entire console with <ESC>c each time. I've tested the code in bash using Mono to run Retina.

Explanation

^.{0,79}$
$0

We start by appending a space if the input contains fewer than 80 characters. This is so that a / at the right end does not have to be treated separately.

:`^
<ESC>c

Now we prepend <ESC>c to the string, which is the ANSI escape code for clearing the terminal. So every time the string is printed it will do so at the top of the terminal. The :` instructs Retina to print out the result of this substitution, i.e. the initial configuration.

(`/ | \\
__

(` begins a loop. Since there is no matching ), the loop is assumed to go until the last stage of the program. Each iteration will simulate one step of the dominoes falling and then "sleep" a bit. This first stage replaces / and \ next to a space into __. This automatically handles the / \ case correctly, because matches cannot overlap and are searched for from left to right. So the /<sp> would be matched and turned into __ such that the \ can't be matched, and we get the correct __\.

/\|(?!\\)
//a

This turns /| into // provided there's no \ next to it. We append an a such that this new / doesn't mess with the next stage (which shouldn't "know" about this change yet).

(?<!/)\|\\
\\

The opposite situation: turn |\ into \\ provided there's no / next to it. We don't need to put an a here, because we're done with this step of the simulation.

Now the sleeping part...

$
aaaaa

Appends 5 more as to the end of the code.

a
aaaa

Turns each a into 4 as, so we get 20 as at the end.

(a+)+b|a
<empty>

Now the fun part... we sleep for a bit with the help of catastrophic backtracking. There is an exponential amount of ways to split up a match of (a+)+ between repetitions of the group. Because the b causes the match to fail, the engine will backtrack and try every single one of those combinations before deciding that (a+)+b can't match. For the twenty as at the end that takes something like half a second.

At the same time, we allow the regex to match a single a, but only after doing the backtracking. When that matches, we replace it with an empty string, removing all the as we inserted for one reason or another from the string.

That leaves printing the string at the end of the loop iteration. Here it comes in handy that I haven't fixed the printing behaviour of loops in Retina yet. Currently, there is only one flag for each stage, which says "print" or "don't print". The default is "don't print" except for the last stage in the program, which defaults to "print". But the stage is looped, so that means it actually prints the current string on each iteration. Normally, that is really annoying, and you almost always need to include an additional empty stage at the end if you only want the final result, but here it lets me save four bytes.


Output and sourcecode lineup General constraints:

Your program should not take any input.
Your program should output words, 1 word/line.
Only capital letters (A-Z) in the output.
A word must be atleast 2 letters in length.
A word can never be a palindrome. That is forbidden.

Rules for word-manipulations, one or more of these operations in any individual order for each new line:

Change one or more letter(-s) in the word 1 char distance (example: A->B, F->E) from the previous word. 'A' can not be 'Z' and 'Z' can not be 'A'.
Insert the letter "A" at any position.
Remove any letter at any position.

Output validation:

Your program must output the following words: OUTPUT, YOUR, SOURCECODE, TODAY atleast (but not limited to) once each, in any order.

Sourcecode validation:

The first and the last letter of all output words should also be part of your sourcecode in the same order as scopes: first and last letter for the first word has the highest scope, example pseudo-code:

<any or no code><first letter, first word>
<any or no code><first letter, second word>
<any or no code><,...              ...,><any or no code>
<last letter, second word><any or no code>
<last letter, first word><any or no code>

For any word # where the actual word number is a fibonacci-number, the first and last letters must be lower-case in the sourcecode.
For any word # where the actual word number is not a fibonacci-number, the first and last letters must be upper-case in the sourcecode.

There is no restriction of the actual letters in the sourcecode, they can be inside strings or part of a command or anything, it is only the order that counts.

Example valid output (only the words YOUR and TODAY in the example):

YOUR
XOUAS
WOAAT
VOBAU
UOCAV
TODAW
TODAX
TODAY

Example valid sourcecode for the above output:

Since words 1, 2, 3, 5 and 8 in the example output is "fibonacci words", their first and last letter-representation in the sourcecode is lower case, leaving us with this constraint on the sourcecode:

yxwVuTTtyXWvUtsr

There could be any code around or between the letters in the sourcecode as long as the representation is there somewhere in that order.

This is code-golf, smallest sourcecode size in counted bytes wins. Competition ends: 2014-02-31.

Java, 1091 1039 bytes
Probably not very good, but I'll give it a try. (Formatting worse will give less Bytes, but for now, let's leave it)
edit 1: used names for Vars to make comment shorter.
public class t {
public static void main(String[] V){
    StringBuilder w = new StringBuilder("SOURCECODE");
    X(w);
    for(int Y=0; Y<6; Y++){
        w.deleteCharAt(4);
        w.setCharAt(0,(char)(w.charAt(0)+1));
        X(w);
    }
    w.deleteCharAt(0);
    for(int o=0;o<2;o++){
        w.setCharAt(2,(char)(w.charAt(2)+1));
        w.append('A');
        w.append('A');
        X(w);}
    for(int O=0;O<20;O++){
        if (O<15) w.setCharAt(3,(char)(w.charAt(3)+1));
        w.setCharAt(4,(char)(w.charAt(4)+1));
        if (O<19) w.setCharAt(5,(char)(w.charAt(5)+1));
        X(w);}
    w.deleteCharAt(6);
    X(w);//o
    for(int O=0;O<6;O++){
        if (O<5) w.setCharAt(0,(char)(w.charAt(0)+1));
        w.setCharAt(1,(char)(w.charAt(1)-1));
        X(w);}
    for(int O=1;O<4;O++){
    w.deleteCharAt(2);//o
    if (O<3) w.insert(4, 'A');
    X(w);}
    for(int O=0;O<5;O++){
        if (O<3) w.setCharAt(2,(char)(w.charAt(2)+1));
        w.setCharAt(4,(char)(w.charAt(4)+1));
        X(w);}
    //OOOOPQRsTTTTTTTTTT
    //yxwVuTTtTTTTtTTAAAAAaAAAAAAAAAAAAaAAREEEEEEE
}
static void X(StringBuilder b){System.out.println(b.toString());}}

outputs:
SOURCECODE
TOURECODE
UOURCODE
VOURODE
WOURDE
XOURE
YOUR
OUSAA
OUTAAAA
OUTBBBA
OUTCCCA
OUTDDDA
OUTEEEA
OUTFFFA
OUTGGGA
OUTHHHA
OUTIIIA
OUTJJJA
OUTKKKA
OUTLLLA
OUTMMMA
OUTNNNA
OUTOOOA
OUTPPPA
OUTPQQA
OUTPRRA
OUTPSSA
OUTPTTA
OUTPUTA
OUTPUT
PTTPUT
QSTPUT
RRTPUT
SQTPUT
TPTPUT
TOTPUT
TOPUAT
TOUAAT
TOAAT
TOBAU
TOCAV
TODAW
TODAX
TODAY


The Curious Case of Steve Ballmer Steve Ballmer is the ex-CEO of Microsoft, and in a recent article, claimed that he "still does not know what he did wrong with mobile".

As CodeProject's newsletter pointed out, "That article's title could be ended at so many spots and still be accurate".

Given no input, output the following:

Steve Ballmer still does not know.
Steve Ballmer still does not know what he did.
Steve Ballmer still does not know what he did wrong.
Steve Ballmer still does not know what he did wrong with mobile.

This must be outputted exactly as shown, and must be the only output of your program. You may include a single trailing newline.

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

Python 3, 100 99 99 97 bytes

-1 byte thanks to ovs
-1 byte thanks to Jonathan Allan
-1 byte thanks to Dennis

for i in b'!-3?':print('Steve Ballmer still does not know what he did wrong with mobile'[:i]+'.')

Try it online!


Swaps to Sort an Array You are given an array \$A\$, which may contain duplicate elements. In each swap, you may swap the value of any two indices \$i, j\$ (i.e. switch the values of \$A_i\$ and \$A_j\$). What is the least amount of swaps needed to sort the array, and what are the corresponding swapped indices?

Scoring

This is code-golf, so shortest code wins. However, your program must terminate in reasonable time (less than 10 seconds) for any array \$A\$ with less than 1000 elements.

Input

The array \$A\$, in any necessary form.

Output

A list of swaps, with each swap being a pair of numbers, in sequential order - first pair in list is swapped first, in any necessary form.
In the output, the numbers should all represent indices. You may output the answer either one-indexed or zero-indexed, but my samples will use one-indexing.
The answer might not be unique. However, your answer should still have the same length as the optimal sequence of swaps.

Test cases

[4,3,2,1] => [(1,4),(2,3)]
[1,3,2,3] => [(2,3)]
[1,2,1,3,2,3] => [(2,3),(4,5)]
[1,2,3,4] => []
[4,2,5,1,3,3] => [(2,6),(1,5),(1,4),(2,3)]

J, 126 bytes

[:>[:{:"1@}./:~(({.@I.@:~:>@{.)({:@](|.@:{`[`]}~;])[,[:(0{*/,&I.{.)(<0{i.@$)*"1{"0 1=|.@])(,:>@{.))^:(-.@-:>@{.)^:a:;&(0 2$'')

Try it online!

Here is the same code in a more procedural form, if you're looking for an explanation of algorithm.

f=. 3 :0
sorting=.y NB. copy of input we'll mutate
sorted=./:~y
swaps=.0 2$''
for_j. i.#y do.
  correct=.j{sorted
  cur=.j{sorting
  if. cur = correct do.
    continue.
  end.
  NB. correctly fill the current idx j
  valid_idxs=.(j<i.#sorting)
  good_j=. valid_idxs * correct = sorting
  NB. will any of these be the correct desitnation for the current elm?
  good_dest=. valid_idxs * cur = sorted
  both=.good_j * good_dest
  use=.(1 e.both) { good_j ,: both
  swap_with=. {.I.use
  swaps=.swaps,(j, swap_with)
  sorting=.(sorting {~ swap_with, j) (j, swap_with)} sorting
end.
swaps
)

Try it online!

original answer, doesn't work for repeats

J, 18 bytes

[:;(2]\])&.>@C.@/:

Try it online!

NOTE: Thanks to Neil for pointing out this currently fails on the test case 4 5 2 1 3 3.

/: Grade up, ie, return the permutation that puts the list into order
C.@ Convert that to cyclic permutation form, which uses boxes
&.> For each of those boxed lists, ie, permutation cycles...
(2]\]) Return all consecutive pairs of two elements.  This gives us the swaps, and it works because J gives the cycle list in descending order.
[:; raze the list of boxes.  This gives us all the swap pairs as a single list of pairs, ie, an N x 2 matrix.


Group adjacent values The task is to group adjacent values from collection and output it as a new aggregated collection.

Consider we have following input:

Sequence
Number      Value
========    =====
1           9
2           9
3           15
4           15
5           15
6           30
7           9

The aim is to enumerate over Sequence Numbers and check if the next element has the same value. If yes, values are aggregated and so, desired output is as following:

Sequence    Sequence
Number      Number
From        To          Value
========    ========    =====
1           2           9
3           5           15
6           6           30
7           7           9

Build a code with following assumptions:

Sequence Numbers are already ordered in input table.
There can be gaps in Sequence Numbers. If input contains gaps, output should contain gaps too. For example input 1 99\n2 99\n4 99\n6 99, output will be 1 2 99\n4 4 99\n6 6 99.
Assume Value is type of integer.
It can be a full program or just a function.
This cruft (Sequence Sequence\n ... ======== ======== =====\n) is not a part of output. Output format is not defined; there should be a delimeter between values and between rows, so anyone can distinguish values and rows.

It's an extend of my StackOverflow question: https://stackoverflow.com/questions/14879197/linq-query-data-aggregation.

K, 43 38

{d:(x;0N,x;y)@\:&~~':y;d[1]:(1_d 1),*|x;+d}

{a::*|x;+@[(x;{x,a};y)@\:&~~':y;1;1_]}

.

k){a::*|x;+@[(x;{x,a};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 2 9
3 5 15
6 6 30
7 7 9

Explanation

The function takes two vectors, x and y, as input

a::*|x takes the last value of x and assigns it to a.

&~~':y returns a list of indices where the y vector changes:

k){&~~':y}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
0 2 5 6

(x;{x,a};y) creates a three element list containing

1) the x vector,

2) the function {x,a} which takes an input variable x(not to be confused with the x vector which was input into the original function) and appends a, and

3) the y vector

(x;{x,a};y)@\:&~~':y takes this three element list and applies the indices to each element
so that we return the x vector at those indices, the indices with a appended, and the y vector at those indices

k){b::*|x;(x;{x,b};y)@\:&~~':y}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 3 6 7
0 2 5 6 7
9 15 30 9

@[(x;{x,a};y)@\:&~~':y;1;1_] takes the matrix we've created and drops the first element of the second row.

k){b::*|x;@[(x;{x,b};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 3  6  7
2 5  6  7
9 15 30 9

+ then transposes the result

k){b::*|x;+@[(x;{x,b};y)@\:&~~':y;1;1_]}[1 2 3 4 5 6 7;9 9 15 15 15 30 9]
1 2 9
3 5 15
6 6 30
7 7 9


sort and restore a set of bytes in optimal form Challenge

For any given input Y of length >= 1024 bytes:

sort in ascending or descending order -- your choice
generate output Q, where Q = [sorted data] + [restore
information]
restore Y using Q as input

Sorting Example

 input: [2, 5, 119, 0, 1, 223, 0, 118, ...]
output: [0, 0, 1, 2, 5, 118, 119, 223, ...] + [restore information]

Restore Example

 input: [0, 0, 1, 2, 5, 118, 119, 223, ...] + [restore information]
output: [2, 5, 119, 0, 1, 223, 0, 118, ...]

Winning

The program that generates the least amount of information in order to restore to original state wins, however it must work within a reasonable amount of time on modern hardware, less than 10 minutes.

UPDATE 1

You may use any third party libraries that are open-source if you so desire.

UPDATE 2

The [restore information] size is measured in bytes, it's your choice what it contains.

UPDATE 3

In case it's not yet clear, the input Y is a stream of bytes, you shouldn't care what it contains, all you care is to sort the values of the bytes in the order you prefer while also generating the necessary data in order to restore to Y from Q.

Python

The restore information is just the original list.  n bytes of restore information for an n byte list.

def sort(Y):
  return (sorted(Y), Y)

def restore(Q):
  return Q[1]


05AB1E, 63 52 50 bytes

Specialization formula

Îƒ0NU62201122vyÍ¹Ì°*8X*N>+÷+}16Xm÷+DX>£X__iÀ'.ìÁ},

Try it online!

BBP formula

ƒ4¹>°UX*8N*©>÷YX*®4+÷-1X*®5+÷-1X*®6+÷-1X*16Nm÷*ODN>£N__iÀ'.ìÁ},

Try it online!


Sum It Up with a Digital Triangle Well, sum it down really.

Write a program or function that takes in a nonempty list of decimal integers (0-9) and outputs a downward pointing "triangle" of digits with the input list at the top where every digit after the first line is the sum of the two digits above it modulo 10.

For example, the input [7, 5, 0, 9] has output

7 5 0 9
 2 5 9
  7 4
   1

because 2 is (7 + 5) mod 10, 5 is (5 + 0) mod 10, 9 is (0 + 9) mod 10, etc. all the way to 1 being (7 + 4) mod 10.

If the list has only one item, then the output matches the input; e.g. an input of [4] will yield

4

Here are some additional examples:

[0]

0

[1, 2]

1 2
 3

[8, 7]

8 7
 5

[0, 0]

0 0
 0

[1, 4, 2]

1 4 2
 5 6
  1

[0, 1, 0]

0 1 0
 1 1
  2

[1, 0, 0, 0]

1 0 0 0
 1 0 0
  1 0
   1

[1, 2, 3, 4]

1 2 3 4
 3 5 7
  8 2
   0

[1, 2, 3, 5, 8]

1 2 3 5 8
 3 5 8 3
  8 3 1
   1 4
    5

[9, 2, 4, 5, 3, 2, 2]

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

Note that in the output:

The first line does not have leading spaces.
Each subsequent line has one more leading space than the line previous.
Digits are separated by a single space.
Each line is allowed to have up to one trailing space.
There may be a single optional trailing newline.
You must use the characters for normal decimal digits (0 through 9).

The shortest code in bytes wins. Tiebreaker is earlier answer.

BrainF**k, 396 391 bytes

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

I couldn't resist the temptation to do this one. At least the triangle is pointy-side down.

Input comes in as a string of numeric characters followed by a single newline.

Output will contain a single trailing space on every line.

Examples:

$ bf sd.bf
010
0 1 0
 1 1
  2

$ bf sd.bf
123456
1 2 3 4 5 6
 3 5 7 9 1
  8 2 6 0
   0 8 6
    8 4
     2

$ bf sd.bf
9245322
9 2 4 5 3 2 2
 1 6 9 8 5 4
  7 5 7 3 9
   2 2 0 2
    4 2 2
     6 4
      0

Explanation

Since it's rather difficult to explain the code from a functional perspective, we can instead look at it from the perspective of the state of the tape at various times. The core idea here is that the triangle we output is initialized as a tightly-packed (for BF, anyway) array that shrinks in size by 1 every iteration of a loop. Another important thought is that we use 255 to indicate a "placeholder" that we can search for on the tape.

Initialization

This is the easiest step. At the start of the program, we execute the following:

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

This forces the tape into the following state (where >N< indicates the location of the pointer on the tape)

[ 0 1 32 255 >0< 0 0 ...]

The first number here is a "buffer" location. We're not going to use it on a long-term basis, but it's useful to make little operations simpler and for copying data around.
The second number is the number of spaces that we'll be outputting at the start of each line, starting after the first line. The first line will have no leading spaces.
The third number is the space character we output.
The fourth number is a placeholder 255, so that we can get back to this position relatively easily.

Input

From this position, we will read in all of the characters. At the end of this step, we hope to be in the following situation:

[ 0 1 32 255 a b c d e f ... >255< 0 0 ... ]

Where a b c d e f ... indicates the string of numeric characters that was input (not the newline).

We accomplish this with the following:

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

There are some nuances to this. First of all, we will output each character as we get them, and then output a space after it. Secondly, we don't want to copy the ASCII value to the tape, we want to copy the actual numeric digit. Third, we want to stop when we hit a newline and leave ourselves in a good place at that time.
Say our input is 6723. Then, upon reading the first 6, our tape looks like this:

[ 0 1 32 255 >54< 0 0 ...]

We check that this value is not equal to 10 (an ASCII newline) with ,----------[++++++++++. We then print out the value and continue by simultaneously subtracting 48 from the input value and adding 32 to the value next to it (>>++++++++[-<++++<------>>]<), leaving us here:

[ 0 1 32 255 6 >32< 0 ...]

Notice how throughout this process we can assume that all digits to the right of our input are 0--this means that we're not in danger of ruining any previous state if we use values to the right to calculate 6 * 8 and 4 * 8.
Now we output the space character we just generated, and take in a new input, deleting the space we calculated there. Eventually, the input will be terminated by a new line and the loop will exit, leaving a 255 where the newline would have been (,----------]-). This is the second placeholder character we will use to navigate the tape. At this point in our scenario, our tape is exactly this:

[ 0 1 32 255 6 7 2 3 >255< 0 0 ... ]

Calculation

The way this works is that the list of digits between our 255 placeholders is going to shrink by one every iteration of the loop. When it only has 1 digit left in it, we're done and should halt immediately (Note that, at this point, every digit in that list has already been output, so we don't have to worry about outputting it again).

We now use this trick to navigate to the first 255 placeholder: <+[-<+]-. This effectively searches the tape to the left for a 255, changing nothing in between. Now that we've moved the pointer, we can check our exit condition: if there's only one digit in the list, then the cell two spaces to the right will hold 255. Thus, we check against that and start a loop: >>+[-<<

The first step in our loop is to output a newline. So we move to the first cell (our buffer cell), add 10 to it and output. The next step is to output all leading space characters. After outputting them, we increment our count for number of leading spaces. These steps are accomplished by the following:

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

Which leaves us in this state:

[ 0 2 32 255 >6< 7 2 3 255 0 0 0 0 0 0 ]

Our next step is to copy the first value in the list over, past the second placeholder 255:

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

We essentially do this by hopping back and forth between our placeholder 255s, leaving us here:

[ 0 2 32 255 >0< 7 2 3 255 0 6 0 0 ... ]

We now start a loop, iterating through the rest of the list, stopping when we hit 255 : >+[-<

At this point, the digit to our immediate left is always 0. So, because we love them, we pop a placeholder 255 in there so that we can come back to our place in the list. The next step is to move the second place in the list to locations surrounding where we moved the first place to, past the second placeholder 255. These steps are accomplished by the following:

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

Leaving us here: [ 0 2 32 255 255 >0< 2 3 255 7 6 7 0 ]
Now, both the 6 and 7 have been moved to a location where the calculation can occur. We need two copies of the 7 because the next number in the list will need it as well. The 7 immediately after the 255 serves this purpose, whereas the other 7 will be consumed by the calculation.

First, we add the two digits:

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

Leaving us here:

[ 0 2 32 255 0 255 2 3 255 7 0 >13< 0 ]

The next combination of steps is the most complicated. We need to see if the number we're pointing to is larger than 10, and if it is, we subtract 10. In reality, what we do is we subtract 10 from it and see if it hits 0 at any point in the subtraction. If it does, we add 10 back on later. At the end of this, we should have the sum modulo 10.

Prepare a 10 to the right
+>++++++++++
Leave yet another 255 for a loop condition later
>>-<<
If the number is greater than 10 end up one space to the left
else one space to the right
[-<-[>>]<]<->
Check if the previous 255 is two spaces to the right and if it is
add 10 back to our sum--we've subtracted too much
>>+[-<<<+>>>[-<->]<+++++++++>>>+]

At this point, we've accomplished the goal. We have the sum modulo 10!
Also, whether or not the number was greater than 10, we'll end up here:

[ 0 2 32 255 0 255 2 3 255 7 0 3 0 0 >0< ]

Our next goals are to output this new sum, follow it with a space, and inject it back into our list. We do this all with our previous techniques of 255-hopping and adding 48 to our sum, so I won't cover it in detail.

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

And we're here: [ 0 2 32 255 3 255 2 3 255 7 0 0 51 >32< ]
Notice how we put an additional 255 placeholder after our newly-injected 3 so that we don't lose place in the list. At this point, we have output our sum and its space, so we need to clean up and revert to a state where the next iteration of this loop is going to work. We need to clear out our 51 and 32 cells, move the 7 once to the right, and navigate to our list placeholder so that we can start over.

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

Now, we're here: [ 0 2 32 255 3 >0< 2 3 255 0 7 0 ... ]
Which is exactly where we want to be for our next iteration. So check for 255 and move on! (>+])

When we get dropped off from the loop, we're going to have a whole new list--made up of the sums from the previous list. The first time, it'll look like this:

 [ 0 2 32 255 3 9 5 0 >0< ]

Now we want to repeat that whole process on our new list, so we plop a 255 down to the left and start all over! We need to do a little bit of cleanup with >>[-]<<, and then drop our placeholder with <-. After that, we're in exactly the same place as we were after input, so we can get away with doing the same checks: <+[-<+]->>+, and boom! We've got our full loop! All we need is the closing bracket, and when it ends we've already output everything, so we're done: ].


Unholy Grail Layout (Reverse Holy Grail Layout) The Holy Grail Layout in CSS, is a full height, 3 column layout which consists of a fluid central column, and two side columns with fixed widths.

Your Task is Simple!

Reverse it, make a fixed width central column, and two fluid width columns to the sides. The point is for them to take All available space both vertically and horizontally. So if one adds elements above, or elements below (assume 100% width), your solution should shrink to accommodate. Same goes with elements on the sides. Your layout should fill 100% of its container's space.

Restrictions

HTML and CSS only (no JavaScript)
IE8+ support mandatory
Must work in all major browsers (it is, after all, a layout!)
HTML and CSS must both be valid.
No tables, it's supposed to be a layout, not an abomination.

Winner

Code with fewest characters wins, excess spaces and newlines do not count, don't be afraid to be readable! (I'm running the solution through a minifier)

Good luck!

Simple

L

R

C

Who said that it needs to be valid html?
Who said that I need a doctype?


Noah's (upgraded) ark As preparation for the nth Exodus, Noah decides to write a program that will decide If he will let animals on his ark.  However, Noah wants to go back to grass roots. Thus he decides that the program should be as small and as simple as possible.
GOAL:
Recreate the Contrabulous Choosematron, in a way that follows evangelical stories.
INPUT:
The program is simple, and elegant, and takes in 2 inputs:
The species of animal [String]
and The animal's gender [boolean]
OUTPUT:
The program then puts out Either 'Y' or 'N', Which determines whether or not the given  animal is allowed onto the ark.
RULES:
Only one Animal of each species and gender is allowed on the ark. No more.
Your output can be any set of boolean values (true false, yes no, y n, yin yang) so long as they're easily distinguishable.
If your program should want to accept a list of input, rather than use STDIN, that's fine. However, each output has to be in corresponding order of the input (FIFO), as well as be in the exact same format as the input.
This is a golf, so the lowest byte count wins, good luck!!!!
EXAMPLE:

"Monkey" true<
y
"Monkey" false<
y
"Monkey" false<
n
"Monkey with symbols" false<
y
"monkey" true<
n

This is valid, as your program doesn't need to distinguish that Monkey, and monkey with symbols are the same thing species, however, Monkey and monkey are very much the same thing, and so the last critter would be denied.

Python 2, 72 bytes

Takes input as a list of strings of the form "animalname T". The idea is it just uses each string as an identifier and should only print true if the string has not occurred in the list so far.

def f(l):k=map(str.lower,l);print[j not in k[:i]for i,j in enumerate(k)]

Try it here!


Rubik's Cube Scrambles Your task is to create a random sequence of moves, which can be used to scramble a Rubik's Cube. Such a scramble is made up of exactly 25 moves. Each move consist of of the letters UDRLFB optionally followed by one of the suffixes '2.
This notation is called the Singmaster notation. UDRLFB represents one of the 6 faces and the optional suffix '2 represents the turning angle. This information is in no way  necessary to solve the task.
To assure, that the scrambles are of 'good quality', the following two rules have to apply:

Two consecutive moves must not have the same letter. This bans the consecutive moves UU, DD, RR, LL, FF and BB and all their combinations using the optional suffixes like U2U or U'U'.
These move pairs are banned, because they can easily reduced to 1 or 0 moves. U2U has the same effect as U', R'R the same effect as  .

Three consecutive moves must not be of the same letter group. The letter groups are UD, RL and FB. This rule additionally bans the consecutive moves UDU, DUD, RLR, LRL, FBF, BFB and all their combinations using the optional suffixes like U2DU, RL'R or B2FB'.
The groups sort the faces by their move axis. U and D are in the same group, because both turn around the same axis. Therefore an U move doesn't influence the pieces of the D face, and a D move doesn't influence pieces of the U face. Therefore the two moves can be exchanged, UDU has the same effect as UUD, and this can be reduced to U2D.

Challenge
Write a script or a function, that generates one random scramble. There is no input. The script / function has to print the 25 moves without separation or separated by one space or return the correspondent string.
Your program has to be able to create every single scramble, which satisfies the rules above. Of course assuming, that the random number generator is true random, and not pseudo random.
This is code-golf. The shortest code (counted in bytes) wins.
Examples outputs:
Calling the script / function 3 times should print / return something like:
R'B2R2F2R2FB'R2DR2ULFB2RB'U2B'FL'BR'U'RB'
U'DBR'B2U'B'U'RUF'B'RDR2U'B'LR'B'F2D2UF2L'
BR2F'B'R'D'R'U2B'F2D2R'F2D'F'D2R2B'L2R'UB'R2L'D

If you separate the moves by a space each:
R2 L' F2 U2 D' R2 L2 F L' D2 U R B D' U2 L B2 L U B2 D U2 R' D2 U'
B R D2 F U2 B' R2 F2 B' U' L' R2 B U2 R' D B' F' U2 R' B' L R D2 R2
B2 R2 U D' B R D' R L2 D2 L2 R B2 F U' F2 B2 U' F U' D F R2 U2 B'

Notice, that all these outputs consists of 25 moves, but have different lengths, because of the optional suffixes. It's not allowed to print a space, when either 2 or ' are uses as suffix. You have to print L2UR2F'R'U2 or L2 U R2 F' R' U2. L2U R2F'R'U2 is not allowed.

C,129
f(){int i,n,m,r,s,t;for(i=26;i--;i<25&&printf("%c%c","URFDLB"[s%6],"'2"[r%3])){for(n=m,t=1;t;t=m*n==9)m=(r=rand()%15)/3+1;s+=m;}}

The inner loop generates a value of m in the range 1..5 which when added to s and taken modulo 6, ensures that no two consecutive moves are on the same side of the cube. The old value of m is stored in n and the test m*n==9 ensures that the value m=3 is never generated twice in a row (so opposite faces cannot be picked twice in a row; note the order of faces in the string.)
The least significant part of r is used to decide which suffix (', 2 or null) to use, taking advantage of the null character at the end of "'2".
The outer loop runs 26 times. The first time, U can never be picked, so printf is suppressed for the first iteration.
Ungolfed code in test program
The ungolfed code puts a space between each move for clarity (the golfed code does not, in order to save one byte.) Additionally the golfed code saves a semicolon by relocating the printf within the for bracket.
f(){
  int i,n,m,r,s,t;
  for(i=26;i--;){
    for(n=m,t=1;t;t=m*n==9)m=(r=rand()%15)/3+1;
    s+=m;
    i<25&&printf("%c%c ","URFDLB"[s%6],"'2"[r%3]);
  }
}

main(){
  int j;
  srand(time(0));
  for(j=0;j<5;j++)f(), puts("");
}

Typical output
U' B D2 B' R' L F' D2 B D2 B2 R' B2 U D2 F' R U R' L B' L R2 B2 F'
U B U B F L2 D2 B' U' L B L R' D B U' D R D' B' F2 D' B D R
L D F2 B2 R' U F B' D2 L U R' L' U2 F' R F D U2 B L' B' U L2 F'
R2 B' F2 R2 L2 F' U2 L U' B' F R' D' F2 D F' L2 U2 R' D' B2 D F R2 L'
U2 F2 B2 D' F D F R L2 U' B D2 L' R D R F2 R' F2 U2 D R' D2 L F2


Von Neumann Neighborhood Your goal is to make a function that takes the coordinates of a cell in 2D space and a distance \$r\$ and returns the coordinates of all cells in the  input coordinate's von Neumann neighborhood of radius \$r\$. That is, all cells at most \$r\$ away in Manhattan distance.
For example, given the following cell coordinates and radius pairs:
[1, 1], 1 -> [0, 1], [1, 0], [1, 1], [1, 2], [2, 1]
[2, 2], 2 -> [0, 2], [1, 1], [1, 2], [1, 3], [2, 0], [2, 1], [2, 2], [2, 3], [2, 4], [3, 1], [3, 2], [3, 3], [4, 2]

This is what the von Neumann neighborhood looks like:

More information about the von Neumann neighborhood can be found here.
This is code-golf, so shortest amount of bytes wins!

APL (Dyalog Extended), 23 bytes

-4 thanks to ovs.
Anonymous tacit infix function, taking coordinates of a cell and radius as left and right arguments. Requires 0-based indexing.
{⍺∘+¨⍵-⍸⍵≥+/¨|∘.,⍨⍵…-⍵}

Try it online!
{…} "dfn"; left argument is ⍺ and right argument is ⍵:
 ⍵…-⍵ inclusive integer range from radius to negative radius
 ∘.,⍨ Cartesian selfie product
 ⊢m← assign to m and pass that
 | absolute values
 +/¨ sum each (gives matrix of Manhattan distances)
 ⍵≥ indicate which ones are less than or equal to the radius
 ⍸ ɩndices where true
 ⍵- subtract from radius
 ⍺∘+¨ add the cell coordinates to each


Tips for golfing in Java Are there any useful shortcuts that can be used in Java?

As shown below, import already adds at least 17 characters to a program.

import java.io.*;

I understand that the simple solution would be to use another language, but it seems to be a real challenge to shorten Java programs.

Tips should be specific to Java: if they're applicable to most C-like languages, they belong in the more general list of tips.

Use the most recent possible java. Java 8 lets you use lambda expressions, so use it if you need anything even like functional objects.
Define shortened functions for things you use a lot. For instance, you have a hundred calls to exampleClassInstance.doSomething(someParameter), define a new function void d(ParameterType p){exampleClassInstance.doSomething(p)} and use it to save yourself some characters.
If you are using a particular long class name more than once, like

MyEventHandlerProxyQueueExecutorServiceCollectionAccessManagerFactory

instead define a new class:

class X extends MyEventHandlerProxyQueueExecutorServiceCollectionAccessManagerFactory{}

If you are only using one particular method of that class (but still need to instantiate it), you can define a shortened version inside the new class at the same time.
Use function type parameters to shorten things, where possible, like this:

<T>void p(T o){System.out.println(o);}

Use for(;;) instead of while(true).
Do not use access modifiers unless absolutely necessary.
Do not use final for anything.
Never put a block after a for loop (but a foreach loop for(x:y) is different). Additional statements should be placed inside the for statement itself, like for(int i=0;i<m;a(i),b(++i))c(i);.
Use inline assignment, incrementation, instantiation. Use anonymous inline classes where appropriate. Use lambdas instead if possible. Nest function calls. Some functions are guaranteed to return their parent object, these ones are actually even meant to be chained together.
Your main method throws Exceptions, not catches them.
Error is shorter than Exception. If for some reason you really need to throw messages up the stack, use an Error, even if it is perfectly normal situation.
If some condition would require immediate termination, use int a=1/0; rather than throw null; or System.exit(0);. At run time, this throws an ArithmeticException.  If you already have a numeric variable in your code, use it instead. (If you already have import static java.lang.System.*;, go with exit(0);.)
Instead of implementing interfaces, like List<E>, extend an immediate (or not-so-immediate, if there is any advantage to doing so at all) child class, like AbstractList<E>, which provides default implementations of most of the methods, and requires only the implementation of a few key pieces.
Write your code out in longhand first, with newlines, indentation, and full variable names. Once you have working code, then you can shorten names, move declarations around, and add shortcut methods. By writing it out long to start, you give yourself more opportunity to simplify the program as a whole.
Compare alternative optimizations to a piece of code, because the most optimal strategy can change dramatically with very small changes to the code. For instance:

If you have only up to two calls to Arrays.sort(a), the most efficient way to is to call it with its fully qualified name, java.util.Arrays.sort(a).
With three or more calls, it is more efficient to instead add a shortcut method void s(int[]a){java.util.Arrays.sort(a);}. This should still use the fully-qualified name in this case. (If you need more than one overload, you are probably doing it wrong.)
However, if your code needs to also copy an array at some point (usually done with a short for loop in golfing, in the absence of an easily-accessible library method), you can take advantage of Arrays.copyOf to do the task. When more than one method is used, and there are 3 or more calls, doing import static java.util.Arrays.*; is the most efficient way of referring to those methods. After that, only if you have more than 8 separate calls to sort should you be using a shortcut method for it, and only at 5 or more calls is a shortcut warranted for copyOf.

The only real way of performing such analysis on code is to actually perform potential modifications on copies of the code, and then compare the results.
Avoid using someTypeValue.toString(); method, instead just append someTypeValue+"".
If you do need windows, don't use Swing, use AWT (unless you really need something from Swing). Compare import javax.swing.*; and import java.awt.*;. Additionally, components in Swing have a J prepended to their name (JFrame, JLabel, etc), but components in AWT don't (Frame, Label, etc)


RGB Gradients Generation The Challenge

Given the two uppercase hexadecimal strings (both 6 characters long, XXXXXX and YYYYYY) representing RGB values (ranging from 000000 to FFFFFF inclusive), and a positive non-zero integer N, display a linear transition of the N+2 colors generated from XXXXXX to YYYYYY that would result in a color gradient.

Example

Input

FF3762
F08800
9

Output

Please note in our example, I've requested 9 interim steps between the two colors, therefore 11 lines will be displayed from initial color to the final color

FF3762
FD3F58
FC474E
FA4F44
F9573A
F75F31
F66727
F46F1D
F37713
F17F09
F08800

Caveats

While I've gone with a simple linear process of deriving the integer values for the interim colors before converting them back into hexadecimal, your methods may vary. Please consider the various ways one could round up/down your numbers accordingly.

Testing

To make this interesting, I've provided a snippet to allow testing of your code, inclusive of a button to provide you with two random colors to test your code against. Displaying your results is optional, but it's encouraged!

c1=()=>('00000'+(Math.random()*(1<<24)|0).toString(16)).slice(-6);

$("#col").click(function(){
  alert("Your two colors are: "+c1()+" and "+c1()+".");
});

$("#colors").blur(function(){
  $("#test").empty();
 var colArr = $("#colors").val().split("\n");
 for(c in colArr){
   $("#test").append('
'+colArr[c]+'
')
  }

});
.tester{height: 20px;
width: 60px;padding: 4px;border: 1px solid black;}

<button id="col">Your two colors</button>

<textarea id="colors"></textarea>

1) You can access two random colors for your test by clicking on the "Your two colors" button.
2) The number of interim steps will be the same as the number of characters in your PPCG username inclusive of spaces, in the case of "WallyWest" it would be 9 (as per my example above).
3) Run your code with the two colors and the number and once you have your generated list, you have the option of pasting your output into the textarea and tabbing away from it to get your generated color gradient.

My example is shown here:

I must admit, that looks pretty awesome!

Please note: As I mentioned, showing your testing of your output using the snippet is optional, but it's encouraged! :)

Output

The list output must be in the form of N+2 sets of 6 digit hex numbers separated by line feeds (\n) as shown in my example above. Output can be in the form of separate lines, space/comma separated list, an array or whatever is best suited for your language... (Thanks @nimi for the heads up) Please remember, that if you plan on testing your code with the snippet, however you separate each "color" is up to you.

Rules

This is code-golf, so the shortest solution in bytes will be crowned the winner. No loopholes, naturally. Input must accept the two strings and a number (which as I said will be equivalent to the number of letters in your username on PPCG, thus your resulting output will always be a minimum of three lines long.

JavaScript (ES6), 130 bytes

g=
(f,t,n)=>[...Array(++n+1)].map((_,i)=>f.replace(/../g,(e,j)=>((`0x${e}`*(n-i)+`0x${t[j]+t[j+1]}`*i)/n|256).toString(16).slice(1)))
;
p=_=>g(f.value,t.value,+n.value).map(e=>o.insertRow().insertCell().appendChild(document.createTextNode(e)).parentNode.bgColor=e);
<input id=f value=e14f09><input id=t value=9a04f6><input id=n value=4 type=number><input type=button onclick=p() value=Go!><table id=o bgcolor=black cellpadding=4>


Produce a palindrome from this text Copy and paste or curl this text:
http://lorem-ipsum.me/api/text
Using any language make the text palindromic.
You may remove letters.
You may rearrange letters.
The goal is to make the text palindromic by the sequence of the letters and spaces. The end result might not contain words. It will be merely a sequence of letters and spaces.
Capital letters are considered the same as lowercase letters.
You may use each letter only once, or you may remove the letter.
You may also use each space only once. Or you may remove the space.
The result should be the longest palindrome you can programmatically create from the text.
While you could technically print just the letters AaA or something similar to it, that is not what I am looking for.
Your palindrome creator should work with any text.
A palindrome, by definition, is a word, phrase, number, or other sequence of symbols that reads the same backward as forward.  A sequence of symbols that reads the same backward as forward is the acceptable palindromic definition I am looking for in this CodeGolf example.
Scoring will be Length of palindrome / Length of code. The winner is the one with the highest score.

Text:

Lorem ipsum dolor sit amet, consectetur adipisicing elit, possimus voluptatem do ut vel deserunt laborum. cupidatat libero minim at a aute minus cupiditate excepturi reiciendis blanditiis, atque vero. dolorem dolores dolore corrupti aute recusandae repellat recusandae modi deleniti libero nostrud aute delectus quidem alias odio nostrum pariatur. placeat minus similique a aliquip facere ullamco officiis eligendi ad at magnam commodi maxime.

Adipisicing modi enim similique maxime ex nisi sed eu suscipit earum corrupti assumenda perferendis cumque maiores qui praesentium nobis. Sed voluptas consequatur voluptates rerum facilis qui dolor commodi minim provident, magnam facere, tenetur. Aliqua voluptatibus delectus illum dolorem excepturi aliquip duis odio. Excepturi similique hic iusto eu consectetur laboriosam quidem esse eiusmod, anim. Eu consequatur magnam tempor vel.

Nobis incididunt eius cum distinctio magnam velit facilis libero ullam, tenetur distinctio eius eveniet. Anim possimus expedita fugiat facilis vel consequatur in temporibus laboriosam at molestiae velit cupidatat. Vel consequatur voluptate cum sint dolores ullamco quas omnis quibusdam id officiis tenetur voluptas, tempore tenetur aliquam debitis. Nostrud, do in numquam magnam quia voluptate incidunt accusamus distinctio officia molestiae fuga. Nam corporis ex quos recusandae sed.

Ullamco incidunt cupidatat eos voluptate delectus nostrud nisi irure quod quis alias. Fuga quam autem mollit ex dolores quod non tempor mollitia quas labore sapiente a anim deserunt expedita minus. Ex pariatur accusamus alias deleniti quo, quia similique voluptas. In voluptatibus esse perferendis commodo aute repellendus accusamus laboriosam deserunt aute possimus laboriosam.

Labore hic tempora, ad iusto hic aliqua ducimus. Distinctio omnis tempore incididunt ut sed mollit, quidem, aute sunt eius eveniet, vel distinctio cupiditate eius atque. Fuga asperiores tenetur enim, provident similique aliqua nostrum ad dolorum, molestiae, repudiandae ad sunt. Consequatur ullamco a nisi aliqua non omnis officia.

Labore sapiente obcaecati libero quas eos incididunt. Saepe quas voluptas mollitia consectetur dolores dolores officiis id, quo, laboriosam reprehenderit alias. Voluptates cumque dignissimos, cumque dolor. Incididunt minima consectetur harum et.

Mathematica 146 92 chars (score 2130/92 = 23.15)
Shorter Version (92 chars)
This palindrome has the characters grouped,
""<>{s=({#[[1]],Length@#~Quotient~2}&/@ Gather@Characters@t)
/.{c_,n_}:>c~Table~{n},Reverse@s}

Longer Version (146 chars)
This will return a maximum length, randomized palindrome from t.
Because capital letters are equivalent to lowercase letters, I converted all capitals to lower case.  (This can be changed if necessary.)
f@t_ := "" <> Join[s = RandomSample[ Flatten[({#[[1]], Quotient[Length[#], 2]} & /@
     Gather[Characters@ToLowerCase@t]) /. {c_, n_} :> ConstantArray[c, n]]], Reverse@s]

Example:
When t is the suggested, Lorem ipsum, text.  (Ignore line returns; all line returns were generated via the SE editor.)

"ti,iopexri  rpiuu opaat tismimetnesa lvuot oiaiu oaaittcoar nc
muapua elhpibemu utin ia f  ihide sdourgeeic e  oaasa.marsae dstircd
ci ndn   rs t egoaiq.aeatntreusng xi a lumalnoiieqqeq cc otiueasniieu
nrpupdlmnai o cdsm t gt.iccmittli i t tu.rust.li maui bea gqiceeo
pncu eonttecvtutqun eaaariusoquppsedlqu scrddmt esiafidurs  hitlpna
nlamltire ivmumbabi nbuderup td x uuualsoq.eiib li olel ru aeelau
idbc lrop iil ssur anda o scnmsr ,m uri,teo
esmiaveuomrt ldqqaid ihi snsr   spueeoevcre oe
msirulaleaisormm.oicolarsstteo td aatncn ieqrsuam boid te utcf eccp
siacu m etnqutlacniiereltiulqemltaqx a
qtdlxmliibileoheesimittlusqemooamuiippeaiilcgudsatfsiemamsc irn
rsgoi, ie
nmteiaiiptraned alsomsui noru ic,mditi ic ouud oadmv iudinrfuludet
eeiidueel nndaemcrepnioe sials unetuamconn,i
ubpo eiu ei dsn equi,ue ostmp udiatqu dalmau nueeiit ln e mioancteop
ntiiao ts noeefubtefrit ldeop earnmsm oas
d.catirotulvliodiellmesurotiomsmduia.nauenb iuiroimduriohs.lrndsaroc
t inidrssq apeuionnlaa eqdroounosmotidr arxr o taouarut  ussce uamae
is.dcadaimuoaprad iifl  i  lmml  i  lfii darpaoumiadacd.si eamau
ecssu  turauoat o rxra rditomsonuoordqe aalnnoiuepa qssrdini t
corasdnrl.shoirudmioriui bneuan.aiudmsmoitorusemlleidoilvlutoritac.d
sao msmnrae poedl tirfetbufeeon st oaiitn poetcnaoim e nl tiieeun
uamlad uqtaidu pmtso eu,iuqe nsd ie uie opbu
i,nnocmautenu slais eoinpercmeadnn leeudiiee tedulufrnidui vmdao duuo
ci itidm,ci uron iusmosla denartpiiaietmn
ei ,iogsr nri
csmameisftasdugcliiaeppiiumaoomeqsulttimiseehoelibiilmxldtq a
xqatlmeqluitlereiincaltuqnte m ucais pcce fctu et diob mausrqei
ncntaa dt oettssralocio.mmrosiaelalurism eo ercveoeeups   rsns ihi
diaqqdl trmouevaimse
oet,iru m, rsmncs o adna russ lii porl cbdi  ualeea ur lelo il
biie.qoslauuu x dt puredubn ibabmumvi eritlmaln anpltih  srudifaise
tmddrcs uqldesppuqosuiraaae nuqtutvcettnoe ucnp oeeciqg aeb iuam
il.tsur.ut t i ilttimcci.tg t msdc o ianmldpuprn  ueiinsaeuito cc
qeqqeiionlamul a ix gnsuertntaea.qiaoge t sr   ndn ic dcritsd
easram.asaao  e cieegruods edihi  f ai nitu umebiphle aupaum cn
raocttiaao uiaio touvl asentemimsit taapo uuipr  irxepoi,it"


Sort a list of numbers on the λ-calculus Write a term on the pure untyped lambda calculus that, when applied to a church-encoded list of numbers, returns it with its numbers sorted in ascending or descending order. Church lists and numbers must be encoded as folds for their usual ADTs:

-- Usual ADTs for Lists and Nats (in Haskell, for example)
data List a = Cons a (List a) | Nil
data Nat a  = Succ (Nat a) | Zero

-- Their respective folds are the λ-calculus representation used on this challenge
church_list = (λ c n . (c ... (c ... (c ... n))))
church_num  = (λ succ zero . (succ (succ (succ ... zero))))

Example input:

(λ cons nil .
    (cons (λ f x . (f x))                         -- 1
    (cons (λ f x . (f (f (f (f (f (f (f x)))))))) -- 7
    (cons (λ f x . (f (f x)))                     -- 2
    (cons (λ f x . (f (f (f x))))                 -- 3
    nil)))))

Example output:

(λ cons nil .
    (cons (λ f x . (f x))                         -- 1
    (cons (λ f x . (f (f x)))                     -- 2
    (cons (λ f x . (f (f (f x))))                 -- 3
    (cons (λ f x . (f (f (f (f (f (f (f x)))))))) -- 7
    nil)))))

The score of a submission will be calculated as follows:

score(x)    = 1
score(λx.t) = score(t) + 1
score(t s)  = score(t) + score(s) + 1

Lowest score wins.

I've managed to beat my own mark:

sort = λabcd.a(λef.f(λghi.g(λj.h(λkl.kj(ikl)))(hi))e(λgh.h))
       (λe.d)(λe.b(λf.e(f(λghi.hg)(λgh.cfh))))

There is a caveat, though - this term must receive an additional argument with the maximum size of naturals that are considered. For example, sort 4 [1,7,3,6,5] will return [1,3], ignoring anything above or equal 4. Of course, you could just give infinity (i.e., the Y-combinator):

sort = λbcd.(λfx.f(x x))(λfx.f(x x))(λef.f(λghi.g(λj.h(λkl.kj(ikl)))
       (hi))e(λgh.h))(λe.d)(λe.b(λf.e(f(λghi.hg)(λgh.cfh))))

And it would sort any list of natural numbers, but this term obviously doesn't have a normal form anymore.


10 9 8 7 6 5 4 3 2 1... Print 2016 As a spin-off to my challenge over at Puzzling, your goal is to output 2016.

Rules:

You must include the numbers 10 9 8 7 6 5 4 3 2 1 in that order. They can be used as individual integers or concatenated together (like 1098), but the 10 may not be separated into 1 and 0 - no character(s) may be present between the digits. Note that, in some languages, 10 may not actually represent the integer literal 10, which is acceptable.
Your code must not contain any other numbers or pre-defined number variables or constants (so T in Pyth is not allowed, since it is a numeric constant).
You must calculate 2016 using numerics. Simply outputting 2016 without performing any operations on the required numbers (for example, by decoding an encoded string consisting of only alphabetic characters) is not allowed. Outputting 2016 in pieces (such as 20, then 16) is also not allowed; you must have a single output consisting of the numeric value 2016.
The valid answer with the fewest bytes wins.

Jelly, 17 15 14 bytes

109876:54+3_21

Try it online!

How it works

109876:54+3_21

109876            Initialize the left argument as 109876.
      :54         Perform integer division by 54, yielding 2034.
         +3       Add 3, yielding 2037.
           _21    Subtract 21, yielding 2016.


Tips for golfing in brainfuck What general tips do you have for golfing in brainfuck? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to brainfuck (e.g. "remove comments" is not an answer). Please post one tip per answer.

Putting one tip per answer would be way too many answers.

Learn to think in Brainfuck. It's very different than anything else. Read and write, and rewrite, and rewrite lots of brainfuck programs. The language doesn't give you much to work with, so it's important to use what it does give you flexibly and efficiently. Don't let any abstractions get between you and the language--get in there and grapple with it.
Get very comfortable with nondestructive flow control. To get out of a decision loop, rather than zeroing the starting cell by copying it elsewhere and then copying it back after leaving the loop, it's often better to move the pointer to a pre-existing zero nearby. Yes, this means the pointer will be in different places depending on whether you went through the loop, but that also means those places probably have different arrangements of nearby zeros and nonzeros, which you can use to resynch the pointer location using another loop. This technique is fundamental to good Brainfuck programming, and various forms of it will constantly prove useful.
That and the fact that every > or < costs mean that the details of memory layout are important. Try out as many variations of your layout as you have patience for. And remember, your memory layout does not have to be a rigid mapping of data to locations. It can morph over the course of execution.
On a larger scale, consider and even try implementing a variety of different algorithms. Initially it will not be obvious exactly what algorithm will be best; it may not even be obvious what basic approach will be best, and it will probably be something different than what would be best in a normal language.
If you're dealing with large or variable-sized data, see if there's any way you can possibly deal with it locally, without having to keep track of how big it is or your numerical location within it.
The same data can be two different things. (Most often, a number or character and also a nonzero positional marker. But see random.b, where a bit counter doubles as the value of one cell of a cellular automaton.)
The same code can do two different things, and it's a lot easier to make it do so in a language where code is as generic as <+<. Be alert to such possibilities. In fact, you may occasionally notice, even in what seems to be a well-written program, that there are small portions that could be deleted entirely, nothing added, and the thing would, by happenstance, still run flawlessly.
In most languages, you use a compiler or interpreter frequently to check your program's behavior. The Brainfuck language demands greater conceptual control; if you need a compiler to tell you what your program does, you don't have a firm enough grasp of your program, and you probably need to stare at it some more--at least if you want to have a clear enough image of the conceptual halo of similar programs to be good at golf. With practice, you'll be producing a dozen versions of your program before you try running one, and by that point you'll be 95% sure that your shortest one will run correctly.
Good luck! Very few people bother to write Brainfuck concisely, but I think that's the only way the language can possibly justify continuing attention--as a stunningly obscure art form.


Align function arguments on their own lines Given an input of a string representing a function definition, output the
string with newlines and spaces inserted so that the function's arguments are
newline-separated and aligned.

The input string will follow the following pattern:

First, it will start with a prefix, which is always at least one character
long and does not contain any of the characters ,().
An open parenthesis (() will then mark the beginning of the argument list.
A list of zero or more arguments will then follow. These are separated by the
string ", " (a comma and then a space). None of the arguments will contain
any of the characters ,().
A close parenthesis ()) will mark the end of the argument list.
Lastly, a postfix may be found, which is zero or more characters long and
may contain the characters ,().

The input string will consist solely of printable ASCII (which means it will never contain a newline).

The output must be:

The prefix, copied down verbatim, and the open parenthesis.
The argument list, this time separated not by ", " but by a comma, newline, and as
many spaces as is needed to vertically align the first character of each
argument.
The close paren and postfix (if it exists) verbatim.

Since this is code-golf, the shortest code in bytes will win.

Test cases (format: single-line input followed by output followed by double
newline):

def foo(bar, baz, quux):
def foo(bar,
        baz,
        quux):

int main() {
int main() {

fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {
fn f(a: i32,
     b: f64,
     c: String) -> (String, Vec<i32>) {

function g(h) {
function g(h) {

def abc(def, ghi, jkl, mno)
def abc(def,
        ghi,
        jkl,
        mno)

x y z(x, y, z) x, y, z)
x y z(x,
      y,
      z) x, y, z)

Haskell, 115 bytes

import Data.Lists
f x|(a,b:c)<-span(/='(')x,(d,e)<-span(/=')')c=a++b:intercalate(",\n "++(a>>" "))(splitOn", "d)++e

Usage example:

*Main> putStrLn $ f "fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {"
fn f(a: i32,
     b: f64,
     c: String) -> (String, Vec<i32>) {

How it works:

bind
  a: everything before the first (
  b: the first (
  c: everything after the first (
  d: everything of c before the first )
  e: everything of c from the first ) to the end

construct the output string by concatenating
  a
  b
  splitting d at the argument separator ", " and rejoining it with ",\n " followed by (length a) spaces
  e


Output the nth rational number according to the Stern-Brocot sequence The Stern-Brocot sequence is a Fibonnaci-like sequence which can be constructed as follows:

Initialise the sequence with s(1) = s(2) = 1
Set counter n = 1
Append s(n) + s(n+1) to the sequence
Append s(n+1) to the sequence
Increment n, return to step 3

This is equivalent to:

Amongst other properties, the Stern-Brocot sequence can be used to generate every possible positive rational number. Every rational number will be generated exactly once, and it will always appear in its simplest terms; for example, 1/3 is the 4th rational number in the sequence, but the equivalent numbers 2/6, 3/9 etc won't appear at all.

We can define the nth rational number as r(n) = s(n) / s(n+1), where s(n) is the nth Stern-Brocot number, as described above.

Your challenge is to write a program or function which will output the nth rational number generated using the Stern-Brocot sequence.

The algorithms described above are 1-indexed; if your entry is 0-indexed, please state in your answer
The algorithms described are for illustrative purposes only, the output can be derived in any way you like (other than hard-coding)
Input can be via STDIN, function parameters, or any other reasonable input mechanism
Ouptut can be to STDOUT, console, function return value, or any other reasonable output stream
Output must be as a string in the form a/b, where a and b are the relevant entries in the Stern-Brocot sequence. Evaluating the fraction before output is not permissable. For example, for input 12, output should be 2/5, not 0.4.
Standard loopholes are disallowed

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

Test cases

The test cases here are 1-indexed.

n    r(n)
--  ------
1    1/1
2    1/2
3    2/1
4    1/3
5    3/2
6    2/3
7    3/1
8    1/4
9    4/3
10   3/5
11   5/2
12   2/5
13   5/3
14   3/4
15   4/1
16   1/5
17   5/4
18   4/7
19   7/3
20   3/8
50   7/12
100  7/19
1000 11/39

OEIS entry: A002487

Excellent Numberphile video discussing the sequence: Infinite Fractions

Haskell, 78 77 65 58 bytes

Shamelessly stealing the optimized approach gives us:

(s#t)0=show s++'/':show t
(s#t)n=t#(s+t-2*mod s t)$n-1
1#1

Thanks to @nimi for golfing a few bytes using an infix function!

(Still) uses 0-based indexing.

The old approach:

s=(!!)(1:1:f 0)
f n=s n+s(n+1):s(n+1):(f$n+1)
r n=show(s n)++'/':(show.s$n+1)

Damn the output format... And indexing operators. EDIT: And precedence.

Fun fact: if heterogenous lists were a thing, the last line could be:

r n=show>>=[s!!n,'/',s!!(n+1)]


Shortest hex dumping program Challenge

Create a console program to display each byte of a file.

Winning

Since this is code-golf, fewest bytes wins.

Rules

Program must be a console application, meaning that it will be ran from some sort of command-line interpreter;
Every byte must be uppercase hexadecimal, separated by a space, and it must be 2 digits; (put number 0 before it if it has 1 digit)
File must be read using IO or alternative, and not hard-coded;
File path must be specified as a command-line argument or a user prompt (like STDIN);
No loopholes please;

Example

test.txt (ends with LF)

Hello World!

$ ./hexdump.exe test.txt
48 65 6C 6C 6F 20 57 6F 72 6C 64 21 0A

C (gcc) on *nix, 73 71 bytes

i;main(c,v)int**v;{for(c=open(v[1],0);read(c,&i,1);printf("%02X ",i));}

Try it online! Test suite

-2 bytes thanks to Johan du Toit

This relies on O_RDONLY == 0 and on int_one == 1 where int int_one; *(char*)&int_one = 1;.


MS Paint is underrated MS Paint was always a great time waster, but it was shunned by most graphic designers. Perhaps people lost interest because of the jarring color palette, or because of limited undo levels. Regardless, it's still possible to generate beautiful images with just the standard brush and default color palette.

Challenge

Using only the default brush (a 4x4 square with no corners) and the default color palette (the 28 colors below), attempt to replicate a source image using a technique based on stochastic hill climbing.

Algorithm

Every answer must follow the same basic algorithm (stochastic hillclimb). Details can be tweaked within each step. A movement is considered to be a stroke of the brush (ie. clicking in paint).

Guess next movement(s). Make a guess (of coordinates and colors) for the next movement(s) however you'd like. However the guess must not reference the source image.
Apply the guess. Apply the brush to the painting to make the movement(s).
Measure the benefit of movement(s). By referencing the source image, determine whether the movement(s) benefited the painting (ie. the painting more closely resembles the source image). If it is beneficial, keep the movement(s), otherwise discard the movement(s).
Repeat until convergence. Go to Step 1 and try the next guess until the algorithm has converged sufficiently. The painting should heavily resemble the source image at this point.

If your program does not match these four steps, it is probably not a stochastic hillclimb. I have tagged this as a popularity contest because the goal is to produce interesting painting algorithms based on the limited color palette and brush.

Contraints

The algorithm should be stochastic in some way.
The next guess should not be influenced by the source image. You are guessing each new movement, and then checking to see if it helped or not. For example, you are not allowed to determine where to place the brush based on the source image colors (that is similar to dithering the source image, which is not the goal).
You are allowed to influence the placement by tweaking the steps of the algorithm however you'd like. For example, you could start your guesses at the edges and move inwards, drag the brush to create lines for each guess, or decide to paint dark colors first. You are allowed to reference previous iteration images (but not the source image) in order to calculate the next desired movement. These can be restrictive as you'd like (ie. only make guesses within the top-left quadrant for the current iteration).
The measure of "difference" between the source image and the current iteration can be measured however you'd like, as long as it does not calculate other potential movements to determine whether this movement is considered to be the "best". It shouldn't know whether the current movement is the "best", only whether it fits within the tolerance of the acceptance criteria. For example, it can be as simple as abs(src.R - current.R) + abs(src.G - current.G) + abs(src.B - current.B) for each affected pixel, or any of the well-known color difference techniques.

Palette

You can download the palette as a 28x1 image or create it directly in the code.

Brush

The brush is a 4x4 square without corners. This is a scaled version of it:

(Your code must use the 4x4 version)

Example

Input:

Output:

You can see how the basic algorithm progresses in a short video I made (each frame is 500 iterations): The Starry Night. The initial stages are interesting to watch:

JavaScript

This solution uses the HTML5 canvas element to extract the image data, but without the need to use HTML, that means it can be run in your console. It access the color palette image as an array; I stored all the colors from the palette image in an array). It outputs to the console (after it finishes) and also stores the result in a variable.

The most updated version of the code is in the fiddle. The fiddle also uses a better algorithm to reduce noise in the pictures. The improvement in the algorithm is mostly fixing a function (max to min) which caused the inverse color to be chosen.

Code in the shape of the MS Paint Icon! (formatted code in fiddle or Stack Snippet)

eval(`                                                   function
                                                        Paint(t){fun
                                                         ction n(t){va
                                                         r n=t.toString(
                                                         16);return 1==n.
                                                         length?"0"+n:n}fu
                                                         nction e(t){return
                                                         "#"+n(t[0])+n(t[1]
                                                          )+n(t[2])}var a=ne
                                                          w Image,i=document.
                                                          createElement("canv
                                                          as"),h=null,o=docum
                                                          ent.createElement(
                                    "canvas"),r=          o.getContext("2d
                               ")     ,l=[],u=this,c      =[[0,0,0],[255
                            ,2       55,255],[ 192,192,   192],[128,12
                          8     ,128],[126,3,8],[252,13,27] ,[255,25
                       3,    56],[128,127,23],[15,127,18],[ 41,253
                      ,    46],[45,255,254],[17,128,127],[2 ,12,1
                    2    6],[ 11,36,2 51],[252,40,252],[12 7,15,1
                  2    6],[  128,127 ,68],[255,253,136],[4 2,253,
                 1   33],   [4,64,64],[23 ,131,251],[133,255,254],
               [    129   ,132,252],[6,6 6,126],[127,37,2 51],[127,
              6   4,1    3],[253,128,73],[252,22,129]];a.crossOrigin
             =   "",   a.src=t,this.done=this.done||function(){},a.o
            n   load=function(){function t(t){var n=0,e=0,a=0;return
           t  .forEach(function(t){n+=t[0],e+=t[1],a+=t[2]}),[n/t.leng
          t  h,e /t.length,a/t.length]}function n(t){for(var n=[],e=0;e
         <  t.l  ength;e+=1)n.push(t[e]);return n}function g(t,n){retur
        n  (Ma  th.abs(t[0]-n[0])/255+Math.abs(t[1]-n[1])/255+Math.abs(t
       [  2]- n[2])/255)/3}function f(t,n){for(var e=Math.floor(Math.ran
          do m()*n.length),a=n[e],i=(g(t,a),1-.8),h=56,o=[];o.length<=h&
         &g (t,a)>i;)if(o.push(a),a=n[Math.floor(Math.random()*n.length)]
     ,  o.length==h){var r=o.map(function(n){return g(t,n)});a=o[r.indexO
       f(Math.max.apply(Math,r))],o.push(a)}return a}function s(t,n){for(
    v  ar e=[];t.length>0;)e.push(t.splice(0,n).slice(0,-1));return e}i.w
   i  dth=a.width,i.height=2*a.height,h=i.getContext("2d"),h.drawImage(a,0
   ,0,a.width,a.height);for(var d=(function(t){reduce=t.map(function(t){re
  turn(t[ 0]+t[1]+t[2])/3})}(c),0),m=0,v=i.width*i.height/4,p=0;v>p;p+=1)d
  >2*Mat h.ceil(a.width/2)&&(d=0,m+=1),l.push(f(t(s(n(h.getImageData(2*d,2
  *m,4,4).data),4)),c)),d+=1;o.width=i.width,o.height=i.height;for(var d=0
 ,m=0,v=i.width*i.height/4,p=0;v>p;p+=1)d>2*Math.ceil(a.width/2)&&(d=0,m+=
 1),console.log("Filling point ("+d+", "+m+") : "+e(l[p])),r.fillStyle=e(l
 [p]),r.fillRect(2*d+1,2*m,2,1)  ,r.fillRect(2*d,2*m+1,4,2),r.fillRect(2*d
+1,2*m+3,2,1),d+=1;u.result=o      .toDataURL("image/png"),u.resultCanvas
=o,u.imageCanvas=i,u.image=a       ,u.done(),console.log(u.result)},a.one
rror=function(t){console.log       ("The image failed to load. "+t)}}/*..
............................       ......................................
. ..........................       .....................................
............................      ......................................
.............................    .......................................
.......................................................................
.......................................................................
..................  ..................................................
................     .................................................
..............       ................................................
.............       ................................................
...........        .................................................
 .........         ................................................
 .......          ................................................
  ....           ................................................
                ................................................
                ...............................................
               ...............................................
              ..............................................
              .............................................
             ............................................
             ..........................................
              .......................................
              .....................................
               .................................
                .............................
                  ......................
                                   .....
                                  .....
                                  .....
                                  ....
                                   */`
.replace(/\n/g,''))

Usage:

Paint('DATA URI');

Fiddle.

The fiddle uses crossorigin.me so you don't need to worry about cross-origin-resource-sharing.

I've also updated the fiddle so you can adjust some values to produce the best-looking painting. Some pictures' colors might be off, to avoid this, adjust the accept_rate to adjust the algorithm. A lower number means better gradients, a higher number will result in sharper colors.

Here's the fiddle as a Stack-Snippet (NOT updated, in case the fiddle doesn't work):

/* Options */

var accept_rate = 82,  // 0 (low) - 100 (high)
    attempts    = 16, // Attemps before giving up
    edge_multi  = 2;   // Contrast, 2-4

function Paint(image_url) {
    var image = new Image(), canvas = document.createElement('canvas'), context = null, result = document.createElement('canvas'), resultContext = result.getContext('2d'), final_colors = [], self = this, color_choices = [
        [0,0,0],
        [255,255,255],
        [192,192,192],
        [128,128,128],
        [126,3,8],
        [252,13,27],
        [255,253,56],
        [128,127,23],
        [15,127,18],
        [41,253,46],
        [45,255,254],
        [17,128,127],
        [2,12,126],
        [11,36,251],
        [252,40,252],
        [127,15,126],
        [128,127,68],
        [255,253,136],
        [42,253,133],
        [4,64,64],
        [23,131,251],
        [133,255,254],
        [129,132,252],
        [6,66,126],
        [127,37,251],
        [127,64,13],
        [253,128,73],
        [252,22,129]
      ];
  image.crossOrigin = "";
  image.src = image_url;

  this.done = this.done || function () {};

  function hex(c) {
    var res = c.toString(16);
    return res.length == 1 ? "0" + res : res;
  }

  function colorHex(r) {
    return '#' + hex(r[0]) + hex(r[1]) + hex(r[2]);
  }

  image.onload = function () {
    canvas.width = image.width; canvas.height = image.height * 2;
    context = canvas.getContext('2d');
    context.drawImage(image, 0, 0, image.width, image.height);

    function averageColors(colors_ar) {
      var av_r = 0,
          av_g = 0,
          av_b = 0;

      colors_ar.forEach(function (color) {
        av_r += color[0];
        av_g += color[1];
        av_b += color[2];
      });

      return [av_r / colors_ar.length,
              av_g / colors_ar.length,
              av_b / colors_ar.length];
    }

    function arrayFrom(ar) {
      var newar = [];
      for (var i = 0; i < ar.length; i += 1) {
        newar.push(ar[i]);
      }
      return newar;
    }

    function colorDif(c1,c2) {
      // Get's distance between two colors 0.0 - 1.0
      return (Math.abs(c1[0] - c2[0]) / 255 +
              Math.abs(c1[1] - c2[1]) / 255 +
              Math.abs(c1[2] - c2[2]) / 255) / 3;
    }

    var furthest = (function (cc) {
      // Determines furthest color

      // Reduces RGB into a "single value"
      reduce = cc.map(function(color) {
        return ( color[0] + color [1] + color [2] ) / 3;
      });

    }(color_choices));

    function intDif(i1,i2,t) {
        return Math.abs(i1 - i2) / t
    }

    function arrayIs(ar, int,d) {
        return intDif(ar[0],int,255) <= d &&
               intDif(ar[1],int,255) <= d &&
               intDif(ar[2],int,255) <= d
    }

    function colorLoop(c1,c2) {
        var edgeCap =  edge_multi * ((accept_rate / 100) / 50), values = c2.map(function (i) {
            return colorDif(c1,i);
        });

      return arrayIs(c1,255,edgeCap)?[255,255,255]:
             arrayIs(c1,0,edgeCap)  ?[0,0,0]:
             c2[values.indexOf(Math.min.apply(Math, values))];
    }

    function colorFilter(c1, c2) {
      // Does the color stuff
      var rand  = Math.floor( Math.random() * c2.length ), // Random number
          color = c2[rand], // Random color
          randdif = colorDif(c1, color),
          threshhold = 1 - accept_rate / 100, // If the color passes a threshhold
          maxTries   = attempts, // To avoid infinite looping, 56 is the maximum tries to reach the threshold
          tries      = [];

      // Repeat until max iterations have been reached or color is close enough

      while ( tries.length <= maxTries && colorDif( c1, color ) > threshhold ) {
        tries.push(color);
        color = c2[Math.floor(Math.random() * c2.length)]; // Tries again

        if (tries.length == maxTries) {
          // Used to hold color and location
          var refLayer = tries.map(function(guess) {
            return colorDif(c1, guess);
          });

          color = tries[refLayer.indexOf(Math.min.apply(Math, refLayer))];
            tries.push(color);
        }

      }

      var edgeCap =  edge_multi * ((accept_rate / 100) / 50), loop = colorLoop(c1, c2);

      return arrayIs(c1,255,edgeCap)?[255,255,255]:
             arrayIs(c1,0,edgeCap)  ?[0,0,0]:
             colorDif(c1,color)<accept_rate?color:
             loop;
    }

    function chunk(ar, len) {
      var arrays = [];

      while (ar.length > 0)
        arrays.push(ar.splice(0, len).slice(0, -1));

      return arrays;
    }

    var x = 0, y = 0, total = (canvas.width * canvas.height) / 4;

    for (var i = 0; i < total; i += 1) {
      if (x > (Math.ceil(image.width / 2) * 2)) {
        x = 0;
        y += 1;
      }

      final_colors.push( colorFilter( averageColors( chunk( arrayFrom(context.getImageData(x * 2, y * 2, 4, 4).data), 4 ) ), color_choices) );

      x += 1;
    }

    // Paint Image
    result.width = canvas.width;
    result.height = canvas.height;
    var x = 0, y = 0, total = (canvas.width * canvas.height) / 4;
    for (var i = 0; i < total; i += 1) {
      if (x > (Math.ceil(image.width / 2) * 2)) {
        x = 0;
        y += 1;
      }

        console.log("Filling point (" + x + ", " + y + ") : " + colorHex(final_colors[i]));

      resultContext.fillStyle = colorHex(final_colors[i]);
      resultContext.fillRect(x*2 + 1, y * 2, 2 , 1); // Top
      resultContext.fillRect(x * 2, y * 2 + 1, 4, 2); // Middle
      resultContext.fillRect(x * 2 + 1, y * 2 + 3, 2, 1); // Bottom

      x += 1;
    }

    self.result = result.toDataURL("image/png");
    self.resultCanvas = result;
    self.imageCanvas = canvas;
    self.image = image;
    self.done();

    console.log(self.result);

  };

  image.onerror = function(error) {
    console.log("The image failed to load. " + error);
  }

}

// Demo

document.getElementById('go').onclick = function () {
    var url = document.getElementById('image').value;
    if (!url.indexOf('data:') == 0) {
        url = 'http://crossorigin.me/' + url;
    }
    var example = new Paint(url);

    example.done = function () {
        document.getElementById('result').src = example.result;
        document.getElementById('result').width = example.resultCanvas.width;
        document.getElementById('result').height = example.resultCanvas.height;
        window.paint = example;
    };
};

Enter the image data URI or a URL, I've used crossorigin.me so it can  perform CORS requests to the image. If you're inputting a URL, be sure to include the http(s)
<input id="image" placeholder="Image URI or URL"><button id="go">Go</button>

    You can get the image URI from a website like this one

    Result:

        Check your console for any errors. After a second, you should see the colors that are being generated / printed getting outputted to the console.

To commemorate New Horizon's flyby of Pluto, I've inputted an image of Pluto:

For the following I've set it to make them resemble the original as close as possible:

I ran this with OS X Yosemite's default wallpaper. After leaving it run for a bit, the results are absolutely stunning. The original file was huge (26 MB) so I resized and compressed it:

The starry night (I've used a higher resolution image for better results)

A picture I found on google:


ASCII Triangle Ripple Ok, my first golf question. Please be gentle :) I know there's way too many ascii puzzles :P but here we go.
The task is simple, use your favorite programming language to print a triangle ripple. The input should be the size of the ripple.
Each triangle is evenly spaced out. Basically, you keep adding the triangles until there is not enough space for the smallest triangle.
You are allowed white spaces anywhere you want as long as the ripples are the same as the example with the correct size.
Example
q)g 1
__
\/
q)g 2
____
\  /
 \/
q)g 3
______
\    /
 \  /
  \/
q)g 4
________
\  __  /
 \ \/ /
  \  /
   \/
q)g 5
__________
\  ____  /
 \ \  / /
  \ \/ /
   \  /
    \/
q)g 6
____________
\  ______  /
 \ \    / /
  \ \  / /
   \ \/ /
    \  /
     \/
q)g 7
______________
\  ________  /
 \ \  __  / /
  \ \ \/ / /
   \ \  / /
    \ \/ /
     \  /
      \/
q)g 8
________________
\  __________  /
 \ \  ____  / /
  \ \ \  / / /
   \ \ \/ / /
    \ \  / /
     \ \/ /
      \  /
       \/

As usual, shortest code wins :)