Fit the factors in the field Given a positive integer below 1000, display all possible rectangles with that area.

Task

Let's say the input is 20. We can make a rectangle 20×1, 10×2, or 5×4, so this is a valid output:

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

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

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

Note that each possible rectangle appears exactly once.

The rectangles may appear in any order, orientation or position, but no two rectangles may overlap or touch, even at the corners. The following is also valid:

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

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

Scoring

The bounding-box area (BBA) of an output is the area of the minimum rectangle enclosing all of the rectangles. In the first example output, the size is 20×9, so the BBA is 180. In the second example output, the size is 20×7, so the BBA is just 140.

Find the BBA of the output when the the input is 60, 111, 230, 400, and 480, and add them up. Multiply this sum by the size of your code in bytes. The result is your score; lowest score wins.

Rules

The program (or function) must produce valid output for any positive integer below 1000.
The output must contain just asterisks (*), spaces (), and newlines.
There can be any amount of space between the rectangles, but this counts towards the BBA.
Leading or trailing lines or columns, if they have just spaces, do not count towards the BBA.

Ruby, 228 bytes * 21895 =4992060

->n{a=(0..n*2).map{$b=' '*n}
g=0
m=n*2
(n**0.5).to_i.downto(1){|i|n%i<1&&(m=[m,n+h=n/i].min
g+=h+1
g<m+2?(a[g-h-1,1]=(1..h).map{?**i+$b}):(x=(m-h..m).map{|j|r=a[j].rindex(?*);r ?r:0}.max
(m-h+1..m).each{|j|a[j][x+2]=?**i}))}
a}

Several changes from ungolfed code. Biggest one is change of meaning of variable m from the height of the squarest rectangle, to the height of the squarest rectangle plus n.

Trivially, *40 has been changed to *n which means a lot of unnecessary whitespace at the right for large n; and -2 is changed to 0 which means rectangles plotted across the bottom always miss the first two columns (this results in poorer packing for numbers whose only factorization is (n/2)*2)

Explanation

I finally found time to get back to this.

For a given n the smallest field must have enough space for both the longest rectangle 1*n and the squarest rectangle x*y. It should be apparent that the best layout can be achieved if both rectangles have their long sides oriented in the same direction.

Ignoring the requirement for whitespace between the rectangles, we find that the total area is either (n+y)*x = (n+n/x)*x or n*(x+1). Either way, this evaluates to n*x + n. Including the whitespace, we have to include an extra x if we place the rectangles end to end, or n if we place the rectangles side by side. The former is therefore preferable.

This gives the following lowerbounds (n+y+1)*x for the field area:

n     area
60    71*6=426
111  149*3=447
230  254*10=2540
400  421*20=8240
480  505*20=10100

This suggests the following algorithm:

Find the value (n+y+1) which shall be the field height
Iterate from the squarest rectangle to the longest one
  While there is space in the field height, draw each rectangle, one below the other, lined up on the left border.
  When there is no more space in the field height, draw the remaining rectangles, one beside the other, along the bottom border, taking care not to overlap any of the rectangles above.
  (Expand the field rightwards in the rare cases where this is necessary.)

It is actually possible to get all the rectangles for the required test cases within the above mentioned lower bounds, with the exception of 60, which gives the following 71*8=568 output. This can be improved slightly to 60*9=540 by moving the two thinnest rectangles right one square and then up, but the saving is minimal, so it's probably not worth any extra code.

10
12
15
20
30
60
******
******
******
******
******
******
******
******
******
******

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

This gives a total area of 21895.

Ungolfed code

f=->n{
  a=(0..n*2).map{' '*40}                                      #Fill an array with strings of 40 spaces
  g=0                                                         #Total height of all rectangles
  m=n                                                         #Height of squarest rectangle (first guess is n)
  (n**0.5).to_i.downto(1){|i|n%i<1&&(puts n/i                 #iterate through widths. Valid ones have n%i=0. Puts outputs heights for debugging.
    m=[m,h=n/i].min                                           #Calculate height of rectangle. On first calculation, m will be set to height of squarest rectangle.
    g+=h+1                                                    #Increment g
    g<n+m+2?                                                  #if the rectangle will fit beneath the last one, against the left margin
      (a[g-h-1,1]=(1..h).map{'*'*i+' '*40})                      #fill the region of the array with stars
    :                                                         #else
      (x=(n+m-h..n+m).map{|j|r=a[j].rindex('* ');r ?r:-2}.max    #find the first clear column
      (n+m-h+1..n+m).each{|j|a[j][x+2]='*'*i}                    #and plot the rectangle along the bottom margin
    )
  )}
a}                                                            #return the array

puts f[gets.to_i]


The Clock Hands of Doom You are chained to a chair. Underneath you is a huge volcano. A 12-hour clock next to you ticks ominously, and you see that it has wires leading from the back up to a chain, which will drop you into the center of the earth. Taped to the clock is a note:

  Each clock hand has an electrode. When both clock hands are in the same position, the power flows and you die. That is, unless you can tell me the exact time that this will occur, to the nearest minute.

You have a computer that knows every programming language. You need to create the shortest (this is code-golf, and standard loopholes are prohibited) program you can, and tell the evil scientist what the time will be. Your program should take input (in any method), consisting of the hour and minute. It should return the next hour and minute (in any method) that this occurs.

According to the OEIS page, the eleven overlap times are:

00:00:00 plus 0/11 s, 01:05:27 plus 3/11 s,
02:10:54 plus 6/11 s, 03:16:21 plus 9/11 s,
04:21:49 plus 1/11 s, 05:27:16 plus 4/11 s,
06:32:43 plus 7/11 s, 07:38:10 plus 10/11 s,
08:43:38 plus 2/11 s, 09:49:05 plus 5/11 s,
10:54:32 plus 8/11 s.

The next time would be 12:00:00. The seconds and their fractional parts are not needed for this challenge. Simply round to the nearest minute.

Test cases:

0:00 (Or 12:00) > 1:05
1:00 > 1:05
11:56 > 12:00 (Or 0:00)
6:45 > 7:38
5:00 > 5:27
6:30 > 6:33 (round up)

The program can be a function, or full program. I do not care if you choose 0:00 or 12:00, and both are acceptable. Good luck!

JavaScript (Node.js), 54 47 bytes (round to the nearest)

-7 bytes. Thanks @user202729

a=>b=>[(a+=b>5.46*a)+a/11|0,a%12*65.46%60+.5|0]

Try it online!

JavaScript (Node.js), 40 33 44 bytes (rounds towards 0)

-3 bytes thanks to @Arnauld

-4 bytes thanks to @Kevin Cruijssen

a=>b=>[(a+=b>5.46*a)+a/11|0,a%12*65.46%60|0]

Explanation

a=>b=>[(a+=b>5.46*a)+a/11|0,a%12*65.46%60|0]    Full Code
a                                               Hours
   b                                            Minutes
    =>[                    ,               ]    return array with
       (a+=        )                            add to the current hour
           b>5.46*a                             1 if the minute's clock hand has
                                                passed the hour's clock hand. Here we use
                                                equation 60*a/11 which is the same as 5.46*a
                    +a/11                       and add 1 when hour is 11
                         |0                     floor the result

                            a%12*65.46%60|0     Here we do equation ((720/11)*a) (mod 60)
                            a%12                In case of hour 12 we take 0
                                *65.46          multiply hour by 720/11 which can be shortened to
                                                65.46 to save 1 byte.
                                      %60       mod 60
                                         |0     floor the result

Side note: I'm pretty sure this can be golf down by someone with more knowledge at math. I barely know how to sum and multiply

Try it online!


The most unreliable gun ever You are given a very special gun with a full magazine.

Let n be the initial number of bullets in the magazine and i the number of bullets left.

That gun is really unreliable, hence each time you shoot, you have a i/n chance to successfully shoot. The fewer bullets you have left, the more tries it requires to shoot.

The goal is to find the average number of attempts to shoot before running out of ammo.

Example

You start with 3 bullets (n=3). Your first shot is always successful. You have now 2 bullets left. You will shoot first with a probability of 2/3 and misfire with 1/3. The probability of emptying your magazine in just 3 tries (no misfires) is (3/3) * (2/3) * (1/3).

The average number of tries before emptying your magazine for this example is 5.5.

Test Cases

f(2) = 3.000
f(3) = 5.500
f(4) = 8.330
f(10) ~= 29.290

05AB1E, 3 bytes

L/O

Try it online!
or as a Test suite

Explanation

L     # range [1 ... n]
 /    # divide n by each in above list
  O   # sum


Find nth root of variable without using math operators/functions Write a program which, given two positive integers n and x, will display the n-th root of x (which is also x1/n) in decimal to an accuracy of 0.00001. The program must output the resulting number in decimal, and it must work for any two numbers n and x. The variables may be defined in the program, or they may be inputted by the user, but it must work for any two positive integers.

However:

You may not use any arithmetic operators or bitwise operators (including +, *, ^, >>, etc.)
You may not use any built-in math functions (such as pow(), sqr(), or add()).
No web requests; the program must be completely independent from all outside sources.

Although I tagged this code-golf, a program with more code that can do the job more than 1 second faster is better. A winning program will be faster than all the other programs by more than a second. Time differences of less than 1 second will be considered negligible. If two programs complete within a second of each other, then the one with less code wins.

JavaScript

This answer doesn't satisfy all the rules, but I'm happy that at least it works. It's valid only for integers greater than one and there's no further precision.

Note that the + and > operators are used for string concatenation/comparison and the maths is behind the curtain. I hope that the ! operator doesn't count as "arithmetic" as it operates over booleans.

function f(x,n){for(a=(c=',')+Array(x),s=r=c;a>s;r+=c)for(i='',s=r;i!=Array(n);i+=c)s=s.split(c).join(r);return r.slice(1).length}

And some tests:

> f(125,3)
5
> f(16807,5)
7
> f(4782969,7)
9


Sort the climbing grades My first code golf post, apologies for any mistakes...

Context

In rock climbing (bouldering specifically), the V/Vermin (USA) climbing grades start at 'VB' (the easiest grade), and then go 'V0', 'V0+', 'V1', 'V2', 'V3', 'V4', 'V5' etc. up to 'V17' (the hardest grade).

Task

You will take as input a list/array of climbing grades and you have to to return or print a list/array of the grades sorted from easiest to hardest.

If the input is empty, return an empty data structure; otherwise the input will always be a valid.

Test cases

Input | Output
[] |  []
['V1'] |  ['V1']
['V7', 'V12', 'V1'] | ['V1', 'V7', 'V12']
['V13', 'V14', 'VB', 'V0'] |  ['VB', 'V0', 'V13', 'V14']
['V0+', 'V0', 'V16', 'V2', 'VB', 'V6'] | ['VB', 'V0', 'V0+', 'V2', 'V6', 'V16']

This is a code-golf challenge.


Find the coefficients of a rational generating function If we write a sequence of numbers as the coefficients of a power series, then that power series is called the (ordinary) generating function (or G.f.) of that sequence. That is, if for some function F(x) and series of integers a(n) we have:

a(0) + a(1)x + a(2)x^2 + a(3)x^3 + a(4)x^4 + ... = F(x)

Then F(x) is the generating function of a. For example, the geometric series tells us that:

1 + x + x^2 + x^3 + x^4 + ... = 1/(1-x)

So the generating function of 1, 1, 1, ... is 1/(1-x). If we differentiate both sides of the equation above and multiply by x we get the following equality:

x + 2x^2 + 3x^3 + 4x^4 + ... = x/(1-x)^2

So the generating function of 1, 2, 3, ... is x/(1-x)^2. Generating functions are a very powerful tool, and you can do many useful things with them. A short introduction can be found here, but for a really thorough explanation there is the amazing book generatingfunctionology.

