Do you know that language? Task:

Your challenge is, given previous submissions and itself as input, output the language that they're written in, in the following format:

Say the first program is in Ruby. It must output 1, because Ruby is the 1st language used in this challenge. An example program is:

a=gets
puts 1

When given itself as input, it returns 1.

The next program might be in Python. It must output 2, because Python is the 2nd language used in the challenge. An example program is:

print(1 if input()[0]=="a"else 2)

Given the first submission, it outputs 1, and given itself it outputs 2.

You're allowed to repeat languages, though you're not allowed to submit an answer in the previous answer's language.

For example, if the third program is in Ruby, it must output 1 given the first program and itself (because Ruby is the 1st language used), and given the second program it must output 2.

Rules:

If there are n answers currently in the challenge, there must be at least floor(n / 3) different languages. Any submission that breaks this rule is disqualified.
No two "neighbouring answers" (e.g. answer n and answer n+1) cannot use the same language.
Different versions of a language do not count as different languages (so Python 2 == Python 3).
Answers must take previous submissions in full as input.
The first submission must take input.
You are not allowed to submit multiple answers in a row.
"Repeat answers" (answers that have the exact same code as a previous submission) are not allowed.
Answers are not allowed to go over the allocated byte-count of that answer - see "Allocated Byte-count" for more details.

Allocated Byte-count:

For each answer number n, the allocated byte-count for that answer is 45 + 5n.

Answer formatting:

Format your answer like so:

# {answer no.}, {language}
{program}
This prints:
- `1` in answer(s) {all answers using 1st language, with links}
- `2` in answer(s) {all answers using 2nd language, with links}
...
{optional explanation}

For the answer lists, do this:

- `1` in answers [1]({link to answer}), [3]({link to answer})...

Scoring:

The first answer to survive after 7 days without any valid submissions after that is declared the winner.

1. Retina, 0 bytes

Try it online!

The empty program prints 1 when given empty input (i.e. itself), because it counts how often the empty regex matches the input (which is always 1+length(input)).


How bold is this post? Preamble

In Stack Exchange markdown, we use ** to bold out text. For example, this markdown:

The **quick brown fox jumps over the lazy** dog.

Renders as:

  The quick brown fox jumps over the lazy dog.

Of course, we use ** to close boldness as well. So less of the answer will be bold. For example:

The **quick** brown fox jumps over the **lazy** dog.

Renders as:

  The quick brown fox jumps over the lazy dog.

However, if the boldness is not closed, it renders as not bold:

The **quick brown fox jumps over the lazy dog.

Renders as:

  The **quick brown fox jumps over the lazy dog.

If the text has a single backslash \, the boldness does not take effect, either:

The \**quick brown fox jumps over the lazy dog.**

Renders as:

  The **quick brown fox jumps over the lazy dog.**

Trailing white space results in unbolded text (note, the white space after brown is a single tab):

The** quick** brown fox jumps over the lazy dog.**

Renders as:

  The** quick** brown fox jumps over the lazy dog.**

We can also use __ for bold, too, but note that only one can be active at a time. Here's a more complicated example:

The __quick**__ brown **fox__ jumps** over__ the__ lazy **dog.

Renders as:

  The quick** brown fox__ jumps over__ the__ lazy **dog.

The question:

You may write a program or function, given ASCII text either as a String argument or on STDIN, where the only special characters are **, __, \ (for escaping) and trailing whitespace, determine how many bold characters there are. This value should be printed to STDOUT or returned from your function. You do not need to support very long strings; String length is guaranteed to be no more than 30K, which is the limit for a Stack Exchange post.

Fine print:

Can I throw an exception / other error for one case, and return normally for the other?

No. It must be either a clear, unambiguous, non errored return value for both cases. STDERR output will be ignored.

Are spaces in between words considered bold?

Yes. **quick brown** has 11 bold characters in it.

Should the \ in \**, if bold, be counted?

No. It renders as **, so if it should be bolded it would only be 2 characters.

Be completely clear: what do you mean by how many characters?

Total characters that would render bold. This means that ** is not rendered if it transforms text, but it is rendered if it does not.
Note that it's possible to make ** be bolded in several ways, e.g. **\**** -> **.
Don't consider the possibility that some text could be converted to italics. The only markdown rule to consider is ** = bold*.

On Stack Exchange, HTML Bold works too. i.e. <b></b>

Yes, I am aware. Don't consider this case, this is normal text.

What about HTML entites? e.g. &lt; -> <

These also should be considered as normal text, there is no HTML entity conversion.

I've thought of an example you didn't cover above!

The rules function exactly as if the text were posted on Stack Exchange, in an answer (not a comment), except that code blocks are not considered special characters. Both the four space type and the backtick type. If you are not sure about how text should be rendered, just throw it into an answer box somewhere as a test, those are the rules you should follow.

Examples:

Input:

The **quick brown fox jumps over the lazy** dog.

Output:

35

Input:

The **quick brown fox jumps over the lazy dog.

Output:

0

Input:

The __quick**__ brown **fox__ jumps** over__ the__ lazy **dog.

Output:

18

Input:

The __quick\____ brown fox **jumps over\** the** lazy \**dog.

Output:

23

Input:

The****quick brown fox****jumps over **the****lazy** dog.

Output:

11

Standard Loopholes are banned.

rs, 107 bytes
\t/
(?<!\\)((\*|_){2})((?=\S)(?!\2)(\\\2|.)*?)?(?<=\S)\1/(\n)^^((^^\3))\3
\\(\*|_)/\t
[^\t\n]/
\n/_
\t_?/
(_*)/(^^\1)

Live demo and test cases.
This is a pretty crazy...thing.
The newest test case does not work yet. WIP...
Explanation
\t/

Replace tabs with spaces. They have the same character count, and tabs are used later on as a special character.
(?<!\\)((\*|_){2})((?=\S)(?!\2)(\\\2|.)*?)?(?<=\S)\1/(\n)^^((^^\3))\3

Replace any text of length N that should be bolded
with N newlines followed by the original text.
\\(\*|_)/\t

Replace any occurrences of a delimiter immediately preceded by a slash with a tab. This is to make sure that entries like **a\*** have a character count of 2 instead of 3.
[^\t\n]/

Remove any character that's not a tab or newline.
\n/_

Replace all the newlines with underscores.
\t_?/

Remove any tabs (which represent escaped delimiters), along with any underscores that may follow them. This is related to the above issue of character counts with escaped ending delimiters.
(_*)/(^^\1)

Replace the underscore sequence with its length. This is the character count.


Given the names of two planets, give the distance Using the following table (source) write some code that takes the names of two planets and returns the distance between them:

+-------------------+---------------+
|      Planets      | Distance (km) |
+-------------------+---------------+
| Mercury -> Venus  |      50290000 |
| Venus -> Earth    |      41400000 |
| Earth -> Mars     |      78340000 |
| Mars -> Jupiter   |     550390000 |
| Jupiter -> Saturn |     646270000 |
| Saturn -> Uranus  |    1448950000 |
| Uranus -> Neptune |    1627450000 |
| Neptune -> Pluto  |    1405380000 |
+-------------------+---------------+

Examples, input then output:

Mercury, Mars
170030000

Neptune, Jupiter
-3722670000

Earth, Earth
0

Note the negative sign there, as Jupiter comes before Neptune. They are also all integers.

Pluto doesn't have to be included (mostly because of a weird orbit which makes it hard to work out the distance - that distance given is my own calculation, but as Pluto is all famous now...).

By distances between planets I'm meaning orbits - I don't expect a date and working out where they are.

This is code golf, shortest code wins.

CJam, 54 51 44 bytes

2{"X84VT:Z/3KD'Y->>6\ Ta "3/r26b93%=70be4}*-

Try it online in the CJam interpreter.

Idea

We use a simple hashing function to identify all eight planets. By considering each name as the array of its code points, converting them from base 26 to integer and taking the result modulo 93 then modulo 8, Mercury, Venus, Earth, etc. map to 2, 4, 0, 1, 3, 5, 6 and 7.

Now, we choose a point that lies 320,000 km behind Neptune and calculate the distances of all eight planets to that point. After dropping four trailing zeroes and reordering the planets so that they fit the 8 indexes from above, we obtain the array

[435172 427338 444341 372299 439312 307672 162777 32]

which, if we encode each integer in base 70, yields the following:

[
   [1 18 56 52] [1 17 14 58] [1 20 47 51] [1 5 68 39]
   [1 19 45 62] [  62 55 22] [  33 15 27] [       32]
]

Remembering that two adjacent digits (A B) can be replaced with ((A-1) (B+70)), we can modify the array from above so that all integers can be encoded as printable ASCII characters:

["X84" "VT:" "Z/3" "KD'" "Y->" ">6\\" " Ta" " "]

Code

2{                         e# Do twice:
  "X84VT:Z/3KD'Y->>6\ Ta " e#   Push that string.
  3/                       e#   Chop it into chunks of length 3.
  r                        e#   Read a token from STDIN.
  26b                      e#   Convert from base 26 to integer.
  93%                      e#   Take the result modulo 93.
  =                        e#   Retrieve the chunk at that index.
  70b                      e#   Convert from base 70 to integer.
  e4                       e#   Multiply by 10,000.
}*                         e#
-                          e# Subtract the two results.


Determining Yes or No? After inputting a string [length 1-20], only containing the chars y for yes and n for no,
your program should output the result (y or n). Example input: yynynynny would output y.

The result is determined by combining the y's and n's in the following way:

yes and no equals no
yes and yes equals yes
no and no equals yes

If the string contains more than 2 characters (likely...), the calculation would look the same. Examples:

