Knock down walls in a maze Rules:

In this game you start at the top of a rectangular grid of size N x M made up of walls and open spaces. The input is N lines of M characters, where a . specifies an open space and a x specifies a wall. Your program should output the smallest number K such that there exists a path from the top left corner to the bottom right corner (no diagonals) that crosses K walls.

For example, given the input:

..x..
..x..
xxxxx
..x..
..x..

your program should output 2.

Other examples:

output 4:

xxxxx
x.x.x
x.x.x
x..xx

output 0:

.xxxxxxxx
.x...x...
.x.x.x.x.
.x.x...x.
...xxxxx.

output 6:

xx
xx
xx
xx
xx

Extra tidbits:

If it makes your life easier, you can specify N and M as command line parameters.

Extra credit if you can have your program print out the path in some form or another.

Ruby 1.9 (235) (225) (222) (214)

I don't know if this is shorter than a program based on Dijkstra, but I figured I would try a different approach. This uses regex in a loop to mark each space with the minimal number of walls required to reach it.

w=".{#{/\s/=~s=$<.read}}?"
j="([.x])"
s[0]=v=s[0]<?x??0:?1
(d=v[-1];n=v.succ![-1]
0while(s.sub!(/#{j}(#{w+d})/m){($1<?x?d: n)+$2}||s.sub!(/(#{d+w})#{j}/m){$1+($2<?x?d: n)}))while/#{j}/=~q=s[-2]
p v.to_i-(q==n ?0:1)

Input is specified as a file on the command line, i.e.

> ruby1.9.1 golf.rb maze.txt

Ungolfed:

# read in the file
maze = $<.read

# find the first newline (the width of the maze)
width = /\s/ =~ maze

# construct part of the regex (the part between the current cell and the target cell)
spaces = ".{#{width}}?"

# construct another part of the regex (the target cell)
target = "([.x])"

# set the value of the first cell, and store that in the current wall count
maze[0] = walls = (maze[0] == "x" ? "1" : "0")

# loop until the goal cell is not "." or "x"
while /#{target}/ =~ (goal = s[-2])

  # store the current wall count digit and the next wall count digit, while incrementing the wall count
  current = walls[-1]; next = walls.succ![-1]

  # loop to set all the reachable cells for the current wall count
  begin

    # first regex handles all cells above or to the left of cells with the current wall count
    result = s.sub!(/#{target}(#{spaces + current})/m) {
      ($1 == 'x' ? next : current) + $2
    }

    # second regex handles all cells below or to the right of cells with the current wall count
    result = result || s.sub!(/(#{current + spaces})#{target}/m) {
      $1 + ($2 == 'x' ? next : current)
    }
  end while result != nil
end

# we reached the goal, so output the wall count if the goal was a wall, or subtract 1 if it wasn't
puts walls.to_i - (goal == next ? 0 : 1)


Which Numbers Would Crash this Function? Which values of x and y will cause a crash with some C compilers?

int f(int x, int y) {
    return (y==0) ? 0 : (x/y);
}

-2147483648 (INT_MIN) and -1

#include <stdio.h>
#include <limits.h>
int f(int x, int y) {
    return (y==0) ? 0 : (x/y);
}
int main() {
    int r = f(INT_MIN, -1);
    printf("%d\n", r);
    return 0;
}

$ gcc -Wall division.c && ./a.out # => zsh: floating point exception  ./a.out


Exploring 10-Rep Questions Related

Introduction

As it happens, someone put forward the idea that, since PPCG has graduated, up votes on questions should be worth 10 rep. As a result, I started wondering how much rep I would have if it had always been 10 rep.

Challenge

Given a PPCG user's id as input, output how much total rep the user would have if question up votes were worth +10.

Example Calculation

I, Beta Decay (user id 30525), have 6744 rep. 3488 of that was earned by posting questions (calculated by subtracting the total rep lost from downvotes from the total rep gained from upvotes).

Firstly, we subtract 3488 from 6744, giving us 3256 rep, the amount earned from posting answers.

Next, we find out how much I would have earned from 10 rep questions by simply multiplying 3488 by 2, giving us 6976.

Finally, we add 3256 and 6976 together to get a final answer of 10232 rep.

A simplified method is to take the total, 6744 and add the rep from questions, 3488, giving is 10232 rep.

For continuity, you must use the method described above

Examples

Note that these examples are subject to change and are unlikely to stay current.

Helka Homba (UID 26997)

71398

Martin Ender (UID 8478)

121077

Downgoat (UID 40695)

21894

Rules

Internet access is allowed. Similarly, access to the Stack Exchange API is allowed. However, URL shorteners are disallowed.

T-SQL entrants using the Stack Exchange Data Explorer are allowed.

You also do not have to take into account the daily rep cap of 200.

Winning

Shortest code in bytes wins.

Python, 336 Bytes
Anonymous lambda function, takes a string.
Should work, but couldn't test it, because I drained my api quota.
(Warning! Will drain your api quota!)
import requests,re
lambda x,u="http://api.stackexchange.com/2.2/users/%s%s?site=codegolf&page=%d":int(re.search('n":\d+',requests.get(u%(x,"",1)).text).group()[3:])+sum([5*len(re.findall(':5,',requests.get(u%(x,"/reputation-history",i)).text))-2*len(re.findall('-2',requests.get(u%(x,"/reputation-history",i)).text))for i in range(99)])

a bit quota-friendlier:
import requests,re
f=lambda x,u="https://api.stackexchange.com/2.2/users/%s%s?site=codegolf&pagesize=100&page=%d":int(re.search('n":\d+',requests.get(u%(x,"",1)).text).group()[3:])+sum([5*len(re.findall(':5,',requests.get(u%(x,"/reputation-history",i)).text))-2*len(re.findall('-2',requests.get(u%(x,"/reputation-history",i)).text))for i in range(30)])


Self Referential Polynomials For every given degree n it is possible to construct (at least one) an integral polynomial p such that p(k) (p evaluated in k) is the coefficient of the term x^k in the polynomial for all 0 <= k <= n. To make them unique, we require the leading coefficient (the coefficient of x^n) to be positive and minimal.
These polynomials have some interesting properties, you can find some references in the thread that inspired me to do this challenge. You can also find those polynomials in https://oeis.org/A103423
One of the a priori unexpected properties is how the roots behave depending on n:

source (by /u/zorngov and /u/EpicSauceSc2)
Task
Given a nonnegative integer n output the self referential integral polynomial of degree n with minimal positive leading coefficient.
Details
The output can be in any human readable form, as string x^2-x-1, or also as a list of coefficients [1,-1,-1]. (The order of the coefficients can also be the other way around, it just needs to be consistent.)
First few outputs
n=0: 1
n=1: x
n=2: x^2-x-1
n=3: 10*x^3-29*x^2-6*x+19
n=4: 57*x^4-325*x^3+287*x^2+423*x-19
n=5: 12813*x^5-120862*x^4+291323*x^3+44088*x^2-355855*x-227362


Noughts and Crosses (aka Tic-Tac-Toe) Write a Notes and Crosses application.

User interface is optional.
You can output the computers move in text: eg 1x1 (meaning center square)

The computer must play an intelligent (extra marks for optimal) game.
Apart from its first move which should be random.

Player computer take turns at first move.
First player to win two games in a row wins.

Score:

Lowest strokes wins.
If equal best computer move algorithm (as I see fit)
If equal submitted date.

c99  -- 1229 characters (and needs nucrses)

#include <ncurses.h>
#include <string.h>
#define R return
#define A char
#define M mvprintw
#define I int
#define O "%c wins a game, press any key to %s."
A*s=" XOCHT";FILE *r;
I W(A*b){I i,p,q,r,w[]={0,1,2,0,3,6,0,2,3,3,3,1,1,1,4,2};if(!memchr(b,0,9))
R 3;for(i=0;i<16;i++){p=w[i/2];q=w[i/2+8];r=i%2+1;if((b[p]==r)&&(b[p+q]==r)
&&(b[p+q+q]==r))R r;}R 0;};
I C(A*b, I s){A c[9];for(I i=0;i<9;i++){memcpy(c,b,9);if(c[i]==0)c[i]=s;
if(s==W(c))R i;}R -1;};I P(A*b){I i;while(b[i=fgetc(r)%9]);R i;};
I D(A*b){A*p=" |-+";I i=0,j;for(;i<5;i++)for(j=0;j<5;j++)
mvaddch(i,j,p[2*(i%2)+j%2]);for(i=0;i<9;i++)mvaddch(2*(i/3),2*(i%3),
b[i]?s[b[i]]:'1'+i);refresh();};
I G(A m){I u=1,i,j;A b[9];memset(b,0,9);M(1,9,"Computer %c",s[m]);M(2,9,
"Human %c",s[m%2+1]);do{M(4,9,"Up %c",s[u]);D(b);if(u==m){if((i=C(b,m))<0&&(i=C
(b,m%2+1))<0)i=P(b);b[i]=m;}else{do{M(6,0,"your move ");refresh();scanw("%d",&i
);}while(i>10||i<1||b[i-1]!=0);b[i-1]=m%2+1;};u=u%2+1;}while(0==W(b));M(8,0,O,
s[W(b)],"continue");D(b);getch();M(8,0,"%44c",*s);R W(b)==3?5:u==m?4:3;}
I main(I c,A**v){A d=0, m=v[1][0]-'x'?2:1;r=fopen("/dev/random","r");
initscr();for(;;){c=G(m);if(c==d&&c-5)break;else M(4,25,"Previous winner %c",
s[c]),d=c;m=m%2+1;}M(9,0,O,c,"quit");getch();endwin();}

It gives away characters for the users convenience by using curses and having actual English prompts and informative lines. The obvious macro golfs have been made, but there are probably some comma and conditional operator improvements still available.

Is it smart? Well, it takes one move wins and blocks one move losses, but is otherwise quite random. (I may take the weekend to repair my interrupted CS education and learn about A* trees...) The "random first move" condition is met automatically as no one has the option to win at that point. Despite this obviously deficient AI I have yet to beat it when it holds X, so I have not defeated it by the "two in a row" rules.

Structurally we have a "is there a winner" function and a "can I win with a single play" function which works by coping the board and trying each position in turn with the isWon function. The single canWin function serves first to search for winning opportunities (by passing the computer's symbol) and then to search for things than need blocking (by passing the human's).

It declares Computer, Human, or Tie the winner on each game and only C or H for the series.

Now respects the spec as to winning conditions And plays well enough that you have to let it win or Ctrl-C to get out.

The version below differs from the above in prompts as well as macroization, but still represents the approach.

#include <ncurses.h>
#include <string.h>

char*s/*ymbols*/=" XOCHT";
FILE *r/*dev/random*/;

/* return the index of the side that wins, 0 if un-won or 3 if cat's game */
int W/*on*/(char*b){
  int i,p,q,r,w/*inning matrix*/[]={0,1,2,0,3,6,0,2,
                    3,3,3,1,1,1,4,2};
  if(!memchr(b,0,9))return 3; /* detect cat games by lack of open positions */
  for(i=0;i<16;i++){
    p=w[i/2];   /* starting position of the winning sequence to check */
    q=w[i/2+8]; /* step size of the winning sequence to check */
    r=i%2+1;  /* winning value to check */
    if( (b[p]==r) &&
    (b[p+q]==r) &&
    (b[p+q+q]==r) )
      return r;
  }
  return 0;
};
/* returns the first square in which the current side can win or -1 if none*/
int C/*an win?*/(char*b, int s/*ide to play*/){
  char c[9];
  for(int i=0;i<9;i++){
    memcpy(c,b,9);
    if(c[i]==0)c[i]=s;
    if(s==W(c))return i;
  }
  return -1;
};
/* returns a random unoccupied square */
int P/*ick a random move*/(char*b){
  /* assumes a move is possible and will loop forever if this
     condition is violated */
  int i;
  while(b[i=fgetc(r)%9])
    ;
  return i;
};
int D/*raw the board*/(char*b){
  char*p=" |-+";
  int i=0,j;
  for(;i<5;i++)
    for(j=0;j<5;j++)
      mvaddch(i,j,p[2*(i%2)+j%2]);
  for(i=0;i<9;i++)
    mvaddch(2*(i/3),2*(i%3),b[i]?s[b[i]]:'1'+i);
  refresh();
};

/* Play a single game with the computer taking s[m] and return the winner
 *
 *  3 -- computer
 *  4 -- human
 *  5 -- tie
 */
int G(char m){
  int u/*p*/=1,i,j;
  char b/*oard*/[9];
  memset(b,0,9); /* initalized to 0 (empty) */
  mvprintw(1,9,"Computer uses %c",s[m]);
  mvprintw(2,9,"Human uses %c",s[m%2+1]);
  /* main loop */
  do {
    mvprintw(4,9,"To play %c",s[u]);
    D(b);
    if(u==m){
      // my turn to move
      if( (i=C(b,m))<0 &&    /* move to win */
      (i=C(b,m%2+1))<0 ) /* 2%2+1 == 1,  1%2+1 == 2 so, the other side */
    i=P(b);
      b[i]=m;
    } else {
      // user's turn
      /* get user selection */
      do {
    mvprintw(6,0,"your move:\n");
    refresh();
    scanw("%d",&i);
      } while (i>10||i<1||b[i-1]!=0);
      b[i-1]=m%2+1;
    };
    u=u%2+1; /* Here u is switched to the *next* player, so if the
        game is one u denotes the *loser*  */
  } while(0==W(b));
  /* Print out the winner */
  mvprintw(8,0,"%c wins a game, press any key to continue.",s[W(b)]);
  D(b);
  getch();
  mvprintw(8,0,"%44c",*s);
  return W(b)==3?5:u==m?4:3;
}

/* first argument is required and expected to be x or o
 *
 * x always goes first
 */
int main(int c,char**v){
  char d=0, /* previous winner, starts on an impossible value */
    m=v[1][0]-'x'?2:1; /* select my symbol by index into s */
  /* /dev/random intialization */
  r=fopen("/dev/random","r");
  /* curses intialization */
  initscr(); /* start curses */
  for(;;){
    c=G(m);
    if (c==d&&c-5) // same *player* wins two in a row
      break;
    else
      mvprintw(4,25,"Previous winner %c",s[c]),d=c;
    m=m%2+1;
  }
  mvprintw(9,0,"Final winner is %c, press any key to quit.",c);
  getch();
  endwin();
}


Golf Wars Episode I: The Phantom Lightsabers Background theme

Introduction

Obi-Wan Kenobi, Qui-Gon Jinn and Darth Maul are about to fight! However, they've all forgotten to bring their respective lightsabers. Write a program or function which, given the string Jedi as input, generates an image similar to this*:

and given the string Sith, generates an image similar to this:

Images specifications

Any of the 3 lightsabers (the white blade including the round edge at the end(2 round edges for the red one) and including the handle) is 900px long (This does not include the color gradient around the blade).
The round edge at the end of the blade is a halfcircle (a discrete approximation of it, obviously) with a diameter equal to the width of the blade.
The blade (i.e. the white part of the lightsaber) is 12px wide.
The green and blue lightsabers are separated by 200 px (from the center line of the green blade to the center line of the blue blade).
The handle for all 3 lightsabers is 180px (1/5 of the total length). Therefore the blade itself including the round edge(s) is 720px long for the blue and green lightsabers and 360px long for the two blades of the red lightsaber.
The handle for the blue and green lightsabers is at the bottom of the lightsaber. The handle for the red lightsaber is horizontaly centered.
The length of the gradient from the edge of the white blade to a completely white color is 1.5 * the width of the blade (e.g. 18px for the linear parts).
The green gradient goes from RGB (0,255,0) to white (255,255,255) (or transparent if it's easier for you to implement). The red gradient goes from (255,0,0) to white, and the blue gradient goes from (0,0,255) to white.
The color of the handle is RGB (128,128,128).
There can be white empty space around the lightsaber(s).

Inputs

Either Sith or Jedi as a string. You can take this string from STDIN, as a function argument, command line parameter, or anything similar. You may assume that the input will always be exactly Sith or Jedi and nothing else.

Output

You must generate an image file containing the image corresponding to the input string. You are relatively free to choose whatever image format you want, as long as it is a True Color image.

Scoring

This is code-golf, so the shortest answer in bytes wins. May the force be with you.

* The images in this post are not displayed full size.

HTML/CSS solution, 765 740 541 bytes

The recent refactor uses the :target pseudo-class rather than a <form> and Javascript.

To enter either input, add it to the end of the URL as a target, e.g. test.html#Jedi or test.html#Sith

Here it is again with whitespace and a few comments:

The lightsabers are
 elements with one cell per part (blade/handle) that are unhidden via their id attributes.

The blades are colored with CSS box-shadows and the Jedi lightsabers undergo a transform: rotate().

Pictures or it didn't happen (click for full res):

If you add td{background:#fff}body{background:#000} to the CSS, you'll get a cool dark view.

Tested in Firefox and Chrome (on Linux).  Note that this is not at all standards-compliant, as I was trying to shrink the size as much as possible.

Thanks to @manatwork for border-spacing and :target.


Reverse ASCII character map In Map inputted ASCII characters, I asked you to .. map inputted ASCII characters. This time, you will do the opposite, by immediately mapping all ASCII characters, and then mapping spaces over them.

This program will have practical uses, such as seeing what characters you have left in a restricted-source challenge submission.

Challenge

Your job is to write a program that un-maps inputted ASCII characters. As soon as the program is run, it will display this exact map (except color, font, size, etc.):

Each time the user inputs a printable ASCII character, you will print a space over it.

Rules

The initial output must be exactly as shown in the first image above: a 6x16 grid with  ASCII characters in their respective positions, with the space (32) at the top left and the tilde (126) at one character left from the bottom right.
Your program only needs to display the printable ASCII characters, 0x20 to 0x7E.
Your program must not terminate and continue to print spaces over characters until all printable ASCII characters have been overwritten. From here, your program can either terminate or run off into Neverland.
Your reverse map must be updated in realtime (as soon as it receives user input).
If your program does not read input silently, it must put the cursor out of the way, so the text won't get in the way of the map.

Here's a useful ASCII table for reference.

Scoring

The answer with the least bytes in each language wins. Have fun!

x86-16 Machine Code, 62 bytes

Hex dump:

BC0100B101B07EBAFE0581EAE00080EA02B402CD1085E4750830E439C5750A30C0B40ACD1084C074094884D275E085D275D831C031E4CD1630E489C5EBC7

Assembly:

mov sp, 0x0001           ; Stack pointer is used as a flag; 0 - Print all characters, 1 - Delete specific character
mov cl, 0x01             ; Number of characters to print per interrupt call

printString:
  mov al, 0x7E           ; Last character to print
  mov dx, 0x05FE         ; Row: 0x05, Collumn: 0xFE
  printRow:
    sub dx, 0x00E0       ; Decrement row number + 2 extra characters
    printChar:
      sub dl, 0x02       ; Decrement collumn index + 1 space
      mov ah, 0x02       ; Prepare for interrupt call, 0x02 - Set cursor position
      int 0x10           ; BIOS interrupt

      test sp, sp        ; Are we printing all characters or removing specific character
      jnz print          ; In first case just print it and go on
      xor ah, ah         ; Otherwise reset the upper byte of ax (shorter than "and ax, 0x00FF")
      cmp bp, ax         ; Is the current character same as the input character
      jne after          ; If no, continue searching
      xor al, al         ; If yes, remove it

      print:
        mov ah, 0x0A     ; Prepare for print
        int 0x10         ; Print

      test al, al        ; If we found target character
      jz loop            ; then stop searching

      after:
        dec ax           ; Shorter than "dec, al"
        test dl, dl      ; Is it the last character in the row
        jnz printChar    ; If no, continue searching
    test dx, dx          ; Is it last char
    jnz printRow         ; If no, go to next row

loop:
  xor ax, ax             ; Remove "ah" cache
  xor sp, sp             ; Reset sp (it will never become 1 again)
  int 0x16               ; BIOS interrupt for reading keyboard input
  xor ah, ah             ; Again reset "ah", because BIOS may change it
  mov bp, ax             ; Save it in stack base pointer
  jmp printString        ; Remove the character from the list


Do these squares overlap? Given the coordinates of the upper left corners of two squares and their side lengths, determine whether the squares overlap. A square includes the top and left lines, but not the bottom and right lines. That is, a point (a,b) is inside a square with side length k that starts at (x,y) if and only if x <= a < x+k and y <= b < y+k. A square with side length 0 is degenerate and will not be considered here, thus, k will be positive.
As usual, all standard rules apply. Input and output may be in whatever form is convenient, so long as it's human readable and there is no precomputation. Be sure to specify what input format you use. Your code should take six numbers and output truthy if the squares overlap and falsy otherwise.
Test Cases
x1 y1 k1  x2 y2 k2  overlap?
 1  1  1   0  1  1  false
 0  0  3   1  1  1  true
 1  1  1   0  0  3  true
 0  0  3   2  1  2  true
 0  0  2   1  1  2  true
 1  1  2   0  0  2  true
 0  1  2   1  0  2  true
 1  0  2   0  1  2  true
 2  0  2   0  2  2  false
 1  0  3   0  1  1  false
 0  2  3   0  0  2  false

All inputs will be non-negative integers. That said, I expect that many or most solutions will also be able to handle negatives and floats.

Python, 33 bytes

lambda x,y,k,X,Y,K:k>X-x>-K<Y-y<k

Python supports chains of inequalities even when they point opposite directions.
The x-coordinate intervals [x,x+k) and [X,X+K) overlap as long as neither one is fully to the right of the other, which means that each interval's left endpoint is left of the other interval's right endpoint.
x<X+K
X<x+k

The can be combined into a joint inequality -K<X-x<k. Writing the same for y-coordinates and splicing them at -K gives the expression
k>X-x>-K<Y-y<k


Print Polyglot Pieces Typically, polyglots are constructed in such a manner that each language can ignore parts of the code that are present for other languages, by wrapping them in string literals, using comment syntax, or other similar tricks.

Your goal is to write a polyglot where the output for each language is the code from the polyglot that produces that output. Specifically, the output must be constructed from the polyglot code with only deletions, and it must be a quine in the given language.

Rules

Only proper quines are allowed (no reading the source code, no taking input, output must be to STDOUT or closest alternative if STDOUT is not an option, and the programs must consist of more than just literals that are implicitly printed).
Since different languages can use different encodings, the raw bytes are what matters here. For example, if language A uses UTF-8 and language B uses CP437, the (hex) code C3 88 46 47 would be ÈFG for language A and ├êFG for language B.
All outputs must be distinct (again, comparing raw bytes). This avoids complications with trying to restrict minor language versions - if two languages use the same part of the code to do the same thing, you can't claim them both.

If you have two languages A and B such that XY is a valid output in both, but YZ is also valid in B, you may choose XY as the output for A and YZ as the output for B, so you can claim both of them in your score (but you can't claim XY for both languages because of the above rule).

All outputs must be as short as possible. For example, if your code was print('foo')#something, for Python 3 (ignoring the fact that the output is not correct), the code you would need to output would be print('foo'), and print('foo')# would not be allowed. If there are multiple strings of equal (minimal) length that produce correct output, you may choose any one of them.
Submissions must be polyglots in at least 2 languages.
Your score will be given by (number of programming languages with distinct outputs)**3/(total byte size of polyglot). The highest score wins. In the event that two submissions achieve the same score, the submission that reached that score first will win.

GolfScript + CJam + Fission 2 + Jelly, 4 languages, 24 bytes, score 2.667
Let's start with the hex dump:
00000000:  3322 3024 700a 2721 2b4f 5222 0a3c 3024 700a 6523 7fff cccc

For GolfScript, CJam and Fission 2, we interpret this in some ASCII-compatible single-byte encoding like ISO 8859-1 (the exact encoding doesn't really matter, because the languages only define operators for ASCII characters anyway):
3"0$p
'!+OR"
<0$p
e#<DEL>ÿÌÌ

Where <DEL> is the control character 0x7f.
In Jelly, this is assumed to be in Jelly's own code page, where it looks like this instead:
3"0$p½'!+OR"½<0$p½e#¶”ṘṘ

GolfScript
The e on the last line is an unknown variable and # comments out the remainder of the line, so this prints
"0$p"
0$p

with a trailing linefeed. This is the GolfScript/CJam polyglot version of the standard quine:
".p"
.p

Try the polyglot. | Try the quine.
CJam
Here, e# comments out the last line, so almost identically, this prints
"0$p"
0$p

without a trailing linefeed.
Try the polyglot | Try the quine.
Fission
Fission only sees the second line which is the standard Fission quine, so it prints
'!+OR"

I can't provide an online link for the polyglot here, because TIO sends the file to Fission as UTF-8, but Fission reads the source byte by byte, which makes the last line too long. However, I've tested this locally with an ISO 8859-1 encoded file (in which the last line has the same length as the second), to confirm that this works.
Try the quine.
Jelly
The pilcrow is an alias for linefeeds in Jelly, so the source is equivalent to:
3"0$p½'!+OR"½<0$p½e#
”ṘṘ

All but the last line of a Jelly program are "helper links" (i.e. functions) which can be ignored unless they are called, provided they are syntactically valid. This is actually the reason the 3 comes first in the CJam and GolfScript programs, because otherwise the " can't be parsed in Jelly.
Otherwise, since the function isn't called, the program is equivalent to only its second line, which is the standard Jelly quine.
Try the polyglot. | Try the quine.


Golf a transcendental number Definitions

An algebraic number is a number that is a zero of a non-zero polynomial with integer coefficients. For example, the square root of 2 is algebraic, because it is a zero of x^2 - 2.
A transcendental number is a real number which is not algebraic.

Task

You are to choose a transcendental number.

Then, write a program/function that takes a positive integer n and output the n-th decimal digit after the decimal point of your chosen transcendental number. You must state clearly in your submission, which transcendental number is used.

You can use 0-indexing or 1-indexing.

Example

e^2=7.389056098... is a transcendental number. For this number:

n output
1 3
2 8
3 9
4 0
5 5
6 6
7 0
8 9
9 8
...

Note that the initial 7 is ignored.

As I mentioned above, you can choose other transcendental numbers.

Scoring

This is code-golf. Lowest score in bytes wins.

Python, 3 bytes

min

Try it online!

Takes a number string, outputs its smallest digit as a smallest character. For example, 254 gives 2. The decimal with these digits starts

0.0123456789011111111101222222220123333333012344444401234555550123456666012345678801234567

This is OEIS A054054.

Claim: This number c is transcendental

Proof:  Note that c is very sparse: almost all of its digits are zero. That's because large n, there's high probability n has a zero digit, giving a digit min of zero. Moreover, c has long runs of consecutive zeroes. We use an existing result that states this means c is transcendental.

Following this math.SE question, let Z(k) represent the position of the k'th nonzero digit of c, and let c_k be that nonzero digit, a whole number between 1 and 9. Then, we express the decimal expansion of c, but only taking the nonzero digits, as as the sum over k=1,2,3,... of c_k/10^Z(k).

We use the result of point 4 of this answer by George Lowther: that c is transcendental if there are infinitely many runs of zeroes that are at least a constant fraction of the number of digits so far. Formally, there must be an ε>0 so that Z(k+1)/Z(k) > 1+ε for infinitely many k. We'll use ε=1/9

For any number of digits d, take k with Z(k) = 99...99 with d nines.  Such a k exists because this digit in c is a 9, and so nonzero. Counting up from 99...99, these numbers all contain a zero digit, so it marks the start of a long run of zeroes in c. The next nonzero digit isn't until Z(k+1) = 1111...11 with d+1 ones. The ratio Z(k+1)/Z(k) slightly exceeds 1+1/9.

This satisfies the condition for every d, implying the result.


Is this a valid Takuzu board? Takuzu is a logic game in which you have to complete a grid with cells containing 0s and 1s. The grid must follow 3 rules:

No three horizontal or vertical consecutive cells can be the same.
There must be an equal number of 0s and 1s in each row and column.
No two rows can be the same, and no two columns can be the same.

Let's look at a finished grid:

0011
1100
0101
1010

As you can see, this board follows rule 1, 2 and 3. There are no three horizontal or vertical cells that are the same, all the rows and columns contain an equal number of 0s and 1s, and no two rows and no two columns are the same.

Let's look at a grid that isn't valid:

110100
010011
011010
101100
100011
001101

There's a bunch of problems with this grid. For example, row 5 has three 0s in a row, and column 2 has three 1s in a row, followed by three 0s. Therefore, this is not a valid grid.

Task:

Your task is to make a program which, given a 2D array of n * n 0s and 1s, verifies the board to see if it's a valid, finished Takuzu board.

Examples:

0011
1100
0101
1010

This board follows all the rules, and is therefore a valid Takuzu board. You must return a truthy value for this.

11
00

This is not a valid board - row 1 doesn't follow rule 2. You must return a falsey value for this.

100110
101001
010101
100110
011010
011001

This is not a valid board, it fails (only) due to rule 3 - the first and fourth rows are the same.

110100
001011
010011
101100
100110
011001

This is not a valid board, it fails (only) due to rule 3 - the first and fourth columns are the same.

011010
010101
101100
010011
100110
101001

This is a valid board.

Rules and Specs:

You can assume that all boards are square of dimensions n * n, where n is a positive even integer.
You can assume that all boards are finished.
You may take input as a 2D array containing values signifying 0 and 1, or as a string.
You must output consistent truthy and falsey values for truthy and falsey boards, and the values representing "truthy" and "falsey" cannot be the same.

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

Brachylog, 20 18 bytes
≠\≠,?¬{∋s₃=|∋ọtᵐ≠}

Try it online!
Explanation
≠                           All rows are different
 \                          Transpose
  ≠                         All columns are different
   ,?                       Append the list of rows to the list of columns
     ¬{          }          It is impossible that:
       ∋                      A row/column of the matrix…
        s₃=                   …contains a substring of 3 equal elements
           |                Or that:
            ∋ọ                The occurences of 1s and 0s in a row/column…
              tᵐ≠             …are not equal


Sabotage the coding standards There are various coding standards enforced at software companies which have the goal of increasing code reliability, portability, and, most importantly, readability in code written jointly by different developers.
Two notable examples are the MISRA C, and the C++ standard developed for the JSF project.
These are usually in the following form, after carefully specifying what the words "must", "shall", "should", "might", etc. mean:
Example:

Rule 50: Floating point variables shall not be tested for exact
equality or inequality.
Rationale: Since floating point numbers are subject to rounding and truncation errors, exact equality may not be achieved, even when
expected.

These coding standards pose restrictions, usually on code which would be legal from the compiler's point of view, but it is dangerous or unreadable, and is therefore "considered harmful".
Now let's abuse this!
You are accepted as a member of a small standardizing committee at your company, which is intended to design the new coding standards every developer at the company will be required to use. Unbeknown to the others, you are secretly in the employ of a sinister organization and have as your mission to sabotage the company.
You have to propose one or more entries to the coding standard which will later hinder the developers. However, you must be careful to not make this immediately obvious, otherwise you risk it not being accepted into the standard.
In other words, you must introduce rules to the coding standard which look legitimate and have a good chance of being accepted by the other members of committee. After the projects are started and countless man-hours are invested in the code, you should be able to abuse these rules (for example, by a technicality, or by a very literal interpretation) to flag otherwise normal and good quality code as being against the standard. So they must put a lot of effort in to redesign it, and the rules will hinder them from this point on, but as the rules are active for quite some time now, pure momentum will keep these roles alive, and as there are significant conflicts of interests between different levels of management, the other managers will probably keep the rules alive (they would be foolish to admit their mistake!), therefore hindering the company! Mwahahahahaaa!
Scoring
The highest voted answer after approximately 2 weeks from the first valid entry wins. I have an idea for a good answer, but I will only post it a few days later, as someone else might come to the same idea, and I don't want to rob them from the pleasure. Of course, my own answer will not be accepted above any other, no matter the score.
Voters are encouraged to score answers based on how well the loopholes are hidden, and how frustrating to the developers they would be.
Rules and regulations

The rule or rules must look professionally written, like in the above example
The rules should look genuine (so things like "all variables must contain at least one underscore, one upper case letter, one lower case letter and two numbers" are not accepted. They would indeed hinder developers, but would most likely not be accepted by the committee) and if their merit is not immediately obvious, you should give a good rationale.
You should be able to find a way to use/abuse your rules to sabotage the developers later on. You might abuse any ambiguity in other rules, or you might use multiple rules which are harmless on their own, but diabolical once combined!
You should post an explanation in spoiler tags at the end of your post about how you could abuse the rules
The language used must not be an esoteric language. A language widely used in real projects must be chosen, so languages with C-like syntax (instead of things like Golfscript) are preferred.

C / C++

  Rule 1: octal constants shall not be used

  Rationale: octal constants can be a cause of confusion. For example, a
  casual glance over the line
  const int coefficients[] = {132, 521, 013, 102};
  might miss the fact, that one of the numbers in the array
  is defined in octal.

If you want to be even more evil, add the following:

  Rule 2: hexadecimal constants shall only be used in the context of bit manipulation.

  Rationale: If a constant represents a numerical value, it's more
  readable if it's in decimal. A hexadecimal constant should indicate
  that it represents a bit mask, not a numerical value.

How it can be abused:

Take the following simple program which will add the first 10 elements of an array. This code would not be standard-conforming.

sum = 0;
for (i = 0; i < 10; i++)
{
    sum += array[i];
}

   Note, that 0 is, per definition, an octal constant. Per rule 1, requiring it to be written as 0x00 all through the code is frustrating. Per rule 2, even more frustrating.


Compute minimax of an array Consider an array x such as [1 5 3 4] and a number n, for example 2. Write all length-n sliding subarrays: [1 5], [5 3], [3 4]. Let the minimax of the array be defined as the minimum of the maxima of the sliding blocks. So in this case it would be the minimum of 5, 5, 4, which is 4.
Challenge
Given an array x and a positive integer n, output the minimax as defined above.
The array x will only contain positive integers. n will always be at least 1 and at most the length of x.
Computation may be done by any procedure, not necessarily as defined above.
Code golf, fewest bytes wins.
Test cases
x, n, result
[1 5 3 4], 2                    4
[1 2 3 4 5], 3                  3
[1 1 1 1 5], 4                  1
[5 42 3 23], 3                 42

Dyalog APL, 4 bytes

⌊/⌈/

This is a monadic function train that expects array and integer as right and left arguments, resp.

Try it with TryAPL.

How it works

A train of two functions is an atop, meaning that the right one is called first (with both arguments), then the left one is called on top of it (with the result as sole argument).

A monadic f/ simply reduces its argument by f. However, if called dyadically, f/ is n-wise reduce, and takes the slice size as its left argument.

⌊/⌈/    Monadic function. Right argument: A (array). Left argument: n (list)

  ⌈/    N-wise reduce A by maximum, using slices of length n.
⌊/      Reduce the maxima by minimum.


Create a Boolean parser (continued) Continuation of this challenge because the author is gone and the question is closed.

What you need to do is create a Boolean parser.

Boolean expressions, in case you haven't heard of them yet, have two inputs and one output.
There are four "gates" in boolean arithmetic, namely:

OR (represented by |) (binary operator, between arguments)
AND (represented by &) (binary operator, between arguments)
XOR (represented by ^) (binary operator, between arguments)
NOT (represented by !) (unary operator, argument on right)

These gates operate on their inputs which are either true (represented by 1) or false (represented by 0). We can list the possible inputs (A and B in this case) and the outputs (O) using a truth table as follows:
XOR
A|B|O
-----
0|0|0
0|1|1
1|0|1
1|1|0

OR
A|B|O
-----
0|0|0
0|1|1
1|0|1
1|1|1

AND
A|B|O
-----
0|0|0
0|1|0
1|0|0
1|1|1

NOT
A|O
---
0|1
1|0

An example input would be 1^((1|0&0)^!(1&!0&1)), which would evaluate to:
 1^((1|0&0)^!(1&!0&1))
=1^(( 1 &0)^!(1&!0&1))
=1^(   0   ^!(1&!0&1))
=1^(   0   ^!(1& 1&1))
=1^(   0   ^!(  1 &1))
=1^(   0   ^!    1   )
=1^(   0   ^    0    )
=1^0
=1

The output would be 1.
Details

As seen in the example, there is no order of prevalence. All are evaluated from left to right, except when inside parentheses, which should be evaluated first.
The input will only contain ()!^&|01.
You can choose any 8-byte character to replace the 8 characters above, but they must have a 1-to-1 mapping and must be stated.
Specifically, the function eval is not allowed to be used on any string derived from the input. Specifically, the function input (or the equivalent in the language) and any function that calls it cannot be used by eval. You also cannot concatenate the input into your string inside the eval.

Scoring
This is code-golf. Shortest solution in bytes wins.


Implement LaTeX accent macros Introduction

The LaTeX typesetting system uses macros for defining accents.
For example, the letter ê is produced by \hat{e}.
In this challenge, your task is to implement an ASCII version of this functionality.

Input

Your input is a non-empty string of printable ASCII characters.
It will not contain newlines.

Output

Your output is a string consisting of two lines.
The first line contains accents, and the second line the characters they belong to.
It is obtained from the input as follows (A denotes an arbitrary character):

Every \bar{A} is replaced by A with _ on top of it.
Every \dot{A} is replaced by A with . on top of it.
Every \hat{A} is replaced by A with ^ on top of it.
For a -10% bonus: every \tilde{A} is replaced by A with ~ on top of it.
All other characters have a space above them.

For example, the input

Je suis pr\hat{e}t.

results in the output

          ^
Je suis pret.

Rules and scoring

You can assume that the characters \{} only occur in the macros \bar{}, \dot{} and \hat{} (and \tilde{} if you go for the bonus).
All macro arguments are exact one character long, so \dot{foo} and \dot{} will not occur in the input.
The output can be a newline-separated string, or a list/pair of two strings.
Any amount of trailing and preceding whitespace is allowed, as long as the accents are in the correct places.
In particular, if there are no accents, the output can be a single string.

You can write a full program or a function.
The lowest byte count (after bonuses) wins, and standard loopholes are disallowed.

Test cases

Without bonus:

Input:
No accents.
Output:

No accents.
Input:
Ch\hat{a}teau
Output:
  ^
Chateau
Input:
Som\bar{e} \dot{a}cc\hat{e}nts.
Output:
   _ .  ^
Some accents.
Input:
dot hat\dot{h}a\hat{t}\hat{ }x\bar{x}dot
Output:
       . ^^ _
dot hathat xxdot
Input:
\hat{g}Hmi\hat{|}Su5Y(\dot{G}"\bar{$}id4\hat{j}gB\dot{n}#6AX'c\dot{[}\hat{)} 6\hat{[}T~_sR\hat{&}CEB
Output:
^   ^     . _   ^  .      .^  ^     ^
gHmi|Su5Y(G"$id4jgBn#6AX'c[) 6[T~_sR&CEB

With bonus:

Input:
Ma\tilde{n}ana
Output:
  ~
Manana
Input:
\dot{L}Vz\dot{[}|M.\bar{#}0\hat{u}U^y!"\tilde{I} K.\bar{"}\hat{m}dT\tilde{$}F\bar{;}59$,/5\bar{'}K\tilde{v}R \tilde{E}X`
Output:
.  .   _ ^     ~   _^  ~ _      _ ~  ~
LVz[|M.#0uU^y!"I K."mdT$F;59$,/5'KvR EX`

Pyth, 51 46 45 43 41 40 bytes
I remove the curly braces and split at \, just like Reto Koradi's CJam answer does. The codes bar, dot and hat are recognized simply by the last decimal digit of the character code of the first character, modulo 3. I just add barf (RIP) """" to the first part and remove it in the end to save the code for handling the first part specially.
jtMsMCm,+@".^_"eChd*\ -ld4>d3c-+*4Nz`H\\

Try it online. Test suite.


Triangular Lattice Points close to the Origin Background

A triangular grid is a grid formed by tiling the plane regularly with equilateral triangles of side length 1. The picture below is an example of a triangular grid.

A triangular lattice point is a vertex of a triangle forming the triangular grid.

The origin is a fixed point on the plane, which is one of the triangular lattice points.

Challenge

Given a non-negative integer n, find the number of triangular lattice points whose Euclidean distance from the origin is less than or equal to n.

Example

The following figure is an example for n = 7 (showing only 60-degree area for convenience, with point A being the origin):

Test Cases

Input | Output
---------------
    0 |       1
    1 |       7
    2 |      19
    3 |      37
    4 |      61
    5 |      91
    6 |     127
    7 |     187
    8 |     241
    9 |     301
   10 |     367
   11 |     439
   12 |     517
   13 |     613
   14 |     721
   15 |     823
   16 |     931
   17 |    1045
   18 |    1165
   19 |    1303
   20 |    1459
   40 |    5815
   60 |   13057
   80 |   23233
  100 |   36295
  200 |  145051
  500 |  906901
 1000 | 3627559

Hint: This sequence is not OEIS A003215.

Rules

Standard rules for code-golf apply. The shortest submission wins.

Please include how you solved the challenge in your submission.

Python 2, 43 bytes

f=lambda n,a=1:n*n<a/3or n*n/a*6-f(n,a+a%3)

Try it online!

This is black magic.

Offering 250 rep for a written-up proof. See Lynn's answer for a proof and explanation.


Make a 2d menger sponge A menger sponge is a fractal made out of cubes within cubes within cubes...

If you start with a cube, on each face there are 9 squares. The middle square becomes empty (or 0). The other 8 squares iterate this process. They each get split up into 9 squares and the middle square face is taken out.

The goal today is to generate a menger sponge face, not the cube.

Here are some example given an input for the number of iterations.

0:
1
(No holes or anything, solid face)

1:
1 1 1
1 0 1
1 1 1

2:
111111111
101101101
111111111
111000111
101000101
111000111
111111111
101101101
111111111

To complete the challenge, based on an input, return a set of 1 (filled in blocks) and 0 (empty blocks) with spaces between or not.

This is code golf, lowest number of bytes wins.

SOGL V0.12, 19 bytes
1¹.{³³┼┼≥:10ŗ;┼┼⁴++

Try it Here!
1¹                   push [1]
  .{                 input times do
    ³³                 duplicate top of stack 4 times, resulting in 5 total copies in the stack
      ┼┼               join the last 3 copies horizontally together
        ≥              put the joined at the bottom of the stack
         :             duplicate top of stack again
          10ŗ          replace 1 with 0 only in the top item
             ;         swap the top 2 items
              ┼┼       join the top 3 items horizontally together
                ⁴      copy the item one below top of stack
                 ++    add together vertically


Coordinate Connecting Input:
Ten unique integer coordinates, between (0,0) and (100,100).
Output:
The coordinates arranged in the order/an order such that a path drawn between the coordinates in that order is the shortest path possible.
This is code golf so the shortest code wins!

Husk, 12 11 bytes
Edit: -1 byte thanks to a tip from Leo
◄oṁ√Ẋδṁo□-P

Try it online (with only 8 points to avoid timing-out...)
How?
          P  # from all permutations of the input
◄o           # get the one that minimizes the result of
  ṁ√         # sum of all the square roots of
    Ẋ        # applying to all adjacent sets of coordinates
     δṁo     # sum of all the
        □-   # squares of the differences


What's your next move? This challenge is to write a minimax function in a language of your choice, to output the next best move in an NxN game of tic-tac-toe given the current board state. The board input can be accepted as a Matrix, 2D Collection or anything else that makes sense to you, but adheres to the rules. The output being the next best move for whoever's turn it is currently, where X is considered to have started.

Quick Background on the Minimax Algorithm

The basic idea of the minimax algorithm is to enumerate all possible outcomes as a DAG then weight them by the benefit that the sequence of moves has to the player, keyed by the first move made. All possible outcomes are then 'bucketed' by the first move, and are scored based on the sum of all outcomes (-1 for a loss, 0 for a tie and a 1 for a win). In implementations that require multiple players to play, you enumerate all possible moves by the player, and all possible responses by the opponents as well. For instance, in a game of tic-tac-toe (after the first move) there are 8 possible first moves you can make, and they all may seem equal when only analyzing the next turn. But by iterating through all possible outcomes for each possible set of moves that results in a final outcome and summing them all up, we can get a score for our next move, and have a basis for our choices.

For a better, more in-depth and contextual summary of the mini-max algorithm in terms of tic-tac-toe, read more here: http://neverstopbuilding.com/minimax

XKCD (3x3 Solution Only)

The Rules

Any language can be used, but no external minimax libraries are allowed.
Output can be a coordinate (0-n,0-n) or a number (1-n*n) indicative of the best next move.

In addition to this, you must be able to identify when the best case scenario is a loss or a tie instead of a win.
The way you denote a loss or a tie is, once again, up to you.

Input must use the traditional X and O, and you must assume X moves first; blank spaces can be represented by anything.
You may assume any inputs coming into your program have n O's and n+1 X's, in other words you may assume you're getting a well-formed board.
The current state of the board must be the only input to your program, if you are using recursion, helper methods must be made to facilitate the input requirements. See https://codegolf.stackexchange.com/a/92851/59376 for clarification.
Any value of 10 >= n >= 1 must be supported; if your program "times out" for n > 10, I find this acceptable as well, as some languages have significantly lower processing power (Especially using web-facing consoles).

Judging

This is code-golf, so the lowest byte-count of the program wins and standard loopholes are universally disallowed.
In the case of a tie, the program that supports the largest 'n' will win.

Example Inputs

2x2

[[X,O]
 [-,-]]

Output: 2 or [0,1]  (3 or [1,1] would also be arguably correct)
(Some form of indication of the location, arbitrary as long as you can easily explain the format you used)

3x3

[[X,O,X]
 [O,X,-]
 [-,-,-]]

Output: -1 (Loss)

Once again any input format you want is allowed, but X's and O's must be used, the examples provided were not meant to constrain to that format, just to inspire.

Perl, 101 98 bytes

Includes +4 for -0p

Run with the input on STDIN

tictactoe.pl
OXO
---
--X
^D

Output is the same diagram, but with each move updated with its status, 1 represents a win, 2 represents a draw and 3 represents a loss. For this case that would be

OXO
223
21X

so 3 moves draw, 1 wins and 1 loses
(I'll update the solution if this output format is unacceptable, but the basic code will remain the same)

tictactoe.pl:

#!/usr/bin/perl -0p
m%@{[map"O.{$_}"x"@-"."O|",1-/.(
)(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2

This is already painfully slow and uses lots of memory for the empty 3*3 board (why actually, the recursion doesn't go that deep. Must be some memory leak). Adding memoizing costs 6 bytes but is a lot saner:

#!/usr/bin/perl -0p
$$_||=m%@{[map"O.{$_}"x"@-"."O|",1-/.(\n)(.)/,@-]}Z%sx||s%-%$_="$`X$'";y/XO/OX/;do$0%eg?/1/?3:1+/2/:2


Decode the hidden message! Introduction

One day, you were just relaxing in your office in the CIA, when suddenly you see an alert on your computer. Your programs have just intercepted hundreds of coded messages! A quick examination reveals the rule for encoding, but you need a program in order to decode fast.

Challenge

You will be given a list of strings, separated by commas. Each string will contain either:

Part of the coded message

It is part of the coded message if it is not in the form a=b. Note that it is part of the message if it is ab=c. Add this string to the coded message.

Part of the encoding scheme

This will be in the form of a=b. That means that all a's in the message must be replaced by b's. Note that it could be a==, meaning that all a`s must be replaced with ='s.

Your program must then output the message, decoded using the scheme found.

Other info:
Your input will only contain commas for separating the strings. It could contain other characters, like !1#, etc. It will not contain uppercase letters. Bits of decoding info do not decode each other. Only the message is affected by the decoding information. Only one replacement will be given for each character, e.g. no "io,"i=u","i=g"

Examples

Input:"ta","y=s","y","a=e","b=t","b"," ","j","j=1"

Output:test 1

Input:"z=p","zota","g=e","yugkb","y=t","u=o","k=s","li","fg","b=="

Output:potatoes=life

Input:"p","=","==n","ot","p=a","hiz","i=e","z=r"

Output:another

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

Python 3, 98

lambda l:''.join(x*('='!=x[1:-1])for x in l).translate({'='!=x[1:-1]or ord(x[0]):x[2:]for x in l})

This lambda function receives a list of strings (input) and returns a string (the decoded message).

Examples:

>>> f(['ta', 'y=s', 'y', 'a=e', 'b=t', 'b', ' ', 'j', 'j=1'])
'test 1'
>>> f(['z=p', 'zota', 'g=e', 'yugkb', 'y=t', 'u=o', 'k=s', 'li', 'fg', 'b=='])
'potatoes=life'
>>> f(['p', '=', '==n', 'ot', 'p=a', 'hiz', 'i=e', 'z=r'])
'another'


Keyboard layouts challenge The keyboard layout people commonly use is the QWERTY layout as shown below.

But there are also other keyboard layouts:

DVORAK

COLEMAK

WORKMAN

Your task

Your code will take two inputs: the name of the keyboard layout and a string to transcribe.
Your goal is to convert your QWERTY input as if you were typing with the keyboard layout given as first parameter.

Rules

The input format is free, you can use strings, arrays, etc. Moreover, you can use any three distinct values to represent the layouts to reduce your byte count, but they each have to be representable in 10 bytes or less.

You need only to handle the keys with a white background. Specifically, you must transpose the printable ASCII characters from the QWERTY alphabet to one of the other alphabets:

 QWERTY: !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
 DVORAK: !_#$%&-()*}w[vz0123456789SsW]VZ@AXJE>UIDCHTNMBRL"POYGK<QF:/\=^{`axje.uidchtnmbrl'poygk,qf;?|+~
COLEMAK: !"#$%&'()*+,-./0123456789Oo<=>?@ABCSFTDHUNEIMKY:QPRGLVWXJZ[\]^_`abcsftdhuneimky;qprglvwxjz{|}~
WORKMAN: !"#$%&'()*+,-./0123456789Ii<=>?@AVMHRTGYUNEOLKP:QWSBFCDXJZ[\]^_`avmhrtgyuneolkp;qwsbfcdxjz{|}~

(Note: this was transcribed by hand by @ETHproductions, so if you see any errors, please point them out!)

Example

DVORAK zZxX as input will give as output ;:qQ

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

JavaScript (ES7), 282 273 251 250 bytes
Takes a keyboard layout ID k and an array of characters a in currying syntax (k)(a). Returns an array of translated characters.
The layout IDs are:

DVORAK: \$-32\$
COLEMAK: \$64\$
WORKMAN: \$160\$

k=>a=>a.map(c=>1/(t=`1_3-2}w[vz8SsW]VZ1XJE>UIDCHTN0BRL"POYGK<QF:/0=0{1xje.uidchtn0brl'poygk,qf;?0+995Oo6SFTD0UNEI0KY:0PRGL2J8sftd0unei0ky;0prgl2j998Ii5VMHRT0YUNEOLKP:0W0BFCD0J6vmhrt0yuneolkp;0w0bfcd0j5`.replace(/\d/g,n=>15**n)[c.charCodeAt()+k])?c:t)

Try it online!
How it works
Compression
All three target layouts are stored in a single compressed string, where each character is either:

a translation character from QWERTY
a digit representing the number of consecutive characters that do not need to be translated

More specifically, a digit \$n\$ is interpreted as the length of the number \$15^n\$ in base \$10\$:
n | 15**n       | length
--+-------------+-------------
0 | 1           | 1
1 | 15          | 2
2 | 225         | 3
3 | 3375        | 4
4 | 50625       | 5 (not used)
5 | 759375      | 6
6 | 11390625    | 8
7 | 170859375   | 9 (not used)
8 | 2562890625  | 10
9 | 38443359375 | 11

For instance, #$%&-()* in DVORAK is stored as 3-2 because #$%& and ()* have identical mappings in QWERTY and only - is an actual translation.
In particular, 0123456789 is mapped the same way on all layouts and never has to be translated. Therefore, there's no possible ambiguity between a digit used for compression and a digit used for translation.
Decompression
To decompress the layout string, we replace each digit \$n\$ with \$15^n\$. For instance, 3-2 is decompressed as 3375-225.
Translation
For each character c in a, we extract the translation character t, using k as an offset in the uncompressed layout string, and test whether it's a digit with 1/t. If so, we output the original character c instead.


Build a Digital Plotter Problem adapted from the book Fortran 77 by Donald M. Monro

Introduction

Digital plotting machines are widely used to produce various forms of drawings, graphs and other pictorial results. Most such machines can move their pens only in certain directions, usually as single steps in the X and Y direction or both. A typical machine would move in one of the eight directions shown in Fig. 1:

Fig. 1

Challenge

Write a program without trigonometric functions which takes a number from 0 to 7 (inclusive) as input and outputs the corresponding coordinates of the endpoints in Fig. 1.

Output should as an array or list with two elements (i.e. (1, 0) or [0,-1])

Table of I/O

0 (1, 0)
1 (1, 1)
2 (0, 1)
3 (-1, 1)
4 (-1, 0)
5 (-1, -1)
6 (0, -1)
7 (1, -1)

Winning

Shortest code in bytes wins

Python 2, 29 bytes

lambda n:1j**(n/2)*(1+n%2*1j)

Returns the coordinates as a complex number.


Two roads diverged in a yellow wood (part 1) This is the first in a series, the second is Two roads diverged in a yellow wood (part 2)

This challenge is inspired by Robert Frost's famous poem, "The Road Not Taken":

  Two roads diverged in a yellow wood,
  And sorry I could not travel both
  And be one traveler, long I stood
  And looked down one as far as I could
  To where it bent in the undergrowth;

  Then took the other, as just as fair,
  And having perhaps the better claim,
  Because it was grassy and wanted wear;
  Though as for that the passing there
  Had worn them really about the same,

  And both that morning equally lay
  In leaves no step had trodden black.
  Oh, I kept the first for another day!
  Yet knowing how way leads on to way,
  I doubted if I should ever come back.

  I shall be telling this with a sigh
  Somewhere ages and ages hence:
  Two roads diverged in a wood, and I —
  I took the one less traveled by,
  And that has made all the difference.

Notice the second to last line, I took the one less traveled by,.

Your actual challenge

You will take input in the form like:

#     ##
 #   ##
  # ##
   #
   #
   #

and you have to find the thinner road.

The road starts at the bottom with a #. The other 2 roads, which always terminate on the top row, are the roads you have to examine. The road that is the thickest is most traveled by, and therefore it is not what you want. The other one is the least traveled by, and it is the one you want.

Output

Your program/function must output one of 2 distinct values (eg. 0 or 1, true or false), one for each possible position of the road not taken. For example, you could output 0 if the road not taken is on the left of the road taken, and 1 otherwise, or you could output the string "left" or "right", true, false, etc.

Test cases:

 ##    #
  ##  #
   ###
    #
    #
    #

Might output "right".

 ##  #
  ## #
   ###
    ##
     #
     #
     #

Might output "right".

 ##  #
  ## #
   ###
    ##
   #
  #
 #

Might output "right".

 ##   #
  ## #
   ###
    #
   #
  #
  #

Might output "right".

 #    ##
  #  ##
   ###
    #
   #
  #
  #

Might output "left"

 #    ##
  #  ##
   ###
    #
     #
     #
     #

Might output "left"

Notes

This is code-golf, so the shortest answer in bytes wins
Standard loopholes forbidden
You must specify your outputs for "left" and "right" and they must be distinct
Input will be one big string, and may have any amount of lines
You don't need to worry about valid input.
The road is always a Y shape, so you only have to look at the top.
Have any questions? Comment below:

Lowest byte count wins!

JavaScript(ES6), 19 12 bytes

Edit:

A more golfed version is

a=>a.trim[1]

Returns # for right and a space for left.

Original:

a=>a.trim()[1]=='#'

Explanation

Ungolfed:

function(input) {
  return input.trim().charAt(1) === '#';
};

The first thing this function does is remove white space the beginning and end of the input. This means that the first character is always #. Then from there I check the second character(JavaScript starts at 0) and see if it is a # character.
This returns a boolean. If the path is right it will be true, if it is left it will return false.

How I golfed it

In ES6 there is an anonymous function shorthand called an arrow function. This means that I can take my wrapper function and turn it into:

input => ...;

Due to the rules of arrow functions it will return the rest of the code. From there I converted charAt(1) to [1] as it is a shorter way, though not recommended. Then I took === and turned it into ==. While they are different in this case it doesn't matter. Finally, I renamed input to a and removed all whitespace.

Output right and left

While the puzzle doesn't actually need the program to output right and left, here's an example of other outputs:

a=>a.trim()[1]=='#'?'right':'left'

The only added part is ?'right':'left'. This creates a ternary operator, a condensed if statement, this means that the(ungolfed) code is equal to*:

function(input) {
  let output = input.trim().charAt(1) === '#';
  if(output) {
    return 'right';
  } else {
    return 'left'
  }
};

Example

// Function assignment not counted in byte count
let f =
a=>a.trim()[1]=='#'
<textarea placeholder="Put path in here" id="path" rows="10" style="width:100%"></textarea>
<button onclick="document.getElementById('result').textContent = f(document.getElementById('path').value)">Submit</button>


Multiplicative persistence Multiplicative Persistence

Multiply all the digits in a number
Repeat until you have a single digit left

As explained by Numberphile:

Numberphile "What's special about 277777788888899?"
Numberphile "Multiplicative Persistence (extra footage)"

Example

277777788888899 → 2x7x7x7x7x7x7x8x8x8x8x8x8x9x9 = 4996238671872
4996238671872 → 4x9x9x6x2x3x8x6x7x1x8x7x2 = 438939648
438939648 → 4x3x8x9x3x9x6x4x8 = 4478976
4478976 → 4x4x7x8x9x7x6 = 338688
338688 → 3x3x8x6x8x8 = 27648
27648 → 2x7x6x4x8 = 2688
2688 → 2x6x8x8 = 768
768 → 7x6x8 = 336
336 → 3x3x6 = 54
54 → 5x4 = 20
20 → 2x0 = 0

This is the current record, by the way: the smallest number with the largest number of steps.

Golf

A program that takes any whole number as input and then outputs the result of each step, starting with the input itself, until we hit a single digit. For 277777788888899 the output should be

277777788888899
4996238671872
438939648
4478976
338688
27648
2688
768
336
54
20
0

(Counting the number of steps is left as an exercise to the user).

More Examples

From A003001:

25
10
0

From A003001 as well:

68889
27648
2688
768
336
54
20
0

From the Numberphile video:

327
42
8

So there has been a question about Additive Persistence, but this is Multiplicative Persistence. Also, that question asks for the number of steps as output, while I'm interested in seeing the intermediate results.

TI-BASIC (TI-84), 30 32 31 bytes

-1 byte thanks to @SolomonUcko!

While Ans>9:Disp Ans:prod(int(10fPart(Ans10^(seq(-X-1,X,0,log(Ans:End:Ans

Input is in Ans.
Output is displayed as the challenge requests.  The trailing Ans is needed to print the last step.

I will admit, I did not think of this formula myself, rather I found it here and modified it to better fit the challenge.

EDIT:  Upon rereading the challenge, I realized that the program must terminate if the product is one digit.  Hence, 2 bytes were to be added to account for this.

Example:

24456756
        24456756
prgmCDGF8
        24456756
          201600
               0
11112
           11112
prgmCDGF8
           11112
               2

Explanation:

While Ans>9               ;loop until the product is one digit
Disp Ans                  ;display the current product
prod(                     ;get the product of...
 int(                     ; the integer part of...
  10fPart(                ; ten times the fractional part of...
  Ans                     ; each element in the following list times the
                          ;  current product
  10^(                    ; multiplied by the list generated by using each
                          ;  element of the following list as an exponent
                          ;  for 10^n
   seq(-X-1),X,0,log(Ans  ; generate a list of exponents from -1 to -L where
                          ;  L = the length of the current product
End
Ans                       ;leave the final product in "Ans" and implicitly
                          ; print it

Visual Model:
Ans starts off as 125673.
This model only covers the logic behind multiplying the digits; everything else is easier to understand.

seq(-X-1,X,0,log(Ans  =>  seq(-X-1,X,0,5.0992
   {-1 -2 -3 -4 -5 -6}
10^(...
   {.1 .01 .001 1E-4 1E-5 1E-6}
Ans...
   {12567.3 1256.73 125.673 12.5673 1.25673 .125673}
fPart(...
   {.3 .73 .673 .5673 .25673 .125673}
10...
   {3 7.3 6.73 5.673 2.5673 1.25673}
int(...
   {3 7 6 5 2 1}
   (the digits of the number, reversed)
prod(...
   1260
   (process is repeated again)

seq(-X-1,X,0,log(Ans  =>  seq(-X-1,X,0,3.1004
   {-1 -2 -3 -4}
10^(...
   {.1 .01 .001 1E-4}
Ans...
   {126 12.6 1.26 .126}
fPart(...
   {0 .6 .26 .126}
10...
   {0 6 2.6 1.26}
int(...
   {0 6 2 1}
prod(...
   0
   (product is less than 10.  loop ends)

Notes:

TI-BASIC is a tokenized language.  Character count does not equal byte count.

10^( is this one-byte token.

This program will not provide the correct sequence of products with integers greater than 14 digits long due to the limitations of decimal precision on the TI calculators.


Shortest Program to Solve a Quartic Equation Write the shortest program to solve a Quartic equation.

A quartic equation is a polynomial equation of the form:

ax⁴ +bx³+cx²+dx+e=0

A solution for x is a number such that the above evaluates to 0.

Rules

The program must take in the 5 floating point coefficients of the equation ax^4+bx^3+cx^2+dx+e as "a b c d e" separated by spaces.
It must then output a single real solution. If there exist no real solutions then it outputs an "n".
No bonus for extra solutions.
No use of CAS (Computer algebra systems) This includes symbolic manipulation properties of Mathematica and related software.
No connecting to external libraries, web calculators etc...
You may use formulas or your own manipulation
Native math libraries that do not solve equations may be used, eg. .NET: System.Math
You may deduct 50 from your char count if recursion is a main technique used.
As long as there is no difference with the answer obtained algebraically, numerical approximation is welcome however adds 25 chars to your solution. This really relies on the accuracy of the floating-point numbers. (Which should be 64 bit).

The winner will be picked in 1 week. (26/02/2014)

C++ A fast and robust solution, 704 chars + numeric - recursion = 679
#include "stdafx.h"
#include "math.h"
double a,b,c,e,j,k,l,p,q,t,z;void s(double x, int i){if(i==99)printf("%f\n",x);else s(x-((x+b)*x*x*x+c*x*x+l*x+e)/(4*x*x*x+j*x*x + k*x + l),i+1);}
void _tmain(){double r[8];scanf_s("%lf%lf%lf%lf%lf",&a,&b,&c,&l,&e);b/=a;c/=a;l/=a;e/= a;j=3*b;k=2*c;p=(12*k-j*j)/48;q=(2*j*j*j-36*j*k+432*l)/1728;z=q*q/4+p*p*p/27;int u=0,v=0,g;
for(g=1;g<4;g++){r[g]=z>0|p==0?cbrt(-q/2+sqrt(z))+cbrt(-q/2-sqrt(z))-j/12:sqrt(-p/.75)*cos(acos(-q/sqrt(-p*p*p*4/27))/3-g*acos(-.5))-j/12;r[g+4]=(r[g]+b)*pow(r[g],3)+c*r[g]*r[g]+l*r[g]+e;if(r[g+4]>r[g+3]|g==1)u=g;if(r[g + 4]<r[g+3]|g==1)v=g;}
if(r[v+4]>0)printf("n\n");if(r[v+4]==0)printf("%f\n",r[v]);if(r[v+4]<0)s(2*r[v]-r[u]+(r[v]-r[u]==0),0);}

This is by no means the shortest answer, but so far no other answer has confirmed that it will work with curves with the full 3 stationary points (maxima/minima.) These correspond to curves with large values of b and c of opposite sign to a. None of the test data in the other solutions has local maxima/minima apart from the global one. The nearest is Eelvex's 1 2 0 0 1 which has a kink on one side where dy/dx falls to zero.
This program handles all the test data shown in other solutions, plus the following interesting examples, amongst others:
1 0 1 0 0 --> multiple root 0
1 0 -1 0 0 --> multiple root at 0, but the program prefers the simple root at -1
1 0 -1 0 0.25 -->  multiple roots at +/- 0.7071 = sqrt(0.5)

It cannot handle the case a=0, but that is not a quartic so it is out of scope.  The only problem I have found but not eliminated is b=c=d=0, but that is an easy problem to fix. I will do it when I golf the code (if I get round to that.) I expect it to come in around 700-800 chars.
How it works
The program divides the whole formula by a (which does not affect the roots, but ensures that we know that y= +infinity at x = +/- infinity )
It then calculates the formula for dy/dx (a cubic) and solves this analytically for dy/dx=0. The code to do this is quite short (the explanation in the comments is much longer than the code itself.)
It calculates the values of y at the up to 3 stationary points where dy/dx=0 and looks for the lowest (global minimum.) If this y is positive here , the whole curve is above the x axis and there are no roots.
If y is zero, then it is a root and this is reported directly. Such a root would be problematic for newton raphson.
If y is less than zero, the program makes a guess for the root on the opposite side of the global minimum from the other stationary points (to avoid getting trapped in the local maximum if there is one.)
Then it searches using newton-raphson (recursive, as you insisted.) This method is fast and simple, and once the right region of the curve has been identified, does not run the risk of dividing by zero.
I did run into other problems with it though. It quickly got very close to a solution (good enough for a human) but kept searching. With the rapid initial convergence, I assumed that the problem was that it couldn't get to f(x)==0 because f'(x) was large and f(x)/f'(x) was being rounded to zero in the calculation. So I put in an extra test condition for f(x)/f'(x) but it still did the same. Then I limited it to just 10 iterations, which is more than enough for all the tests I have done.
The current version goes up to 99 iterations. The ungolfed version has medium verbosity output (with uncommentable code for high verbosity) as seen in the screenshot and has its iterations terminated when f(x)==0. The golfed version has low verbosity (in accordance with specified requirements) and always runs to 99 iterations. The golfed version has other minor differences, such as no while loop and simplified (but less clear) expressions.
There are certainly other methods which might work better, but I think that might go into another answer (which I don't think I have time for.)
Ungolfed version
#include "stdafx.h"
#include "math.h"

double a,b,c,d,e,j,k,l,p,q,t,z;
//explanation of variables
//dy/dx= i* x3 + j*x2 + k*x + l. No i variable needed as it is normalised to 4.
//depressed form of dy/dx: t3+pt+q. A subsitution is used to eliminate the squared term, see below.
//z=q2/4 + p3/27. z is proportional to the "discriminant." The sign tells the number of roots of dy/dx
// +ve z means 1 real root, -ve z means 3 real roots, 0 means one simple root plus a double root.

// recursive newton-raphson to depth i
void s(double x, int i){
    double m=(x + b)*x*x*x + c*x*x + d*x + e;
    if (m == 0 | i == 99)  printf("z= %f x= %f y= %f iteration %d\n", z,x,m,i);
    else s(x-m/(4*x*x*x + j*x*x + k*x + l), i+1);

}

void _tmain(){
    while (true){

        double r[8];
        //r[1,2,3] and r[5,6,7] store x and y values of the maxima and minima.
        //r[0] and r[4] are dummies to handle [subscript-1] references.

        scanf_s("%lf %lf %lf %lf %lf", &a, &b, &c, &d, &e);
        //uncomment for verbose output: printf("data for minima and maxima \n");
        //uncomment for verbose output: printf("   z       x       dy/x      y     hi/low \n");
        //hi/low indicate which y values are highest and lowest: 1st, 2nd, 3rd.

        //Divide by a to give a "monic polynomial" with a=1.
        //This does not affect the roots but saves a lot of typing of powers of a.
        // differentiate to i*x3 + j*x2 + k*x + l. As a=1, we know i=4.
        b /= a; c /= a; d /= a; e /= a;
        j = 3*b; k = 2*c; l = d;

        // to prepare to solve this cubic, convert to depressed cubic t3+pt+q, eliminating x2. x=t-j/(3*i)
        // p=(3*i*k - j2)/(3*i2) q=(2*j3 - 9*i*j*k + 27*i2*l)/27*i3. But we know i=4.
        p = (12 * k - j*j) / 48;
        q = (2 * j*j*j - 36 * j*k + 432 * l) / 1728;
        z = q*q / 4 + p*p*p / 27;

        //u and v indicate which of the stationary points are highest and lowest.
        //solve dy/dx, store the roots in r[1,2,3] and the y values in r[5,6,7].
        int u=0,v=0,g;
        for (g = 1; g < 4; g++){

            //if z>0 or p==0 use cardano's method to store the one real root of dy/x three times in r[1,2,3]
            //if z<=0 use viete's trigonometric method to find the multiple real roots.
            //use of different methods for each case avoids the need to handle complex numbers.

            r[g] =z > 0 | p==0? cbrt(-q / 2 + sqrt(z)) + cbrt(-q / 2 - sqrt(z)) - j / 12 :
                sqrt(-p / .75)*cos(acos(-q / sqrt(-p * p * p * 4 / 27)) / 3 - g*acos(-.5)) - j / 12;

            r[g+4] = (r[g]+b)*pow(r[g],3) + c*r[g]*r[g] + d*r[g] + e;

            if (r[g + 4]>r[g+3]|g==1)u=g;
            if (r[g + 4]<r[g+3]|g==1)v=g;

            // uncomment for verbose output
            //printf("%f %f %f %f %d %d \n  \n", z, r[g], 4 * pow(r[g], 3) + j*pow(r[g], 2) + k*r[g] + l, r[g+4], u, v);
        }

        //because we divided by a, the new a=1 and y tends to infinity at large |x|.
        //so if the lowest stationary point has y>0, the whole curve is above the x axis and there is no solution.

        //if the lowest stationary point has y=0 it is tangent to the x axis and would cause problems for newton-raphson

        //if the lowest stationary point has y<0, use newton raphson, 99 iterations. ensure 1st guess is on the side
        //opposite the highest stationary point, just in case that point also has y<0, to avoid getting trapped.
        //special case: if r[v]-r[u] == 0 (implies only one stationary point) then add 1!

        if (r[v+4] >0) printf("n\n");
        if (r[v+4]==0) printf("z= %f x= %f multiple root", z,r[v]);
        if (r[v+4] <0) s(r[v]+(r[v]-r[u])+(r[v]-r[u]==0),0);
    }
}

Output
All data tested by other answers is here, as well as many additional examples. The sign of the value z is positive when there is only one stationary point where dy/dx=0, negative when there are three (2 minima and a maximum if a is positive), and zero when there are two (a minimum if a is positive, plus an inflexion.) This is the only answer so far that presents test cases for three stationary points.
The y values are shown for easy checking of the program. y is zero at the root, and as can be seen, an acceptable zero is always found.
The golfed version is low verbosity, displaying only the root per question spec.


To find islands of 1 and 0 in matrix Given a two dimensional matrix of 0 and 1s. Find the number of island for 1s and 0s where neighbours are only in the horizontal and vertical.

Given input:

1 1 1 0
1 1 1 0

output = 1 1
Number of 1s island = 1

xxx-
xxx-

Number of 0s island = 1

---x
---x

------------------------------

Given input:

0 0 0 0
1 1 1 1
0 0 0 0
1 1 1 1

output = 2 2
Number of 1s island = 2

----
xxxx  <-- an island of 1s
----
xxxx  <-- another island of 1s

Number of 0s island = 2

xxxx  <-- an island
----
xxxx  <-- another island
----

------------------------------

Given input:

1 0 0
0 0 0
0 0 1
output = 2 1
Number for 1's island = 2:

x--  <-- an island of 1s
---
--x  <-- an island of 1s

Number of 0's island = 1:

-xx  \
xxx   > 1 big island of 0s
xx-  /

------------------------------

Given input:

1 1 0
1 0 0
output = 1 1
Number for 1's island =1 and number of 0's island = 1

------------------------------

Given input:

1 1
1 1
output = 1 0
Number for 1's island =1 and number of 0's island = 0

APL (Dyalog Unicode), 29 28 bytesSBCS

-1 thanks to @Adám

{≢∪∨.∧⍨⍣≡2>+/↑|∘.-⍨⍸⍵}¨⊂,~∘⊂

Try it online!

⊂,~∘⊂ the matrix and its negation

{ }¨ for each of them do

⍸⍵ list of pairs of coords of 1s

+/↑|∘.-⍨ matrix of manhattan distances

2> neighbour matrix

∨.∧⍨⍣≡ transitive closure

≢∪ number of unique rows


Reversed language name You should code a piece of code that looks like it outputs the language name but actually outputs the name reversed.

E.g. a Python program should look like it outputs Python but should actually output nohtyP.

The winner is the answer with the most upvotes in a week!

PHP, 3 bytes

PHP

Try it online!

It looks like it outputs the language name, but it's actually the letters in reversed order.


Disco Zoo animal hunt This question is inspired by the game Disco Zoo

Background

Disco Zoo is a game where you can go into the wild and rescue animals. Once you have found an animal you can put it in your zoo for your visitors to see.

To find animals you first select a field to search, and you get to see a 5x5 grid where the animals are hiding. At the top of the screen you can see which animals are hiding in the field.

Each animal has a different pattern, which never changes for the same animal. E.g. (X is pattern, o is padding)

Animal=Sheep    Animal=Unicorn
Pattern:        Pattern:

 XXXX            Xoo
                 oXX

Some animals use 2 blocks, some 3 and some 4. The pattern will be translated, but not rotated.

Task

The user gives you a pattern or the name of an animal (your choice) and you have to generate an optimum strategy to search for that animal/pattern. A strategy is a set of blocks from the 5x5 grid; an optimum strategy is one which guarantees to find at least 1 block from the pattern, and where there is no strategy with fewer blocks which can make the same guarantee.

For sheep and unicorns the optimum strategy would be searching the middle column:

ooXoo
ooXoo
ooXoo
ooXoo
ooXoo

Another example:

Animal: Hippo
Pattern:       Optimum strategy:
               ooooo
 XoX           oXXoo
 ooo           oXXoo
 XoX           ooooo
               ooooo

The Disco Zoo wiki's Patterns page lists all the animals and their patterns. You may hard-code the patterns. The wiki also lists optimum strategies for all the animals. Feel free to look at them but you're not allowed to hard-code them.

Input: Either a pattern made of X and O or the name of the animal.
Output: a 5x5 grid made of X or O where X marks an optimum strategy.

Ruby 221

->a{l=a.join(?o*(5-w=a[0].size))
s=?o*25
q=(0..25-l.size).select{|i|i/5==(i+w-1)/5}.map{|i|(?o*i+l+s)}
(h=q[0].size.times.map{|i|q.count{|p|p[i]<?o}}
s[c=h.index(h.max)]=?X
q.reject!{|p|p[c]<?o})while q!=[]
s.scan /.{5}/}

Input and Output

This is a Ruby function that takes one parameter representing the animal and returns the solution, both being represented as string arrays.

For example, the Hippo is represented as:

['XoX',
 'ooo',
 'XoX']

and its solution is:

['ooooo',
 'oXXoo',
 'oXXoo',
 'ooooo',
 'ooooo']

Test

Here's a working version. Feel free to experiment with it and enter more animals as parameters.

Algorithm

I found this problem very interesting and I experimented to solve it in different ways, including brute force, which is less feasible, but possible for the given inputs (it would be terribly inefficient for the input ['X'] though).

The algorithm I found to be the most efficient is the following:

Compute all possible positions for the animal on the 5x5 board
Given the existing positions, compute a map of frequencies for each of the 25 cells
Take one of the cells that contain the max number of "hits" and make it part of the solution. Exclude all positions that are "hit" in that particular cell.
Repeat steps 2-3 until there are no positions left.

I don't have a proof of optimality for this algorithm, but it tested most animals present on the wiki page and it returned optimal solutions for all.

Note that for some animals the solutions are not identical to the ones presented in the wiki, but involve the same number of blocks.

For example, the Wooly Rhino page presents this solution:

ooooo
ooooo
oXXXo
ooooo
ooooo

and the algorithm returns this one:

ooooo
oooXo
ooXXo
ooooo
ooooo

which is also correct and optimal (3 blocks).

Here's the (slightly more) readable version of the program:

SIZE = 5

# return all possible placements for the animal on a 5x5 board
def get_placements(animal)
  # represent the 5x5 board and the animal as linear arrays
  linear_animal = animal.join(?o*(SIZE - animal[0].size))
  d = SIZE*SIZE
  (0..d-linear_animal.size)
    .select{|i| i/5 == (i+animal[0].size-1)/5} # to avoid wrap-around positions
    .map { |i|
      (?o*i + linear_animal + ?o*d)[0...d]
    }
end

# given a set of possible placements,
# return a map of frequencies for every cell
def heatmap(placements)
  placements[0].size.times.map do |i|
    placements.count {|p|p[i] < ?o}
  end
end

# given an animal, return the solution as an array of 5 5-character strings
def solve(animal)
  placements = get_placements animal
  solution = []

  while placements.any?
    h = heatmap(placements)

    solution << chosen = h.index(h.max)

    placements = placements.reject {|pl| pl[chosen] < ?o }
  end

  (0...25).map{|i| solution.include?(i) ? ?X : ?o }.join.scan /.{5}/
end


Interpreted arithmetic A little known fact is that if you turn on enough language extensions (ghc) Haskell becomes a dynamically typed interpreted language!  For example the following program implements addition.

{-# Language MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances #-}

data Zero
data Succ a

class Add a b c | a b -> c
instance Add Zero a a
instance (Add a b c) => Add (Succ a) b (Succ c)

This doesn't really look like Haskell any more.  For one instead of operating over objects, we operate over types.  Each number is it's own type.  Instead of functions we have type classes. The functional dependencies allows us to use them as functions between types.

So how do we invoke our code? We use another class

class Test a | -> a
 where test :: a
instance (Add (Succ (Succ (Succ (Succ Zero)))) (Succ (Succ (Succ Zero))) a)
  => Test a

This sets the type of test to the type 4 + 3.  If we open this up in ghci we will find that test is indeed of type 7:

Ok, one module loaded.
*Main> :t test
test :: Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero))))))

Task

I want you to implement a class that multiplies two Peano numerals (non-negative integers).  The Peano numerals will be constructed using the same data types in the example above:

data Zero
data Succ a

And your class will be evaluated in the same way as above as well.  You may name your class whatever you wish.

You may use any ghc language extensions you want at no cost to bytes.

Test Cases

These test cases assume your class is named M, you can name it something else if you would like.

class Test1 a| ->a where test1::a
instance (M (Succ (Succ (Succ (Succ Zero)))) (Succ (Succ (Succ Zero))) a)=>Test1 a

class Test2 a| ->a where test2::a
instance (M Zero (Succ (Succ Zero)) a)=>Test2 a

class Test3 a| ->a where test3::a
instance (M (Succ (Succ (Succ (Succ Zero)))) (Succ Zero) a)=>Test3 a

class Test4 a| ->a where test4::a
instance (M (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))) (Succ (Succ (Succ Zero))) a)=>Test4 a

Results

*Main> :t test1
test1
  :: Succ
       (Succ
          (Succ
             (Succ
                (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))
*Main> :t test2
test2 :: Zero
*Main> :t test3
test3 :: Succ (Succ (Succ (Succ Zero)))
*Main> :t test4
test4
  :: Succ
       (Succ
          (Succ
             (Succ
                (Succ
                   (Succ
                      (Succ
                         (Succ
                            (Succ
                               (Succ
                                  (Succ
                                     (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))))))))

Draws inspiration from Typing the technical interview

130 121 bytes

-9 bytes thanks to Ørjan Johansen

type family a+b where s a+b=a+s b;z+b=b
type family a*b where s a*b=a*b+b;z*b=z
class(a#b)c|a b->c
instance a*b~c=>(a#b)c

Try it online!

This defines closed type families for addition (+) and multiplication (*). Then a type class (#) is defined that uses the (*) type family along with an equality constraint to convert from the world of type familes to the world of typeclass prolog.


N Slab Slanted Slash Cake Write a program or function that takes in a positive integer N.

When N is 1, output

/\
\/

When N is 2, output

/\/\
\/ /
/ /
\/

When N is 3, output

/\/\/\
\/ / /
/ / /
\/ /
/ /
\/

When N is 4, output

/\/\/\/\
\/ / / /
/ / / /
\/ / /
/ / /
\/ /
/ /
\/

For larger N the pattern continues, a new layer is added every time N is incremented.

"Output" means print the slash pattern or return it as a string.
A single trailing newline in the output is allowed.
Trailing spaces in the output are allowed but leading spaces are not.

The shortest code in bytes wins.

CJam, 32 30 29 28 bytes

ri_"/\ /"2/f*)@,\f>+_z..e>N*

Test it here.

I was trying to help Reto golf his CJam answer but ended up with a solution that had nothing to do with his, so I figured I might as well post it myself.

Explanation

This makes use of the symmetry of the output. In particular, the fact that the output is the same as its transpose.

First, we generate the first N+1 lines, but without the left edge:

ri       e# Read input and convert to integer N.
_        e# Duplicate.
"/\ /"2/ e# Push an array with two strings: ["/\" " /"]
f*       e# Repeat each of the two strings N times. That gives the first two rows.
)        e# Detach the second row.
@,       e# Pull up the other copy of N and turn into range [0 1 ... N-1].
\f>      e# For each element i in that range, discard the first i characters of
         e# the second row.
+        e# Add all those lines back to the first row.

Now we've got an array of strings representing the following grid:

/\/\/\/\
 / / / /
/ / / /
 / / /
/ / /

The transpose of that looks like this:

/ / /
\/ /
/ / /
\/ /
/ / /
\/ /
/ /
\/

Together, these have all the non-space characters that we need. We can now make use of Dennis's rad tip to combine two ASCII grids into one, by taking the maximum of each corresponding pair of characters. In all positions where the two grids differ, one will have a space (or nothing at all) and the other will have the character we're looking for. When one list in a vectorised operation is longer than the other, the additional elements of the longer list will simply be kept, which is just what we're looking for. In the other cases, the non-space character will always be the maximum of the two characters:

_z   e# Duplicate the grid and transpose it.
..e> e# For each pair of characters in corresponding positions, pick the maximum.
N*   e# Join the lines by linefeed characters.


Write a Palindrome-Polyglot-Quine Write a "palipolyquine": a program that is a quine, a polyglot,  and a palindrome.

Rules:

The number of polyglot languages is more preferable than code size.
The shortest answer (in bytes) wins, in case of a tie.
Polyglot and Quine rules see here: Write a Polyquine.

My example (I have a repository Freaky-Sources with tests):

C#/Java (1747 bytes):

/**///\u000A\u002F\u002A
using System;//\u002A\u002F
class Program{public static void//\u000A\u002F\u002A
Main//\u002A\u002Fmain
(String[]z){String s="`**?`@#_^using System;?_#^class Program{public static void?@#_^Main?_#main^(String[]z){String s=!$!,t=s;int i;int[]a=new int[]{33,94,38,64,35,95,96,63,36};String[]b=new String[]{!&!!,!&n!,!&&!,!&@!,!&#!,!&_!,!`!,!?!,s};for(i=0;i<9;i++)t=t.?@#_^Replace?_#replace^(!!+(char)a[i],b[i]);t+='*';for(i=872;i>=0;i--)t=t+t?@#_^[i];Console.Write?_#.charAt(i);System.out.printf^(t);}}/",t=s;int i;int[]a=new int[]{33,94,38,64,35,95,96,63,36};String[]b=new String[]{"\"","\n","\\","\\u000A","\\u002F","\\u002A","/","//",s};for(i=0;i<9;i++)t=t.//\u000A\u002F\u002A
Replace//\u002A\u002Freplace
(""+(char)a[i],b[i]);t+='*';for(i=872;i>=0;i--)t=t+t//\u000A\u002F\u002A
[i];Console.Write//\u002A\u002F.charAt(i);System.out.printf
(t);}}/*/}};)t(
ftnirp.tuo.metsyS;)i(tArahc.F200u\A200u\//etirW.elosnoC;]i[
A200u\F200u\A000u\//t+t=t)--i;0=>i;278=i(rof;'*'=+t;)]i[b,]i[a)rahc(+""(
ecalperF200u\A200u\//ecalpeR
A200u\F200u\A000u\//.t=t)++i;9<i;0=i(rof;}s,"//","/","A200u\\","F200u\\","A000u\\","\\","n\",""\"{][gnirtS wen=b][gnirtS;}63,36,69,59,53,46,83,49,33{][tni wen=a][tni;i tni;s=t,"/}};)t(^ftnirp.tuo.metsyS;)i(tArahc.#_?etirW.elosnoC;]i[^_#@?t+t=t)--i;0=>i;278=i(rof;'*'=+t;)]i[b,]i[a)rahc(+!!(^ecalper#_?ecalpeR^_#@?.t=t)++i;9<i;0=i(rof;}s,!?!,!`!,!_&!,!#&!,!@&!,!&&!,!n&!,!!&!{][gnirtS wen=b][gnirtS;}63,36,69,59,53,46,83,49,33{][tni wen=a][tni;i tni;s=t,!$!=s gnirtS{)z][gnirtS(^niam#_?niaM^_#@?diov citats cilbup{margorP ssalc^#_?;metsyS gnisu^_#@`?**`"=s gnirtS{)z][gnirtS(
niamF200u\A200u\//niaM
A200u\F200u\A000u\//diov citats cilbup{margorP ssalc
F200u\A200u\//;metsyS gnisu
A200u\F200u\A000u\///**/

Compilation available on ideone.com: C#, Java.

CJam/GolfScript, 2 languages, 50 bytes

{`"0$~e#"+0$-1%"":n}0$~e##e~$0}n:""%1-$0+"#e~$0"`{

Try it CJam!
Try it in GolfScript!

Huh, this went unanswered surprisingly long.

Explanation

It's probably easiest to explain this by showing how I turned the basic quine in each language into a palindromic polyglot quine.

So the basic quines in both languages are:

{".~"}.~

{"_~"}_~

In GolfScript and CJam, respectively. These are quite similar thanks to the fact that CJam was originally inspired by GolfScript (but has since deviated quite a lot). The first difference we notice is that one uses . for duplicating the top of the stack and the other uses _. A common trick to avoid this problem is to use 0$, since both languages have the "copy-nth-item-on-stack" operator $. So we get {"0$~"}0$~, although that still needs a trailing linefeed in GolfScript. But let's worry about that at the end.

First, we need to make it a palindrome. The obvious solution to this is to append a comment and put the source code there in reverse. This is quite simple, because CJam uses e# for comments, and in GolfScript e does nothing at all, and # is a comment. So if we append e#... that works for both languages. Here is what we've got:

{"0$~"}0$~e##e~$0}"~$0"{

Of course, that doesn't actually print the part from e# onward. We can reconstruct this quite easily from the source code itself. Both languages can turn the initial block into a string with ` and append the "0$~" part with +, so that we get the entire unmirrored source code in a single string. To append a mirrored copy, all we need to do is duplicate the string with 0$ again and then reverse it with -1%, which also works in both languages. So now we've got this:

{`"0$~e#"+0$-1%}0$~e##e~$0}%1-$0+"#e~$0"`{

This is a valid palindromic quine in CJam, and it also works in GolfScript but still prints that pesky trailing linefeed.

The usual way to prevent this is to assign an empty string to n, because what GolfScript really does is print the contents of n at the end. So what we need is "":n. So what about CJam? Thankfully, this does nothing at all. "" is also an empty string (or empty list, they're the same thing in CJam), and : maps the operator n (print with linefeed) over the list. But since the list is empty, mapping an operator over it does nothing at all. Hence, we can get rid of the linefeed, without messing with CJam, and end up with the final solution:

{`"0$~e#"+0$-1%"":n}0$~e##e~$0}n:""%1-$0+"#e~$0"`{


What is the Subspace Dimension? Challenge
Given the Cartesian coordinates of two or more distinct points in Euclidean n-space (\$\mathbb{R}^n\$), output the minimum dimension of a flat (affine) subspace that contains those points, that is 1 for a line, 2 for a plane, and so on.
For example, in 3-space (the 3-dimensional world we live in), there are a few possibilities:

The points are not coplanar, e.g. (0,0,0),(0,0,1),(0,1,0),(1,0,0). The full 3 dimensions would be needed to describe the points, so the output would be 3
The points are coplanar but not all collinear, e.g. (0,0,0),(1,0,0),(0,1,0),(1,1,0). The points lie on a 2-dimensional surface (a plane), so the output would be 2.
The points are collinear, and there is more than one, e.g. (0,0,0),(1,0,0). They all lie on a line (1-dimensional), so the output is 1.
One or zero points are given. You do not have to handle these degenerate cases.

As @user202729 pointed out in sandbox, this is equivalent to the rank of the matrix whose column vectors are the given points if one of the points is the zero vector.
I encourage upvoting answers that don't have built-ins do most of the work, but they are valid answers.
Details

The coordinates of each point will always be integers, so errors due to excessive floating-point roundoff are not acceptable
Again, you do not have to handle fewer than 2 points
The dimension n will be at least 2
The set of points can be taken in any format that encodes equivalent information to a list of n-tuples. Your program/function may also take n as input if you desire.
Note that the subspace may not necessarily pass through the origin*
This is code-golf, so shortest bytes wins

*Mathematically, if we require the subspace to pass through the origin, then it would be more specifically called a "linear subspace", not just flat.
Testcases
n points -> output
2 (1,0),(0,0) -> 1
2 (0,1),(0,0) -> 1
2 (6,6),(0,-2),(15,18),(12,14) -> 1
2 (0,0),(250,500),(100001,200002) -> 1
2 (0,0),(250,500),(100001,200003) -> 2
2 (3,0),(1,1),(1,0) -> 2
3 (0,0,0),(0,0,1),(0,1,0),(1,0,0) -> 3
3 (0,0,0),(1,0,0),(0,1,0),(1,1,0) -> 2
3 (0,0,0),(1,0,0) -> 1
4 (1,2,3,4),(2,3,4,5),(4,5,6,7),(4,4,4,4),(3,3,3,3),(2,2,2,2) -> 2
5 (5,5,5,5,5),(5,5,6,5,5),(5,6,5,5,5),(6,5,5,5,5),(5,4,3,2,1) -> 4

Related Challenges:

Is the matrix rank one?
Linear Independence.

MATL, 12 bytes
t1Y)-X$&Yvoz

Input is a matrix, where each row defines a point.
Try it online! Or verify all test cases.
Explanation
The code uses the singular value decomposition of a matrix, which is done symbolically to prevent floating-point issues. The rank of a matrix equals the number of non-zero singular values.
t      % Implicit input: matrix of integer values. Duplicate
1Y)    % Get the first row
-      % Subtract, with broadcast. This subtracts this row from each row
X$     % Convert to symbolic matrix. Note that integers, are represented
       % exactly as floating-point values up to ±2^53.
&Yv    % Single-output singular value decomposition. Gives a vector with
       % the singular values
o      % Convert to floating point. Note that 0 is represented exactly
       % as a floating-point value
z      % Number of nonzeros. Implicit output


LeetCode 552: Student Attendance Record II I'm posting my code for a LeetCode problem copied here. If you have time and would like to golf for a short solution, please do so.
Requirement

It has to only pass the LeetCode's Online Judge, if the language would be available.

If the language is not available, simply we should possibly keep the class Solution as well as the function name.

Languages and Version Notes
Available languages are:

C++ clang 9 Uses the C++17 standard.
Java    13.0.1
Python  2.7.12
Python3 3.8
C   gcc 8.2
C#  8.0
JavaScript 14.3.0
Ruby    2.4.5
Bash    4.3.30
Swift   5.0.1
Go  1.13
Scala   2.13
Kotlin  1.3.10
Rust    1.40.0
PHP 7.2

Thank you!
Problem

Given a positive integer n, return the number of all possible
attendance records with length n, which will be regarded as
rewardable. The answer may be very large, return it after mod 10 ^ 9 + 7.
A student attendance record is a string that only contains the
following three characters:

'A' : Absent.
'L' : Late.
'P' : Present.

A record is regarded as rewardable if it doesn't contain more than one
'A' (absent) or more than two continuous 'L' (late).
Example 1:

Input: n = 2
Output: 8

Explanation:
There are 8 records with length 2 will be regarded as rewardable:

"PP" , "AP", "PA", "LP", "PL", "AL", "LA", "LL"

Only "AA" won't be regarded as rewardable owing to more than one absent times.

Note: The value of n won't exceed 100,000.

Accepted Code
class Solution:
    def checkRecord(self, n):
        MOD = 1000000007
        a = b = d = 1
        c = e = f = 0
        for _ in range(n - 1):
            a, b, c, d, e, f = (a + b + c) % MOD, a, b, (a + b + c + d + e + f) % MOD, d, e

        return (a + b + c + d + e + f) % MOD

Accepted Golf Attempt in Python 3 - 185 bytes - I
class Solution:
    def checkRecord(self,n):
        M=1000000007;a=b=d=1;c=e=f=0
        for _ in range(n-1):a,b,c,d,e,f=(a+b+c)%M,a,b,(a+b+c+d+e+f)%M,d,e
        return(a+b+c+d+e+f)%M

Accepted Golf Attempt in Python 3 - 185 bytes - II
class Solution:
    def checkRecord(self,n):
        M=int(1e9+7);a=b=d=1;c=e=f=0
        for _ in range(n-1):a,b,c,d,e,f=(a+b+c)%M,a,b,(a+b+c+d+e+f)%M,d,e
        return(a+b+c+d+e+f)%M

Reference
In LeetCode's answer template, there is a class usually named Solution with one or more public functions which we are not allowed to rename.

Problem

Discuss

Languages

I guess the solution was originally designed by Stefan Pochmann

Tips:

The first argument self can be renamed to something shorter.
Use while n:n-=1 to loop n times
(Python 2 specific) You can use a single tab for the second level of indentation, instead of 2 spaces.
For this problem, it's sufficiently fast to just mod b every loop, instead of having to mod both a and d.
The part a,b,c,d,e,f=... can be broken into a,b,c=...;d,e,f=..., which allows reusing the updated value a=a+b+c
c,e,f can be initialized to 10**9+7 instead of 0 (found by @xnor).

Python 2, 136 134 131 127 125 bytes

class Solution:
 def checkRecord(_,n):
	a=b=d=1;c=e=f=M=10**9+7
	while n:n-=1;a,b,c=a+b+c,a%M,b;d,e,f=a+d+e+f,d,e
	return d%M

Try it online!


Iterative Alliterative Additive Array Antics I honestly don't know what the point of this sort of calculation would be, but it should make fun golfing. Shortest code wins.

Input (in no particular order)

An array of integers, a (All elements will be integers less than the length of the array.)
An index therein, i
An iteration count, n

Processing

Store a number x with initial value of 0.
Do the following steps n times:

Add the current value of i to x.
Decrement a[i].
If a[i] is negative, increment it by the length of a.
Set i to a[i].

After the iterations, add the final value of i to x.

Output

After doing the above process, your program should output the final value of x.

Example (n=5)

a                     i   x
2,0,0,5,5,6,7,5,8,5   0   0
1,0,0,5,5,6,7,5,8,5   1   0
1,9,0,5,5,6,7,5,8,5   9   1
1,9,0,5,5,6,7,5,8,4   4   10
1,9,0,5,4,6,7,5,8,4   4   14
1,9,0,5,3,6,7,5,8,4   3   18

The program outputs 21.

Test Case Generator

function newTestCase() {
    var a = Array(Math.floor(Math.random() * 50) + 25).fill(0);
    a = a.map(Math.random).map(e => e * a.length).map(Math.floor);
    var i = Math.floor(Math.random() * a.length);
    for (var x = 0, n = 0, aa = [...a], ii = i; Math.random() * a.length >= .5;) {
        n++;
        x += ii;
        aa[ii]--;
        if (aa[ii] < 0) aa[ii] += a.length;
        ii = aa[ii];
    }
    return {a, i, n, shouldOutput: x + ii};
}
<button type="button" onclick="console.log(newTestCase());">Generate</button>

Python 2, 71 bytes

def f(a,i,n):x=0;exec"x+=i;a[i]+=len(a)*(a[i]<1)-1;i=a[i];"*n;print x+i

Try it online!