In this challenge you will take a rational function (the quotient of two polynomials with integer coefficients) as input as two arrays of integer coefficients, first the numerator then the denominator. For example the function f(x) = x / (1 - x - x^2) will be encoded as [0, 1], [1, -1, -1] in the input.

Given this input your program must infinitely print the coefficients of the power series that equals the generating function, one per line, starting at the coefficient of x, then x^2, etc.

Examples:

[1], [1, -1] -> 1, 1, 1, 1, 1, 1, 1, ...
[1], [2, -2] -> 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, ...
[0, 1], [1, -2, 1] -> 1, 2, 3, 4, 5, 6, 7, 8, ...
[0, 1], [1, -1, -1] -> 1, 1, 2, 3, 5, 8, 13, 21, 34, ...
[1], [1, -2] -> 1, 2, 4, 8, 16, 32, 64, 128, ...
[0, 1, 1], [1, -3, 3, -1] -> 1, 4, 9, 16, 25, 36, ...

Haskell, 63 bytes

z=0:z
(a:b)%y@(c:d)=a/c:zipWith(-)(b++z)(map(a/c*)d++z)%y
_%_=z

Try it online!

Defines an operator % returning an infinite lazy list of coefficients. The list is zero-indexed, so the constant coefficient is included.


Pixel-art, episode 1: display Super Mario it's a-me!

Today's task is simple: write a program, or a function that displays the idle small Mario sprite, from Super Mario Bros, on NES, over a blue background.

Any kind of entry is valid as long as it displays those 12 * 16 pixels anywhere on the screen / window / browser.