yes and yes and no equals no (because the no merges with the first yes to no. then there are no and yes left and the same thing happens again)
no and no and no equals no (the first two no's merge to yes, then there are yes and no left, which emerge to no)

Example input with output:

yynynynynyyn = n

Tip: have in mind that the order of the chars your program works off doesn't care. (for example you can read the input from back, or from behind, mix the letters, sort it, whatever. What counts is the correct ouptput) have fun!

Winning criteria:
this is code-golf, so shortest code in byte wins.

Octave, 29 27 bytes
Thanks to @RickHithcock for pointing out a mistake, now corrected. Also, 2 bytes off thanks to @StewieGriffin!

@(s)'yn'(mod(sum(s+1),2)+1)

Try it online!
Explanation
The ASCII code point of 'y' is odd, and that of 'n' is even. The code

adds 1 to each char in the input string to make 'y' even and 'n' odd;
computes the sum;
reduces the result to 1 if even, 2 if odd;
indexes (1-based) into the string 'yn'.


Convert superscripts to MathJax CGCC hasn't always had MathJax. Back in the dark ages, it would have been necessary to write \$x^2\$ as x² (the horror!). In this challenge, you will be given some math which may include superscripts, and you should convert it to MathJax.
Input:
Input will consist of one or more letters a to z, some with superscripts. Answers may choose to handle only upper or lower case, or both.
Examples of inputs would be x, x², xy², x²y², or x²yz. There will never be duplicates of a letter (so xx or x²zx won't be given), but you cannot assume the superscripts or letters are in any particular order. The first character in the input will never be a superscript.
Superscripts consist of the characters ¹, ², ³, ⁴, ⁵, ⁶, ⁷, ⁸, ⁹, and ⁰. These can be joined into multi-digit superscripts, like x²¹ (\$x^{21}\$). You can assume ⁰ or ¹ are never given as superscripts, and there will not be leading ⁰s.
Output:
Output should consist of a MathJax representation of the input. This must start and finish with \$.
Characters without superscripts can be written as themselves; xyz would simply become \$xyz\$. Characters with superscripts should be followed by ^, then the superscript written with normal digits and wrapped in {}. For example, x²¹z⁴⁸⁸ would become \$x^{21}z^{488}\$. Optionally, single digit superscripts can be written without the {}. For example, x² could be either \$x^{2}\$ or \$x^2\$.
Test cases:
x           \$x\$
xyz         \$xyz\$
x²          \$x^{2}\$ OR \$x^2\$
x²¹         \$x^{21}\$
x²yz²       \$x^{2}yz^{2}\$ OR \$x^2yz^2\$
xy¹¹z       \$xy^{11}z\$
x⁴          \$x^{4}\$ OR \$x^4\$
x⁶⁰         \$x^{60}\$

Other:
This is code-golf, shortest answer (in bytes) per language wins!

Husk, 43 41 40 bytes
`JD;"¦$"ṁ?Iȯ:'^`J"{}"ṁos€"¹²³⁴⁵⁶⁷⁸⁹"Λ√ġ√

Try it online!
The superscripts are 1 byte each since they're in Husk's codepage.
I wanted to replace +₁+₁ with S+`+"¦$" but it didn't work for some reason.. :(
-2 bytes borrowing the indexing idea from hyper-neutrino.
-1 byte from Leo.
Explanation
`JD;"¦$"ṁ?Iȯ`:'}+"^{"ṁos€"¹..⁹"Λ√ġ√
                              ġ√ group on alphabets
     ṁ                           map and concatenate with:
      ?                            if:
                            Λ√      the group is alphabetical
       I                             leave as is
        ȯ`:'}+"^{"ṁos€"¹..⁹"        otherwise:
                  ṁȯ                  map and concat each char to:
                     €"¹..⁹"           index in ¹..⁹(0 if not present)
                    s                  cast to string
             +"^{"                    prepend "^{"
         `:'}                         append '{'
`JD;"¦$"                            surround the final string with "\$"


What size is the digit? 7-segment digits can be represented in ASCII using _| characters.  Here are the size 1 digits:

   _  _       _   _   _   _   _   _
|  _| _| |_| |_  |_    | |_| |_| | |
| |_  _|   |  _| |_|   | |_|  _| |_|

Larger sizes are formed by making each segment proportionately longer.  Here are a couple size 3 digits.

 ___    ___    ___    ___    ___    ___    ___
|   |  |          |  |          |  |   |  |   |
|   |  |          |  |          |  |   |  |   |
|___|  |___       |  |___    ___|  |   |  |___|
|   |  |   |      |      |      |  |   |      |
|   |  |   |      |      |      |  |   |      |
|___|  |___|      |   ___|   ___|  |___|   ___|

Goal

In this challenge, you are to write a program/function that can take a single digit as input and identify its size.  The catch: if the input is not a valid digit, then your program should output 0.

This is code-golf, fewest bytes wins.

You can write either a program or a function, which can receive the digit either as STDIN or an argument, and print/return the value.

Digits will be provided as a multi-line string, padded with the minimal amount of trailing whitespace needed to make it a perfect rectangle.  The trailing newline is an optional part of input.  There will be no unneeded leading spaces.

When a non-digit is passed, it will still be comprised of _| characters, padded to a rectangle, and have no unneeded leading spaces. There will be no blank lines. You won't have to deal with empty input.

Output should be a single non-negative integer, with optional trailing newline.  If the input is not a proper digit of any size, output 0.  Else, output the size.

Here is a handy guide for the widths and heights of each digit for a given size N.

Digit  Height  Width (not counting newlines)
1      2N      1
2      2N+1    N+2
3      2N+1    N+1
4      2N      N+2
5      2N+1    N+2
6      2N+1    N+2
7      2N+1    N+1
8      2N+1    N+2
9      2N+1    N+2
0      2N+1    N+2

I/O Examples

In:

__
  |
__|
  |
__|

Out:

2

In:

|
|
|

Out:

0  //because it is of an invalid height.  Either 1 char too short or tall.

In:

|    |
|    |
|    |
|____|
     |
     |
     |
     |

Out:

4

In:

 ___
|
|___
|   |
|___|

Out:

0 //1 char too wide

In:

 _
|_|
| |

Out:

0 //it's not a digit

In:

 __
|
|__
   |
 __|

Out:

2

In:

 _  _
 _| _|
|_  _|

Out:

0  //both would be valid individually, but input should be a *single* digit

In:

 _
|_|
|_|

Out:

1

In:

|
|

Out:

1

In:

__|_
 |
 _ |
  _
|__

Out:

0

This is approximately the inverse of Transform number into 7-segment display pattern, from 3 years back.

Ruby, 250
->x{d=y=0
x.size.downto(0){|n|y=n
a=["|
"*2*n]
"XNRDqpm@A".bytes{|z|p=[?|,' ','']
h=s=""
(n*2).times{|i|
i%n<1&&(d=z>>i/n*3&7)&&h=[?_,' '][d/3%2]*n
s=p[d%3]+h+p[d/6]+"
"+s
h=' '*n}
z!=68&&s=' '*(1-d%3/2)+?_*n+"
"+s
a<<s};puts a
a.index(x)&&break}
y}

Given that there are so many possible invalid inputs, the only way to do this was to generate all the correct digits and check to see if the input matches.
I build each digit up from bottom to top, in 2 halves plus the top line. Although there are 12 possibilities (considering that the left segment can be on, off, or in the case of 3and 7completely absent) only 7 are actually present and careful choice of encoding enables all info (except the top line) to be encoded into a single character.
the digit 1 doesn't really fit the pattern and is handled separately, being used to initialize the array.
Ungolfed in test program
This version uses . instead of spaces for diagnostic reasons.
#Encoding used for half-digits (radix 3,2,2 most significant digit at right)

#000    |_|  0

#100    ._|  1  . = space

#200    X_|  2  X = no space (for digits 3 and 7)

#010    |.|  3

#110    ..|  4

#210    X.|  5

#001    |_.  6

f=->x{d=y=0                                        #d and y required to be intialized for scoping reasons
  x.size.downto(0){|n|y=n                          #Assume max possible size of character = length of input and iterate down through all possible sizes n
    a=["|\n"*2*n]                                  #Make an array containing the digit 1 (different shape to others)
    "XNRDqpm@A".bytes{|z|                          #Each character encodes the pattern for a digit. Iterate through them
      p=['|','.','']                               #Possible components for left and right of digit
      h=s=""                                       #h initialized for scoping reasons. s will contain the digit string
      (n*2).times{|i|                              #For each row
        i%n<1&&                                    #If i%n==1 we are at the bottom of a half digit
        (d=z>>i/n*3&7)&&                           #so extract info from z and store in d
        h=[?_,'.'][d/3%2]*n                        #h is the horizontal part of the half digit, either _ or spaces
        s=p[d%3]+h+p[d/6]+"\n"+s                   #Build one row of digit, working upwards: left,middle,right
        h='.'*n                                    #If row i%n!=0 (not bottom row of half digit)the middle section must contain spaces
      }                                            #We now have both halves of the digit, only the top segment missing
      z!=68&&s='.'*(1-d%3/2)+?_*n+".\n"+s          #If z!=68 (digit 4) add a top to the digit, with appropriate leading and trailing spaces
      a<<s                                         #Add the completed digit of size n to a
    }
    #puts a                                        #Diagnostic: uncomment to print all the strings checked
    a.index(x)&&break                              #If string x is in a, break

  }
y                                                  #and return last value of n
}

# digit 7, size 2. Trailing newline required. Outputs 2
puts f[
"__.
..|
..|
..|
..|
"]


Encode an image inside of the source The golf challenge is to encode and compress the following image inside a source file.

To do this you need to write 3 functions: red, green, and blue which accept x/y coordinates of the image and return the corresponding R/G/B pixel value between 0-255.

Here is the C/C++ test code:

#include <stdio.h>
#include "your_file"
int main() {
  int x, y;
  for(y = 0; y < 32; ++y)
  for(x = 0; x < 32; ++x)
    printf("%i %i %i\n", red(x, y), blue(x, y), green(x, y));
}

And the output: http://pastebin.com/A770ckxL (you can use this to generate your image data)

Rules & details:

This is a golf
Only your code/file is golfed - the test code is separate
The character set used is ASCII, however control characters in strings may only be used if escaped (like '\n' and '\r', etc)
Everything must be contained inside the source - no file loading
Your output must match the example output. This means loseless compression.

Languages:

The problem was written with C/C++ in mind, but I'm removing those restrictions. With that said, I'll still recommend using them.

C, 796 754 712 703 692 685 682 670 666 662 656 648 chars

Changelog:

754->712: Added return to the #define, replacing if with ? statements (thanks @FUZxxl), removing int from the functions parameter list.
712->703: Shameless copy from bunnit again :) Moved the whole image creation into the #define
703->692: Merged p[] and h[], some more ?: improvements
692->685: Incrementing b so i isn't needed anymore. m=b instead of m=11 and n<2e3 instead of i<356 - these are close to undefined behaviour/memory corruption, but it seems I'm lucky :)
685->682: k is now (32,16,8,4,2,1,0) instead of (5,4,3,2,1,0). Gotcha, D C ;)
682->670: Split p[] and h[], converted h[] to a char* - awwww, there's a sleepy kitty in it ^<+_=>-
670->666: while => for, l=l*2+... => l+=l+...
666->662: m=m>9?... => c[n++]=m>9?...
662->656: Reversed bit order in b[], so we can map to 64-127 instead of 0-63 and don't need bit index k anymore. Thanks @Piotr Tarsa. Replaced ?: (GCC extension) with ||. Thanks @JamesB
656->648: Shameless copy from Shelwien :) (multi-character constants for p[])

Image is converted to a Base64-like string (ASCII 37-100), using huffman coding to encode colors 0-9 using 3-6 bits and a special color 10 (pixel is same as previous one) using only 1 bit.

#define P (x,y){for(;n<2e3;j/=2){j>1||(j=*b+++27);l+=l+(j&1);for(m=0;m<11;m++)l-h[m]+32||(c[n++]=m>9?c[n-1]:m,l=0,m=b);}return 255&p[c[x+y*32]]
char*h="$^<+_=>-,* ",*b="F0(%A=A=%SE&?AEVF1E01IN8X&WA=%S+E+A-(,+IZZM&=%]U5;SK;cM84%WE*cAZ7dJT3R.H1I2@;a^/2DIK&=&>^X/2U*0%'0E+;VC<-0c>&YU'%],;]70R=.[1U4EZ:Y=6[0WU4%SQARE0=-XDcXd_WW*UAF&cFZJJ0EV*(a(P05S3IXA>51cH:S5SAE6+W%/[]7SF(153UM]4U()(53DA+J:]&5+5KX,L6>*4I,/UMBcML9WKLa9%UYIHKWW(9-*):(-ZW(9%T'N&9;C,C/Ea/Y7(JJ\\6CD9E,2%J*,ac]NIW8(M=VFac)/^)?IS-;W&45^%*N7>V,,C-4N35FMQaF,EaWX&*EJ4'";p[]={0,'R@+','aXL',7783255,'4k`',16354410,'NNv',5295994,4671418,9975021},c[1024],j,l,m,n;red P;}blue P>>16;}green P>>8;}

Copied two things from bunnit's answer, the #define and the whole image being decoded completely every time red/green/blue are called. There's some room for additional improvement, so expect some updates :) I'm not sure about code compliance, used GCC 4.6.1 to compile and test.

Compression-wise, I think arithmetic coding would help as the distribution is pretty skewed, but maybe code overhead would be too heavy in this case. LZW also should do a very good job. Colors are quite local, so adaptive coding might be an idea.

More readable 754 character version with some comments:

#define P 255&p[c[x+y*32]]
// Base64 coded image bitstream, ASCII 37-100
// Huffman codes: 100, 111110, 11100, 1011, 111111, 11101, 11110, 1101, 1100, 1010, 0
char b[]="FYU%3+3+%B&E;3&HF1&Y1.JWXE83+%B=&=3)U]=.PP*E+%,('?B>?D*Wa%8&MD3P7dNbARIV1.Q[?4L9Qc.>E+EKLX9Q(MY%5Y&=?HC_)YDKE0(5%,]?,7YR+I@1(a&PO0+G@Y8(a%B23R&Y+)XcDXd<88M(3FEDFPNNY&HMU4UZY'BA.X3K'1DVOB'B3&G=8%9@,7BFU1'A(*,a(U-U'Ac3=NO,E'='>X]^GKMa.]9(*SD*^/8>^4/%(0.V>88U/)M-OU)P8U/%b5JE/?C]C9&4907UNN`GCc/&]Q%NM]4D,J.8WU*+HF4D-9L-;.B)?8Ea'L%MJ7KH]]C)aJA'F*24F]&48XEM&Na5";
// Colors, order GBR (one char shorter than all the others)
p[]={0,5390379,6379596,7783255,3435360,16354410,5131894,5295994,4671418,9975021};
// Huffman codes for colors 0-10
h[]={4,62,28,11,63,29,30,13,12,10,0};
// Array for image data
c[1024];
i,j,k,l,m,n;
red(int x,int y){
  while(i<356){
    k--;
    if (k<0) {
      j=b[i++]-37;
      k=5;
    }
    l*=2;
    if (j&(1<<k)) l++;
    for(m=0;m<11;m++){
      if(l==h[m]){
        if (m>9) m=c[n-1];
        c[n++]=m;
        l=0;
        m=12;
      }
    }
  }
  return P;
}
blue(int x,int y){return P>>16;}
green(int x,int y){return P>>8;}


