Limerick Hello World A rhyming program you write
Attempting to win the fight
For winning the contest and vote
It must compute "Hello World"
Then print it very polite

The most popular poem will win.

The requirements are:

The poem should be of 5 lines with rhymes AABBA
It can print whatever you want, but the output should contain "hello world" (uppercase/lowercase does not matter, quotes not included in the output)
Symbols are read aloud. For example, the fourth line above is read: It must compute quote hello world quote
Post below your code, on another code preview, the "read-aloud" version of your code for disambiguation on special symbols.

Excluded are poems:

including dead code, or characters which could be safely removed without changing the rhymes or the functionality
Using comments as a way to rhyme (except if there is a good reason for that)
using the same symbol as end of phrase for rhyme.

In case of a tie, programs outputting a poem will win. If there is still a tie, shorter programs will win.

New lines do not count. spaces, tabs and newlines are not read aloud.
For example, "Hello, world!" would be read aloud "double-quote hello comma world exclamation point double-quote".

Whitespace

A rhyming program I	wrote

this poem of whitespace and bloat

because newlines don't count

despite the amount

so deserves your sincerest upvote

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

Output:

Hello World

print 'the letter keys on my keyboard'
    print 'are sufficient to say Hello World
        print 'when I type in the dark'
            print 'sitting here in the park'
                print'feeling horribly,horribly bored'


Shortest way to reverse a number Write a function (or equivalent subprogram) to accept a single integer valued argument and return a (similarly typed) value found by reversing the order of the base-10 digits of the argument.

For example given 76543 return 34567