(EDIT: the displayed image can be scaled up if your language can't do pixel art. You can also output ASCII art or HTML art, but using the right colors.)

Image (zoomed 400%):

You must use the following colors:

blue: #6B8CFF
red: #B13425
green/brown: #6A6B04
orange: #E39D25

Shortest program (in number of characters) wins!

Standard loopholes apply (especially, no network connexion allowed), but hardcoding and displaying an image file in your program is allowed. (entries using this trick will be rank separately)

Here we go!

Current Leaderboard

Shortest answer using code only:

Mathematica, 141. https://codegolf.stackexchange.com/a/39916/10732 (by Martin Büttner)
Bash, 158. https://codegolf.stackexchange.com/a/40002/10732 (by hpsMouse)
...

Shortest answer using some kind of hardcoded image:

HTML, 102b. https://codegolf.stackexchange.com/a/39923/10732 (by xem and NiettheDarkAbsol)
PHP, 131b. https://codegolf.stackexchange.com/a/39926/10732 (by NiettheDarkAbsol)
...

HTML/JS, 206 158 153 102

102

Trick used: save the compressed GIF file as an HTML file, and add  at the end

Thanks to this entry: https://codegolf.stackexchange.com/a/39926/10732 by @NiettheDarkAbsol

GIF87a  ¡ kŒÿã%jk±4%,       6„‡héj„Af-ÕdÎy\%    …R˜0”ŒÈJ³I©±²û“ú=ª$±p%i¸•¤

Demo: http://meuziere.free.fr/mario/gif.html

Older versions:

153

Trick used: save the compressed PNG file as an HTML file, and add  at the end

‰PNG

IHDR         _v”   PLTEjkkŒÿ±4%ã%ó’V   IIDAT×c[Êµj%C€ÍUŸ?|ìíœÿ02„ÿÿÊÐÊàÐÄÈÀ°ŠáÓë~†«ö3üZµž!jÚR‡P x( s6ïåÇ

158

Trick used: setting the trimmed dataURI of a compressed PNG as the SRC of an IMG tag and packing the whole thing in Unicode chars.

Execute that in your JS console:

document.write(unescape(escape('').replace(/uD./g,'')))

206

Unpacked (206b):

Demo

Tools used:

https://tinypng.com/
http://xem.github.io/miniURI/input.html
http://xem.github.io/obfuscatweet/


Array-of-array string conversion to and from matrix Matrix challenges are popular. There's an issue of how to provide test cases. A common method is the row-wise array-of-arrays representation, such as:

[[1,2],[3,4],[5,6]] -> a 3 by 2 matrix

This is good with vertical space, but there's always the task of converting the test cases into something your language can use, and vice versa for producing test cases to this format.

So this is a code-golf challenge and also a repository of conversion functions that people can use when trying or composing matrix challenges.

Defining the format

A row string of length m is a comma-separated list of m ≥ 1 numbers, enclosed in square brackets.

A row-wise n×m array-of-arrays string is a comma-separated list of n ≥ 1 row strings of length m enclosed in square brackets with the following whitespace rules:

has no whitespace before the first [ or after the last ], except for an optional trailing newline.
otherwise may contain spaces

The challenge

Produce two* programs/functions in your language:

one which takes a rowwise n×m array-of-arrays string as an input, and outputs the matrix (as implemented in the language.)
another one which takes an n×m matrix (as implemented in the language) as an input and outputs the rowwise n×m array-of-arrays string.

*It is allowed for one program/function to perform both tasks and you can have helper code used by both conversion functions.

Rules

To be clear: the language must support matrices (or something equivalent like 2D arrays - the name is not important) because the output/input of the two tasks needs to be an actual matrix in the language.
This is code-golf.
Fewest total number of bytes (from all functions and any helper code) in each language wins.
If one program or function does both conversions, only count those bytes once.
Standard rules apply/loopholes forbidden.

Test strings

[[1]]
[ [ 1, 2 ], [ 3, 4 ] ]
[[1.2,3.4,5.6],[3,2,1], [10, 11, 12.1]]

Not really possible to provide test matrices.

A non-golfed, possibly not bug-free worked example

I hope this doesn't violate the "don't answer your own question" guideline.

The R function I use to convert from string to matrix

The R function I use to convert from matrix to string

Here's the Sandbox and a related question.

Japt, 30 bytes
F=_OxZ}G=_Oo'[+Zm_'[+Z+']} +']

Try it online!
Function F converts a string into a matrix, and function G converts a matrix into a string.


Polyglot Iterative Quine Introduction

A polyglot is a program that is valid in multiple languages at once. An iterative quine is a program that outputs another program that outputs another program that outputs the source of the original program. Note that the number of chained programs does not have to be 3; it could be 2, 4, or 97384.

Challenge

Your task is to write a polyglot iterative quine. Each program in the program chain must be a polyglot.

Each of your programs must take no input.
As stated above, each of the programs must output the source of the next program in the chain. The last program in the chain must output the source code of the first program.

Scoring

Your score is calculated as follows:

For each program in the chain, take the number of languages it is valid in. Sum the results.
Sum the byte count of each program in the chain.
Divide the byte count by the number from the first program.

Rules

The length of the chain must be at least 2.
Each program in the chain must be valid in at least 2 languages.
The program with the lowest score wins.
"Different language" is defined as follows:

A language where the source code of the compiler or interpreter is not the same as another, and the compiler or interpreter does not run the same language as another. Some examples of different languages are: Python 2 and 3, C and C++, Java and C, and Lua and Ruby. However, by this definition, using tcc instead of gcc does not count as a different language, because tcc runs the same language as gcc: C.

Programs are allowed to throw errors, but only after they print out the output of the program. For example, print(1/0);print(<quine stuff>) in Python 3 would be invalid, but print(<quine stuff);print(1/0) would be.

Wumpus, ><>, Befunge-98, \$\frac{57+57}{3+3}=19\$

"]<0~[#34ooo!O;#53&o@,k*4e-1#'$ #o#!-1'#'+3*a9*c5+*68%2++

Try it in Wumpus! Try it in ><>! Try it in Befunge-98!

A modified version of a previous polyglot of mine that makes it iterative by flipping the first 0 to a 1 and back again.


Convert CP437 to UTF-8 The goal is to read bytes from input encoded in Code Page 437 and output the same characters encoded as UTF-8.  That is, bytes should be translated into Unicode codepoints per this table (a particular revision of the Wikipedia article).  Bytes 0-31 and 127 are to be treated as graphics characters.

Rules

Input and output is via stdin/stdout, or something equivalent to it (only a function that performs the conversion doesn't qualify).  Input is 0 or more bytes before the input stream is closed.

Encoding with UTF-8 is part of the task (as is decoding the input as CP437), so to that end built-in functions or language features that perform conversion between character encodings are not allowed.  Submissions should implement the character encoding conversion themselves.

Scoring is pure code-golf, shortest code wins.  Code length is measured in bytes assuming the source code is encoded using UTF-8.

Example

A byte containing 0x0D received on input, representing '♪', should output bytes 0xE2, 0x99, 0xAA (in that order), which represents codepoint U+266A encoded in UTF-8.

Links

CP437 to Unicode conversion table
Summary of UTF-8 encoding
(Task) Unicode UTF Converter -- for converting between Unicode encodings.

Tcl, 675

eval [zlib i Ò×sgÆáB\nPÃïÿòpÁ\f0\fv®4\fBc!j¶%cluYbãdÃw¨)+½MB()zàõÍóÝ=\{vÏì®ÿ¢Ö¶\rk×áóUë\tÌÀOÖ)'*ð,ò¦Ì1\[¦y\v?e~oÀÛ\;¼3)ï*S!ïMgÀÜé¬0OVy_sÌÇï©³@ýa>ÀoïæCMl°7ÎG¸«£Æ'º6Ä\"e±³DÆX*#,Ãïd¹êª²Á&ü®Al±!¬Ì,KË³KÓØèÀ*tbU¶cCìÀöÓíc'VcæKl+¬(V\$µÇFI`ãtc#ô`ôbHbS¤°ú°~vã²ôãrìÁÀäD4!í%\$ÕÉcÃ°(E\\®În²vPÁÕ¨âSÃ5ØË°We?nÚ>Ê°1\"ãÄOyÆð»3Ë,²¯d7dº2)\{iÈ=ý|-w3¥\tÈGå(NÖ0ÙÏ1ä¸lpBý\}\t¾e¾E¾i¾<Y£)KCy~ÎÉçe\v2ÆEç¬rYV¸¢ç&¹*»¸¦\;¸.ÃÜ\]ÜnÉ\ ·ñùÄÇóÍ\ ?ãåøæîàÆøf»xEîá%¹WæÞ(¿é_àwíü7Æ:.ó¿3Ã_¸a©,ð·Ìó>Veÿ°\tëtOpxªS<ÃMð\\e/ð7Oñ7ÂÿzÍ4¯pé´lølÕjZÛV¯\]·råk]

Just a simple mapping between input and output. Decompressed it looks like

puts [string map { âº  â»  â¥  â¦  â£  â   â¢  â {  } â {
} â {} â {} â {
} âª  â«  â¼  âº  â  â  â¼  Â¶  Â§  â¬  â¨  â  â  â  â  â  â  â²  â¼  â  Ã  Ã¼  Ã©  Ã¢  Ã¤  Ã   Ã¥  Ã§  Ãª  Ã«  Ã¨  Ã¯  Ã®  Ã¬  Ã  Ã  Ã  Ã¦  Ã  Ã´  Ã¶  Ã²  Ã»  Ã¹  Ã¿  Ã  Ã  Â¢  Â£  Â¥  â§  Æ   Ã¡ ¡ Ã ¢ Ã³ £ Ãº ¤ Ã± ¥ Ã ¦ Âª § Âº ¨ Â¿ © â ª Â¬ « Â½ ¬ Â¼  Â¡ ® Â« ¯ Â» ° â ± â ² â ³ â ´ â¤ µ â¡ ¶ â¢ · â ¸ â ¹ â£ º â » â ¼ â ½ â ¾ â ¿ â À â Á â´ Â â¬ Ã â Ä â Å â¼ Æ â Ç â È â É â Ê â© Ë â¦ Ì â  Í â Î â¬ Ï â§ Ð â¨ Ñ â¤ Ò â¥ Ó â Ô â Õ â Ö â × â« Ø âª Ù â Ú â Û â Ü â Ý â Þ â ß â à Î± á Ã â Î ã Ï ä Î£ å Ï æ Âµ ç Ï è Î¦ é Î ê Î© ë Î´ ì â í Ï î Îµ ï â© ð â¡ ñ Â± ò â¥ ó â¤ ô â  õ â¡ ö Ã· ÷ â ø Â° ù â ú Â· û â ü â¿ ý Â² þ â  ÿ Â } [read stdin]]


Read a password: on mobile! Thanks to MD XF's recent challenge, we can now read passwords in many different languages! The problem is, now we need to port our applications to mobile devices, and they do password entry a little differently.

Challenge

Read a string from the keyboard.
Each time a characterk is entered, display it for a short time interval.
After the time interval has passed OR the user has entered another character, replace k with some character c.

Rules

c must be constant; it must be the same character.
c can be any visible character (i.e. it cannot be a newline, space, tab, or unprintable).
c can't be based on any inputted k; c must be defined/constant
before the first k is read.
c must be the same every time the program is run.
c can be one of the values given as k if by accident, as long as all other rules are followed.

You must print k in realtime. As soon as the user enters a new k, you must display it immediately.
k should be visible to the end user before being changed to c; the time interval shall not be less than 0.5 seconds.
k should be replaced by c within a reasonable time; the time interval shall not exceed 5 seconds.
As soon as a new character is entered, whether or not the time interval has expired, you should replace k with c and use the entered key as the new k immediately.

It is acceptable to clear and redraw the screen each time you need to change a character.
You may use any reasonable methods of input and output as long as all other rules are followed.
You may assume that the number of characters inputted is never longer than the terminal/graphical window width.
If using a terminal, your program should terminate after a newline is entered or EOF is reached.
Your program should function as outlined here on both mobile and other environments.

Your program may assume that the input will only contain printable characters (letters, numbers, symbols) and possibly a terminating newline (no backspace, arrow keys, delete, etc).
Your program may terminate when Ctrl+C is pressed.
You may terminate your program by closing a window, if your program launches one.

Scoring

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

Example

Here is an example of what it should look like. Note this is recorded on a mobile platform, but should also work on a desktop platform.

HTML + JavaScript, 20+105 = 125 bytes

<input id=I oninput=v=I.value;s='*'.repeat(l=v.length-1);I.value=s+v[l];clearTimeout(I.t);I.t=setTimeout(`I.value=s+'*'`,1e3)

The delay between the entry of k and the letter becoming * is one second.

JavaScript oninput, Formatted

v=I.value;
s='*'.repeat(l=v.length-1);
I.value=s+v[l];
clearTimeout(I.t);
I.t=setTimeout(`I.value=s+'*'`,1e3)

Test Snippet

Added the ending bracket (>) for better compatibility.

<input id=I oninput=v=I.value;s='*'.repeat(l=v.length-1);I.value=s+v[l];clearTimeout(I.t);I.t=setTimeout(`I.value=s+'*'`,1e3)>


Roman-style date formatting Today (March 15) is the Ides of March, best known for being the date that Julius Caesar was assassinated.

What's “Ides”?  Well, the ancient Romans didn't simply number the days of month from 1 to 31 like we do.  Instead, they had a more complex system of counting backwards to the Kalends, Nones, or Ides.

Challenge

Write, in as few bytes as possible, a program that will display the current date (on the Gregorian calendar, in the local timezone) using the abbreviated Roman-style convention described below.  Your program should work until at least the end of 2037.

Roman dates

Months of the year

These should look familiar to you: Ianuarius, Februarius, Martius, Aprilis, Maius, Iunius, Iulius (Quintilis), Augustus (Sextilis), September, October, November, December.

Your program is to abbreviate all months to three letters, using the classical Latin alphabet (all caps, with J=I and U=V).  That is, IAN, FEB, MAR, APR, MAI, IVN, IVL, AVG, SEP, OCT, NOV, DEC.

Special dates of the month

Kalendis, or the Kalends (abbr. KAL) is the first day of each month.
Idibus, or the Ides (abbr. ID) is the 15th day of March, May, July, or October; but the 13th day of the other eight months.
Nonas, or the Nones (abbr. NON) is 8 days before the Ides (5th or 7th of the month)

Other days of the month

Other days of the month are numbered by counting backwards and inclusively to the next reference date (Kalends, Ides, or Nones).  Notation is AD (abbreviation for ante diem, no relation to Jesus of Nazareth) followed by the appropriate Roman numeral.

Exception: Write PR (for pridie) instead of AD II for the day before Kalends, Nones, or Ides.

The leap day

In leap years, two days (February 24 and 25 in modern reckoning) are given the date AD VI KAL MAR.  (You do not need to distinguish the two days in your program.)  February 14-23 are AD XVI KAL MAR through AD VII KAL MAR as in non-leap years.  Feb 26 = AD V KAL MAR, Feb 27 = AD IV KAL MAR, Feb 28 = AD III KAL MAR, and Feb 29 = PR KAL MAR, offset by one from the corresponding dates in non-leap years.

Example

In March, the output of your program should be:

On March 1: KAL MAR
On March 2: AD VI NON MAR
On March 3: AD V NON MAR
On March 4: AD IV NON MAR
On March 5: AD III NON MAR
On March 6: PR NON MAR
On March 7: NON MAR
On March 8: AD VIII ID MAR
...
On March 13: AD III ID MAR
On March 14: PR ID MAR
On March 15: ID MAR
On March 16: AD XVII KAL APR
...
On March 30: AD III KAL APR
On March 31: PR KAL APR

Tcl/Tk, 675 bytes

Well, I suppose I could crunch it more, but this is it for now...

set a {y m d}
rename proc p
p r {n {s ""}} {foreach {v d} {10 X 5 V 1 I} {while {$n>=$v} {set s $s$d;incr n -$v}};string map {VIIII IX IIII IV} $s}
p y y {expr !($y%100?$y%4:$y%400)}
p i $a {expr {($m in {3 5 7 10})?15:13}}
p n $a {expr [i $y $m $d]-8}
p k $a {expr $m==2?29+($d>24&&[y $y]):$m<8?31+$m%2:32-$m%2}
p N {} {clock f [clock se] -f {%Y %N %e}}
p M m {lindex {IAN FEB MAR APR MAI IVN IVL AVG SEP OCT NOV DEC IAN} $m-1}
p d $a {foreach f {n i k} n {NON ID KAL} mo {0 0 1} {if {$d<=[$f $y $m $d]} break}
string map {{AD I } {} {AD II } {PR }} "AD [r [expr [$f $y $m $d]+1-$d]] $n [M [expr $m+$mo]]"}
p p $a {if {$d==1} {puts "KAL [M $m]"} {puts [d $y $m $d]}}
p {*}[N]

How it works

The first thing is to collect today's date as a list: year, month, day. Everything works over that. The first of the month is a simple special case; we handle that separately.

All remaining cases work like this:

Find the future reference day's date in (5,7,13,15,days-in-month)
Get the abbreviation corresponding to that reference (NON, ID, KAL)
For Kalends we increment the month by one
Assemble the date string as:
"AD <days-in-roman-numerals> <abbreviated-reference-day> <abbreviated-month-name>"
Apply a text replace to correct AD I and AD II.

The first step is done with a function lookup table for each of the Nones, Ides, and Kalends. Nones and Ides are straight-forward subtraction and lookup, respectively. Computing the Kalends is only a little more complicated (notice the trick with leap-February's day number.):

February → 28 days + (it's a leap year AND day > 24)
January..July → 30 days + (it's January, March, May or July)
August..December → 31 days - (it's September or November)

The days is a simple difference: (reference_day - todays_day + 1)

Computing the leap year is done with a somewhat unusual arrangement of the standard formula so that it could be crunched better (removing braces and parentheses from the expr command).

Converting decimal to Roman numerals is a simple table-driven approach, stripped to use only ones, fives, and tens since we don't need to print the year in Roman numerals (domain is [1,39]).

Almost everything else is application of lookup tables.

A note on Tcl and reducing bytes

The first two lines of the script eat bytes by simply being shorter than spelling out proc f {y m d} for all instances.

Single-letter proc names and variables, of course:

    r := decimal→roman(n)    i := ides(y,m,d)        M := month-abbreviation(month)
    y := is-leap(year)       n := nones(y,m,d)       d := date→roman(y,m,d) [d ≠ 1]
    N := today → (y,m,d)     k := kalends(y,m,d)     p := date→roman(y,m,d) [∀d]

Testing for dates other than today

Change the very last line from p {*}[N] to

p {*}$argv

and run the program with the date desired:

% tclsh roman.tcl 2016 2 25
AD VI KAL MAR

Enjoy!


Largest monetary amount impossible to make with two types of coin Suppose we have two different types of coin which are worth relatively prime positive integer amounts. In this case, it is possible to make change for all but finitely many quantities. Your job is to find the largest amount that cannot be made with these two types of coin.

Task

Input: A pair of relatively prime integers \$(a,b)\$ such that \$1<a<b\$.

Output: The largest integer that cannot be expressed as \$ax+by\$ where \$x\$ and \$y\$ are nonnegative integers.

Scoring:

This is code golf so shortest answer in bytes wins.

Example:

Input \$(3,11)\$

\$4\cdot 3- 1\cdot 11=1\$, so if \$n\geq 22\$ we can write \$n=q\cdot 3 + 2\cdot 11 +r\$ where \$q\$ is the quotient and \$r\in\{0,1,2\}\$ the remainder after dividing \$n-22\$ by \$3\$. The combination \$(q+4r)\cdot 3 + (2-r)\cdot 11 = n\$ is a nonnegative combination equal to \$n\$. Thus the answer is less than \$22\$. We can make \$21=7\cdot 3\$ and \$20=3\cdot 3 + 1\cdot 11\$ but it's impossible to make \$19\$ so the output should be \$19\$.

Test Cases:

[ 2,  3] => 1

[ 2,  7] => 5

[ 3,  7] => 11

[ 3, 11] => 19

[ 5,  8] => 27

[ 7, 12] => 65

[19, 23] => 395

[19, 27] => 467

[29, 39] => 1063

[ 1,  7] => error / undefined behavior (inputs not greater than one)

[ 6, 15] => error / undefined behavior (not relatively prime).

[ 3,  2] => error / undefined behavior (3 > 2)

[-3,  7] => error / undefined behavior (-3 < 0)

J, 7,6 3 bytes

-1 byte thanks to FrownyFrog !

-3 bytes thanks to Grimmy!

*-+

Try it online!

     -    subtract
      +   the sum of the arguments
    *     from their product


Build a bit-counting comparator using NAND logic gates A bit-counting comparator (BCC) is a logic circuit that takes some number of counting inputs A1, A2, A3, ..., An as well as inputs B1, B2, B4, B8, ... representing a number. It then returns 1 if the total number of A inputs that are on is greater than the number represented in binary by the B inputs (e.g. B1, B2, and B8 would make the number 11), and 0 otherwise.

For example, for a bit-counting comparator that takes 5 inputs, of which A2, A4, A5, and B2 are set to 1, will return 1 because there are 3 A inputs that are on, which is greater than 2 (the number represented by only B2 being on).

Your task is to create a bit-counting comparator that takes a total of 16 A inputs and 4 B inputs (representing bits from 1 to 8), using only two-input NAND gates, and using as few NAND gates as possible. To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:

NOT: 1
AND: 2
OR: 3
XOR: 4

Each of these scores corresponds to the number of NAND gates that it takes to construct the corresponding gate.

The logic circuit that uses the fewest NAND gates to produce a correct construction wins.

169 nands

Adds up the A's to get A{1,2,4,8,16}.  Then does a binary comparison with the Bs.

I use a few more building blocks:

FA = full adder, 9 nands (from here)
HA = half adder, 7 nands (same ref)
EQ = equality, 5 gates (a.k.a. xnor)

The half and full adders have 2 outputs - they are distinguished with an r for result and c for carry.

The A{1,2,4,8,16} are the outputs from the half adders.


Output a non-Context-Free Language Your challenge is to write a program which will output a non-context-free language.

A Context-free Grammar is a series of replacement rules, describing which symbols can be replaced by which other symbols. It defines set of strings, known as a language, which is generated by performing all possible replacement rules on an initial symbol until no more replacements can be made.

Any language which can be generated this way is known as a context-free language.

Your challenge is to write a program which will output a language which cannot be generated this way.

Details:

Output your language in increasing order of length. Ordering between strings of a given length is up to you.
As all CSLs are infinite, your program must not halt.
The strings must be separated from each other. However, you may choose the separation.
Please include in your answer a description of the language you generate and an explanation of why it is not context-free.
One possible way to prove this is by using the pumping lemma.
Example context-sensitive language: [abc, aabbcc, aaabbbccc, aaaabbbbcccc, ...]

Scoring: For all programs which can be encoded in ASCII or another 7 bit or less character set, scoring is by character. For all other programs, scoring is (# of bits in binary encoding)/7.

Feel free to ask questions.

Python 2 (24) (26)

s="1"
while 1:print s;s+=s

Prints the language of strings in the symbol 1 whose length is a power of 2, i.e {"1"*(2**n) | n>=0}. The s+=s is equivalent to s*=2; it doubles the string each time.

Since unary (one-symbol) CFG's are regular, and unary regular CFG's are periodic past a point, this cannot be regular and thus is not a CFG. Alternatively, use the pumping lemma to see that the possible lengths of words in a CFL must have finite density and can't have arbitrarily large gaps.

Unfortunately, Python doesn't have a short way to produce an infinite counter. I'm sure some language can do for i in Naturals:print("1"*i*i) shorter (squares suffice just as well).

Edit: Can shorten to

s=2
while 1:print s;s*=s

which prints numbers of the form 2**(2**n), which can be taken as strings over 0123456789. Because the decimal length doubles at each step, this can't be context-free because the length gaps cannot satisfy the pumping lemma.


Flag Semaphore Encoder Your goal is to write a flag semaphore encoder, which will convert a given sentence into the corresponding flag semaphore characters, according to the semaphore system described on Wikipedia.

Assume that the input is a single sentence provided through stdin (or equivalent). Your output should be a series of semaphore characters, with each row representing one word from the sentence. You only need to deal with the alphabet (A-Z) and should ignore all other non-space characters, but you must be able to handle both uppercase and lowercase. Your output is allowed to contain extra whitespace.

Semaphore characters must be displayed as a 3x3 square, with an O in the middle and the flag positions represented by the characters | - / \. Each semaphore character must be separated from adjacent characters by a space, and each row must be separated by a blank line. Don't worry about wrapping for words that may be too long for your display - pretend that your lines have infinite length.

Sample input:

abcdefg hijklmn opqrstu vwxyz

Sample output:

        \    |    /
 O  -O   O   O   O   O-  O
/|   |   |   |   |   |   |\

    \    |   |    /
-O   O   O-  O   O   O-  O
/   /       /   /   /   / \

\    |    /         \|  \ /
-O  -O  -O  -O- -O   O   O
                  \

 |    /   / \
 O   O-  O   O-  O-
  \       \       \

Sample input:

This is Code Golf.

Sample output:

\|      \
 O  -O   O  -O
    /   /     \

\
 O  -O
/     \

\   \    |    /
 O  -O   O   O
 |       |   |

    \     /
 O  -O   O   O-
 |\     /    |

Since this is code-golf, the shortest solution wins.

Python, 244 238 233 232

e='abhioptuwycdjmnsqxzfgvklebr'
for w in raw_input().split():
 for i in 0,3,6,9:print' '.join(''.join((' '+'\|/-O-/|\ '[j])[`j`in'4'+'6736031025071568328578162735'[e.find(c):][:2]]for j in range(i,9)[:3])for c in w if c.lower()in e)

This uses a favorite trick of mine: single-track encoding.  I've labeled the semaphore bits (sbits)

\|/     012
- -  -> 3 5
/|\     678

to obtain the following chart of which sbits occur for which letter:

0: ciotuy
1: djkptv
2: elquwx
3: bhopqrs
5: fjmrwyz
6: ahiklmn
7: abcdefg
8: gnsvxz

each letter occurs exactly twice in the chart, since the signalman has two arms.  Then, I view this as a graph on the letters a-z, with edges between letters sharing sbits, with the edges labeled according to the shared sbit.  Ideally, I'd find a Hamilton path through this graph, such that subsequent edges don't have the same label.  No such paths exist... so you'll note that the variable e contains the letter b twice.

With my nearly-Hamilton path e, I construct an array d of sbit labels used in the traversal of e.  Then, to figure out where to put her arms, the signalman need only find the desired letter in the following handy chart

abhioptuwycdjmnsqxzfgvklebr
6736031025071568328578162735

whence her arms go in the position directly below, and below&right of the letter.


Sum of primes between given range Write the shortest code for finding the sum of primes between \$a\$ and \$b\$ (inclusive).
Input

\$a\$ and \$b\$ can be taken from command line or stdin (space seperated)
Assume \$1 \le a \le b \le 10^8\$

Output
Just print the sum with a newline character.
Bonus Points

If the program accepts multiple ranges (print one sum on each line), you get extra points. :)


Cut a silicon wafer into dies When manufacturing chips, circular silicon wafers are cut into dies of needed size:

The goal of this challenge is maximizing the number of whole dies that can be cut from a wafer of a given diameter.

The machine puts the wafer into an angular compartment:

_____________________
|     xxxxxx
|  xxxxxxxxxxxx
| xxxxxxxxxxxxxx
|xxxxxxxxxxxxxxxx
|xxxxxxxxxxxxxxxx
| xxxxxxxxxxxxxx
|  xxxxxxxxxxxx
|     xxxxxx     (this ascii art is meant to be a perfect circle)

It measures a distance dx from the left edge, and makes a vertical cut. Then it makes the needed number of additional vertical cuts, with spacing of the needed width. It makes the horizontal cuts in the same way: first one at a distance dy, and then with spacing of height.

The material remains perfectly still during the cutting: it's not allowed to move some slices of material before making the perpendicular cuts.

The machine has a stepper motor that works at absolute accuracy but can only go integer-sized distances.

Make a program or a subroutine that gets (or reads) the following parameters:

Wafer diameter
Die width
Die height

and outputs (or prints)

dx - horizontal starting position
dy - vertical starting position

such that the number of rectangular dies is maximal.

Some fine points:

If a corner of a die lies exactly on the circumference of the circle, the die is considered usable (rectangular)
No edge cases: you can assume that the wafer's diameter is even; at least one die can be cut out; also make other reasonable assumptions
All sizes are integer numbers of millimeters; maximum wafer diameter is 450

Shortest code wins!

P.S. The code must finish running in a reasonable amount of time, e.g. over a weekend (2 days) - for wafer diameter equal to 300.

P.P.S. If there are several different output values that are optimal, the code must output one of them - no need to output all of them!

Test cases:

Wafer diameter 8, die size 2 x 2 => dx = 0, dy = 1 (6 dies)
Wafer diameter 20, die size 5 x 4 => dx = 1, dy = 2 (10 dies)
Wafer diameter 100, die size 12 x 12 => dx = 9, dy = 3 (41 dies)
Wafer diameter 300, die size 11 x 11 => dx = 7, dy = 7 (540 dies) - a realistic example
Wafer diameter 340, die size 15 x 8 => dx = 5, dy = 2 (700 dies) - a Pythagorean triple
Wafer diameter 300, die size 36 x 24 => dx = 2, dy = 6 (66 dies) - full-frame sensors

Here is a visualization of the last test case:

Python 2.7, 317

Here is my solution. Could be golfed a bit more, I think - but I like the solving better than the golfing. Suggestions are welcome.

I solve it using brute force, iterating over all dx and dy and then counting by column. It all runs pretty fast (<0,05 sec. on my Mac).

Code:

import math as m
def D(d,w,h):
 r=d/2
 s=[0,0,0]
 for dx in range(0,w):
  for dy in range(0,h):
   t=0
   for c in range(1,int(d/w)+1):
    l=r-dx-(c-1)*w
    if l<w/2:
     l-=w
    if abs(l)<=r:
     f=r*m.sin(m.acos(1.0*l/r));t+=int((2.0*f-(dy+m.ceil((r-dy-f)/h)*h+f-r))/h)
   if t>s[0]:
    s=[t,dx,dy]
 return s

A main to test and profile the given cases:

def runTestcases():
    for d,w,h in [[8,2,2],[20,5,4],[100,12,12],[300,11,11],[340,15,8],[300,36,24]]:
        S=D(d,w,h)
        print "Wafer diameter {}, die size {} x {} => dx = {}, dy = {} ({} dies)".format(d,w,h,S[1],S[2],S[0])

def main():
    import cProfile
    cProfile.run("runTestcases()")

if __name__ == "__main__":
    main()

And its output:

Wafer diameter 8, die size 2 x 2 => dx = 0, dy = 1 (6 dies)
Wafer diameter 20, die size 5 x 4 => dx = 1, dy = 2 (10 dies)
Wafer diameter 100, die size 12 x 12 => dx = 0, dy = 8 (41 dies)
Wafer diameter 300, die size 11 x 11 => dx = 7, dy = 7 (540 dies)
Wafer diameter 340, die size 15 x 8 => dx = 5, dy = 2 (700 dies)
Wafer diameter 300, die size 36 x 24 => dx = 2, dy = 6 (66 dies)
         55354 function calls in 0.049 seconds


How do I alias member functions in Python? In Python, one can save bytes by aliasing functions that are used repeatedly. For example:

r=range
a=r(100)
b=r(200)
c=r(300)

However, when the functions are member functions together, I don't know how to alias them in a way that allows chaining. For example:

s='Hello'

// Plain code
s=s.replace('H','J').replace('e','i').replace('l','m').replace('o','y')

// What I am trying to do
q=replace
s=s.q('H','J').q('e','i').q('l','m').q('o','y')

Obviously, what I am trying to do is not valid. And neither is this:

q=s.replace
s=q('H','J') // Replaces the 'H' in 'Hello'
s=q('e','i') // Replaces the 'e' in 'Hello'... and the J is gone.
s=q('l','m')
s=q('o','y')

Is there a another way to alias member functions and chained functions that saves characters?

No problemo! You can alias a method, but you have to know how to use it:

>>> r=str.replace
>>> a='hello'
>>> r(r(r(r(a,'h','j'),'e','i'),'l','m'),'o','y')
'jimmy'

The key is that you have to pass self explicitly, because the alias is a kind of function that takes an extra argument that takes self:

>>> type(r)
<type 'method_descriptor'>


Shortest method to implement the Pythagorean Theorem Who doesn't love the Pythagorean theorem \$a^2+b^2=c^2\$? Write the shortest method you can in any language that takes in value a and b and prints out The hypotenuse of this right triangle is c.  Keep c to only three decimal places.

APL (54)

'The hypotenuse of this right triangle is',3⍕.5*⍨+/⎕*2

Test:

      'The hypotenuse of this right triangle is',3⍕.5*⍨+/⎕*2
⎕:
      9 10
The hypotenuse of this right triangle is 13.454

Explanation:

⎕*2: raise the values in the input to the second power
+/: take the sum
.5*⍨: raise the result to the 0.5th power
3⍕: round to 3 decimal places


Convert radicals to mixed & entire radicals and to real numbers Challenge

The goal of this challenge is to take a radical and convert it to a reduced and entire radical, and a real number. You do not have to convert it to all 3, however, you will get bonus points for converting it to 2 or 3 of them. You will also get bonus points if your code works not just with square roots. How the input works is your choice. You don't have to parse the input so you could just have it as a function. If your unable to output the root symbol (√) then you could output it as sqrt(x) or cuberoot(x). You could also use a superscript (²√) for the index of the radical.

Rules

If you just output one of the 3 options, then you can't just output it without converting it (ie: if the input is √125 then you can't just output √125 back).
The entire radical must have no co-efficient.
The mixed radical must have a coefficient (if there is no coefficient, then it should be 1).
The real number (or result of the radical) should have as many decimals as possible.

Example

Here's an example output for the square root of 125 (√125):

Entire radical: √125
Mixed radical: 5√5
Real number: 11.18033988749895

Scoring

10% off your score for outputting 2 of either an entire radical, mixed radical, or real number.
30% off your score for outputting all 3 (entire radical, mixed radical, and real number).
30% off your score for working with a radical with any index

Winner

The person with the shortest code length wins. Good luck!

C (314)

n,d;main(i){scanf("%d %d",&n,&d);int val[d];for(;pow(i,n)<=d;i++)val[i]=pow(i,n);printf("Entire radical: %drt(%d)\n",n,d);for(i--;i>0;i--)if(d%val[i]==0){printf("Mixed radical: %d*%drt(%d)\n",i,n,d/val[i]);break;}double v,x=1.5,a=d;do{v=(a/pow(x,n-1)-x)/n;x+=v;}while(abs(v)>=1E-9);printf("Real number: %lf\n",x);}

Here it is with whitespace.

n,d;
main(i){
    scanf("%d %d",&n,&d);
    int val[d];

    for(;pow(i,n)<=d;i++)
        val[i]=pow(i,n);

    printf("Entire Radical: %d*rt(%d)\n",n,d);

    for (i--;i>0;i--)
        if (d%val[i]==0){
            printf("Mixed Radical: %d*%drt(%d)\n", i, n, d/val[i]);
            break;}

    double v,x=1.5,a=d;
    do{
        v=(a/pow(x,n-1)-x)/n;
        x+=v;
    }while(abs(v)>=1E-9);

    printf("Real number: %lf\n", x);
}

Input:

2 125

Output:

Entire radical: 2rt(125)
Mixed radical: 5*2rt(5)
Real number: 11.180340

Input:

3 125

Output:

Entire radical: 3rt(125)
Mixed radical: 5*3rt(1)
Real number: 5.000000

This isn't perfect, the root calculation will not work for all input values, and the chosen guess value is not random. It takes the whole value of the radical as input (see above).


Pitch dark (Earth Hour remembrance) Your goal is simple: the program must turn the screen of your computer totally black.

After the program is started, the screen must quickly turn completely black, and remain so until the program is exited (any key, or alt+F4, mouse movement, etc.), after which things should turn back to normal. So shutting down the computer or turning the power of the monitor off is NOT allowed.
Not a single non-black pixel should be visible during this time, not even a blinking cursor.

The user should not do any preparation (moving the mouse outside the screen, disconnecting cables, etc. or user input after the program started), just start the program.

You can safely assume the computer has only one monitor attached. We also assume a standard desktop or notebook computer, because doing it on a specific device without a normal monitor would be too simple.

If you use any external resources (a black image, a GUI file, etc.) their size in bytes is added to your code size.

It's OK if it only works on one OS family, or if it requires opengl etc., but requiring a very specific hardware configuration is frowned upon.

Your source code must be written in a programming language, not just a configuration file some other program (like a screen saver) will use.

Assembly (bootloader) 131 chars / 512 bytes compiled (actually smaller, but bootsector must be 512 bytes long.)

It is a simple boot loader. When computer starts, BIOS will load it from disk (floppy). Then it enters into graphics mode and just hangs. When user presses the power button, program will end and computer will enter to mode where is was before running program.

Tested with VirtualBox.

It will compile with nasm:

nasm -f bin file.asm -o start.img

Source code:

[BITS 16]
[ORG 0x7C00]
cli
mov AX,0x0
mov SS,AX
mov SP,0x9000
sti
mov AH,0x0
mov AL,0x13
int 0x10
times 510 - ($-$$) db 0
dw 0xAA55


Is it a stochastic matrix? A stochastic matrix is a matrix of probabilities used in the context of Markov chains.

A right stochastic matrix is a matrix where each row sums to 1.

A left stochastic matrix is a matrix where each column sums to 1.

A doubly stochastic matrix is a matrix where each row and each column sums to 1.

In this challenge, we will represent the probabilities in percent using integers. A row or column must in that case sum to 100 and not 1.

Your goal is to write a program or function which, given a square matrix of integers as input, outputs one of four values indicating that the matrix is either right stochastic, left stochastic, doubly stochastic or none of those.

Input

You may use any proper representation of a matrix that is natural for your language for the input. For example, a list of lists, a string of comma separated values with rows separated by linebreaks, etc.

The input matrix will always be square and will only contain non-negative integers. The input matrix will always be at least 1×1.

You may pass the input using STDIN, as a function argument, or anything similar.

Output

You must choose four distinct outputs that correspond to right stochastic, left stochastic, doubly stochastic or none of those. Those outputs must be constant regardless of what input is passed. Your program may not return different outputs for the same case, e.g. saying that any negative number corresponds to none of those is not valid.

In short, there must be a 1-to-1 correspondence between your output an the four possible cases. Some examples of those four outputs would be {1, 2, 3, 4} or {[1,0], [0,1], [1,1], [0,0]} or even {right, left, doubly, none}.

Please indicate in your answer the four outputs your program uses.

If a matrix is doubly stochastic, then you must return the output corresponding to doubly stochastic, and not right or left stochastic.

You may print the output to STDOUT, return it from a function, or anything similar.

Test cases

[100]               => Doubly stochastic

[42]                => None of those

[100  0  ]          => Doubly stochastic
[0    100]

[4   8   15]
[16  23  42]        => Left stochastic
[80  69  43]

[99  1 ]            => Right stochastic
[2   98]

[1   2   3   4 ]
[5   6   7   8 ]    => None of those
[9   10  11  12]
[13  14  15  16]

Scoring

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

Haskell, 57 55 bytes

import Data.List
s a=all((==100).sum)<$>[transpose a,a]

Input of type (Eq a, Num a) => [[a]]. Outputs boolean list [left-stochastic, right-stochastic]

Thanks to @proudhaskeller for saving 2 bytes


Strip all non-printable ASCII characters Your challenge, should you be coded to accept it, runs as follows:

You may choose one of the following two challenges to implement:

Challenge #1

Read from a file a.txt
Write only printable ASCII characters (values 32-126) to a file b.txt

Challenge #2

With a file a.txt, delete all characters in the file except printable ASCII characters (values 32-126)

Specs on a.txt

a.txt is a plain text file which can include any ASCII values from 0-255 (even undefined/control) and its size can range up to 1 GB.

Winning

The answer with the smallest amount of sourcecode in bytes wins.

sh

Challenge 1, 24 23 chars

tr -dc \ -~<a.txt>b.txt

Bonus: variations on the set of characters to delete.

tr -dc " -~
"<a.txt>b.txt                       # preserves printables + line feed

tr -dc "[:space:] -~"<a.txt>b.txt   # preserves printables + whitespace


Create an Alphabet Song Your goal is to create an alphabet song as text in the following form (in order):

A is for <word starting with A>
B is for <word starting with B>
C is for <word starting with C>
...
Z is for <word starting with Z>

Example output:

A is for Apple
B is for Banana
C is for Carrot
D is for Door
E is for Elephant
F is for Frog
G is for Goat
H is for Hat
I is for Icicle
J is for Jelly
K is for Kangaroo
L is for Lovely
M is for Mom
N is for Never
O is for Open
P is for Paste
Q is for Queen
R is for Rice
S is for Star
T is for Test
U is for Underneath
V is for Very
W is for Water
X is for X-ray
Y is for Yellow
Z is for Zipper

Rules:

Each "letter" of the song has its own line, so there are 26 lines, and a possible trailing linefeed.
The output is case-sensitive:

The letter at the start of each line must be capitalized.
is for is lowercase.
The chosen word does not need to be capitalized, but may be. All lines should be consistent.

The chosen word for each line is up to you, but must be a valid English word with at least 3 letters, and it cannot be a conjunction (like and or but), interjection/exclamation (like hey or yay), abbreviation (like XLS), or a name (like Jon).
Though I doubt anyone would find it shorter, I'd find it acceptable to use a phrase instead of a single word. So if for some reason S is for Something smells fishy... is shorter, go for it.
Put your program's output in your answer, or at least the list of words you used (if there's a link to run your code online, we don't need to see the entire output).
Shortest code wins

This challenge was inspired by this video.

Bash (+coreutils), 81, 87, 82, 78 bytes
Uses the man page for X, as the source of words.
Golfed
man xyst\  x|&grep -Po '\b[a-z]{4,} '|sed 's/\(.\)/\u\1 is for &/'|sort -uk1,1

EDITS

Used a non-existing 'xyst' man page + |& to save 5 bytes;
Saved 4 more bytes, by swapping sed and sort.

Test
%man xyst\  x|&grep -Po '\b[a-z]{4,} '|sed 's/\(.\)/\u\1 is for &/'|sort -uk1,1

A is for also
B is for build
C is for computing
D is for distribution
E is for entry
F is for following
G is for graphics
H is for hierarchical
I is for implementations
J is for just
K is for keyboard
L is for listing
M is for manual
N is for network
O is for output
P is for programs
Q is for quite
R is for runs
S is for system
T is for transparent
U is for used
V is for various
W is for window
X is for xyst
Y is for your
Z is for zeros


Quadratic residues are so much fun! Definitions
Quadratic residues
An integer \$r\$ is called a quadratic residue modulo \$n\$ if there exists an integer \$x\$ such that:
$$x^2\equiv r \pmod n$$
The set of quadratic residues modulo \$n\$ can be simply computed by looking at the results of \$x^2 \bmod n\$ for \$0 \le x \le \lfloor n/2\rfloor\$.
The challenge sequence
We define \$a_n\$ as the minimum number of occurrences of the same value \$(r_0-r_1+n) \bmod n\$ for all pairs \$(r_0,r_1)\$ of quadratic residues modulo \$n\$.
The first 30 terms are:
$$1, 2, 1, 1, 1, 2, 2, 1, 1, 2, 3, 1, 3, 4, 1, 1, 4, 2, 5, 1, 2, 6, 6, 1, 2, 6, 2, 2, 7, 2$$
This is A316975 (submitted by myself).
Example: \$n=10\$
The quadratic residues modulo \$10\$ are \$0\$, \$1\$, \$4\$, \$5\$, \$6\$ and \$9\$.
For each pair \$(r_0,r_1)\$ of these quadratic residues, we compute \$(r_0-r_1+10) \bmod 10\$, which leads to the following table (where \$r_0\$ is on the left and \$r_1\$ is on the top):
$$\begin{array}{c|cccccc}
& 0 & 1 & 4 & 5 & 6 & 9\\
\hline
0 & 0 & 9 & 6 & 5 & 4 & 1\\
1 & 1 & 0 & \color{blue}7 & 6 & 5 & \color{green}2\\
4 & 4 & \color{magenta}3 & 0 & 9 & \color{red}8 & 5\\
5 & 5 & 4 & 1 & 0 & 9 & 6\\
6 & 6 & 5 & \color{green}2 & 1 & 0 & \color{blue}7\\
9 & 9 & \color{red}8 & 5 & 4 & \color{magenta}3 & 0
\end{array}$$
The minimum number of occurrences of the same value in the above table is \$2\$ (for \$\color{green}2\$, \$\color{magenta}3\$, \$\color{blue}7\$ and \$\color{red}8\$). Therefore \$a_{10}=2\$.
Your task

You may either:

take an integer \$n\$ and print or return \$a_n\$ (either 0-indexed or 1-indexed)
take an integer \$n\$ and print or return the \$n\$ first terms of the sequence
take no input and print the sequence forever

Your code must be able to process any of the 50 first values of the
sequence in less than 1 minute.

Given enough time and memory, your code must theoretically work for any positive integer supported by your language.

This is code-golf.

MATL, 14 bytes

:UG\u&-G\8#uX<

Try it online! Or verify the first 30 values.

Explanation

:      % Implicit input. Range
U      % Square, element-wise
G      % Push input again
\      % Modulo, element-wise
u      % Unique elements
&-     % Table of pair-wise differences
G      % Push input
\      % Modulo, element-wise
8#u    % Number of occurrences of each element
X<     % Minimum. Implicit display


When integers join the queue Introduction
A queue is an abstract data type where elements are added to the front (enqueue) and removed from the back (dequeue). This is also known as the FIFO (First In First Out) principle.
It is best shown with an example:

Challenge
Given a non-empty array that contains positive integers and elements that indicate a dequeue (removing an element), output the final list of the queue.
Let's say that X denotes a dequeue in this example. Let's take a look at the following list:
[45, X, X, 37, 20, X, 97, X, 85]

This can be translated to the following queue-pseudo code:
                   Queue
Enqueue 45    ->   45
Dequeue       ->
Dequeue       ->              (dequeue on an empty queue is a no-op)
Enqueue 37    ->   37
Enqueue 20    ->   20 37
Dequeue       ->   20
Enqueue 97    ->   97 20
Dequeue       ->   97
Enqueue 85    ->   85 97

You can see that in the end, the result is [85, 97], which is the output for this sequence.

Test cases
Note that you may choose any other symbol or character for X, as long as it's not a positive integer.
[1, X, 2, X, 3, X]      ->     []
[1, 2, X]               ->     [2]
[1, 2, 3]               ->     [3, 2, 1]
[1, 2, X, X, X, 3]      ->     [3]
[1, 2, X, 3, X, 4]      ->     [4, 3]

This is code-golf, so the submission with the least amount of bytes wins!

Python 2, 56 53 50 bytes

q=[]
for i in input():q=[[i]+q,q[:i]][i<0]
print q

Try it Online!

Dequeue is -1. This trick allows easy pythonic slicing of the queue.


Tips for Golfing in Brain-Flak Brain-flak is a stack-based turing-tarpit language, written collaboratively between me, DJMcMayhem, and 1000000000.

Some users  are very experienced in the mysterious ways of Brain-Flak. So I thought it a good idea to set up this question as a way for us, and hopefully others too, to share our knowledge with the community and lower the bar of entry to this language "designed to be painful to use". And perhaps even teach those of us with more experience some new tricks.

So what tips do you have for golfing in brain-flak? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to brain-flak (e.g. "remove comments" is not an answer).

Please post one tip per answer.

Use the Third Stack
If you have read the title you might be a bit confused.  Surely there are only two stacks in Brain-Flak?  However I assure you that it exists and it is one of the most powerful if not the most powerful tool in writing and golfing Brain-Flak.

What is the "Third Stack"?
Every Brain-Flak program uses the third stack in one way or another but most of the use goes on behind the scenes and it is often useful to simply ignore the fact that it exists.  Each parenthesis in the program either adds or removes one item from the stack.  Three of the open braces ([< all add an item to the stack while their three conjugates )]> all remove an item from the stack.  The value of the item on the stack is the value of the current scope of the program and using nilads will modify this value in certain ways.  The close parenthesis ) has the unique function of moving an element from the Third Stack to the current stack; a push.
Hopefully this is becoming clear to you.  The Third Stack is some sort of stack that remembers the return values of code that has already been executed.  Let's walk through an example of a simple program keeping track of the two normal stacks and the Third Stack.
Example
We will walk through the following program.  This program pushes -3, 1, -2 to the stack.
(([()()()])(()))

We start with three open braces, which all push a zero to the third stack.
Our stacks now look like this, the Third Stack is the one on the right and the active stack has a ^ under it:
        0
        0
  0  0  0
  ^

(([()()()])(()))
   ^

Now we have three () nilads.  These do not do anything to the normal two stacks, however they do each add one to the top of the Third Stack making our stacks look like:
        3
        0
  0  0  0
  ^

(([()()()])(()))
         ^

Now we encounter a ] as stated before close braces remove an item from the Third Stack, but ] has the function of subtracting the element it removes from the top of the stack.  Thus our new stacks will look like:
       -3
  0  0  0
  ^

(([()()()])(()))
          ^

This makes sense; [...] does negation so ] should subtract downwards.
Now we must execute a ).  As you likely recall ) is the place in the program where stuff gets pushed to the stack so we will be moving the top of the Third Stack to the current stack, in addition we will be adding the -3 to the next element in the third stack.
 -3  0 -3
  ^