Hash collision: "NO" means "YES" This Code Golf was inspired by the recent Daily WTF article You Can't Handle the True!, which features a string comparison written as:

String yes = "YES";
if ((delay.hashCode()) == yes.hashCode())

Imagine the trouble it would have caused for Steve's team if Java's String.hashCode method just happened to be implemented in a way that "YES".hashCode() == "NO".hashCode().  So, the challenge I propose here is:

  Write, in as few characters as possible, a hash function (I'll call it
  h) with a string parameter and integer return value, such that
  h("YES") is equal to h("NO").

Of course, this would be trivial to do with a function like def h(s): return 0, which makes a hash collision for every string.  To make this challenge more interesting, you must abide by the following additional rule:

  Of the other 18 277 possible strings consisting of three or fewer
  uppercase ASCII letters (^[A-Z]{0,3}$), there must be no hash
  collisions.

Clarification (pointed out by Heiko Oberdiek): The input string may contain characters other than A-Z, and your code must be able to hash arbitrary strings.  (You may, however, assume that the input is a character string rather than a null pointer or an object of some other data type.)  However, it does not matter what the return value is for strings that do not match ^[A-Z]{0,3}$, as long as it's an integer.

Furthermore, to obfuscate the intent of this function:

  Your code must not include any of the letters 'Y', 'E', 'S', 'N', or
  'O' (in either upper- or lowercase) within character or string
  literals.

Of course, this restriction doesn't apply to language keywords, so else, return, etc. are fine.

32-bit Python 2.x (19)

hash(w*9)%537105043

RSA uses a semiprime modulus, and that makes it secure, so using one with my hash algorithm should surely make it even better!1

This is a pure math function, works for all strings (hell, works for any hashable Python object), and doesn't contain any conditionals or special-casing! 32-bit Python can typically be called as python-32 on most systems that have both installed2.

I've tested this, and it returns 18,278 different values for the 18,279 3-letter-or-less uppercase strings. Assigning this to a function takes 11 more bytes:

h=lambda w:hash(w*9)%537105043

and h('YES') == h('NO') == 188338253.

64-bit Python 2.x (19)

hash(w*2)%105706823

Same deal as above.

To come up with these numbers, a little bit of modular math was used. I was looking for a function f and a modulus n such that hash(f('YES')) % n == hash(f('NO')) % n. This is equivalent to testing that n divides d = hash(f('YES')) - hash(f('NO')), i.e. we only have to check the factors of d for suitable values of n.

The ideal n is in the neighbourhood of 20000**2 to reduce the chance of a birthday paradox collision. Finding a suitable n turns out to be a bit of trial and error, playing with all the factors of d (there usually aren't many) and different choices for the function f. Notice though that the trial and error is only needed because I wanted to make n as small as possible (for golfing). If that wasn't a requirement, I could just choose d as my modulus, which is usually sufficiently large.

Note too that you can't pull this trick off using just f(s) = s (the identity function) because the rightmost character of the string has essentially a linear relationship (actually an XOR relationship) with the final hash (the other characters contribute in a much more nonlinear way). The repetition of the string therefore ensures that the differences between the strings are amplified to eliminate the effect of changing only the rightmost character.

1 This is patent nonsense.
2 Python string hashing depends on major version (2 vs 3) and bitness (32-bit vs 64-bit). It does not depend on platform AFAIK.


Make a codegolf scorer You are to make a program that given a number, such as 22009, will go for example to Pi Calculation Code Golf. Then it will, for each answer, try to figure out what the code is, and count its characters. It will then output, for each answer, its number of characters, and a link to it. It should be sorted with fewest characters at the top. For example :

$ answers 22009
5 https://codegolf.stackexchange.com/a/22138/16842
5 https://codegolf.stackexchange.com/a/22188/16842
6 https://codegolf.stackexchange.com/a/22012/16842
6 https://codegolf.stackexchange.com/a/22043/16842

and so on

This is code-golf, so shortest code wins!

Note: If there are multiple things that look like code blocks, it doesn't matter which you choose. It is better though if you look which block actually looks like a program, or you could post a different one for each block.

Note: This specifically says characters. It does not matter what the question actually says, just count characters.

Perl - 233

use LWP::Simple;for($s="http://codegolf.stackexchange.com",$h=get"$s/questions/@ARGV";$h=~/-answerid="(\d+).+?(<div id="answer-|$)/sg;){$a=$&;$i=$1;$_=$1,$_=~s/&.+?;/@/sgm,print length."$u\t$s/a/$i/\n"while$a=~/
(.+?)</sg;}

More aerated version:

use LWP::Simple;
$s="http://codegolf.stackexchange.com";
$h=get"$s/questions/@ARGV";
for(;$h=~/-answerid="(\d+).+?(<div id="answer-|$)/gs;){
    $a=$&;
    $i=$1;
    while($a=~/
(.+?)</gs){
        $_=$1;
        $_=~s/&.+?;/@/sgm;
        print length."$u\t$s/a/$i/\n"
    }
}

This is my first script in this language... so there's still probably a lot of golfing to do.


Bot: Outsnake the game! So, I wrote a simple Javascript game (as yet unnamed) and naturally I wanted to write an API so I could write a bot to play it for me, and naturally I wanted to let the PPCG community have a go for themselves.

It's a 'snake' game with the simple goal of collecting as many blue squares as possible while avoiding red squares or the edge of the board. It was initially controlled with a mouse.

Find the API edition of the game here: https://ajfaraday.github.io/game_name_here/api.html

Gameplay:

Type the code for your bot in the field under 'Your function': This will repeat automatically when you tell it to run.

Only in Javascript, sorry.
See restrictions, below.

You can try it step-wise by clicking 'step'.
I suggest you 'Run (fast)' once you have a workable function.
Click 'Reset' to try a fresh game.
Every 10 points will increase the points per blue square by 1.
Every 10 points will increase the red squares spawned by 1.
You can lose lives by:

Gobbling up a red square (Be aware that, while you lose a life, it also breaks down the wall. Sacrificing lives to break through walls is a legitimate tactic).
Attempting to leave the game board.
Running down the 'Timeout' clock of 20 seconds between blue squares.

You will not lose a life by 'stepping on your tail' in this version.
Every 100 points will earn an additional life.
Be aware that all coordinates are x, y starting in the top left corner. 0 indexed.

Restrictions:

There is no security in this code. Please do not hack the game!

Only use standard JS and the API methods described.
PLEASE! Don't change API.coord
You may not interact directly with Sketch, Cell or other entities defined within the game.

The competition

Please give your entry title a short name for your snake.
Include your JS code and any explanation you'd like to include.
The OP will copy/paste the code into the game, and run it 5 times (using 'Run (fast)').
The highest score achieved in those attempts is your score.
The OP will add your score to the answer, and to a leader board in the question.
You may submit more than one function.

Leader Board

+--------------------------+---------------------------------+----------+
| Username                 | Snake Name                      | Score    |
+--------------------------+---------------------------------+----------+
| orlp                     | Simple A*                       | 595      |
+--------------------------+---------------------------------+----------+

Rendering Issue

This rendering issue has now been fixed and deployed.

Please be aware that if you call more than one of the direction methods during your function, the snake will visit all of the squares and collect points or lose lives accordingly. However, due to a rendering issue, it will only display the ending position of your snake.

Be aware that the snake can not travel diagonally between walls without losing a life.

Responsible disclosure: This is written in pure Javascript, it contains no logging, analytics or other data gathering processes. It's hosted on github pages, typically a trusted home of code.

If you want to confirm this, or would prefer to develop your answer on a locally hosted instance, the code is available here:
https://github.com/ajfaraday/game_name_here

This is my first attempt at a competitive non-golf challenge, so I'm open to suggestions about how I could make it more suitable for this kind of situation.

Happy snaking!

Simple A* - Official score: 595

This solution uses simple A* pathfinding, with no long-term strategy - it always finds the optimal route towards just the next blue square.

var h = function(p, q) {
    // Manhattan distance.
    return Math.abs(p[0] - q[0]) + Math.abs(p[1] - q[1]);
};

var s = JSON.stringify;
var p = JSON.parse;
var walls = API.walls.map(s);
var start = API.coord;
var goal = API.goal;

var is_closed = {};
is_closed[s(start)] = 0;
var open = [s(start)];

var came_from = {};
var gs = {};
gs[s(start)] = 0;
var fs = {};
fs[s(start)] = h(start, goal);

var cur;
while (open.length) {
    var best;
    var bestf = Infinity;
    for (var i = 0; i < open.length; ++i) {
        if (fs[open[i]] < bestf) {
            bestf = fs[open[i]];
            best = i;
        }
    }

    cur = p(open.splice(best, 1)[0]);
    is_closed[s(cur)] = 1;

    if (s(cur) == s(goal)) break;

    for (var d of [[0, 1], [0, -1], [1, 0], [-1, 0]]) {
        var next = [cur[0] + d[0], cur[1] + d[1]];
        if (next[0] < 0 || next[0] >= API.width ||
            next[1] < 0 || next[1] >= API.height) {
            continue;
        }

        if (is_closed[s(next)]) continue;
        if (open.indexOf(s(next)) == -1) open.push(s(next));
        var is_wall = walls.indexOf(s(next)) > -1;
        var g = gs[s(cur)] + 1 + 10000 * is_wall;
        if (gs[s(next)] != undefined && g > gs[s(next)]) continue;

        came_from[s(next)] = cur;
        gs[s(next)] = g;
        fs[s(next)] = g + h(next, goal);
    }
}

var path = [cur];
while (came_from[s(cur)] != undefined) {
    cur = came_from[s(cur)];
    path.push(cur);
}

var c = path[path.length - 1];
var n = path[path.length - 2];
if (n[0] < c[0]) {
    API.left();
} else if (n[0] > c[0]) {
    API.right();
} else if (n[1] < c[1]) {
    API.up();
} else {
    API.down();
}


Determine whether a number is 2017-friable without primes in your source code Out of all the years I've been making this challenge, 2017 is the first year that's been a prime number. So the question will be about prime numbers and their properties.

Your task is to produce a program or function that will take an arbitrarily large positive integer as input, and output or return whether or not the number is 2,017-friable — that is, whether the largest prime factor in that number is 2,017 or less.

Some example inputs and their outputs:

1 (has no prime factors)
true

2 (= 2)
true

80 (= 2 x 2 x 2 x 2 x 5)
true

2017 (= 2017)
true

2019 (= 3 x 673)
true

2027 (= 2027)
false

11111 (= 41 x 271)
true

45183 (= 3 x 15061)
false

102349 (= 13 x 7873)
false

999999 (= 3 x 3 x 3 x 7 x 11 x 13 x 37)
true

1234567 (= 127 x 9721)
false

4068289 (= 2017 x 2017)
true

Your program does not have to literally output true and false — any truthy or falsy values, and in fact any two different outputs that are consistent across true and false cases are fine.

However, you may not use any primes in your source code. Primes come in two types:

Characters, or sequences of characters, that represent prime number literals.

The characters 2, 3, 5, and 7 are illegal in languages where numbers are valid tokens.
The number 141 is illegal because it contains 41, even though 1 and 4 are otherwise valid.
The characters B and D (or b and d) are illegal in languages where they are typically used as 11 and 13, such as CJam or Befunge.

Characters that have prime-valued Unicode values, or contain prime-valued bytes in their encoding.

The characters %)+/5;=CGIOSYaegkmq are illegal in ASCII, as well as the carriage return character.
The character ó is illegal in UTF-8 because its encoding has 0xb3 in it. However, in ISO-8859-1, its encoding is simply 0xf3, which is composite and therefore okay.

The shortest code to do the above in any language wins.

Jelly, 8 bytes

44‘²!*ḍ@

Try it online! Note that test cases 11111 and above are a bit too much for TIO.

Verification

$ source="34,34,fc,82,21,2a,d5,40"
$ xxd -ps -r > 2017.jelly <<< $source
$ xxd -g 1 2017.jelly
0000000: 34 34 fc 82 21 2a d5 40                          44..!*.@
$ eval printf '"%d "' 0x{$source}; echo # Code points in decimal
52 52 252 130 33 42 213 64
$ test_cases="1 2 80 2017 2019 2027 11111 45183 102349 999999 1234567 4068289"
$ for n in $test_cases; do printf "%11d: %d\n" $n $(jelly f 2017.jelly $n); done
      1: 1
      2: 1
     80: 1
   2017: 1
   2019: 1
   2027: 0
  11111: 1
  45183: 0
 102349: 0

