You're on a 8 day streak! Duolingo, the language learning app, has a lot of things going for it, but there is one major issue that drives me crazy. It tells me how many days in a row I've used the app with a message like You're on a 7 day streak! Setting aside hyphenation and whether the number should be spelled out, this works fine for most numbers, but is indisputably wrong when it says You're on a 8 day streak! I'm not using it to learn English but this is still unfortunate behavior for a language app.

You're going to help out the Duolingo team by writing a complete program or function that figures out whether a given number should be preceded by a or an. A number is preceded by a if its pronunciation in spoken English begins with a consonant or semivowel sound, and preceded by an if its pronunciation begins with a vowel sound. Thus the only numbers preceded by an are those whose pronunciation begins with eight, eleven, eighteen, or eighty.

Presumably the Duolingo dev team left this bug in because they ran out of space for more source code in the app, so you need to make this code as short as possible in the hopes they can squeeze it in.

Your code must take an integer from 0 to 2,147,483,647 and output a or an. A trailing newline is optional. For the purposes of this challenge, 1863 is read as one thousand eight hundred and sixty-three, not eighteen hundred and sixty-three.

Test cases:

0 → a
8 → an
11 → an
18 → an
84 → an
110 → a
843 → an
1111 → a
1863 → a
8192 → an
11000 → an
18000 → an
110000 → a
180000 → a
1141592 → a
1897932 → a
11234567 → an
18675309 → an

Python 2, 60 bytes
lambda n:'a'+'n'[:`n`[0]=='8'or`n`[:2]in len(`n`)%3/2*'118']

An anonymous function. Adds an n if either:

The first digit is 8
The first two digits are 11 or 18, and the length is 2 modulo 3.

Perl, 71 55 49 bytes

$_=<>;$_=/^8/||/^1[18]/&&length%3==1?'an':'a';say

I knew the ternary operator would help one day...

Let me break this down.

$_=<> accepts a number as input.
The big $_=... block will set the value of $_ after it's used.

...?...:... is the ternary operator. If the condition (first argument) is true, it returns the second argument. Otherwise, it returns the third.
/^8/||(/^1[18]/&&length%3==2) checks to see if the number starts with 8 or begins with 11 or 18 (1[18] accepts either) and has a length mod 3 of 2.
If that's true, $_ is set to an. Otherwise, it's set to a.

It then prints out the contents of $_ (either a or an) with say.

Changes

Saved 16 bytes thanks to msh210.
Saved 6 bytes by removing parens and using defaults.


Another amicable number problem Two numbers are said to be 'amicable' or 'friends' if the sum of the proper divisors of the first is equal to the second, and viceversa.  For example, the proper divisors of 220 are: 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110 which sum up to 284.  284's proper divisors are 1, 2, 4, 71 and 142, which sum to 220, thus 220 and 284 are friends. Write a function which returns true if and only if a number is a friend of some other number.

Examples:

friend(220) ==> true

friend(7) ==> false

friend(284) ==> true

Function with least number of chars wins.

NOTE: I just found out that there is a similar question, but I believe this one is simpler and perhaps more general.

Python, 67

a=lambda x:sum(i for i in range(1,x)if x%i<1)
b=lambda x:x==a(a(x))

GolfScript (25 chars)