(([()()()])(()))
           ^

Once again we encounter one of our three open braces so we will add another element to our Third Stack.
        0
 -3  0 -3
  ^

(([()()()])(()))
            ^

As we said earlier () will increment the top of our third stack by one.
        1
 -3  0 -3
  ^

(([()()()])(()))
              ^

And ) will move the top of the Third Stack onto the active stack and add downwards
  1
 -3  0 -2
  ^

(([()()()])(()))
               ^

The last ) moves the Third Stack onto the active stack and since there are no elements left on the Third Stack for it to add, does nothing else.
 -2
  1
 -3  0
  ^

(([()()()])(()))
                ^

The program is over so we terminate and output.

This example is intended to give you a feel for what the Third Stack is and does.  It does not include all of the operations, but hopefully you can figure out what each of them does on its own.  If you are still struggling I have included a "cheatsheet" at the bottom of this answer to help you along.
Ok, So what?
Ok, now you understand the Third Stack, but "So what"?  You were already using it even if you didn't call it the "Third Stack", how does thinking in terms of the Third Stack help you golf?
Lets look at a problem.  You want to take the Triangle of a number.  This is the sum of all numbers less than n.
One approach might be to create an accumulator on the offstack and add to it as you count down.  This creates code that looks like this:
(<>)<>{(({}[()])()<>{})<>}{}<>({}<>)