Test case 999999 has been running for 13 hours. I'm pessimistic about computing 2025!4068289...

How it works

44‘²!*ḍ@  Main link. Argument: n

44        Yield 44.
  ‘       Increment to yield 45.
   ²      Square to yield 2025.
          Note that no integers in [2018, ..., 2025] are prime numbers.
    !     Take the factorial of 2025.
     *    Raise it to the n-th power.
          This repeats all prime factors in 2025! at least n times, so the result
          will be divisible by n if (and only if) all of its prime factors fall
          in the range [1, ..., 2025].
      ḍ@  Test the result for divisibility by n.


Exponentiation Sequence The oldest Polish salt mine, located in Bochnia*, was started in year 1248, which we can consider a magical number. We can see that it's equal to 4 digits from the sequence of exponentiations: .

As the date is actually 4 digits from the sequence, we could make it longer. We could repeat the process until we reach infinity. The sequence would look like this, if we limit it to number 2048

124816326412825651210242048

To make it look a bit better, we can separate the numbers:

1|2|4|8|16|32|64|128|256|512|1024|2048

Let's try a custom, longer sequence than the date. Let's say, we want it to have 5 digits - there are more than one possibility:

24816
81632
64128

Or 3 digit ones:

124
248
816

We could also add the 3 digit numbers to this, but let's say, that a sequence must have at least two numbers.

* There is no information about this on the English Wikipedia. If you enter the Polish version - then there is. If you visit the mine, the workers will also tell you, that it started in 1248.

The challenge

Create a exponentiation sequence like in examples above with 2 as the base.

Given a number from range 2-27, output all possible parts of the sequence (The 2048 one or larger if you want) with amount of digits equal to the input. You cannot cut a number, so output like 481 is invalid, because 16 is cut in half.

Rules:

Standard loopholes are forbidden.
You can assume the input is a number inside the range.
Your program can accept inputs larger than the range (28+), but that won't increase/decrease score.
Spaces in output are ignored. You can output like 124 or like 4 8 16.
Different possibilities should be separated by any character from the list: ,./| or a line feed.
You can output as an array.
Every possibility should include at least 2 different numbers.
You must output a part of the sequence, you cannot mix numbers that aren't next to each other, like: 14.
Hardcoded output isn't allowed, however, you can hardcode a string/number/array containing the full sequence.
Input 27 should return the full 2048 sequence.
As already mentioned before, do not cut numbers. Ex. 16 must stay 16 - you can't use 481 - you must use 4816.
EDIT: I might have said something wrong there; 2048 is the last number which your program should support, you can add support for larger int's.

Test cases

Input: 2

12, 24, 48

Input: 3

124, 248, 816

Input: 4

1248, 4816, 1632, 3264

Input: 5

24816, 81632, 64128

Input: 27

124816326412825651210242048

And later numbers...

If I made a mistake in any of the test cases, tell me or edit the question.

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

05AB1E, 12 11 10 bytes

Supports the sequence up to 2^95 = 39614081257132168796771975168

₃ÝoŒʒg≠}Jù

Try it online!

Explanation

₃Ý            # push range [0 ... 95]
  o           # raise 2 to the power of each
   Œ          # get a list of all sublists
    ʒ         # filter, keep elements that satisfy:
     g        # length
      ≠       # false (not equal to 1)
       }      # end filter
        J     # join each
         ù    # keep numbers of length matching the input

Saved 1 byte thanks to Erik the Outgolfer
Saved 1 byte thanks to Riley


Lípínguapua dopo Pêpê Língua do Pê, or P Language, is a language game spoken in Brazil and Portugal with Portuguese. It is also known in other languages, such as Dutch and Afrikaans. (Wikipedia)

There are some dialects in this language game. The different languages the game is played with even have their own unique dialects. Some people are fluent in speaking P Language and the best can even translate any text to their preferred dialect on the spot!

P Language

In this challenge, we will use the Double Talk dialect.

To translate text into P Language, any sequence of vowels in the text is appended with a single p character followed by a copy of the sequence of vowels.

Challenge

Write a function or program that accepts a string as input and outputs its translation in P Language.

The input consists only of printable ASCII characters.
The output consists only of the translated input and optionally a trailing newline.
Vowels are any of the following characters aeiouyAEIOUY.
A sequence of vowels is delimited by any other character. The string "Aa aa-aa" has three vowel sequences.
Leading and trailing whitespace may optionally be omitted from the translated output string.

Examples

""                              =>   ""
"Lingua do Pe"                  =>   "Lipinguapua dopo Pepe"
"Hello world!"                  =>   "Hepellopo woporld!"
"Aa aa-aa"                      =>   "AapAa aapaa-aapaa"
"This should be easy, right?"   =>   "Thipis shoupould bepe eapeasypy, ripight?"
"WHAT ABOUT CAPS?"              =>   "WHApAT ApABOUpOUT CApAPS?"
"   Hi "                        =>   "   Hipi " or "Hipi"

The double quotes character " is used to delimit the input and output strings in the examples but obviously this character may also appear in any valid input string.

JavaScript (ES6), 35 bytes

s=>s.replace(/[aeiouy]+/gi,'$&p$&')

Try it online!
Where the special replacement pattern $& means matched substring.


Is this a straight flush? Related: Name the poker hand

  A straight flush is a poker hand containing five cards of sequential rank, all of the same suit. As part of a straight flush, an ace can rank either above a king or below a two. An ace can rank either high (e.g. A♥ K♥ Q♥ J♥ 10♥ is an ace-high straight flush) or low (e.g. 5♦ 4♦ 3♦ 2♦ A♦ is a five-high straight flush), but cannot rank both high and low in the same hand (e.g. Q♣ K♣ A♣ 2♣ 3♣ is an ace-high flush, not a straight flush).

Challenge

Given N cards (in any reasonable format) output a truthy value if a straight flush is contained in the poker hand.

Input

N numbers of cards. (In any reasonable format)

There are four suits; hearts, spades, diamonds, and clubs (H, S, D, C).

Each suit has one card for the numbers 2 to 10, plus 4 'picture' cards, Ace, Jack, Queen, and King (A, J, Q, K)

Note: You can take 10 as T

Output

Truthy/Falsy value

Test case

["AS", "2S", "3S", "4S", "5S"] => true

["3D", "9C", "4S", "KH", "AD", "AC"] => false

["5D", "6D", "7D", "8H", "9D", "10D", "JD"] => false

["JC", "7C", "5D", "8C", "AC", "10C", "9C", "5S"] =>true

[] => false

["AS", "2S", "3S"] => false

["JC", "QC", "KC", "AC", "2C"] => false

[ "2H", "3H", "4H", "5H", "6H", "7H"] => true

Standard code-golf rules apply.

Winning criteria: Shortest code in each lang

Python 2, 95 bytes

lambda a:any(set('A234567891JQKA'[i/4:][:5])<={r['HCSD'[i%4]in r]for r in a}for i in range(40))

Try it online!

There are 40 possible straight flushes, and this simply checks them all. Chas Brown saved 2 bytes; Jo King saved 4 more.


Decode Arabic to Arabic Presentation Form Objective

Given an Arabic string consisting of ISO/IEC 8859-6 Arabic letters (U+0621–063A, 0640–064A), decode it to Arabic Presentation Forms-B (U+FE70–FEFF).

Behavior of Arabic letters

ISO/IEC 8859-6 Arabic letters change their displayed form to letters in Arabic Presentation Forms-B, which are categorized to isolated, initial, medial, or final letters.

If a letter is the first letter or follows another letter in isolated or final form:

If it is also the last letter or it lacks an initial form, it is in isolated form.
Otherwise, it is in initial form.

Otherwise, if the letter is not the last letter, its medial form is available, and the next letter is not ء(U+0621), it is in medial form.
Otherwise, the letter is in final form.
ـ (U+0640) is a special case. It doesn't have a presentation form, and always will be mapped to itself. It will be assumed to appear only where a letter in medial form could appear.

Note that Arabic letters are written right-to-left.

Mapping

Note that we don't care about ligatures (U+FEF5–FEFC).

Rule

If the string contains a letter not within U+0621–063A nor U+0640–064A, the challenge falls in don't care situation.

Example

The following word:

الله (U+0627 U+0644 U+0644 U+0647)

is decoded to:

ﺍﻟﻠﻪ (U+FE8D U+FEDF U+FEE0 U+FEEA)

The following word:

تكبر (U+062A U+0643 U+0628 U+0631)

is decoded to:

تكبر (U+FE97 U+FEDC U+FE92 U+FEAE)

The following word:

سلـام (U+0633 U+0644 U+0640 U+0627 U+0645)

is decoded to:

ﺳﻠـﺎﻡ (U+FEB3 U+FEE0 U+0640 U+FE8E U+FEE1)

The following word:

شيء (U+0634 U+064A U+0621)

is decoded to:

ﺷﻲﺀ (U+FEB7 U+FEF2 U+FE80)

JavaScript (ES6),  231 ... 148  146 bytes
I/O format: list of code points

a=>a.map(t=(c,i)=>c%32?(g=A=>n^c%49?g([x=n%32<26,k*x,x&=454642>>n++*25%54%26,x].map(x=>x&&++k)):A[t=t>1^2*(a[i+1]>1569)]||A[t^=2])(n=k=0)+65151:c)

Try it online!
a =>                             // a[] = input array
a.map(t = (c, i) =>              // for each code point c at position i in a[]:
  c % 32 ?                       //   if c is not 0x0640:
    ( g = A =>                   //     g is a recursive function taking a list A[]
        n ^ c % 49 ?             //       if we haven't reached the correct character:
          g(                     //         do a recursive call:
            [                    //           build a list describing the existence of:
              x = n % 32 < 26,   //           - isolated: if not in range 0x063B-0x0640
              k * x,             //           - final: same as isolated, except for the
                                 //             first entry which is undefined
              x &=               //           - initial: we use a lookup bit-mask
                454642 >> n++    //             with the following hash formula:
                * 25 % 54 % 26,  //               ((n * 25) mod 54) mod 26
              x                  //           - medial: same as initial
            ].map(x => x && ++k) //           turn it into a list of indices
          )                      //         end of recursive call
        :                        //       else:
          A[                     //         output the relevant entry from A[]:
            t =                  //           update t:
              t > 1 ^ 2 * (      //             (previous was initial or medial) XOR
                a[i + 1] > 1569  //             2 * (this is not the last letter
              )                  //             and the next letter is not 0x0621)
          ] ||                   //         if A[t] is not defined:
            A[t ^= 2]            //           use A[t ^ 2] instead
    )(n = k = 0)                 //     initial call to g with n = k = 0
    + 65151                      //     add 0xFE7F
  :                              //   else:
    c                            //     output c unchanged
)                                // end of map()


Building a Structured Outline In a fictional document management system, input documents are structured with weighted headings. Lowest weighted headings are the most important.

This is a sample document:

H1 All About Birds

H2 Kinds of Birds

H3 The Finch

H3 The Swan

H2 Habitats

H3 Wetlands

From this document we would like to produce an outline using nested ordered lists in HTML, which would look like this when rendered:

All About Birds

Kinds of Birds

The Finch
The Swan

Habitats

Wetlands

Your code only needs to take the input list and transform it into the expected data structure, which will be printed.

Jelly, 53 50 bytes

Ḋœṡ¥€⁶ZµḢVØ0jI>0ẋ"AƲị“
“
”żṪ“
“
”jⱮƊ

Try it online!

A monadic link taking a list of strings as input and outputting an HTML fragment with nested ordered lists. Should handle arbitrarily deep nesting of lists and return a syntactically valid HTML fragment.

Example:

H1 All About Birds
H2 Kinds of Birds
H3 The Finch
H3 The Swan
H2 Habitats
H3 Wetlands
H4 Types of wetlands
H5 Very wet wetland
H3 Coast
H1 All about fish
H2 Sharks

yields:

All About Birds

Kinds of Birds

The Finch

The Swan

Habitats

Wetlands

Types of wetlands

Very wet wetland

Coast

All about fish

Sharks

All About BirdsKinds of BirdsThe FinchThe SwanHabitatsWetlandsTypes of wetlandsVery wet wetlandCoastAll about fishSharks


How could I reduce the length of this code? I need to reduce the length of this code in Python 3 as much as possible (even if it will be less readable):

