Stereographic projection of polyhedra You will create a program that generates the stereographic projection of polyhedra.

In particular, to keep things simple, we'll only focus on n-chamfered dodecahedron.

Given a natural number n as input, and also a natural number d your program will output an d pixels by d pixels image which is the stereographic projection of the dodecahedron which has been chamfered n times. This is code-golf, so the shortest program wins!

Examples

0 ->  (the regular dodecahedron)

Notes

You must select a color for the background, edges, and vertices. The color of the edges and vertices may coincide, but the color of the background must coincide with neither.
You may treat the polyhedra either spherically or straight edged.
The center of the image must be the center of a pentagon.
Since stereographic projection results in an infinitely large image, you only need to have at least 75% of the vertices in the image.
EDIT: Since I never specified you can chamfer by any non-trivial amount. That being said, it would be nice if it looked like the images of chamfering below (i.e. almost regular).

Smiley Bonus

The n-chamfered dodecahedron is the $GP(2^n,0)$ goldberg polyhedron (where $GP(x,y)$ means a polyhedron consisting of hexagons and pentagons where if you start at one pentagon and move x spaces one direction, turn 60 degrees clockwise, and y spaces in that direction, you end up at another pentagon). Therefore, it might be easier to just calculate $GP(x,y)$ for arbitrary $x$ and $y$. If you do, you get a Smiley bonus (I can't award points since the challenge has already started).

Background

A dodecahedron is polyhedron with 12 sides, each pentagons. It looks like this

When you chamfer a shape, you replace each face with a smaller face, and each edge with a hexagonal face. For instance, here is what happens when you chamfer a dodecahedron (note, this is not the same shape as a soccer/football)

Here is what it looks like when you chamfer it again (i.e. n=2) polyHédronisme (sorry, the image export doesn't seem to be working).

Stereographic projection means that vertices of the polyhedron on a sphere. Place a plane tangent to it, and point on the opposite side of the sphere (called the view point). Then, draw a line between each point of the polyhedron and the view point. Extend this line to the plane, and map that point there. Do this for all the points. See above for an example of the stereographic projection of the dodecahedron.

837 Bytes : Javascript/HTML + d3.js + d3-delaunay + d3-geo-voronoi*

I believe I have a solution for this challenge. It relies on d3's geographic features: projections and pathing along great circles, d3-delaunay (a voronoi generator) and d3-geo-voronoi (a geographical voronoi extension to d3-delaunay).

The approach I've taken is fairly simple:

Take the centers of the faces of a regular dodecahedron (as lat/long pairs).
Create a spherical voronoi diagram of the centers (replicating the dodecahedron, contained in a sphere)
If more chamfering is needed, calculate the midpoint of each edge of the spherical voronoi diagram, add these to the list of centers, go back to step 2.
Project and draw

Using the midpoint from each edge as a new face center creates a new face for every edge when running through  the voronoi generator. This chamfering is fairly regular, the midpoint of each edge should be in the middle of a new face when chamfering. This does not mean the hexagons are regular, hexagons cannot be regular when chamfering twice or more (if I'm not mistaken).

Here's the implementation in 837 bytes:

<input><input>
d
<canvas>

Input is in the form of two html input fields, first one is the size of the drawing, the second one is the number of times to chamfer, clicking "d" will draw).

And in snippet form (with some minor interface changes: input s is size, input n is times to chamfer, click "draw" to draw):

_="canvas",O=d3,$=O.select,$("p").on("click",()=>{N=O.selectAll("input").nodes(),w=N[0].value,n=N[1].value,$(_).attr("width",w).attr("height",w),a=31.71801,b=58.28198,c=121.71801,C=[[0,a],[180,-a],[-90,b],[90,-b],[0,-a],[180,a],[90,b],[-90,-b],[-b,0],[-c,0],[c,0],[b,0]],s=$(_).node().getContext("2d"),p=O.geoStereographic().scale(60/960*w).rotate([-b,0]).translate([w/2,w/2]).clipAngle(170),P=O.geoPath(p,s),s.clearRect(0,0,w,w),D=C=>O.geoVoronoi()(C),M=v=>v.mesh().coordinates.map((c)=>O.geoInterpolate(c[0],c[1])(0.5)),v=D(C);for(i=0;i<n;i++){C.push(...M(v)),v=D(C)}v.polygons().features.forEach(f=>(s.beginPath(),P(f),s.stroke()))})
s<input>n<input>
draw
<canvas>

slightly modified for snippet view as noted, also as there are other nodes in the snippet to navigate, so there is a change there

If rendered as 3d, this produces something along the lines of (chamfered five times):

Original pentagons are in orange - they are separated by 31 hexagons.

An example with the sterographic (chamfered 6 times):

*Note

The above may not conform to scoring rules very well. Without using new (relative to challenge) updates to dependecies, but replacing those with poor and incomplete minimization:

4454 Bytes : d3.js (v4) + d3-delaunay (v2)

d3-geo-voronoi has been altered since the challenge has been posted in a way that enables the above solution. While it wasn't altered by me, nor to address this challenge, I'll include the longer solution that relies on only d3.js and d3-delaunay (versions that predate the challenge) and incorporates the necessary parts of d3-geo-voronoi:

<input><input>
draw
<canvas></canvas></script>

Lastly, here's an animated ungolfed snippet to show the workings:

var n = 3; // chamfer this many times.

var a = 31.71801891964135;
var b = 58.28198108035894;
var c = 121.71801891964117;
var centroids = [[0,a],[180,-a],[-90,b],[90,-b],[0,-a],[180,a],[90,b],[-90,-b],[-b,0],[-c,0],[c,0],[b,0]];

var getDiagram = function(centroids) {
 return d3.geoVoronoi()
  .x(function(a) {
   return a[0]
  })
  .y(function(a) {
   return a[1]
  })
  (centroids);
}

var getCenters = function(v) {
 return v.mesh().coordinates.map(function(c) {
  return d3.geoInterpolate(c[0],c[1])(0.5);
 })
}

// Starting voronoi:
var voronoi = getDiagram(centroids);

for (var i = 0; i < n; i++) {
 centroids.push(...getCenters(voronoi));
 voronoi = getDiagram(centroids);
}

var canvas = document.getElementsByTagName("canvas")[0];
var context = canvas.getContext("2d");
var projection = d3.geoStereographic().scale(60).clipAngle(170).translate([480,480])
var path = d3.geoPath().projection(projection).pointRadius(1).context(context);

// animate:
d3.interval(function(elapsed) {
    projection.rotate([ -elapsed / 200, 0 ]);
 context.clearRect(0,0,960,960);
 voronoi.polygons().features.forEach(function(d) {
  context.beginPath();
  path(d)
  context.stroke();
 })
}, 50);
<canvas width="960" height="960"></canvas>


Make a program for printing a string in my esolang MAWP! The task

Given an ascii string, output a program in my esolang MAWP that outputs the inputted string when run.

Useful functions in MAWP

Numbers from 0-9: Pushes the number to stack
M                 Takes the top two numbers off stack and pushes the sum to stack
A                 Takes the top two numbers off stack and pushes the difference to stack (xyA = y-x)
W                 Takes the top two numbers off stack and pushes the multiplied result to stack
P                 Takes the top two numbers off stack and pushes the floored divided result to stack (xyP = yx)
;                 Takes top number off stack and prints it as an ascii char

Test cases

Input: Hello, World!

Possible output: 89W;689MWA;269WW;269WW;1278WWA;159WA;48W;699WM;1278WWA;67W89WM;269WW;455WW;148WM;

Input: codegolf

Possible output: 929MW;278WWA;455WW;1689MWA;1849MWA;1278WWA;269WW;689MW;

Rules

There can be multiple solutions for each symbol, but the length must be minimal: for example, 04M5W5W; is unacceptable while 45W5W; is fine.
The stack starts with a 1 one it.
You may leave something on the stack
Your output may not print out other characters other than the string, and all of the character s must be given in the og order.
This is code-golf, so lowest byte score wins!

ASCII table for reference

JavaScript (Node.js),  276 266  263 bytes
Saved 3 bytes thanks to @KevinCruijssen

i=>[v=[],O='',[...2**29+'4'].map(F=x=>F[v[x]=+x]=x)].map(s=_=>v.map(x=>v.map(y=>[x+y,x*y,y-x].map((z,o)=>(!F[z]&&V.push(z))|(S=~~s[x]-~s[y])<s[z]|S==s[z]&F[x]<2?F[s[z]=S,z]=F[x]+F[y]+'MWA'[o]:0)),V=[])&&v.push(...V))&Buffer(i).map(n=>O+=F[n]+';')||O.replace(1,'')

Try it online!
MAWP interpreter
Here is a simple MAWP interpreter I wrote to check the results.

function MAWP(code) {
  let stack = [ 1 ], out = "";

  function assertStkSz(n) { if(stack.length < n) throw "stack error"; }

  [...code].forEach(c => {
    switch(c) {
      case 'M': assertStkSz(2); stack.push(stack.pop() + stack.pop()); break;
      case 'A': assertStkSz(2); stack.push(stack.pop() - stack.pop()); break;
      case 'W': assertStkSz(2); stack.push(stack.pop() * stack.pop()); break;
      case 'P': assertStkSz(2); stack.push(stack.pop() / stack.pop() | 0); break;
      case ';': assertStkSz(1); out += String.fromCharCode(stack.pop()); break;
      default : stack.push(+c); break;
    }
  })
  return out;
}

Try it online!


Simple One Game Blackjack This is a very stripped down version of A BlackJack KOTH contest...

This is the goal:

Upon the execution: There are two inputs, "H" to hit (have the code deal a card), "S" to stand (Stop getting cards, and let dealer try to win).

Coding Rules:

There is no betting or splitting of hands, for simplicity of the challenge.
Suits are HDCS; standing for Hearts, Diamonds, Clubs and Spades respectively.
Trumps must be formatted as A23456789TJQK, where T is the 10; therefore TH is the 10 of Hearts, etc.
A is worth 1 or 11. Face cards are worth 10 points. A perfect game is 21 points.
If you go over 21 points, the output along with the cards must show "BUST".
If the dealer goes over 21 points and you're standing, output with cards must show "WIN"
If the dealer beats you even though you're standing, output with cards must show "LOSE"
If the dealer matches your score on standing, output with cards must show "PUSH"
Dealer must stand on 17 through to 21.
If you Stand, it calculates your score and displays it (see below), and then goes into dealer play mode. If the dealer stands or busts, it calculates its score and displays it.
Standard 52 cards in a deck, no duplicates can be generated.
Output must resemble the following:

H
Your hand: 3H
H
Your hand: 3H 8S
H
Your hand: 3H 8S 9D
S
Standing... Your hand: 3H 8S 9D = 20 points
My hand: 2C 5H 8H 9S = 24 points
WIN

Shortest code wins

Javascript 838

The very first version, not optimized !
All rules are not fully observed, :-o

!function(){var f=require("readline").createInterface(process.stdin,process.stdout),g=[],h=function(){for(var b;!b||-1<g.indexOf(b);)b="A23456789TJQK".charAt(13*Math.random()|0)+"HDCS".charAt(4*Math.random()|0);g.push(b);return b},k=function(b){var a=0,d=0;for(z=b.length;z--;){var c=b[z].charAt(0);/[TJQK]/.test(c)?a+=10:/[2-9]/.test(c)?a+=+c:"A"==c&&(d++,a++)}for(;d--;)21>=a+10&&(a+=10);return a};(function(){var b=[],a=[],d=0,c=0;f.prompt();f.on("line",function(e){e=e.charAt(0);"H"==e&&(b.push(h()),
c=k(b),console.log("Your hand: "+b+" = "+c+" points"),21<c&&(console.log("LOSE"),process.exit(0)));if("S"==e){for(;17>(d=k(a));)a.push(h());console.log("My hand: "+a+" = "+d+" points");21<d||d<c?console.log("WIN"):d>c?console.log("LOSE"):console.log("DRAW");process.exit(0)}f.prompt()}).on("close",function(){process.exit(0)})})()}();

Execute it with nodeJS


The cyclic sequence of even digits, with odds in between Consider the following sequence:

1, 0, 1, 2, 4, 1, 6, 8, 0, 1, 2, 4, 6, 8, 1, 0, 2, 4, 6, 8, 1, 0, 2, 4, 6, 8, 0, 1, ...

The even digits start from 0 and are grouped into runs of increasing length. They are arranged cyclically, meaning that they are sorted in ascending order until 8 is reached, and then cycled back from 0. 1 separates the runs of even digits, and it also starts the sequence. Let's visualize how this sequence is formed:

                 1, 0, 1, 2, 4, 1, 6, 8, 0, 1, 2, 4, 6, 8, 1, 0, 2, 4, 6, 8, 1,  ...

                    -     ----     -------     ----------     -------------
run length:         1      2          3            4                5            ...
position of 1:   X     X        X           X              X                 X   ...
even sequence:      0,    2, 4,    6, 8, 0,    2, 4, 6, 8,    0, 2, 4, 6, 8      ...

Acceptable Input and Output methods:

Receive an integer N as input and output the Nth term of this sequence.
Receive an integer N as input and output the first N terms of this sequence.
Print the sequence indefinitely.

You can choose either 0 or 1-indexing for the first two methods.

You can compete in any programming language, while using the standard input and output methods. Standard loopholes are forbidden. This is code-golf, so the shortest code in each language wins.

Haskell, 50 46 bytes

1#cycle[0,2..8]
n#r=1:take n r++(n+1)#drop n r

Try it online!

1#cycle[0,2..8] returns the sequence as infinite list.

-4 bytes thanks to Ørjan Johansen!


Pass on your radiation The task here is pretty simple.  You should write a program that takes a string as input and outputs it (that is a cat program).

Additionally when the \$n\$th byte of your program is removed (without replacement) the augmented program should take a string as input and remove the \$n\$th character.  If the input to your augmented program is less than \$n\$ characters long it should return it as is. For example the python program

x = input()
if "y" == "y":
  print(x)
else:
  print(x[:16] + x[17:])

Try it online!

will remove the \$17\$th character if its \$17\$th byte is removed (the first y).

Scoring

Your answer's score will be the number of bytes for which removal does not cause the program to remove the corresponding byte.  With better score being lower.

In our example above the total length is 68 bytes, with one byte (the \$16\$th one) augmenting the program correctly.  That leaves a score of 67 bytes.

If the program were modfied to work in two places like so:

x=input()
u="az"
if u!="az":x=x[:13+(u<"c")]+x[14+(u<"c"):]
print(x)

Try it online!

Where removing the \$14\$th and \$15\$th characters (a and z) work properly.  The score is 66 bytes or 68 - 2, since the program is 68 bytes long but two of those bytes work properly.

Rules and clarifications

There must be at least one byte which can be removed that causes the program to remove the corresponding character in the input.  This means a cat program on its own is not a valid submission.
Only one byte will be removed at a time.  You do not have to worry about what happens when multiple bytes are removed from your program at the same time.
You should support strings using printable ascii characters in addition to all characters that appear in your program itself.  Input containing anything else is undefined behavior.

Python 2, score:  56 50  48 bytes - 6 = 42
This is more an attempt to allow to remove more than 1 or 2 characters than to achieve the lowest possible score. Given the scoring scheme, allowing one more byte to be removed this way would cost at least one extra byte, leaving the score unchanged at best.
You may remove the 3rd to the 8th character, i.e. any digit of \$545454\$.
n=545454;x=input();print x[:n%11]+x[n%11+n%9/4:]

Try it online!
How?
Removing the \$n\$th digit from \$545454\$ and applying a modulo \$11\$ results in \$n+1\$. Applying a modulo \$9\$ instead allows to figure out whether the number was changed or not.
 pattern |    x   | x mod 9 | x mod 11
---------+--------+---------+----------
  545454 | 545454 |    0    |   (8)
  _45454 |  45454 |    4    |    2
  5_5454 |  55454 |    5    |    3
  54_454 |  54454 |    4    |    4
  545_54 |  54554 |    5    |    5
  5454_4 |  54544 |    4    |    6
  54545_ |  54545 |    5    |    7


Hi, can you draw some odd art? Bye! Create a program that outputs "Hi, Hello!" in k bytes. By altering n bytes, the code should output all odd numbers in the range 5 <= x <= 25.
Changing another m bytes should result in a code that prints the following frame in ASCII-art:

+-+
| |
+-+

Change another o bytes, and print Hello, bye!.

m, n and o are calculated in Levenshtein distance (cumulative). n is the distance from the first to the second code. m is the distance between the second and third and so on.

The score of your submission will be 0.5*k + n + m + o.

As an example:

The code that prints `Hi, Hello!` is 30 bytes.              15
Add two bytes and remove one and print the odd numbers     + 3
Alter three bytes in place, and add one to print the box   + 4
Remove four bytes and print `Hello, bye!`                  + 4
Total score:                                                26

Rules

All codes must be in the same language
You have to follow the given order (i.e. the first code prints Hi, Hello, the second prints the numbers etc.)
The strings and ASCII-box must be exactly as specified. The list of digits can be on any suitable format

Pyth - 49 46 44/2 + 1 + 1 + 1 = 25
Hello code:
h["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!

Odd numbers code:
ht["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!

Box code:
htt["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!

Bye Code:
httt["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!


How long does it take to paint a stick? (Based on this Math.SE problem, which also provides some graphics)

I have a stick which looks kinda like this:

I want it to look kinda like this:

I'm not an expert painter, however, so before I start such an ambitious DIY project, I want to make sure that I'm not in over my head.

Your program should tell me how  how many steps are involved in painting this stick.  Each step involves painting a continuous area with a solid color, which covers up previous layers of paint.  For the above example, I could paint the left half blue, the right half red, and then the two separate green areas for a total of 4 steps (the green is not continuously painted).

Here it is in ASCII:

------
bbb---
bbbrrr
bgbrrr
bgbrgr

There are a couple different ways to paint this stick and end up with the same result.  I'm only interested in the time estimate, however, which is four steps.

Goal

Your program should output the minimum number of steps needed to paint a stick with a given color scheme.  The paint scheme will be in the form of a string of characters, while output will be a number. This is code golf.  Shortest program wins.

Input

Your program will receive the coloring scheme for a stick in the form of a string of letters.  Each unique letter (case sensitive) represents a unique color.

YRYGR

grG

GyRyGyG

pbgbrgrp

hyghgy

Output

These numbers are the least number of steps needed to paint the sticks.

4

3

4

5

4

Explanations

This is how I arrived at the above numbers.  Your program does not need to output this:

 -----
 YYY--
 YRY--
 YRYG-
 YRYGR

 ---
 g--
 gr-
 grG

 -------
 GGGGGGG
 GyyyGGG
 GyRyGGG
 GyRyGyG

 --------
 pppppppp
 pbbbpppp
 pbbbrrrp
 pbgbrrrp
 pbgbrgrp

 ------
 -yyyyy
 -ygggy
 hygggy
 hyghgy

Edit: I'll add more test cases if they prove to be more difficult test cases.

GolfScript, 82 72 67 characters
.,n*{:c,,{[).2$1<*\c>+1$.,,{).2$<\3$<=},,.@>@@>]}%\;{~S)}%$0+0=}:S~

Reasonably fast for a GolfScript program, examples:
> hyghgy
4

> pbgbrgrp
5

The algorithm used works through the colors left-to-right recursively, according to the following statements:

Ignore all parts from the left which already have the required color. Overpainting them again will not provide a better answer.

If the complete stick already has the desired color, return 0 steps as result.

Otherwise, take the target color of the now leftmost part (i.e. the first not in the desired color).

Paint 1 part with the target color and recurse.
Paint 2 parts with this color and recurse.

...

Paint the whole remaining stick with this color and recurse.

Take the minimum of all those numbers and add 1 (for the current step). Return this as the optimal number of steps.

This algorithm works, because the leftmost part has to be painted at one time anyways, so why not do it immediately - in any possible fashion.
.,n*         # prepare the initial situation (target stick, unpainted stick)
             # used n instead of '-' for the unpainted parts, because it is shorter
{            # Define the operator S which does t c S -> n
             #   - t: the desired target colors
             #   - c: the stick as it is colored currently
             #   - n: minimum number of steps required to go from c to t
  :c         # Assign the current configuration to the variable c
  ,,{[       # Map the list [0 1 2 .. L-1]
             # We will build a list of all possible configurations if we paint
             # the stick with the 0th part's color (either 1 or 2 or 3 or ... parts)
    ).       # Increase the number, i.e. we paint 1, 2, 3, ... L parts, copy
    2$1<     # Take the first color of the target configuration
    *        # ...paint as many parts
    \c>+     # ...and keep the rest as with the current stick
    1$       # take the target configuration
             # Top of stack now e.g. reads
             #    h----- hyghgy (for i=0)
             #    hh---- hyghgy (for i=1)
             # Next, we strip the common leading characters from both strings:
    .,,      # Make list [0 1 2 ... L-1]
    {        # Filter {}, all the numbers for which the first j+1 parts are the same
      ).     # incr j
      2$<    # take leftmost j parts of stick A
      \3$<   # take leftmost j parts of stick B
      =      # are they equal?
    },,      # The length of the result is the number of common parts.
    .@>      # cut parts from A
    @@>      # cut parts from B
  ]}%
  \;         # Remove the target from the stack (not needed anymore)
             # We now have a list of possible paintings where 1, 2, ..., L parts were
             # painted from the left with the same color.
             # All configurations were reduced by the common parts (they won't be
             # painted over anyways)
  {~S)}%     # Call the method S recursively on the previously prepared configurations
  $0+0=      # $0= -> sort and take first, i.e. take the minimum, 0+ is a workaround
             # if the list was empty (i.e. the operator was called with a stick of length 0).
}:S
~            # Execute S