Try it Online!
This code is pretty compact and one might think that it can't get much smaller.  However if we approach it from a third stack point of view it become clear that this is grossly inefficient.  Instead of putting our accumulator on the offstack we can put it on the third stack with a ( and retrieve it at the end we use ).  We will once again loop through all the numbers, but this time we don't have to do much of anything to increment our Third Stack, the program does it for us.  This looks like:
({()({}[()])}{})

Try it Online
This code is less than half the size of the pretty well golfed version we made before.  In fact a computer search has proven that this program is the shortest possible program that can perform this task.  This program can be explained using the "sum of all runs" approach, but I think it is a lot more intuitive and clear when explained using a Third Stack approach.
When do I use the Third Stack?
Ideally whenever you begin work on a new problem in Brain-Flak you should think to yourself how would I do this with the Third Stack in mind.  However as a general rule of thumb whenever you have to keep track of some type of accumulator or have a running total it is a good idea to try putting that on your third stack instead of the two real stacks.
Another time that it might be a good idea to consider using your third stack is when you don't have any space to store some value on the other two stacks.  This can be particularly useful when you are doing manipulations on two existing stacks and you want to save a value for later use without having to keep track of where it is.
Limitations of the Third Stack
The Third Stack is very powerful in a lot of ways but it comes with its own limitations and drawbacks.
Firstly, the maximum stack height for the Third Stack at any given point is determined at compile time.  This means that if you want to use an amount of space on the stack you have to allocate that space when you are writing the program.
Secondly the Third Stack is not Random Access.  This means that you cannot perform any operations on any value but the top most value.  In addition you cannot move values around on the stack (say swap the first two elements).
Conclusion
The Third Stack is a powerful tool and I would consider it essential to every Brain-Flak user.  It takes some getting used to and requires a shift in the way your think about programming in Brain-Flak, but when used properly it makes all the difference between a decent and an amazing when it comes to golfing.
Cheatsheet
Here is a list of operations and how they affect the Third Stack
 Operation  |                 Action
