Tweetable hash function challenge In this code-challenge you will write a hash function in 140 bytes1 or less of source code. The hash function must take an ASCII string as input, and return a 24-bit unsigned integer ([0, 224-1]) as output.

Your hash function will be evaluated for every word in this large British English dictionary2. Your score is the amount of words that share a hash value with another word (a collision).

The lowest score wins, ties broken by first poster.

Test case

Before submitting, please test your scoring script on the following input:

duplicate
duplicate
duplicate
duplicate

If it gives any score other than 4, it is buggy.

Clarifying rules:

Your hash function must run on a single string, not a whole array. Also, your hash function may not do any other I/O than the input string and output integer.
Built-in hash functions or similar functionality (e.g. encryption to scramble bytes) is disallowed.
Your hash function must be deterministic.
Contrary to most other contests optimizing specifically for the scoring input is allowed.

1 I am aware Twitter limits characters instead of bytes, but for simplicity we will use bytes as a limit for this challenge.
2 Modified from Debian's wbritish-huge, removing any non-ASCII words.

Python, 5333 4991

I believe this is the first contender to score significantly better than a random oracle.

def H(s):n=int(s.encode('hex'),16);return n%(8**8-ord('+%:5O![/5;QwrXsIf]\'k#!__u5O}nQ~{;/~{CutM;ItulA{uOk_7"ud-o?y<Cn~-`bl_Yb'[n%70]))

Ruby, 6473 collisions, 129 bytes

h=->(w){@p=@p||(2..999).select{|i|(2..i**0.5).select{|j|i%j==0}==[]};c=w.chars.reduce(1){|a,s|(a*@p[s.ord%92]+179)%((1<<24)-3)}}

The @p variable is filled with all the primes below 999.

This converts ascii values into primes numbers and takes their product modulo a large prime. The fudge factor of 179 deals with the fact that the original algorithm was for use in finding anagrams, where all words that are rearrangements of the same letters get the same hash. By adding the factor in the loop, it makes anagrams have distinct codes.

I could remove the **0.5 (sqrt test for prime) at the expense of poorer performance to shorten the code. I could even make the prime number finder execute in the loop to remove nine more characters, leaving 115 bytes.

To test, the following tries to find the best value for the fudge factor in the range 1 to 300. It assume that the word file in in the /tmp directory:

h=->(w,y){
  @p=@p||(2..999).
    select{|i|(2..i**0.5).
    select{|j|i%j==0}==[]};
  c=w.chars.reduce(1){|a,s|(a*@p[s.ord%92]+y)%((1<<24)-3)}
}

american_dictionary = "/usr/share/dict/words"
british_dictionary = "/tmp/british-english-huge.txt"
words = (IO.readlines british_dictionary).map{|word| word.chomp}.uniq
wordcount = words.size

fewest_collisions = 9999
(1..300).each do |y|
  whash = Hash.new(0)
  words.each do |w|
    code=h.call(w,y)
    whash[code] += 1
  end
  hashcount = whash.size
  collisions = whash.values.select{|count| count > 1}.inject(:+)
  if (collisions < fewest_collisions)
    puts "y = #{y}. #{collisions} Collisions. #{wordcount} Unique words. #{hashcount} Unique hash values"
    fewest_collisions = collisions
  end
end


4, 8, 15, 16, 23, 42 4, 8, 15, 16, 23, 42

Write a program that outputs this sequence of numbers infinitely. However, The Numbers must not appear in your source code anywhere.

The following is not a valid Java program to output The Numbers because The Numbers appear in its source code:

class TheNumbers {
    public static void main(String[] args) {
        for(int n = 0;;) System.out.println(
            n == 4 ? n = 8 :
            n == 8 ? n = 15 :
            n == 15 ? n = 16 :
            n == 16 ? n = 23 :
            n == 23 ? n = 42 : (n = 4)
        );
    }
}

The definition of "The Numbers must not appear in your source code" is as follows:

You must not use the numeral 4.
You must not use the numeral 8.
You must not use the numeral 1 followed by the numeral 5.
You must not use the numeral 1 followed by the numeral 6.
You must not use the numeral 2 followed by the numeral 3.

If your language ignores certain characters that can be placed between the numerals, it's not a valid substitution. So for example if your language interprets the literal 1_5 as 15, this would count as the numeral 1 followed by the numeral 5.

Alternative bases are included in the restriction, so for example:

Binary 100 can't be used as a substitute for 4.
Octal 10 can't be used as a substitute for 8.
Hexadecimal F can't be used as a substitute for 15.

Therefore, the following is a valid (but not very inspired) Java program to output The Numbers because The Numbers do not appear in its source code:

class TheNumbers {
    public static void main(String[] args) {
        for(int n = '*';;) {
            System.out.println(n -= '&');
            System.out.println(n *= 2);
            System.out.println(n += 7);
            System.out.println(++n);
            System.out.println(n += 7);
            System.out.println(n += 19);
        }
    }
}

Note that in that program, '*' and '&' are substituted for the integers 42 and 38, because otherwise the numerals 4 and 8 would appear in its source code.

The definition of "outputs the sequence infinitely" is open to interpretation. So, for example, a program that outputs glyphs getting smaller until they are "infinitely" small would be valid.