a,b,x,y=[int(i) for i in input().split()]
while 1:
 r=''
 if y<b:r='S';y+=1
 if y>b:r='N';y-=1
 if x<a:r+='E';x+=1
 if x>a:r+='W';x-=1
 print(r)

It's a map: you are on (x,y) and you need to go to (a,b). S for South, N for North, NE for North East and so on. After each turn I must tell where to go using print.

Update: This is what I've got now, but is there any way to shorten it further?

a,b,x,y=map(int,input().split())
while 1:c,d=(y>b)-(y<b),(x>a)-(x<a);print((' NS'[c]+' WE'[d]).strip());y-=c;x-=d

Python 3, 107

a,b,x,y=map(int,input().split())
A=abs(a-x);B=abs(b-y)
while 1:print('SN'[b>y][:B]+'WE'[a>x][:A]);A-=1;B-=1

A different strategy to generate the directions, tracking each coordinate's absolute displacement to the goal rather than the actual location.

For the horizontal direction, finds the absolute displacement A=abs(a-x) and direction character 'WE'[a>x]. Simulates going towards the goal by decrementing A and printing the direction character as long as we haven't already reached the goal coordinate (A>0). Does the same for vertical.


As Easy as One-Two-Three Write a program or function that takes in a positive integer. You can assume the input is valid and may take it as a string. If the number is any of

123
234
345
456
567
678
789

then output a truthy value. Otherwise, output a falsy value. For example, the inputs

1
2
3
12
122
124
132
321
457
777
890
900
1011
1230
1234