====================================================
   (,[,<    | Put a zero on top of the Third Stack
----------------------------------------------------
     )      | Add the top of the Third Stack to the
            | second element and move it to the
            | active stack
----------------------------------------------------
     ]      | Subtract the top of the Third Stack
            | from the second element and pop it
----------------------------------------------------
     >      | Pop the top of the Third Stack
----------------------------------------------------
     ()     | Add one to the top of the Third Stack
----------------------------------------------------
     {}     | Pop the top of the active stack and
            | add it to the top of the Third Stack
----------------------------------------------------
     []     | Add the stack height to the Third
            | Stack
----------------------------------------------------
   <>,{,}   | Nothing


Find an Illegal String The challenge is to find a string of characters that cannot appear in any legal program in your programming language of choice. That includes comments, strings, or other "non-executable" parts.

Challenge

Your program may be specific to a particular version or implementation of your language's compiler/interpreter/runtime environment. If so, please specify the particulars.
Only standard compiler/interpreter/runtime options are permitted. You cannot pass some weird flag to your compiler to get a specific result (e.g. passing a flag to convert warnings into errors).
If your programming language requires a specific encoding (e.g. UTF-8), your string must also be correctly encoded (i.e. strings which fail solely due to character decoding errors are not allowed).
Every individual character in your submission must be admissible in a legal program; that is, you can't just use a character which is always rejected.
The compiler/interpreter/runtime must give an error when given any source code that contains your string as a substring. The error does not have to be the same across programs - one embedding of your string might cause a syntax error, while another might cause a runtime error.

Scoring