Kudos if you are able to generate the sequence in some way that's not basically hard-coding each number.

Deriving it to a formula. My impression is there is not one but maybe there is or it can be faked.
Fixing a pseudo-random generator to return the sequence.

This is a popularity contest, so be creative. The answer with the most up votes on March 26th is the winner.

Java

I decided to add another entry since this is completely different from my first one (which was more like an example).

This program calculates the average of an array entered by the user...

import java.util.Scanner;

public class Numbers {
    public static double getSum(int[] nums) {
        double sum = 0;
        if(nums.length > 0) {
            for(int i = 0; i <= nums.length; i++) {
                sum += nums[i];
            }
        }

        return sum;
    }

    public static double getAverage(int[] nums) { return getSum(nums) / nums.length; }
    public static long roundAverage(int[] nums) { return Math.round(getAverage(nums)); }

    private static void beginLoop(int[] nums) {
        if(nums == null) {
            return;
        }

        long avg = roundAverage(nums);
        System.out.println("enter nums for average");
        System.out.println("example:");
        System.out.print("array is " + nums[0]);
        for(int i = 1; i <= nums.length; i++) {
            System.out.print(", " + nums[i]);
        }

        System.out.println();
        System.out.println("avg is " + avg);
    }

    private static int[] example = { 1, 2, 7, 9, };