Write program which verifies Erdős–Straus conjecture Write program, which verifies Erdős–Straus conjecture.
Program should take as input one integern (3 <= n <= 1 000 000) and print triple of integers satisfying identity 4/n = 1/x + 1/y + 1/z, 0 < x < y < z.

Shortest code wins.

Some examples:

3 => {1, 4, 12}
4 => {2, 3, 6}
5 => {2, 4, 20}
1009 => {253, 85096, 1974822872}
999983 => {249996, 249991750069, 62495875102311369754692}
1000000 => {500000, 750000, 1500000}

Note that your program may print other results for these numbers because there are multiple solutions.


Print the difference in the Thue-Morse sequence Note, when I say "negate", I mean replace all ones with zeroes (i.e. a bitwise negation)

The Thue-Morse sequence goes like 01101001

The way you generate it is:

Start by taking 0.
Negate what is left and append it to the end.

So, take 0. Negate it and add that to the end - 01

Then take that and negate it and add that to the end - 0110

And so on.

Another interesting property of this is that distance between zeros creates an "irrational" and non-repeating string.

So:

0110100110010110
|__|_||__||_|__|
 2  1 0 2 01 2          <------------Print this!

Can you write a program that, when input n, will output the first n digits of the string to printed?

This is code golf, so shortest number of bytes wins!

Python 3 2, 104 92 88 84 bytes

This is a pretty rudimentary solution based on building a ternary Thue-Morse sequence from scratch. This sequence is identical to the one being asked, though someone else will have to write a more thorough explanation of why that is. At any rate, this sequence is only a trivial modification of this one, A036580.

Edit: Changed the for loop into a list comprehension, changed from a function to a program, and changed the whole thing to Python 2. Thanks to Dennis for golfing help.

n=input()
s="2"
while len(s)<n:s="".join(`[1,20,210][int(i)]`for i in s)
print s[:n]


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.