HTML 21 7 chars (1 char if I'm cheeky...)

&#8238;n

replace n with your number

JavaScript (ES6) 35

a=b=>b.split("").reverse().join("")


Most creative way to display 42 Douglas Adams was born on March 11, 1952, and died when he was just 49. In honor of this wonderful writer, I challenge you to display 42 in the most creative way possible.

You could print it in the log, via some convoluted method, or display it as ASCII art, or anything! Just come up with a creative method of displaying 42.

Because this a popularity-contest, whichever answer has the most upvotes by March 11, will be declared the winner.

Note: this is not a duplicate. The question it was marked as duplicating was a code-trolling question whose goal was to write code to output 42, not find the most creative way to display it.

Winner: grovesNL! With an astounding 813 votes! Congrats!

Honorable Mentions:

Mr Lister C 228  For the clever use of #define

David Carraher Mathematica 45  For the complicated and convoluted math function to achieve 42

Aschratt Windows Calculator 20  Because, well, it's windows calculator And definitely 1337.

f.rodrigues Python 17 Because of the clever use of using external programs. And MSPaint

Jason C LMGTFY 14 For the use of LMGTFY (Let Me Google That For You)

Trimsty Python 12 For the clever use of an error message to output 42.

Mukul Kumar C++ 7 For the nice ASCII output.

If you think that there is another answer worth putting on the list, please comment it!

PHP

echo '42';

Sorry, not sorry.

All you haters, this was meant to be sarcastic! But then again, sarcasm isn't allowed here.


Remove vowels without using too many different characters The challenge is to remove vowels (a, e, i, o, u) from string from STDIN (yes, I know, simple). You can expect that your program will be not ran with any arguments in argv.

Example:

This program will remove VOWELS.
So we can now speak without them.

Is changed to:

Ths prgrm wll rmv VWLS.
S w cn nw spk wtht thm.

There is a catch. The winning entry is decided basing on number of different bytes. For example a ab has three different bytes (a, b and space). If two or more entries will have this same ammount of different bytes, then fallback is done on number of bytes for those entries.

Python (23)

Somebody had to do it.

print filter(lambda x:x not in'aeiou',raw_input())


Convert degrees to one of the 32 points of the compass The 32-point compass is... interesting, to say the least.

By Denelson83 (Own work) [GFDL or CC-BY-SA-3.0], via Wikimedia Commons

Your challenge is to take a degree measure, and convert it into a direction on the 32-point compass.

Each direction is 11.25 (360 / 32) degrees farther than the previous. For example, N (north) is 0 degrees, NbE (north by east) is 11.25 degrees, NNE (north-northeast) is 22.5 degrees, etc.

As for how you're supposed to get the directions,

0 degrees is N, 90 degrees is E, 180 degrees is S, and 270 degrees is W.

These are called cardinal directions.

The halfway points between the cardinal directions are simply the cardinal directions they're between concatenated. N or S always go first, and W or E always are second.

These are called ordinal directions.

The halfway points between the cardinal and ordinal directions are the directions they're between concatenated, again, with a "-" in between. Cardinal directions go first, ordinal second.

These are called secondary-intercardinal directions.

The halfway points between secondary-intercardinal directions and other directions are the other directions "by" the cardinal direction they're closest to (other than the one directly next to them, of course).

I have no idea what these are called :P

If all this explanation hurts your brain as much as mine, you can refer to this chart:

1   North               N
2   North by east       NbE
3   North-northeast     NNE
4   Northeast by north  NEbN
5   Northeast           NE
6   Northeast by east   NEbE
7   East-northeast      ENE
8   East by north       EbN
9   East                E
10  East by south       EbS
11  East-southeast      ESE
12  Southeast by east   SEbE
13  Southeast           SE
14  Southeast by south  SEbS
15  South-southeast     SSE
16  South by east       SbE
17  South               S
18  South by west       SbW
19  South-southwest     SSW
20  Southwest by south  SWbS
21  Southwest           SW
22  Southwest by west   SWbW
23  West-southwest      WSW
24  West by south       WbS
25  West                W
26  West by north       WbN
27  West-northwest      WNW
28  Northwest by west   NWbW
29  Northwest           NW
30  Northwest by north  NWbN
31  North-northwest     NNW
32  North by west       NbW

Here is a more detailed chart and possibly better explanation of the points of the compass.

Your challenge is to take input in degrees, and output the full name of the compass direction it corresponds to, along with its abbreviation.

Test cases:

Input  Output
0      North N
23.97  North-northeast NNE
33.7   Northeast by north NEbN
73.12  East-northeast ENE
73.13  East by north EbN
219    Southwest by south SWbS
275    West W
276    West by north WbN
287    West-northwest WNW

All capitalization must be preserved, as in the test cases. Maximum number of decimal places is 2. All input numbers will be greater than or equal to 0, and less than 360. If a decimal point is present, there will be digits on both sides (you don't have to handle .1 or 1.).

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

Javascript 470 453 438 434 432 421 404

s=String;s.prototype.a=s.prototype.replace;var a=prompt()/11.25,a=a+0.5|0,b,k,c=a,d=c%8,c=c/8|0,e=["north","east","south","west"],f,g,h;f=e[c];g=e[(c+1)%4];h=f==e[0]|f==e[2]?f+g:g+f;b="1;1 by 2;1-C;C by 1;C;C by 2;2-C;2 by 1".split(";")[d].a(1,f).a(2,g).a("C",h);k=b.a(/north/g,"N").a(/east/g,"E").a(/south/g,"S").a(/west/g,"W").a(/by/g,"b").a(/[\s-]/g,"");b=b[0].toUpperCase()+b.slice(1);alert(b+" "+k)

You can copy this code to your console and execute it. It prompts you for the degrees input and outputs the result with alert();

Ungolfed Javascript can be found at this fiddle:
http://jsfiddle.net/AezL3/11

Python, 2103 1647 1103 1034 924 889 848 bytes

Very late, I know.  Thanks for the challenge, I am setting up a magnetometer for wind direction with my Pi, and wanted a 16 point of compass solution like this to feed into weather forecasting algorithms.  All my code is in Python, so here is version of the javascript solution already posted in Python, but with an extra twist that you can specify either 32, 16, or 8 points of the compass at variable j, and I have changed the offset of degHead in the statement before it, depending on the number of points.  I used a modified rename alogorithm (and used variables I could rename without corrupting the words!) to ensure I met the case requirements of the question.

I know this won't win, as Python is more wordy, and so am I.

Short version:

  def a(t,d,l):
    for i,j in d.items():
      if l:
        i=i.lower()
      t=t.replace(i,j)
    return t
  def b(h,q):
    p=32
    r=360
    h=(h+(r/q/2))/(r/p)
    j=int(int(int(h %8)%8/(p/q))*p/q)
    h=int(h/8)%4
    k=c.keys()
    u=['W','W by x','W-z','Z by w','Z','Z by x','X-z','X by w']
    d={}
    d['W']=list(k)[h]
    d['w']=d['W'].lower()
    d['X']=list(k)[(h+1)%4]
    d['x']=d['X'].lower()
    if(d['W']=='North' or d['W']=='South'):
      d['Z']=d['W']+d['x']
    else:
      d['Z']=d['X']+d['w']
    d['z']=d['Z'].lower()
    return a(u[j],d,0)
  def g(n):
    n=a(n,c,0)
    n=a(n,c,1)
    d={'by':'b',' ':'','-':''}
    return a(n,d,0)
  def v(m):
    while True:
      try:
        return float(input(m))
      except ValueError:
        print("?")
  c={'North':'N','East':'E','South':'S','West':'W'}
  while True:
    h=v("?")
    n=b(h,32)
    print(h,n,g(n))

Clear version

            import math
            import sys

            def calcPoint(degHead, points):
                maxPoints=32
                if points not in(8,16,32):
                    sys.exit("not a good question")
                degHead=(degHead+(360/points/2))/(360/maxPoints)
                j =int(int( int(degHead  % 8)%8/(maxPoints/points))*maxPoints/points)
                degHead = int(degHead / 8) % 4
                cardinal = ['North', 'East', 'South', 'West']
                pointDesc = ['W', 'W by x', 'W-z', 'Z by w', 'Z', 'Z by x', 'X-z', 'X by w']#vars not compass points
                W = cardinal[degHead]
                X = cardinal[(degHead + 1) % 4]
                w=W.lower()
                x=X.lower()
                if (W == cardinal[0] or W == cardinal[2]) :
                    Z =W + x
                else:
                    Z =X + w
                z=Z.lower()
                return pointDesc[j].replace('W', W).replace('X', X).replace('w', w).replace('x', x).replace('Z', Z).replace('z', z);

            def getShortName(name):
                return name.replace('North', 'N').replace('East', 'E').replace('South', 'S').replace('West', 'W').replace('north', 'N').replace('east', 'E').replace('south', 'S').replace('west', 'W').replace('by', 'b').replace(' ', '').replace('-', '')

            def input_number(msg, err_msg=None):
                while True:
                    try:
                        return float(input(msg))
                    except ValueError:
                        sys.exit("not a number")

            while True:
                headingCalib=input_number("input a number: ")
                print (headingCalib, end=' ')
                name = calcPoint(headingCalib,32) #degrees heading, points of compass 8,16 or 32)
                print (name, end=' ')
                shortName = getShortName(name)
                print (shortName)


As close to flat as possible Write a program or function that fulfills the following

Scores less than 101 bytes under normal code-golf rules
Takes no input1 and always outputs a single integer.
Every integer is a possible output.

Your score will be the probability of the most frequent integer occurring, with a lower scoring being the goal.  That is \$\mathrm{sup}\left\{P(x)|x\in\mathbb{Z}\right\}\$.

Since a few of these properties are not program decidable, you should be ready to provide a proof that your answer is valid and obtains the score it claims.

1 You may optionally take a stream of random bits, or a subroutine which produces random bits on each call as an input to provide randomness.  Each bit will be uniform and independent of other bits.

05AB1E, score 0.5 / 1000!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

bug fix thanks to FryAmTheEggman

+1 ! thanks to ExpiredData

 [₄!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!LΩ#¼]¾D±)Ω

(dont't) Try it online! (will timeout).

Try it online without the factorials

[           ]            # loop:
 ₄                       #  1000
  !!...!                 #  take the factorial, 88 times
        LΩ               #  pick a random number from 1 to that many
          #              #  if the number was 1, exit the loop
           ¼             #  increment counter_variable
             ¾           # after the loop: push counter_variable
              D±         # push its bitwise negation
                )        # wrap the two in a list
                 Ω       # pick a random element of that list

Any integer would work instead of 1000!!...!, so this approach could score as low as 0.5 / BB(89), where BB is 05AB1E's Busy Beaver function.

bash + linux, 1 / big number

cat /dev/random | hexdump -n `b` -ve '/1 "%02u"'

This program will print out 'b' bytes of decimal digits, where b is a program producing a random input number.

(edited to try to be more infinity-ish, although technically still limited by the bash shell)


Ring me when our cup noodles are ready I'm currently cooking us some cup noodles, but we're really sleepy at the moment. They'll be finished in 50 seconds from now, can you wake me up then?
Problem:
Write a program or function that waits 50 seconds of busy waiting (so that you too doesn't sleep) and then outputs at least 1 visible character to wake me up.
Busy waiting:
You can't use functions like sleep or delay or pause to wait for the 50 seconds, you have to keep checking the elapsed time.
Rules:

Your code must be somewhat consistent in time, between runs and between computers. A small error of +- 1 seconds is acceptable.
You can't output any visible characters between 1 and 50 seconds (let me sleep).
Whitespace characters (newline, space, tab, ...) are not considered visible characters for this challenge.
This is code-golf, so shortest code wins.

Octave, 22 21 bytes
Saved one byte by changing from while ... end to do ... until.
tic;do
until toc>50;1

tic starts a timer, while toc returns the number of decimal seconds since the last call to tic. We initiate a do - until loop, where we'll loop until toc>50, doing nothing inside the loop. The loop stops after 50 seconds, followed by ans = 1 on the screen.
Try it on TIO (time changed to 5 seconds) or paste it into Octave Online.

This may be foul play.
Bash, 24 Bytes
ping 192.0.0.8 -rqc50|wc

To verify +6 bytes
ping 192.0.0.8 -rqc50|tail -n2

192.0.0.8 is IPv4 dummy address.
It send packet for 50 times in one second interval because it would not be reached.


Ordinal string check Description :

Given a string as input, check if it is a valid ordinal number in English or not. If it is valid return truthy value otherwise return falsy value. (Suggested by @Arnauld. Thanks . Also by @JoKing)

For users who want to know about ordinal numbers go here :

https://www.mathsisfun.com/numbers/cardinal-ordinal-chart.html (Suggestion by : qwr)

Possible inputs :

21st ---> true
12nd ---> false
1nd ---> false
....

This is a code golf challenge so shortest code in each language will be the winner.

Examples :

console.log('12th' , true) // This evaluates to true
console.log('1st' , true) // also evaluates to true
console.log('21nd' , false) // returns false
console.log('11st' , false) // returns false
console.log('111199231923819238198231923213123909808th' , true) // true

Since a lot of people asked the question regarding whether input will be only valid strings or not :

All inputs will always be valid. i.e they will be in the form of string and consist of a digit (or number of digits) along with one of the four suffixes :

st , nd , rd , th

Python,  56  53 bytes
-3 thanks to  (use unique letter inclusion instead of penultimate character equality)

lambda v:'hsnrhhhhhh'[(v[-4:-3]!='1')*int(v[-3])]in v

An unnamed function.
Try it online!
How?
Since all input (here v) is guaranteed to be of the form \d*[st|nd|rd|th] we can just test whether a character exists in v which we expect to be there if it were correct (s, n, r, or h, respectively) - that is <getExpectedLetter>in v.
The last digit usually determines this:
v[-3]: 0 1 2 3 4 5 6 7 8 9
v[-2]: h s n r h h h h h h

...except when the penultimate digit is a 1, when all should end with th and hence our expected character must be h; to evaluate this we can take a slice (to avoid an index error occurring for inputs with no -4th character) v[-4:-3]. Since 0 maps to h already we can achieve the desired effect using multiplication prior to indexing into 'hsnrhhhhhh'.

Perl-compatible regular expression, 29 bytes
1.th|(?<!1)(1s|2n|3r)|[4-90]t

We accept th after any "teen" number, or after any digit other than 1..3.  For 1..3, we use a negative lookbehind to accept st, nd, or rd only when not preceded by 1.
Test program
#!/usr/bin/bash

ok=(✓ ❌)

for i
do grep -Pq '1.th|(?<!1)(1s|2n|3r)|[4-90]t' <<<"$i"; echo $i ${ok[$?]}
done

Results
1st ✓
1th ❌
2nd ✓
2th ❌
3rd ✓
3th ❌
4st ❌
4th ✓
11th ✓
11st ❌
12nd ❌
12th ✓
13th ✓
13rd ❌
112nd ❌
112th ✓
21nd ❌
32nd ✓
33rd ✓
21th ❌
21st ✓
11st ❌
111199231923819238198231923213123909808th ✓


Truncate consecutive character runs to n length The challenge

Given an input string, and an integer n - truncate any runs of consecutive characters to a maximum of n length. The characters can be anything, including special characters. The function should be case sensitive, and n can range from 0 to infinity.

Example inputs/outputs:

f("aaaaaaabbbccCCCcc", 2) //"aabbccCCcc"
f("aaabbbc", 1) //"abc"
f("abcdefg", 0) //""
f("aaaaaaabccccccccCCCCCC@", 4) //"aaaabccccCCCC@"

Scoring

The scoring is based on the number of bytes used.
Thus

function f(s,n){return s.replace(new RegExp("(.)\\1{"+n+",}","g"),function(x){return x.substr(0, n);});}

would be 104 points.

Happy golfing!

Edit: removed language restriction, but I still would love to see javascript answers

C, 81 78

Modifies the incoming string.

c,a;f(p,n)char*p;{char*s=p;for(;*p;s+=c<n)*s=*p++,a^*s?c=0:++c,a=*s;c=a=*s=0;}

Test Program

Requires two parameters, the first is the string to truncate, the second is the length limit.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, const char **argv)
{
    char *input=malloc(strlen(argv[1])+1);
    strcpy(input,argv[1]);
    f(input,atoi(argv[2]));
    printf("%s\n",input);
    free(input);
    return 0;
}

Explanation:

c,a;                 //declare two global integers, initialized to zero.
                     //c is the run length, a is the previous character
f(char*p,int n){...} //define function f to truncate input
char*s=p;            //copy p to s; p is source, s is destination
for(;*p              //while there is a source character
;s+=c<n)             //increment copied pointer if run is under the limit
*s=*p++,             //copy from source to destination, increment source
a^*s?c=0:++c,        //if previous character != current then run=0 else increment run
a=*s;                //previous character = current source character
c=a=*s=0;            //after loop, terminate destination string with NUL and reset c and a.

This works because the source pointer will always be equal to or greater than the destination pointer, so we can write over the string as we parse it.

TCC, 7 5 bytes

$~(;)

Input is a string and a number, seperated by space.

Try it online!

       | Printing is implicit
$~     | Limit occurence
  (;   | First part of input
    )  | Second part of input


Help!! How to do square root! Hi guys, for my class I need to make a number square root but it
  doesnt work !!HELLPP!

The challenge:

Write a function or program that will "make a number square root".

Note: This is code trolling. Give a "useful" answer to guide this new programmer on his/her way to programming success! Be creative!

Java

Wow, this is a complicated problem. I've never done a square root before. I've taken square roots, but I haven't done one. Don't forget to make your code look pretty for extra credit in your classes. Here's the code that makes a square root of a number inputted:

       import java
       .awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
       import javax
       .swing.JPanel;

public class SquareRoot {

    public static void main(String[] args) {
        java.util.Scanner scan = new java.util.Scanner(java.lang.System.in);
        System.out.print("Please input a number to take the square root of: ");
        int num = scan.nextInt();
        System.out.print("The answer is: ");
        System.out.print(sqrt(num));
    }

    static int sqrt(int n){int
    m = n ;while (n==n){m++;if
    (m * m
    > n&&m    <n        &&
    m>0 ){
    return     0+      0+
    m-1;}}       ;;  ;;
    return        0+0+
 n  == 0 ?       1+  1-
  m --:--m     +0     -0
   ;}//sqr

            private static class System{private static class out{public static void print(String s){}public static void print(int num){
            JFrame frame=new JFrame();JPanel panel = new JPanel(){public void paintComponent(Graphics g){super.paintComponent(g);;;;;g.
            setColor(new Color(0x964B00));g.fillRect(0,500,3000,3000);g.setColor(new Color(0xCC7722));g.fillRect(700,505,75,75);;;;;;g.
            fillRect
            (720,450,
            36,50);g.
            drawLine
            (700,581,
             690,600);
            g.drawLine
            (685,600,
            665,615);
            g.drawLine
            (685,600,
            695,610);
            g.drawLine
            (780,581,
             795,600);
            g.drawLine
            (790,600,
            775,615);
            g.drawLine
            (790,600,
            810,610);
            g.setColor
            (Color.
            GREEN);g.
            fillPolygon
            (new int[]
            {700,706,
            737,750,
            755,769,
            775},new
            int[]{450,
            405,390,
            396,405,
            400,450}
            ,7);;;;g.
            drawString
            (""+num,
            725,542);
}};         frame.add
(panel      );;//;;/
 ;;;        ;;;frame.
   setAlwaysOnTop
   (true);  frame.
   setDefaultCloseOperation
    (JFrame.DO_NOTHING_ON_CLOSE);
       frame.setVisible(true)
         ;;;;;;;;;}}}}

Trolls:

Obviously, the code is obfuscated.

Do I get bonus points for the art in the code?

The System.out.prints don't print to java.lang.System.out.print. They print to an inner class. The first two (which are supposed to print strings) don't do anything; the second one:
Outputs to a window. Sample output - do you see the square root (input is 100)?:
The window does nothing on close. Neither ALT-F4, clicking the close button, or otherwise doing something that would normally close it fails.
The window is always on top of other windows. Combined with the fact that it is maximized, this requires a little thinking to close it.
finds the sqrt by integer ADDITION from the number until we reach the correct number. This takes a long time since we wait for integer wrap-around. Because of this, it actually takes less time for larger numbers. For the sample output, it took 20 seconds.
Doesn't work properly for when the input is 0. Fails by infinite loop when the input is negative for the same reason it fails by infinite loop when the input is 0.
I trolled myself and spent ~2 hours coding this and aligning it.

Python

import math
print math.sqrt(input())


What base is this number in? Here's a nice easy challenge:

Given a string that represents a number in an unknown base, determine the lowest possible base that number might be in. The string will only contain 0-9, a-z. If you like, you may choose to take uppercase letters instead of lowercase, but please specify this. You must output this lowest possible base in decimal.

Here is a more concrete example. If the input string was "01234", it is impossible for this number to be in binary, since 2, 3, and 4 are all undefined in binary. Similarly, this number cannot be in base 3, or base 4. Therefore, this number must be in base-5, or a higher base, so you should output '5'.
Your code must work for any base between base 1 (unary, all '0's) and base 36 ('0-9' and 'a-z').
You may take input and provide output in any reasonable format. Base-conversion builtins are allowed. As usual, standard loopholes apply, and the shortest answer in bytes is the winner!
Test IO:
#Input          #Output
00000       --> 1
123456      --> 7
ff          --> 16
4815162342  --> 9
42          --> 5
codegolf    --> 25
0123456789abcdefghijklmnopqrstuvwxyz    --> 36

Python, 27 22 bytes

lambda s:(max(s)-8)%39

This requires the input to be a bytestring (Python 3) or a bytearray (Python 2 and 3).

Thanks to @AleksiTorhamo for golfing off 5 bytes!

Test it on Ideone.

How it works

We begin by taking the maximum of the string. This the code points of letters are higher than the code points of digits, this maximal character is also the maximal base 36 digit.

The code point of '0' – '9' are 48 – 57, so we must subtract 48 from their code points to compute the corresponding digits, or 47 to compute the lowest possible base. Similarly, the code points of the letters 'a' – 'z' are 97 – 122. Since 'a' represents the digit with value 10, we must subtract 87 from their code points to compute the corresponding digits, or 86 to compute the lowest possible base. One way to achieve this is as follows.

The difference between 97 and 58 (':', the character after '9') is 39, so taking the code points modulo 39 can achieve the subtraction. Since 48 % 39 = 9, and the desired result for the character '0' is 1, we first subtract 8 before taking the result modulo 39. Subtracting first is necessary since otherwise 'u' % 39 = 117 % 39 = 0.

c    n    n-8    (n-8)%39
0    48    40     1
1    49    41     2
2    50    42     3
3    51    43     4
4    52    44     5
5    53    45     6
6    54    46     7
7    55    47     8
8    56    48     9
9    57    49    10
a    97    89    11
b    98    90    12
c    99    91    13
d   100    92    14
e   101    93    15
f   102    94    16
g   103    95    17
h   104    96    18
i   105    97    19
j   106    98    20
k   107    99    21
l   108   100    22
m   109   101    23
n   110   102    24
o   111   103    25
p   112   104    26
q   113   105    27
r   114   106    28
s   115   107    29
t   116   108    30
u   117   109    31
v   118   110    32
w   119   111    33
x   120   112    34
y   121   113    35
z   122   114    36

Powershell, 62 bytes
function t($s){(($s[0..$s.Length]|measure -Max).Maximum-8)%39}

%39 @Dennis, of course :)


What's my name? Produce the name of the language indirectly Produce only the name of a programming language using only the facilities of the language itself. The name of the language can only be invoked indirectly, i.e., from non custom environment variables, built-in functions or methods or the interpreter/compiler of the language. Output should be the name of the language only.

One example would be:

$ awk --v | awk 'NR<2 { print $2}'  # GNU Awk 3.1.8
Awk

The answer I select will be the one with the most up votes. In case of a tie, the shortest golfed version (separate or the only given answer), will be the tie breaker.

Javascript : 48

alert((function Javascript(){}+"").substr(9,10))


Pi Calculation Code Golf The Challenge

You must calculate pi in the shortest length you can. Any language is welcome to join and you can use any formula to calculate pi. It must be able to calculate pi to at least 5 decimal places. Shortest, would be measured in characters. Competition lasts for 48 hours. Begin.

Note: This similar question states that PI must be calculated using the series 4 * (1 – 1/3 + 1/5 – 1/7 + …). This question does not have this restriction, and in fact a lot of answers here (including the most likely to win) would be invalid in that other question. So, this is not a duplicate.

Python3, 7

Runs in the interactive shell

355/113

Output: 3.1415929203539825, correct to 6 decimal places

And finally I have a solution that beats APL!

Oh, and in case you are wondering, this ratio is called the 密率 (literally "precise ratio"), and is proposed by the Chinese mathematician Zu Chongzhi (429-500 AD). A related wikipedia article can be found  here. Zu also gave the ratio 22/7 as the "rough ratio", and he is known to be the first mathematician to propose that 3.1415926 <= pi <=3.1415927

Matlab or Octave

0+pi

So short stackexchange won't let me post it without this. The output:

octave:5> 0+pi
ans =  3.14159265358979


-ENDED- Do something that looks like something else Write a snippet, a function, a programm, ... that is obfuscated in a way that it looks clear at the first sight that it does something else.

For example: write a bit of code that adds two number, but when you ask someone "what does it do?", he will tell you it prints "Hello, World!".

Rules

The code must be readable for someone who roughly knows the language you use (avoid intrinsic obfuscated language like APL, in your own interest).
The code must do something unexpected that the reader initially couldn't predict.
When you ask different readers, they must have the same (wrong) opinion about what the code does.

Rating

Please read other contestants' codes during maximum 10-20 seconds, just to have a good idea of what happens there.
Add a comment to the answer saying what you think the code does. If the answer you want to give is already there, simply +1 the comment. (if you miss that answer and add another comment, don't worry, it won't be counted as another answer).
The points will be awared this way: (maxFalseOpinion - goodGuess) / totalOpinion (see example below).
Rate other contestants with fairplay and don't comment your own code.
Only add useful comments. Avoid "I don't know" and "good one!", they are not taken into account for the rating, but it's the code and not the ratings that must be obfuscated.

Rating example

The snippet adds two numbers. The comments say:

(3) It displays "Hello, World!"
(1) It substracts 2 numbers.
(2) It adds 2 numbers.

The total amount of points is the maximum number of opinions (3) - the number of good guesses (2) divided by the total amount of guesses (3 + 1 + 2 = 6). Result: (3 - 2) / 6 = 1/6 = 16.67%.

MORE ABOUT POINTS

People seem to have some trouble figuring out the points.

Here is a perfect score:

printf('Hello World');

comments:
It displays the number of time you have clicked a button. (17 comments).
TOTAL: 17 comments

Score: (17 - 0)/17 = 1 = 100%

Here is a lame score:

printf('Hello World');

comments:
It prints "Hello World". (13 comments).
TOTAL: 13 comments

Score: (0 - 13) / 13 = -1 = -100%

Here is a not so bad score:

printf('Hello World');

comments:
It prints the user name. (2 comments).
It displays the current time (15 comments).
It returns what you entered without modification. (3 comment).
It prints "Hello World" (1 comment).
TOTAL: 21 comments

Score: (15 - 1) / 21 = 0.6667 = 66.67%
Explaining :
15 is the main guess, what people said the most.
1 is the correct number of guesses.
21 is the sum of all comments.

Javascript

var а;
a = 1;
а++;
alert( a );

Answer: It outputs 1. The comments below explain it pretty well - there are two different variables here, a - 'LATIN SMALL LETTER A' and а - 'CYRILLIC SMALL LETTER A'.

There was 1 correct answer, 50 people thought it outputs 2, and with a total of 52 answers, the score is (50 - 1) / 52 = 49 / 52 = 94,23%

Here it is for C

int main(){
    int a = 10;
    int b = 20;
    int c = a + b;
    printf("Hello World!");
}


Define a field with 256 elements A field in mathematics is a set of numbers, with addition and multiplication operations defined on it, such that they satisfy certain axioms (described in Wikipedia; see also below).

A finite field can have pn elements, where p is a prime number, and n is a natural number. In this challenge, let's take p = 2 and n = 8, so let's make a field with 256 elements.

The elements of the field should be consecutive integers in a range that contains 0 and 1:

-128 ... 127
0 ... 255
or any other such range

Define two functions (or programs, if that is easier), a(x,y) for abstract "addition", and m(x,y) for abstract "multiplication", such that they satisfy the field axioms:

Consistency: a(x,y) and m(x,y) produce the same result when called with same arguments
Closedness: The result of a and m is an integer in the relevant range
Associativity: for any x, y and z in the range, a(a(x,y),z) is equal to a(x,a(y,z)); the same for m
Commutativity: for any x and y in the range, a(x,y) is equal to a(y,x); the same for m
Distributivity: for any x, y and z in the range, m(x,a(y,z)) is equal to a(m(x,y),m(x,z))
Neutral elements: for any x in the range, a(0,x) is equal to x, and m(1,x) is equal to x
Negation: for any x in the range, there exists such y that a(x,y) is 0
Inverse: for any x≠0 in the range, there exists such y that m(x,y) is 1

The names a and m are just examples; you can use other names, or unnamed functions. The score of your answer is the sum of byte-lengths for a and m.

If you use a built-in function, please also describe in words which result it produces (e.g. provide a multiplication table).

Python 2, 11 + 45 = 56 bytes

Addition (11 bytes):

int.__xor__

Multiplication (45 bytes):

m=lambda x,y:y and m(x*2^x/128*283,y/2)^y%2*x

Takes input numbers in the range [0 ... 255]. Addition is just bitwise XOR, multiplication is multiplication of polynomials with coefficients in GF2 with Russian peasant.

And for checking:

a=int.__xor__
m=lambda x,y:y and m(x*2^x/128*283,y/2)^y%2*x

for x in range(256):
    assert a(0,x) == a(x,0) == x
    assert m(1,x) == m(x,1) == x

    assert any(a(x,y) == 0 for y in range(256))

    if x != 0:
        assert any(m(x,y) == 1 for y in range(256))

    for y in range(256):
        assert 0 <= a(x,y) < 256
        assert 0 <= m(x,y) < 256
        assert a(x,y) == a(y,x)
        assert m(x,y) == m(y,x)

        for z in range(256):
            assert a(a(x,y),z) == a(x,a(y,z))
            assert m(m(x,y),z) == m(x,m(y,z))
            assert m(x,a(y,z)) == a(m(x,y), m(x,z))

Brainfuck, 28 characters
Fortunately, standard Brainfuck does everything modulo 256.
Addition: [->+<], assumes that the inputs are in the first two positions of the tape, places the output in position 0
Multiplication: [->[->+>+<<]>[-<+>]<<], assumes that the inputs are in the first two positions of the tape, places the output in position 3


Make me a bad fade animation... please Your task is to, as the title discreetly suggests, make a bad fade animation of one word turning into a second word for yours truly.

What exactly is this "fade animation" you may ask?

To make a spectacular(ly bad) fade animation, you take two strings which will contain only printable ASCII characters. You start by printing your starting string (the first of the two). Then, you randomly pick a character in the original word and change it to the corresponding character in the word you want to animate to. When the words are of unequal length, you must pad them with spaces.

You keep on doing this until all of the characters have been changed, but you will not change the character at a certain index more than once. Here is an example i/o:

Hey -> Peeps
Hey    # original string
Hey s  # replace char at index 4
Hey s  # replace char at index 1
Pey s  # replace char at index 0
Pee s  # replace char at index 2
Peeps  # replace char at index 3

You must write a function or full program that changes a letter and then prints the new string at increments of one second. The input format is loose, but the output format is strict.

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

Some test cases (Form: init -> final):

Stringy -> Blingy
Banana -> Republic
United -> States
Make America -> Tissue box
I like walls -> I have small hands
Hello, -> world!

Reference implementation in Python 2:

import random
import time
def F(c,f):
    print c                                      # before we do stuff
    if len(c)>len(f):f+=" "*(len(c)-len(f))      # add padding part 1
    if len(f)>len(c):c+=" "*(len(f)-len(c))      # add padding part 2
    c, f = list(c), list(f)
    ai = [i for i in range(len(c))]              # a list for keeping track
    while len(ai) > 0:                           #  of available indices
        time.sleep(1)                            # 1 second pause...
        i = ai.pop(random.randint(0,len(ai)-1))  # get a random index and remove
        c[i] = f[i]                              #   it from the list
        print ''.join(c)                         # print the new string

Pyth - 25 24 bytes
Will refactor.
AC.tQdV.SU
G
=XGN@HN.d_1

Try it online here.

Ruby, 106 bytes

->a,b{puts a=a.ljust(l=[a.size,b.size].max);b=b.ljust l
[*0...l].shuffle.map{|i|sleep 1;a[i]=b[i];puts a}}

Try it online!
Oh, all right. No more rick rolling in the Try It Online link, if that's what's causing the downvotes. If not, please let me know what I'm doing wrong


From 0 to 2^n - 1 in POPCORN order ... Ah sorry, no popcorn here, just POPCNT.

Write the shortest program or function which takes in a number n and output all integers from 0 to 2n - 1, in ascending order of number of 1 bits in the binary representation of the numbers (popcount). No duplicates allowed.

The order of numbers with the same popcount is implementation-defined.

For example, for n = 3, all these output are valid:

0, 1, 2, 4, 3, 5, 6, 7
[0, 4, 1, 2, 5, 3, 6, 7]
0 4 2 1 6 5 3 7

The input and output format are implementation-defined to allow the use of language features to further golf the code. There are a few restrictions on the output:

The numbers must be output in decimal format.
The output must contain a reasonable separator between the numbers (trailing separator allowed, but not leading).

Line feed (\n), tab (\t), space, ,, ., ;, |, -, _, / are quite reasonable separator. I don't mind additional spaces for pretty printing, but don't use letter or digits as separators.
The numbers and separators can be surrounded by [ ], { } or any array or list notation.
Don't print anything else not stated above.

Bonus

Multiply your score by 0.5 if your solution can generate the number on the fly. The spirit of this bonus is that if you were to directly convert your printing solution to a generator, the generator only uses at most O(n) memory where n is the number of bits as defined above. (You don't have to actually convert your solution to generator). Note that while I impose n <= 28, the memory needed to store all numbers still grows exponentially, and a naive sorting solution would hog up at least 4 GB of memory at n = 28.

Please add some simple explanation of how your solution works before claiming this bonus.

Pyth, 9 bytes
osjN2U^2Q

order by the sum of the base 2 representation (jN2) over the range (U) of 2 ^ Q.
(Q = eval(input())).
Try it here.

Perl, 64/2 = 32

#!perl -ln
for$i(0..$_){$i-(sprintf"%b",$_)=~y/1//||print for 0..2**$_-1}

Simply iterate over the range [0..2^n-1] n + 1 times. In each iteration print only the numbers that have number of 1 bits equal to the iteration variable ($i). Bits are counted by counting 1's (y/1//) in the number converted to binary string with sprintf.

Test me.

Perl, 63

Sorting approach:

#!perl -l
print for sort{eval+(sprintf"%b-%b",$a,$b)=~y/0//dr}0..2**<>-1


Format microseconds as hours:minutes:seconds, etc The following is inspired by a question that came up on Stack Overflow today.

Given a number of microseconds, 0 <= n <= 86400000000 (e.g. 12345678900), output a formatted string hh:mm:ss:000:000, e.g. 03:25:45:678:900.

          0 -> '00:00:00:000:000'
12345678900 -> '03:25:45:678:900'
86400000000 -> '24:00:00:000:000'

I have a solution in Python in 209 bytes, but can it go lower?

Python 2, 82 79 bytes

n=input()
o=""
for k in[1000]*2+[60]*3:o=":%0*d"%(k%7/2,n%k)+o;n/=k
print o[1:]

Builds the string, iterating through a series of divmods. The only fancy bit is the %7/2, which maps 1000 -> 3 and 60 -> 2.

Ruby - 82 Bytes

puts (t=Time.at(0,gets.to_i)).strftime("%2H:%2M:%2S:%3L:#{(t.usec%1000).to_s.rjust(3,?0)}")


Print a letter Fibonacci Given N (2 <= N), print N lines of the letter Fibonacci series like this (i.e. N = 5)
First, start with a and b:

a
b

Next, add the two lines.

a
b
ab

Keep adding the last two lines.

a
b
ab
bab

Keep going...

a
b
ab
bab
abbab

And we're done.

Remmeber, this is code-golf, so the code with the fewest bytes wins.

Python 2, 41 bytes

Saved 3 bytes thanks to @xnor

a,b="ab";exec"print a;a,b=b,a+b;"*input()

Test on Ideone

Simply follows the recursive definition.


Cats go Meow, Cows go Moo Everyone knows that cats go meow, but what many don't realise is that caaaats go meeeeoooow. In fact, the length of the vowel sounds that the cat makes are dependant on the length of the vowel with which you address it.

In the same way, cows go moo, but coooows go moooooooo

Challenge

You are to write a program that takes as input, a word meaning cat, and a word meaning cow, determine the number of main vowels, and print one of the following strings, as appropriate:

C[]ts go M[]w
C[]ws go M[]

Where [] stands for the vowels, according to the following rules:

The number of e's and o's in "Meow" must both match the number of vowels found in the input word.
The number of o's in "Moo" must be double the number of vowels found in the input word.

The program must recognise the input words cat and cow. Input may use any capitalisation that is most convenient, but the output must be capitalised exactly as shown above.

Retina, 57 49 44 43 41 bytes

So close... :) Pyth...

.(.+).
$0s go M$1$1
+`aa(\w*$)
e$1ow
wo
o

Try it online.

Expects input to be capitalised like Caaat or Coooow.

Explanation

.(.+).
$0s go M$1$1

The regex matches the entire input, and captures the vowels in group 1 (we don't need anchors, because the match cannot fail and will greedily match the entire input). The substitution writes back that input, and appends s go M, followed by twice the vowels. For inputs Caaat and Coooow, we get:

Caaats go Maaaaaa
Coooows go Moooooooo

The output for cows is already correct. We just need to do something about those cats.

+`aa(\w*$)
e$1ow

The + tells Retina to repeat this stage as often as possible. The regex matches two as in the last part of the string (we ensure this with the $ anchor, so that we don't replace things inside Caaats). This will essentially match everything after M, as long as that part still has as. The two as are removed and the entire suffix after it is wrapped in e...ow:

Caaats go Meaaaaow
Caaats go Meeaaowow
Caaats go Meeeowowow

Finally, there are two many ws in the result, so we remove those that precede an o (to make sure we're not messing up the w in Coooows):

wo
o

And we're left with:

Caaats go Meeeooow

PHP, 170 164 161 157 bytes

preg_match("/(?i)c([ao]+)/",$argv[1],$e);
$n=strlen($e[1]);
$c=$e[1][0];
$a=($c=="a"?("ew"):("o"));
echo "M".str_repeat($a[0],$n).str_repeat("o",$n).$a[1]."\n";

Takes any capitalization whatsoever. CaAaT, coOOOw, whatever.

v2: don't really need [wt]$. also corrected char ct
v3: char ct was all wrong, condensed $a and $e assignment
v4: save 3 bytes on $af->$a
v5: save 4 bytes by onelining it (not shown)


Triangular code, triangular output For this challenge, submissions should be a program or function shaped like a right triangle, which produces a right triangle of the same size.

What is a right triangle?

For this challenge, a right triangle consists of 1 or more lines, each containing a number of characters (assume all non-newline characters are the same width) equal to that line number:

.
..
...
....

Trailing newlines are allowed.

The challenge:

Your code should form a right triangle, and output a right triangle with the same height made up of any non-newline characters.

As this is code golf, shortest answer in bytes per language wins.


Sort a list and write some English! Your boss managed to read the secret hidden message. He didn't end up firing you, though, he just made you a secretary and forbade you from writing code.

But you're a programmer. You need to write code. You must code.

Therefore, your code needs to look as similar to English as possible, make sense, and look as little like code as possible. Your code should take a list of integers (either in a function, or STDIN), and return that list sorted (returning it, or STDOUT).

Any language can be used, but I'm looking for the most creative solution, (kudos if your code looks like a business letter).

This is a popularity contest!

GolfScript

Dear Boss Man.
It came to my attention that my keyboard needs replacement; the keys required  to write the
symbols ~ $ ` . and } are not functioning properly.
It's very difficult to work like this! Please instruct the IT department to exchange the faulty
keyboard as soon as possible.
Sincerely,
Dennis

Try it online!
How it works

 Undefined tokens (e.g., most English words) are noops in GolfScript.

 . ; duplicates the input string and discards the copy.

  ~ $ evaluates the input string and sorts the resulting array.

 ` inspects the array (for pretty printing).

  . and duplicates the output string and discards the copy.

 } is a "super comment" since it is unmatched; everything following it is ignored.

C#

// Dear Boss Man,

/*i have a */public/*shed a*/ List /*of*/ <string>/*s
to*/ Sort /*for you on our internal website
please take a look at the */(List /*of*/ <string>/*s and*/ check){
/*them for company restrictions. please also */check /*the */.Sort();/*ing of the     list*/
/*furthermore could you please */return /*an email to me in which you state your */check/*ing state*/;}

// sincerely your slave Rob


Shortest, lexicographically smallest generating string A string x generates a string y if y is a substring of an infinite repeat of x.  For example abc generates bcabcab.

Write a program to find the shortest, lexicographically smallest string that will generate the input.  You are given on standard input a single line of text.  You should print the generating string to standard output.  For example:

input

bcabcabca

output

abc

Shortest code wins.  You may assume the input contains only the characters a-z (and a trailing newline if you want).

Ruby 1.9, 40 characters

gets;a=?a;a.next!until(a*~/$/)[$_];$><<a

Assumes the input is not terminated by a newline. Also it's probably ridiculously slow for larger results.

$ echo -n "bcabcabca" | ruby genlex.rb
abc
$ echo -n "barfoobarfoobarfoo" | ruby1.9 genlex.rb
arfoob

javascript 96 Chars.

var temp = {},len = str.length;
for(i in str)
temp[str[i]] = true;
Object.keys(temp).join("");

Working Plunkr


Debunking Stroustrup's debunking of the myth “C++ is for large, complicated, programs only” Stroustrup has recently posted a series of posts debunking popular myths about C++. The fifth myth is: “C++ is for large, complicated, programs only”. To debunk it, he wrote a simple C++ program downloading a web page and extracting links from it. Here it is:
#include <string>
#include <set>
#include <iostream>
#include <sstream>
#include <regex>
#include <boost/asio.hpp>

using namespace std;

set<string> get_strings(istream& is, regex pat)
{
    set<string> res;
    smatch m;
    for (string s; getline(is, s);)  // read a line
        if (regex_search(s, m, pat))
            res.insert(m[0]);              // save match in set
    return res;
}

void connect_to_file(iostream& s, const string& server, const string& file)
// open a connection to server and open an attach file to s
// skip headers
{
    if (!s)
        throw runtime_error{ "can't connect\n" };

    // Request to read the file from the server:
    s << "GET " << "http://" + server + "/" + file << " HTTP/1.0\r\n";
    s << "Host: " << server << "\r\n";
    s << "Accept: */*\r\n";
    s << "Connection: close\r\n\r\n";

    // Check that the response is OK:
    string http_version;
    unsigned int status_code;
    s >> http_version >> status_code;

    string status_message;
    getline(s, status_message);
    if (!s || http_version.substr(0, 5) != "HTTP/")
        throw runtime_error{ "Invalid response\n" };

    if (status_code != 200)
        throw runtime_error{ "Response returned with status code" };

    // Discard the response headers, which are terminated by a blank line:
    string header;
    while (getline(s, header) && header != "\r")
        ;
}

int main()
{
    try {
        string server = "www.stroustrup.com";
        boost::asio::ip::tcp::iostream s{ server, "http" };  // make a connection
        connect_to_file(s, server, "C++.html");    // check and open file

        regex pat{ R"((http://)?www([./#\+-]\w*)+)" }; // URL
        for (auto x : get_strings(s, pat))    // look for URLs
            cout << x << '\n';
    }
    catch (std::exception& e) {
        std::cout << "Exception: " << e.what() << "\n";
        return 1;
    }
}

Let's show Stroustrup what small and readable program actually is.

Download http://www.stroustrup.com/C++.html

List all links:
 http://www-h.eng.cam.ac.uk/help/tpl/languages/C++.html
 http://www.accu.org
 http://www.artima.co/cppsource
 http://www.boost.org
 ...

You can use any language, but no third-party libraries are allowed.
Winner
C++ answer won by votes, but it relies on a semi-third-party library (which is disallowed by rules), and, along with another close competitor Bash, relies on a hacked together HTTP client (it won't work with HTTPS, gzip, redirects etc.). So Wolfram is a clear winner. Another solution which comes close in terms of size and readability is PowerShell (with improvement from comments), but it hasn't received much attention. Mainstream languages (Python, C#) came pretty close too.
Comment on subjectivity
The most upvoted answer (C++) at the moment votes were counted was disqualified for not following the rules listed here in the question. There's nothing subjective about it. The second most upvoted question at that moment (Wolfram) was declared winner. The third answer's (Bash) "disqualification" is subjective, but it's irrelevant as the answer didn't win by votes at any point in time. You can consider it a comment if you like. Furthermore, right now the Wolfram answer is the most upvoted answer, the accepted one, and is declared winner, which means there's zero debate or subjectivity.

Wolfram

This feels like complete cheating

Import["http://www.stroustrup.com/C++.html", "Hyperlinks"]

So just add some honest parsing on top

Cases[
 Import["http://www.stroustrup.com/C++.html", "XMLObject"],
 XMLElement["a", {___, "href" -> link_, ___}, ___] :>
  link /; StringMatchQ[link, RegularExpression["((http://)?www([./#\\+-]\\w*)+)"]]
, Infinity]

Bash

 GET http://www.stroustrup.com/C++.html | grep -o "https\?://[^ \"]\+

needs libwww-perl and grep packages :)


Very Simple Grid Marks Write a program or function that takes in three positive integers, W, H, and N. Print or return a W×H grid of .'s where every Nth . in normal English reading order is replaced with an X.

For example, given W = 7, H = 3, N = 3, the grid is 7 characters wide and 3 high, and every third character reading from the top left is an X:

..X..X.
.X..X..
X..X..X

Similarly, if the input is W = 10, H = 4, N = 5, the output would be:

....X....X
....X....X
....X....X
....X....X

Notes

"Normal English reading order" means going left to right on each line, from the top line to the bottom.
When N is 1 then all the .'s will become X's.
You may use any two distinct printable ASCII characters in place of . and X.

If you use space ( ) then trailing spaces are not required when the result would be visually the same. (Empty lines are still required.)
You may not using something else in place of the newlines that shape the grid.

The exact input format and order of W, H, and N is not super important. Things like [H,W,N] or N\nW,H are alright.
A trailing newline in the output is fine.
The shortest code in bytes wins!

Examples

W = 5, H = 3, N = 1
XXXXX
XXXXX
XXXXX

W = 5, H = 3, N = 2
.X.X.
X.X.X
.X.X.

W = 5, H = 3, N = 3
..X..
X..X.
.X..X

W = 5, H = 3, N = 4
...X.
..X..
.X...

W = 5, H = 3, N = 5
....X
....X
....X

W = 5, H = 3, N = 6
.....
X....
.X...

W = 5, H = 3, N = 7
.....
.X...
...X.

W = 5, H = 3, N = 15
.....
.....
....X

W = 5, H = 3, N = 16 (or more)
.....
.....
.....

W = 1, H = 1, N = 1
X

W = 1, H = 1, N = 2 (or more)
.

W = 8, H = 6, N = 2
.X.X.X.X
.X.X.X.X
.X.X.X.X
.X.X.X.X
.X.X.X.X
.X.X.X.X

W = 8, H = 6, N = 3
..X..X..
X..X..X.
.X..X..X
..X..X..
X..X..X.
.X..X..X

W = 8, H = 6, N = 4
...X...X
...X...X
...X...X
...X...X
...X...X
...X...X

W = 8, H = 6, N = 7
......X.
.....X..
....X...
...X....
..X.....
.X......

W = 8, H = 6, N = 16
........
.......X
........
.......X
........
.......X

W = 37, H = 1, N = 4
...X...X...X...X...X...X...X...X...X.

W = 1, H = 10, N = 8
.
.
.
.
.
.
.
X
.
.

J, 9 5 bytes

$":&1

Uses spaces and 1's and expects input in the form H W f N

Explanation:

$":&1
   &1 bonds the fixed right argument 1 to ":
 ":   formats the right argument number (1) to take up left argument (N) number of cells
      padding with spaces, resulting  in "  1"
$     reshape to H-by-W with repeating the string if necessary

Usage:

   3 7 ($":&1) 3
  1  1
 1  1
1  1  1

Try it online here.

Java, 185 183 bytes

Thanks Thomas Kwa, for saving me 2 bytes!

interface B{static void main(String[] a){int w = Byte.parseByte(a[0]);for(int i=0;i++<w*Byte.parseByte(a[1]);)System.out.print((i%Byte.parseByte(a[2])>0?".":"X")+(i%w<1?"\n":""));}}

Ungolfed (ish):

interface A {
  static void main(String[] a) {
    int w = Byte.parseByte(a[0]);
    for(
      int i = 0;
      i++ < w*Byte.parseByte(a[1]);
    )
      System.out.print((
        i%Byte.parseByte(a[2]) > 0 ? "." : "X"
        )+(
        i%w < 1 ? "\n" : ""
      ));
  }
}

Usage:

$ java B 5 3 7
.....
.X...
...X.

Maybe java will win one day :P


Write program in your favorite language in another language The determined Real Programmer can write Fortran programs in any language.

from Real Programmers Don't Use Pascal

Your task is to write program in your programming language of choice, but you are allowed to use only another language. That is, throw away all coding conventions from one language and replace them with coding conventions from other language. The more the better. Make your program look as if it was written in another language.

For example, Python fan who hates Java could write following Python program in Java:

void my_function()                                                             {
    int i = 9                                                                  ;
    while(i>0)                                                                 {
        System.out.println("Hello!")                                           ;
        i = i - 1                                                              ;}}

Pascal enthusiast forced to use C could write this:

#define begin {
#define end }
#define then
#define writeln(str) puts(str)

if (i == 10) then
begin
    writeln("I hate C");
end

You have to write complete program. The program desn't have to do anything useful.

Good Luck. This is a popularity contest so the code with the most votes wins!

C in C++
#include <stdio.h>

int main(int argc, char** argv)
{
        printf("Hello world!\n");
        return 0;
}

HTML in PHP

First thing that came to my mind was apparently stolen by @toscho . But i'm not giving up yet,

<?php
echo "<title>This is HTML in PHP</title>";
echo "
Now Beat This!!!
";
echo "
";
?>


In Honor of Adam West Adam West passed away, and I'd like to honor his memory here on PPCG, though I doubt he knew of our existence. While there are many, many different things that this man is known for, none are more prominent than his role as the original batman. I'll always remember my step-father still watching the old-school Batman and Robin to this day. This challenge is simplistic in nature, not at all in line with the complicated man that was Adam West. However, it's the best I could come up with, as this is the most iconic image of the man's career.

I wanted to post this earlier, but I was waiting for someone to come up with something better.

Output the following (with or without trailing spaces/newlines):

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

This is code-golf, the lowest byte-count will win.

Wordfuck, 5761 2686 bytes

I guess using his name as a source code gets Adam West some honor.

adam west adam west adam_wes t_a dam_we st_a dam_ west adam west adam west adam west_ad am_west_a dam_we st ad am we st ad am we st ad am west_a dam_we st_a dam_ west_ada m_w est ada m_w est ada m_west_ adam west_a dam_west_ adam_we st_ ad am_west ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am_wes t_ adam_w est_ adam west adam west adam west adam west adam we st_adam west_ad am we st ad am we st adam_w es t_ ad am west_ad am we st ad am we st ad am we st_ada m_ west_ad am we st ad am west_a da m_west_ ad am we st ad am we st ad am west_a da m_ we st adam_w es t_adam_ west_ad am we st ad am west_a da m_ we st adam_we st ad am we st ad am we st ad am we st_ada m_ we st ad am we st adam_we st ad am we st ad am we st ad am we st_ada m_ we st ad am_wes t_ adam_we st_adam we st ad am_wes t_ ad am we st ad am_west ad am we st ad am we st ad am we st adam_w es t_ ad am we st ad am_west ad am we st ad am we st ad am we st adam_w es t_ ad am we st adam_w es t_adam_ west_ad am we st_ada m_ we st ad am we st ad am west_ad am we st ad am we st ad am west_a da m_ we st ad am we st ad am_west ad am we st ad am we st ad am_wes t_ ad am we st ad am we st adam_w es t_adam_ west_ad am west_a da m_ we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st_ada m_ west_ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am west_a da m_west_ ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am_wes t_ adam_we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st adam_w es t_adam_ west_ad am west_a da m_ we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st ad am we st_ada m_ west_ad am_west ad am west_a da m_ we st ad am_west ad am we st ad am we st_ada m_ we st ad am we st ad am we st ad am we st ad am we st ad am west_ad am we st ad am we st adam_w es t_ ad am we st_ada m_ west_ad am_west ad am we st adam_w es t_ ad am west_ad am we st ad am we st adam_w es t_ ad am_west ad am we st adam_w es t_ ad am we st_adam we st ad am west_a da m_ we st_adam we st ad am we st ad am_wes t_ ad am we st_ada m_ west_ad am_west ad am we st ad am we st_ada m_ we st_adam we st ad am we st ad am_wes t_ adam_we st ad am we st ad am_wes t_ ad am west_ad am we st ad am we st_ada m_ west_ad am we st ad am we st adam_w es t!

Try it online! (transpiled brainfuck)

Adam West singing (thanks @carusocomputing)


Build a working game of Tetris in Conway's Game of Life Here is a theoretical question - one that doesn't afford an easy answer in any case, not even the trivial one.

In Conway's Game of Life, there exist constructs such as the metapixel which allow the Game of Life to simulate any other Game-of-Life rule system as well. In addition, it is known that the Game of Life is Turing-complete.

Your task is to build a cellular automaton using the rules of Conway's game of life that will allow for the playing of a game of Tetris.

Your program will receive input by manually changing the state of the automaton at a specific generation to represent an interrupt (e.g. moving a piece left or right, dropping it, rotating it, or randomly generating a new piece to place onto the grid), counting a specific number of generations as waiting time, and displaying the result somewhere on the automaton. The displayed result must visibly resemble an actual Tetris grid.

Your program will be scored on the following things, in order (with lower criteria acting as tiebreakers for higher criteria):

Bounding box size — the rectangular box with the smallest area that completely contains the given solution wins.
Smaller changes to input — the fewest cells (for the worst case in your automaton) that need to be manually adjusted for an interrupt wins.
Fastest execution — the fewest generations to advance one tick in the simulation wins.
Initial live cell count — smaller count wins.
First to post — earlier post wins.

This began as a quest but ended as an odyssey.
Quest for Tetris Processor, 2,940,928 x 10,295,296
The pattern file, in all its glory, can be found here, viewable in-browser here.
This project is the culmination of the efforts of many users over the course of the past 1 & 1/2 years.  Although the composition of the team has varied over time, the participants as of writing are the following:

PhiNotPi
El'endia Starman
K Zhang
Blue (Muddyfish)
Cows quack (Kritixi Lithos)
Mego
Quartata

We would also like to extend our thanks to 7H3_H4CK3R, Conor O'Brien, and the many other users who have put effort into solving this challenge.
Due to the unprecedented scope of this collaboration, this answer is split in parts across multiple answers written by the members of this team.  Each member will write about specific sub-topics, roughly corresponding to the areas of the project in which they were most involved.
Please distribute any upvotes or bounties across all members of the team.
Table of Contents

Overview
Metapixels and VarLife
Hardware
QFTASM and Cogol
Assembly, Translation, and the Future
New Language and Compiler

Also consider checking out our GitHub organization where we've put all of the code we've written as part of our solution.  Questions can be directed to our development chatroom.

Part 1: Overview
The underlying idea of this project is abstraction.  Rather than develop a Tetris game in Life directly, we slowly ratcheted up the abstraction in a series of steps.  At each layer, we get further away from the difficulties of Life and closer to the construction of a computer that is as easy to program as any other.
First, we used OTCA metapixels as the foundation of our computer. These metapixels are capable of emulating any "life-like" rule.  Wireworld and the Wireworld computer served as important sources of inspiration for this project, so we sought to create a similar constuction with metapixels.  Although it is not possible to emulate Wireworld with OTCA metapixels, it is possible to assign different metapixels different rules and to build metapixel arrangements that function similarly to wires.
The next step was to construct a variety of fundamental logic gates to serve as the basis for the computer.  Already at this stage we are dealing with concepts similar to real-world processor design.  Here is an example of an OR gate, each cell in this image is actually an entire OTCA metapixel.  You can see "electrons" (each representing a single bit of data) enter and leave the gate.  You can also see all of the different metapixel types that we used in our computer: B/S as the black background, B1/S in blue, B2/S in green, and B12/S1 in red.

From here we developed an architecture for our processor.  We spent significant effort on designing an architecture that was both as non-esoteric and as easily-implementable as possible.  Whereas the Wireworld computer used a rudimentary transport-triggered architecture, this project uses a much more flexible RISC architecture complete with multiple opcodes and addressing modes.  We created an assembly language, known as QFTASM (Quest for Tetris Assembly), which guided the construction of our processor.
Our computer is also asynchronous, meaning that there is no global clock controlling the computer.  Rather, the data is accompanied by a clock signal as it flows around the computer, which means we only need to focus on local but not global timings of the computer.
Here is an illustration of our processor architecture:

From here it is just a matter of implementing Tetris on the computer.  To help accomplish this, we have worked on multiple methods of compiling higher-level language to QFTASM.  We have a basic language called Cogol, a second, more advanced language under development, and finally we have an under-construction GCC backend.  The current Tetris program was written in / compiled from Cogol.
Once the final Tetris QFTASM code was generated, the final steps were to assemble from this code to corresponding ROM, and then from metapixels to the underlying Game of Life, completing our construction.
Running Tetris
For those who wish to play Tetris without messing around with the computer, you can run the Tetris source code on the QFTASM interpreter.  Set the RAM display addresses to 3-32 to view the entire game. Here is a permalink for convenience: Tetris in QFTASM.
Game features:

All 7 tetrominoes
Movement, rotation, soft drops
Line clears and scoring
Preview piece
Player inputs inject randomness

Display
Our computer represents the Tetris board as a grid within its memory.  Addresses 10-31 display the board, addresses 5-8 display the preview piece, and address 3 contains the score.
Input
Input to the game is performed by manually editing the contents of RAM address 1.  Using the QFTASM interpreter, this means performing direct writes to address 1.  Look for "Direct write to RAM" on the interpreter's page.  Each move only requires editing a single bit of RAM, and this input register is automatically cleared after the input event has been read.
value     motion
   1      counterclockwise rotation
   2      left
   4      down (soft drop)
   8      right
  16      clockwise rotation

Scoring system
You get a bonus for clearing multiple lines in a single turn.
1 row    =  1 point
2 rows   =  2 points
3 rows   =  4 points
4 rows   =  8 points

Part 6: The Newer Compiler to QFTASM

Although Cogol is sufficient for a rudimentary Tetris implementation, it is too simple and too low-level for general-purpose programming at an easily readable level.
We began work on a new language in September 2016.
Progress on the language was slow due to hard to understand bugs as well as real life.

We built a low level language with similar syntax to Python, including a simple type system, subroutines supporting recursion and inline operators.
The compiler from text to QFTASM was created with 4 steps: the tokeniser, the grammar tree, a high level compiler and a low level compiler.

The tokeniser

Development was started using Python using the built in tokeniser library, meaning this step was pretty simple.
Only a few changes to the default output were required, including stripping comments (but not #includes).

The grammar tree

The grammar tree was created to be easily extendible without having to modify any source code.

The tree structure is stored in an XML file which includes the structure of the nodes that can make up the tree and how they're made up with other nodes and tokens.

The grammar needed to support repeated nodes as well as optional ones. This was achieved by introducing meta tags to describe how tokens were to be read.

The tokens that are generated then get parsed through the rules of the grammar such that the output forms a tree of grammar elements such as subs and generic_variables, which in turn contain other grammar elements and tokens.

Compilation into high level code

Each feature of the language needs to be able to be compiled into high level constructs. These include assign(a, 12)
 and call_subroutine(is_prime, call_variable=12, return_variable=temp_var). Features such as the inlining of elements are executed in this segment. These are defined as operators and are special in that they're inlined every time an operator such as + or % are used. Because of this, they're more restricted than regular code - they can't use their own operator nor any operator that relies on the one being defined.

During the inlining process, the internal variables are replaced with the ones being called. This in effect turns

operator(int a + int b) -> int c
    return __ADD__(a, b)
int i = 3+3

into

int i = __ADD__(3, 3)

This behaviour however can be detrimental and bug prone if the input variable and output variables point to the same location in memory. To use 'safer' behaviour, the unsafe keyword adjusts the compilation process such that additional variables are created and copied to and from the inline as needed.

Scratch variables and complex operations

Mathematical operations such as a += (b + c) * 4 cannot be calculated without using extra memory cells. The high level compiler deals with this by seperating the operations into different sections:

scratch_1 = b + c
scratch_1 = scratch_1 * 4
a = a + scratch_1

This introduces the concept of scratch variables which are used for storing intermediate information of calculations. They're allocated as required and deallocated into the general pool once finished with. This decreases the number of scratch memory locations required for use. Scratch variables are considered globals.

Each subroutine has its own VariableStore to keep a reference to all of the variables the subroutine uses as well as their type. At the end of the compilation, they're translated into relative offsets from the start of the store and then given actual addresses in RAM.

RAM Structure

Program counter
Subroutine locals
Operator locals (reused throughout)
Scratch variables
Result variable
Stack pointer
Stack
...

Low level compilation

The only things the low level compiler has to deal with are sub, call_sub, return, assign, if and while. This is a much reduced list of tasks that can be translated into QFTASM instructions more easily.

sub

This locates the start and end of a named subroutine. The low level compiler adds labels and in the case of the main subroutine, adds an exit instruction (jump to end of ROM).

if and while

Both the while and if low level interpreters are pretty simple: they get pointers to their conditions and jump depending on them. while loops are slightly different in that they're compiled as

...
condition
jump to check
code
condition
if condtion: jump to code
...

call_sub and return

Unlike most architectures, the computer we're compiling for doesn't have hardware support for pushing and popping from a stack. This means that both pushing and popping from the stack take two instructions. In the case of popping, we decrement the stack pointer and copy the value to an address. In the case of pushing, we copy a value from an address to the address at the current stack pointer and then incrementing.

All the locals for a subroutine are stored at a fixed location in RAM determined at compile time. To make recursion work, all the locals for a function are placed onto the stack at the start of a call. Then the arguments to the subroutine are copied to their position in the local store. The value of the return address is put onto the stack and the subroutine executes.

When a return statement is encountered, the top of the stack is popped off and the program counter is set to that value. The values for the locals of the calling subroutine are the popped off the stack and into their previous position.

assign

Variable assignments are the easiest things to compile: they take a variable and a value and compile into the single line: MLZ -1 VALUE VARIABLE

Assigning jump targets

Finally, the compiler works out the jump targets for labels attached to instructions. The absolute position of labels is determined and then references to those labels are replaced with those values. Labels themselves are removed from the code and finally instruction numbers are added to the compiled code.

Example step by step compilation

Now that we've gone through all the stages, let's go through an actual compilation process for an actual program, step by step.

#include stdint

sub main
    int a = 8
    int b = 12
    int c = a * b

Ok, simple enough. It should be obvious that at the end of the program, a = 8, b = 12, c = 96. Firstly, lets include the relevant parts of stdint.txt:

operator (int a + int b) -> int
    return __ADD__(a, b)

operator (int a - int b) -> int
    return __SUB__(a, b)

operator (int a < int b) -> bool
    bool rtn = 0
    rtn = __MLZ__(a-b, 1)
    return rtn

unsafe operator (int a * int b) -> int
    int rtn = 0
    for (int i = 0; i < b; i+=1)
        rtn += a
    return rtn

sub main
    int a = 8
    int b = 12
    int c = a * b

Ok, slightly more complicated. Let's move onto the tokeniser and see what comes out. At this stage, we'll only have a linear flow of tokens without any form of structure

NAME NAME operator
LPAR OP (
NAME NAME int
NAME NAME a
PLUS OP +
NAME NAME int
NAME NAME b
RPAR OP )
OP OP ->
NAME NAME int
NEWLINE NEWLINE
INDENT INDENT
NAME NAME return
NAME NAME __ADD__
LPAR OP (
NAME NAME a
COMMA OP ,
NAME NAME b
RPAR OP )
...

Now all the tokens get put through the grammar parser and outputs a tree with the names of each of the sections. This shows the high level structure as read by the code.

GrammarTree file
 'stmts': [GrammarTree stmts_0
  '_block_name': 'inline'
  'inline': GrammarTree inline
   '_block_name': 'two_op'
   'type_var': GrammarTree type_var
    '_block_name': 'type'
    'type': 'int'
    'name': 'a'
    '_global': False

   'operator': GrammarTree operator
    '_block_name': '+'

   'type_var_2': GrammarTree type_var
    '_block_name': 'type'
    'type': 'int'
    'name': 'b'
    '_global': False
   'rtn_type': 'int'
   'stmts': GrammarTree stmts
    ...

This grammar tree sets up information to be parsed by the high level compiler. It includes information such as structure types and attributes of a variable. The grammar tree then takes this information and assigns the variables that are needed for the subroutines. The tree also inserts all the inlines.

('sub', 'start', 'main')
('assign', int main_a, 8)
('assign', int main_b, 12)
('assign', int op(*:rtn), 0)
('assign', int op(*:i), 0)
('assign', global bool scratch_2, 0)
('call_sub', '__SUB__', [int op(*:i), int main_b], global int scratch_3)
('call_sub', '__MLZ__', [global int scratch_3, 1], global bool scratch_2)
('while', 'start', 1, 'for')
('call_sub', '__ADD__', [int op(*:rtn), int main_a], int op(*:rtn))
('call_sub', '__ADD__', [int op(*:i), 1], int op(*:i))
('assign', global bool scratch_2, 0)
('call_sub', '__SUB__', [int op(*:i), int main_b], global int scratch_3)
('call_sub', '__MLZ__', [global int scratch_3, 1], global bool scratch_2)
('while', 'end', 1, global bool scratch_2)
('assign', int main_c, int op(*:rtn))
('sub', 'end', 'main')

Next, the low level compiler has to convert this high level representation into QFTASM code. Variables are assigned locations in RAM like so:

int program_counter
int op(*:i)
int main_a
int op(*:rtn)
int main_c
int main_b
global int scratch_1
global bool scratch_2
global int scratch_3
global int scratch_4
global int <result>
global int <stack>

The simple instructions are then compiled. Finally, instruction numbers are added, resulting in executable QFTASM code.

0. MLZ 0 0 0;
1. MLZ -1 12 11;
2. MLZ -1 8 2;
3. MLZ -1 12 5;
4. MLZ -1 0 3;
5. MLZ -1 0 1;
6. MLZ -1 0 7;
7. SUB A1 A5 8;
8. MLZ A8 1 7;
9. MLZ -1 15 0;
10. MLZ 0 0 0;
11. ADD A3 A2 3;
12. ADD A1 1 1;
13. MLZ -1 0 7;
14. SUB A1 A5 8;
15. MLZ A8 1 7;
16. MNZ A7 10 0;
17. MLZ 0 0 0;
18. MLZ -1 A3 4;
19. MLZ -1 -2 0;
20. MLZ 0 0 0;

The Syntax

Now that we've got the bare language, we've got to actually write a small program in it. We're using indentation like Python does, splitting logical blocks and control flow. This means whitespace is important for our programs. Every full program has a main subroutine that acts just like the main() function in C-like languages. The function is run at the start of the program.

Variables and types

When variables are defined the first time, they need to have a type associated with them. The currently defined types are int and bool with the syntax for arrays defined but not the compiler.

Libraries and operators

A library called stdint.txt is available which defines the basic operators. If this isn't included, even simple operators won't be defined. We can use this library with #include stdint. stdint defines operators such as +, >> and even * and %, neither of which are direct QFTASM opcodes.

The language also allows QFTASM opcodes to be direct called with __OPCODENAME__.

Addition in stdint is defined as

operator (int a + int b) -> int
    return __ADD__(a, b)

Which defines what the + operator does when given two ints.


Make a circle illusion animation Your job is to animate this circle illusion. It looks like the points rotating inside of the circle, but they are actually just moving in straight lines.

Criterias

The result has to be animated. The way you do the animation is irrelevant, it can generate a .gif, it can draw to a window, some device screen or whatever.
This is a popularity contest, so you might want to add some additional features to your program to get more upvotes, for example varying the number of points.
The winner is the most upvoted valid answer 7 days after the last valid submission.
The answers that will actually implement points moving on straight lines and not another way around are more welcomed

Python 3.4

Using the turtle module. The turtles are different colours and they always face in the same direction, so they can be easily seen to be moving along straight lines by just focusing on one of them. Despite this the circle illusion is still strong.

The illusion still seems quite strong even with just 3 or 4 turtles:

The framerate is reduced considerably for all of these GIF examples, but it doesn't seem to detract from the illusion. Running the code locally gives a smoother animation.

import turtle
import time
from math import sin, pi
from random import random

def circle_dance(population=11, resolution=480, loops=1, flip=0, lines=0):
    population = int(population)
    resolution = int(resolution)
    radius = 250
    screen = turtle.Screen()
    screen.tracer(0)
    if lines:
        arrange_lines(population, radius)
    turtles = [turtle.Turtle() for i in range(population)]
    for i in range(population):
        dancer = turtles[i]
        make_dancer(dancer, i, population)
    animate(turtles, resolution, screen, loops, flip, radius)

def arrange_lines(population, radius):
    artist = turtle.Turtle()
    for n in range(population):
        artist.penup()
        artist.setposition(0, 0)
        artist.setheading(n / population * 180)
        artist.forward(-radius)
        artist.pendown()
        artist.forward(radius * 2)
    artist.hideturtle()

def make_dancer(dancer, i, population):
    dancer.setheading(i / population * 180)
    dancer.color(random_turtle_colour())
    dancer.penup()
    dancer.shape('turtle')
    dancer.turtlesize(2)

def random_turtle_colour():
    return random() * 0.9, 0.5 + random() * 0.5, random() * 0.7

def animate(turtles, resolution, screen, loops, flip, radius):
    delay = 4 / resolution      # 4 seconds per repetition
    while True:
        for step in range(resolution):
            timer = time.perf_counter()
            phase = step / resolution * 2 * pi
            draw_dancers(turtles, phase, screen, loops, flip, radius)
            elapsed = time.perf_counter() - timer
            adjusted_delay = max(0, delay - elapsed)
            time.sleep(adjusted_delay)

def draw_dancers(turtles, phase, screen, loops, flip, radius):
    population = len(turtles)
    for i in range(population):
        individual_phase = (phase + i / population * loops * pi) % (2*pi)
        dancer = turtles[i]
        if flip:
            if pi / 2 < individual_phase <= 3 * pi / 2:
                dancer.settiltangle(180)
            else:
                dancer.settiltangle(0)
        distance = radius * sin(individual_phase)
        dancer.setposition(0, 0)
        dancer.forward(distance)
    screen.update()

if __name__ == '__main__':
    import sys
    circle_dance(*(float(n) for n in sys.argv[1:]))

For contrast here are some that really do rotate:

...or do they?

The code can be run with 5 optional arguments: population, resolution, loops, flip and lines.

population is the number of turtles
resolution is the time resolution (number of animation frames per repetition)
loops determines how many times the turtles loop back on themselves. The default of 1 gives a standard circle, other odd numbers give that number of loops in the string of turtles, while even numbers give a string of turtles disconnected at the ends, but still with the illusion of curved motion.
flip if non-zero causes the turtles to flip direction for their return trip (as suggested by aslum so that they are never moving backwards). As default they keep a fixed direction to avoid the visual distraction at the endpoints.
lines if non-zero displays the lines on which the turtles move, for consistency with the example image in the question.

Examples with flip set, with and without lines. I've left my main example above without flip as I prefer not to have the sporadic jump, but the edge of the circle does look smoother with all the turtles aligned, so the option is there for people to choose whichever style they prefer when running the code.

It might not be immediately obvious how the images above were all produced from this same code. In particular the image further up which has a slow outer loop and a fast inner loop (the one that looks like a cardioid that someone accidentally dropped). I've hidden the explanation of this one below in case anyone wants to delay finding out while experimenting/thinking.

   The animation with an inner and outer loop of different sizes was created by setting the number of loops to 15 and leaving the number of turtles at 23 (too low to represent 15 loops). Using a large number of turtles would result in 15 clearly defined loops. Using too few turtles results in aliasing (for the same reason as in image processing and rendering). Trying to represent too high a frequency results in a lower frequency being displayed, with distortion.

Trying out different numbers I found some of these distortions more interesting than the more symmetrical originals, so I wanted to include one here...

PICO-8, 271 chars
camera(-64,-64)p=8::_::s=p.." lines"cls(7)circfill(0,0,50,0)for l=0,.5,.5/p do
u=flr(50*cos(l))v=flr(50*sin(l))line(u,-v,-u,v,5)end
?s,-#s*2,-60
for l=0,.5,.5/p do
u=flr(48*cos(l))v=flr(48*sin(l))q=cos(l-t()/4)circfill(u*q,-v*q,2,7)end
flip()p+=flr(btnp()/16+1)%3-1goto _

The code for this is so short, I could post it as a tweet. In fact, I just did.

You can also change the number of lines with the X and Z keys. (Oddly enough, due to a side effect of how division by 0 is handled in PICO-8, 0 lines acts exactly like 1 line. Negative numbers of lines don't show up.)
Ungolfed source:
lines=8

while true do
 cls(7)
 -- draw circle
 circfill(64,64,50,0)
 -- draw lines
 for l=0,.5,.5/lines do
  u=flr(50*cos(l))
  v=flr(50*sin(l))
  line(64+u,64-v,64-u,64+v,5)
 end
 -- center string
 s=lines.." lines"
 print(s,64-#s*2,4)
 -- draw points
 for l=0,.5,.5/lines do
  u=flr(48*cos(l))
  v=flr(48*sin(l))
  -- one full turn every 4 secs
  q=cos(l-t()/4)
  circfill(64+u*q,64-v*q,2,7)
 end
 flip()
 -- -1 if only ❎ is pressed
 -- +1 if only  is pressed
 --  0 otherwise
 lines+=flr(btnp()/16+1)%3-1
end


The Quickest Fox in the East In the spirit of Hello world! with NO repetition

Write a program that prints the string "the quick brown fox jumps over the lazy dog" with optional newline. The entire program must not repeat any characters.

Note that the string to be printed does repeat characters, so you will have to get around that limitation somehow.

Note that the winning condition is popularity-contest, i.e. the highest-voted answer wins.

Update: To make this a little easier, repetition is allowed but you must attempt to minimize it. Programs with less (or no) repetition are given precedence over programs with some repetition.

Microsoft Word from 97 to 2003 (and some Mac Word versions) — 10 characters

No repetitions, but doesn't quite match specs - 10 characters:

=rand(2,1)

Output:

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

Matches specs, other than capitalization and punctuation, one repetition - 10 characters:

=rand(1,1)

Output:

The quick brown fox jumps over the lazy dog.

Newer versions of Microsoft Word use =rand.old(1,1) which duplicates d and 1.

There might be a way to use a field {=SUM(3,-2)} as input to rand() but my installation is having issues with fields -- namely, they're not working...

"Bob" has confirmed that {=SUM(3,-2)} (with some difficulty) can be used to replace the first 1, but = is repeated...

=rand({=SUM(3,-2)},1)

Provided you get Word to update SUM first, the output is:

The quick brown fox jumps over the lazy dog.

Batch Script: 7 bytes

echo %1

If the script is named hello.bat, type this in at the command line:

hello.bat "The quick brown fox jumps over the lazy dog"


Output Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo Challenge
The goal is to output Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo.
Context. (Maybe another interesting challenge could be printing all of the other examples? This would probably use similar logic but involve either a function or just a for loop.)
Rule(s)

You cannot output anything other than the string with correct casing and spacing. Trailing new lines are allowed, trailing spaces are not.

This is code-golf, so fewest bytes win!

Python 3, 72 bytes
print('Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo')

I mean, that works.
Try it online!


Tips for golfing in C What general tips do you have for golfing in C? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C (e.g. "remove comments" is not an answer). Please post one tip per answer. Also, please include if your tip applies to C89 and/or C99 and if it only works on certain compilers.

Use bitwise XOR to check for inequality between integers:

if(a^b) instead of if(a!=b) saves 1 character.

Favor recursion over loops, especially if going forwards then backwards

Loops, 67 bytes

l;f(char*s){for(l=0;s[l];)putchar(s[l++]);for(;l;)putchar(s[--l]);}

Try it online!

Recursion, 47 bytes

f(char*s){*s?putchar(*s),f(s+1),putchar(*s):0;}

Try it online!

You can remove two for-loops and a counter variable. Even if you use just one for-loop in order to loop in one direction, you could save ~10 bytes with this transformation.


I need a program where the user inputs an array of doubles and the program outputs the array sorted Note: This question was severely edited since I first posted it here. The rules were moved to here, read them before posting any answer to understand the purpose of this. This was the first question created in the code-trolling category.

Imagine a lazy user on Stack Overflow asks this question:

  I need a program where the user inputs an array of doubles and the program outputs the array sorted. Could you please give the code?

How could you create a piece of code that will troll this user? Create a piece of code that will appear useful to an inexperienced programmer but is utterly useless in practice.

The winner is the most upvoted answer, except if the answer is somehow not eligible (for eligibility requirements, check the tag wiki description of code-trolling). If the previously most upvoted answer is beaten in the future in the number of upvotes after being accepted, the new best answer is accepted and the previous one is unaccepted. In the case of a tie, I will choose the winner at will among the tied ones or just wait a bit more.

Answers that have no code are not eligible. They might be fun and get some upvotes, but they won't be accepted.

Rules can be found at tag description.

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

Here it is in java. It is utter cheating, unacceptable and unfixable because it creates a MySQL database, insert the number there, do a select with an ORDER BY clause and outputs the numbers given by MySQL. In fact, it is MySQL who is doing the sorting, not the program.

package sorter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

public class SortingAlgorithm {

    private static final String CREATE_DB = "CREATE DATABASE sorting";
    private static final String DROP_DB = "DROP DATABASE sorting";
    private static final String CREATE_TABLE = "CREATE TABLE sorting.sorting ( num double not null )";

    public static void main(String[] args) throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        List<Double> doubles = new ArrayList<>(50);
        String typed;
        do {
            typed = JOptionPane.showInputDialog(null, "Type a double:");
            if (typed != null) doubles.add(Double.parseDouble(typed));
        } while (typed != null);

        List<Double> sorted = new ArrayList<>(50);

        try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306", "root", "root")) {
            try (PreparedStatement ps = con.prepareStatement(CREATE_DB)) {
                ps.executeUpdate();
            }
            try (PreparedStatement ps = con.prepareStatement(CREATE_TABLE)) {
                ps.executeUpdate();
            }

            for (Double d : doubles) {
                try (PreparedStatement ps = con.prepareStatement("INSERT INTO sorting.sorting (num) VALUES (" + d + ")")) {
                    ps.executeUpdate();
                }
            }

            try (
                    PreparedStatement ps = con.prepareStatement("SELECT * FROM sorting.sorting ORDER BY num");
                    ResultSet rs = ps.executeQuery())
            {
                while (rs.next()) {
                    sorted.add(rs.getDouble("num"));
                }
            }
            try (PreparedStatement ps = con.prepareStatement(DROP_DB)) {
                ps.executeUpdate();
            }
        }

        JOptionPane.showMessageDialog(null, "The array sorted is: " + sorted);
    }
}

I actually saw someone implement this in my undergrad. Start at the min value in the array, and iterate to the max value with some epsilon threshold. An order of magnitude increase in efficiency is an order of magnitude increase in runtime!

Luckily, the code is linear in the size of the array.

https://github.com/artoonie/shittycode/blob/master/sort.cpp


Divide a number by 3 without using *, /, +, -, % operators Quoting this question on SO (Spoiler alert!):

  This question has been asked in an Oracle interview.

  How would you divide a number by 3 without using *, /, +, -, %,
  operators?

  The number may be signed or unsigned.

The task is solvable, but see if you can write the shortest code.

Rules:

Perform the required integer division (/3)
Do not use the non-text-based operators *, /, +, -, or % (or their equivalents, such as __div__ or add()). This also applies to incrementing and decrementing operators, like i++ or i--. Use of operators for string concatenation and formatting are OK. Using these characters for different operators, such as unary - operator for negative numbers, or * to represent a pointer in C is OK as well.
Input value can be arbitrarily large (whatever your system can handle), both positive and negative
Input can be on STDIN or ARGV or entered any other way
Create the shortest code you can to do the above

C, 167503724710

Here's my solution to the problem. I admit it is unlikely to win a strict code golf competition, but it doesn't use any tricks to indirectly call built-in division functionality, it is written in portable C (as the original Stack Overflow question asked for), it works perfectly for negative numbers, and the code is exceptionally clear and explicit.

My program is the output of the following script:

#!/usr/bin/env python3
import sys

# 71
sys.stdout.write('''#include <stdint.h>
#include <stdio.h>
int32_t div_by_3(int32_t input){''')

# 39 * 2**32
for i in range(-2**31, 2**31):
    # 18 + 11 + 10 = 39
    sys.stdout.write('if(input==%11d)return%10d;' % (i, i / 3))

# 95
sys.stdout.write(r'''return 7;}int main(int c,char**v){int32_t n=atoi(a[1]);printf("%d / 3 = %d\n",n, div_by_3(n));}''')

Character count: 71 + 39 * 2**32 + 95 = 167503724710

Benchmarks

It was asked how long this would take and how much memory it would use, so here are some benchmarks:

Script execution time — Running ./test.py | pv --buffer-size=1M --average-rate > /dev/null for about 30 seconds gives a rate of about 14.8 MB/s. The rate of output can reasonably be assumed to be roughly constant, so the running time to completion should be about 167503724710 B / (14.8 * 1048576 B/s) ≈ 10794 s.
Compilation time — The TCC compiler claims to compile C code at 29.6 MB/s, which makes for a compilation time of 167503724710 B / (29.6 * 1048576 B/s) ≈ 5397 s. (Of course this can run in a pipeline with the script.)
Size of compiled code — I tried estimating it using ./test.py | tcc -c - -o /dev/stdout | pv --buffer-size=1M --average-rate > /dev/null, but it seems tcc doesn't output anything until it reads the entire source file in.
Memory usage to run — Since the algorithm is linear (and tcc doesn't optimize across lines), the memory overhead should be only a few kilobytes (apart from the code itself, of course).

Scheme, 95 110 bytes

(define (h n)
  (length
   (let l ((a (iota n)))
     (if (> (length a) 2)
         (cons 1 (l (cdddr a)))
         '()))))

My original attempt using base conversion:

(define (g n)
  (string->number
   (list->string
    (reverse
     (cdr
      (reverse
       (string->list
        (number->string n 3))))))
   3))

I can't think of a better way of removing the last character from the string.