    public static void main(String[] args) {
        boolean done = false;
        while(!done) {
            try {
                int[] nums = example;
                beginLoop(nums);

                nums = getInput();
                if(nums == null) {
                    done = true;
                } else {
                    System.out.println("avg is " + getAverage(nums));
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    static int[] getInput() {
        Scanner in = new Scanner(System.in);
        System.out.print("enter length of array to average or 0 to exit: ");
        int length = in.nextInt();
        if(length == 0) {
            return null;

        } else {
            int[] nums = new int[length];
            for(int i = 0; i <= nums.length; i++) {
                System.out.print("enter number for index " + i + ": ");
                nums[i] = in.nextInt();
            }
            return nums;
        }
    }
}

...or does it?

java.lang.ArrayIndexOutOfBoundsException: 4
    at Numbers.getSum(Numbers.java:8)
    at Numbers.getAverage(Numbers.java:15)
    at Numbers.roundAverage(Numbers.java:16)
    at Numbers.beginLoop(Numbers.java:23)
    at Numbers.main(Numbers.java:42)
java.lang.ArrayIndexOutOfBoundsException: 4
    at Numbers.getSum(Numbers.java:8)
    at Numbers.getAverage(Numbers.java:15)
    at Numbers.roundAverage(Numbers.java:16)
    at Numbers.beginLoop(Numbers.java:23)
    at Numbers.main(Numbers.java:42)
java.lang.ArrayIndexOutOfBoundsException: 4
    at Numbers.getSum(Numbers.java:8)
    ...

VBA

Sub chr_la_head_chr_la()
n = 50
Do While (True)
MsgBox Chr(n + 2) & " " & Chr(n + 6) & " " & Chr(n - 1) & Chr(n + 3) & " " & Chr(n - 1) & Chr(n + 3 + 1) & " " & Chr(n) & Chr(n + 1) & " " & Chr(n + 2) & Chr(n)
Loop
End Sub


Remove repeated words from a string Remove all repeating words from an inputted sentence.

Input will be something like cat dog cat dog bird dog Snake snake Snake and the output should be cat dog bird Snake snake. There will always be a single space separating words.

Output order must be the same as input. (Refer to the example)

You don't need to handle punctuation but capital letter handling is required.

CJam, 7 chars

qS/_&S*

Can probably be much shorter... but whatever I've almost never used CJam. ^.^

q reads input, S/ splits on spaces, _& duplicates and applies a setwise AND (therefore getting rid of duplicates), and S* re-joins on space.

Online interpreter link

C#, 909 bytes

class Dictionary
{
    public Dictionary<int, string> InsertWordsIntoDictionary(string userInput)
    {
        Dictionary<int, string> newWords = new Dictionary<int, string>();
        int a = 0;
        int b = 1;

        userInput = userInput.Insert(userInput.Length, " ");

        for (int i = 0; i < userInput.Length; i++)
        {
            char holder = userInput.ElementAt(i);
            if (holder.Equals(' '))
            {
                if (!newWords.ContainsValue(userInput.Substring(a, i - a)))
                {
                    string hello = userInput.Substring(a, i - a);
                    newWords.Add(b, hello);
                    a = i + 1;
                    b++;
                    hello = userInput;
                }
                a = i + 1;
            }
        }
        return newWords;
    }
}


Find the "Recursive Size" of a List Inspired by Find the “unwrapped size” of a list.

Define the Recursive Size, RS, of a list containing no lists as its length (number of items contained) and the Recursive Size of a list containing any lists as the sum of its length and the Recursive Size of those lists.

Challenge

Write a program or function that outputs the Recursive Size of any given list in as few bytes as possible.

The input is a list and may contain numbers, strings (if your language has them), and similar lists.

For example:

RS([]) = 0

RS([[]]) = 1

RS([4, 5, 6]) = 3
RS(["four", "five", "six"]) = 3
RS(["[[[[]]]]", "[][][][][]", "][][[[]]][]["]) = 3

RS([[4, 5, 6]]) = 4
RS([["four", "five", "six"]]) = 4
RS([["[[[[]]]]", "[][][][][]", "][][[[]]][]["]]) = 4

RS([[4], [5], [6]]) = 6
RS([["four"], ["five"], ["six"]]) = 6
RS([["[[[[]]]]"], ["[][][][][]"], ["][][[[]]][]["]]) = 6

RS([[[[[[[[[]]]]]]]]]) = 8

RS([[],[],[],[],[],[],[],[]]) = 8

RS([[],[],[[]],[[[[]]]]]) = 8

RS([0,[-1],[2.3,-4.3],[5,[6]],[7,[8,9,[10,11,[12,13,14]]]]]) = 22

Note that if your language has no strings but does have lists of characters, the examples containing "strings" above could actually be lists of characters and have larger results. As an example:

RS([['f','o','u','r'], ['f','i','v','e'], ['s','i','x']]) = 14

This is code-golf, so the shortest answer in bytes wins; no funny-business, as always.

A non-list input may produce any output.
I/O is as flexible as usual.

Python, 42 bytes

f=lambda x:x*0==[]and len(x)+sum(map(f,x))

For a non-list, output 0. For a list, output its length plus the sum of the recursive outputs for its elements.

Lists fall above numbers and below strings in the Python 2 ordering, requiring []<=x<''. Instead, we check x*0==[], whereas the result of 0 for a number or '' for a string.

Python, 72 bytes

l=lambda a:0if len(a)==0else len(a)+sum(l(i)for i in a if type(i)==list)


Print an alphabet wave You are to print this exact text:

ABABABABABABABABABABABABAB
BCBCBCBCBCBCBCBCBCBCBCBCBC
CDCDCDCDCDCDCDCDCDCDCDCDCD
DEDEDEDEDEDEDEDEDEDEDEDEDE
EFEFEFEFEFEFEFEFEFEFEFEFEF
FGFGFGFGFGFGFGFGFGFGFGFGFG
GHGHGHGHGHGHGHGHGHGHGHGHGH
HIHIHIHIHIHIHIHIHIHIHIHIHI
IJIJIJIJIJIJIJIJIJIJIJIJIJ
JKJKJKJKJKJKJKJKJKJKJKJKJK
KLKLKLKLKLKLKLKLKLKLKLKLKL
LMLMLMLMLMLMLMLMLMLMLMLMLM
MNMNMNMNMNMNMNMNMNMNMNMNMN
NONONONONONONONONONONONONO
OPOPOPOPOPOPOPOPOPOPOPOPOP
PQPQPQPQPQPQPQPQPQPQPQPQPQ
QRQRQRQRQRQRQRQRQRQRQRQRQR
RSRSRSRSRSRSRSRSRSRSRSRSRS
STSTSTSTSTSTSTSTSTSTSTSTST
TUTUTUTUTUTUTUTUTUTUTUTUTU
UVUVUVUVUVUVUVUVUVUVUVUVUV
VWVWVWVWVWVWVWVWVWVWVWVWVW
WXWXWXWXWXWXWXWXWXWXWXWXWX
XYXYXYXYXYXYXYXYXYXYXYXYXY
YZYZYZYZYZYZYZYZYZYZYZYZYZ
ZAZAZAZAZAZAZAZAZAZAZAZAZA

Specs

You can print all lowercase instead of all uppercase. However, case must be consistent throughout the output.
You may print one extra trailing linefeed.

Scoring

Since this is an alphabet wave that fluctuates to a small extent, your code should also be small in terms of byte-count. In fact, the smallest code in terms of byte-count wins.

PHP, 78, 72, 67 bytes

<?php $s='A';while($s!='AA')echo str_repeat($s++.(--$s)[0],13)."
";

Try it online!


Compare the averages of my lists Getting the average of a list  (e.g [2,6,7])

Get the length of the list: [2,6,7] -> 3
Sum the numbers in the list: 2 + 6 + 7 = 15.
Divide the sum by their count: 15 / 3 = 5.

You should compare the averages of two lists of positive integers N and M, by returning a value if N has a higher average, another value if M has a higher average, and another one in case of a tie.

I/O rules
All the standard Input and Output methods are allowed.
Input
You may take input as two separate lists, a nested list, or anything else you consider suitable for the task. Please specify the format.
Output
The values provided have to be distinct and must consist of at least one non-whitespace character. Also, they must be consistent between runs (a single value for N, a single value for M, a single value for Tie). Please specify those in your answer. The values can be non-empty Strings, Bool values, Integers, or anything you consider suitable.

Specs

The lists will not necessarily have equal length.

You are guaranteed that the lists are non-empty.

Test Cases
I chose the values N wins, M wins and Tie, which are pretty much self-evident.

N, M                     ->   Output     (Averages)

[7], [6]                 -> N wins  (N has 7, M has 6 )
[4,5], [4,4]             -> N wins  (N has 4.5, M has 4)
[2,3,4], [4,5,6]         -> M wins  (N has 3, M has 5)
[4,1,3], [7,3,2,1,1,2]   -> Tie     (both have 2.666...)
[100,390,1], [89,82,89]  -> N wins  (N has 163.666..., M has 86.666...)
[92,892], [892,92]       -> Tie     (lists are basically identical)
[10,182], [12,78,203,91] -> Tie     (both have 96)

Default Loopholes apply. Explanations are encouraged! This is code-golf, so the shortest code in bytes wins!

Mathematica, 15 bytes

Order@@Mean/@#&

Try it online!

Function which expects a list of two lists. Mean/@# takes the arithmetic mean of each list in the input, then those means are passed into Order, which returns -1 if the first list wins, 0 if there is a tie, and 1 if the second list wins.

Python 3, 44 bytes

Takes two lists n and m. Returns True if the average of n is larger, False if that of m is, and throws a ZeroDivisionError if they are equal.

lambda n,m:1/(sum(n)/len(n)-sum(m)/len(m))>0

Try it online!


I copied my password to the clipboard! Can you delete it? Following the best security practices, I keep a plain text file with my passwords on my hard drive. In fact, I just copied and pasted one of them to access my PPCG account.
In a lucid moment, I decide that the password should better not remain in the clipboard after its use. Since this happens to me often, I could use a program to remove the clipboard contents.
Challenge
Write a program or function that deletes or overwrites any text contained in the clipboard, using a programming language of your choice.
Additional details:

If your system has several clipboards, you can write the program for any one of them. The only requirement is that it must be possible for the user to copy and paste text using that clipboard.

If your clipboard keeps a history of recent copied entries, assume the most recent entry.

If your answer is specific to an operating system or clipboard, indicate it in the title of your post, together with the used language.

The clipboard is guaranteed to contain text when your program is run. You can either delete the contents from the clipboard, or overwrite it with something else (not necessarily text). The only requirement is that after running the program, pasting from the clipboard will not produce the original text.

If you choose to overwrite with some fixed or randomly chosen text, you can assume that the previous clipboard contents are different from that text, so the password is effectively removed. In other words, disregard the possibility that the filler text coincides with the password.

The program should not have any side-effects like restarting the system, closing programs, shutting down the computer, or freezing it. After your program is run, the user should be able to keep using the computer as normal, only with the password removed from the clipboard. Also, standard loopholes are forbidden.

Shortest code in bytes wins.

PowerShell, 3 bytes

scb

That's a default alias for Set-Clipboard. When called with nothing piped in and no arguments supplied, it blows away the current clipboard contents.

Java, 139 bytes
enum c{;static{java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new java.awt.datatransfer.StringSelection(""),null);}}

No one said that the program can't crash at the end.
Ungolfed version:
enum c {;
    static {
        java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new java.awt.datatransfer.StringSelection(""), null);
    }
}


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

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

/pattern/optional-flags

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

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

Thanks, and have fun!

6 chars

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

/(?!)/

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

/$^/

A thing that ends before it has begun...


Write a program to compose a quine of a specified length Write a program, in a language of your choice, that will compose a quine program of a requested size. The generated program may be in the same or a different language, if desired.

Programs are scored based on the following formula:

  generating_program_length + smallest_supported_size + 512 * number_of_supported_sizes ^ (-3/4)

Halve your score if you support every size between the minimum and maximum supported sizes.

Lowest score wins.

GolfScript → GolfScript: (4 + 0 + 0) / 2 = 2

~1`*

Program length: 4
Minimum supported size: 0
Maximum supported size: unbounded
All sizes supported: yes

This program simply reads an integer n from its input, and outputs an n-digit integer consisting of n 1 digits.  For example, the input 5 yields the output 11111.  In GolfScript, any integer literal (without leading zeros) is a quine, and since GolfScript integers can be arbitrarily large, the maximum supported length is only bounded by the amount of memory available.

For the input 0, the code outputs an empty program, which is also a quine in GolfScript.

Ps. The generated quines work for several other languages too, including PHP.

Golf-Basic 84 -> Golf-Basic 84

(54 + 0 + 0) / 2 = 27

Program length: 54
Minimum supported size: 0
Maximum supported size: none
All sizes supported: yes

Only limited by the calculator's RAM.

i`A:""_Str1:"1"_Str2l`1:A--A:Str1+Str2_Str1@Ag`1d`Str1


I know you, but you don't know me You're tasked with writing two programs. Program A must print out nothing on all inputs except when program B is input, in which case it should print 1. Program B must print out 1 on all inputs except when program A is input, in which case it should print nothing.

Scoring:

+1 For each character from both programs.
Lowest score wins.

Bash - 32 characters

Script A - 16 characters

cmp -s b&&echo 1

Script B - 16 characters

cmp -s a||echo 1

Usage

$> echo "foo" | ./a
$> cat b | ./a
1
$> echo "foo" ./b
foo ./b
$> cat a | ./b

R (62 chars)

i=identical
A=function(x)if(i(x,B))1
B=function(x)if(!i(x,A))1

produces:

> A(123)
> A(A)
> A(B)
[1] 1
> B(123)
[1] 1
> B(A)
> B(B)
[1] 1

Meta comment: R fairs relatively bad on code golf as there is no shortcut to function...


Build a Compiler Bomb Introduction

You're probably familiar with zip bombs, XML bombs, etc. Put simply, they are (relatively) small files which produce enormous output when interpreted by naïve software. The challenge here is to abuse a compiler in the same way.

Challenge

Write some source code which occupies 512 bytes or less and which compiles into a file which occupies the most possible space. Largest output file wins!

Rules

OK, so there are a few important clarifications, definitions and restrictions;

The output of the compilation must be an ELF file, a Windows Portable Executable (.exe), or virtual bytecode for the JVM or .Net's CLR (other types of virtual bytecode are also likely to be OK if asked for). Update: Python's .pyc / .pyo output also counts.
If your language-of-choice can't be compiled directly into one of those formats, transpilation followed by compilation is also allowed (Update: you can transpile multiple times, just so long as you never use the same language more than once).
Your source code can consist of multiple files, and even resource files, but the summed size of all these files must not exceed 512 bytes.
You cannot use any other input than your source file(s) and the standard library of your language-of-choice. Static linking standard libraries is OK when it's supported. Specifically, no third party libraries or OS libraries.
It must be possible to invoke your compilation using a command or series of commands. If you require specific flags when compiling, these count towards your byte limit (e.g. if your compile line is gcc bomb.c -o bomb -O3 -lm, the -O3 -lm part (7 bytes) will be counted (note the initial leading space isn't counted).
Preprocessors are permitted only if they are a standard compilation option for your language.
The environment is up to you, but in the interests of making this verifiable, please stick to recent (i.e. available) compiler versions and operating systems (and obviously specify which you're using).
It must compile without errors (warnings are OK), and crashing the compiler doesn't count for anything.
What your program actually does is irrelevant, though it can't be anything malicious. It doesn't even have to be able to start.

Example 1

The C program

main(){return 1;}

Compiled with Apple LLVM version 7.0.2 (clang-700.1.81) on OS X 10.11 (64-bit):

clang bomb.c -o bomb -pg

Produces a file of 9228 bytes. The total source size is 17+3 (for the -pg) = 20 bytes, which is easily within size limit.

Example 2

The Brainfuck program:

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

Transpiled with awib to c with:

./awib < bomb.bf > bomb.c

Then compiled with Apple LLVM version 7.0.2 (clang-700.1.81) on OS X 10.11 (64-bit):

clang bomb.c

Produces a file of 8464 bytes. The total input here is 143 bytes (since @lang_c is the default for awib it didn't need to be added to the source file, and there are no special flags on either command).

Also note that in this case, the temporary bomb.c file is 802 bytes, but this counts towards neither the source size nor the output size.

Final Note

If an output of more than 4GB is achieved (perhaps if somebody finds a turing complete preprocessor), the competition will be for the smallest source which produces a file of at least that size (it's just not practical to test submissions which get too big).

C, (14 + 15) = 29 byte source, 17,179,875,837 (16 GB) byte executable
Thanks to @viraptor for 6 bytes off.
Thanks to @hvd for 2 bytes off and executable size x4.
This defines the main function as a large array and initialises its first element.  This causes GCC to store the entire array in the resulting executable.
Because this array is bigger than 2GB, we need to provide the -mcmodel=medium flag to GCC.  The extra 15 bytes are included in the score, as per the rules.

main[-1u]={1};

Don't expect this code to do anything nice when run.
Compile with:
gcc -mcmodel=medium cbomb.c -o cbomb

It took me a while to get round to testing @hvd's suggestion - and to find a machine with enough juice to handle it. Eventually I found a old non-production RedHat 5.6 VM with 10GB RAM, 12GB swap, and /tmp set to a large local partition.  GCC version is 4.1.2.  Total compile time about 27 minutes.

Due to the CPU and RAM load, I recommend against doing this compile on any remotely production-related machine.

Python 3:

9**9**9**9**9

Tetration bomb


One Ring to rule them all. One String to contain them all Objectives: Output a String which contains every positive integer strictly below 1000.

The obvious answer would be to concatenate every one of them, and that would create a String of 2890 characters (thanks manatwork), to avoid this kind of easy answer, the length of the string must be under 1500 characters.
Here is a straightforward Java code which outputs a 1200 chars String.

import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;

import static org.junit.Assert.assertTrue;

/**
 * Created with IntelliJ IDEA.
 * User: fab
 * Date: 05/11/13
 * Time: 09:53
 * To change this template use File | Settings | File Templates.
 */
public class AStringToContainThemAll {

    @Test
    public void testsubStrings() throws Exception {
        String a = generateNewString();
        boolean cool = true;
        for (int i = 0; i < 1000; i++) {
            assertTrue(a.contains(Integer.toString(i)));
        }
    }

    private String generateNewString() {
        List<Integer> myTree = new ArrayList<Integer>();
        String finalString = new String("100");
        for (int i = 10; i < 1000; i++) {
            myTree.add(i);
        }
        while (myTree.size() > 0) {
            if (finalString.contains(Integer.toString(myTree.get(0)))) {
                myTree.remove(0);
            } else {
                String substringLong = finalString.substring(finalString.length() - 2, finalString.length());
                boolean found = false;
                loop:
                for (Integer integer : myTree) {
                    if (integer.toString().startsWith(substringLong) && !finalString.contains(integer.toString())) {
                        finalString = finalString.concat(integer.toString().substring(2, 3));
                        myTree.remove(integer);
                        found = true;
                        break loop;
                    }
                }
                if(! found){
                    finalString = finalString.concat(myTree.get(0).toString());
                    myTree.remove(0);
                }
            }

        }
        return finalString;
    }
}

Shortest code win, bonus point for the shortest String!


Evaluate the binomial theorem! Your mission, even if you don't accept it, is to input three numbers from STDIN or file:

  5 0.5 6

What you must do is evaluate this:

  (5a + 0.5b)^6

This basically means that the first two numbers are the coefficients of a and b and the third is the exponent in a binomial expansion.

Rules:

The first two numbers are either integers or simple terminating fractions.
The third number is a positive integer.
Do not use any inbuilt binomial functions from libs. (thanks to comments)
The shortest code wins!

Go on, do it.


Create a solar system Intro

This is based on an actual problem I recently faced while making a computer game and I thought it would make for a nice round of code-golf.

There are seven main spectral classes of star which put out varying amounts of heat. The geology of planets around a star are greatly influenced by the amount of heat received from the star, which is a factor of spectral class and distance from the star. Hence Mercury is practically molten, Neptune frozen.

The galaxy in my game is procedurally generated and randomly selecting planet types for given stars turned out to be a real 'if statement hell'!

The challenge

Your method should select one planet from a list of planet types appropriate for the class of star, based on a minimum heat threshold, a maximum heat threshold and a random number.
For simplicity this challenge will only use a class G star, just like our sun.

Inputs

An integer heat in the range 4 to 11 representing the amount of heat received by the planet from the star.

Variables

This table shows the possible planets based on heat. Your method should first narrow the available choices based on the heat min and heat max, heat should fall on or between the two. E.g. with a heat of 10 passed in the only choices would be Desert, Iron and Lava.

Planet type    Heat min   Heat max   Random Chance
Gas Giant         4          9            15
Ice               4          6            10
Ice Giant         4          6            10
Gaia class        5          7            10
Dense Atmosphere  7          9            10
Desert            7          10           25
Iron              7          10           14
Lava             10          11           6

Next, the probability of a planet (in the remaining choices) being chosen is its random chances divided by the sum of the random chances of all the choices.

In the above example, the probability of Iron being chosen is 14/(25+14+6).

Output

Return the planet type as a string.

Do the best you can to avoid logic arrowheads. Shortest code wins, points all round for creativity. Happy golfing!

Jelly, 78 bytes
“'ĖøÆḳƙ’ḃ7ṣ6+\+3r/ċ€×“½½½½©ÐÇı‘
“ŀỊẋ8ƒ³ẈRɼƈñqẋẏȧɱḌ<ṄỴḳ⁾ÆʋeẒĊ'@ƬØƓƝ}ḟ¬»ỴW€ẋ"ÇẎX

A monadic link accepting an integer (in [4,11]) which returns a list of characters.
Try it online!
How?
Creates the heat ranges of the planets as a list of lists and counts the occurrences of the input heat in those lists to get a list of zeros and ones representing which planet types are possible, then multiplies by the likelihood numbers of the eight planet types to get the distribution. The distribution is used to repeat the planet type names, and finally a uniform random choice is made.
“'ĖøÆḳƙ’ḃ7ṣ6+\+3r/ċ€×“½½½½©ÐÇı‘ - Link 1, getDistribution: integer
“'ĖøÆḳƙ’                        - base 250 integer = 39824688429662
        ḃ7                      - to bijective-base 7 = [1,1,2,4,7,1,4,4,6,2,2,2,2,1,5,3,3]
          ṣ6                    - split at sixes = [[1,1,2,4,7,1,4,4][2,2,2,2,1,5,3,3]]
             \                  - cumulative reduce with:
            +                   -   addition = [[1,1,2,4,7,1,4,4][3,3,4,6,8,6,7,7]]
              +3                - add three = [[4,4,5,7,10,4,7,7],[6,6,7,9,11,9,10,10]]
                 /              - reduce with:
                r               -   inclusive range = [[4,5,6],[4,5,6],[5,6,7],[7,8,9],[10,11],[4,5,6,7,8,9],[7,8,9,10],[7,8,9,10]]
                  ċ€            - count (input) in €ach e.g. for 5: [1, 1, 1, 0,0, 1, 0, 0]
                     “½½½½©ÐÇı‘ - list of code-page indices        [10,10,10,10,6,15,14,25]
                    ×           - multiply                         [10,10,10, 0,0,15, 0, 0]

“ ... »ỴW€ẋ"ÇẎX - Main link: integer
“ ... »         - compressed string = "Ice\nIce Giant\nGaia class\nDense Atmosphere\nLava\nGas Giant\nIron\nDesert"
       Ỵ        - split at new lines = ["Ice","Ice Giant","Gaia class","Dense Atmosphere","Lava","Gas Giant","Iron","Desert"]
        W€      - wrap €ach in a list
            Ç   - call last link (1) as a monad e.g. for 5: [10,10,10,0,0,15,0,0]
           "    - zip with:
          ẋ     -   repeat e.g. for 5:  [["Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice"],["Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant"],["Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class"],["Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant"]]
             Ẏ  - tighten               ["Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant"]
              X - a random choice from that list

PHP, 1236 bytes

<?php
$heat = (int)fgets(STDIN);
$planets =
    [
        'Gas Giant' =>        ['heat_min' => 4, 'heat_max' => 9, 'selection_chance' => 15],
        'Ice' =>              ['heat_min' => 4, 'heat_max' => 6, 'selection_chance' => 10],
        'Ice Giant' =>        ['heat_min' => 4, 'heat_max' => 6, 'selection_chance' => 10],
        'Gaia class' =>       ['heat_min' => 5, 'heat_max' => 7, 'selection_chance' => 10],
        'Dense Atmosphere' => ['heat_min' => 7, 'heat_max' => 9, 'selection_chance' => 10],
        'Desert' =>           ['heat_min' => 7, 'heat_max' => 10, 'selection_chance' => 25],
        'Iron' =>             ['heat_min' => 7, 'heat_max' => 10, 'selection_chance' => 14],
        'Lava' =>             ['heat_min' => 10, 'heat_max' => 11, 'selection_chance' => 6],
    ];
foreach ($planets as $planet) {
    $chance_sum += ($heat >= $planet['heat_min'] && $heat <= $planet['heat_max']) * $planet['selection_chance'];
}
while (true) {
    foreach ($planets as $name => $planet) {
        $prob = 100 * ($heat >= $planet['heat_min'] && $heat <= $planet['heat_max']) * $planet['selection_chance'] / $chance_sum;
        if (rand(0, 100) < $prob) {
            echo $name."\n";
            exit;
        }
    }
}
?>

Try it online!


Reimplementing square root Define a function, s, which takes a number and returns the square root.

No use of library functions, such as Java's Math.sqrt() or PHP's built in sqrt(), allowed.

Python - 11 chars

Technically not a library function :)

input()**.5

As a function it's 16 chars

f=lambda x:x**.5

/*Fast inverse square root*/
/* from http://en.wikipedia.org/wiki/Fast_inverse_square_root */
float rsqrt( float y,int iter)
{
    const unsigned int fpMagic = 0x5f3759de << 1;
    /*evil floating point bitlevel hacking*/
    unsigned int *i;
    if (sizeof(int) != sizeof(float))
    return -1.0;
    int j;
    const float threehalfs = 1.5F;
    float x2 = y * 0.5F;
    void *p = &y;
    i = p;
    *i = (fpMagic - *i) >> 1;
    /* Newton iterations */
    for (j=0; j < iter; j++)
    {
    y  *=  threehalfs - ( x2 * y * y ) ;
    }
    return 1.0 / y;
}


Code that will only execute once Goal

The goal of this challenge is to write code that will execute once and only once.  This means basically that it damages the program, script, or environment in some way.  If rebooting the system allows the code to run again that is permitted.

Scoring

Number of votes.  All assumptions must be clearly listed.  Any answers just initiating a reboot or halt will be disqualified.

Additional Rules because Greg Hewgill is a demi-god

No root access is permitted.

End Date

The contest will close on May 31, 2014.

Edit

This contest has been changed to popularity contest.

Vigil
Finally a usecase for Vigil!
def main():
  raise Exception()

Excerpt from the "language specification":

It goes without saying that any function that throws an exception which isn't caught is wrong and must be punished.
...
If an oath is broken, the offending function [...] will be duly punished.
How?
Simple: it will be deleted from your source code.
The only way to ensure your program meets its requirements to absolutely forbid code that fails to do so. With Vigil, it will do this for you automatically.

There are other ways to do this, because Vigil provides the keywords implore and swear which are basically oaths to adhere to certain pre- and post-conditions:
def main():
  swear 0 > 1

Bash file linux

#!/bin/bash
shutdown -h now


Compress your code in an image This is a quine variation.
Introduction
We all write short code, because some obscure reasons, but whatever we do, the'll take up at least 144 pixels/byte (with a 12px font). But what would happen, if we would encode our code in images? This is your task today.
Challenge
You task is to read in your own source code (non-proper quines are allowed, e.g. literally reading the source file), and create an image out of it, by setting the red, green and blue components of a pixel based on the ASCII value of the character.
Example:
We have the string "Hello world!"
Hello world!

Let's convert this to ASCII values:
72 101 108 108 111 32 119 111 114 108 100 33

Map the RGB values to it (If the source code's length is not divisible by 3, use 0s as the remaining characters):
 __________________________________________________
| R | G | B || R | G | B || R | G | B || R | G | B |
----------------------------------------------------
|72 |101|108||108|111|32 ||119|111|114||108|100|33 |
----------------------------------------------------

We then create the image with the smallest area out of it. We have 4 sets of RGB values, so the smallest image will be a 2*2 image, going from the top left pixel to the right:

And we get this awfully colored image (resized, so it's at least visible, also proves the fact how small it can get)
Rules/Additional information

There's no input
The output should be as a separate file, or in a separate window.
For multibyte characters, split the character in 2 bytes.
The source code must be at least 1 byte long
The image should be the one from the possible sizes, wich has the closest width/height ratio to 1
The pixel count on the image should exactly be ceil(byte count / 3), no extra pixels should be added

Scoring
This is a code-golf, so the smallest answer in bytes wins.

MATLAB, 81 72 69 bytes
@()image(shiftdim(reshape(evalin('base','char(ans)'),3,1,23)/255,1.))

This creates an anonymous function which can be pasted into the command window and run using ans(). When run this creates a 23-pixel image (a prime) therefore the most square representation is a simple array of pixels.

Explanation
When pasted into the command window, the anonymous function will automatically assign itself to the variable ans. Then from within the anonymous function, we use:
evalin('base', 'char(ans)')

which evaluates char(ans) within the namespace of the command window rather than within the local namespace of the anonymous function. It is therefore able to convert the anonymous function itself into a string representation.
Then we have the following operations which are more straightforward:
%// Reshape the result into a 3 x 1 x 23 matrix where the first dimension is RGB
%// due to column-major ordering of MATLAB
R = reshape(string, 3, 1, 23);

%// Divide the result by 255. This implicitly converts the char to a double
%// and in order for RGB interpreted properly by MATLAB, doubles must be
%// normalized between 0 and 1.
R = R / 255;

%// Shift the dimensions to the left 1 to move the RGB channel values into
%// the third dimension. Note the extra decimal point. This is because it
%// is far shorter to lengthen the code by one byte than to pad the string
%// to give us a length divisible by 3
R = shiftdim(R, 1.);

%// Display the RGB image
image(R);

Python, 81 bytes

q=open(__file__).read()
print'P3\n9 3 256 '+' '.join(map(lambda x:str(ord(x)),q))

Output is in PPM format.

This is what the image looks like:

Scaled up:


Programming Less-Than, Greater-Than and Equal-To functions using Restricted Source I'm currently working with a branchless language which does not have native Less-Than, Greater-Than or Equal-To functions. I do however have min, max and abs functions and standard arithmetic (+, -, / and *) available to me.
I'd like to create these three functions (as L(a, b), G(a, b) and E(a, b) respectively, which will output 0 for false and 1 for true. So, for example, L(3, 7) would return 1 for true whereas G(3, 7) would return 0 for false, and E(3, 7) would also return 0, etc.
The min and max functions only allow you to pass two parameters, a and b, and then spits out the respective minimum or maximum of the two parameters. The abs function takes the one parameter and returns the absolute value.
I've postulated that given that the min(a, b) is equivalent to:
L(a,b) * a + (1 - L(a,b)) * b
It would stand to reason that:
L(a,b) = (min(a,b) - b) / (a - b)
and similarly:
max(a,b) = G(a,b) * a + (1 - G(a,b)) * b
therefore:
G(a,b) = (max(a,b) - b) / (a - b)
But this is where I get stumped because, I'm not sure how to account for the possibility of a-b equalling 0 in both instances, which as a result stumps me on how to approach the E(a, b) function.
So my question is this... Given that I only currently have access to basic arithmetic functions as well as min(a,b), max(a,b) and abs(a), and because of the language being branchless (therefore no loops), is there a way to programmatically account for the a-b divide-by-zero issue such that if I do have a scenario where a == b that these functions can return zero for either L() or G(), otherwise output the original equations I have derived, and also be able to provide code for E(a, b)?
Given that this is fairly generic (hey, I've written it in psuedocode!) I'd appreciate some insight on how to proceed. In this case, the solution needs to work with both integers as well as floats.
Context: This is research for a personal project I'm working on relating to binary registers, thus the need for 1's and 0's for output and I'm kinda stuck at this point.

Integers and round-to-zero integer division
// 1 if x >= y, 0 otherwise
GE(x, y) = (x - y + 1) / (abs(x - y) + 1)
LE(x, y) = GE(y, x)
E(x, y) = GE(x, y) * LE(x, y)
L(x, y) = LE(x, y) - E(x, y) = 1 - GE(x, y)
G(x, y) = GE(x, y) - E(x, y) = 1 - LE(x, y)

If x - y is negative, x - y + 1 has smaller magnitude than abs(x - y) + 1, so the division rounds to 0.
If x - y is zero or higher, x - y + 1 is the same as abs(x - y) + 1, so the result is 1.
Integers and floored integer division
GE(x, y) = (x - y + abs(x - y) + 1) / (abs(x - y) * 2 + 1)

If x - y is negative, the numerator is fixed at 1, but the denominator is at least 3. Therefore the result is zero.
If x - y is zero or positive, the numerator and the denominator are the same, so the result is 1.
Floating-point numbers
MarcMush pointed out a possible use of eps, the smallest representable number greater than 0. GE can be implemented for floating-point numbers using it:
GE(x, y) = (max(x - y, -eps) + eps)/(abs(x - y) + eps)

I haven't found any way without eps or the floor function. (If floor is available, flooring the second solution works for floats.) tsh pointed out that we can't get a (true) discontinuous function from a bunch of continuous functions, so I'm pretty sure it is impossible without eps or an additional built-in that provides discontinuity.
Assuming an IEEE floating-point representation, the solution above is expected to give exact results (exactly 0 or exactly 1) for all non-NaN, non-infinite floating-point values of x and y.

Assuming floor division:
E(x,y) = (1 - abs(x-y)) / (1 + abs(x-y))
L(a,b) = E(min(a,b), a) - E(a,b)
G(a,b) = E(max(a,b), a) - E(a,b)