Shortest illegal string for each language wins.
You should explain why your string is illegal (why it cannot appear anywhere in a legal program).
Dispute incorrect solutions in the comments. More specifically, you should provide a link to TIO or equivalent demonstrating a legal program (i.e. one that doesn't produce any errors) that contains the proposed substring.
Some languages (e.g. Bash, Batch, Perl) allow arbitrary binary data to be appended to a program without affecting validity (e.g. using __DATA__ in Perl). For such languages, you may submit a solution that can appear only in such a trailing section. Make sure to make a note of that in your answer. (The definition of this "trailing section" is language-dependent, but generally means any text after the parser has entirely stopped reading the script).

Example

In Python, I might submit

x
"""
'''

but this can be embedded into the larger program

"""
x
"""
'''
y
'''

so it isn't admissible.

Changeling, 2 bytes

That's two linefeeds. Valid Changeling must always form a perfect square of printable ASCII characters, so it cannot contain two linefeeds in a row.

The error is always a parser error and always the same:

This shape is unpleasant.

accompanied by exit code 1.

Try it online!


Unique Array Combinations The goal is to write a function or program which takes a set of integer arrays and returns a set of all possible arrays which meet the following criteria:

A valid array must contain at least one number from each of the input arrays.
A valid array cannot contain more than one number from a single input array.
A valid array cannot contain duplicate values.

Additional rules:

Order of the output does not matter.
Input/Output can be in any format you wish.
If no valid arrays exist, the result should be an empty array or blank string.

Examples:

input:
[[1,2],
 [2,1,0],
 [0,3,1]]

output:
[[2,3],
 [1]]

input:
[[1,3,4,7],
 [1,2,5,6],
 [3,4,8],
 [8,9]]

output:
[[6,7,8],
 [5,7,8],
 [2,7,8],
 [4,6,9],
 [4,5,9],
 [2,4,9],
 [3,6,9],
 [3,5,9],
 [2,3,9],
 [1,8]]

input:
[[1,2,3],
 [2,3,4],
 [1,4]]

output:
[]

GolfScript, 36 characters
:I[[]]\{{{|$}+1$/}%|}/{I{1$&,(},!*},

Input/output is standard GolfScript arrays, see in this example.
:I              # save input to variable I

# part 1: generate all possible sets with zero or one numbers from each array
# (zero or one is one char shorter than exactly one which would work also)
[[]]\           # push the set with an empty set
{               # iterate over all input sets
  {             #   iterate over the numbers in the current set
    {|$}+1$/    #     add this number to any set in the result
  }%
  |             #   join with the result set
}/

# part 2: filter for valid sets (i.e. exactly one number from each array)
{               # start of filter block
  I{            #   filter the input array of sets
    1$&         #     calculate overlap of the current set with the input set
    ,(          #     remove if length is equal to one
  },
  !             #   is the list empty? (i.e. all input matched the filter criterion)
  *             #   get rid of the second item on the stack
},              # end of filter block


Compose two Brainfuck programs Given 2 brainfuck code snippets A and B, output some brainfuck code C which has the same behavior as running B with the input of As result. Note that C must work for any input that match the following assumptions, as if it were given to A.

You can assume:

Finite input.
both A and B halt.
EOF is consistently 0 or consistently -1.
Consistently allow or disallow cells to left
Unbounded tape (otherwise the requirement may be impossible)
Consistently 8-bit wrapping or unbounded integer
No stream(input or output for A or B) contain the byte representing EOF
Code A and B can contain characters that possibly appear in your C, and +-[]<>,.

E.g. (EOF=0)

A = ,[..,]
B = ,[...,]
C = ,[......,]

A = >,[>,]<[.<]
B = ,[...,]
C = >>>>,[[-<+<+<+>>>]>>>,]<<<<[.<]

A = >,[>,]<[.<]
B = ,[...,]
C = >,[>,]<[...<]

A = ,.
B = ,.
C = ,>,[,]<.

A = ,.
B = ,.
C = ,.

are valid tests

Shortest code in each language win. Winner in Brainfuck will be accepted.


Calculate gravity on a 1D field Given a string or list, calculate the effects of gravity on that string/list.

The string will be made of 5 characters:

N has a weight of 2
L has a weight of 1
S has a weight of -2
D has a weight of -1

(the 5th character is whatever you want, it means empty space. I use  (space) in my examples)

Items with negative weight fall upwards (towards the top of the string), and items with positive weight fall downwards (towards the bottom of the string).

When an object collides with something, one of three things happens:

If the object collides with the top or bottom "walls" of the input, then it just stops.
If the object collides with another object, their weight/velocity is summed (i.e. N and D would give 1). If the result is positive, both objects fall downwards. If it's negative, they fall upwards.
If an object  (let's call it A) collides with an object B, and B is already pinned against the ceiling/floor, A will just come to rest against B.

All non-occupied spaces of the string/list should be filled with the empty character.

If it wasn't clear already: each character in the string/line is on top of the next one.  i.e. NL is the same as:

N
L

And  SD is:

(blank)
S
D

Test cases: (uses  (the space character) to show empty space)

" L D " -> " LD  " or "  LD "

" SDLN " -> "SD  LN"

" NLLSSD " -> "NLLSSD  "

Haskell, 169 180 bytes

g s=sum[n|c<-s,(d,n)<-zip"SD LN"[-2..],c==d]
w=elem ' '
h(x:y:r)|(w x&&g y<0)||(w y&&g x>0)=y:h(x:r)|w(x++y)||g x<0=x:h(y:r)|t<-x++y=h$t:r
h r=r
concat.until((==)=<<h)h.map(:[])

Try it online!
 Example usage: concat.until((==)=<<h)h.map(:[]) $ " SDLN ".

Edit: +11 bytes, now also works for the "  NSDLLD  " test case proposed by @zgrep.

(short) Explanation:

h works on a list of tokens where initially each char of the input string is token. Until the token list no longer changes, h bubbles through the list comparing two tokens x and y at a time. Depending on the tokens their order is kept (x:h(y:r)), they are swapped (y:h(x:r)) or combined to a single token (t<-x++y=h$t:r).

g computes the weight of a token and w checks whether a token contains a space.


Write an aphorism using valid code Can you write an aphorism in at most 4 lines of code ?

Code should read as much as possible as an aphorism in plain English and should return the boolean true.

Language: of choice.

Criteria for accepted answer: Most votes in 180 30 days. (8th of July 2014)

Originality: can be an old aphorism but a creative one would be much more appreciated.

Python
import this
love = this
this is love, love is not True or False, love is love
# (True, True, True)

Okay, this returns a tuple of Truths, but that itself evaluates as True anyway.


The "Do While False" idiom Do While False

At work today one of my colleagues was describing the use-case for do while(false). The person he was talking to thought that
this was silly and that simple if statements would be much better. We then proceeded to waste half of our day discussing the best
manner to write something equivalent to:

do
{
   //some code that should always execute...

   if ( condition )
   {
      //do some stuff
      break;
   }

   //some code that should execute if condition is not true

   if ( condition2 )
   {
       //do some more stuff
       break;
   }

   //further code that should not execute if condition or condition2 are true

}
while(false);

This is an idiom which is found in c quite often.
Your program should produce the same output as the below pseudo-code depending on the conditions.

do
{
   result += "A";

   if ( C1)
   {
      result += "B";
      break;
   }

   result += "C"

   if ( C2 )
   {
       result += "D";
       break;
   }

   result += "E";

}
while(false);

print(result);

Therefore the input could be:

1. C1 = true, C2 = true
2. C1 = true, C2 = false
3. C1 = false, C2 = true
4. C1 = false, C2 = false

and the output should be:

1. "AB"
2. "AB"
3. "ACD"
4. "ACE"

This is code-golf so answers will be judged on bytes.
Standard loopholes are banned.

Yes this is a simple one, but hopefully we will see some creative answers, I'm hoping the simplicity will encourage people to use languages they are less confident with.

Python 3, 31
Saved 1 byte thanks to xnor.
Only one byte away from ES6. :/ Stupid Python and its long anonymous function syntax.
Hooray for one liners!
lambda x,y:x*"AB"or"AC"+"ED"[y]

Test cases:
assert f(1, 1) == "AB"
assert f(1, 0) == "AB"
assert f(0, 1) == "ACD"
assert f(0, 0) == "ACE"


Chiral three dimensional texts Two dimensional chiral objects are not chiral in three dimensional space. This is because you can flip them over which is equivalent to taking the mirror image unlike in two dimensions where only rotations in the plane of the object are allowed which cannot reproduce the effect of a mirror operation. In this challenge, we will be deciding whether three dimensional texts are chiral.

Some definitions

Three dimensional text: A rectangular three dimensional array of characters. In this challenge, programs will only need to handle nonwhitespace printable ASCII (! through ~).
Mirror operation: The operation of reversing the order of characters along a single axis of the three dimensional text.

Rotations can be thought of intuitively, but here is an explicit definition for those who will eventually ask.

90-degree rotation: The operation of transposing each plane perpendicular to a specific axis (say \$i\$), then applying a mirror operation to an axis other than \$i\$.
Rotation: A succession of 90-degree rotations.
Chiral: A three dimensional text is chiral if after applying any single mirror operation, there does not exist a rotation of the new text that reproduces the original text. A text is not chiral if after applying a single mirror operation the new text can be rotated back to the original text.

A slightly more concise definition of chirality is lack of existence of an improper rotation under which an object is invariant.

Task

In whatever format you prefer, take a three dimensional text as input.

Output one of two consistent values, one indicating that the text is chiral and one indicating that it is not.

Shortest code wins.

Examples

In each section, the vertical pipes (|) separate the test cases. Within each test case, layers of the three dimensional texts are separated by blank lines.

Not chiral

Z--Z    |    i~    |    Qx    |    a    |    abaLIa
----    |    >>    |    xx    |    b    |    N#)*@"
Z--Z    |          |          |         |    }-3}#k
        |    >>    |    QQ    |    d    |    ../..'
Z--Z    |    ~i    |    QQ    |    e    |
----    |          |          |         |
Z--Z    |          |          |    f    |
        |          |          |    g    |

Chiral

Z--Z    |    *k    |    Qxxx    |    a*
----    |    <0    |    xxxx    |    **
Z---    |          |            |
        |    l7    |    QQQQ    |    **
Z---    |    GB    |    QQQQ    |    a*
----    |          |            |
Z--Z    |    q~    |            |    **
        |    ]J    |            |    *a

Haskell, 97 96 95 bytes

-1 byte thanks to nimi

f s=all(r s/=)$foldr($)s<$>mapM(\_->[id,g,map g])[1..6]
g=r.foldr(zipWith(:))e
r=reverse
e=[]:e

Try it online!

Explanation

Ok, this is a bit mathy. It is well known that the group of rotations as described in the challenge (i.e. the group generated by rotations of 90 degrees around one of the three principal axes) is isomorphic to the symmetric group \$S_4\$, as described here. It is also well known that \$S_4\$ is generated by the elements \$(1\, 2\, 3\, 4),(1\, 3\, 2\, 4)\$.

What I am trying to say is this: fix two distinct axes, and call the 90 degrees rotations about those axes \$r_1\$ and \$r_2\$. Then we can generate all the rotations by repeatedly applying \$r_1\$ and \$r_2\$. A bit of bruteforce shows that we only need up to 6 applications of \$r_1\$ and \$r_2\$.

Thus we have the following algorithm: given a three-dimensional text \$s\$, we apply all possible rotations to \$s\$ and check whether any of those matches \$s\$ flipped along an axis. The rotations are generated by composing up to six 90 degrees rotations about two fixed axes.

g=r.foldr(zipWith(:))e
e=[]:e

g is a 90 degrees rotation of a 2D list (also works on 3D lists, as those can be seen as 2D lists of 1D lists). The foldr(zipWith(:))e is simply transpose from Data.List, but shorter.

f s=all(r s/=)$foldr($)s<$>mapM(\_->[id,g,map g])[1..6]

f checks whether its argument s is chiral.

mapM(\_->[id,g,map g])[1..6] generates a list of all sequences of length 6 whose elements are any of id (the identity transformation, i.e. do nothing), g (90 degrees rotation about an axis), map g (90 degrees rotations about a different axis).
given a list [f1,f2,...,f6] of transformations, foldr($)s computes f1(f2(...f6(s)...), and (r s/=) checks whether the result is equal to s reversed (i.e. a mirror image of s).

So what f does is check if any rotation of s matches its mirror image, returning False if it does and True otherwise.


Making Future Posts Runnable Online with Stack Snippets Stack Snippets were recently added to PPCG! Reminiscent of JSFiddle, Stack Snippets allow HTML, CSS, and JavaScript to be run directly in posts!
Here is a very simple Stack Snippet:

alert('This is JavaScript')
h3 { color: red } /* This is CSS */

This is HTML

This feature of Stack Exchange would be very useful for us if languages besides JavaScript were supported. (The answers to challenges could be tested on the spot, example inputs could be generated dynamically, etc.) This is where you come in.
Challenge
The goal of this challenge is to write an interpreter for some programming language using Stack Snippets and JavaScript. The point is to make something that can be easily copied and used in future PPCG questions and answers.
More or less, you need to create a Stack Snippet that has a "run" button and two textboxes, one for code and one for input. Clicking the run button will execute the code (written in the language you're interpreting) on the input and display the result (probably in another textbox). The snippet should be something akin to cjam.aditsu.net or the sample answer.
For most languages it would make sense for the input and output to represent stdin and sdout respectively, and you might have another input box for the command line. But not all languages have have such traditional I/O mechanisms. HQ9+, for example, doesn't even have input, making a textbox for it pointless. So feel free to take some liberties, design around the language, not this spec. The main requirement is that your language be "runnable" in a Stack Snippet in the accepted sense of the term.
Notes

Implementing every single feature of your language, though ideal, is not required. Some things like reading and writing files or importing libraries may be unwieldy or impossible. Focus on making an interpreter that maximizes utility for use on this site.
Posting a "language X to JavaScript" interpreter that you didn't write is ok (with attribution).
Stack Exchange limits answers to 30,000 characters, so plan accordingly if your interpreter is likely to be long.
It is best that you make a version of your interpreter as easy as possible to include in future posts. For example, in the sample answer, the raw Markdown for the entire snippet is provided, with obvious places to put code and input.

Although this question is intended to be more a compendium of interpreters than a proper challenge, it is still a popularity-contest, so the highest voted answer wins.
List of Current Interpreters
(sorted alphabetically by language name)

Beam
Befunge-93
Brainfuck
Brainfuck
CHIQRSX9+
Deadfish
Deadfish (only runs preset code)
Fourier
FRACTRAN
Hello++
HQ9+
Insomnia
Japt
JavaScript (sample answer)
JavaScript ES2015
Marbelous
Neoscript
oOo CODE
Ouroboros
Prelude
Python 2
STATA
TI-Basic
Unary (translates to BF)

(This question might be better suited for Meta but it will be more visible here. People might actually produce very useful interpreters, I think they deserve the rep for it.)

Python 2 (No STDIN)
Thanks to Skulpt, it has become very easy to write a Python interpreter.

function out(text) {
  var output = document.getElementById("output");
  output.innerHTML = output.innerHTML + text;
}

function builtinRead(x) {
  if(Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
    throw "File not found: '" + x + "'";
  return Sk.builtinFiles["files"][x];
}

function run() {
  var program = document.getElementById("python-in").value;
  var output = document.getElementById("output");

  output.innerHTML = "";

  Sk.canvas = "canvas";
  Sk.pre = "output";

  Sk.configure({
    output: out,
    read: builtinRead
  });

  try {
    Sk.importMainWithBody("<stdin>", false, program);
  }
  catch(e) {
    throw new Error(e.toString());
  }
}
#python-in {
  border-radius: 3px;
  background: rgb(250, 250, 250);
  width: 95%;
  height: 200px;
}

#output {
  border-radius: 3px;
  background: lightgray;
  width: 95%;
  height: 200px;
  overflow: auto;
}

#canvas {
  border: 1px solid gray;
  border-radius: 3px;
  height: 400px;
  width: 400px;
}

Python code:

<textarea id="python-in" name="python-in" rows="10" cols="80"></textarea>

<button id="run-code" onclick="run()">Run</button>

Output:

Canvas for turtles:

<canvas height="400" width="400" id="canvas">Your browser does not support HTML5 Canvas!</canvas>

No STDIN, but it's a pretty complete implementation of Python in JS. I would load the libraries from somewhere else but I can't find a host of them.


Electrons bouncing in a wire Imagine a "wire" that has n spaces. Imagine further that there are "electrons" in that wire. These electrons only live for one unit of time. Any spaces in the wire that are adjacent to exactly one electron become an electron. In Game of Life terminology, this is B1/S.
For example, this is a wire of length 10, with period 62.

Rules

Input, n, is a single, positive integer.
Output must be a single integer denoting the period of a wire of length n.
The starting state is a single electron at one end of the wire.
The period does not necessarily include the starting state. Some lengths never return to the starting state, but all of them are periodic.
A static wire (i.e., one without electrons) has period 1.
Boundary conditions are not periodic. That is, the wire is not toroidal in any way.

Test cases
Special thanks to orlp for producing this list. (I have verified it up to n=27.)
1 1
2 2
3 1
4 6
5 4
6 14
7 1
8 14
9 12
10 62
11 8
12 126
13 28
14 30
15 1
16 30
17 28
18 1022
19 24
20 126
21 124
22 4094
23 16
24 2046
25 252
26 1022
27 56
28 32766
29 60
30 62
31 1
32 62
33 60
34 8190
35 56
36 174762
37 2044
38 8190
39 48
40 2046
41 252
42 254
43 248
44 8190
45 8188

You can see test cases for n=2 through 21 here with my Game-of-Life-esque simulator: Variations of Life.

EDIT: the sequence here has been published as A268754!

Python 2, 148 142 87 bytes
n=input()
p=l=1
t=1
h=2
while t!=h:
 if p==l:t,l,p=h,0,p*2
 h=h/2^h*2%2**n;l+=1
print l

Uses Brent's cycle detection algorithm, and thus actually runs fast.

I have also written an animation in Python (both 2 & 3 work). It needs pyglet to run. You can view the animation by running:
python -m pip install --user pyglet
curl -s https://gist.githubusercontent.com/orlp/f32d158130259cbae0b0/raw/ | python

(Feel free to download the gist and inspect the code before running.) You can press the + and - keys to increase/decrease the n being visualized.

And finally, for those interested in exploring this number sequence further, here is a readable version (this was used to generate the test cases above):
# Brent's cycle detection, modified from wikipedia.
def electron_period(n):
    wire_mask = (1 << n) - 1
    power = lam = 1
    tortoise, hare = 1, 2
    while tortoise != hare:
        if power == lam:
            tortoise = hare
            power *= 2
            lam = 0
        hare = ((hare << 1) ^ (hare >> 1)) & wire_mask
        lam += 1
    return lam


Mathematical substitution Sometimes it is useful to run a math problem with multiple inputs. The goal of this challenge is to make a program that eases this task.

Number-generating expressions

You must support 3 types of expression:

Single number generator: Very simple, just a literal number
Multi-number generator: A tad more complicated. Thees are surrounded by square brackets ([]). Numbers are comma (,) separated in the expression. Example [-1,2,3.26].
Range generator: This one is surrounded by curly braces ({}). It will have 3 numbers separated by a comma. The format of this expression is {start,stop,step}. start and stop are inclusive.

Rules for evaluation

You must support the order of operations. (https://en.wikipedia.org/wiki/Order_of_operations#Definition)
You don't need to support parenthesis.
Any number of spaces may occur in the expression.
You must support floating point numbers (whatever precision your language defaults to is fine).
Division by 0 results in NaN (not a number).

Your program must support multiplication (*), division (/), addition (+) and subtraction (-).

Output

Each line of output is one of the combinations of the generators. The format is the expression (with the real numbers substituted into it) followed by a equals sign (=) and the result of evaluation. All combinations of the generators must be represented in the output.

Examples

(>>> denotes input)

>>>3 * [3,2]
3 * 3 = 9
3 * 2 = 6

>>>{1,2,3}
1 = 1 <-- this is because 1 + 3 > the end

>>>{0,2,1} + {0,1,1}
0 + 0 = 0
1 + 0 = 1
2 + 0 = 2
0 + 1 = 1
1 + 1 = 2
2 + 1 = 3

>>>6/[2,3]
6/2 = 3
6/3 = 2

>>>{1.5,2.5,0.5}
1.5 = 1.5
2 = 2
2.5 = 2.5

>>>3-{6,5,-1}
3-6 = -3
3-5 = -2

>>>5/{-1,1,1}
5/-1 = -5
5/0 = NaN
5/1 = 5

>>>4.4 / [1,2.2] + {0,2,1}
4.4 / 1 + 0 = 4.4
4.4 / 1 + 1 = 5.4
4.4 / 1 + 2 = 6.4
4.4 / 2.2 + 0 = 2
4.4 / 2.2 + 1 = 3
4.4 / 2.2 + 2 = 4

>>> [1,2] / 0 + 5
1 / 0 + 5 = NaN
2 / 0 + 5 = NaN

The program needs to be short so I can memorizes it and use it anywhere.

Thanks to @PeterTaylor and @geokavel for helping me with this post in the sandbox


Average distance of two points in unit n-dimensional hypercube An easy way to understand the unit n-dimensional hypercube is to consider the region of space in n dimensions that you can get if every coordinate component lies in [0, 1]. So for one dimension it's the line segment from 0 to 1, for two dimensions it's the square with corners (0, 0) and (1, 1), etc.

Write a program or function that given n returns the average Euclidean distance of two points uniformly random selected from the unit n-dimension hypercube. Your answer must be within 10-6 of the actual value. It's ok if your answer overflows your language's native floating point type for big n.

Randomly selecting a 'big' number of points and calculating the average does not guarantee such accuracy.

Examples:

  1 → 0.3333333333...
  2 → 0.5214054331...
  3 → 0.6617071822...
  4 → 0.7776656535...
  5 → 0.8785309152...
  6 → 0.9689420830...
  7 → 1.0515838734...
  8 → 1.1281653402...

Data acquired from MathWorld.

This is code-golf, lowest byte-count wins.

Mathematica, 68 bytes

NIntegrate[(1-((E^-u^2+u*Erf@u√π-1)/u^2)^#)/u^2,{u,0,∞}]/√π&

Implementation of the formula using NIntegrate to approximate its value.


This will eventually stop… Given an input string S, print S followed by a non-empty separator in the following way:

Step 1: S has a 1/2 chance of being printed, and a 1/2 chance for the program to terminate.

Step 2: S has a 2/3 chance of being printed, and a 1/3 chance for the program to terminate.

Step 3: S has a 3/4 chance of being printed, and a 1/4 chance for the program to terminate.

…

Step n: S has a n/(n+1) chance of being printed, and a 1/(n+1) chance for the program to terminate.

Notes

The input string will only consist of characters that are acceptable in your language's string type.

Any non-empty separator can be used, as long as it is always the same. It is expected that the separator is printed after the last print of S before the program terminates.

The program has a 1/2 chance of terminating before printing anything.

A trailing new line is acceptable.

Your answer must make a genuine attempt at respecting the probabilities described. Obviously, when n is big this will be less and less true. A proper explanation of how probabilities are computed in your answer (and why they respect the specs, disregarding pseudo-randomness and big numbers problems) is sufficient.

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

C#, 94 85 bytes

My first answer!

using System;s=>{var r=new Random();for(var i=2;r.Next(i++)>0;)Console.Write(s+" ");}

Previous attempt (I liked that goto):

using System;s=>{var i=2;var r=new Random();a:if(r.Next(i++)>0){Console.Write(s+" ");goto a;}}

Ungolfed:

using System;
class P
{
    static void Main()
    {
        Action<string> f = s =>
        {
            var r = new Random();
            for (var i = 2; r.Next(i++) > 0;) Console.Write(s + " ");
        };

        f("test");

        Console.ReadKey();
    }
}

Note: in C# the Random.Next(N) method returns a nonnegative integer in the [0, N-1] range, so we can just check that the number returned is greater than 0.


A Numpad's Knight Numbers For the non-zero digits on a standard numpad
789
456
123

consider placing a chess knight at any digit and moving it around with any number of normal L-shaped jumps, tracing out a positive decimal integer. What positive integers can be expressed in such a way?
One of them is 38, since the knight could start on the 3 and move left and up to the 8. 381 and 383 are also possible.
3 itself is possible if no jumps are taken (which is allowed). 5 is as well, but no other digits can be reached from the 5, so it is the only number where the digit 5 appears.
Write a program or function that takes in a positive decimal integer (you may take it as a string if desired) and prints or returns a truthy value if the number can be expressed by a knight on a numpad in the way described, but otherwise outputs a falsy value.
The shortest code in bytes wins. Tiebreaker is earlier answer
Examples
Truthy:
1, 2, 3, 4, 5, 6, 7, 8, 9, 16, 18, 38, 61, 81, 294, 349, 381, 383, 729, 767, 38183, 38383, 18349276, 183492761, 618349276

Falsy:
10, 11, 50, 53, 55, 65, 95, 100, 180, 182, 184, 185, 186, 187, 188, 189, 209, 305, 2009, 5030, 3838384, 4838383, 183492760

Python 2, 52 bytes
f=lambda n:n<6or`n%100`in'18349276167294381'*f(n/10)

Checks that any two consecutive digits are in the string '18349276167294381'. To get consecutive digits, rather than doing zip(`n`,`n`[1:]), the function repeatedly checks the last two digits and removes the last digit.