(Tips that apply to C as well can be found in Tips for golfing in C - but note that some C tips don't work in C++.  For example, C++ does require function prototypes and return values.)

The ternary conditional operator ?: can often be used as a stand in for simple if--else statements at considerable savings.

It is of special value in that it can be used to select alternate lvalues as in

#include <iostream>
#include <cstdlib>
int main(int c, char**v){
  int o=0,e=0,u;
  while(--c) ((u=atoi(v[c]))%2?o:e)+=u;
  std::cout << "Sum of odds " << o <<std::endl
            << "Sum of evens " << e <<std::endl;
}


We're no strangers to code golf, you know the rules, and so do I Write the shortest program that prints the entire lyrics of "Never Gonna Give You Up" by Rick Astley.

Rules:

Must output the lyrics exactly as they appear in the above pastebin*. Here's the raw dump: http://pastebin.com/raw/wwvdjvEj
Cannot rely on any external resources - all lyrics must be generated by / embedded in code.
No use of existing compression algorithms (e.g. gzip / bzip2) unless you include the full algorithm in your code.
Use any language, shortest code wins.

Update, 1st June 2012:
For solutions containing non-ASCII text, the size of your solution will be counted in bytes, based on UTF-8 encoding. If you use codepoints that cannot be encoded in UTF-8, your solution will not be judged as valid.

Update, 7th June 2012:
Thank you all for your awesome solutions! I'll be accepting the shortest answer tomorrow afternoon. Right now, Peter Taylor's GolfScript answer is winning, so get cracking on some improvements if you want to beat him! :)

*There is a typo in the Pastebin (line 46, "know" should be "known").  You may either replicate it or not at your discretion.

Ruby 576 557 556 (552) chars && PHP 543 chars

Another search-and-replace solution. Note that this form of solution is essentially a Grammar-based Compression Code http://en.wikipedia.org/wiki/Grammar-based_code
Check out http://www.cs.washington.edu/education/courses/csep590a/07au/lectures/lecture05small.pdf for a simple to understand compression example.

I've written the substitution rules so that the starting character for each substitution is computed (they are in sequential ASCII order); it need not be present in the transition data.

i=44
s="We; n7trangMsL8loT63Ke rules5s8d8I
AJull commit4nt'sChatFKink: of6CHldn'tRetKisJrom<ny@Ruy-/A= if?<sk 42DS'tLE 4?;Lo8bli=L7ee..
O,R1)O,R001)/-.."
"
I justCannaLE?2Gotta >u=Msta=.|
Ng1Nlet? downNrun<rH=5desMt?N>cryNsayRoodbyeNtE< lie5hurt?|