{.{:a,(\{.a\%!*+}/}2*=}:f

a can, of course, be replaced by the name of any other variable whose contents you don't care about.


Implementing bool() without any conditionals Title says it all. Given some input, turn it into a boolean value (0 or 1), without using conditional statements (e.x. == > < <= >= != ~=), or any function which uses conditional statements within its implementation, such as if, while and for. Your program must work with floating points, although you get more if it works with other items.

A general rule for determining whether bool(item) is False is if the item is empty ('' is an empty string, [] is an empty list.), or if the function used to turn an item of one type into another is given no input (in Python, str() returns '', list() returns [].)

Here are (some of) the different valid types. Your program is considered to work with one type if it works with one item in the following lists:

Integers, floating points, doubles, longs
Strings
Lists, tuples, arrays (bytearrays)
Dictionaries
Functions
Objects/Classes

Program score will be calculated like this: [# of characters]-(50*[# of types]). The program with the smallest score wins the challenge.

Python - 122 chars - 50*13 types = -528

def b(x=False):
 try:return[False][x]
 except IndexError:return True
 except:
  try:return b(len(x))
  except:return True

Works for the following built-in types (as listed in §3.2 The standard type hierarchy)

NotImplemented
Ellipsis
int
long
bool
string
unicode
tuple
list
bytearray
set
frozenset
dict

Perl, 5 char

1-!$x

Works for integers, floating-point values, strings, and C. Although in Perl, these are all the same type.


That's not my X, its Y is too Z This challenge is inspired by a series of young children's books by Fiona Watt and Rachel Wells, which I've recently been enjoying with my daughter.

In each book a mouse (illustrated, but not part of the text) complains that a succession of 5 things of the same type are not its thing. It then backs this up by declaring that some component of the thing doesn't have the property it expects.

On the sixth time of asking, the mouse finds its thing and is pleased because it has the expected property.

Here is the text of a typical example:

That's not my bunny, its tail is too fluffy.
That's not my bunny, its paws are too rough.
That's not my bunny, its tail is too woolly.
That's not my bunny, its eyes are too shiny.
That's not my bunny, its nose is too wrinkled.
That's my bunny! Its ears are so soft.

Now, most programming folk would realise that this is a very algorithmic method of producing some text. Because it's such a clear process, we should be able to reproduce this by writing some code.

Let's start with three collections of words:

things = ["dinosaur", "lamb", "princess", "reindeer", "train"]
parts = ["back", "bells", "body", "bows", "crown", "dress", "ears",
  "engine", "fan", "flippers", "funnel", "hooves", "horns", "neck",
  "nose", "roof", "sash", "side", "spines", "spots", "tail", "teeth",
  "tiara", "wheels", "windows"]
properties = ["bumpy", "fluffy", "furry", "fuzzy", "glittery", "glossy",
  "hairy", "red", "rough", "rusty", "shiny", "silky", "slippery",
  "soft", "sparkly", "squashy", "thick", "velvety", "woolly"]

First, we decide which kind of thing we will be describing.
Then 5 times, we will generate the line "That's not my [thing], its [part] is too [property].
Finally, we generate the line "That's my [thing]! Its [part] is so [property]!

The challenge

Generate the text of a "That's not my..." story.
It must not consistently reproduce the same text.
It's code golf, so attempt to do so in the smallest number of bytes.
Use any language you please.
White space doesn't matter, but there must be a newline character between lines.
The lists of source words are not part of your answer (in TIO they can be added to the header).
You can rename the lists of source words.
Output can be output to a terminal or text generated into an object.
Please include a link to an online interpreter.
Ignore plurals, "its horns is" is fine.
It doesn't need to make sense. If your princess's funnel is too fluffy, just say so.

Sample output:

That's not my train, its engine is too rusty.
That's not my train, its hooves is too thick.
That's not my train, its sash is too fuzzy.
That's not my train, its tail is too velvety.
That's not my train, its horns is too glittery.
That's my train! Its hooves is so hairy.

Happy golfing!

Python 3, 149 bytes

lambda a,*l:shuffle(a)or["That's "+s%(a[0],*map(choice,l))for s in["not my %s, its %s is too %s."]*5+["my %s! Its %s is so %s."]]
from random import*

Try it online!

-9 bytes thanks to movatica

Python 3, 130 bytes
Taking your requirements literally, and taking carriage returns to be one byte each:
y=0
def x():
    global y
    y=1-y
    print(("That's not my lamb, it's "+b[0:1][y]+" is too red\n")*5+"That's my lamb! Its fan is so red")


Generate a 5-pointed star Your challenge is generate a 5 pointed star like below. The star doesn't need to be filled.
Shortest code wins.

PHP, 1 character
Although very short it will probably not become the accepted answer.
☆

(this is U+2606). May work also in other languages (untested).

TI-83/84 Basic, 32 bytes
Line(0,1,1,1:Line(0,0,.5,1.5:Line(1,0,.5,1.5

Note I haven't actually tested this out but I'm assuming it's going to show up as a low resolution, distorted star-shaped object.

Line( command is one byte


Find the shortest pangrams from a word list A pangram is a string that contains every letter a-z of the English alphabet, case-insensitive. (It's OK if the pangram contains more than one copy of a letter, or if it contains non-letter characters in addition to the letters.)

Write a program or function whose input is a list of strings, and which outputs one or more strings which have the following properties:

Each output string must be a pangram.
Each output string must be formed by concatenating one or more strings from the input list, separated by spaces.
Each output string must be the shortest, or tied for the shortest, among all strings with these properties.

Many programs will choose to output only one string; you'd only want to output more than one string if you'd otherwise have to write extra code to limit the output.

You may assume that the input contains no unprintable characters or spaces, and that no word in it is more than (26 times the natural logarithm of the length of the list) characters long. (You may not assume, however, that the input contains nothing but letters, or only lowercase letters; punctuation marks and uppercase letters are entirely possible.)

Input and output can be given in any reasonable format. For testing your program, I recommend using two test cases: a dictionary of English words (most computers have one), and the following case (for which a perfect (26-letter) pangram is impossible, so you'd have to find one containing duplicate letters):

abcdefghi
defghijkl
ijklmnop
lmnopqrs
opqrstuvw
rstuvwxyz

You should include a sample of your program's output along with your submission. (This may well be different for different people as a result of using different word lists.)

Victory condition

This is a restricted-complexity code-golf challenge. The winner is the shortest program (in bytes) that runs in polynomial time. (A summary for people who don't know what that means: if you double the size of the word list, the program should become slower by no more than a constant factor. However, the constant factor in question can be as large as you like. For example, it's valid for it to become four times slower, or eight times slower, but not for it to become smaller by a factor of the length of the word list; the factor via which it becomes slower must be bounded.)

Ruby 159 (iterative)

Ruby 227 220 229 227 221 (recursive)

New iterative solution (based on the algorithm described by @Niel):

c={('A'..'Z').to_a=>""}
while l=gets
d=c.clone
c.map{|k,v|j=k-l.upcase.chars
w=v+" "+l.strip
d[j]=w if !c[j]||c[j].size<w.size}
c=d
end
x=c[[]]
p x[1..-1] if x

Old recursive solution:

W=[]
while l=gets
W<<l.strip
end
I=W.join(" ")+"!!"
C={[]=>""}
def o(r)if C[r]
C[r]
else
b=I
W.map{|x|s=r-x.upcase.chars
if s!=r
c=x+" "+o(s)
b=c if c.size<b.size
end}
C[r]=b
end
end
r=o ('A'..'Z').to_a
p r[0..-2] if r!=I

The byte measurement is based on leaving off the final newline in the file, which does not matter to ruby 2.3.1p112. The byte count went back up after fixing a small bug (adding .downcase .upcase for case-insensitivity as required by the problem statement).

Here is an earlier version from before shortening identifiers and such:

#!/usr/bin/env ruby

$words = [];

while (line=gets)
  $words << line[0..-2];
end

$impossible = $words.join(" ")+"!!";

$cache = {};

def optimize(remaining)
  return $cache[remaining] if ($cache[remaining]);
  return "" if (remaining == []);

  best = $impossible;

  $words.each{|word|
    remaining2 = remaining - word.chars;
    if (remaining2 != remaining)
      curr = word + " " + optimize(remaining2);
      best = curr if (curr.length < best.length);
    end
  };

  $stderr.puts("optimize(#{remaining.inspect})=#{best.inspect}");

  return $cache[remaining] = best;
end

result = optimize(('a'..'z').to_a);

puts(result[0..-1]);

How does it work? It basically maintains a set of characters still to cover and only recurses on a word if it would reduce the uncovered set. Additionally, the results of recursion are memoized. Each subset of 2^26 corresponds to a memoization table entry. Each such entry is calculated in time proportional to the size of the input file. So the whole thing is O(N) (where N is the size of the input file), albeit with a huge constant.

Python 3, 98, 94, 92 bytes

print([s for s in input().split()if sum([1 for c in range(65,91)if chr(c)in s.upper()])>25])

Iterates through the ASCII representation of the alphabet and adds a 1 to a list if the letter is found in the string. If the sum of the list is greater than 25 it contains all letters of the alphabet and will be printed.


Smallest positive number whose y-th power is divisible by x Task

Given integers x and y which are both at least 2, find the smallest positive number whose y-th power is divisible by x.

Example

Given x=96 and y=2, the output should be 24 since 24 is the smallest positive n satisfying n^2 is divisible by 96.

Testcases

x  y output
26 2 26
96 2 24
32 3 4
64 9 2
27 3 3

Scoring

This is code-golf. Solution with lowest byte-count wins.

References

y=2: OEIS A019554
y=3: OEIS A019555
y=4: OEIS A053166
y=5: OEIS A015052
y=6: OEIS A015054

Brachylog, 19 17 16 15 12 bytes
2 bytes saved thanks to @LeakyNun.
:[I:1]*$r=#>

Try it online!
Explanation
               Input = [X, Y]
:[I:1]*        Get a list [X*I, Y] (I being any integer at this point)
       $r=     Get the first integer which is the Yth root of X*I
          #>   This integer must be strictly positive
               This integer is the Output

PHP 59 bytes
Sorry, but I can't test this from my mobile. :)
function blahblah($x,$y){
  for($i=0;1;$i++){
    if(!$i^$y%$x){
      return $i;
    }
  }
}

Golfed
function b($x,$y){for($i=0;1;$i++){if(!$i^$y%$x)return $i;}


Shortest code that raises a SIGSEGV Write the shortest code that raises a  Segmentation Fault (SIGSEGV) in any programming language.

C, 5 characters

main;

It's a variable declaration - int type is implied (feature copied from B language) and 0 is default value. When executed this tries to execute a number (numbers aren't executable), and causes SIGSEGV.

Try it online!

.mmo (MMIX executable), 28 bytes (7 tetras)
Doesn't cause emulator segfault, but the program itself does segfault.
Negative addresses are reserved for the OS, and a fault occurs if the protection bit in rK is the same as the high bit of the instruction pointer, which it will be when the OS tries to start this program at the address given to start.
00000000: 98090100 980a00ff 8fe6a7d6 9b16daee  Ƭµ¢¡Ƭ½¡”Ɓȧʂẹɓæḷŀ
00000010: 980b0000 00000000 980c0001           Ƭ¿¡¡¡¡¡¡Ƭ€¡¢

98090100 lop_pre 1,0                // version 1, 0 tetras
980A00FF lop_post 255               // and immediately jump to postamble
8FE6A7D6                            // almost arbitrary address to start at
9B16DAEE                            // must have high bit set
980B0000 lop_stab
00000000                            // no tetras in symtab
980C0001 lop_end


Most optimized algorithm for incrementing squares Write the "fastest" program to print an incrementing series of squares from a given input to a given input.

Example input:

-2
7

Example output:

4, 1, 0, 1, 4, 9, 16, 25, 36, 49

When using a "cryptic" language, please post the pseudocode, in addition to your program.

The entries will be judged on the most efficient algorithm.

The tag says "code-challenge", but I don't see any challenge. Just some mathematics we studied when I was about 12.

import java.util.*;

public class IncSquares
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        int min = in.nextInt();
        int max = in.nextInt();

        int sq = min * min;
        System.out.print(sq);
        while (min < max) {
            sq += (min << 1) + 1;
            min++;
            System.out.print(", " + sq);
        }
        System.out.println();
    }
}

(z + 1)^2 = z^2 + (2z + 1)

We already know z^2, and 2z is simply z<<1.

(z + 1)^2 = (z^2) + (z << 2 + 1)

Now just memorize this trick if you want to list squares in your head.

If you've got an arbitrary [two-digit] square (to do in your head), z^2, do this:

z^2 = (z-n)*(z+n) + n^2

Or:

23^2 = (23-3)*(23+3) + 3^2
23^2 = 20*26 + 9
23^2 = 520 + 9
23^2 = 529

Works even "faster" with larger numbers, relative to you doing 97*97 in your head. Have fun showing off.


Windows Error Boxes to the next level You know those Windows boxes where you can only do one thing?

Let's take this to the next level!

Challenge

Make a dialog box with a button that follows your cursor everywhere!

Specs

No input may be taken. There may be output to either STDOUT or STDERR. You must open a window with one button (no text is necessary, but text may be contained in either the window title, the dialog box, or the button). The button must be clickable, and it must always follow under your cursor so that you can only click it. Upon clicking, it can do anything you want, but please do not make it crash a computer because I will be testing this... The dialog box must stay open for as long as the button is not pressed, but it does not need to close when the button is closed.

Assumptions that you can make

You may assume that the cursor will stay within the drawing canvas.
You may assume that the window will stay in focus, but you must not put the window out of focus as long as the button is not pressed.

Example Pseudocode

Here's some example pseudocode:

Open Dialog Box
Add Button to Dialog Box at position X, Y
WHILE True:
    SET Dialog Box to CursorX - X, CursorY - Y

Test Cases cannot be provided for this challenge

This is a code-golf challenge, so the shortest valid submission by March 14th (Pi Day) wins!

MATLAB, 86 63 bytes
set(warndlg,'WindowButtonM',@(s,e)movegui(get(0,'Po')-[99,20]))

This solution takes advantage of MATLAB's (typically annoying) ability to use partial property names as long as the part that is provided is unique to only the property of interest.
This solution uses the builtin warndlg to create a warning dialog with an "OK" button. This function returns a figure handle which we can then use to set the WindowButtonMotionFcn callback (using the short name 'WindowButtonM').
The callback that is evaluated any time the cursor is moved within the window gets the current position of the cursor (using the PointerLocation property of the root graphics object, using it's short name 'Po'). We then update the Position of the figure using movegui and specifying the new location of the figure after applying an offset of [99, 20] so that the cursor is placed on the button.
When the button is finally clicked, the figure is deleted and all callbacks are automatically released.

Javascript (ES6) + HTML + CSS, 139 bytes

HTML:

<d id=d><button>X

CSS:

d{background:red;padding:9px;position:absolute

Javascript:

onmousemove=e=>{with(d.style){top=e.clientY-20+'px';left=e.clientX-20+'px'}}

Since you can't position alert dialogs, I made my custom super fancy dialog in HTML. The javascript registers an event handler on the window object and sets the position to the coordinates of the event.

Try it online: https://jsfiddle.net/1yohswje/


It's a yearly task, alright Given a number 1≤n≤365, output the nth day of the year in "Day-numberth Month" format. For example, given 1, you should output "1st January", without "of".

The Gregorian calendar will be used and the program should not account for leap years, so your program should never output "29th February" in any circumstance. Any method can be used, as long as it follows the "Day-numberth Month" format mentioned before. Your program should also output ordinals correctly, meaning it should always output 1st, 2nd, 3rd, should 1, 2 or 3 respectively be the day numbers for any input. Leading spaces or other indentation are allowed.

This is code golf, so the shortest solution by characters wins.

Test cases:

1 gives 1st January
2 gives 2nd January
3 gives 3rd January
365 gives 31st December
60 gives 1st March
11 gives 11th January

PHP, 38 40 30 28 bytes

<?=date("jS F",86399*$argn);

Try it online!

Run with php -nF input is from STDIN. Example (above script named y.php):

$ echo 1|php -nF y.php
1st January
$ echo 2| php -nF y.php
2nd January
$ echo 3| php -nF y.php
3rd January
$ echo 11|php -nF y.php
11th January
$ echo 21|php -nF y.php
21st January
$ echo 60|php -nF y.php
1st March
$ echo 365|php -nF y.php
31st December

Explanation

Construct an epoch timestamp for the desired day in 1970 (conveniently not a leap year) by multiplying the day number * number of seconds per day (86400).  However, this would yield one day higher so instead multiply by number of seconds in a day - 1 (86399) which for the range of input numbers (1≤n≤365) will result with the timestamp of the end of each correct day. Then just use PHP's built-in date formatting for output.

Python 3, 95 Bytes

Datetimed it :P

from datetime import *;f=lambda s:(datetime(2019,1,1)+timedelta(days=s-1)).strftime("%d of %B")

Try it online!


Print all numbers from -100 to 100 which contain a given digit Provided a digit between 0 and 9 (inclusive), your function/subroutine should print all numbers between -100 and 100 (inclusive) that contain the given digit.

For example:

Input: 9
Output: -99 -98 -97 -96 -95 -94 -93 -92 -91 -90 -89 -79 -69 -59 -49 -39 -29 -19 -9 9 19 29 39 49 59 69 79 89 90 91 92 93 94 95 96 97 98 99

Rules:

You cannot use strings (in whatever way they are represented in your chosen language) or char arrays. (Except to print the answer to the console.)
You cannot use arrays.

Scoring:

Score = length of subroutine/function (whitespace will not be counted)

The answer with the lowest score wins.

Whitespace will NOT be counted. Please format your code properly!

Some answers are using regular expressions, which may violate the no strings rule, as pointed out by some members. These answers will not be accepted.

Please test your code with 0 before posting.

Whitespace, 834 characters (0 if you subtract whitespaces)

Used this interpreter to test it.

This took me some 4 hour of hard work and horrible debugging to create. But it is done!

EDIT: Selectable text provided with HTML tricks. If you copy and paste it from here to some other place, please check if you got exactly [space][tab][linefeed][linefeed][linefeed] at the end with 100 or 101 lines (depending if your editor counts or not a new line if the last one ends with a linefeed).

In the case that you can't use it this way, considering space as S, linefeed as L and tab as T, and breaking lines after the L's, here it is:

SSSTSSSSTSL
SSSTSSSSTSL
TL
TSSSSTSSSSTSL
TTTSSSTTSSSSL
TSSTTTSSSSTSSSSTTL
SSTTTSSSTTL
TTSSSSTSSSSSTL
SSSL
TTSSSSTSSSSTSL
TTTL
TSSTSSTSTTL
SSSTSSSSTSL
TTTSSSTL
TSSTL
TSSTSSTSTTL
L
SSSTSSSTSSL
SSSTSSSSTTL
TTTSL
SSSSTTSSTSSL
TSSTL
TSSTSSSTSTL
SL
SSSTTL
TSSL
L
TTSTSSSTTTL
SSTTL
TSSL
L
SSSTSSSTTTL
SL
SSSSTSSSSTSL
TTTL
TSSTSSTSSSL
SSSTSTSL
TSTSSSSTSSSSTSL
TTTTSSTL
TSSTSSTSSTL
L
SSSTSSTSSSL
SSSTSTSL
TSTTSSSTSSSSTSL
TTTTSSTL
TSSTSSTSSTL
L
SL
STSSTSTSL
L
SSSTSSTSSTL
SSSTSSSSSTL
TTTL
TSSTSSSTTSL
SSSTSSSSSL
TL
SSL
SSSTSSSTTSL
SSSTSSSSSTL
SSSTL
TTSSSSTSSSSTTL
TTTTL
STL
SSSTSSTSTSL
SSSTSSSSTTL
SSSTSSSSTTL
TTTSSSTL
TSSSTTSL
SL
STSSSTSSL
L
SSSTSSSTSTL
SSSTSSSSTSL
TTTL
TSSTSSTTSSL
SSSTSSSSTSL
TTTSSSTL
TSSTL
TSSTSSTTSSL
L
L
L
L
SSSTSSTSTTL
SSTTTSSTSSL
TL
STSSSTSSSSSL
TL
SSL
SL
STSSSTSSL
L
SSSTSSTTSSL
SSSTSSSSSL
TL
SSSSSTTSSTSSL
TL
STL
L
L

Javascript (72 93 bytes):

Here is my fixed try with Javascript:

    function(n,i){for(i=-101;i<100;~String(++i).search(n)&&console.log(i));}

function(n,i){for(i=-101;i<100;~window.String.prototype.search.call(++i,n)&&console.log(i));}

To use this, simply what it around () and add (<number>) at the end.

The most important part is only 57 bytes (without the function declaration).

Here is an ungolfed version and usage example:

(function(n){
    for(var i=-101;i<100;++i)
    {
        if(window.String.prototype.search.call.search(++i,n)>=0)
        {
            console.log(i);
        }
    }
})(0);

I had a 'talk' with the original poster and he was arguing that window.String is a string object, but I will keep this answer because I only want the prototype of the object.


Obfuscation Challenge You are to write a program that does one of the following.

Only displays "Hello World" does nothing else
Quits and nothing else (no output, no errors.)
Takes one line of input, parses it as an integer, displays the first that many primes (or gives a nice error if it is given input that can't be parsed as an integer, or is less than 0.)
Given one line of input, it parses it has a stock symbol, and checks online for the current stock value and its change.

The catch, it should not be apparent which function it performs. Namely, for someone looking at your code, it should not be apparent which function it will do. Also, it may only perform and be able to perform one function (it can not pick and choose.) How good a program is is determined by how uncertain someone is that looks at it as to what its function is, and also how familiar that person is with that language.

BONUS:
If you in a clever way make it so although for any one compiler/intrpreter and platform, the program will also perform the same function, different compilers/interpreters or platforms, it will perform a different function. This bonus may only be collected if done cleverly.

BONUS:
If your program only contains code that is capable of one function (save nothing, as empty code is capable of that), and it is not possible to make a simple modification unrelated to the function to allow it to perform a different function.
For example: if you did

obfuscatedBool = 1g8uhad'l8fygrcetdu8y4fd/,.oe87fy4d --Magic
if obfuscatedBool: print "Hello World"

Would not count as obfuscatedBool could be made True or False to make it print "Hello World" or do nothing respectively.

INFINITY BONUS: If you realize both bonuses simultaneously, you are magic.

NEGATIVE BONUS: Using libraries with specific abilities to do the functions.

Voters, take the bonuses in to consideration, because the program with the most votes wins!

Note: If you say what your program does, make sure to use spoiler syntax!

Whitespace/Brainfuck/Python

'''begin''''''''''''
main(args){
	parseArgs=args.Find('^++++++++^[<++++[<++<+++<+++<+>>>>a-z]<+<+<A-Z[>]>0-9]<<.<---.*$');
    for(int i=0;	Range(GetLength(parseArgs));	i++){validateArg(parseArgs(i));}
	//name
    string stockName="";
	//loop
    for(int i=0;Range(GetLength(parseArgs));i++){
	//validate
     	if(matchFound=Find('a+z+A+.Z.0+9+_+.<<*$'){
	//found
     	parseArgs(i).Split('>-.>.+');}

     	for(int j=0;Range(GetLength(parseArgs(i)));j++){
	//download
    data=ConvertTo.String(eval("curl -get	http://some-stock-ticker-source-url-here.com"));
	print;
    print data;

    //line separator

    print "--------.";
	}}
}

''finish'''''''''''''''

Wikipedia: Whitespace (programming language)
Online Whitespace Interpreter to Test Answer
Online Brainfuck Interpreter to Test Answer

   Output (Whitespace/Brainfuck):
 Hello World

 Ouput (Python):
 Nothing, but runs successfully.

C

#include <stdio.h>
int main(void) {
    int numbers[] = {1, 2, 3, 4};
    printf("%d\n", numbers[42]);
}

   This can do anything, and you won't know what will happen. In theory, undefined behavior in C is allowed to do anything, including the behaviors you mentioned. Obviously, it doesn't happen in most compilers, but perhaps somebody could fine one where this happens.


all occurences of each line from a file in another file for each line in the first file This is a code golf problem: Say you have two files, one file s and one  file h. The problem is that for each line l of s you should produce a list that contains all lines of h that contain l. By "contain" I mean a substring, so, for example the line "foobar12baz" contains either foo, bar, foobar, 12, 1 or baz, etc...

You may use any programming language or any program to accomplish this in the least number of characters possible. Instead of a list you may print an array, or other sequence type structure.

Here is some Haskell I wrote that does it in 103 characters, and assumes you have the following modules imported

Data.List

Control.Monad

Control.Applicative

let f = (<$>) lines . readFile in (\(a,b)-> [[d|d<-b, isInfixOf c d]|c<-a]) <$> liftM2 (,) (f "s") (f "h")

Example files:

"h"

asdf1
asd2asdf
s3adsf

"s"

1
2
3

Output:

[["asdf1"],["asd2asdf"],["s3adsf"]]

while read -r;do grep "$REPLY" --h>"$REPLY";done<s

YEAAAAAAAH!!1


How to write a C program for multiplication without using the * and + operators? Is it possible to write a C program that multiplies two numbers without using the multiplication and addition operators?

I found this on Stack Overflow. Please help this poor programmer with his problem. And please don't give answers like c = a/(1/((float)b)), which is exactly the same as c = a*b. (And is already given as an answer.)

The answer with the most upvotes on January 19th 2014 wins.

Note: This is a code-trolling question. Please do not take the question and/or answers seriously. More information is in code-trolling.

Always use recursion

Recusion is the right way!

int inc(int x) {
    return x&1?inc(x>>1)<<1:x|1;
}

int dec(int x) {
    return x&1?x^1:dec(x>>1)<<1|1;
}

int add(int x, int y) {
    return x?add(dec(x),inc(y)):y;
}

int mul(int x, int y) {
    return x?x^1?add(y,mul(dec(x),y)):y:0;
}

int main() {
    int a, b;
    scanf("%i\n%i", &a, &b);
    printf("%i", mul(a,b));
}

You can use the following recursions.  It will be much faster than the top-rated answer.

add x 0 = x
add x y = add (x^y) ((x&y)<<1)

multiply 0 _ = 0
multiply x (y<<1) = multiply (x<<1) y
multiply x y = add (multiply x (y&~1)) y


Tell me my screen resolution! Output the device's screen resolution in the specific format of [width]x[height](without the brackets). For example, an output could be 1440x900.

Here's an online tester that you can use to check your own screen resolution.

JavaScript (ES6), 32 bytes
(_=screen)=>_.width+"x"+_.height

Outputs as function return. Add f= at the beginning and invoke like f(). Uses parameter-initializing to initialize the parameter _ to screen object. The rest is self-explanatory.

f=(_=screen)=>_.width+"x"+_.height
console.log(f())

Note: Passing an argument to this function will cause it to fail.

JavaScript (Previous Solution), 35 bytes

with(screen)alert(width+"x"+height)

Never thought I will one day use with! I don't think this can be golfed further.

Bash, 21 bytes
tr , x</*/*/*/fb0/v*

If the device has frame buffer you can query /sys/class/graphics/fb0/virtual_size to get resolution.
Width and Height are delimited by , so tr translates to x.
Path to the file is shortened by using * to the point there are no ambiguities.


Prefix Tree Traversal Write a program that takes in (via stdin or command line) a string with the recursive form

PREFIX[SUFFIXES]

where

PREFIX may be any string of lowercase letters (a-z), including the empty string, and
SUFFIXES may be any sequence of strings with the recursive form PREFIX[SUFFIXES] concatenated together, including the empty sequence.

Generate a list of lowercase lettered strings from the input by recursively evaluating the list of strings in each of the suffixes and appending them to the prefix. Output to stdout the strings in this list in any order, one per line (plus an optional trailing newline).

  Example

  If the input is

cat[s[up[][]][]ch[e[r[]s[]]]a[maran[]comb[]pult[[]ing[]]]]

  then the prefix is cat and and the suffixes are s[up[][]], [],
  ch[e[r[]s[]]], and a[maran[]comb[]pult[[]ing[]]]. Each suffix has
  its own prefix and suffixes in turn.

  The output would be these 9 words in any order

catsup
cats
cat
catcher
catches
catamaran
catacomb
catapult
catapulting

  because the input encodes this tree

  and each of the 9 output words can be formed by traversing the tree
  from root to leaf.

Notes

Remember that the prefix may be the empty string, so something like

[donut[][]cruller[]]

is valid input whose output would be (in any order)

donut

cruller

where the empty line is for the empty string that the second suffix matches.
The suffix sequence can also be empty, so the trivial input case

[]

has a single empty line as its output:

You may assume that the input will only produce unique output words.

e.g. hat[s[]ter[]s[]] would be invalid input because hats is encoded twice.
Similarly, [[][]] is invalid because the empty string is encoded twice.

You may not assume that the input is as short or compressed as possible.

e.g. the 'e' node in the main example above could be combined with the 'ch' node, but that's doesn't mean the input is invalid.
Similarly, [[[[[]]]]] is valid, despite only encoding the empty string in a sub-optimal way.

Instead of a program you may write a function that takes the input string as an argument and prints the output normally or returns it as a string or list.

The shortest code in bytes wins.

Haskell, 125 bytes

t=tail.p
p=g.break(=='[')
g(a,(_:t))=(:)&(map(a++).z)$t#[]
z[]=[""];z x=x
(']':u)#a=u:a
s#a=(#)&(a++)$p s
(g&f)(x:y)=g x$f y

The function is t (for traversal):

λ: t "cat[s[up[][]][]ch[e[r[]s[]]]a[maran[]comb[]pult[[]ing[]]]]"
["catsup","cats","cat","catcher","catches","catamaran","catacomb","catapult","catapulting"]
λ: t "[donut[][]cruller[]]"
["donut","","cruller"]
λ: t "[[[[[]]]]]"
[""]

Cobra - 181

def f(s='')as String*
    for m in RegularExpressions.Regex.matches(s,r'(\w*)\[((?:(?<B>\[)|\w|(?<-B>]))*)](?(B)(?!))'),for r in.f('[(u=m.groups)[2]]'),yield'[u[1]]'+r
    if''==s,yield''


Smallest chess board compression Write an algorithm or program that can encode and decode a chess board. The goal is to make the smallest representation of a chessboard that could be used (once decoded) to determine all movement possibilities for a player on that turn.

The encoding must be able to show:

Whose turn it is.
Whether the player can castle on each side.
Whether the player can perform an en-passant, and if so, which of their pawns?
Positions of all pieces.

Important note on castling: If white moves their king one turn, and then moves it back the next, it must be clear that they cannot castle on either side after that. Same would go if they moved their left or right rook. Although the board is visually in the same state as it was two turns ago, the game state has changed. More info here: http://en.wikipedia.org/wiki/Chess#Castling

Important note on en-passant: This is also a turn-sensitive move. Read the rules for more info. http://en.wikipedia.org/wiki/Chess#En_passant

Determine input and output as needed. Major props to whoever can compress it the most!

Your score is determined worst-case scenario - maximum possible size in bits. Make sure you show how you calculated it that number and what you accounted for. Shoot for the smallest worst-case!

Min: 12 bitsMax: Avg:

Had and thought last night that I could possibly make it even smaller.

x   Colour to play next (0 -> Black, 1-> White)
1   Only King left?

00000 Position of White King (0 -> A1 ... 63 -> H8)
00000 Position of Black King

01 00000 11111  WK:A1, BK:H2 (Black to play)
11 00000 11111  WK:A1, BK:H2 (White to play)

The result is an impressive size of 12 bits!

So what about K +1 other type of piece?

x
 0
   0
     000  +Pawn
     001  +Rook
     010  +Knight
     011  +Bishop
     100  +Queen

There 2 possible arrangement of the sub tree.

   /\      /\
  +  K    K  +

Both result in the same bit sizes for all pieces. So it make no difference to which we use, I'll choose the first one.

x
 0
  0
   000
      1011001110000000000000000000000000000000000000000000000000000000000000
(+ 000) En-Passant (if >= 2 pawn & pawn in en-passant positions)
(+ 00 ) Castlings  (if >= 1 rook)
Min: 75 bit
Max: 109 bits

So on King +2 other piece types

x
 0
  1
   PRBNQ
   00011  +N +Q
   00101  +B +Q
   00110  +B +N
   01001  +R +Q
   01010  +R +N
   01100  +R +B
   10001  +P +Q
   10010  +P +N
   10100  +P +B
   11000  +P +R

There are 5 possible sub trees (I'll use 1 and 2 to indicate which of the pieces.)

   /\          /\       /\         /\          /\
  /  \        /  \     /  \       /  \        /  \
 K   /\      /\   2   /\   \     1   /\      /\   \
    1  2    K  1     K  2   1       K  2    1  2   K

So we'll require 3 bits to encode which sub tree to use.

x
 0
  1
   PRBNQ
         000  Sub Tree used

Min:= 11 = Header
       6 = 2 * 3
       4 = 1 * 4
       4 = 1 * 4
      60 = 60    Empty
      --
      85 bits

Max:=  11 = Header
        4 =  2 * 4 Kings
       48 = 16 * 3 Pawns
       12 =  4 * 3 Rook
       42 = 42 * 1 Empty
        3 =  1 * 3 En-Passant
        2 =  1 * 2 Castlings
      ---
      122 bits

Still doing the analysis for more pieces

+3 Other

x
 0
  1
   PRBNQ
         0000  Sub Tree used (of 14 possible)

+4 Other

x
 0
  1
   PRBNQ
         000000  Sub Tree used (of 42 possible)

+5 Other

x
 0
  1
   PRBNQ
         0000000  Sub Tree used (of 132 possible)
 (+000)
 (+00)

Max: 208?

Is it possible to encode all these sub-trees into 9bits?

If we total up all of the possible sub-trees we get 392 possible sub-trees.

 1  0
 2  2
 3  5
 4  14
 5  42
 6  132
    ---
    392  <= 2^9

Using Freq ID

Since there 164603 unique piece frequencies.

Log2( 164603) = 17.3286110452
             ~ 18 bits

0
 0000 0000 0000 0000 00  Freq ID

(+000)
   (+00)  Castling

Max:= 204 bits

rev 3

Min: 82 Max: 199 Avg: 160

Finally got around doing some analysis to find the maximum bit size.
With optimal huffman encoding for each of the unique piece frequencies.

               0   Player
              00  Castling
               0  En-Passant Possible
            ?000  En-Passant column (include if En-Passant Possible = 1
  0000 0000 0000  Tree Encoding ID
[Board Encoding]  Between 66 .. 180 bits

Note this is the worst possible size, which the En-Passant column bits if the number of pawns is greater than one. Irrespective of those pawns colours and position there is the potential for some boards to be 3 bits smaller.

Also there are only 144 different sizes(Worst case) for the size of the board.

 75 - 216 bits (v2)
v1  The minimum size is 98 bits (12.25 bytes), only the two kings on the board.

Maximum size is only 216 bits (27 bytes.) In the unlikly:-

  9 x Queens
  1 x King
  2 x Rooks
  2 x Knights
  2 x Bishops
on each side.

On average the size will be around 157 bits (19.625 bytes).

Pieces

To encode the board I'm using a binary tree encoding scheme.
An empty square is the most frequent from any where between 32 and 62 appearances.
Next are the pawns, then Rooks, Knights, Bishops and the least frequent are the Queen and King.

0 - left node
1 - righ node

     /\
    e  \    e:= Empty Square
      B/\W  B:= Black ; W:= White
      /  \
     /    \
    /      \
   /\      /\
  p  \    p  \  p:= Pawn
     /\      /\
    /  \    /  \
   /\  /\  /\  /\
  r  b n \ r b n \  r:= Rook; b:= Bishop; n:= Knight
         /\      /\
        q  k    q  k  q:= Queen ; k:= King

The starting board can be encode in just 166 bits (20.75 bytes)

  A     B     C      D      E     F     G     H
-----+-----+-----+------+------+-----+-----+------+
10100 10101 10110 101110 101111 10110 10101 10100 | 8
  100   100   100    100    100   100   100   100 | 7
    0     0     0      0      0     0     0     0 | 6
    0     0     0      0      0     0     0     0 | 5
    0     0     0      0      0     0     0     0 | 4
    0     0     0      0      0     0     0     0 | 3
  110   110   110    110    110   110   110   110 | 2
11100 11101 11110 111110 111111 11110 11101 11100 | 1

To indicate whom's move it takes only single bit

0-> Black , 1-> White

Castling can be encoded in 4 bits.

 B  W
LR LR
00 00

So I've use 171 bits (21.375 bytes)

En-Passe can be encoded into just 16 bits (2 bytes)

So in total thats 187 bit (23.375 bytes).

Layout

  bits    Encodes
 0 -  15  En-Passe
16 -  19  Castling
      20  Move
21 -  23  Unused
24 -> ..  Board

Not written any code yet.

Notice that 3 of the bits that are unused. So the max is 213bits.

Possible Improvements

1) Reduced the header block form 24 to 8 bits (with @Peter Taylor suggestion)

0 - 2 En-Passant
    3 Move
4 - 7 Castling
8 ... Board Pieces

2) Variable length header

A small 4 bit fixed header

0 0 0 0
| | | |
| | | +-> En-Passant Block Present?
| | |
| | +---> Pawns on board?
| |
| +-----> Castling still possible?
|
+-------> Who's move? 0-Black
                      1-White

Next block of additional bits (If castling is still possible)

00 00
|| ||
|| |+-> White Castle Right
|| +--> White Castle Left
||
|+----> Black Castle Right
+-----> Black Castle Left

Next block of additional bits (if pawns are present)

000--> En-Passant column Position

So now I have a variable length header 4 - 11 bits

3) Use a different encoding scheme depending on what pieces are left on the board.

By changing the tree encoding depending on what pieces are on the board and there frequency.

One possible encoding for an end game state (No Pawns)

        /\
       e /\
  Black /  \ White
       /    \
      /      \
     /        \
    /\        /\
   /  \      /  \
  /   /\    /   /\
 /\  / /\  /\  / /\
r b n q k  r b n q k

Which is about ~4 bits per piece.

Which type of pieces are present on the board?

RBNQK Permutation
11111 (11111)

Permutation is Variable length 0-5 bits.
If only one type of piece is left then don't include it.

Which permutation of those pieces to use for the tree?
This is the factorial of the number of pieces in the above example it is 5 pieces so 120 possible permutations that can be encoded.

 #    !  bit
 6  720  10  (If pawn included)
 5  120   6
 4   24   5
 3    6   3
 2    2   1  Don't include as of equal size.
 1    1   0  Don't include as its not needed.

Remember that there is addition bits for the empty squares and color.

Examples

Let's give an example of only QK left

RBNKQ
00011

  /\
 s  \
    /\
  B/  \W
  /\  /\
q  k q  k

101 100  0 x 60 110 111 ==> 60 + (2 x 6) = 60 + 12 = 72 bits for the board

0000 00011 Header ==> 9 bits

81 bits total

Let's give and example of only kings left

 RBNQK
 00001

  /\
 s  k
   / \
  B   W

 10 0 0 0 0 0 0 0   K... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 0   .... ....
  0 0 0 0 0 0 0 11  .... ...k

Put all together

 header  4   0 0 0 0
 pieces  5   0 0 0 0 1
 perm    0   - - - - - -
  board 66   10 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 0
              0 0 0 0 0 0 0 11

So I calculate the smallest encoding for board at 75bits (9 bits 3 bit)

Still yet to calculate how this coding scheme affects the maximum size.

Improvement 4

Reduce the number of bits for castling to just 2 bits. Just castling for the player who's turn it is.

 0 Castling possible (from header block)
 LR
 00

Thinking about it, it maybe better just to include the 2 bits inside the header block.

Min: 0 bits

Max: 1734 243 bits (4.335 4.401 bits/board amortized)

Expected: 351 177 bits (4.376 4.430 bits/board amortized)

Since I can determine the input and output however I want I decided to go with encoding the history of the game up until this point.  One advantage is that the additional information of who's turn it is, en-passant, and who has the ability to castle where can be derived and not encoded.

Attempt 1:

Naively I thought that I can encode each move in 12 bits, 4 triplets of the form (start x, start y, end x, end y) where each is 3 bits.

We would assume the starting position and move pieces from there with white going first.  The board is arranged such that

      (
      0
      ,
      0
      )

 is white's lower left corner.

For example the game:

  e4    e5
 Nf3    f6
Nxe5  fxe5
...    ...

Would be encoded as:

100001 100010 100110 100100
110000 101010 101110 101101
101010 100100 101101 100100
...

This leads to an encoding of 12 m bits where m is the number of moves made

On one hand this could get really big, on the other hand you can consider each move to be it's own game so each encoding really encodes m "chess boards".  If you amortized this you get that each "chess board" is 12 bits. But I feel this is a bit cheating...

Attempt 2:

I realized that each move in the previous attempt encodes many illegal moves.  So I decided to only encode legal moves.  We enumerate possible moves as follows, number each square such that
  (
  0
  ,
  0
  )
  →
  0
,
  (
  1
  ,
  0
  )
  →
  1
,
  (
  x
  ,
  y
  )
  →
  x
  +
  8
  y
.  Iterate through the tiles and check if a piece is there and if it can move.  If so add the positions it can go to to a list.  Choose the list index that is the move you want to make.  Add that number to the running total of moves weighted by 1 plus the number of possible moves.

Example as above:
From the starting position the first piece that can move is the knight on square 1, it can move to square 16 or 18, so add those to the list [(1,16),(1,18)].  Next is the knight on square 6, add it's moves.  Overall we get:

[(1,16),(1,18),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(11,19),(11,27),(12,20),(12,28),(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]

Since we want the move
  (
  12
  ,
  28
  )
, we encode this as 13 in base 20 since there are 20 possible moves.

So now we get the game number

    g0

  =
  13

Next we do the same for black except we number the tiles in reverse (to make it easier, not required) to get the list of moves:

[(1,16),(1,18),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(11,19),(11,27),(12,20),(12,28),(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]

Since we want the move
  (
  11
  ,
  27
  )
, we encode this as 11 in base 20 since there are 20 possible moves.

So now we get the game number
  g1
  =
  (
  11
  ⋅
  20
  )
  +
  13
  =
  233

Next we get the following list of moves for white:

[(1,16),(1,18),(3,12),(3,21),(3,30),(3,39),(4,12),(5,12),(5,19),(5,26),(5,33),(5,40),(6,12),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(11,19),(11,27)(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]

Since we want the move
  (
  6
  ,
  21
  )
, we encode this as 13 in base 29 since there are 29 possible moves.

So now we get the game number
  g2
  =
  (
  (
  13
  ⋅
  20
  )
  +
  11
  )
  20
  +
  13
  =
  5433

Next we get the following list of moves for black:
[(1,11),(1,16),(1,18),(2,11),(2,20),(2,29),(2,38),(2,47),(3,11),(4,11),(4,18),(4,25),(4,32),(6,21),(6,23),(8,16),(8,24),(9,17),(9,25),(10,18),(10,26),(12,20),(12,28),(13,21),(13,29),(14,22),(14,30),(15,23),(15,31)]

Since we want the move $(10, 18)$
  (
  10
  ,
  18
  )

So now we get the game number
  g3
  =
  (
  (
  (
  19
  ⋅
  29
  +
  13
  )
  20
  )
  +
  11
  )
  20
  +
  13
  =
  225833

And continue this process for all the remaining moves.  You can think of g as the function
  g
  (
  x
  ,
  y
  ,
  z
  )
  =
  x
  y
  +
  z
.  Thus
  g0
  =
  g
  (
  1
  ,
  1
  ,
  13
  )
,
  g1
  =
  g
  (
  g
  (
  1
  ,
  1
  ,
  11
  )
  ,
  20
  ,
  13
  )
,
  g2
  =
  g
  (
  g
  (
  g
  (
  1
  ,
  1
  ,
  13
  )
  ,
  20
  ,
  11
  )
  ,
  20
  ,
  13
  )
,
  g3
  =
  g
  (
  g
  (
  g
  (
  g
  (
  1
  ,
  1
  ,
  19
  )
  ,
  29
  ,
  13
  )
  ,
  20
  ,
  11
  )
  ,
  20
  ,
  13
  )

To decode a game number g0, we start at the initial position and enumerate all possible moves.  Then we compute g1 = g0 // l, m0 = g0 % l, where l is the number of possible moves, '//' is the integer division operator and '%' is the modulus operator.  It should hold that g0 = g1 + m0.  Next we make the move m0 and repeat.

From the example above if g0 = 225833 then g1 = 225833 // 20 = 11291 and m0 = 225833 % 20= 13.  Next g2 = 11291 // 20 = 564 and m1 = 11291 % 20 = 11.  Then g3 = 11291 // 20 = 564 and m2 = 11291 % 20 = 11. Therefore g4 = 564 // 29 = 19 and_m_3 = 564 % 29 = 13. Finally g5= 19 // 29 = 0 and m4 = 19 % 29 = 19.

So how many bits are used to encode a game this way?

For simplicity, let's say there are always 20 moves each turn and for the worst case scenario we always pick the biggest one, 19.  The number we will get is
  19
  ⋅
  20m

+
  19
  ⋅
  20m-1
  +
  19
  ⋅
  20m-2
  +
  ⋯
  +
  19
  ⋅
  20
  +
  19
  =
  20m+1
  −
  1
 where _m is the number of moves.  To encode
  20m+1
  −
  1
 we need about
  log2
  (
  20m+1
  )
 bits which is about
  (
  m
  +
  1
  )
  ∗
  log2
  (
  20
  )
  =
  4.3219
  ∗
  (
  m
  +
  1
  )

On average m = 80 (40 moves per player) so this would take 351 bits to encode.  If we were recording many games we would need a universal encoding since we don't know how many bits each number will need

Worst case when m = 400 (200 moves per player) so this would take 1734 bits to encode.

Note that the position we want to encode must be given to us via the shortest path to get there by following the rules.  For example the game theorized here doesn't need m = 11741 to encode the final position.  Instead we run a Breadth-First search to find the shortest path to that position and encode that instead.  I don't know how deep we would need to go to enumerate all chess positions, but I suspect that 400 is an overestimate.

Quick calculation:

There are 12 unique pieces or the square can be empty so to position them on a chessboard is 1364.  This is a vast overestimate since it includes many invalid positions.  When we are m moves into the game we have created about 20m positions.  So we are looking for when 20m =
1364.  Log both sides to get m = 64 * log20(13) = 54.797.  This shows that we should be able to get to any position in 55 moves.

Now that I calculated the worst case to be m = 55 not m = 400 I will edit my results.  To encode a position where m = 55 takes 243 bits.  I'm going to also say that the average case is around m = 40 which takes 177 bits to encode.

If we use the amortization argument from earlier we are encoding 400 "chess boards" in 1734 bits so we get that each "chess board" takes up 4.335 bits in the worst case.

Note that g = 0 denotes a valid game, the one where the piece on the lowest square moves to the lowest square it can.

Additional Notes:

If you want to refer to a specific position in the game you may need to encode the index.  This can be added either manually e.g concatenate the index to the game, or add an additional "end" move as the last possible move each turn.  This can now account for players conceding, or 2 in a row to denote the players agreed to a draw.  This is only necessary if the game did not end in a checkmate or stalemate based on the position, in this case it is implied.  In this case it brings the number of bits needed on average to 356 and in the worst case 1762.


Execute prints backwards Your task is to reverse the order in which some prints get executed.

Specs:
Your code will be in this form:

//some lines of code
/*code*/ print "Line1" /*code*/
/*code*/ print "Line2" /*code*/
/*code*/ print "Line3" /*code*/
/*code*/ print "Line4" /*code*/
//some lines of code

You will have to print (or echo, or write, or equivalent) those strings from the fourth to the first.

You decide which lines of your program must print the strings, but they must be adjacent;
Every line can contain only one print, and cannot exceed 60 bytes in length;
Since this is popularity-contest, be creative and avoid to write just a goto or a simple for(i){if(i=4)print"Line1";if(i=3)...}
The most upvoted answer in 2 weeks wins this.
Your output MUST be Line4 Line3 Line2 Line1 OR Line4Line3Line2Line1 OR Line4\nLine3\nLine2\nLine1(where \n is a newline), and it must be generated only by executing those prints backwards.

Happy coding!

UPDATE: Contest is over! Thank you all :)

Commodore 64 BASIC

40 print "Line 1"
30 print "Line 2"
20 print "Line 3"
10 print "Line 4"

Ruby

This syntax is somewhat confusing.

eval <<print.split($/)*'unless '
print "Line1"
print "Line2"
print "Line3"
print "Line4"
print


The greedy regex (cops) This is the cops' post. The robbers' is here.

You make a program and a regex.

For most inputs, one of the following happens:

the regex doesn't match, and the program returns a falsey value
the regex doesn't match, and the program returns a truthy value
the regex matches, and the program returns a truthy value

But for one (or more) input, the regex matches, but the program returns a falsy value.

You should try to keep this input hidden. Robbers will try to find an input where the regex matches, but the program returns a falsy value.

Post your program and your regex, as well as your language name, byte count of the program, regex flavor, and byte count of the regex.

If a robber finds an input where the regex matches, but the program returns a falsy value, even if it wasn't the intended input your program is considered cracked, and you edit in a link to the robber's crack.

If nobody has cracked your program & regex after a week, then edit in that your submission is safe and is therefore not eligible for cracking. Also edit in the intended input. The shortest (program bytes + regex bytes) non-cracked submission wins.

Example

Let's say your regex is (all of the flavors):

/^[0-9]$/

And your program is (JS):

x=>Boolean(parseInt(x))

Then a valid crack would be 0, because the regex matches 0 but 0 is falsey.

Delimiters don't count in the byte count.

I can't enforce the banning of hash functions with rules, but please don't use SHA/RSA or anything that is unfair to the robbers

Python, cracked
Regex: (?!.)
Program: from operator import not_
This is a little easier than my previous one.

Pyth
Regex: .*
Program: !qC%.hz^TT"U|(¡
Try it online!
Simple hash function, shouldn't be allowed, but it is. I could've made it much stronger, but I tried to optimize for byte count.


List of possible birth years of living humans The Challenge

Output a list of years that starts with the current year and ends 120 years ago. The birth year of every living human would be included in this list.

Details

The list should be in descending order.

Every built-in function to manipulate arrays and/or lists is allowed.

Shortest code in bytes wins.

When run this year the output would be

2016, 2015, ..., 1897, 1896

When run next year the output would be

2017, 2016, ..., 1898, 1897

Etc.

Update

Some have asked about the format of the list. As most have guessed, it doesn't matter. Insert any separator between the numbers. Intuitively most inserted a comma or space or both, newline or output an array.
Quasi superhumans like Jeanne Calment are an exception to the rule stated in my question.

Pyke, 6 bytes
wC7m-

Try it here!
w     - 121
   m- - for i in range(^):
 C7   -  current_year-i

(After w, the codepoint for 153 is present but it isn't printable)

Ruby, 39 36 bytes

t=Time.new.year;t.downto(t-120).to_a

Old:

t=Time.new.year;(t-120..t).to_a.reverse

Should be obvious.


Restricted Integer Partitions Pk(n) means the amount of partitions of n into exactly k parts. Given n and k, calculate Pk(n).

  Tip: Pk(n) = Pk(n−k) + Pk−1(n−1), with initial values p0(0) = 1 and pk(n) = 0 if n ≤ 0 or k ≤ 0. [Wiki]

Examples

n    k    Ans
1    1    1
2    2    1
4    2    2
6    2    3
10   3    8

Rules

General code-golf rules apply.

Swift, 76 73 bytes

func P(_ n:Int,_ k:Int)->Int{return n*k>0 ?P(n-k,k)+P(n-1,k-1):n==k ?1:0}

Try it online!

Explanation
How does the code structurally work?
First of all, we define our function P, with two integer parameters n and k, and give it a return type of Int, with this piece of code: func P(_ n:Int,_ k:Int)->Int{...}. The cool trick here is that we tell the compiler to ignore the names of the parameters, with _ followed by a space, which saves us two bytes when we call the function. return is obviously used to return the result of our nested ternary described below.
Another trick I used was n*k>0, which saves us a couple of bytes over n>0&&k>0. If the condition is true (both the integers are still higher than 0), then we recursively call our function with n decremented by k as our new n and k stays the same, and we add the result of P() with n and k decremented by 1. If the condition is not true, we return either 1 or 0 depending on whether n is equal to k.
How does the recursive algorithm work?
We know that the first element of the sequence is p0(0), and so we check that both integers are positive (n*k>0). If they are not higher than 0, we check if they are equal (n==l ?1:0), here being two cases:

There is exactly 1 possible partition, and thus we return 1, if the integers are equal.

There are no partitions if one of them is already 0 and the other is not.

However, if both are positive, we recursively call P twice, adding the results of P(n-k,k) and P(n-1,k-1). And we loop again until n has reached 0.

* Note: The spaces cannot be removed.

Scala, 73 bytes

Well this is some easy unreworked use of OP's tip.

k and n are the parameters of my recursive function f. See TIO link for context.

Since this is recursive, should I include function def in byte count?

(k,n)match{case(0,0)=>1
case _ if k<1|n<1=>0
case _=>f(n-k,k)+f(n-1,k-1)}

Try it online!


Code Golf Christmas Edition: How to print out a Christmas tree of height N Given a number N, how can I print out a Christmas tree of height N using the least number of code characters?  N is assumed constrained to a minimum value of 3, and a maximum value of 30 (bounds and error checking are not necessary). N is given as the one and only command line argument to your program or script.

All languages appreciated, if you see a language already implemented and you can make it shorter, edit if possible - comment otherwise and hope someone cleans up the mess.  Include newlines and White Spaces for clarity, but don't include them in the character count.

A Christmas tree is generated as such, with its "trunk" consisting of only a centered "*"

N = 3:

   *
  ***
 *****
   *

N = 4:

    *
   ***
  *****
 *******
    *

N = 5:

     *
    ***
   *****
  *******
 *********
     *

N defines the height of the branches not including the one line trunk.

Merry Christmas PPCG!

Brainfuck, 240 characters

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

Not yet done.  It works, but only with single-digit numbers.

EDIT: Done!  Works for interpreters using 0 as EOF.  See NOTEs in commented source for those with -1.

EDIT again: I should note that because Brainfuck lacks a standard method for reading command line arguments, I used stdin (standard input) instead.  ASCII, of course.

EDIT a third time: Oh dear, it seems I stripped . (output) characters when condensing the code.  Fixed...

Here's the basic memory management of the main loop.  I'm sure it can be heavily optimized to reduce the character count by 30 or so.

Temporary
Copy of counter
Counter (counts to 0)
Space character (decimal 32)
Asterisk character (decimal 42)
Number of asterisks on current line (1 + 2*counter)
Temporary
New line character
Temporary?
Total number of lines (i.e. input value; stored until the very end, when printing the trunk)

Condensed version:

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

And the pretty version:

ASCII to number
,>
++++++++[-<------>]  = 48 ('0')

Second digit (may be NULL)
,
NOTE:   Add plus sign here if your interpreter uses negative one for EOF
[ NOTE: Then add minus sign here
 >++++++++[-<------>]
 <<[->++++++++++<]>>  Add first digit by tens
]

Duplicate number
<[->+>+>>>>>>>+<<<<<<<<<]>>

Space char
>>++++++++[-<++++>]

Asterisk char
>++++++[-<+++++++>]

Star count
+

New line char
>>>++[-<+++++>]<<<

<<<

Main loop
[
Print leading spaces
-[>.<-]

Undo delete
<[-<+>>+<]
<[->+<]
>>

Print stars
>>>[-<.>>+<]

Add stars and print new line
>[-<+>]
>.<
<++

<<<

-<->
End main loop
]

Print the trunk
>>>>>>>
-[-<<<<<<.>>>>>>]
<<<<<.

Merry Christmas =)

First try in LUA

f=string.rep p=print function t(N) for i=0,N do s=f(" ",N-i) p(s..f("+",2*i-1)..s) end p(f(" ",N-1).."+"..f(" ",N-1)) end t(arg[1])

After selecting all of it scite tells me these are 131 chars

For clarities sake without optimizing away the \n etc:

f=string.rep
p=print
function t(N)
 for i=0,N do
   s=f(" ",N-i)
   p(s..f("+",2*i-1)..s)
 end
  p(f(" ",N-1).."+"..f(" ",N-1))
end
t(arg[1])

For the python version by ΤΖΩΤΖΙΟΥ I get shown 115 chars... Hrm, some more things to optimize


Stripping off extra spaces from a string You are given a string. Output the string with one space per words.

Challenge

Input will be a string (not null or empty), surrounded with quotes(") sent via the stdin. Remove leading and trailing spaces from it. Also, if there are more than one space between two words (or symbols or whatever), trim it to just one space. Output the modified string with the quotes.

Rules

The string will not be longer than 100 characters and will only contain ASCII characters in range (space) to ~(tilde) (character codes 0x20 to 0x7E, inclusive) except ",i.e, the string will not contain quotes(") and other characters outside the range specified above. See ASCII table for reference.
You must take input from the stdin( or closest alternative ).
The output must contain quotes(").
You can write a full program, or a function which takes input (from stdin), and outputs the final string

Test Cases

"this  is  a    string   "         --> "this is a string"

"  blah blah    blah "             --> "blah blah blah"

"abcdefg"                          --> "abcdefg"

"           "                      --> ""

"12 34  ~5 6   (7, 8) - 9 -  "     --> "12 34 ~5 6 (7, 8) - 9 -"

Scoring

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

CJam, 7 bytes
q~S%S*p

Code Explanation
CJam has reserved all capital letters as inbuilt variables. So S has a value of a space here.
q~          e# Read the input (using q) and evaluate (~) to get the string
  S%        e# Split on running lengths (%) of space
    S*      e# Join (*) the splitted parts by single space
      p     e# Print the stringified form (p) of the string.

This removes the trailing and leading spaces as well
Try it online here

Python2, 28 Bytes

lambda s:" ".join(s.split())

Explanation

lambda s

Anonymous function which takes as input s.

s.split()

Returns a list of the words (which are separated by arbitrary strings of whitespace characters) of the string s.

" ".join(...)

Joins list back into a string, with each word separated by a space (" ").


VEVO User Account Checker We often see music videos on Youtube. Many Youtube channels that host music videos are "powered by VEVO". Those can be easily identified by both embedding VEVO at their video thumbnails and appending VEVO to their channel name.

Now write some code to test whether a string given by user is a VEVO user account or not.

Requirements for valid VEVO user account strings:

Must only contain uppercase, lowercase, and digit characters. (no whitespace or punctuation)
Must not exceed 80 characters length.
Must have "VEVO" substring at the end of string

Test cases:

Valid inputs:

AdeleVEVO
ConnieTalbotVEVO
SHMVEVO
justimberlakeVEVO
DJMartinJensenVEVO
test123VEVO

Invalid inputs:

syam kapuk
jypentertainment
Noche de Brujas
testVEVO123

Of course, because this is code-golf, I'm looking for the shortest code using any programming language.

Python 2, 45 bytes

-3 bytes thanks to Rod. -2 bytes thanks to ovs.

lambda s:len(s)<81*s.isalnum()<'VEVO'==s[-4:]

Try it online!

A regex solution turns out to be longer.

lambda s:re.match('^[^\W_]{0,76}VEVO$',s)
import re

Clojure, 146 bytes

(fn[u](let[c count](and(<(c u)81)(=(c(filter #(let[i(int %)](or(< 47 i 58)(< 64 i 91)(< 96 i 123)))u))(c u))(clojure.string/ends-with? u"VEVO"))))

Try it online!
This would be much shorter using a regex, but I figured doing it manually would be more interesting.
(defn vevo? [username]
  (and (< (count username) 81)

       ; Filter out the illegal characters, then check if the length is the same as the original string
       (= (count (filter #(let [i (int %)]
                            ; Make sure the char code is in the valid ranges
                            (or (< 47 i 58) (< 64 i 91) (< 96 i 123)))
                         username))
          (count username))

       (clojure.string/ends-with? username "VEVO")))


Playing the Name Game Write a program to play the name game.

Input

Your program should accept a single name as input from the user in some way (e.g read from standard input or as a command-line argument). You can assume that the name is a single word consisting of an upper case letter followed by one or more lower case letters.

Output

Your program must print the rhyme for the given name, as explained in the song, by filling out the following template:

(X), (X), bo-b(Y)
Banana-fana fo-f(Y)
Fee-fi-mo-m(Y)
(X)!

Here, (X) is the original name, and (Y) is the name in lower case with any initial consonants removed.

There is one exception, however. If the original name began with m, f or b, it should be written without this letter on the corresponding line. E.g. if the name was Bob, the "b" line should end with bo-ob. Note that in this case, any other consonants are kept, so for Fred it's fo-red, not fo-ed.

Examples

Shirley:

Shirley, Shirley, bo-birley
Banana-fana fo-firley
Fee-fi-mo-mirley
Shirley!

Arnold:

Arnold, Arnold, bo-barnold
Banana-fana fo-farnold
Fee-fi-mo-marnold
Arnold!

Bob:

Bob, Bob, bo-ob
Banana-fana fo-fob
Fee-fi-mo-mob
Bob!

Fred:

Fred, Fred, bo-bed
Banana-fana fo-red
Fee-fi-mo-med
Fred!

Scoring

Shortest code wins.

vi, 118 115

Y2PA,<ESC>Ypj~Y2PIbo-b<c-o>wBanana-fana fo-f<c-o>wFee-fi-mo-m<c-o>2$!<ESC>HJJ:%s/\vo-(([bfm])\2([^aeiou]*))?([bfm]?)[^aeiou]*/o-\3\4
ZZ

The code includes 5 control characters, which I've put in brackets. Each only counts as a single character towards the character count.

EDIT: Moving the first join (J) to later and changing the paste-before (P) to a paste-after (p) saved me 1 character. Also, not capturing the o- in the regex saved me 2 more characters.

Python

n=raw_input('')
if n[0].lower() in ("m", "f", "b"): r=n[1:]
else:
    i = iter(n.lower())
    for a in range(len(n)):
        if i.next() in ("a","e","i","o","u"):
            r = n[a:]
            break
print "%s, %s, bo-b%s\nBanana-fana fo-f%s\nFee-fi-mo-m%s\n%s!" %(name,name,rhyme,rhyme,rhyme,name)


Will it halt? (Cops) This is the cops' thread. The robbers' thread is here.

Your challenge is to make a program that runs forever without halting1, unless it gets a particular input or inputs2. If it receives that input, it must terminate in a finite amount of time3. This is code-golf, so the shortest answer that has not been cracked by a robber within one week of posting wins. After the week has passed, please mark your answer as safe and show the halting input (in a > ! spoiler quote). If a robber cracks your submission, please mark it as cracked and show the halting input (in a > ! spoiler quote).

Submissions are preferred be runnable & crackable on TIO. Submissions not runnable or crackable on TIO are allowed, but please include instructions to download / run them.

Please make your input deterministic, and uniform across all runs. See this meta post for details.

Please, don't "implement RSA" or anything mean to the robbers. Use obscure languages and features, not boring encryption and hashing. I can't enforce this with rules, but you can expect torrential downvotes if all you do is sha(input) === "abcd1234".

1Assuming that the computer doesn't get shut down, break, get engulfed by the sun, overheat in the universe's heat death, or hit the TIO timeout of 60s.

2The program must halt on at least one input. As long as it loops forever on one input and halts on another, it works.

3This must be < 60 seconds, so that the code can be tested on TIO.

Looking for uncracked submissions?

fetch("https://api.stackexchange.com/2.2/questions/135363/answers?order=desc&sort=activity&site=codegolf&filter=!.Fjs-H6J36vlFcdkRGfButLhYEngU&key=kAc8QIHB*IqJDUFcjEF1KA((&pagesize=100").then(x=>x.json()).then(data=>{var res = data.items.filter(i=>!i.body_markdown.toLowerCase().includes("cracked")).map(x=>{const matched = /^ ?##? ?(?:(?:(?:\[|)([^\]]+)(?:\]|<\/a>)(?:[\(\[][a-z0-9/:\.]+[\]\)])?)|([^, ]+)).*[^\d](\d+) ?\[?(?:(?:byte|block|codel)s?)(?:\](?:\(.+\))?)? ?(?:\(?(?!no[nt][ -]competing)\)?)?/gim.exec(x.body_markdown);if(!matched){return;}return {link: x.link, lang: matched[1] || matched[2], owner: x.owner}}).filter(Boolean).forEach(ans=>{var tr = document.createElement("tr");var add = (lang, link)=>{var td = document.createElement("td");var a = document.createElement("a");a.innerHTML = lang;a.href = link;td.appendChild(a);tr.appendChild(td);};add(ans.lang, ans.link);add(ans.owner.display_name, ans.owner.link);document.querySelector("tbody").appendChild(tr);});});

Uncracked Submissions

Language	Author

Malbolge, 128 bytes, cracked by KBRON111

(=&r:#o=~l4jz7g5vttbrpp^nllZjhhVfddRb`O;:('JYX#VV~jS{Ql>jMKK9IGcFaD_X]\[ZYXWVsN6L4J\[kYEhVBeScba%_M]]~IYG3Eyx5432+rpp-n+l)j'h%B0

Have fun!

(Yes, I learned Malbolge just for this. Yes, it took an absurdly long time to finally get working. And yes, it was totally worth it.)

Wrapped, so you can see it in its full, er, "glory":

(=&r:#o=~l4jz7g5vttbrpp^nllZjhhV
fddRb`O;:('JYX#VV~jS{Ql>jMKK9IGc
FaD_X]\[ZYXWVsN6L4J\[kYEhVBeScba
%_M]]~IYG3Eyx5432+rpp-n+l)j'h%B0

I used this interpreter to test it; I'm not sure if it matters, but I figured I'd specify just in case.

CPython 3.6, 635 634 bytes Cracked

j=input()
__builtins__.__dict__["__import__"]=eval(j)
import random,functools,itertools,zlib
exec("@functools.lru_cache(None)\ndef f():i=input();return(all(x is y for x,y in itertools.zip_longest((x for x in sorted(dir(eval(i[::2])))if'_'not in x),sorted{}))\nand all(x is y for x,y in itertools.zip_longest((x for x in sorted(dir(eval(i[1::2])))if'_'not in x),sorted{}))and 8 and zlib.crc32(bytes(i,'ASCII'))==zlib.crc32(bytes(j,'ASCII')))".format(*eval('('+"(tuple(''.join(random.choice('abcdefghijklmnopqrstuvwxyz')for x in range%s)for x in range%s),),"%(("(random.randint(1,9))",)*2)*2+')')))
try:f()
except:f=bool
while not f():8

Try it online!

It probably works in some other versions too, but I haven't tested it in them. Golfing advice welcome.

Note that triggering an EOFError is cheaty - this program expects streams to remain open!

I also have an ungolfed version, complete with terrible, terrible ASCII art, prettified output and probable cryptographic security.

import_input = input()
__builtins__.__dict__["__import__"] = eval(import_input)

import secrets
import functools
import itertools
import zlib
import base64

code = b"""
             GA2
   A      LGA  2     AL1ad        >eG
  @ >T   )Ec#  6     *  C       WM 2 +0    4.            ^1
 +   5  i      T    m   \'     J   ]   7  g                q
 e  `   -+     D V_4W  a ,    :C<  G  E*t
3   GW0P0V/bkg iU>       o    %hb  &  CM_
n      Y 1!SHJIUjh^     iZ    Ol5  %  =n4   Q`b   21   Z>A
R    l& j       iSDh  c>j  ;#  @h  E  ?l    B  W h  # u
di-90o @\\O"t6XNM8boo1T   /JHW     c        Y,@  H    N Ok
                        ?pDT:)     (        (    `    %  F
3<uEZ_BZ"\\hNA)a.1W_9\\)/e%/ROb    2        V     ?5   3q
c5g^O89kP>iuQ3`*GZHb>#u0%gcC_6(    i
L                           Es/    V
6                           >qD    m       H              6
,                           D;$    J        K            ,
                             :K    O              U   ?
                                 I0L(#               d
                                 =   C              9
                                                   `
f$g3<"""

alphabet = "abcdefghijklmnopqrstuvwxyz"
make_keyword = lambda l:"".join(secrets.choice(alphabet) for x in range(l))
exec(zlib.decompress(base64.a85decode(code)[::-1]).decode("ASCII").format(
    *eval('('+"(tuple(make_keyword(secrets.randbelow(20)+1)"
                "for x in range(secrets.randbelow(20)+1)),),"*2+')')))

try:
    f()
except:
    f = bool

while not f():
    print(secrets.randbelow(2), end="")

for byte in itertools.zip_longest(
    *(iter(bin(int.from_bytes(code, "big"))[2:]),) * 8, # bits in a byte
    fillvalue = 0):
    print("".join(byte), end="")

Try it online!


DISARM THE B.O.M.B.! You have been hired for your tech knowledge as a Secret Agent's sidekick to ensure that the good guy can get his job done and the world can be saved.

This is your last mission before retiring with a high paycheck and the gratitude of the whole world. But before you have to disarm the Evil Genius' Big Overly Massive BOMB (seems that the evil genius is a smart ass who likes recursive acronyms). Anyways you and your buddy are in the very core of the Evil Genius secret base, ready to disarm the BOMB that could wipe the continent out. In your previous mission you managed to get the disarm code that to your astonishment is just "PASSWORD_01". You connect your keyboard to the BOMB but when you are ready to go, the Evil Genius' henchmen enter in with a barrage of bullets. Unfortunately one of these bullets impacts on your keyboard. "Finish the job while I distract those d*ckheads!" says your buddy and then begins to fire his gun. But how could you finish the job with only half a keyboard?

SPECS

Write a program that outputs in any way you want the string PASSWORD_01 (uppercase).
Since your keyboard has been hit by a bullet, you can only use these keys:

1 2 3 4 5

Q W E R T

A S D F G

< > Z X C

Ctrl Shift Tab Space

Using the Shift key, your keyboard allows you to use these characters:

! " · $ %
You don't have any other hardware than the keyboard and the screen (a mouse for example), nor a file with the password written in your computer.
You don't have an Internet connection.
You can assume you have the interpreter shell / source editor opened before the bullets came in. Sadly you have not written anything in it before the keyboard was hit.
You don't have a virtual keyboard. In fact the BOMB has a TOO_FUNNY detector that will make it explode if you try to use the Standard loopholes.
Since your buddy is waiting for you to finish soon to escape off the Secret Base, you will have to write the smallest code possible (so it's restricted-source and code-golf!).

Good luck because the count down has begun!

HELP MODE: Also a KEY (only one Key you want from the keyboard, but not the Shift + Key or any other combination) has miraculously survived too. E.g.: You can use =, or 0 or /… This extra key cannot be any of the letters in PASSWORD_01 (so you cannot add P or O). Name that key in your answer. You have a penalization of 10 characters for use of this key regardless of how many times you use the key.

bash, vim and dc (343)
I'm sitting at a bash prompt which has been configured by the Evil Genius, and of course he has VISUAL=vim in the default environment. Using the default bash binding for edit-and-execute-command (C-x C-e) bash invokes $VISUAL and will execute its buffer contents on exit (ZZ). I type in the following sequence (Note: kbd-mode are commands issued in normal mode and control sequences):

C-xC-e

acat<<<45C-c4C-aaa
Now the vim buffer contains cat<<<49a. Continuing ...

45C-c3C-aaa

54C-c41C-aaa

55C-c13C-aaa
Now the vim buffer contains cat<<<49a48a95a68a. Continuing ...

51C-c31C-aaa

55C-c24C-aaa

44C-c43C-aaa

42C-c41C-aaa

42C-c41C-aaa

54C-c11C-aaa

55C-c25C-aaa>s
Now the vim buffer contains cat<<<49a48a95a68a82a79a87a83a83a65a80a>s
Get out of insert mode, save and exit

C-cZZ
The s file now contains a dc script that generates the desired string on the stack, now we need to add print commands.

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ
Repeat the above command 9 times.

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eadc<<<55C-c25C-aaa>>sC-cZZ

C-xC-eacat<<< f >>s
Execute the dc script:

C-xC-eadc sC-cZZ

Output:
PASSWORD_01

Contents of the s file:
49a48a95a68a82a79a87a83a83a65a80a
P
P
P
P
P
P
P
P
P
P
f

Deadfish~, 154 + 10 bytes
iiissdcdddddddddddddddciiiiiiiiiiiiiiiiiicciiiicddddddddciiicddddddddddddddciiiiiiiiiiiiiiiiiiiiiiiiiiicdddddddddddddddddddddddddddddddddddddddddddddddcic

Try it online!
No {} :(
Needs i, you can't do anything without it...


Random Password Generator The domain server requires that all employees have a strong, random password conforming to the following rules:

Exactly 15 characters long.
Keyboard-typeable characters only (as shown in code-type below).  Teaching the sales to use ALT+NUMPAD codes is not permitted.
At least 1 lower case letter: abcdefghijklmnopqrstuvwxyz
At least 1 upper case letter: ABCDEFGHIJKLMNOPQRSTUVWXYZ
At least 1 numeric digit: 0123456789
At least 1 symbol: `~!@#$%^&*()_+-={}|[]\:";'<>?,./

For this purpose IT have commissioned and will be distributing a Random Password Generator to all employees.  All employees will be required to use the Random Password Generator.  The requirements for the Random Password Generator are, in addition to the password restrictions above:

It must be able to generate all permutations of all allowable characters.
It must display the generated password on the screen.
The code is required to be as small as possible (in bytes).

Please submit your proposed solution within the next week.

Mathematica (18)
Let me a little cheat
= 15char ASCII pwd

&(^F7yP8k:*1P<t

P.S. not safety :)

Perl (73 characters)

sub x{@x=map{chr rand6+6*$_+27%122}1..15;print splice@x,rand@x,1 while@x}

Maybe someone can minify it more..


Print a string in as few distinct characters as possible The task is simple: print The quick brown fox jumps over the lazy dog using as few distinct characters in your source code as possible.
print "The quick brown fox jumps over the lazy dog" has a score of 29 characters, as all 26 lowercase letters appear at least once, as well as an uppercase T, spaces, and quote characters. I'm sure you can get more creative than that, though!
In the event of a tie, the shorter answer will be accepted.


A Mnemonic for Remembering 23940 The major system is a mnemonic device for converting numbers into words so they can be memorized more easily.
It is based on how words sound phonetically, but to keep things simple for the challenge we'll only be concerned with how words are spelled. This means there will be some incorrect conversions, but that's alright.

To convert a number into a word using our simplified major system:

Replace each 0 with s or z. (Some could be s and some could be z. Same goes below.)
Replace each 1 with t or d or th.
Replace each 2 with n.
Replace each 3 with m.
Replace each 4 with r.
Replace each 5 with l.
Replace each 6 with j or sh or ch.
Replace each 7 with k or c or g or q.
Replace each 8 with f or v.
Replace each 9 with p or b.
Add the letters aehiouwxy anywhere in any amounts to make a real English word, if possible.
The only exception is that h may not be inserted after an s or c.

The number may actually be any string of the digits 0-9 (no decimals or commas or signs).
The word can only contain the lowercase letters a-z.

Examples
The number 32 must be converted as ?m?n?, where ? represents any finite string made from the letters aehiouwxy (a string from the free monoid if you prefer). There are many ways this could be made into a real English word: mane, moon, yeoman, etc.
The number 05 could be converted as ?s?l? or ?z?l?. Some possibilities are easily, hassle, and hazel. The word shawl is not allowed because h may not be placed after s; it would be incorrectly read as 65.
Challenge
Write a program or function that takes in a string of the digits 0-9 and finds all the words that it could be converted into using the simplified major system mnemonic.
Your program has access to a word list text file that defines what all the "real" English words are. There is one lowercase a-z word on each line of this file, and you may optionally assume it has a trailing newline. Here is a list of real words you can use for testing. You can assume this word list file is called f (or something longer) and lies in any convenient directory.
For a 35 byte penalty (add 35 to your score) you may assume the word list is already loaded into a variable as a list of strings. This is mainly for languages that can't read files, but any submission may take advantage of it.
Your program must output all the words in the word list that the input number can be converted to. They should be printed to stdout (or similar), one per line (with an optional trailing newline), or they can be returned as a list of strings if you chose to write a function. The word list is not necessarily alphabetized and the output doesn't need to be either.
If there are no possible words then the output (or the list) will be empty. The output is also empty if the empty string is input.
Take input via stdin, command line, or as a string argument to a function. The word list, or its file name, should not be part of the input, only the digit string.
You are only matching single words in the word list, not sequences of words. The word noon would probably be one of the results for 22, but the word sequence no one wouldn't.
Test Cases
Suppose this is the word list:
stnmrljkfp
zthnmrlshqfb
asatanamaralajakafapa
aizxydwwwnhimouooraleshhhcavabe
zdnmrlshcvb
zdnmrlshchvb
sthnmrlchgvb
shthnmrlchgvb
bob
pop
bop
bopy
boppy

The input 0123456789 should give all the long words except zdnmrlshchvb and shthnmrlchgvb:
stnmrljkfp
zthnmrlshqfb
asatanamaralajakafapa
aizxydwwwnhimouooraleshhhcavabe
zdnmrlshcvb
sthnmrlchgvb

The input 99 should give:
bob
pop
bop
bopy

(The output words may be in any order.)
Scoring
The shortest submission in bytes wins. Tiebreaker goes to the submission posted first.
Nifty related site: numzi.com.

Perl, 87 84

open A,f;"@ARGV"eq s/[cs]h/j/gr=~y/stnmrljkfpzdcgqvb\0-z/0-90177789/dr&&print for<A>

Takes input in as the command line parameter:

$perl m.pl 23940

Can be made somewhat shorter if the word list would be allowed on the standard input:

$perl -lnE'INIT{$;=pop}$;eq s/[cs]h/j/gr=~y/stnmrljkfpzdcgqvba-z/0-90177789/dr&&say' 99 <f

tr, sed, grep, xargs, sh, 77

tr 0123456789 ztnmrljkfp|sed 's/ */[aehiouwxy]*/g'|xargs sh -c 'grep -x $0 f'

Expects the number in stdin and the word list should be stored in the file f.

Does not uses all replacements (1 will always be z, 7 will always be k), so it may be called a lazy solution, but it finds at least one mnemonic for 95 numbers in [1-100].


Print invisible text Given a string as input, output a number of whitespace characters (0x0A and 0x20) equal to the length of the string.

For example, given the string Hello, World! your code would need to output exactly 13 whitespace characters and nothing else. These can be any mix of spaces and newlines.

Your code should not output any additional trailing newlines or spaces.

Testcases:

     Input      -> Amount of whitespace to output
"Hello, World!" -> 13
"Hi"            -> 2
"   Don't
Forget about
Existing
Whitespace!   " -> 45
""              -> 0
"             " -> 13
"
"               -> 1

Scoring:

This is code-golf so fewest bytes wins!

Whitespace, 311 150 77 68 65 46 41 38 bytes
-3 bytes thanks to Kevin Cruijssen
-27 bytes thanks to Ephphatha

&nbsp&nbsp
&nbsp&nbsp&nbsp	&nbsp	&nbsp
&nbsp
&nbsp&nbsp
&nbsp
	&nbsp
	&nbsp&nbsp

&nbsp&nbsp
&nbsp

Try it online!
A visible format
'\n  \n   \t \t \n \n  \n \t\n\t \t\t\t\n\t  \n\t\n  \n \n\n'

Explanation (s = space, t = tab, n = new line)
nssn     # label(NULL) - loop start
ssststsn # push 10 in the stack -> [10]
sns      # duplicate the top of the stack -> [10, 10]
sns      # duplicate the top of the stack -> [10, 10, 10]
tnts     # read a single char from input, pop the stack and store at that address -> [10, 10] [10:<char that was read>]
ttt      # pop the stack and put the value at that adress on stack -> [10,<char>] [10:<char>]
ntssn    # jump to label(0) - since label(0) is not defined, the interpreter jumps to the end of the program - if the top of the stack (char) is 0 -> [10] [10:<char>]
tnss     # pop the top of the stack and print as ascii -> [] [10:<char>]
nsnn     # go back to the label(NULL)

ZX80 (4K ROM version with sanity check)
~58 bytes (listing)
 1 INPUT A$
 2 IF A$="" THEN GO TO 1
 3 PRINT " ";
 4 LET A$=TL$(A$)
 5 IF A$="" THEN STOP
 6 GO TO 3

Line 2 can be removed to save RAMs. However, if an empty string is entered without line 2 then it will PRINT one space.


Longest Common Prefix of 2 Strings Write a program that takes 2 strings as input, and returns the longest common prefix. This is code-golf, so the answer with the shortest amount of bytes wins.

Test Case 1:

"global" , "glossary"
"glo"

Test Case 2:

"department" , "depart"
"depart"

Test Case 3:

"glove", "dove"
""

Python 3, 54 bytes

Thanks Python for having a built-in function for this task! :D

import os;print(os.path.commonprefix(input().split()))

Takes input as two words separated by a space such as glossary global.

Java, 152 bytes

String a="aa",b="ab";char[]c=a.toCharArray(),d=b.toCharArray();int e=0,f=Math.min(c.length,d.length);for(;e<f&&c[e]==d[e];e++);return new String(c,0,e);


24 and 12 Hour Times Write a program or function with no input that prints or returns this string of 24-hour and 12-hour times:

00:00 12:00am
01:00  1:00am
02:00  2:00am
03:00  3:00am
04:00  4:00am
05:00  5:00am
06:00  6:00am
07:00  7:00am
08:00  8:00am
09:00  9:00am
10:00 10:00am
11:00 11:00am
12:00 12:00pm
13:00  1:00pm
14:00  2:00pm
15:00  3:00pm
16:00  4:00pm
17:00  5:00pm
18:00  6:00pm
19:00  7:00pm
20:00  8:00pm
21:00  9:00pm
22:00 10:00pm
23:00 11:00pm

The string must be output exactly as it appears here. The only exception is that it may optionally have a single trailing newline.

So the MD5 hash of your output should be

827ae6e2dbb1df494930baedb3ee2653

if you do not have a trailing newline and

cd4c3d18abee9bafb495f390a919a13f

if you do. (Your hash could be different if your system uses another type of newline but that's OK.)

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

Bash + coreutils, 43 30

Saved 7 bytes thanks to @Yossarian
Saved 3 bytes thanks to @AndersKaseorg

seq 0 23|date -f- +%R\ %l:00%P

seq generates integers 0-23, one per line.
date interprets each line as a datetime.  Bare integers appear to be sufficient to be recognised as hours of the day by date.  date then outputs each time with the required formatting using the available time format specifiers.

Assumes LANG=C locale, as per this meta answer.
Ideone.


Generate code in another language Write a program in language A which outputs a program in language B where:

  Language A != Language B
  The output is itself a solution to this question.

This is a popularity contest. If you want to define your own BNFs/grammars for this, feel free, but try not to make it too boring by doing so.

EDIT: The more languages it ends up generating code in, the better (in my opinion).

EDIT2: Try to use languages that are not similar (I.e. generate the code in a different family of languages). (E.g. C to Scheme)

php --> asp --> html --> xhtml .......
 Hello

Infinite languages

HQ9+, HQ9++ (and more)

Q

I'm starting to like this family of languages.


Code golf a random orthogonal matrix An orthogonal matrix is a square matrix with real entries whose columns and rows are orthogonal unit vectors (i.e., orthonormal vectors).

This means that M^T M = I, where I is the identity matrix and ^T signifies matrix transposition.

Note that this is orthogonal not "special orthogonal" so the determinant of M can be 1 or -1.

The aim of this challenge is not  machine precision so if M^T M = I to within 4 decimal places that will be fine.

The task is to write code that takes a positive integer n > 1 and outputs a random orthogonal n by n matrix.  The matrix should be randomly and uniformly chosen from all  n by n orthogonal matrices.   In this context, "uniform" is defined in terms of the Haar measure, which essentially requires that the distribution does not change if multiplied by any freely chosen orthogonal matrix.  This means the values of the matrix will be floating point values in the range -1 to 1.

The input and output can be any form you find convenient.

Please show an explicit example of your code running.

You may not use any existing library function which creates orthogonal matrices. This rule is a little subtle so I  will explain more. This rule bans the use of any existing function which takes in some (or no) input and outputs a matrix of size at least n by n which is guaranteed to be orthogonal.  As an extreme example, if you want the n by n identity matrix, you will have to create it yourself.

You can use any standard random number generator library for choosing random numbers of your choosing.

Your code should complete within at most a few seconds for n < 50.

Haskell, 169 150 148 141 132 131 bytes

import Numeric.LinearAlgebra
z=(unitary.flatten<$>).randn 1
r 1=asRow<$>z 1
r n=do;m<-r$n-1;(<>diagBlock[m,1]).haussholder 2<$>z n

Recursively extend an orthogonal matrix of size n-1 by adding 1 to lower right corner and apply a random Householder reflection. randn gives a matrix with random values from a gaussian distribution and z d gives a uniformly distributed unit vector in d dimensions.

haussholder tau v returns the matrix I - tau*v*vᵀ which isn't orthogonal when v isn't a unit vector.

Usage:

*Main> m <- r 5
*Main> disp 5 m
5x5
-0.24045  -0.17761   0.01603  -0.83299  -0.46531
-0.94274   0.12031   0.00566   0.29741  -0.09098
-0.02069   0.30417  -0.93612  -0.13759   0.10865
 0.02155  -0.83065  -0.35109   0.32365  -0.28556
-0.22919  -0.41411   0.01141  -0.30659   0.82575
*Main> (<1e-14) . maxElement . abs $ tr m <> m - ident 5
True

Mathematica, 69 bytes, probably non-competing

#&@@QRDecomposition@Array[RandomVariate@NormalDistribution[]&,{#,#}]&

QRDecomposition returns a pair of matrices, the first of which is guaranteed to be orthogonal (and the second of which is not orthogonal, but upper triangular). One could argue that this technically obeys the letter of the restriction in the post: it doesn't output an orthogonal matrix, but a pair of matrices....

Mathematica, 63 bytes, definitely non-competing

Orthogonalize@Array[RandomVariate@NormalDistribution[]&,{#,#}]&

Orthogonalize is unambiguously forbidden by the OP. Still, Mathematica is pretty cool eh?


Don't google "google" We all know that if you google the word "google" it will break the internet.

Your task is to create a function that accepts one string and returns its length, in the fewest possible Unicode characters.

However, if the given string is google (lowercase), it will cause an error.

For example, g('bing') will return 4 but g('google') will cause an error.

Please provide an example of usage, and the error if possible.

Python 2, 29

lambda x:len(x)/(x!='google')

Gives a ZeroDivisionError on "google", and the length otherwise. This takes advantage of Python's booleans equaling 0 and 1.

Groovy, 32 chars

e={(it=='google'?0:it).length()}

A similar approach like a bunch of others here. The closure tries to return the length of either

the passed string, if it's not equal to google
the length of the integer 0, if the passed string is equal to google, which results in a MissingMethodException as there's no Integer.length() method

Tested with

e('bing')
e('google')
e('duckduckgo')


Remove single line and multiline comments from string Goal

Using the programming language of your choice, write the shortest program to eliminate comments from a string representing a C program.

Input

The string can be taken as any form of input, but it may also be taken as a variable.

Instructions

Two different kinds of comments are to be removed:

multiline comments, starting with /* and ending with */
single line comments, starting with // and ending with Linux-style line breaks (LF, \n)

Comments within strings are not to be deleted. For the purpose of this challenge, you only need to consider "-delimited strings. In particular, you can ignore the possibility of '-delimited character literals. You may also ignore trigraphs and line continuations (/\<LF>*...).

Examples

Input:

#include <stdio.h>

int main(int argc, char** argv)
{
    // this comment will be removed
    if (argc > 1) {
        printf("Too many arguments.\n");   // this too will be removed
        return 1;
    }
    printf("Please vist http://this.will.not.be.removed.com\n");
    printf("/* This will stay */\n");
    printf("\"/* This will stay too */\"\n");
    printf("//and so will this\\");
    // but not this
    printf("just \"ano//ther\" test.");
    return 0;
}

Output:

#include <stdio.h>

int main(int argc, char** argv)
{

    if (argc > 1) {
        printf("Too many arguments.\n");
        return 1;
    }
    printf("Please vist http://this.will.not.be.removed.com\n");
    printf("/* This will stay */\n");
    printf("\"/* This will stay too */\"\n");
    printf("//and so will this\\");

    printf("just \"ano//ther\" test.");
    return 0;
}

Input:

/*
    this shall disappear
*/
#include <string>
int main(int argc, char** argv)
{
    string foo = ""/*remove that!**/;
    // Remove /* this
    int butNotThis = 42;
    // But do */ remove this
    int bar = 4 /*remove this*/* 3; // but don't remove that 3. */
    return 0;//just a comment
}/*end of the file has been reached.*/

Output:

#include <string>
int main(int argc, char** argv)
{
    string foo = "";

    int butNotThis = 42;

    int bar = 4 * 3;
    return 0;
}

Shell + coreutils + gcc compiler collection, 31 bytes
This answer may seem a bit loopholey, but I didn't see anything specifically banning it in the question.
Rather than using clumsy regular expressions, why not use the tool that was built for the job.  It should have no problem giving correct results:
cpp -fpreprocessed -o- -|sed 1d

Takes input from STDIN and output to STDOUT.  Normally ccp will do all preprocessing (header files, macro expansion, comment removal, etc), but with the -fpreprocessed option, it will skip most of the steps, but it will still remove comments.  In addition, cpp adds a line like # 1 "<stdin>" to the beginning of the output, so the sed is there to delete it.

JS (ES6), 47 chars (wip)

DEMO: http://codepen.io/anon/pen/dPEMro

a=b=>b.replace(/(\/\*[^]*?\*\/|\/\/.*)\n?/g,"")

Inspired by my codegolfed minifiers: http://xem.github.io/miniMinifier/

doesn't handle comments in strings yet...

I'm curious to see if it's possible to achieve that in JS regexes.


Shortest program that throws StackOverflow Error Write a program that throws a StackOverflow Error or the equivalent in the language used. For example, in java, the program should throw java.lang.StackOverflowError.

You are not allowed to define a function that calls itself or a new class(except the one containing main in java). It should use the classes of the selected programming language.

And it should not throw the error explicitly.

Befunge, 1

I don't know Befunge, but...

1

from Stack overflow code golf

Java (OpenJDK 9), 70 bytes

public class Main{public static void main(String[] args){main(args);}}

Try it online!


Bloatware contest: producing 100+ MiB executable Create short source code in your favourite compiled language that compiles into a big (not less than 104857600 bytes) executable file. The program must be runnable (assuming 1GB of free memory) and can do anything (preferrable something simple like a hello world).

Usage of non-obvious tricks is encouraged.

Boring example in C:

int a[1024*1024*25] = { 1 };

int main(){}

Bonus points if it can be "explained" why the executable can't be reduced in size (i.e. all bloat is actually used somehow).

OK, here's another one in C, going for the vaguely defined bonus points:

#define a(x) x,x|1,x|2,x|3,x|4,x|5,x|6,x|7
#define b(x) a(x),a(x|8),a(x|16),a(x|24)
#define c(x) b(x),b(x|32),b(x|64),b(x|96)
#define d(x) c(x),c(x|128),c(x|256),c(x|384)
#define e(x) d(x),d(x|512),d(x|4<<8),d(x|6<<8)
#define f(x) e(x),e(x|2048),e(x|4096),e(x|6144)
#define g(x) f(x),f(x|8192),f(x|4<<12),f(x|6<<12)
#define h(x) g(x),g(x|2<<14),g(x|4<<14),g(x|6<<14)
#define i(x) h(x),h(x|2<<16),h(x|4<<16),h(x|6<<16)
#define j(x) i(x),i(x|2<<18),i(x|4<<18),i(x|6<<18)
#define k(x) j(x),j(x|2<<20),j(x|4<<20),j(x|6<<20)
int u,v,z[]={k(0),k(2<<22),k(4<<22),k(6<<22)}
int main(){for(u=v=0;u<1<<25;u++)v|=u!=z[u];return v;}

Basically, at compile time, it build a ascending sequence of integers from 0 to 225 − 1.  At runtime, it verifies that the sequence indeed contains the expected values, and if not, returns a non-zero error code.

Ps. If I did my math right, the executable should be over 100 MiB.  I'll let you know the exact size once it's done compiling...

Javascript

function bigenough(){
        var kbytes = $('html').html().length;
        return (kbytes>1024*100);
}
while(!bigenough()){
$('html').append('
WASSUP
');}

Run this code in Browser Console on this page and when complete, save the page. it should result in a file size greater than 100 MB. Still testing. Will post actual size once done.

update-
the saved page is the result executable. The v8 engine of chrome is the compiler. And the code I posted is the program. i admit that it does take quiet a long to compile. :D