must all result in falsy output. (The input will not have leading zeroes so you needn't worry about things like 012.)

The shortest code in bytes wins.

Python, 24 bytes

range(123,790,111).count

An anonymous function that outputs 0 or 1. It creates the list [123, 234, 345, 456, 567, 678, 789] and counts how many times the input appears.
f=range(123,790,111).count

f(123)
=> 1
f(258)
=> 0


Horizontal graph of word length Input

A list of words separated by any number of spaces.

Output

A horizontal ASCII art graph, where the n-th line is composed by as many asterisks (*) as the n-th word is long.

Example usage

The > signals user input, you should not input it when testing the program.

> This is an example histogram of word length
****
**
**
*******
*********
**
****
******

> a aa aaa aaaa aaaaa
*
**
***
****
*****

> double space  example
******
*****
*******

Reference implementation

In case of doubt over the specification, the output of your program should match exactly that of the below program under all inputs.

puts gets.chomp.split.map{|word| '*' * word.length}.join("\n")

Retina, 5 + 3 = 8 bytes

 +
\n
.
*

Every line goes in its own file, so I've added 1 byte for each additional file. Also, the \n should be replaced with an actual newline.

Each pair of lines is a pattern-replacement pair.  + matches one or more spaces and replaces it with a newline. . matches any character except a newline, and it replaces that with a *. This is applied globally, so every character is replaced with a *.


Implement DFA/NFA/epsilon-NFA Write the shortest code that implements a:

DFA
NFA
epsilon-NFA

The program should accept as input:

a string(that we want to see if is accepted or not)
the delta function, represented in whichever way it's more convenient.
the "set" of final states of the automaton

And it should output Accepted! if the string is accepted by the automaton, and the string Not a chance! otherwise.

Note that all inputs should be taken from stdin or the command line.

The total points should be computed as (L1 + 2*L2 + 3*L3) / 6 where Li is the length, in bytes, of the code solving point i and the winner will be the answer with smallest score.

Edit: You can assume the starting state, so that it is not required as input.

The epsilon transitions can be labelled in any way you want.

Edit2: An example of input for the DFA:

0100
{'q_0': {'0': 'q_1', '1': 'q_0'}, 'q_1': {'0': 'q_2', '1': 'q_3'}, 'q_2': {'0': 'q_2', '1': 'q_3'}, 'q_3': {'1': 'q_0', '0': 'q_1'}}
{'q_2', 'q_3'}

Output:

Accepted!

An other input:

010010
{'q_0': {'0': 'q_1', '1': 'q_0'}, 'q_1': {'0': 'q_2', '1': 'q_3'}, 'q_2': {'0': 'q_2', '1': 'q_3'}, 'q_3': {'1': 'q_0', '0': 'q_1'}}
{'q_2', 'q_3'}

Output:

Not a chance!

I want to stress that you are free to use a different formatting for the inputs. Choose the simpler to "parse" in your target language. The above is simple to use in python since you can eval it to obtain the real objects.

Python, score = 138 1/6 = (79+108*2+178*3)/6

DFA

S,D,F=input()
s=1
for c in S:s=D[s,c]
print["Not a chance!","Accepted!"][F&s>0]

Input is a triple of string S, a delta function D, and final state mask F.  I number each state with a power of 2, so F is just the OR of each accepting state.  D is a map from (state,input char)->state.

example input (accepts all strings ending in b):

'abab',{(1,'a'):1,(1,'b'):2,(2,'a'):1,(2,'b'):2},2

NFA

S,D,F=input()
s=1
for c in S:
 t,s=s,0
 for a,b in D[c]:s|=t/a%2*b
print["Not a chance!","Accepted!"][F&s>0]

We number states as powers of 2 as before.  D is a map from input character to a list of transitions labeled by that character.

example input (accepts all strings ending in b):

'abab',{'a':[(1,1)],'b':[(1,1),(1,2)]},2

epsilon-NFA

S,D,F=input()
E={1:1}
for i in D[0]:
 for a,b in D[0]:E[a]=a|E.get(b,b)
s=E[1]
for c in S:
 t,s=s,0
 for a,b in D[c]:s|=t/a%2*E.get(b,b)
print["Not a chance!","Accepted!"][F&s>0]

Same as NFA, but with the additional 0 character listing the epsilon transitions.

example input (accepts all strings ending in b):

'abab',{'a':[(1,1)],'b':[(1,1),(1,2)],0:[(2,4)]},2


Tips for golfing in Jelly Jelly is a tacit, golf-oriented programming language by our very own Dennis. It’s popping up in answers here more and more often, beating other golf-y languages like Pyth and CJam, both by using its own code page and its powerful chain system to succinctly express programs.

Let’s collect some useful tips for golfing in Jelly. (As always, one tip per answer, please!)

String compression

  If you're looking for a more optimized/automatic string compressor, try this one.

Try it online!

A compressed string looks like “...», where the dots are a chunk of base-250-encoded data. The decompression algorithm is a bit complicated: the chunk is interpreted as a “mixed-base” integer, with divmod breaking off various parts of this integer and constructing a string out of them.

I’ve created a little Python 3 interface to compress Jelly strings:

import dictionary
code_page = '''¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑ×ØŒÞßæçðıȷñ÷øœþ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭụṿẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż«»‘’“”'''

class Compress(list):
    def character(self, c):
        if c in '\n\x7f¶':
            o = 95
        elif ' ' <= c <= '~':
            o = ord(c)-32
        else:
            raise ValueError(c + " is neither printable ASCII nor a linefeed.")
        self += [lambda z: 3*z+0, lambda z: 96*z+o]; return self
    def string(self, s):
        for c in s: self.character(c)
        return self
    def dictionary(self, w):
        ts = bool(self)
        if w[:1] == ' ': w = w[1:]; ts = not ts
        dct = dictionary.short if len(w) < 6 else dictionary.long
        W, sc = (w, 0) if w in dct else (w[:1].swapcase() + w[1:], 1)
        if W not in dct: raise ValueError(w + " isn't in the dictionary.")
        f = ts or sc; j = (2 if sc else 1) if ts else 0; i = dct.index(W)
        self += [lambda z: 3*z+2, lambda z: 3*z+j] if f else [lambda z: 3*z+1]
        self += [lambda z: 2*z+int(len(w) < 6), lambda z: len(dct)*z+i]
        return self
    def go(self):
        compressed = []; z = 0
        for f in self[::-1]: z = f(z)
        while z:
            c = z % 250
            if c == 0: c = 250
            z = (z - c) // 250
            compressed.append(code_page[c - 1])
        return '“{0}»'.format(''.join(compressed[::-1]))

Use the compressor as follows.

print(Compress()
      .dictionary('public')
      .dictionary(' static')
      .dictionary(' boolean')
      .string(' is')
      .dictionary('Power')
      .string('Of')
      .dictionary('Ten')
      .string('(')
      .dictionary('long')
      .dictionary(' input')
      .string(') {\n ')
      .dictionary(' return')
      .string('\n   ')
      .dictionary(' input')
      .string(' ==')
      .go())

Compress is a string builder:

.string(s) will insert raw, printable ASCII characters into the string.

(Each character costs about 0.827 compressed bytes.)
.dictionary(w) will look up a string in Jelly’s built-in dictionaries. You may begin the string with a single space, if you want one. If this needs to deviate from the normal string-adding behavior, or flip the capitalization of a dictionary word, it’ll add flags accordingly.

(Costs about 1.997 bytes for short words, 2.433 bytes for long words; if there are flags, add 0.199 bytes.)


Rosetta Stone Code Golf Challenge: Print Certain Numbers; all snippets must be same length Rosetta Stone Code Challenges are challenges where you must complete the task in as many languages as possible.

The Challenge

You will be given two numbers, n and s, in a list as input. The n will be a number you have to count up to. n will be any number from 2 to 10000. s will be the number you skip by when counting up to n. s will be from 1 to n/2 (half of n). If n was 600, s could not be greater 300. You have to output all of the numbers up to n skipping by s starting with 1. Each output number should either be on a newline, on the same line separated by spaces, or in a list.

The Twist

For this Rosetta Stone Code Challenge, each snippet you write the program in must be the same length. ie: If your Python program has 56 characters then your Java program must also be 56 characters. Spaces and comments do not count as characters. Variable/function names can't be more than 10 characters. Remember, this is also code golf, so try to keep your code short.

Example

Input

[100, 7]

Output

1
8
15
22
29
36
43
50
57
64
71
78
85
92
99

Note: Output could be in single line separated by spaces or list format

Winning Criterion

The winner will be decided by this formula:

numberOfLanguages/codeSize

codeSize is not the total code size but the average code size of a snippet.

The user with the highest score will win. ie: An answer with 4 languages and a size of 31 bytes would win over an answer with 7 languages and a size of 80 bytes. A winner will be chosen at 2:00 UTC on March 9, 2015.

Scoreboard

All scores are rounded to the nearest thousandth

Maltysen - 14 languages / 24 characters = 0.583 ---- Winner

mbomb007 - 15 languages / 29 characters = 0.517

Jakube - 5 languages / 11 characters = 0.455

Teun Pronk - 4 languages / 51 characters = 0.078

captncraig - 1 language / 56 characters = 0.018


Number Plate Golf: Recognition See also: Parsing

Introduction

You're working on a government programming team, who have been programming the speed cameras. However, the group of people who have programmed the speed calculator have taken up too much space, so you have to make the number plate recognition software as small as possible.

Challenge

Given an image of a number plate, return the text on the plate.

Number plates

The following are all of the characters which your program must recognise:

ABCDEFG

H1JKLMN0

PQRSTUVW

XYZ01234

56789

Note

On British number plates, the characters for I (i) and 1 (one) are the same and the characters for O (o) and 0 (zero) are the same. For that reason, always assume characters are the numbers. I.e. the following number plate is 10 (one zero):

Examples

C0D3 GLF

B3T4 DCY

M1NUS 15

YET1CGN

Other rules

Internet access and OCR libraries and functions are disallowed.

The number plates will always look identical to the ones shown above. All number plates will be roughly same size (there will be some inaccuracies due to cropping method).

If you require lossless PNG versions of any number plates, I will supply them to you.

Scoring

The shortest program in bytes wins.

All number plates are screenshots of the search bar at this site

Mathematica 1170 1270 1096 1059 650 528 570 551 525 498 bytes

The latest version saves 27 bytes by not requiring that the plate be "trimmed" before it is parsed.  The penultimate version saved 26 bytes by using only 10 of the original 24 sample points.

z=Partition;h@i_:=i~PixelValue~#/.{_,_,_,z_}:>⌈z⌉&/@z[{45,99,27,81,63,81,9,63,45,63,9,45,45,45,63,45,45,27,45,9},2];f@p_:=h/@SortBy[Select[p~ColorReplace~Yellow~ComponentMeasurements~{"Image","Centroid"},100<Last@ImageDimensions@#[[2,1]]<120&],#[[2,2,1]]&][[All,2,1]]/.Thread[IntegerDigits[#,2,10]&/@(z[IntegerDigits[Subscript["ekqeuiv5pa5rsebjlic4i5886qsmvy34z5vu4e7nlg9qqe3g0p8hcioom6qrrkzv4k7c9fdc3shsm1cij7jrluo", "36"]],4]/.{a__Integer}:> FromDigits[{a}])-> Characters@"BD54TARP89Q0723Z6EFGCSWMNVYXHUJKL1"]

122 bytes saved through LegionMammal978's idea of packing the long list of base 10 numbers as a single, base 36 number.  He pared another 20 bytes off the final code.

The jump from 528 to 570 bytes was due to additional code to ensure that the order of the letters returned corresponded to the order of the letters on the license plate. The centroid for each letter contains the x-coordinate, which reveals the relative positions of the letters along x.

Ungolfed Code

coordinates=Flatten[Table[{x,y},{y,99,0,-18},{x,9,72,18}],1];
h[img_] :=ArrayReshape[PixelValue[img, #] /. {_, _, _, z_} :>  ⌈z⌉  & /@ coordinates, {6, 4}];
plateCrop[img_]:=ColorReplace[ImageTrim[img,{{100,53},{830,160}}],Yellow];
codes={{{15,13,15,13,13,15},"B"},{{15,8,8,8,9,15},"C"},{{15,13,13,13,13,15},"D"},{{15,8,14,8,8,15},"E"},{{15,8,14,8,8,8},"F"},{{15,8,8,11,9,15},"G"},{{6,6,6,6,15,9},"A"},{{9,9,15,15,9,9},"H"},{{8,8,8,8,8,15},"L"},{{9,15,15,15,13,9},"M"},{{15,9,9,9,9,15},"0"},{{9,10,12,14,10,9},"K"},{{9,13,13,11,11,9},"N"},{{8,8,8,8,8,8},"1"},{{1,1,1,1,9,15},"J"},{{15,9,15,14,8,8},"P"},{{15,9,9,9,15,15},"Q"},{{15,9,15,14,10,11},"R"},{{15,8,12,3,1,15},"S"},{{9,15,6,6,6,6},"V"},{{15,6,6,6,6,6},"T"},{{9,15,15,15,15,15},"W"},{{9,9,9,9,9,15},"U"},{{9,14,6,6,14,9},"X"},{{9,14,6,6,6,6},"Y"},{{15,3,2,4,12,15},"Z"},{{15,9,9,9,9,15},"0"},{{8,8,8,8,8,8},"1"},{{15,1,3,6,12,15},"2"},{{15,1,3,1,9,15},"3"},{{2,6,6,15,2,2},"4"},{{7,12,14,1,1,15},"5"},{{15,8,14,9,9,15},"6"},{{15,1,2,2,6,4},"7"},{{15,9,15,9,9,15},"8"},{{15,9,15,1,9,15},"9"}};
decryptRules=Rule@@@codes;
isolateLetters[img_]:=SortBy[Select[ComponentMeasurements[plateCrop[img],{"Image","Centroid"}],ImageDimensions[#[[2,1]]][[2]]>100&],#[[2,2,1]]&][[All,2,1]]
f[plate_]:=FromDigits[#,2]&/@#&/@h/@isolateLetters[plate]/.decryptRules

Overview

The basic idea is to check whether a systematic sampling of pixels from the input image matches pixels from the same location on the bonafide images.  Much of the code consists of the bit signatures for each character,

The diagram shows the pixels that are sampled from the letters "J", "P","Q", and "R".

The pixel values can be represented as matrices. The dark, bold 1's correspond to black cells. The 0's correspond to white cells.

These are the decryption replacement rules for J  P  Q  R.

{1, 1, 1, 1, 9, 15} -> "J",
{15, 9, 15, 14, 8, 8} -> "P",
{15, 9, 9, 9, 15, 15} -> "Q",
{15, 9, 15, 14, 10, 11} -> "R"

It should be possible to understand why the rule for "0" is:

{15, 9, 9, 9, 9, 15} -> "0"

and thus distinguishable from the letter "Q".

The following shows the 10 points used in the final version.  These points are sufficient for identifying all of the characters.

What the functions do

plateCrop[img] removes the frame and left edge from the plate, makes the background white.  I was able to eliminate this function from the final version by selecting image components, possible letters  that were between 100 and 120 pixels high.

isolateLetters[img] removes the individual letters from the cropped image.

We can display how it works by showing where the cropped image, output from plateCrop goes as input for isolateLetters. The output is a list of individual characters.

Coordinates are 24 evenly distributed positions for checking the pixel color. The coordinates correspond to those in the first figure.

coordinates=Flatten[Table[{x,y},{y,99,0,-18},{x,9,72,18}],1];

{{9, 99}, {27, 99}, {45, 99}, {63, 99}, {9, 81}, {27, 81}, {45,
  81}, {63, 81}, {9, 63}, {27, 63}, {45, 63}, {63, 63}, {9, 45}, {27,
  45}, {45, 45}, {63, 45}, {9, 27}, {27, 27}, {45, 27}, {63, 27}, {9,
  9}, {27, 9}, {45, 9}, {63, 9}}

h converts the pixels to binary.

h[img_] :=ArrayReshape[PixelValue[img, #] /. {_, _, _, z_} :>  ⌈z⌉  & /@ coordinates, {6, 4}];

codes are the signature for each character.  The decimal values are abbreviations of the binary code for black (0) and White (1) cells. In the golfed version, base 36 is used.

codes={{{15, 9, 9, 9, 9, 15}, "0"}, {{8, 8, 8, 8, 8, 8}, "1"}, {{15, 1, 3,6,12, 15}, "2"}, {{15, 1, 3, 1, 9, 15}, "3"}, {{2, 6, 6, 15, 2, 2}, "4"}, {{7, 12, 14, 1, 1, 15},"5"}, {{15, 8, 14, 9, 9, 15}, "6"}, {{15, 1, 2, 2, 6, 4},"7"}, {{15, 9, 15, 9, 9, 15}, "8"}, {{15, 9, 15, 1, 9, 15},"9"}, {{6, 6, 6, 6, 15, 9}, "A"}, {{15, 13, 15, 13, 13, 15}, "B"}, {{15, 8, 8, 8, 9, 15}, "C"}, {{15, 13, 13, 13, 13, 15}, "D"}, {{15, 8, 14, 8, 8, 15}, "E"}, {{15, 8, 14, 8, 8, 8},"F"}, {{15, 8, 8, 11, 9, 15}, "G"}, {{9, 9, 15, 15, 9, 9}, "H"}, {{1, 1, 1, 1, 9, 15}, "J"}, {{9, 10, 12, 14, 10, 9}, "K"}, {{8, 8, 8, 8, 8, 15}, "L"}, {{9, 15, 15, 15, 13, 9}, "M"}, {{9, 13, 13, 11, 11, 9}, "N"}, {{15, 9, 15, 14, 8, 8}, "P"}, {{15, 9, 9, 9, 15, 15}, "Q"}, {{15, 9, 15, 14, 10, 11}, "R"}, {{15, 8, 12, 3, 1, 15}, "S"}, {{15, 6, 6, 6, 6, 6}, "T"}, {{9, 9, 9, 9, 9, 15}, "U"}, {{9, 15, 6, 6, 6, 6}, "V"}, {{9, 15, 15, 15, 15, 15}, "W"}, {{9, 14, 6, 6, 14, 9}, "X"}, {{9, 14, 6, 6, 6, 6}, "Y"}, {{15, 3, 2, 4, 12, 15}, "Z"}};

(* decryptRules are for replacing signatures with their respective character *)

decryptRules=Rule@@@codes;

f is the function that takes an image of a license plate and returns a letter.

f[plate_]:=FromDigits[#,2]&/@#&/@h/@isolate[plateCrop@plate]/.decryptRules;

{"A", "B", "C", "D", "E", "F", "G"}
{"H", "1", "J", "K", "L", "M", "N", "0"}
{"P", "Q", "R", "S", "T", "U", "V", "W"}
{"X", "Y", "Z", "0", "1", "2", "3", "4"}
{"5", "6", "7", "8", "9"}

Golfed

The code is shortened by using a single decimal number to represent all 24 bits (white or black) for each character. For example, the letter "J" uses the following replacement rule: 1118623 -> "J".

1118623 corresponds to

IntegerDigits[1118623 , 2, 24]

{0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1,
  1}

which can be repackaged as

ArrayReshape[{0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1}, {6, 4}]

{{0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {0, 0, 0, 1}, {1, 0, 0,
  1}, {1, 1, 1, 1}}

which is simply the matrix for "J" that we saw above.

%//MatrixForm

Another savings comes from representing the alphabet as "0123456789ABCDEFGHJKLMNPQRSTUVWXYZ" rather than as a list of letters.

Finally, all of the functions from the long version, except h, were integrated into the function f rather than defined separately.

h@i_:=ArrayReshape[i~PixelValue~#/.{_,_,_,z_}:>⌈z⌉&/@Join@@Table[{x,y},{y,99,0,-18},{x,9,72,18}],{6,4}];f@p_:=#~FromDigits~2&/@(Join@@@h/@SortBy[Select[p~ImageTrim~{{100,53},{830,160}}~ColorReplace~Yellow~ComponentMeasurements~{"Image","Centroid"},Last@ImageDimensions@#[[2,1]]>100&],#[[2,2,1]]&][[;;,2,1]])/.Thread[IntegerDigits[36^^1c01agxiuxom9ds3c3cskcp0esglxf68g235g1d27jethy2e1lbttwk1xj6yf590oin0ny1r45wc1i6yu68zxnm2jnb8vkkjc5yu06t05l0xnqhw9oi2lwvzd5f6lsvsb4izs1kse3xvx694zwxz007pnj8f6n,8^8]->Characters@"J4A51LUHKNYXVMW732ZTCGSFE60Q98PRDB"]


shortest progam to scan a line and print it using befunge! well, I'm newly introduced to befunge.
it seems to be an amazing language but a bit hard to start with! anyway after about 2 hours of hard work I've created a code which could read a line from stdin and write same line into stdout(I'm using line -1 as buffer in this code):

0> :~:a-#v_$$v vg-10:-1< >$>:#,_@
 ^+1p-10\<   >0>\:    #^_^

since I'm new to this language I wanted to know if there is a shorter code to do such a thing.
I'm currently using Rc/funge-98 v2 interpreter. note that none-trailing whitespaces are counted in your code.

Befunge-98, 4

~,#@

Try it online!

It works because ~ acts like r when there is no more input (credit to David Holderness for finding this in the funge-98 spec)


Evaluate the primorial of a number The primorial of a number is the product of all the primes until that number, itself included.

Take a number from STDIN as the input and evaluate its primorial, also known as the prime factorial.

Don't use libraries. Shortest code wins.

Test cases:

1 1
2 2
3 6
4 6
5 30
6 30
7 210
8 210
9 210
10 210
11 2310
12 2310
13 30030
14 30030
15 30030
16 30030
17 510510
18 510510
19 9699690


Monkey Island: The Head of the Navigator Warning: This challenge contains some mild spoilers for The Secret of Monkey Island.

Towards the end of the game, you're being led through the catacombs by a magically preserved head of a navigator:

You need its eyeball necklace, but the Head is reluctant to give it to you. One way to get it is just to keep begging:

  Guybrush: May I please have that necklace?
  Head: No, but thanks for asking so politely.
  Guybrush: Oh come on, pleeeeease?
  Head: You can beg all you want, but you can't have it.
  Guybrush: Pretty please?
  Head: You can beg all you want, but you can't have it.
  Guybrush: Pretty PRETTY please?
  Head: You can beg all you want, but you can't have it.
  Guybrush: Pretty please with sugar on top?
  Head: Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?

The Challenge

Write a full program which prints the above dialogue. The catch is that each time the program is called it should only print two lines (one pleading by Guybrush and the Head's response). E.g. if your submission is written in Python, usage should look like this:

$> python please.py
Guybrush: May I please have that necklace?
Head: No, but thanks for asking so politely.
$> python please.py
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.
$> python please.py
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.
$> python please.py
Guybrush: Pretty PRETTY please?
Head: You can beg all you want, but you can't have it.
$> python please.py
Guybrush: Pretty please with sugar on top?
Head: Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?

Invoking the program more than 5 times may result in undefined behaviour, so you could either loop, keep printing the last two lines or the program could even be broken after the 5th invocation.

You may write to a file in the working directory, or you can modify the source code of the program itself to keep track of invocations. In the latter case, your program must not depend its own filename. (In the former case, you can assume that your program's file name will not clash with any file names your program depends on.)

You must not assume a REPL-like environment or that any data is kept in RAM between invocations. E.g. if you answer in Mathematica, you have to assume that I quit the kernel between invocations.

This is code golf, the shortest answer (in bytes) wins. If your program depends on any additional files to exist before the first invocation, add its name and contents to your byte count.

Python, 224 + 97 + 1 = 322 characters

A most straightforward solution to start us all off. Thanks to gnibbler for helping me shave off 18 bytes!

n=0
print open('z','rb').read().decode('zip').split('|')[n]
open(__file__,'r+').write("n="+`n+1`)

Requires the file z to be present in the same directory (+1 for filename, +224 for file size):

$ hexdump z
0000000 9c78 d1ad 6e3d 30c3 050c bde0 78a7 165b
0000010 0723 92c8 48a9 b43a 8209 192c 9b29 0491
0000020 a2ab 9fa1 021a f87a 715a f46c d100 1026
0000030 1efc 1e41 5172 4721 c3b3 1527 607c 4c70
0000040 6191 87e8 0c91 7825 7b6e 2d47 dfef 4c8e
0000050 0edd d25f e540 8b54 8fbe 4bb8 c500 7ade
0000060 288d c418 c4d9 6cae 0f7f 7bab 6832 9be5
0000070 be21 7aa9 537d c2c2 24dd 25a3 c50f e41a
0000080 ca1c 1ff4 a7c9 a439 d5cc 9a4d b207 3fe9
0000090 0e7c 529c 4e79 3afc 7cef bf79 6f5e 672f
00000a0 8b9f 6d1d 8832 5359 1698 2482 92c3 3270
00000b0 43cd 560e 899b a4ad 1ab2 548a aed9 0bf1
00000c0 238f 0697 bd63 168f 36e9 b411 0a1e fef6
00000d0 eee8 1d64 1a28 aec9 10e3 7ff7 3a0b d9ab
00000e0

$ ls -l z
-rw-r--r--+ 1 Laxori mkpasswd 224 2014-09-22 22:35 z

You can generate z with the following:

>>> open('z','wb').write("""eJyt0T1uwzAMBeC9p3hbFiMHyJKpSDq0CYIsGSmbkQSroqGfGgJ6+FpxbPQA0SYQ/B5BHnJRIUez
wycVfGBwTJFh6IeRDCV4bntHLe/fjkzdDl/SQOVUi76PuEsAxd56jSgYxNnErmx/D6t7MmjlmyG+
qXp9U8LC3SSjJQ/FGuQcyvQfyac5pMzVTZoHsuk/fA6cUnlO/DrvfHm/Xm8vZ5+LHW0yiFlTmBaC
JMOScDLNQw5Wm4mtpLIailTZrvELjyOXBmO9jxbpNhG0Hgr2/ujuZB0oGsmu4xD3fws6q9k=""".decode('base64'))

Output:

$ python monkeyisland.py
Guybrush: May I please have that necklace?
Head: No, but thanks for asking so politely.
$ python monkeyisland.py
Guybrush: Oh come on, pleeeeease?
Head: You can beg all you want, but you can't have it.
$ python monkeyisland.py
Guybrush: Pretty please?
Head: You can beg all you want, but you can't have it.
$ python monkeyisland.py
Guybrush: Pretty PRETTY please?
Head: You can beg all you want, but you can't have it.
$ python monkeyisland.py
Guybrush: Pretty please with sugar on top?
Head: Oh, all right, you big baby. You can have it. Hey, what good's a necklace if you don't have shoulders?
$ python monkeyisland.py
Traceback (most recent call last):
  File "monkeyisland.py", line 2, in <module>
    print open('z','rb').read().decode('zip').split('|')[n]
IndexError: list index out of range


Don't get your head in a spin! Guidelines
Task
Write a function that takes in a sentence (a string, or list of characters) and reverses all the words that are greater than or equal to 5 in length.

Examples
"Hey fellow code golfers" -> "Hey wollef code sreflog"
"I aM noT a cAr" -> "I aM noT a cAr"
"I Am a tRaiN" -> "I Am a NiaRt"

Rules

Since this is code golf, the person with the least amount of bytes as their answer wins.

The input will have only one space between two adjacent words and there will be no trailing or leading spaces.

The output must also only have one space between two adjacent words and no trailing or leading spaces.

You can assume that the input will either be a string, or an array of characters. It WILL NOT be an array of words.

You must output either a string, or an array of characters. You MUST NOT output an array of words.

Words with punctuation marks can be seen as 5 or 4 letters, whichever you want

Capitalisation should stay the same for the same letters

Jelly,  12 10 8  7 bytes

-1 thanks to dylnan (use of repeat, ¡, as a replacement of if, ?, saving the need for identity, ¹.)

ḲṚṫ¡€5K

A monadic link taking and returning lists of characters.

Try it online!

How?

ḲṚṫ¡€5K - Link: list of characters
Ḳ       - split at spaces (gets words)
     5  - literal five
    €   - for €ach word:
   ¡    -   repeat:
  ṫ     -   ...number of times: tail (5th character on, if empty falsey->0, else truthy->1)
 Ṛ      -   ...action: reverse
      K - join with spaces

Previous 8: ḲṚ¹ṫ?€5K

Previous 10: ḲµṚ¹ṫ?5µ€K

Previous 12s: ḲµUµL€>4Tµ¦K and ḲµṚ¹L>¥?4µ€K


Roll the Alphabet into a Spiral Write a program or function that, when given n, will print a spiral n characters long made up of the Latin alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZ repeated as needed. This spiral should run through the alphabet only forwards.

Related to Alphabet Spiral, though the spiral runs through the alphabet forwards and backwards, and the spiral is constant.

Test cases

4   AB
    DC

40   UVWXYZ
     TGHIJA
    NSFABKB
    MREDCLC
    LQPONMD
    KJIHGFE

0

10  GHIJ
    FAB
    EDC

1000    UVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ
        TGHIJKLMNOPQRSTUVWXYZABCDEFGHIJA
        SFABCDEFGHIJKLMNOPQRSTUVWXYZABKB
        REZCDEFGHIJKLMNOPQRSTUVWXYZABCLC
        QDYBMNOPQRSTUVWXYZABCDEFGHIJCDMD
        PCXALEFGHIJKLMNOPQRSTUVWXYZKDENE
        OBWZKDEFGHIJKLMNOPQRSTUVWXALEFOF
        NAVYJCDMNOPQRSTUVWXYZABCDYBMFGPG
        MZUXIBCLCDEFGHIJKLMNOPQREZCNGHQH
        LYTWHABKBABCDEFGHIJKLMNSFADOHIRI
        KXSVGZAJAZGHIJKLMNOPQROTGBEPIJSJ
        JWRUFYZIZYFUVWXYZABCDSPUHCFQJKTK
        IVQTEXYHYXETQRSTUVWXETQVIDGRKLUL
        HUPSDWXGXWDSPUVWXYZYFURWJEHSLMVM
        GTORCVWFWVCROTGHIJAZGVSXKFITMNWN
        FSNQBUVEVUBQNSFABKBAHWTYLGJUNOXO
        ERMPATUDUTAPMREDCLCBIXUZMHKVOPYP
        DQLOZSTCTSZOLQPONMDCJYVANILWPQZQ
        CPKNYRSBSRYNKJIHGFEDKZWBOJMXQRAR
        BOJMXQRARQXMLKJIHGFELAXCPKNYRSBS
        ANILWPQZQPWVUTSRQPONMBYDQLOZSTCT
        ZMHKVOPYPONMLKJIHGFEDCZERMPATUDU
        YLGJUNOXONMLKJIHGFEDCBAFSNQBUVEV
        XKFITMNWVUTSRQPONMLKJIHGTORCVWFW
        WJEHSLMLKJIHGFEDCBAZYXWVUPSDWXGX
        VIDGRKJIHGFEDCBAZYXWVUTSRQTEXYHY
        UHCFQPONMLKJIHGFEDCBAZYXWVUFYZIZ
        TGBEDCBAZYXWVUTSRQPONMLKJIHGZAJA
        SFAZYXWVUTSRQPONMLKJIHGFEDCBABKB
        REDCBAZYXWVUTSRQPONMLKJIHGFEDCLC
        QPONMLKJIHGFEDCBAZYXWVUTSRQPONMD
                                LKJIHGFE

Rules

Your input will be a non-negative integer 0 <= n <= 1000, but your code should theoretically handle any non-negative integer.
Your output format may be in any sane format, with delimiters if necessary.
Rotations and reflections are equivalent.
Your alphabet may be uppercase or lowercase.
The empty spaces in your spiral may be filled in with whatever non-alphabetic nulls you see fit.
The spiral itself may be in any shape you see fit. Rectangular spirals work best with ASCII solutions, but graphical solutions may be shorter with circular spirals.
Leading and trailing spaces and newlines are allowed.
This is code golf. The shortest answer in bytes (or equivalent) wins.

As always, if anything is unclear or incorrect, please let me know in the comments. Good luck and good golfing!

Logo, 129 87 bytes

Graphical solution, implemented as function

This was built on Calormen.com's Logo interpreter.  The S function takes the number of characters as a parameter and draws them in a spiral.  The T function outputs letters upright to prevent them from rotating with the spiral..  I decided that it looked nicer (and golfed out 42 bytes) to omit correcting the letter orientation.  I also tightened up the spacing which did not change the byte count.  If you were to actually roll up an alphabet, it would look more like this anyway.

Updated Version (letters roll)

TO S:r
PU IF:r[REPEAT:r[LABEL CHAR((REPCOUNT-1)%26)+65
RT 99/SQRT(REPCOUNT)FD 12]]END

Invocation

Invoke as follows: S iterations

Sample output

S 1000

Old Version (letters always upright)

TO T:l:h
RT:h
LABEL CHAR(:l%26)+65
LT:h
END
TO S:r
PU IF:r[REPEAT:r[T REPCOUNT-1 90-HEADING
RT 95/SQRT(REPCOUNT)FD 15]]END

Old output removed to save space.  See it here.


Sum the deltas of my matrix Background
The deltas of an array of integers is the array formed by getting the differences of consecutive elements. For example, [1, 2, 4, 7, 3, 9, 6] has the following deltas: [1, 2, 3, -4, 6, -3].
We will now define the deltas of a matrix of integers as the deltas of each row and each column it contains.
As an example:
Row deltas:

1 2 3 4 │ => [1, 1, 1]
4 5 6 7 │ => [1, 1, 1]
7 1 8 2 │ => [-6, 7, -6]

Column deltas (the matrix' columns have been rotated into rows for simplicity):

1 4 7 │ => [3, 3]
2 5 1 │ => [3, -4]
3 6 8 │ => [3, 2]
4 7 2 │ => [3, -5]

Which gives us the following list of matrix deltas:
[[1, 1, 1], [1, 1, 1], [-6, 7, -6], [3, 3], [3, -4], [3, 2], [3, -5]]

And as we don't want them to be nested, we flatten that list:
[1, 1, 1, 1, 1, 1, -6, 7, -6, 3, 3, 3, -4, 3, 2, 3, -5]

Task
Your task is to sum all the deltas of a matrix given as input. Note that the matrix will only consist of non-negative integers.
Rules

All standard rules apply.

You may assume the matrix contains at least two values on each row and column, so the minimum  size will be 2x2.

You may take the matrix in any reasonable format, as long as you specify it.

You may not assume that the matrix is square.

If it might help you reduce your byte count, you may optionally take the number of rows and the number of columns as input as well (Looking at you C!).

This is code-golf, so the shortest code (in bytes), in each language wins!

Test Cases

Input  =>  Output

[[1, 2], [1, 2]]                                    => 2
[[8, 7, 1], [4, 1, 3], [5, 5, 5]]                   => -9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]                   => 24
[[9, 9, 9, 9, 9], [9, 9, 9, 9, 9]]                  => 0
[[1, 3, 14], [56, 89, 20], [99, 99, 99]]            => 256
[[1, 2, 3, 4], [4, 5, 6, 7], [7, 1, 8, 2]]          => 9
[[13, 19, 478], [0, 12, 4], [45, 3, 6], [1, 2, 3]]  => -72

Python 2, 42 bytes

lambda m:sum(r[-1]-r[0]for r in m+zip(*m))

An unnamed function taking a list of lists, m, and returning the resulting number.

Try it online!

How?

The sum of the deltas of a list is the last element minus the first, everything else just cancels:
(r[n]-r[n-1])+(r[n-1]-r[n-2])+...+(r[2]-r[1]) = r[n]-r[1]

The zip(*m) uses unpacking (*) of m to pass the rows of m as separate arguments to zip (interleave) and hence transposes the matrix. In python 2 this yields a list (of tuples, but that's fine), so we can add  (concatenate) it to (with) m, step through all our rows and columns, r, perform the above trick for each and just add up the results (sum(...)).


What's the shortest contiguous subset of ASCII you need to output the rest? The printable ASCII characters (hex codes 20 to 7E) in order are:
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

(Note that space is in there.)
This string clearly contains all the printable ASCII characters at least once in increasing order when read from left to to right, but not in decreasing order.
The string
REVERSED:~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"! NORMAL: !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~

contains all the printable ASCII characters at least once both in increasing and decreasing order. In other words, when the characters are valued with their numeric code, the longest increasing and longest decreasing subsequences have length 95 (the number of printable ASCII characters).
Challenge
Choose a contiguous subset of N printable ASCII characters, such as LMNOP (N = 5). Write a program using only those N characters whose output contains all 95 ASCII characters in increasing and decreasing order like the example above.
The winner is the submission with the lowest N. In case of ties the shortest code in bytes wins.
Notes

A contiguous subset means a set of the printable ASCIIs that all appear in an unbroken line, such as LMNOP or 89:;<=>.
Your contiguous subset may "loop around" from ~ to space, but this incurs a +3 penalty on N. So {|}~ has N = 4, but {|}~ ! has N = 6 + 3 = 9.
Your program may only contain the N printable ASCII characters from the contiguous subset you've selected. They do not all have to appear and may appear multiple times in any order. (All non-printable ASCII and all non-ASCII is not allowed. This means tabs and newlines are not allowed.)
Your output may only contain printable ASCII characters and must be less than 10000 characters long.
Your output's longest increasing and decreasing subsequences must both have length 95 (as explained above).
Output to stdout. There is no input.
N is a positive integer less than 96.


Translate your English source code into a foreign language I have noticed that there are a disproportionate number of computer languages based on English. I propose to fix this by translating existing computer languages into foreign languages!

Pick a computer language that uses English keywords/functions
Pick any natural* language other than English
Write a program that translates its own source code or any other program written using the same subset of keywords/functions into the other language
Post the source code and the output (the translated code)

Start your post with something like:

BASIC, French

or

BASIC, French - FONDAMENTAL

You don't have to translate the language name if you don't want to, it's just for fun!

You don't have to translate all the keywords/functions in your chosen language, just the ones you actually use in your source code. For instance, PHP has thousands so you definitely don't need to translate them all! Also, if you use any comments please do your best to translate them too! After your program has finished there should be no recognisable English words, unless they are appropriate for the foreign language. Words in strings should be translated too (meaning your translated program won't work on English source code anymore, even if it could be run!). Hopefully your program will make some sort of sense to a programmer who speaks the other language!

For example, if () {} elseif () {} else {} might become si () {} sinonsi () {} sinon {} in French! If you were translating Perl's elsif into French, maybe you'd drop the second n the way the second e is dropped in English: sinosi. In French else would more likely be autre but the alternative sinon (or else, otherwise) feels nicer to me!

Be creative! Try to capture the feel of both the computer and natural languages! Languages like Brainfuck, CJam, etc. that don't have English tokens can't be used. Languages like BASIC or COBOL are much more suitable. Use meaningful variable names and translate them too unless your language doesn't support variable names that can be English words.

You may post multiple answers, one for each combination of computer/natural language. You may not use a library or an external tool to do the translation! Your code should do the translation itself, not call something else that does translation! This is not Code Golf! If your program takes any input it must only be its own source code, if it reads from the disc it can only be the source file, etc.

* For the purposes of this challenge I will consider Esperanto, Lojban, Volapük, Interlingua, etc. as natural languages. You may not invent your own language for this challenge!

I have added a rule to prevent explicit quines. You may pick any subset of keywords/functions - even all of them - to translate. Your program must be able to translate itself as a minimum, i.e. if your original source includes the word print then adding print(42) anywhere to the input code (not your program itself) should still produce the correct results.

For example:

function translate() {
  ...
}
print(translate());

might become

fonction traduire() {
  ...
}
imprimer(traduire());

If the input is changed to

print(42);
function translate() {
  ...
}
print(translate());
print(42);

the output should then become

imprimer(42);
fonction traduire() {
  ...
}
imprimer(traduire());
imprimer(42);

Python, Koine Greek - Πύθων
My favorite programming language, in my favorite foreign language--perfect! And it doesn't hurt that the name is already Greek.
The translator program in Python 3 (thank goodness for native Unicode support):
with open(__file__, encoding="utf-8") as f:
    code = f.read()

replacements = [
    ("print", "γραψάτω"),
    ("input", "λαβέτω"),
    ("read", "ἀναγνώτω"),
    ("open", "ἀνεῳξάτω"),
    ("file", "βιβλίον"),
    ("import", "εἰσενεγκάτω"),
    ("encoding", "τύπος"),
    ("code", "λόγοι"),
    ("replacements", "νεόλογοι"),
    ("location", "τόπος"),
    ("old", "παλαιόν"),
    ("new", "νέον"),
    ("find", "εὑρέτω"),
    ("replace", "ἀλλαξάτω"),
    ("for", "ἕκαστον"),
    ("while", "ἐν τῷ"),
    ("elif", "εἰ δὲ"),
    ("if", "εἰ"),
    ("else", "εἰ δὲ μή"),
    ("is not", "οὐκ ἔστιν"),
    ("is", "ἔστιν"),
    ("not in", "οὐκ ἐν"),
    ("in", "ἐν"),
    ("and", "καὶ"),
    ("or", "ἢ"),
    ("not", "οὐ"),
    ("with", "μετὰ"),
    ("as", "ὡς"),
    ("re", "ῥλ"),
    ("sys", "σύς"),
    (":", "·"),
    ("ph", "φ"),
    ("th", "θ"),
    ("ch", "χ"),
    ("ps", "ψ"),
    ("a", "α"),
    ("b", "β"),
    ("c", "κ"),
    ("d", "δ"),
    ("e", "ε"),
    ("f", "φ"),
    ("g", "γ"),
    ("h", ""),
    ("i", "ι"),
    ("j", "ι"),
    ("k", "κ"),
    ("l", "λ"),
    ("m", "μ"),
    ("n", "ν"),
    ("o", "ο"),
    ("p", "π"),
    ("r", "ρ"),
    ("s ", "ς "),
    ("s.", "ς."),
    ("s,", "ς,"),
    ("s·", "ς·"),
    ("s", "σ"),
    ("t", "τ"),
    ("u", "ου"),
    ("v", "ου"),
    ("w", "ου"),
    ("x", "ξ"),
    ("y", "υ"),
    ("z", "ζ")
    ]

for old, new in replacements:
    if old == "for":
        location = 0
        while old in code[location:]:
            location = code.find(old, location)
            if code[location+3] != '"':
                location = code.find("in", location)
                code = code[:location] + "ἐκ" + code[location+2:]
            else:
                location += 1
    code = code.replace(old, new)

print(code)

Results of running the code on itself (with the big translation list redacted):
μετὰ ἀνεῳξάτω(__βιβλίον__, τύπος="ουτφ-8") ὡς φ·
    λόγοι = φ.ἀναγνώτω()

νεόλογοι = [
    ("γραψάτω", "γραψάτω"),
    ("λαβέτω", "λαβέτω"),
    ("ἀναγνώτω", "ἀναγνώτω"),
    ...
    ]

ἕκαστον παλαιόν, νέον ἐκ νεόλογοι·
    εἰ παλαιόν == "ἕκαστον"·
        τόπος = 0
        ἐν τῷ παλαιόν ἐν λόγοι[τόπος·]·
            τόπος = λόγοι.εὑρέτω(παλαιόν, τόπος)
            εἰ λόγοι[τόπος+3] != '"'·
                τόπος = λόγοι.εὑρέτω("ἐν", τόπος)
                λόγοι = λόγοι[·τόπος] + "ἐκ" + λόγοι[τόπος+2·]
            εἰ δὲ μή·
                τόπος += 1
    λόγοι = λόγοι.ἀλλαξάτω(παλαιόν, νέον)

γραψάτω(λόγοι)

Koine Greek is 2000 years old, so it was fun translating programming terms. Here's a few of my favorites:

βιβλίον = "scroll" (file)
γραψάτω = "write" (print)
λαβέτω = "take" (input)
εἰσενεγκάτω = "bring in" (import)
τύπος = "pattern, type" (encoding)
λόγοι/νεόλογοι = "words"/"new words" (code/replacements)
ἕκαστον... ἐκ = "each... from" (for ... in)
εἰ... εἰ δὲ... εἰ δὲ μή = "if... but if... but if not" (if ... elif ... else)
ἐν τῷ literally means "in the," but in certain contexts it can be an idiom for "when, while"
"Regular expression" became ῥήμα λογικόν, "rational/reasonable saying"; thus, the abbreviation re is ῥλ

Most of the words can be also found by searching on Wiktionary.
Some other salient features:

English programming uses a bunch of imperative verbs (print, read, replace). I suspect the ancient Greeks would feel a bit foolish talking to the computer like this, so I made them all third-person imperatives: "it must print," "it must read," "it must replace."
Greek punctuation is a bit different from English. I didn't go overboard with this, because I'm not sure what to replace the square brackets and underscores with, but I did swap out colons for ano teleia or "high period" (·).
For words that aren't in the list, I made sure to transliterate all the lowercase letters too. There isn't always a straight one-to-one correspondence; so for example, utf turns into ουτφ--which sounds about like "ootf" if you try to pronounce it.

This still leaves a lot to be desired grammar-wise. Greek is a much more highly inflected language than English, and my code isn't nearly sophisticated enough to get all the cases and numbers right. For example, ἕκαστον παλαιόν, νέον ἐκ νεόλογοι ought to read ἐκ νεολόγων, with the object of the preposition in the genitive case. However, I'm not about to put that much time into this! The look is sufficiently Greek (at least to the untrained eye) and the high periods add a nice touch. All in all, I'm pretty satisfied with the results.


Print a sinusoidal wave (vertically) Print a continuous sinusoidal wave scrolling vertically on a terminal. The program should not terminate and should continuously scroll down the wave (except until it is somehow interrupted). You may assume overflow is not a problem (i.e. you may use infinite loops with incrementing counters, or infinite recursion).

The wave should satisfy the following properties:

Amplitude = 20 chars (peak amplitude)
Period = 60 to 65 lines (inclusive)
The output should only consist of spaces, newline and |
After each line of output, pause for 50ms

Sample output:

                    |
                      |
                        |
                          |
                            |
                              |
                                |
                                 |
                                   |
                                    |
                                     |
                                      |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                     |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                       |
                     |
                   |
                 |
               |
             |
            |
          |
        |
       |
     |
    |
   |
  |
 |
 |
 |
 |
 |
 |
 |
  |
   |
    |
     |
      |
        |
         |
           |
             |
               |
                 |
                   |
                     |
                       |
                         |
                           |
                             |
                              |
                                |
                                  |
                                   |
                                    |
                                      |
                                      |
                                       |
                                        |
                                        |
                                        |
                                        |
                                        |
                                        |
                                       |
                                       |
                                      |
                                    |
                                   |
                                  |
                                |
                               |
                             |
                           |
                         |
                       |
                     |
                   |
                 |
               |
             |
           |
          |
        |
       |
     |
    |
   |
  |
 |
 |
 |
 |
 |
 |
 |
  |
   |
    |
     |
       |
        |
          |
            |
             |
               |
                 |
                   |

The above output should go on forever unless otherwise interrupted, e.g. SIGINT or SIGKILL, or closing terminal window, or you power off your machine, or the Sun swallows the Earth, etc.

Shortest code wins.

Note. I am aware of a similar problem on Display Scrolling Waves but this isn't exactly the same. In my problem, the wave is not to be scrolled "in place" - just output it on a terminal. Also, this is an ascii-art problem, so don't use Mathematica to plot it.

C, 74 73 70 69 67 characters

67 character solution with many good ideas from @ugoren & others:

i;main(j){main(poll(printf("%*c|\n",j=21+sin(i++*.1)*20,0),0,50));}

69 character solution with while loop instead of recursion:

i;main(j){while(printf("%*c|\n",j=21+sin(i++*.1)*20,0))poll(0,0,50);}

Approaching perl territory. :)