We'T3n each@Jor s8lSg6r hear9<ch: but6;Lo7hyL7BInsideCe both3Cha9Ro: S
We3KeRa45we;QplB|1)O)NgiT, nPgiT
(G|iT? up| howFJeel:
| know|me|<= |
YH|8s|o |t's been|ing|'re| a|nd|make? | yH| othM|A|ay it
| w|D|ell| I'm|G|ou|I| f|Lh| t|er|
NP|
(Ooh|eTrQ|RSna | g|on|ve".scan(/[^|]+/){s.gsub!((i+=1).chr,$&)}
puts s

implementation notes

The above solution is 556 chars long, but scores 552 with the removal of newlines from source code. It is slightly better scoring than the original 556 char solution I had that scored 554.
I use "known" instead of "know"; this makes the verse repetition identical and should make the compression better
I originally optimized the rules by repeatedly searching for the substitution that would yield the most decrease in current code size. However, I found that RiderOfGiraffe's substitution rules were (slightly) better than mine, so I'm now using a modified version of his rules.
I spent time reordering the rules so that a single substitution pass can decompress everything.
Due to the computed initial character in the substitution rules, my rule list has a rule for every character in a contiguous ASCII range. I found that having some "dummy" substitution rules was better for code size than having all real rules and coding a final text fixup substitution.
This example is small enough that you probably could successfully write a program to find the optimal (least total cost) set of rules. I would not expect doing this would yield size reductions of more than a few bytes.

older implementation

This older implementation has 576 characters and started with substitution rules from ugoren's bash/sed implementation. Ignoring the substitution variable renaming, my first 28 substitutions are exactly the same as those performed in ugoren's program. I added a few more to lower the overall byte count. This is possible because my rules are more efficiently represented than those in ugoren's implementation.

i=44
puts"WeM noHtraLersB loJ;6 C rules=so do $
& full commitment'sGhat<thinkDof;Gouldn'tKet this fromFny oCrKuy.
-&E if9ask me1~on't @ me:MBo bliEBHee//

3300-.//|
We'J6n each oCr forHo loL;r hear2FchDbut;MBoHhyBH7$nsideGe both6Gha2ADon
We6 CKame=weM>pl7|
$ justGanna @:1#otta 8uEerstaE/|
5?9up5let9down5runFrouE=desert:58cry5sayAodbye5@F lie=hurt:|(Ooh)5?, nI>?
(#4| how<feeliL
|t's been|(Ooh,K4|iJ9up)
|
NI>| know|ay it
|make9|: | you|
You| $'m |FE |Anna |giJ|tell|Ko| to|the|iL |nd| a| w| s|eJr|ve| g|ng|'re".split("|").inject{|m,o|m.gsub((i+=1).chr,o)}.tr('&~#$',"ADGI")

I did not try optimizing the substitution rules in this one.

contest notes

The search-and-replace decompression scheme works well for this contest because most languages have pre-built routines that can do this. With such a small amount of text to be generated, complex decompression schemes do not seem to be feasible winners.

I've used only ASCII text and also avoided using unprintable ASCII characters. With these restrictions, each character in your code can only represent up to a maximum of 6.6 bits of information; this is very different than to real compression techniques where you use all 8 bits. In some sense, it is not "fair" to compare to gzip/bzip2 code size because those algorithms will use all 8 bits. A fancier decompression algorithm may be possible if you can include traditionally unprintable ASCII in your strings AND each unprintable character is still written in your code as a single byte.

PHP Solution

<?=str_replace(range('-',T),split(q,"
I justCannaLE?2Gotta >u=Msta=.q
Ng1Nlet? downNrun<rH=5desMt?N>cryNsayRoodbyeNtE< lie5hurt?q

We'T3n each@Jor s8lSg6r hear9<ch: but6;Lo7hyL7BInsideCe both3Cha9Ro: S
We3KeRa45we;QplBq1)O)NgiT, nPgiT
(GqiT? upq howFJeel:
q knowqmeq<= q
YHq8sqo qt's beenqingq'req aqndqmake? q yHq othMqAqay it
q wqDqellq I'mqGqouqIq fqLhq tqerq
NPq
(OohqeTrQqRSna q gqonqve"),"We; n7trangMsL8loT63Ke rules5s8d8I
AJull commit4nt'sChatFKink: of6CHldn'tRetKisJrom<ny@Ruy-/A= if?<sk 42DS'tLE 4?;Lo8bli=L7ee..
O,R1)O,R001)/-..");

The above solution takes the PHP from "a sad dude" and combines it with my substitution rules. The PHP answer turns out to have the shortest decompression code. See http://ideone.com/XoW5t


Alignment of a string This is similar to the alignment used in word.
Task
3 inputs: A 1 line string, a positive integer k, and direction (left or middle or right)
Your job is to insert new lines(\n) and spaces in the string such that every line has k characters in it and aligned to the direction given.
Rules
The words must not be split(unless their length is greater than k)
Direction can be taken as any 3 unique characters(must be mentioned).
Any format and order of input is valid(must be mentioned).
Input will only have alphabetical characters of any case(and spaces).
There will not be any trailing or leading spaces in the input and will have only 1 space between words.
Output can be either a string on one line as is in examples or multiple lines.
If the direction is left:
There should not be any spaces in left of the line and only 1 space between words.
If the direction is right:
There cannot be any spaces to the right of the line and only 1 space between words.
If the direction is middle:
There cannot be any spaces to the left or right of a line and an equal number of spaces between words on one line.
In case the word length is shorter than k and only 1 word can fit in 1 line, then spaces on the right is allowed.
If more than 2 words can fit in one line but they cannot be divided keeping number of spaces equal, words will shift to next line to keep number of spaces equal.
Test Cases
input: 'Hello World',6,right
output: ' Hello\n World'

input: 'Hello World',7,left
output: 'Hello  \nWorld  '

input: 'Hello World',7,middle
output: 'Hello  \nWorld  '

input: 'This is a test case',5,middle
output: 'This \nis  a\ntest \ncase '

input: 'This is a test case',5,left
output: 'This \nis a \ntest \ncase '

input: 'For example',1,left
output: 'F\no\nr\ne\nx\na\nm\np\nl\ne' #The space is removed as the next word is in a newline.

input: 'Hello Worlds How are you',5,left
output: 'Hello\nWorld\ns How\nare  \nyou  '

input: 'qwert asdfghjkl zxcvbnm',7,middle
output: 'qwert  \nasdfghj\nkl      \nzxcvbnm'

input: 'ab abcdefg',6,middle
output: 'ab    \nabcdef\ng     '

input: 'This is code golf so shortest code wins',10,middle
output: 'This    is\ncode  golf\nso        \nshortest  \ncode  wins'

input: 'Credit to Jo for this case',13,middle
output: 'Credit     to\nJo  for  this\ncase         '

This is code-golf so shortest code wins

Perl 6, 195 186 177 132 bytes

-41 bytes thanks to nwellnhof!

{->\b,\c{$!={!c*(b-$0.comb)/($0-1||1)+1};S:g{[(\S+)[\s|$]<?{b>=$0.ords&&.$!%%1}>]+|(\S**{b})}=$0.join(' 'x.$!).fmt("%{b*c||-b}s
")}}

Try it online!

Anonymous code block that takes input curried, e.g. f('text')(length, direction). Uses the values -1,0,1 as left, middle and right respectively.


Optimal path through a matrix Given a matrix consisting of positive integers, output the path with the lowest sum when traversing from the upper left element to the bottom right. You may move vertically, horizontally and diagonally. Note that it's possible to move both up/down, right/left and diagonally to all sides.

Example:

 1*   9    7    3   10    2    2
10    4*   1*   1*   1*   7    8
 3    6    3    8    9    5*   7
 8   10    2    5    2    1*   4
 5    1    1    3    6    7    9*

The path giving the lowest sum is marked with asterisks, and results in the following sum: 1+4+1+1+1+5+1+9=23.

Test cases:

1   1   1
1   1   1
Output: 3

 7    9    6    6    4
 6    5    9    1    6
10    7   10    4    3
 4    2    2    3    7
 9    2    7    9    4
Output: 28

2  42   6   4   1
3  33   1   1   1
4  21   7  59   1
1   7   6  49   1
1   9   2  39   1
Output: 27 (2+3+4+7+7+1+1+1+1)

 5    6    7    4    4
12   12   25   25   25
 9    4   25    9    5
 7    4   25    1   12
 4    4    4    4    4
Output: 34 (5+12+4+4+4+1+4)

1   1   1   1
9   9   9   1
1   9   9   9
1   9   9   9
1   1   1   1
Output: 15

 2   55    5    3    1    1    4    1
 2   56    1   99   99   99   99    5
 3   57    5    2    2    2   99    1
 3   58    4    2    8    1   99    2
 4   65   66   67   68    3   99    3
 2    5    4    3    3    4   99    5
75   76   77   78   79   80   81    2
 5    4    5    1    1    3    3    2
Output: 67 (2+2+3+3+4+5+4+3+3+3+1+2+2+1+3+1+1+4+5+1+2+3+5+2+2)

This is code-golf so the shortest code in each language wins.


Most complex "Hello world" program you can justify Your boss asks you to write a "hello world" program. Since you get paid for lines of code, you want to make it as complex as possible. However if you just add nonsense lines, or obviously useless or obfuscating stuff, you will never get it through code review. Therefore the challenge is:

Write a "hello world" program which is as complex as possible under the condition that you can give a "justification" for every complexity in the code.

The required behavior of the program is to just output a single line "Hello world" (without the quotes, but with a newline at the end) and then exit successfully.

"Justifications" include:

buzzword compatibility ("Modern software is object oriented!")
generally accepted good programming practices ("Everyone knows that you should separate model and view")
maintainability ("If we do it this way, we can more easily do XXX later")
and of course any other justification you can imagine using (in other situations) for real code.

Obviously silly justifications will not be accepted.

Also, you have to "justify" your choice of language (so if you choose an inherently verbose language, you'll have to justify why it is the "right" choice). Fun languages like Unlambda or Intercal are not acceptable (unless you can give a very good justification for using them).

The score of qualifying entries is computed as follows:

1 point for each statement (or whatever the equivalent to a statement is in your language of choice).
1 point for each definition of a function, type, variable etc (with the exception of the main function, where applicable).
1 point for each module use statement, file include directive, namespace using statement or similar.
1 point for each source file.
1 point for each necessary forward declaration (if you could get rid of it by rearranging code, you have to "justify" why the arrangement you've chosen is the "right" one).
1 point for each control structure (if, while, for, etc.)

Remember that you have to "justify" each single line.

If the chosen language is different enough that this scheme cannot be applied (and you can give a good "justification" for its use), please suggest a scoring method which most closely resembles the above for your language of choice.

Contestants are asked to calculate the score of their entry and write it in the answer.

C++, trollpost

  Most complex “Hello world” program you can justify

#include <iostream>

using namespace std;

int main(int argc, char * argv[])
{
    cout << "Hello, world!" << endl;
    return 0;
}

My brain cannot justify writing a longer one :)


Real base conversion We've had a few challenges for base conversion, but all of them seem to apply to integer values. Let's do it with real numbers!
The challenge
Inputs:

A real positive number x, expressed in base 10. This can be taken as a double-precision float or as a string. To avoid precision issues, the number can be assumed to be greater than 10−6 and less than 1015.
A target base b. This will be an integer from 2 to 36.
A number of fractional digits n. This will be an integer from 1 to 20.

Output: the representation of x in base b with n fractional digits.
When computing the output expression, the digits beyond the n-th should be truncated (not rounded). For example, x = 3.141592653589793 in base b = 3 is 10.0102110122..., so for n = 3 the output would be 10.010 (truncation), not 10.011 (rounding).
For x and b that produce a finite number of digits in the fractional part, the equivalent infinite representation (truncated to n digits) is also allowed. For example, 4.5 in decimal can also be represented as 4.49999....
Don't worry about floating point errors.
Input and output format
x will be given without leading zeros. If x happens to be an integer you can assume that it will be given with a zero decimal part (3.0), or without decimal part (3).
The output is flexible. For example, it can be:

A string representing the number with a suitable separator (decimal point) between integer and fractional parts. Digits 11, 12 etc (for b beyond 10) can be represented as letters A, B as usual, or as any other distinct characters (please specify).
A string for the integer part and another string for the fractional part.
Two arrays/lists, one for each part, containing numbers from 0 to 35 as digits.

The only restrictions are that the integer and fractional parts can be told apart (suitable separator) and use the same format (for example, no [5, 11] for the list representing the integer part and ['5', 'B'] for the list representing the fractional part).
Additional rules

Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
Shortest code in bytes wins.

Test cases
Output is shown as a string with digits 0, ..., 9, A, ... , Z, using . as decimal separator.
x, b, n                    ->  output(s)

4.5, 10, 5                 ->  4.50000 or 4.49999
42, 13, 1                  ->  33.0 or 32.C
3.141592653589793, 3, 8    ->  10.01021101
3.141592653589793, 5, 10   ->  3.0323221430
1.234, 16, 12              ->  1.3BE76C8B4395
10.5, 2, 8                 ->  1010.10000000 or 1010.01111111
10.5, 3, 8                 ->  101.11111111
6.5817645, 20, 10          ->  6.BCE2680000 or 6.BCE267JJJJ
0.367879441171442, 25, 10  ->  0.94N2MGH7G8
12944892982609, 29, 9      ->  PPCGROCKS.000000000

JavaScript (ES8), 81 74 71 bytes

f=
(x,b,n,g=x=>x.toString(b))=>g(x-x%1)+'.'+g(x%1).substr(2,n).padEnd(n,0)

<input id=x><input type=number min=2 max=36 value=10 id=b><input type=number min=1 max=20 value=10 id=n>

Works for x between 1e-6 and 1e21, b from 2 to 36 (exactly as required) and n from 1 to anything from 10 to 48 depending on the base before floating-point errors creep in. Edit: Saved 7 bytes with help from @Birjolaxew. Saved a further 3 bytes with help from @tsh. Previous 74-byte version also worked with negative numbers:

f=
(x,b,n,[i,d]=`${x.toString(b)}.`.split`.`)=>i+`.`+d.slice(0,n).padEnd(n,0)

<input id=x><input type=number min=2 max=36 value=10 id=b><input type=number min=1 max=20 value=10 id=n>


Tents and Trees feasibility Sequel to Verify Tents and Trees solution.
Background
Tents and Trees (try here) is a puzzle played on a square (or rectangular) grid, where the objective is to place tents horizontally or vertically adjacent to each of the trees, so that no two tents touch each other in 8 directions (horizontally, vertically, and diagonally) and the number of tents on each row/column matches the given clues.
Example puzzle and solution
In these examples, trees are T and tents are A.
Puzzle
  2 0 2 0 2 1
2 . T . T . .
1 . . . . T .
1 T . T . . .
2 . . . . . T
1 T . . . . .
0 . . . . . .

Solution
  2 0 2 0 2 1
2 . T A T A .
1 A . . . T .
1 T . T . A .
2 A . A . . T
1 T . . . . A
0 . . . . . .

Challenge
Given a grid with some trees, determine whether it is possible to place tents next to each of the trees so that they don't touch each other in 8 directions. Ignore the number clues in this challenge.
You may take the input in any reasonable way to represent a matrix containing two distinct values to represent a tree and an empty space respectively.
You can choose to follow your language's convention of truthy/falsy, or use two distinct values for true/false respectively.
Standard code-golf rules apply. The shortest code in bytes wins.
Test cases
This uses the same notation as the above example; T for trees and . for empty spaces.
Truthy
. . .
. . .
. . . (empty board)

T .

. T .
. . T

. .
T T
. .

. T .
T . T
. T .

. . .
T T .
. T T
. . .

. T . .
. . . T
T T . .
. . . .

. T . . . .
. . . . . .
. . T . . T
. T . T . .
T . T . . .
. T . . T .

Falsy
(No space to place a tent)
T

T . T

T . T
. T .

. . . .
. T T T
T . . .

. T .
T T .
. T .

T . T
. . .
. T .

T . . . .
. . T . .
. T . T .
T . T . .
. T . . .

. . . . .
. T . . .
. T T . .
. . T T .
. . . . .

Python 3.8 (pre-release), 253 244 bytes

from itertools import*
f=lambda b,h,w:all(set(t:=[i%w+i//w*1jfor i,e in enumerate(b)if e])&set(s:=[*map(sum,zip(t,T))])or~any(abs(a-b)<2for a,b in combinations(s,2))+all(h>a.imag>-1<a.real<w for a in s)for T in product(*[[1,1j,-1,-1j]]*sum(b)))

Try it online!
-6 bytes thanks to @user202729 (chain comparisons)
-3 bytes thanks to @ovs (1jfor; …or a+1^b → …or~a+b for "implies" boolean operator)
# Itertools for combinations and product
from itertools import*
f=lambda b,h,w: all(
    # Test if a given set of tent position deltas works:
    # Positions are complex numbers: real part increasing to the right, imaginary part increasing down
    # (De Morgan shortened, so many expressions negated)
        # No tree is on a tent:
            # t:=Tree positions (1s)
            set(t:=[i%w+i//w*1j for i,e in enumerate(b)if e])
            # s:=Tent positions as sum of tree positions and deltas
            & set(s:=[*map(sum,zip(t,T))])
        # and difference between all distinct pairs oftrees is at least 2:
            or any(abs(a-b)<2for a,b in combinations(s,2))
        # and all trees are within rectangular boundary
            # (Using Python 2's quirky complex floordiv doesn't work since those return complex nums,
            # which don't have a total order.
            # Plus Python 38 has saves so much here; using 2 would be a waste anyway)
            >= all(h > a.imag > -1 < a.real < w for a in s)
    # For each possible delta (four directions, distance 1)
    # sum(b) is the number of tents since each tent contributes 1
    for T in product(*[[1,1j,-1,-1j]]*sum(b))
)


The longest consecutive traversal possible (number of edges) A truck fleet dispatcher is trying to determine which routes are still accessible after heavy rains flood certain highways. During their trips, trucks must follow linear, ordered paths between 26 waypoints labeled A through Z; in other words, they must traverse waypoints in either standard or reverse alphabetical order.
The only data the dispatcher can use is the trip logbook, which contains a record of the recent successful trips. The logbook is represented as a list of strings, where each string (corresponding to one entry) has two characters corresponding to the trip origin and destination waypoints respectively.
If the logbook contains a record of a successful trip between two points, it can be assumed that the full path between those points is accessible. Note that logbook entries imply that both directions of the traversal are valid. For example, an entry of RP means that trucks can move along both R --> Q --> P and P --> Q --> R. Note that the trips  A --> B and C -> D do not together imply that B -> C is usable. Entries can have the same character twice, such as C -> C, but this indicates no paths.
Given an array of logbook entries, your task is to write a function to return the length of the longest consecutive traversal possible; in other words, compute the maximum number of consecutive edges known to be safe. (In even more formal terms, compute the diameter of the largest tree on this graph.)
Example
For logbook = ["BG", "CA", "FI", "OK"], the output should be 8
Because we can get both from A to C and from B to G, we can thus get from A to G. Because we can get from F to I and access I from G, we can therefore traverse A --> I. This corresponds to a traversal length of 8 since 8 edges connect these 9 waypoints. O through K is a length 4 traversal. These two paths are disjoint, so no longer consecutive paths can be found and the answer is 8.

Guaranteed constraints:
1 ≤ logbook.length ≤ 100,
logbook[i].length = 2,
logbook[i][j] ∈ ['A'..'Z'].

Test Cases:
logbook: ["AZ"]
Output:25
logbook: ["AB", "CD"]
Output:1
logbook: ["BG",  "CA",  "FI",  "OK"]
Output: 8
logbook: ["KM",  "SQ",  "ON",  "XM",  "UK"]
Output:13
logbook: ["XU",  "WY",  "ZD",  "HH",  "BK",  "LG"]
Output: 24
logbook: ["QR",  "PC",  "TK",  "OE",  "YQ",  "IJ",  "HB"]
Output: 23
logbook: ["MG",  "QQ",  "JV",  "IZ",  "SQ",  "PN",  "TI",  "NK"]
Output: 19
logbook: ["II",  "ZW",  "CI",  "DT",  "IM",  "II",  "TR",  "XO",  "AL"]
Output: 25

The input will always be an array of strings, each of which has exactly two characters corresponding to the trip origin and destination waypoints respectively. The characters will always be letters, in a consistent case of your choice. The input will never contain more than 100 pairs.
Your program should output the longest consecutive traversal possible (number of edges) given the input.
This is code-golf so the shortest code in bytes wins

APL (Dyalog Unicode), 17 bytes

≢⍉↑⊆⍨∨/≠/∨⍀⎕a∘.=⎕

Try it online!


You call it Centering, I call it Code Golf "Let's face it, aligned images are like little gifts from Heaven. Welcome, but unexpected." - Geobits

+10000 reputation to whoever wins this challenge.

Rules:

1) You are to generate a program.

2) Input will be an image, however whether it is passed as a file or a list of numbers is up to you.

3) Output will be a file which when opened in paint (or similar) will show the image aligned.

4) The canvas size will always be between 100 x 100 and 2000 x 2000 pixels. It will always be a rectangle, but not always a square.

5) No hard coding of images or funky URL magic.

6) No external libraries to be used.

Guide to Centralisation (Joshpbarron Variant)

An image will be defined as centered if the 1st white(255,255,255,>0 rgba) or transparent(x,y,z,0 rgba) on an axis is equal distance (plus or minus 1 pixel) from the edge of the canvas.

This can be achieved (and will be verified by) the following method.

1) Imagine a bounding box around the object. (Black lines added for help)

2) Move the object around until the edge of the object is equal distance from the appropriate edge of the canvas.

3) Now forget the black lines.

Input:

Output:

More inputs here.

And respective outputs here.

The +10000 rep is a lie.

HTML5 + JavaScript (ES5), 515 bytes

That count includes the HTML tags as they are part of the program. If you only count the image processing code, it is 376 bytes including the function wrapper.

<canvas id=o></canvas><script>f=function(p){o=new Image();o.crossOrigin='Anonymous';o.src=p;o.onload=function(){v=document.getElementById('o'),c=v.getContext('2d');v.width=l=w=o.width;v.height=t=h=o.height;c.drawImage(o,0,0);for(k=255,d=c[g='getImageData'](0,0,w,h).data,r=b=i=0;i<d.length;)if((d[i++]<k||d[i++]<k||d[i++]<k)&&d[i++]){x=i/4%w;y=~~(i/4/w);l=l<x?l:x;t=t<y?t:y;b=b>y?b:y;r=r>x?r:x}n=c[g](l,t,r-l+1,b-t+1);c.clearRect(0,0,w,h);c.putImageData(n,(w-r+l)/2,(h-b+t)/2)}}</script><input onblur=f(this.value)>

Input

A URL to an image.

Security restrictions

Because this program is running in a browser environment, only URLs to CORS-enabled images will work. Imgur is CORS enabled.

IE 10 does not support CORS. I haven't tested in IE 11 yet but it does work in Chrome and Firefox.

How to run

Type/paste in a URL into the input field.
De-focus (tab/click out of) from the input field.

Output

It outputs on the canvas on the page.

As this is a browser-based application, security restrictions prevent automatic download of a file but you can right click and save image in Chrome and Firefox. I haven't tested on IE 11 yet.

Demo

JavaScript code has been removed from the script element and put into the appropriate area to accommodate Stack Snippets:

f = function(p) {
  o = new Image();
  o.crossOrigin = 'Anonymous';
  o.src = p;
  o.onload = function() {
    v = document.getElementById('o'), c = v.getContext('2d');
    v.width = l = w = o.width;
    v.height = t = h = o.height;
    c.drawImage(o, 0, 0);
    for (k = 255, d = c[g = 'getImageData'](0, 0, w, h).data, r = b = i = 0; i < d.length;)
      if ((d[i++] < k || d[i++] < k || d[i++] < k) && d[i++]) {
        x = i / 4 % w;
        y = ~~(i / 4 / w);
        l = l < x ? l : x;
        t = t < y ? t : y;
        b = b > y ? b : y;
        r = r > x ? r : x
      }
    n = c[g](l, t, r - l + 1, b - t + 1);
    c.clearRect(0, 0, w, h);
    c.putImageData(n, (w - r + l) / 2, (h - b + t) / 2)
  }
}
<canvas id=o></canvas>
<input onblur=f(this.value)>


N-dimensional pyramid numbers Given two inputs, a number n and a dimension d, generate the nth d-dimensional pyramid number.
That was confusing, let me try again.
For d = 1, the numbers start 1,2,3,4,5 and is the number of points in a line n points long.
For d = 2, the numbers start 1,3,6,10,15 and is the number of points in a triangle with side length n, also known as the triangle numbers e.g.
     0
    0 0
   0 0 0
  0 0 0 0

For d=3, the numbers start 1,4,10,20,35 and is the number of points in a pyramid of side n. For d=4, it's a 4-d pyramid, and so on.
Beyond this, visualization gets a bit tricky so you will have to use the fact that the nth d-dimensional pyramid number is equal to the sum of the first n d-1-dimensional pyramid numbers.
For example, the number of dots in a 3-d pyramid of side 5 is the sum of the first 5 triangle numbers: 1+3+6+10+15 = 35.
You can expect reasonable input (within your languages boundaries), although Standard loopholes apply. No builtins explicitly for this purpose (looking at you, Mathematica)
Numbers are 1-indexed, unless you specify otherwise.
Example recursive code in Javascript:
function pyramid(dim,num){                          //declare function
  if(dim == 0){                                     //any 0-dimensional is a single point, so return 1
    return 1;
  } else {                                          //otherwise
    function numbersUpTo(x){                        //helper function to get the numbers up to x
      if(x==0){                                     //no numbers up to 0
        return [];
      } else {                                      //otherwise recurse
        return [x].concat(numbersUpTo(x-1));
      }
    }
    var upto = numbersUpTo(num).map(function(each){ //for each number up to num
      return pyramid(dim-1,each);                   //replace in array with pyramid(dimension - 1,the number)
    });
    return upto.reduce((a,b)=>a+b);                 //get sum of array
  }
}

This is code-golf, so fewest bytes wins.

JavaScript (ES6), 24 bytes
Expects (n)(d).

n=>g=d=>d?n++/d*g(d-1):1

Try it online!


Maximum number of distinct substrings Description
Given a length n, and an alphabet size k>0, your program must determine the number of strings with those parameters which have a maximal number of unique substrings. In the case of k=2, this generates OEIS A134457.
Example
For example, 2210 has the substrings   , 2, 22, 221, 2210, 2, 21, 210, 1, 10, and 0, for a total of 11. However, 2 appears twice, so it only has 10 unique substrings.
This is as many as possible for a length 4 string containing 3 different symbols, but it ties with 35 other strings for a total of 36 tieing strings including 0012, 2101, and 0121. Therefore, for n=4 and k=3, your program should output 36.
Test Cases
n    k    output

0    5    1
1    3    3
5    1    1
9    2    40
2    3    6
5    5    120

Pyth, 12 bytes
l.Ml{.:Z)^UE

Try it online.
Pure brute force.
Explanation

Implicit: append Q to the program.
Implicit: read and evaluate a line of input (n) in Q.
E: read and evaluate a line of input (k).
U: get a range [0, ..., k-1].
^: get all n-length strings of [0, ..., k-1].
.M: find the ones that give a maximum for function f(Z):

.:Z: find the substrings of Z
{: remove duplicates
l: get the number of unique substrings

l: get the number of such strings


Calculate The Digit Sum Your task is to get two numbers, and output the digit sum of them. We'll define digit sum as the following:

take the decimal (base 10) digits of each of them, and pad with 0s the shortest number (e.g. [1,9], [0, 7])
sum the digits as vectors (e.g. [1, 16])
convert the number back from base 19, and output it (e.g. 1*19+16=35)

Input
You can take the input as two numbers, as a list containing both of them or in any other reasonable format (like an array of digits). You can assume the shortest number is padded with zeros so it fits the length of the longer one
Output
You can output the digit sum in any reasonable format.
Test cases
1, 2 -> 3
5, 10 -> 24
42, 32 -> 137
15717, 51358 -> 826819
1000, 1 -> 6860

explanation of 5, 10: the digits of these are [0, 5] and [1, 0]. Their sum is [1, 5], which when converted from base 19 results in 24.
Scoring
This is code golf, so the shortest answer wins, good luck!

J, 6 bytes

19#.+/

Try it online!

19#. convert the following to base 19...
+/ elementwise sum of the input digit lists.


Sort a list of numbers About Code-Bowling:

  In golf, you try to get the lowest score (smallest application, most elegant, etc). In Bowling, you try to get the highest score. So if you follow, the goal of a Code-Bowling challenge is to make the biggest, most bastardized, hardest to maintain piece of code that still meets the requirements of the challenge. However, there's no point in making source longer just for the sake of it. It needs to seem like that added length was from design and not just padding.

The Challenge:

Create a program that sorts a list of numbers in ascending order.

Example:

Input: 1, 4, 7, 2, 5

Output: 1, 2, 4, 5, 7

Code: Obviously this wouldn't be a good answer, since there aren't many WTFs in there

function doSort(array $input) {
    sort($input);
    return $input;
}

Rules:

There are no real rules.  As long as the program functions, have at it!

Remember: This is code-bowling, not golf.  The objective is to make the worst, most bastardized code that you can!  Bonus points for code that looks good, but is actually deceptively evil...

Sorting by user input. What can be worse?

function sort(array) {
    newArray = new Array
    notSorted = true;
    while (notSorted) {
        sortfail = false;
        i = -1
        for (;;) {
            if ((++i + 1) == array.length) break;
            if (confirm("is " + array[i] + " less than " + array[i + 1])) {
                newArray[i] = array[i]
                newArray[i + 1] = array[i + 1]
            } else {
                newArray[i] = array[i + 1]
                newArray[i + 1] = array[i]
                array[i] = newArray[i]
                array[i + 1] = newArray[i + 1]
                sortfail = true
            }
        }
        array = newArray;
        if (!sortfail) notSorted = false
    }
    return array
}

console.log(sort([2,1,3]))

See live example


Is it an exercise set? We all know that a lot of exercises only affect one half of your body, so you have to do them twice, once for each side. Such exercises have two counterparts, one for the left side and one for the right. However, there's no need to execute the two counterparts consecutively, as long as the exercises for both sides are in the same order. You may as well switch between sides in your exercise program, but it wouldn't make sense to start some exercises with one side and some with the other.

Challenge

An exercise part is a list of non-zero integers, where its second half consists of the integers of the first half negated and in the same order, and the signs of the integers on each half are equal. The sign of the first half of an exercise part is its leading side.

An exercise set is zero or more exercise parts with the same leading side concatenated together.

Given a list of non-zero integers as input, determine if it is an exercise set. The integers aren't necessarily unique. The list's length isn't necessarily even.

Your solution may not use any of the standard loopholes. You may use any two different consistent values for output. This is code-golf, so the shortest solution wins.

Examples

[-5, -1, -7, -6, -5, 5, 1, 7, 6, 5] is an example of an exercise part. The first half is [-5, -1, -7, -6, -5], and the last half is [5, 1, 7, 6, 5], which is each integer in the first half negated. Additionally, the first half's integers are all of the same sign. This exercise part's leading side is -1.

[3, 6, 5, -3, -6, -5, 1, 6, 4, 3, -1, -6, -4, -3] is an example of an exercise set. Its individual exercise parts are [3, 6, 5, -3, -6, -5] and [1, 6, 4, 3, -1, -6, -4, -3], and they both have leading side 1.

[4, -4, -5, 5], despite only consisting of valid exercise parts, isn't an exercise set, since the first part, [4, -4], has leading side 1, while the second part, [-5, 5], has leading side -1.

Test cases

Valid test cases:

[]
[1, -1]
[1, -1, 1, -1]
[-6, 6, -5, -4, -3, 5, 4, 3]
[-1, -5, -8, 1, 5, 8, -7, -6, -5, -3, 7, 6, 5, 3]
[-1, -5, -8, 1, 5, 8, -1, 1]

Invalid test cases:

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

Python 2, 69 67 bytes

a,b=x=[[],[]];k=0
for n in input():x[n>0]+=n*n,n*k>0;k=n
print a==b

Try it online!


Help me sort out my desktop windows! It's really frustrating when I'm working and I have a ton of windows open that are completely or partially hidden behind other windows. To make things worse, I'm still using two 1024x768 monitors.

Your task is to take a list of coordinates that designate the area, in pixels, on a screen, that a list of windows occupy and output a truthy value if, for a 2 monitor set-up with 1024x768 resolution, all the following conditions are met:

None of the windows would overlap,
None of the windows would be partly off screen
None of the windows would straddle a boundary between the two monitors (so the order in which you visualize monitors 1 and 2 is irrelevant)

And a falsey value if any of these criteria are not met.

You may assume that all windows are rectangular, and that no coordinates are negative in the input, which is in a file, in stdin, or in a list of tuples, is in the following format:

monitor-number left-x bottom-y right-x top-y
monitor-number left-x bottom-y right-x top-y
monitor-number left-x bottom-y right-x top-y

Where each line contains the ID of the monitor (which can either be in [1, 2] or [0, 1] depending on which is easier for your language), and the dimensions of a window.

For example, the following input will result in a truthy output because none of the windows overlap:

1 10 10 100 200
1 210 300 600 600
2 10 10 100 200

The following input will result in a falsey value because lines 1 and 3 result in an overlap:

1 10 10 50 50
2 5 5 600 200
1 20 20 80 80

The following input will result in a falsey value because it would partially off-screen on one of the monitors:

1 1000 400 1400 300

This is code-golf so the shortest solution wins.

Jelly, 33 bytes

<⁽¡ð,769FẠ
Ḋs2Zr/€p/;€Ḣµ€ẎµQL⁼LȧÇ

A monadic link taking a list of lists of the window-data and returning 0 if any windows exceed their monitor's space or overlap, or 1 otherwise.

Uses 1-indexed monitor IDs; 1,1 to 1024,768 inclusive are considered on-screen.

Try it online! (Too slow for the first two test cases! Typical golf :))

How?

The reason this is so slow is because it creates all the pixels for all the windows, each with its monitor ID and checks for overlap using de-duplication (which is implemented using lists not sets). It also checks each pixel is on-screen rather than checking just the input corners. All in all very inefficient...

Test-case 1 succeeded (1) locally in only eleven minutes! Test-case 2 succeeded (0) in less.

<⁽¡ð,769FẠ - Link 1 check pixels are on-screen: list of lists, each being [x,y,ID]
 ⁽¡ð       - literal base-250 integer = 1025
    ,769   - pair with literal 769
<          - less than (vectorises) -> [[x<1025, y<769, ID],...]
        F  - flatten into a single list
         Ạ - all truthy?

Ḋs2Zr/€p/;€Ḣµ€ẎµQL⁼LȧÇ - Main link: list of lists, each being [ID,Lx,By,Rx,Ty]
            µ€         - for €ach window:
Ḋ                      -   dequeue -> [Lx,By,Rx,Ty]
 s2                    -   split into twos -> [[Lx,By],[Rx,Ty]]
   Z                   -   transpose -> [[Lx,Rx],[By,Ty]]
     /€                -   reduce €ach with:
    r                  -     inclusive range -> [[Lx,...,Rx],[By,...,Ty]]
        /              -   reduce with:
       p               -     Cartesian product -> all pixels, [[Lx,By],[Lx,By+1],...[Lx,Ty],[Lx+1,By],... ...[Rx,Ty]]
           Ḣ           -   head -> ID
         ;€            -   concatenate each pixel with the monitor ID
              Ẏ        - tighten -> one list of all window's [x,y,ID] values
               µ       - monadic chain separation, call that w
                Q      - deduplicate (unique [x,y,ID] values)
                 L     - length
                   L   - length of w
                  ⁼    - equal?
                     Ç - call last link (1) as a monad (all on-screen?)
                    ȧ  - logical and


Cyclic strings, hidden programs Write 3 programs that do the following task:
Let A, B, C source codes of those three programs;

if A runs BC is produced as output,
if B runs CA is produced,
if C runs AB is produced;

so each program writes a string (cycled for each program) and hides itself from it.
Additional, but essential constraints:

standard loopholes are forbidden;
each program must be at least 1 byte long;
each of three programs must be written in a different language;

It would be nice if your submission had this format:
Language A (size of A) - Language B (size of B) - Language C (size of C) - Score
A B C
<extra stuff>

Winner is someone who get the minimum score, which is the sum of sizes of three programs.

Befunge-98, Gol><> and Wumpus 47*3 = 141 bytes

"r75*1-47*0.@o&r84#o&]=74#]=\`/KHj '!_@#,k.'g00

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

That's right, it's the same program three times over! When run in any of the above languages, it prints the source code twice, which is the other two programs concatenated.

How It Works:

Befunge code:
  "r                               j '!_@#,k.'g00

  "   Wrapping string literal over code
   r  Reflect the pointer
  "   Wrapping string literal
                                              g00   Fetch " from cell 0,0
                                          ,k.'      Print 47 characters
                                       _@#          If the next character is 0, exit
                                      !             Otherwise, set it to 0
                                   j '              And jump back to the beginning

Gol><> code:
  "r75*1-47*0.                \`/KH

  "             Wrapping string literal
   r            Reverse stack
    75*1-       Push "
         47*0.  Jump to cell 28,0
                              \  Continue right
                               `/K   Duplicate the top 47 characters on the stack
                                  H  Halt and output stack contents

Wumpus code:
  "r75*1-47*0.@o&r84#o&]=74#]=\

  "r75*1-47*0.  Exact same function as the ><> code, but with a bouncing string literal
                              \  Reflect left
                            ]=   Push a copy of the " to the bottom of the stack
                         74#     Push 47
                       ]=        Push a copy of the 47 to the bottom of the stack
                     o&          Print the top 47 characters
                  84#            Push a '0' to make up for the missing 0 at the end
               o&r               Reverse the stack and print the top 47 characters
              @                  And terminate


Detect rotated strings Read two strings from stdin.
Output Yes if one string is a rotated version of the other.
Otherwise output No

Testcases

Input

CodeGolf GolfCode

Output

Yes

Input

stackexchange changestackex

Output

Yes

Input

stackexchange changestack

Output

No

Input

Hello World

Output

No

Ruby 49 41

a,b=$*;puts (a*2).sub(b,'')==a ?:yes: :no

Edit: replaced gets.split by $*


Fold a string into a triangle Given a string whose length is divisible by 4, make a triangle as demonstrate below.

If the string is abcdefghijkl, then the triangle would be:

   a
  b l
 c   k
defghij

If the string is iamastringwithalengthdivisiblebyfour, then the triangle would be:

         i
        a r
       m   u
      a     o
     s       f
    t         y
   r           b
  i             e
 n               l
gwithalengthdivisib

If the string is thisrepresentationisnotatriangle, then the triangle would be:

        t
       h e
      i   l
     s     g
    r       n
   e         a
  p           i
 r             r
esentationisnotat

Notes

The string will only consist of characters from a to z.
Leading/Trailing whitespaces and newlines are allowed as long as the shape is not broken.
A list of strings as output is allowed.

This is code-golf. Shortest answer in bytes wins. Standard loopholes apply.

Charcoal, 25 22 21 bytes

≔÷Ｌθ⁴λ↙…θλ→✂θλ±λ↖✂θ±λ

Try it online! Link is to verbose version of code. Simply slices the string into three parts and prints them in the appropriate directions. Edit: Saved 3 bytes by using integer division and slicing. Saved a further byte by using CycleChop instead of Slice for the head of the string. Edit: Charcoal now supports drawing arbitrary text along the edge of a polygon, simplifying the code to 12 bytes:

ＧＨ↙→→↖⊕÷Ｌθ⁴θ

Try it online! Link is to verbose version of code.


Unscramble those case-(very)-sensitive strings Goal
This is a simple challenge. Your goal is to unscramble a string by swapping each letter with the next letter of the same case, while leaving non-letter characters unchanged.

Step by step explanation

The first character is a E. We look for the next letter in upper case: it's a C. We swap these characters, which leads to CdoE!.

We advance to the next character: this is a d. We look for the next letter in lower case: it's a o. We swap these characters, which leads to CodE!.

We advance to the next character: this is the d that we've just moved here. We ignore it, because it has already been processed.

We advance to the next character: this is the E that was moved here at step #1. We ignore it, because it has already been processed.

We advance to the next character: this is a !. We ignore it, because it's not a letter.

Rules

You can assume that the input string is made exclusively of printable ASCII characters, in the range 32 - 126.

You may write either a full program or a function, which either prints or returns the result.

If the input string contains an odd number of letters, the last remaining letter can't be swapped with another one and should remain in place, no matter its case. The same logic applies if the string contains an even number of letters, but an odd number of uppercase letters and an odd number of lowercase letters.

This is code-golf, so the shortest answer in bytes wins. Standard loopholes are forbidden.

Test cases
Input : lLEhW OroLd!
Output: hELlO WorLd!

Input : rpGOZmaimgn uplRzse naC DEoO LdGf
Output: prOGRamming puzZles anD COdE GoLf

Input : eIt uqHKC RBWOO xNf ujPMO SzRE HTL EOvd yAg
Output: tHe quICK BROWN fOx juMPS OvER THE LAzy dOg

Input : NraWgCi: Nsas-eNEiTIsev rNsiTG!!
Output: WarNiNg: Case-sENsITive sTriNG!!

Not-so-random test cases:
Input : (^_^)
Output: (^_^)

Input : AWCTY HUOS RETP
Output: WATCH YOUR STEP

Input : hwn oeesd acsp nawyya
Output: who needs caps anyway

Input : SpMycaeIesKyBorekn
Output: MySpaceKeyIsBroken

Input : D's mroyr, Ivam. I'e faardi I act'n od htta.
Output: I'm sorry, Dave. I'm afraid I can't do that.

Retina, 53 bytes

Not really clever, but a clean and quite readable solution

([a-z])(.*?)([a-z])
$3$2$1
([A-Z])(.*?)([A-Z])
$3$2$1

Try it online!


Equality in the sum of digits Introduction
Let's take the number 180. This is an interesting number because the sum of digits of this number is equal to:
1 + 8 + 0 = 9

And the squared version of this number, or:
180² = 32400 > 3 + 2 + 4 + 0 + 0 = 9

These are both 9. The sum of digits of the original number and the squared number are the same. Of course, this is also found at OEIS: A058369.
Task
Given a non-negative integer n, output the nth positive number with this condition.
Test cases (zero-indexed)
Input > Output

0 > 1
1 > 9
2 > 10
3 > 18
4 > 19
5 > 45
6 > 46
7 > 55
8 > 90
9 > 99
10 > 100
11 > 145
12 > 180
13 > 189
14 > 190
15 > 198
16 > 199
17 > 289
18 > 351
19 > 361

The input can also be 1-indexed if that fits you better.
This is code-golf, so the submission with the least amount of bytes wins!

Jelly, 13 bytes

,²DS€=/
1Ç³#Ṫ

Input is 1-indexed. Try it online!

How it works

1Ç³#Ṫ    Main link. Argument: n (index)

1        Set the return value to 1.
   #     Execute ... until ... matches have been found.
 Ç         the helper link
  ³        n
    Ṫ    Extract the last match.

,²DS€=/  Helper link. Argument: k (integer)

,²       Pair k with k².
  D      Convert each to decimal.
   S€    Compute the sum of each list of base 10 digits.
     =/  Reduce by equality.


Amicable number calculator Write a program that calculates amicable numbers, starting from [0,0], intil the maximum value for an integer is reached in the language you chose to write it in.

Amicable numbers are two different numbers so related that the sum of the proper divisors of each is equal to the other number. (A proper divisor of a number is a positive integer divisor other than the number itself. For example, the proper divisors of 6 are 1, 2, and 3.) A pair of amicable numbers constitutes an aliquot sequence of period 2. A related concept is that of a perfect number, which is a number which equals the sum of its own proper divisors, in other words a number which forms an aliquot sequence of period 1. Numbers that are members of an aliquot sequence with period greater than 2 are known as sociable numbers.

For example, the smallest pair of amicable numbers is (220, 284); for the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110, of which the sum is 284; and the proper divisors of 284 are 1, 2, 4, 71, and 142, of which the sum is 220.

If you want more information on amicable numbers, here's a link to Wikipedia's entry on the subject.

NOTE: It cannot use pre-determined tables of which are and which are not amicable numbers

EDIT: I suppose I should have said how I will determine the winner:
Your score will be calculated by this formula: Total_characters_of_code / Up_votes = Score
I will select an answer on Sunday, May 1.
The lowest score wins!

Golfscript (51 50 chars)

2{.{:a,(\{.a\%!*+}/}:^~1$>{..^^={[..^](\p}*}*).}do

The core is the override of ^ as :a,(\{.a\%!*+}/ which finds the aliquot of the number on the top of the stack (call it n) by the grossly inefficient approach of considering every number from 1 to n-1 to see whether it's a factor.


Complex Binary Numbers Let's create a simple, surjective mapping from positive integers to Gaussian integers, which are complex numbers where the real and imaginary parts are integers.

Given a positive integer, for example 4538, express it in binary with no leading 0's:

4538 base 10 = 1000110111010 base 2

Remove any trailing 0's:

100011011101

Replace any runs of one or more 0's with a single +:

1+11+111+1

Replace all 1's with i's:

i+ii+iii+i

Evaluate the resulting complex expression and output the simplified Gaussian integer:

i+ii+iii+i = i+i*i+i*i*i+i = 2i+i^2+i^3 = 2i+(-1)+(-i) = -1+i

The output can be expressed in a traditional mathematical way, or given as two separate integers for the real and complex parts. For the 4538 example, any of these would be fine:

-1+i
i-1
-1+1i
(-1, 1)
-1 1
-1\n1

For inputs like 29, mathy formatted outputs such as 0, 0i, or 0+0i are all fine.

Using j (or something else) instead of i is fine if that is more natural for your language.

The shortest code in bytes wins.

MATL, 7 bytes
BJ*Y'^s

Try it online!
How it works
Consider input 4538 for example.
B     % Implicit input. Convert to binary
      % STACK: [1 0 0 0 1 1 0 1 1 1 0 1 0]
J*    % Multiply by 1i
      % STACK: [1i 0 0 0 1i 1i 0 1i 1i 1i 0 1i 0]
Y'    % Run-length encoding
      % STACK: [1i 0 1i 0 1i 0 1i 0], [1 3 2 1 3 1 1 1]
^     % Power, element-wise
      % STACK: [1i 0 -1 0 -1i 0 1i 0]
s     % Sum of array. Implicit display
      % STACK: -1+1i


Generate a special period image Construct a program or function that takes input in form of
<width>, <height>, <color1>, <color2>

and generates an output such that first row alternates between pixels of color  <color1> and <color2> with a period of <height>. For each row that follows, the period shall be <height> - <row number>. Note that <color1> always begins the row.
Sample Output
Input 120, 6, #000000, #FFFF00:

Input 80, 50, #000000, #FFFF00:

(Sample output has been scaled for clarity)
This is code-golf, so the shortest valid entry in bytes wins.

JavaScript (ES6), 177 bytes

g=
(w,h,f,b)=>`<svg${s=` width=${w} height=`+h}><rect${s} fill=${b} />`+[...Array(h)].map((_,i)=>`<line stroke=${f} stroke-dasharray=${h-i} x1=0 y1=${i} x2=${w} y2=${i} />`).join``
Width: <input id=w value=80 type=number min=1>
Height: <input id=h value=50 type=number min=1>
Foreground: <input id=f value=#000000>
Background: <input id=b value=#FFFF00>
<input type=button value=Go! onclick=o.innerHTML=g(+w.value,+h.value,f.value,b.value)>

Outputs an HTML5-compatibile SVG image.


Selectively murder positive integers Introduction

Arithmetic Gaol is a special facility that incarcerates positive integers. However, recently, the positive integers have been trying to escape. Therefore the wardens have decided to, um, eliminate some of the positive integers to send a message to the other integers. They have hired a software engineer to write a program to figure out which integers to eliminate for maximum effect.

Input Description

Input is given via STDIN, command line arguments, or a user input function (such as raw_input). You can't have it as a function argument or a preinitialized variable (e.g. this program expects input in a variable x).

The first line of input contains a single positive integer n where 8 >= n >= 3. Following that are n lines containing n characters from the set [1,2,3,4,5,6,7,8,9]. Here is an example input:

5
22332
46351
65455
24463
65652

Output Description

The wardens would like to eliminate numbers so that the following conditions are met:

In each row and column of the resulting grid, no number will appear twice;
No two eliminated numbers may be adjacent horizontally or vertically;
The surviving numbers must form an orthogonally contiguous group -- it will be possible to travel from any surviving number to any other surviving number moving only horizontally and vertically and never crossing any eliminated number.

Output the input (minus the first line), with the eliminated numbers replaced with #.

There may be more than one solution. If that is the case, you may output any solution.

There may also be no solution. If that is the case, output the string no answer.

Here is a possible output for the example input:

#2#3#
46351
6#4#5
24#63
#56#2

Example Inputs and Outputs

There are multiple outputs for each input, so these outputs are just examples.

Input:

5
46551
51565
32654
14423
43244

Output:

46#51
#156#
326#4
1#423
#324#

Input:

7
7183625
1681563
5238564
8786268
1545382
3814756
5325345

Output:

71#362#
#6815#3
5238#64
#7#62#8
154#382
3814756
#325#4#

Input:

8
21534768
75196287
68392184
96244853
44865912
76516647
89751326
43698979

Output:

21#34768
#5196287
683#21#4
9#24#853
#4865912
7#51#64#
89751326
436#8#7#

Input:

4
2222
2331
3112
1322

Output:

no answer

Ruby - 541..., 394

The basic algorithm is a recursive depth-first search of duplicates to affirmatively select, looking through row 1, then column 1, then row 2, etc, and checking that two neighbors are not killed and that the grid is connected (that's the break if clause in there, and the bit that comes before it).

K=(0...(N=gets.to_i)*N).to_a
J=gets(p).split*''
H=->m{K&[m+1,m-1,m+N,m-N]}
Q=->k{s=[k[j=0]]
(j=s.size
s.map{|x|(s+=H[x]&k).uniq!})while s[j]
break if(K-k).any?{|m|(H[m]-k)[0]}||k!=k&s
$><<K.map{|m|[k.index(m)?J[m]:?#,m%N>N-2?"
":p]}*''|exit if !g=((0...N*2).map{|x|(k.select{|m|m.divmod(N)[x/N]==x%N}.group_by{|m|J[m]}.find{|l,c|c[1]}||[])[1]}-[p]).min
g.map{|d|Q[k-g<<d]}}
Q[K]
puts"no answer"

Some neat tricks:

if w[1] is much shorter than if !w.one? and if you know there's at least one member, it's the same result.

Similarly, [0] is shorter than any? if there's no block, and s[j] is a cute shortcut for j<s.size (technically, it's more like j.abs<s.size)

And y%N+(y/N).i is much shorter than Complex(y%N,y/N)

Also, when there's two complicated conditionals to generate strings, it might be shorter to do [cond1?str1a:str1b,cond2?str2a:str2b]*'' than to add all the parens or #{}s in.

Ungolfing and explanation:

(This is from the 531 byte version.  I've made changes.  Most notably, I've since eliminated the call to product - just solve one digit per row/column at a time, and J is now just an array, indexed by integers. All coordinates are just integers.)

H calculates neighbors

def H m
  # m, like all indices, is a complex number
  #    where the real part is x and the imaginary is y
  # so neighbors are just +/-i and +/-1

  i='i'.to_c
  neighborhood = [m+1, m-1, m+i, m-i]

  # and let's just make sure to eliminate out-of-bounds cells
  K & neighborhood
end

N is the size of the grid

N = gets.to_i

K are the keys to the map (complex numbers)

# pretty self-explanatory
# a range of, e.g., if N=3, (0..8)
# mapped to (0+0i),(1+0i),(2+0i),(0+1i),(1+1i),(2+1i),...
K = (0..N**2-1).map{|y| (y%N) +(y/N).i }

J is the input map (jail)

# so J is [[0+0,"2"],[0+1i,"3"],....].to_h
J=K.zip($<.flat_map {|s|
  # take each input line, and...
  # remove the "\n" and then turn it into an array of chars
  s.chomp.chars
}).to_h

k are the non-killed keys

# starts as K

Q is the main recursive method

def Q k
  j=0 # j is the size of mass
  # the connected mass starts arbitrarily wherever k starts
  mass=[k[0]]
  while j < s.size # while s hasn't grown
    j = mass.size
    mass.each{|cell|
      # add all neighbors that are in k
      (mass+=H[cell] & k).uniq!
    }
  end
  # if mass != k, it's not all orthogonally connected
  is_all_connected = k!=k&mass

  # (K-k) are the killed cells
  two_neighbors_killed = (K-k).any?{|m|
    # if any neighbors of killed cells aren't in k,
    # it means it was killed, too
    (H[m]-k)[0]
  }
  # fail fast
  return if two_neighbors_killed || is_all_connected

  def u x
    x.group_by{|m|J[m]}.select{|l,c|c[1]}
  end

  rows_with_dupes = Array.new(N){|r|u[k.select{|m|m.imag==r}]}

  cols_with_dupes = Array.new(N){|r|u[k.select{|m|m.real==r}]}

  # dupes is an array of hashes
  # each hash represents one row or column.  E.g.,
  #   {
  #     "3"=>[(0+0i),(1+0i),(3+0i)],
  #     "2"=>[(2+0i),(4+0i)]
  #   }
  # means that the 0th, 1st and 3rd cells in row 0
  # all are "3", and 2nd and 4th are "2".
  # Any digits without a duplicate are rejected.
  # Any row/col without any dupes is removed here.
  dupes = (rows_with_dupes+cols_with_dupes-[{}])

  # we solve one row at a time
  first_row = dupes[0]

  if !first_row
    # no dupes => success!
    J.map{|m,v|k.member?(m)?v:?#}.each_slice(N){|s|puts s*''}
    exit
  else
    # the digit doesn't really matter
    t=first_row.values

    # cross-multiply all arrays in the row to get a
    # small search space. We choose one cell from each
    # digit grouping and drop the rest.
    t.inject(:product).map{ |*e|
      # Technically, we drop all cells, and add back the
      # chosen cells, but it's all the same.
      new_k = k-t.flatten+e.flatten

      # and then search that space, recursively
      Q[new_k]
    }
  end
end

The code is executed with:

# run with whole board
Q[K]

# if we get here, we didn't hit an exit, so we fail
puts"no answer"

Changelog

394 added @blutorange's suggestion below, and chopped out a lot more manipulation

408 revised output once more. Also use .min instead of .inject(:+) since I'm just taking one row anyway.

417 shorter output calculation

421 dropped complex numbers. Just use integers. Save a bundle

450 more input improvements

456 input improvements

462 incremental improvements - esp. find, not select

475 dropped u and squashed the row/col dupe builder

503 only solve one duplicate digit per row/column at a time.

530 use map &:pop instead of values

531 pull out the lambda that makes the dupes array

552 oops! missed a requirement

536 marginally improved population of dupes array (what was formerly d)

541 initial


Build a small and balanced mobile You are given a bunch of weights, and your task is to build a small balanced mobile using those weights.

The input is a list of integer weights in the range 1 through 9, inclusive.  There may be duplicates.

The output is an ascii picture of a mobile that, when hung, would balance.  Perhaps best shown by example:

input

3 8 9 7 5

possible output

         |
   +-----+---------+
   |               |
+--+-+        +----+------+
|    |        |           |
8   ++--+     7           5
    |   |
    9   3

You must use the ascii characters as shown.  The horizontal and vertical segments may be of any length.  No part of the mobile may touch (horizontally or vertically) another unconnected part of the mobile.  All weights must be hung from a vertical segment of length at least 1, and there must be a vertical segment from which the whole mobile is hung.

The size of a mobile is the total number of +,-,and | characters required to build it.  Lower sizes are better.

You may put as many connections on a segment as you would like.  For example:

input

2 3 3 5 3 9

possible output

           |
   +---+---+-----------+
   |   |               |
+--+-+ 5               9
|  | |
2  | 3
   |
  +++
  | |
  3 3

The winning program is the one that can generate the lowest average of mobile sizes for a test set of inputs.  The real test is super-secret to prevent hard-coding, but it will be something like this:

8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7
1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 7 7
3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7

Python 2.

I'm cheating a little bit:

I only construct mobiles with one horizontal. I have a feeling (but I haven't proven it) that the optimal mobile under the given conditions actually always does only have one horizontal. Edit: Not always true; with 2 2 9 1 Nabb has found a counter-example in the comments below:

Size 18:                Size 16:
   |                        |
+-++--+-----+            +--++-+
| |   |     |            |   | |
2 9   2     1           -+-  9 1
                        | |
                        2 2

I just do stupid brute-forcing:

The given weights are shuffled randomly.
Two weights at a time are placed on the mobile in the best positions such that it stays balanced.
If the resulting mobile is better than any that we had before, remember it.
Rinse and repeat, until a pre-defined number of seconds is up.

My results for your sample inputs; each was run for 5 seconds (I'm aware that this is ridiculous for the small ones – just going through all possible permutations would be faster). Note that since there's a random element, subsequent runs may find better or worse results.

3 8 9 7 5
Tested 107887 mobiles, smallest size 20:
        |
+-+-----+-+--+
| |     | |  |
5 3     7 9  8

2 3 3 5 3 9
Tested 57915 mobiles, smallest size 23:
      |
+--+-++--+-+---+
|  | |   | |   |
3  5 9   3 3   2

8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7
Tested 11992 mobiles, smallest size 50:
                |
+-+-+-+--+-+-+-+++-+-+--+-+-+-+-+
| | | |  | | | | | | |  | | | | |
8 8 8 8  8 8 8 8 8 8 8  7 8 8 8 8

1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 7 7
Tested 11119 mobiles, smallest size 62:
                    |
+-+-+-+-+-+--+-+-+-+++-+-+-+--+-+-+-+-+-+
| | | | | |  | | | | | | | |  | | | | | |
2 7 5 6 6 8  3 2 3 7 9 7 8 1  1 7 9 5 4 4

3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7
Tested 16301 mobiles, smallest size 51:
                |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | | | | |
4 6 5 7 7 4 6 5 3 5 6 4 7 6 7 5 4

The code (verbose, as this isn't code golf):

import time, random

def gcd(a, b):
    while b > 0:
        a, b = b, a % b
    return a

class Mobile(object):
    def __init__(self):
        self.contents = [None];
        self.pivot = 0;

    def addWeights(self, w1, w2):
        g = gcd(w1, w2)
        m1 = w2 / g
        m2 = w1 / g
        mul = 0
        p1 = -1
        while True:
            if p1 < 0:
                mul += 1
                p1 = mul * m1
                p2 = -mul * m2
            else:
                p1 *= -1
                p2 *= -1
            if self.free(p1) and self.free(p2):
                self.add(w1, p1)
                self.add(w2, p2)
                return

    def add(self, w, pos):
        listindex = self.pivot - pos
        if listindex < 0:
            self.contents = [w] + (abs(listindex) - 1) * [None] + self.contents
            self.pivot += abs(listindex)
        elif listindex >= len(self.contents):
            self.contents += (listindex - len(self.contents)) * [None] + [w]
        else:
            self.contents[listindex] = w

    def at(self, pos):
        listindex = self.pivot - pos
        if 0 <= listindex < len(self.contents):
            return self.contents[listindex]
        return None

    def free(self, pos):
        return all(self.at(pos + d) is None for d in (-1, 0, 1))

    def score(self):
        return 1 + 2 * len(self.contents) - self.contents.count(None)

    def draw(self):
        print self.pivot * " " + "|"
        print "".join("+" if c is not None or i == self.pivot else "-" for i, c in enumerate(self.contents))
        print "".join("|" if c is not None else " " for c in self.contents)
        print "".join(str(c) if c is not None else " " for c in self.contents)

    def assertBalance(self):
        assert sum((i - self.pivot) * (c or 0) for i, c in enumerate(self.contents)) == 0

weights = map(int, raw_input().split())

best = None
count = 0

# change the 5 to the number of seconds that are acceptable
until = time.time() + 5

while time.time() < until:
    count += 1
    m = Mobile()

    # create a random permutation of the weights
    perm = list(weights)
    random.shuffle(perm)

    if len(perm) % 2:
        # uneven number of weights -- place one in the middle
        m.add(perm.pop(), 0)

    while perm:
        m.addWeights(perm.pop(), perm.pop())

    m.assertBalance() # just to prove the algorithm is correct :)
    s = m.score()
    if best is None or s < bestScore:
        best = m
        bestScore = s

print "Tested %d mobiles, smallest size %d:" % (count, best.score())
best.draw()


Program that adds all natural numbers and yields -1/12 As you might know there is a mathematical fun-fact that if you add all natural numbers you end up with... -1/12 (see Wikipedia here).

Of course this is very strange result and can not be obtained by just adding one number followed by another, but some special mathematical tricks.

However your task is to write a program, that looks like it attempts to add all natural numbers, but when you run it - it returns -1/12.

In pseudocode it might look like this:

result  = 0;
counter = 1;
while(true) {
  result  += counter;
  counter ++;
}
println(result);

You can do this in any way you like - you can exploit some buffer overflow, play with errors thrown while some variable becomes too big or just hide the crucial thing along the code in some clever way. The only conditions are that code should at first look as if it attempts to add all natural numbers and when run it returns -1/12 (in any format, it might be decimal, binary, text, ascii art whatever).

The code can of course contain much more, than shown above, but it should be clear enough, to fool reader.

This is popularity contest - vote for the most clever idea!

C

Should work on platforms where both sizeof(float) and sizeof(int) are 4 and follows the IEEE floating point standard (I guess).

Version 1:

#define toFloat(x) (*(float*)&x)
#define ABS(x)     (x<0 ? (-x) : x)
#include <stdio.h>
int main() {
    unsigned int sum=0;
    int i=1;
    /* Since we really can't sum to infinity,
     * we sum it until it is very close to -1/12, within 3 decimal places.
     * Need to convert sum to float since -1/12 is not int                 */
    while(!(ABS(toFloat(sum) + 1./12) <= 0.001)) {
        sum+=i;
        i++;
    }
    printf("%.3f\n", toFloat(sum));
    return 0;
}

Output: -0.083

Explanation:

   Not a very interesting answer, but with misleading comments.  The sum from 1 to 79774 is 3181985425, which has the same binary representation as -0.082638867199420928955078125 when interpreted as a float instead of an unsigned int.  Note that !(abs<=0.001) is used instead of abs>0.001 to avoid quitting the loop when the sum reaches 2139135936 (NaN in float). (Thanks to @CodesInChaos for suggesting this idea instead of an independent isNaN check.)

Special thanks to @Geobits for the idea of terminating the loop by comparing the sum instead of the counter.

Edit: Version 2

#include <stdio.h>
const float inf = 1./0.;
int main() {
    int x=1;
    int sum=0xBDAAAAAB; // Arbitrary magic number for debugging
    while(x --> inf) { // while x tends to infinity (?)
        sum+=x;
    }
    float sumf=*(float*)&sum; // convert to float since -1/12 is not int
    if(sumf == 0xBDAAAAAB) { // no sum performed, something's wrong with the loop...
        fprintf(stderr, "sum is unchanged\n");
        return -1;
    }
    printf("%f\n", sumf);
    return 0;
}

Output: -0.083333

Explanation:

   Uses the same int-to-float trick, but with the --> "tends to" operator here. Since every number is smaller than infinity the loop will not be executed even once.  After converting to float it is compared with the int magic number (i.e. -0.83333 is compared with 0xBDAAAAAB, or 3182078635), which of course is different.


Acrostic Poem - Programming TASK:

Make an acrostic poem in the lines.
e.g.

BATCH

break
attrib -h acrostic.txt
type acrostic.txt
cls
help

The output CAN also be an acrostic poem.

RULES:

Popularity Contest - the answer with highest vote wins!
You may create more than one.
Any language is accepted.
Every line must be executable.

bash - every man dies alone
This line writes the poem:
echo echo view echo renice yes make apropos nice date identify echo start apropos locate octave nice echo | xargs -n 1 | awk '{s = s substr($1, 1, 1); if ($1 == "echo"){print $1, "-n", s; s = "";}else print $1, "--they >.said 2>&1";}' > acrostic.sh

To see the poem:
$ cat acrostic.sh

To see the poem within the poem:
$ sh acrostic.sh


Write a haiku-w detector A haiku is a poem with three lines, with a 5/7/5 syllable count, respectively.

A haiku-w is poem with three lines, with a 5/7/5 word count, respectively.

Challenge

Write a program that will return true if the input is a haiku-w, and false if not.

A valid haiku-w input must consist of 3 lines, separated by a newline.

Line 1 must consist of 5 words, each word separated by a space.
Line 2 must consist of 7 words, each word separated by a space.
Line 3 must consist of 5 words, each word separated by a space.

Examples

The man in the suit
is the same man from the store.
He is a cool guy.

Result: True

Whitecaps on the bay:
A broken signboard banging
In the April wind.

Result: False

Rules

This is code-golf, so the shortest answer in bytes wins.
Standard code-golf loopholes apply. Cheating is prohibited.
Other boolean return values, such as 1 and 0, are acceptable.
A length-3 list of strings as an input is also acceptable.
Valid haiku-w inputs should not have leading or trailing spaces, or multiple spaces separating words.

JavaScript (ES6), 73 72 64 63 54 42 39 bytes

Thanks to Neil for saving 13 bytes

a=>a.map(b=>b.split` `.length)=='5,7,5'

Explanation

This is a fat-arrow function that takes an array of strings as argument. It replaces each line by its word count. If it is a haiku-w, a now contains an array of a five, a seven and a five again. Since JavaScript doesn't allow us to compare 2 arrays at the same time, the array is converted to a string first, and then compared. This results in a boolean that is returned.


Are there any languages especially good at ASCII art? I was wondering if there are any esoteric or golfing languages which specifically target text output and ASCII art?

For example, 05AB1E at least started by targeting base conversions. Are there any golfing languages targeting text output and text output art?

If so, do they have tip pages here, and are they in common use?

Note: I'm not looking for languages that are able to output ASCII art, but rather ones intentionally designed to be able to complete ascii-art challenges in a relatively short and concise way.

Well, as a matter of fact, there is! One such language is one I have been working on for a while called V.

Under the hood, V is just vim, but all of the keystrokes are run automatically, and the contents of the vim buffer are printed to STDOUT when the program is over. This just makes running it more convenient.

Some history on the language. When I started using the vim text editor for code-golf, I discovered that it's actually pretty good at it, but has some annoying features that make it more difficult to compete it. For example, you can set up a "while loop" of sorts by doing

qq<foobar>@qq@q

which will repeat <foobar> until an error happens. This has 7 bytes of boilerplate code. In V, this is shortened to ò<foobar>ò.

Some of the things that make V great for ASCII-art:

It is 2d by nature. One feature is that is has a "cursor" position, where most of the commands do something based on where the cursor is in the text. The other commands move the location of the cursor. For example, x deletes a single character, but Wx moves forward a word and then deletes a character. Since most other languages are not intentionally 2 dimensional, this offers a nice edge when the challenge is about positioning text in 2D space
It is entirely string based. You can use some mathy operations, but these are usually the longer way to achieve things.
It uses regex compression to quickly change text.
All of it's internal memory, which is just a 2d array of characters, is implicitly printed when the program ends. Additionally, all inputs is implicitly added into it's internal memory, which is nice when most of the challenge is about changing the input in a certain way.

So I really enjoy using this language, and if you are looking for a specifically ascii-art language, I highly recommend it. However, I would also give a few disclaimers.

It is very confusing to learn. It's also very powerful, but because it's based on a very popular text editor that is 30 years old, there are lot's of obscure features that could very easily confuse new users.
Even though it is better at handling numbers than vim, it's number support is still not great. Personally, I think this makes it more fun to work in (kind of like using retina for tasks regex was never intended for). :D
It is still a WIP. There are some bugs, and some things I haven't gotten around to adding yet.
It doesn't have very many users. (Current number of users: 1).

If you are interested in learning more, here are some good resources:

A chat room where I would be happy to answer any questions you have, and help explain how it works to you.
A tips thread for golfing in vim, but most of the tips carry over.
A meta post describing V in some more detail.