Tic-Tac-Toe and Chess, with fewest [distinct] characters In this form of the game Tic-Tac-Chec, the goal is to move chess pieces to get four-in-a-row. Your goal here is to figure out if a position has a winning move.
Rules
The rules are similar, but not identical, to those of Tic-Tac-Chec.
The board is 4 by 4 squares. Each player has a rook, bishop, knight, and queen. On your turn, you have two options. You can move one of your pieces already on the board, following  standard chess rules. Or you can place a piece not already on the board, on any unoccupied place.
If you move an existing piece onto an opponent's piece, their piece is taken off the board and returned to them. However, you may not place a new piece on top of an opponent's piece.
As soon as one player has all of their pieces in a row (or column, or diagonal), they win.
Challenge
Write a full program that accepts a board from STDIN, and outputs whether the white player can win on the next turn.
Input
Four strings of 4 characters each. Each character is either a space or a chess piece. Only rooks, bishops, knights, and queens are used, and at most one of each (per color) may appear. Neither player already has a four-in-a-row.
You can choose whether to accept as input the Unicode symbols for the chess pieces, or letters. If you choose letters, RBKQ represents white pieces, and rbkq represents black pieces.
Output
If the white player can win on the next turn, output true or 1. Otherwise, output false or 0.
Program
Choose a number X. Your program may contain at most X distinct characters, and no character may appear more than X times.
Winning
Lowest X wins. In case of a tie, fewest characters wins.
Examples
These examples assume the input uses letters to represent the pieces.
rkb

RB Q
true - the white player can place the knight to complete the bottom row.
-----------------------------------
rk

RBbQ
false - the black bishop prevents the white knight from completing the row.
-----------------------------------
rk
 K

RBbQ
true - the white knight can capture the black bishop and complete the row.
-----------------------------------
rkRB

 Qb
K
true - the white rook can move down one to complete the diagonal.

APL (Dyalog Unicode), 369 characters, score 28

{Q←(QQ←⍴⍵)[1]
R←∨/¨⍵=⊂'RBQK'
B←({⍵(⍵[↑(⍳Q),¨¨⊂1--Q-⍳Q])}↑(⍳Q)=⊂⍳Q),{⍵,{⍵[{⍵[(1--1)1]}¨⍳QQ]}¨⍵}(⊂QQ)⍴¨(⍳Q)=⊂⍳Q
K←(Q-1)={∨/1↑⍴{(,⍵)/,⍳⍴⍵}⍵}¨B×⊂R
1-∨/K:1-1
K←↑∨/K/B
BB←{(,⍵)/,⍳⍴⍵}K×1-R
R←↑∨/BB-B←{(,⍵)/,⍳⍴⍵}R×1-K
1-⍴B:⍵[BB]=1↑''
BB←(1-∨/¨'RBQK'=⊂⍵[(,K)/,⍳⍴K])/'RBQK'
'K'=BB:×/∨/¨(⍳1--1)=⊂R∨-R
1-∨/(1-(⍳1--1)='RB'⍳BB)×(=/,{∨/1-×⍵})R∨-R:1-1
×/(1↑'')=⍵[B--(×⊂R)×⍳-1-∨/R]}↑⍞⍞⍞⍞

Try it online!
Character statistics:
 -  1  B  )  (  ⍵  /  Q  ⍳  R  '  ∨  LF   K  ,  =  ←  }  { ⊂ × ¨ ⍴ ↑ ] [ ⍞ :
27 26 22 20 20 19 19 18 15 15 14 12  12  12 12 11 10 10 10 9 9 9 8 8 7 7 4 4
chars 28

Decisions made during optimizing the score:

Boolean guard : is needed for early returns from a dfn {}. Either LF (\n) or a statement separator character ⋄ cannot be removed as a side effect.
I didn't try to avoid four letters RBQK as avoiding it requires at least ⎕A and the code would get messy.
Removed composition ∘, reflex/flip ⍨, and self ⊢ in favor of dfns and explicitly writing down arguments with parentheses.
Removed ≢ (tally) in favor of ⍴ (shape/reshape), as tally = first element of shape, and reshape is unavoidable.
Removed ⍉ (transpose) and ⌽ (reverse/rotate) in favor of explicit indexing [] combined with index generator ⍳. Although there are one-char functions to do the indexing (⌷, ⊃), none is suitable for transpose operation.
Removed ⊃ (first/pick) in favor of ↑ (mix/take), as take is unavoidable and indexing+mix can simulate both uses of ⊃.
Removed ∧ (logical and) in favor of × (times), and | (abs/mod) by using the workaround x∨-x for |x (abs) and explicit membership ∊ (which was removed later) for x|y (mod). ⊤ was also removed that way.
Removed ∘.f in favor of f⊂ or f¨⊂. Similar trick was used to simulate ∊ (membership) and ~ (set minus): x∊y → ∨/¨x=⊂y, x~y → (1-∨/¨x=⊂y)/x
Removed ⍸ (extract indices of ones) with the workaround (,x)/,⍳⍴x.
Removed zero with 1-1, four by extracting from ⍴⍵, and + with --.
Removing blanks in plain code is easy, but this code has ' '. I avoided it with 1↑'', which "overtakes" length 1 from an empty string and gives a single blank. (It is a slightly different thing from the literal ' ', but they are compatible in most cases.)

Ungolfed with comments
{
  ⍝ 4×4 boolean matrix where 1 means a white piece
  whites←⍵∊'RBKQ'
  ⍝ one matrix per a winning position; roughly looks like
  ⍝ 1 0 0 0 ... 1 1 1 1 ... 1 0 0 0
  ⍝ 1 0 0 0     0 0 0 0     0 1 0 0
  ⍝ 1 0 0 0     0 0 0 0     0 0 1 0
  ⍝ 1 0 0 0     0 0 0 0     0 0 0 1
  masks←((⊂,⊂∘⌽)∘.=⍨⍳4),(⊢,⍉¨)(⍳4)⌽¨⊂4 4⍴4↑1
  ⍝ 1 if the white is about to win in that specific winning position
  filter←3=masks{≢⍸⍺∧⍵}¨⊂whites
  ⍝ No three-in-a-row: return false
  ~∨/filter:0

  ⍝ fetch the mask closest to white's winning
  mask←(⍸filter)⊃masks
  ⍝ coordinates of misplaced piece (from) and empty position (to)
  from←⍸whites>mask
  to←⍸whites<mask
  ⍝ No from: the remaining place must be empty
  ~≢from:' '=⍵[to]

  ⍝ get the type of the piece to move
  type←'RBKQ'~⍵[⍸mask]
  ⍝ Knight: true if 1×2 steps away, ignoring any obstacles
  'K'=type:∧/1 2∊|⊃from-to
  ⍝ two booleans indicating if it can move in diagonals (BQ) or
  ⍝ cardinal directions (RQ)
  diag cross←0 2⊤⊃'RB'⍳type
  ⍝ two booleans indicating if the direction to move is actually
  ⍝ diagonal or cardinal
  isdiag←=/|⊃from-to
  iscross←0∊|⊃from-to
  ⍝ Not aligned with the piece to move: return false
  diag cross⍱.∧isdiag iscross:0
  ⍝ If aligned, true if all cells between from and to are blanks
  ∧/' '=¯1↓⍵[from+(×v)×⍳⌈/⊃|v←to-from]
}↑{⍞}¨⍳4  ⍝ Take 4 lines of input, format as matrix and pass to function


Counting ways of scoring k points in n games with half-points for draws If a game can result in a win, worth one point; a draw, worth half a point; or a loss, worth no points; how many ways are there of scoring k points in n games?

Applicable scenarios include NFL and chess.

Input is via stdin, and consists of n and k on separate lines.
n will be a non-negative integer. (n ≤ 16)
k will be either a non-negative integer or a non-negative integer plus a half. (k ≤ n)
Output is to stdout. It may, but does not have to, include a trailing newline.

Test cases

In each case, the first two lines are user-supplied input and the third line is the program output.

10
4.5
8350

16
8
5196627

16
13.5
13328

12
12
1

Perl 59 bytes

@0=map"$v"+($v=$u)+($u=$_),@0,0,0for(@0=1)x<>;print@0[<>*2]

Iteratively generates each row of the triangle of trinomial coefficients up to n, and then prints the correct term, 2k.

Ruby 73 bytes

r=*1
gets.to_i.times{r<<0<<u=v=0;r.map!{|t|v+(v=u)+u=t}}
p r[gets.to_f*2]

Largely equivalent to the Perl solution above.

Python 84 bytes

r=[1]
exec"r=map(sum,zip(r+[0],[0]+r,[0,0]+r))+[1];"*input()
print r[int(input()*2)]

Same method as both solutions above.

PHP 91 bytes

<?for($n=+fgets(STDIN);(${$j--}+=$$j+${$j-1})?:$n--*$j=$i+=2;${0}=1);echo${fgets(STDIN)*2};

Despite being the longest, this was actually the most fun to work on.


Simple Printing Arrows For golfing practice, I have been doing the assignments in my girlfriend's Intro to Python class. I found that for this assignment, there were multiple strategies that came very close in character count, and I'm sure people here can find even better ways. Although I am most interested in ways to do this in Python, I would like to know the most golfed this program can get, therefore this is code golf and shortest answer wins.
The Rules:
The assignment is outlined below. The user should be asked to input twice, although the prompts don't have to say anything, and can be in a different order.
Standard loopholes apply.

Assignment 3: Arrows
Write a program that prompts the user for a number of columns, and them prints the pattern as seen below. You can assume that the user will supply positive numbers. Your program should handle both left and right arrows. Here are a few sample runnings:
How many columns? 3
Direction? (l)eft or (r)ight: r
*
 *
  *
 *
*
How many columns? 5
Direction? (l)eft or (r)ight: l
    *
   *
  *
 *
*
 *
  *
   *
    *

Pyth, 23 bytes
May or may not be valid, based on the answer to this comment. Regardless, I found this neat, and, if it is invalid, the other Pyth answers are also invalid. ;) Well, it's valid, because I apparently missed the blatantly obvious. :/
EDIT: I WON!!!! YESSS!!!! First time ever! :D
j+_J_Wqz\r.e+*dkb*\*QtJ

Live demo.


Surrounded Countries Countries own a series of territories on a 1D world. Each country is uniquely identified by a number. Ownership of the territories can be represented by a list as follows:
1 1 2 2 1 3 3 2 4

We define a country's edgemost territories as the two territories closest to either edge. If the above list was zero indexed, country 1's edgemost territories occur at position 0 and 4.
A country surrounds another if the sublist between its two edgemost territories contains all the territories of another country. In the above example, the sublist between country 2's edgemost territories is:
2 2 1 3 3 2

And we see that all the territories of country 3 are between the edgemost territories of country 2, so country 2 surrounds country 3.
A country with only one element will never surround another.
Challenge
Take a list of integers as input (in any format) and output a truthy value if any country is surrounded by another, and a falsy value otherwise.
You can assume that the input list is nonempty, only contains positive integers, and does not 'skip' any numbers: for example, 1 2 1 5 would be invalid input.
Test Cases
+----------------------+--------+
|        Input         | Output |
+----------------------+--------+
| 1                    | False  |
| 2 1 3 2              | True   |
| 2 1 2 1 2            | True   |
| 1 2 3 1 2 3          | False  |
| 1 3 1 2 2 3 2 3      | True   |
| 1 2 2 1 3 2 3 3 4    | False  |
| 1 2 3 4 5 6 7 8 9 10 | False  |
+----------------------+--------+

Pyth, 7 bytes
n{Q_{_Q

Run the code on test cases.
n      Check whether the following are not equal:
 {Q     The unique elements in order of first appearance
 _{_Q   The unique elements in order of last appearance
         (done by reversing, taking unique elts, then reversing again)

The only way to avoid surrounding is for the countries' leftmost territories to be sorted in the same order as their rightmost territories. If two countries are swapped in this order, one has a territory both further left and further right than the other, and so surrounds it.
To obtain the unique countries in order of leftmost territory, we simply deduplicate, which preserves this order. The same is done for the rightmost territory by reversing, deduplicating, then reversing again. If these give different results, then a country is surrounded.


How can I shorten this python code analyzing a 3d grid? My Python 3 function golf(...) should take a list of lists of lists of strings representing a solid cube and return whether there are any places in which two equal strings are directly next to each other on the x, y or z axis (not diagonally).
If there are no adjacent duplicates, True shall be returned, else False.

The input list and all of its sublists have the same length as they represent a cube, and their length is greater than 1 but lower than or equal to 5. The only possible values for the Strings inside the nested lists are "X" and "Z".
The maximum code length should be less than 200 bytes.

This is an example test case:

golf([[["X", "Z"],
       ["Z", "X"]],
      [["Z", "X"],
       ["X", "Z"]]]) == True
golf([[["X", "Z"],
       ["Z", "X"]],
      [["X", "Z"],
       ["Z", "X"]]]) == False

My current solution has 234 bytes:

def golf(c):
 r=range(len(c));R=[(a,b)for a in r for b in r];j="".join
 return all("XX"not in l and"ZZ"not in l for l in[j(c[x][y][z]for x in r)for y,z in R]+[j(c[x][y][z]for y in r)for x,z in R]+[j(c[x][y][z]for z in r)for x,y in R])

How can I golf this code any further to save another 35 bytes?

Python 3, 108 107 bytes
Since the cube only contains the strings "X" and "Z", there are only two valid cube patterns. The one that starts with XZXZX... and the one that starts with ZXZXZ....
My solutions generates these 2 cubes and checks if the inputted cube is one of them.
def golf(l):L=len(l);r=range(L);return l in[[[list("XZ"*L)[(i+j+k)%2:][:L]for j in r]for k in r]for i in r]
i iterates over the possible cubes. Since the dimension is at least 2, we can reuse r instead of writing for i in(0,1).


Number letter counts If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.

Output how many letters would be used if all the numbers from 1 to 1000 (one thousand) inclusive were written out in words.

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.

You must actually calculate it - just printing the predetermined result is not allowed.

Output with any acceptable method.

Mathematica, 38 bytes

StringLength@StringJoin@IntegerName[Range[1000]]

@Doorknob has a leaner implementation:

Tr@StringLength@IntegerName@Range@1000

(* 20961 *)

Explanation

IntegerName[Range[10]]

(* {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"} *)

StringJoin@IntegerName[Range[10]]

(* "onetwothreefourfivesixseveneightnineten" *)

StringLength@StringJoin@IntegerName[Range[10]]

(* 39 *)


Convert RGB color to websafe Web safe colors are in intervals of 51, they include 0, 3, 6, 9, c, and, f as digits in hex (such as #993333), or 0, 51, 102, 153, 204, 255 in decimal. Your task today is convert a given color to a web safe one. You may read more about web safe colors on Wikipedia.

Input

You will take in 3 integers between 0, 255 inclusive representing red, green, and blue values.

Output

Output the converted 3 integers, as an array or similar structure.

Rules

answers must be rounded to the nearest value, not floor or ceiling. (25 -> 0 and 26 -> 51)
As this is code golf, lowest bytes wins.

Test Cases

Input            Output
(0, 25, 76)      (0, 0, 51)
(1, 26, 77)      (0, 51, 102)
(127, 178, 229)  (102, 153, 204)
(128, 179, 230)  (153, 204, 255)
(0, 254, 255)    (0, 255, 255)
(9, 143, 53)     (0, 153, 51)

I'm sure these answers will be pretty short; this is an easier question meant for those more novice at code golf, however feel free to answer regardless of your skill/experience.

Japt, 4 bytes

mr51

Try it online!

Input and output is a 3-item array.

Just maps each item rounded to the nearest multiple of 51.


Virus vs Antidotes code golf There is a rectangular 2D array containing viruses denoted by 'v', antidote1 denoted by 'a', and antidote2 denoted by 'b' (there are no values other than 'v', 'a' and 'b').
Antidote1 can kill neighboring viruses in horizontal and vertical directions only, but antidote2 can kill neighboring(if any) viruses in horizontal, vertical and diagonal directions.
Once the antidotes are activated, how many viruses will remain at the end?
Examples:
Input:
vv
vv

Output: 4
Input:
av
vv

Output: 1
Input:
vvv
vbv
vvv

Output: 0
Input:
bvb
bav
vab
vvv
vvb
vvv
vvv
bva
vav

Output: 3

Python 3, 131 bytes

j=''.join
g=lambda s:eval('j(s)'+4*'.replace("%s%s","%s%s")'%(*'vbbbbvbbavacvaca',))
f=lambda x:j(map(g,zip(*map(g,x)))).count('v')

Try it online!
-2 bytes thanks to Kevin Cruijssen
Explanation
Replaces all 'v' to 'b' if found next to 'b'. Next, replaces all 'v' to 'c' if found next to 'a'. A second iteration with the transposed version of the array clears all vertical and diagonal viruses. Finally, it will return the remaining number of 'v's.

Without eval:
Python 3, 134 bytes

j=''.join
g=lambda s,m='vbbbbvbbavacvaca':m and g(j(s).replace(m[:2],m[2:4]),m[4:])or s
f=lambda x:j(map(g,zip(*map(g,x)))).count('v')

Try it online!


Return 1 - Popularity Contest The Task

Create a function/subroutine which returns 1. You can make it as elaborate as you like, as long as it returns 1.

The Rules

The entry with the most upvote wins - just like any popularity contest. Good luck!

Golf Script

1

It took a long time to optimise this code to its most pure, and dare I say it - beautiful form. Such elegance of the language does not come without years of dedicated practice. The program that, without a Zero-Instruction-Set-Computer can literally never be compressed any further. My entire code golf career has been leading to this moment.

I am free. I am alive.

I see the code that underlies the universe.


Quine Anagrams! (Cops' Thread) This is the cops' thread. For the robbers' thread, click here.
Cops' Task

First, write a quine in a language of your choosing.
Next, scramble the quine. Make sure to do this well as the robbers will be trying to unscramble it and find the original source code! Note that the scrambled code does not need to work.
Post an answer on this thread. Include the language, the byte count, and the scrambled code.

Your program may not print to STDERR.
Here is an example of a cop submission:

Python, 29 bytes
nt _%=_r;_riinp;pr_='t _%%%_'

Robbers' Task
For the robbers' thread, click here.
Safe Submissions
If your submission has not yet been cracked after a week of posting, you may add the solution and specify that it is safe. If you do not, your submission may still be cracked.
Scoring
This is code-golf, so the user with the safe submission with the fewest bytes will be the winner of this section.
Leaderboard
Here is a stack snippet to generate a learderboard for this challenge. For it to display properly, please format your submission like this:
# Language Name, N bytes

... other stuff ...

If your submission gets cracked, please format like this:
# Language Name, N bytes, [Cracked!](link)

... other stuff ...

If your submission is safe, format like this:
# Language Name, N bytes, Safe!

... other stuff ...

C#, 288 bytes
Stag is a great shoW.        "="=""="="Agent"plastic"Was"tryin"to"Release"an"Astroid"."$Money$"st@le"tigers"and"Agent"plastic"got"mad"."$Money$"sic","man","t0tally"rad"."Sistrs"Rms"titAnic";"Civic"Ace"in"{sC@m}{hic}{vicis}..{cats}sAc}((@))((@)){{{>>{{{{{{}}}}}}}}}\\\\\\\;;;(@)((@)()),,;;

My strategy is for all the short ones to get cracked and nobody bothers with this considering how long it is... Also I suppose I should note that this is a full program, not just a function.


Draw centered polygonal numbers A centered polygonal number is able to be put into an arrangement of multiple concentric polygons, each with a side length of one more than the inner one. For example (image from linked page),

the above image has 31 dots, so 31 is a centered pentagonal number.
Write a program which receives a number as input (any typical input method is fine), and displays a picture similar to the above.
In particular:

There must be a centered dot.
Each concentric polygon contains an increasing number of dots, all connected through a line.
The angles must be correct for the appropriate regular polygon.
The distance between connected dots must be the same throughout the picture.
Each polygon must be centered inside the surrounding polygon.

The input will be between 2 and 1000, and is guaranteed to be a centered polygonal number of some kind.
If there are multiple possible solutions, display them all. For example, an input of 181 should display both a centered square (of 9 "rings") and a centered pentagon (of 8 "rings").
No hardcoding answers.

HTML + JS, 913 857 675 bytes

(Line breaks are added for readability)

<body><script>
function O(X,x,y,R){X.beginPath();X.arc(x,y,R,0,M.PI*2,true);X.closePath();X.fill()}
Z=300,P=3,H=Z/2,$=+prompt(),M=Math;for(S=3;S<$;S++){for(C=1;C<30;C++){if(S*C*C+S*C+2==$*2){
V=document.createElement("canvas");V.width=V.height=Z;document.querySelector("body").appendChild(V);X=V.getContext("2d");
O(X,H,H,P);for(R=1;R<=C;R++){
D=[],A=R*(H-P)/C,G=0;X.beginPath();X.moveTo(H+A,H);D.push([H+A,H]);for(s=1;s<S;s++){x=M.cos(G+=M.PI*2/S)*A,y=M.sin(G)*A;X.lineTo(H+x,H+y);D.push([H+x,H+y])}X.closePath();X.stroke();
for(j=0;j<D.length;j++){x=D[j][0],y=D[j][1],q=D[(j+1)%S][0]-x,w=D[(j+1)%S][1]-y;O(X,x,y,P);for(k=0;k<R-1;k++)O(X,x+=q/R,y+=w/R,P)}
}break}}}
</script></body>

This is working jsfiddle example, and ungolfed source. It gets input from prompt(). You can adjust output size by adjusting sz = 300, and dot size by pt = 3 (in pixels).

Example (31 dots)


Let's make a map of dungeon Long time ago, when I was spending more time playing RPG, one of the issues what some players had, was to track party movement and to draw proper map.
So I come with idea, to check how you guys come deal with this issue.

Task is to write a function, which takes as input parameter list of directions (passed as structure of your choice) ^v<>, display map of dungeon.
In example for input: >>>vvv<<<^^^ output will be:

+----+               +----+
|    |               |>>>v|
| ++ |               |^++v|
| ++ |  because      |^++v|
|    |               |^<<<|
+----+               +----+

Testcases

>>>>>>vvvvv<<<<^^^>>v

 +-------+
 |       |
 +-+---+ |
   |   | |
   | + | |
   | +-+ |
   |     |
   +-----+

^^^^^vvv<<<^^vv>>>>>>>>vv>><<^^^^v>>>>v^<^

          +-+
       +-+| | +-++-+
       | || | | ++ ++
       | ++ +-+     |
       |        +-+ |
       +--+ +-+ +-+-+
          | | |   |
          +-+ +---+

As it is golf code challenge, shortest code wins.

Happy golfing.

EDIT
Sorry for late edit, I didn't have much time recently.

Map is generated based on movement.  It should contain only corridors which were visited during walk. Hence creating one big room won't be a valid answer.

There are three valid symbols in the map:

| vertical wall
| horizontal wall
+ intersection of vertical and horizontal wall.

Maximum length of the path is 255 character (but if you can, do not limit yourself).

More test cases:

 ><><><><

 +--+
 |  |
 +--+

 >^<v

 +--+
 |  |
 |  |
 +--+

I hope now everything is clear.


Draw the lambda blazon To celebrate the 2497th anniversary of the Greek victory at Salamis in 480 BC. Draw the lambda blazon.

The lambda blazon was the lambda painted on greek shields like so:

Puzzle: Given a positive odd integer n, produce an ascii art image of the above shield.

Specifications:

n=1:

( /\ )

n=3:

(   /\   )
|  /  \  |
( /    \ )

n=5

(     /\     )
|    /  \    |
|   /    \   |
|  /      \  |
( /        \ )

Graph:
n=3

          2|   (   /\   )
y-axis    1|   |  /  \  |
          0|   ( /    \ )
               ___________
               0123456789

                 x-axis

Description:

There should be exactly n \ characters and n / characters. The /s and \s should not touch the edge of the shield. The bottom and top corners of the shield will be denoted with a ( or ) unless n=1 where there will be one ) and one (. There will always be one space between the bottom corners and the lambda, increasing by 1 with the y axis until y + 1 == n. Non corners of the shield side will be denoted with |. There is no shield top.

Charcoal,  17  13 bytes

Thanks to @Neil for saving 4 bytes!

(↙↓⊖θＭ↑(→↗Ｎ‖Ｍ

Try it online!

Explanation:

(↙                // Print '(' and move one step down and to the left.
  ↓⊖θ             // Print n-1 '|'s downwards.
     Ｍ↑          // Move one step up.
        (→        // Print '(' and move one step to the right.
          ↗Ｎ      // Print n '/'s towards the upper right corner.
            ‖Ｍ    // Mirror the left half to produce the right half.


Two palindromes are not enough Some numbers, such as \$14241\$, are palindromes in base 10: if you write the digits in reverse order, you get the same number.

Some numbers are the sum of 2 palindromes; for example, \$110=88+22\$, or \$2380=939+1441\$.

For other numbers, 2 palindromes are not enough; for example, 21 cannot be written as the sum of 2 palindromes, and the best you can do is 3: \$21=11+9+1\$.

Write a function or program which takes integer input n and outputs the nth number which cannot be decomposed as the sum of 2 palindromes. This corresponds to OEIS A035137.

Single digits (including 0) are palindromes.

Standard rules for sequences apply:

input/output is flexible
you may use 0- or 1- indexing
you may output the nth term, or the first n terms, or an infinite sequence

(As a sidenote: all integers can be decomposed as the sum of at most 3 palindromes.)

Test cases (1-indexed):

1 -> 21
2 -> 32
10 -> 1031
16 -> 1061
40 -> 1103

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

JavaScript (ES6),  93 83 80  79 bytes
Saved 1 byte thanks to @tsh
Returns the \$n\$th term, 1-indexed.

i=>eval("for(n=k=1;k=(a=[...k+[n-k]+k])+''!=a.reverse()?k-1||--i&&++n:++n;);n")

Try it online!
How?
Given \$n\$, we test whether there exists any \$1\le k\le n\$ such that both \$k\$ and \$n-k\$ are palindromes. If we do find such a \$k\$, then \$n\$ is the sum of two palindromes.
The trick here is to process \$k\$ and \$n-k\$ at the same time by testing a single string made of the concatenation of \$k\$, \$n-k\$ and \$k\$.
Example:
For \$n=2380\$:

we eventually reach \$k=1441\$ and \$n-k=939\$
we test the string "\$1441\color{red}{939}1441\$" and find out that it is a palindrome

Commented
NB: This is a version without eval() for readability.
i => {                       // i = index of requested term (1-based)
  for(                       // for loop:
    n = k = 1;               //   start with n = k = 1
    k =                      //   update k:
      ( a =                  //     split and save in a[] ...
        [...k + [n - k] + k] //     ... the concatenation of k, n-k and k
      ) + ''                 //     coerce it back to a string
      != a.reverse() ?       //     if it's different from a[] reversed:
        k - 1                //       decrement k; if the result is zero:
          || --i             //         decrement i; if the result is not zero:
            && ++n           //           increment n (and update k to n)
                             //         (otherwise, exit the for loop)
      :                      //     else:
        ++n;                 //       increment n (and update k to n)
  );                         // end of for
  return n                   // n is the requested term; return it
}                            //


Move the "post your answer" form next to the question on SE sites I have a problem when posting an answer to a question that already have several answers and/or several comments:

The "post your answer" form sits on bottom, the answer is on top. There is an awful lot of "clutter" between them, that are not needed for the act of posting a new answer (yes, I've read the other answers and comments, what I am about to write is original).

I have a very short short term memory and hate to scroll all the way up and down to read question and write answer text.

Write a script or program that

Can run on vanilla (downloaded from the main page for those softwares) Firefox and/or Chrome (irrelevant if it also runs on other browsers or on all browsers)
you get 10 fake internet points from me if it runs on all browsers, but this is not a victory condition
You can call any code that ships with the browser, loads with the SE page (like jQuery) or sideloads from the web.
Can be run (as a bookmarklet, from console, any input method) on a fresh install of one of those two browsers.
Does not depend on any other software installed on the machine, or the installation of any add-ons and/or plugins on the browsers.
Irrelevant if it runs only on windows, only on mac or only on linux, as long as those browsers can be downloaded from the browsers' official download page, for that platform.
Does not break the submit answer form (I can still write my answer and submit, and the whole edit toolbar is still intact - including the help icon).
Question is intact. Title, body, votes panel, post menu and owner signature.

(italics denote editted-in content)

vertical Distance between bottom of owner signature and the top of edit toolbar is the same or smaller (negatives allowed) than when posting the first answer to a question in the same site.
Edit form toolbar cannot be higher than the question title.

both question, answer edit form, answer toolbar and answer preview have to remain visible and non-overlapping.

Only the screen display matters. If the other elements were hidden, deleted, moved, ejected into outer space or phase-shifted into a Dirac Sea is irrelevant.

Your code must work for a minimum of:

https://stackoverflow.com/
https://superuser.com/
https://codegolf.stackexchange.com/
https://rpg.stackexchange.com/
https://android.stackexchange.com/
https://scifi.stackexchange.com/

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

I am now required to link this question for the exerpts' credits. Thanks @Doorknob.

P.S.: It is my first time in PpCG, be kind.

JavaScript, 35 34 bytes

$(answers).before($('#post-form'))


Counting unit squares circle passes through Write a program or function that given an integer radius r returns the number of unit squares the circle with radius r centered at the origin passes through. If the circle passes exactly through a point on the grid that does not count as passing through the adjacent unit squares.

Here's an illustration for r = 5:

Illustration by Kival Ngaokrajang, found on OEIS

Examples:

  0 → 0
  1 → 4
  4 → 28
  5 → 28
  49 → 388
  50 → 380
  325 → 2540
  5524 → 44180
  5525 → 44020

Python 2, 54 bytes

f=lambda r,x=0:r-x and-~((r*r-x*x)**.5%1>0)*4+f(r,x+1)

Try it online!
Less golfed (55 bytes) (TIO)
lambda r:8*r-4*sum((r*r-x*x)**.5%1==0for x in range(r))

This estimates the output as 8*r, then corrects for vertex crossings. The result is 8*r-g(r*r), where g(x) counts the number of ways to write x as a sum of two squares (except g(0)=0).
If the circle never went through any vertices, the number of cells touched would equal the number of edges crossed. The circle passes through 2*r vertical gridlines and 2*r horizontal gridlines, passing each one in both directions, for a total of 8*r.
But, each crossing at a vertex counts as two edge crossings while only entering one new cell. So, we compensate by subtracting the number of vertex crossings.
This includes the points on axes like (r,0) as well as Pythagorean triples like (4,3) for r=5.
We count for a single quadrant the points (x,y) with x>=0 and y>0 with x*x+y*y==n, then multiply by 4. We do this by counting the numer of sqrt(r*r-x*x) that are whole number for x in the interval [0,r).


Solve an equation with (almost) any numbers you like Given a string of the characters +=- where there is at least one =, insert positive integers between all the symbols and at the start and the end such that the math equations are satisfied.

For example, given the input

+-=-=

you need to insert positive integers A through F like this

A+B-C=D-E=F

such that the equations are all satisfied, i.e. A + B - C and D - E and F are all the same number.

There are many possible ways to do this since, as long as the equations work out, any set of positive integers may be used. Each line here is a possible valid output to input +-=-=:

2+3-4=6-5=1
1+1-1=2-1=1
4+2-4=4-2=2
100+1-10=182-91=91
89+231-77=1024-781=243

Note that the value of the expressions is not required to be a positive integer like the inserted numbers are. For example, given input -=- the outputs 1-10=8-17 (evals to -9) and 10-1=17-8 (evals to 9) are both equally valid. Of course for some inputs such as = it's impossible to have a negative as the expression since only positive numbers like 5=5 can be inserted.

Note also that zero is not a positive integer.

The shortest code in bytes wins.

You may output the numbers as a list instead of inserting them directly into the string. If you do output the string there may be spaces separating symbols and numbers. So, for input +-=-=, outputting

2, 3, 4, 6, 5, 1

or

2 + 3 - 4 = 6 - 5 = 1

is equivalent to outputting

2+3-4=6-5=1

Test Cases

Input | One Possible Output
= | 1=1
== | 2=2=2
+= | 1+3=4
=+ | 2=1+1
-= | 30-10=20
=- | 1=2-1
=-= | 3=7-4=3
=+= | 2=1+1=2
=== | 100=100=100=100
+=- | 3+2=7-2
-=+ | 7-2=3+2
+=+ | 3+3=3+3
-=- | 1-10=8-17
--= | 60-1-1=58
++= | 60+1+1=62
-+= | 60-9+1=52
+-= | 60+9-1=68
+-=-= | 2+3-4=6-5=1
--=-- | 2-1-1=2-1-1
==-== | 47=47=50-3=47=47
=++=+-=-+=--= | 3=1+1+1=3+1-1=1-1+3=5-1-1=3
+--++-=-+-+- | 35+10-16-29+20+107-1000=5-4+3-2+1-876
====== | 8=8=8=8=8=8=8

Retina, 58 bytes

[-+]
$&1
\B((\+1)|(-1))*
$._$*1$#3$*1$#2$*_$&
+`1_

1+
$.&

Try it online!

Alternative solution at the same byte count:

((\+)|(-))*
$._$*1$#3$*1$#2$*_$&
+`1_

([+-])1*
$+1
1+
$.&

Try it online!

Explanation

The basic idea is to turn all the +s and -s into simple +1 and -1 operations and then to prepend a sufficiently large number that makes all the equations work. To make the equations match, we can simply prepend the same number to each of them, and then reduce it by one for each +1 and increase it by one for each -1 after it. Since we'll be working with unary numbers, the only catch is that the first number needs to be large enough that we can reduce it by 1 enough times.

[-+]
$&1

We start by inserting a 1 after each - or +.

\B((\+1)|(-1))*
$._$*1$#3$*1$#2$*_$&

The \B ensures that these matches are either at the beginning of the input, or between a = and a + or -, i.e. all the positions where we want to insert the leading number of an expression. The  ((\+1)|(-1))* part then simply counts the number of +1s and -1s in groups 2 and 3 respectively. Now let's break down the substitution string:

$._$*1   # For each character in the current string, insert a 1. This is
         # an offset which is the same for each expression and is guaranteed
         # to be large enough that all subsequent +1s can be cancelled.
$#3$*1   # For each -1, insert a 1.
$#2$*_   # For each +1, insert a _.
$&       # Re-insert the string of +1s and -1s.

+`1_

Repeatedly drop 1_ from the string, applying the required cancellation from the +1s.

1+
$.&

Finally, replace all the strings of 1s with their lengths to convert from unary to decimal.


Julia, 124 81 73 bytes

n->(a=2863311530;b=3435973836;[base(2,(i+a)$a)*base(4,(i+b)$b)for i=1:n])

This creates an unnamed function that accepts an integer and returns an array. Each element of the array is a successive number between 1 and n in negabinary concatenated to itself in negaquaternary.

The negabinary representation of an integer can be computed using Schroppel's shortcut:

base(2, (i + 2863311530) $ 2863311530)

For an integer i, this is i + 2863311530, XOR 2863311530, encoded in base 2. The negaquaternary shortcut is similar:

base(4, (i + 3435973836) $ 3435973836)


Avoid walking into a rectangle Given a rectangle, a start point, and an end point, find any path from start to finish that avoids the rectangle.
Example
Suppose you were at \$(1.5, -1.5)\$ and you needed to get to \$(2, 4)\$. However, there is a rectangle with upper left corner \$(1, 3)\$ and bottom right corner \$(4, 1)\$ in your way. It would look like this:

There are lots of paths you could take to get from the (green) start to the (red) end:

You could go via \$(-3, 3)\$.
You could go to \$(-1.5, -0.5)\$ and then to \$(-1, 4)\$.
Since you're infinitely thin (having perfected your workout routine), you could go via \$(4, 1)\$ and \$(4, 3)\$.
Among many others.

Here's what those three options look like (click for full size):

Challenge
Given a starting point \$S\$, an end point \$E\$, and the coordinates for the upper left and bottom right corners of a rectangle (in any format reasonable for your language, including complex numbers if you wish), output a series of points \$A_1, A_2, \ldots, A_n\$ of any length such that the piecewise linear path \$S \rightarrow A_1 \rightarrow A_2 \rightarrow \ldots \rightarrow A_n \rightarrow E\$ does not intersect the interior of the rectangle. Note that:

The start point and end point will not be inside the rectangle, nor on the edge or corner of the rectangle.
Your path may touch the corners and edges of the rectangle, but must not intersect the rectangle's interior.
You may output nothing, an empty list or similar if you wish to traverse \$S \rightarrow E\$ directly.
You may assume that the rectangle has a strictly positive width and height.
Your approach need not use the same number of points for all testcases.
The path may have duplicate points, and may intersect itself, if you so wish.

Testcases
Here, (sx,sy) is the start point, (ex,ey) is the end point, (tlx,tly) is the top left corner of the rectangle and (brx,bry) is the bottom right corner. Note that from the spec we will always have tlx < brx and tly > bry.
Input                                  -> Sample output (one of infinite valid answers)
(sx,sy), (ex,ey), (tlx,tly), (brx,bry) -> ...

(1.5,-1.5), (2,4), (1,3), (4,1)        -> (-3,3)
                                       or (-1.5,0.5),(-1,4)
                                       or (4,1),(4,3)

(-5,0), (5,0), (-1,1), (2,-2)          -> (0,5)
                                       or (-5,1),(5,1)

(0.5,-2), (0.5,1), (2,2), (4,-3)       -> []
                                       or (0.5,-0.5)
                                       or (-1,-0.5)

Scoring
The shortest code in bytes wins.

JavaScript (ES6),  66  57 bytes
Expects (Sx,Sy,Ex,Ey,[Tx,Ty],[Bx,By]). Returns 3 points.

(S,s,E,e,T,B,[x,y]=T)=>[S>x&s<y?B:T,[B[0],y],E>x&e<y?B:T]

Try it online!
Method
The first point is \$(Bx,By)\$ if the start point is in the gray area or \$(Tx,Ty)\$ otherwise.
The second point is always \$(Bx,Ty)\$.
The third point is \$(Bx,By)\$ if the end point is in the gray area or \$(Tx,Ty)\$ otherwise.


Match up to 10 in an array Challenge

Given an array of single digit number, work out if any 2 of them add up to 10 and print them out

Example

Input

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

This returns ((4,6),(5,5),(3,7))

Input

  (1,2,3,4,5)

This returns (). as there is only one 5

Input

  (5,5,5,5,5)

This returns ((5,5),(5,5)) as there is odd number of 5s and each 5 can be used only once

Rules

Here are the rules!

Assume input will only be an unsorted array of positive single digit integers
Each number will be pair up only once, which means if there are three 5s it only form 1 pair (5,5). If there are (3,3,7) it will only form 1 pair (3,7)
For the input: You can use any type of parentheses(or lack of) as long as readers can tell that the input is a single array of numbers.
For the output: It must look like an array of pairs. Where the array is the same form as your input.(If you did not use any parenheses in your input, you have to use some kind of symbols so that any readers can tell they are pairs in an array)

Test Cases

(1,2,3,4,5,5,6,7) =((4,6),(5,5),(3,7))
(1,2,3,4,5) = ()
(5,5,5,5,5) = ((5,5),(5,5))
(1,2,3,3,4,5,6,7)=((3,7),(4,6))
(9,8,7,6,4,4,3,1)=((9,1),(7,3),(6,4))

Good luck!

The shorter an answer is, the better!

Edit 1: update the rules and Testcases from comments

Edit 2: update rules to define format of input.

Edit 3: update rules to define format of output. trying to be as accommodating as possible.


Draw an asterisk triangle Inspired by a task for programming 101 here's a task that hopefully isn't too easy or is a duplicate (kinda hard to search for things like this).

Input:

A positive integer n >= 1.

Output:

n lines of asterisks, where every new line has one asterisk more than the line before, and starting with one asterisk in the first line.

General rules:

This is code-golf, so shortest answer in bytes wins.
Since the course is taught in C++, I'm eager to see solutions in C++.

Test case (n=5):

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

Vim, 8 bytes

o <Esc><C-V>{r*J

Takes input in the readahead buffer, so if input is 15, you would type that and then the code above. This is a silly rule, but seems to be allowed. If you got input in a register like "a, you'd just stick @a in front (10). If you got it from the start file, you'd prepend D@" instead (11).

Relies on abuse of :set autoindent, which is default in vimgolf.com rules and default in Vim 8 (and everyone uses it anyway).

o <Esc>: With its number argument, if your text starts with whitespace, and you have :set autoindent, Vim glitches out and creates a cascade of indent.
<C-V>{r*: Turn all those spaces into *s. I'm using block visual so that, even if your lousy indent settings silently group your spaces into tabs, you'll still get the right number of *s.
J: Starting with o unfortunately left a blank line at the top. This removes it.


Draw the prime race tracks Odd prime numbers are either in the form of 4k+1 or 4k+3 where k is a non-negative integer. If we divide the set of odd prime numbers into two such groups like this:
4k+3  |   3     7  11          19  23      31          43  47      59      67  71
      |
4k+1  |      5         13  17          29      37  41          53      61          73

we can see that the two groups are kind of racing with each other. Sometimes the so-called 'upper' group wins and sometimes the 'lower' one is on track. In fact, Chebyshev discovered that in this race, the upper group wins slightly more often.
The problem
Let's assume that we are interested in knowing the shape of this race track up to a certain number. Something like this:

The upper and lower horizontal lines indicate that the next prime stays in the same group, while the slanted lines indicate a 'jump' from one group to the other.
Now assume that the underline character _ represents a lower horizontal line and the overline character ‾ (U+203E) represents an upper one. The slanted lines are represented by slash / or backslash \ characters.
Challenge
Write a program or function that gets a number N as input, and draws this prime race track up to N, in a kind of ASCII-art-form described as above (Well, it's not an actual ASCII-art since it would contain a non-ASCII character).
Rules

N is an integer and not necessarily a prime number. Draw the race path for the primes up to, (and maybe including) N.
For a valid N as input, the output shall only be composed of these four characters ‾_/\. No other character, space or separator is allowed (except maybe at the end of output).
The output can either be in a text file or stdout or wherever supports displaying those characters. But an actual plot (like the blue figure above) is not desired.
This is code-golf, so the shortest code in bytes wins.

Examples
Here is a list of possible inputs and their acceptable outputs.
N < 5        no output or maybe an error message whatsoever
N = 5        \
N = 20       \/‾\_/
N = 100      \/‾\_/‾\/\_/‾\/\/‾\/‾\_

Trivia
The resulting plots of this challenge may actually resemble the derivative of the plots shown in there.

05AB1E, 31 26 19 bytes
…\/_ŽW ç«ÀIÅP¦4%üeè

-5 bytes by taking inspiration from @HyperNeutrino's Jelly answer.
-7 bytes thanks to @Grimmy.
Outputs as a list of characters.
Try it online (the J in the footer is to join the list together to pretty-print it).
Explanation:

…\/_                 # Push the string "\/_"
    ŽW               # Push compressed integer 8254
       ç             # Convert it to a character with this codepoint: "‾"
        «            # Append it to the earlier string: "\/_‾"
         À           # And rotate it once to the left: "/_‾\"
          IÅP        # Push a list of all primes <= the input-integer
                     #  i.e. 50 → [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47]
             ¦       # Remove the first value
                     #  → [3,5,7,11,13,17,19,23,29,31,37,41,43,47]
              4%     # Take modulo-4 on each value
                     #  → [3,1,3,3,1,1,3,3,1,3,1,1,3,3]
                ü    # For each overlapping pair:
                     #  → [[3,1],[1,3],[3,3],[3,1],[1,1],[1,3],[3,3],[3,1],[1,3],[3,1],[1,1],[1,3],[3,3]]
                 e   #  Get the number of permutations; short for ⌊a!/|a-b|!⌋
                     #   → [3,0,6,3,1,0,6,3,0,3,1,0,6]
                  è  # And index each into the earlier created string
                     # (0-based and with wraparound, so the 6 is index 2 in this case)
                     #  → ["\","/","‾","\","_","/","‾","\","/","\","_","/","‾"]
                     # (after which the result is output implicitly as result)

See this 05AB1E tip of mine (section How to compress large integer?) to understand why ŽW  is 8254.


Same length, different string Challenge

Given a non-empty string S of length L consisting entirely of printable ASCII chars, output another string of length L that consists entirely of printable ASCII chars, but is not equal to S.

For the purposes of this challenge, a printable ASCII char is one between U+0020 and U+007E, inclusive; that is, from   (space) to ~ (tilde). Newlines and tabs are not included.

For example, given "abcde", some valid outputs could be:

"11111"
"abcdf"
"edcba"

But these would be invalid:

"abcde"
"bcde"
"abcde0"

Test cases

"asdf"
"1111"
"       "
"~~~~~"
"abcba"
"1"
" "
"~"
" ~"
"~ "
"  0"
"!@#$%^&*()ABCDEFGhijklmnop1234567890"
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"

Rules

You may assume the input consists entirely of printable ASCII chars.
You may not assume that the input does not contain all 95 printable chars.
You may assume the input contains at least one character and is less than 256 chars long.
The output must also consist entirely of printable ASCII chars. You could not, for example, output the byte \x7F for input "~".
The output must be different than the input with probability 1; that is, you may generate random strings until one is different than the input, but you can't just output L random characters and hope it's different.
Newlines are disallowed in the output, but you may output one trailing newline which is not counted toward the string.

Scoring

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

Python 2, 21 bytes

lambda s:`s`[:len(s)]

Try it online!

Takes the string representation of the input string and truncates it to the length of the input string. For a typical string, this puts it in ' quotes and chops off the end:

abc  ->   'abc'  ->  'ab
     rep        chop

Note that the new string starts with '. Let's show that the output always differs from the input.

If the input has no ', then the output starts with ' and the input does not.
If the input contains a ' and but no ", then Python will use " for the outer quotes, giving a first character " that's not in the input string.
If the input has both ' and ", then the outer quotes are ' and each ' is escaped as \'. Wherever the first " appears in the input, it's shifted right by the initial ' in the output and by any possible escaping. This means it cannot match with a " in the corresponding position in the output.

Finally, note that quoting the input and possibly escaping characters always increases the number of characters, so truncating the output makes it the same length as the input.

Note that it was crucial that Python adaptively switches to " in the second case. If it didn't do so, it would fail on the three-character input '\'. Or, any longer prefix of the fix show string using '. So, this method won't work for most languages.


generate a valid equation using specified operators A twist on a recently asked question, you are given a list of operators and a result and you need to find integers which, when operated on by those operators, generate the result.

Example 1

input

+ + * / 13

possible output

4 8 2 2 4

which means that 4 + 8 + 2 * 2 / 4 = 13.

More specifically, you are given a sequence of N operators (between 1 and 5 inclusive) and an integer result, space separated.  You must print N+1 integers, space separated, in the range 1 through 9, inclusive, that when alternated with the operators produce the result.

The operators are +,-,*,/.  They have the natural precedence order (* and / before + and -, left associative).  Divides must be integral divides, a divide with a fractional result is not allowed.  Operators must appear in the order given.

Most problems will have more than one solution.  Printing any of them, or any subset of them, is fine.  If there is no solution, print NO SOLUTION.

Example 2

input

/ + - - 16

output

9 1 9 1 1

Example 3

input

+ 5

output

1 4
2 3
3 2
4 1

(or any nonempty subset of those lines)

Example 4

input

+ + 30

output

NO SOLUTION

Example 5

input

/ + / 3

output

6 3 5 5

note that 3 2 3 2 is not a solution, as 3/2+3/2=3 is true but the individual divides have fractional values.

Standard code golf, shortest answer wins.

Perl, 129 160 151 chars

sub a{my($s,$t,$o)=splice@_,0,3;@_?map{a("$s $_","$t$o$_",@_)}1..9:
$o-eval$t||$o-eval"use integer;$t"||exit say$s}a"","","",split$",<>;say"NO SOLUTION"

Fun with recursion. The program exits upon finding the first valid tuple.

The eval has to be done twice, in and out of integer-only mode, in order to avoid invalid solutions like that given in example 5 in the description.


Tips for golfing in Pure Data Pure data is a graphical programming language designed for audio processing.  This makes it unsuitable for most general programming but especially unsuitable for code-golf.

It would then be nice to have a tips question so that people can get a first foot up in this language.

What tips are there for golfing in Pure Data?  Answers should apply specifically to Pure Data.

Use a text editor

The editor that comes with Pure Data is really useful for making programs that work or helping you to understand existing programs.  However if you want to golf, the files it creates are full of extra stuff that can be removed with an text editor (e.g. vim).

This post will serve as a list of a bunch of small byte saving tricks accessible only through or more easily though a traditional editor.

Use defaults on canvas:  Your file needs a canvas line.  #N canvas; is enough to get things to run without error. The missing arguments default to zero.
Newlines are optional:  The graphical editor puts newlines between statements.  Presumably to make these files somewhat readable.  However these are not strictly required and can be removed with an editor.
Rearrange your objects for better object indices:  Since connections identify objects by their order in the source, placing objects with a lot of connections earlier in the file can shorten your source.  Make sure that you update all the references once you reorder.
Put everything in the top left:  Since object location is purely a graphical aid, you can place them wherever. Single digit locations are the shortest so changing the location to 0 0 or something similar will save you.  This turns your code into an unreadable blob so it is probably best to do this once everything already works.


Efficient Typing on a Game Boy Many old Game Boy games often required string input from the user. However, there was no keyboard. This was handled by presenting the user with a "keyboard screen" like so:

The 'character pointer' would begin on letter A. The user would navigate to each desired character with the D-Pad's four buttons (UP, DOWN, LEFT and RIGHT), then press BUTTON A to append it to the final string.

Please note:

The grid wraps around, so pressing UP whilst on letter A would take you to T.
The 'character pointer' stays put after appending a letter

The Challenge

The above keyboard has options to change case and is an irregular shape. So, for simplicity, in this challenge we will use the following keyboard (the bottom right is ASCII char 32, a space):

A B C D E F G
H I J K L M N
O P Q R S T U
V W X Y Z .

Typing on keyboards like this is extremely slow - so, to make this easier, your task is to write a program which tells the user the fastest possible way to type a given string. If there are multiple fastest ways, you only need to show one.

The output key should be:

> for RIGHT
< for LEFT
^ for UP
v for DOWN
. for BUTTON A (append current letter to string)

For example, when given the string DENNIS, the solution would look like this:

>>>.>.>>v..>>.>>>v.

Rules / Details

Please remember, the grid wraps around!
You may submit a full program or a function, as long as it takes the initial string and produces a solution string. Whitespace / trailing newlines are irrelevant as long as the output is correct.
You can assume input will only consist of characters typable on the specified keyboard, but it may be empty.
This is code-golf, so the shortest code wins. Standard code-golf loopholes apply.

Test Cases

There are usually multiple solutions of the same length. For each test case, I've included the optimum length, and an example. You don't need to print the length in your answer, just the solution.

FLP.TKC  ->  25 steps:  <<.<v.<<<v.<<<v.^.<<^.<^.
MOYLEX   ->  23 steps:  <<v.>>v.>>>v.>^^.^.<<^.
FEERSUM  ->  18 steps:  <<.<..<vv.>.>>.<^.
MEGO     ->  14 steps:  <<v.<^.>>.>vv.

A CAT    ->  17 steps:  .<^.>>>v.<<.<<vv.
BOB      ->  10 steps:  >.<vv.>^^.

(space)  ->  3 steps:   <^.
(empty)  ->  0 steps:   (empty)

You can view my testcase generator on repl.it - please notify me if there are any bugs.

Thank you everyone for the submissions! User ngn is currently the winner with 61 bytes, but if anyone can find a shorter solution, the little green tick can be moved ;)

JavaScript (ES6), 147 bytes

s=>s.replace(/./g,c=>(q=p,p="AHOVBIPWCJQXDKRYELSZFMY.GNU ".indexOf(c),"<<<>>>".substring(3,((p>>2)+10-(q>>2))%7)+["","v","vv","^"][p-q&3]+"."),p=0)

An interesting behaviour of substring is that it exchanges the arguments if the second is less than the first. This means that if I calculate the optimal number of left/right presses as a number between -3 and 3, I can add 3, and take the substring of <<<>>> starting at 3 and I will get the correct number of arrows. Meanwhile the down/up presses are simply handled by looking up an array using a bitwise and of the difference in rows with 3; this way is slightly shorter as there are fewer array elements.


Shortest parser for a left-recursive grammar Write the shortest parser for the grammar:

M -> M + n | n

Output must be some representation of a structured value representing the concrete syntax tree produced by the input n+n+n.
The code to produce the textual output from the structured value is not necessary.
The code to read/validate input is not necessary.
Solution is anything that can somehow be called; a function, an object, doesn't matter.
How your solution receives input (currying character-by-character, whole-string, some kind of input reader) does not matter.

For example a bottom-up parser (Javascript, 284 characters):

function M(d){function c(a){throw"unexpected "+a;}function f(a){if("+"==a)return b.push(a),e;if(null==a)return b;c(a)}function e(a){if("n"==a)return b.push(a),b=[b],g;c(a)}function g(a){if("+"==a)return b.push(a),e;if(null==a)return b;c(a)}var b=[];if("n"==d)return b.push(d),f;c(d)};

When called:

 M('n')('+')('n')('+')('n')(null)

will return an array that in JSON-notation looks like this:

[["n", "+", "n"], "+", "n"]

Edit for the uninitiated in parsing: This is one of those questions where making a program produce the correct output is easy but the form of the program is essential for up-boats.

M -> M + n | n

Means that M consists of a previous M, a plus sign and a literal "n". Or good M is a single "n" literal character.

There are several way of approaching this challenge, I'll describe my own solution, which is called bottom-up parsing. Character by character:

 Stack               Incoming Character         Action on stack
                     n
 n                   +                          reduce "n" to M
 M+                  n
 M+n                 +                          reduce "M + n" to M
 M+                  n
 M+n                 EOF                        reduce "M + n" to M
 M

The twist in this question is that the simplest form of parsers called "recursive-descent" parsers won't work because the grammar is left-recursive and that throws a recursive-descent parser into an infinite loop.

Ruby, 51 bytes

f=->s{s.split(/(\+)(?=n$)/).map{|t|t['+n']?f[t]:t}}

This seems weirdly cumbersome. It can be called like f['n+n+n'].


Shortest "arithmetic" formula to output 1000 primes Write a formula using only the digits 0-9, +, *, -, /, % and ^ to output a 1000 distinct primes when given input (which can be used as a variable n in the formula) of numbers 1 to 1000. (Note that / will give the quotient as all arithmetic is integer arithmetic.) Solutions can use ( and ) freely and they will not be counted in the length.
The shortest formula wins! The primes only need to be some 1000 primes not necessarily the first 1000.
EDIT
Edited for clarity based on suggestions by Sisyphus and an earlier question on primality testing.
Symbols are meant to work with integers in the "usual" way as follows.
n
:    Represents a number from 1 to 1000 which is the "input" to the formula. It can be used any number of times in the formula and it will represent the same input.
0-9
:    Sequences of digits (terminated by non 0-9 symbols or  ) return the number represented by this decimal representation. Negation of an expression can be represented as (-{expression})
+
:    Returns the sum of two numbers
*
:    Returns the product of two numbers
/
:    Returns the integer quotient of two numbers
%
:    Returns the remainder on division of the first number by the second number. This and / follow Euclidean division conventions.
-
:    Returns the result of subtracting the second number from the first number.
^
:    Returns the power of the first number by the second number. Anything to the power 0 is taken as 1 including 0!
()
:    Brackets are used in pairs to encapsulate an expression that returns a number using the previous rules.


How many times is rectangular array A embedded in rectangular array B? Given two rectangular arrays, A and B, let's say that A is embedded in B if A can be obtained from B by deleting some (or none) of the rows and columns of B.

Write a program with the following I/O:

Input: two arbitrary rectangular arrays of letters (a-z), as a string from stdin.

Output: the number of embeddings of the first array in the second array, followed by a "text picture" of each embedding (showing deleted elements replaced by dots).

(This is a two dimensional generalization of my old question Is string X a subsequence of string Y?)

Example:

input:

abb
aba

ababb
aabba
babab
abbaa

output  (if I haven't missed any):

5

a..bb
a..ba
.....
.....

ab.b.
.....
.....
ab.a.

ab..b
.....
.....
ab..a

.....
a.bb.
.....
a.ba.

.....
.abb.
.aba.
.....

The winner is the shortest such program (least number of characters).

APL (160)

{∆,⍨⍴∆←⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨⊃¨∘.∧/¨∆/⍨⍺∘≡¨⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆←,⊃∘.,/⊂¨¨K{⍵=0:⊂⍺/1⋄~(⍳⍺)∘∊¨⍵{⍺=1:(⍳⍵)⋄∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵}⍺}¨(K←⍴⍵)-⍴⍺}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬

Output:

      {∆,⍨⍴∆←⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨⊃¨∘.∧/¨∆/⍨⍺∘≡¨⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆←,⊃∘.,/⊂¨¨K{⍵=0:⊂⍺/1⋄~(⍳⍺)∘∊¨⍵{⍺=1:(⍳⍵)⋄∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵}⍺}¨(K←⍴⍵)-⍴⍺}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬
abb
aba

ababb
aabba
babab
abbaa

 5  .....  .....  ab..b  ab.b.  a..bb
    a.bb.  .abb.  .....  .....  a..ba
    .....  .aba.  .....  .....  .....
    a.ba.  .....  ab..a  ab.a.  .....

Explanation:

{...}/{×⍴K←⍞:∇⍵,⊂K⋄↑⍵}¨⍬⍬: read the two arrays from the keyboard, and return them as two matrices. Reduce the following function over the list of the two matrices.
∆{...}¨(∆←⍴⍵)-⍴⍺: get the height and width of each of the matrices. In both the width and the height, get a list of possible lines to drop.

⍵=0:⊂⍺/1: if the matrices are the same length in a dimension, never drop any lines from that dimension. Otherwise:
⍺=1:(⍳⍵)⋄: If the difference is one, try to drop each line
∆/⍨{∧/</¨2,/⍵}¨∆←,⍳⍺/⍵: otherwise, drop each possible combination of ⍺ lines.

∆←,⊃∘.,/⊂¨¨: combine each height mask with each width mask, giving all possible combinations to make the second list the size of the first.
⍵∘{(⊃⍵)⌿⍺/⍨⊃⌽⍵}¨∆: for each possible combination, remove those lines from the second matrix.
∆/⍨⍺∘≡¨: drop all the ones that are not equal to the first matrix, giving the solutions.
⊃¨∘.∧/¨: for each of the possible solutions, make a matrix with 0 where a dot should go and 1 where the corresponding character from the first matrix should go.
⍵∘{(⍴⍵)⍴(,⍵){⍺:⍵⋄'.'}¨,⍺}¨: for each of these, flatten both the second matrix (,⍵) and the matrix of dots (,⍺), and take either the character or a dot for each position ({⍺:⍵⋄'.'}¨). Then reshape it to the shape it had before ((⍴⍵)⍴).
∆,⍨⍴∆: give the amount of solution, and each solution.


Diluted Integer Sums A positive integer can be diluted by inserting a 0 between two bits in its binary expansion. This means that an n-bit number has n-1 dilutions, which are not necessarily all distinct.

For example, for 12 (or 1100 in binary), the dilutions are

11000 = 24
   ^

11000 = 24
  ^

10100 = 20
 ^

In this challenge, we're going to be taking the sum of all the dilutions, exclusive of the original number. For 12, taking the sum of 24, 24, 20 results in 68, so 68 should be the output for 12.

Challenge

Given a positive integer n > 1 as input, output/return the diluted sum as explained above.

Examples

in    out
---   ---
2       4
3       5
7      24
12     68
333  5128
512  9216

Rules

The input and output can be assumed to fit in your language's native integer type.
The input and output can be given in any convenient format.
Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
Standard loopholes are forbidden.
This is code-golf so all usual golfing rules apply, and the shortest code (in bytes) wins.

Python 2, 43 39 bytes

f=lambda n,i=2:n/i and n*2-n%i+f(n,i*2)

Try it online!

How?

Each call of the recursive function calculates a single dilution. The position of the inserted 0 is log2(i). The function recurses until i gets bigger than n and the insertion would be on the left of the number. If i>n, n/i evaluates to 0, which is a falsy value in Python.

n*2 shifts the entire number one binary digit left, n%i or n % 2**(position of insertion) calculates the value of the part that should not be shifted left. This value gets subtracted from the shifted number.

Example (n=7)

call       n/i          bin(n)  n*2     n%i   dilution       return value

f(7, i=2)  3 => truthy  0b111   0b1110  0b1   0b1101 = 13    13 + f(7, 2*2) = 13 + 11 = 24
f(7, i=4)  1 => truthy  0b111   0b1110  0b11  0b1011 = 11    11 + f(7, 4*2) = 11 + 0 = 11
f(7, i=8)  0 => falsy                                        0


Computer: you do the math This challenge is partly an algorithms challenge, involves some math and is partly simply a fastest code challenge.

For some positive integer n, consider a uniformly random string of 1s and 0s of length n and call it A.   Now also consider a second uniformly chosen random string of length n whose values are -1, 0, or 1 and call it B_pre.   Now let B be B_pre+B_pre. That is B_pre concatenated to itself.

Now consider the inner product of A and B[j,...,j+n-1] and call it Z_j and index from 1.

Task

The output should be a list of n+1 fractions. The ith term in the output should be the exact probability that all of the first i terms Z_j with j <= i equal 0.

Score

The largest n for which your code gives the correct output in under 10 minutes on my machine.

Tie Breaker

If two answers have the same score, the one submitted first wins.

In the (very very) unlikely event that someone finds a method to get unlimited scores, the first valid proof of such a solution will be accepted.

Hint

Do not try to solve this problem mathematically, it's too hard. The best way in my view is to go back to basic definitions of probability from high school and find smart ways to get the code to do an exhaustive enumeration of the possibilities.

Languages and libraries

You can use any language which has a freely available compiler/interpreter/etc. for Linux and any libraries which are also freely available for Linux.

My machine
The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. As a consequence, only use easily available free software and please include full instructions how to compile and run your code.

Some test outputs. Consider just the first output for each n. That is when i=1. For n from 1 to 13 they should be.

 1: 4/6
 2: 18/36
 3: 88/216
 4: 454/1296
 5: 2424/7776
 6: 13236/46656
 7: 73392/279936
 8: 411462/1679616
 9: 2325976/10077696
10: 13233628/60466176
11: 75682512/362797056
12: 434662684/2176782336
13: 2505229744/13060694016

You can also find a general formula for i=1 at http://oeis.org/A081671 .

Leaderboard (split by language)

n = 15. Python + parallel python + pypy in 1min49s by Jakube
n = 17. C++ in 3min37s by Keith Randall
n = 16. C++ in 2min38s by kuroi neko

Python 2 using pypy and pp: n = 15 in 3 minutes

Also just a simple brute force. Interesting to see, that I nearly get the same same speed as kuroi neko with C++. My code can reach n = 12 in about 5 minutes. And I only run it on one virtual core.

edit: Reduce search space by a factor of n

I noticed, that a cycled vector A* of A produces the same numbers as probabilities (same numbers) as the original vector A when I iterate over B.
E.g. The vector (1, 1, 0, 1, 0, 0) has the same probabilities as each of the vectors (1, 0, 1, 0, 0, 1), (0, 1, 0, 0, 1, 1), (1, 0, 0, 1, 1, 0), (0, 0, 1, 1, 0, 1) and (0, 1, 1, 0, 1, 0) when choosing a random B. Therefore I don't have to iterate over each of these 6 vectors, but only about 1 and replace count[i] += 1 with count[i] += cycle_number.

This reduces the complexity from Theta(n) = 6^n to Theta(n) = 6^n / n. Therefore for n = 13 it's about 13 times as fast as my previous version. It calculates n = 13 in about 2 minutes 20 seconds. For n = 14 it is still a little bit too slow. It takes about 13 minutes.

edit 2: Multi-core-programming

Not really happy with the next improvement. I decided to also try to execute my program on multiple cores. On my 2 + 2 cores I now can calculate n = 14 in about 7 minutes. Only a factor of 2 improvement.

The code is available in this github repo: Link. The multi-core programming makes is a little bit ugly.

edit 3: Reducing search space for A vectors and B vectors

I noticed the same mirror-symmetry for the vectors A as kuroi neko did. Still not sure, why this works (and if it works for each n).

The reducing of the search space for B vectors is a bit cleverer. I replaced the generation of the vectors (itertools.product), with an own function. Basically, I start with an empty list and put it on a stack. Until the stack is empty, I remove a list, if it has not the same lenght as n, I generate 3 other lists (by appending -1, 0, 1) and pushing them onto the stack. I a list has the same length as n, I can evaluate the sums.

Now that I generate the vectors myself, I can filter them depending on if I can reach the sum = 0 or not. E.g. if my vector A is (1, 1, 1, 0, 0), and my vector B looks (1, 1, ?, ?, ?), I know, that I cannot fill the ? with values, so that A*B = 0. So I don't have to iterate over all those 6 vectors B of the form (1, 1, ?, ?, ?).

We can improve on this, if we ignore the values for 1. As noted in the question, for the values for i = 1 are the sequence A081671. There are many ways to calculate those. I choose the simple recurrence: a(n) = (4*(2*n-1)*a(n-1) - 12*(n-1)*a(n-2)) / n. Since we can calculate i = 1 in basically no time, we can filter more vectors for B. E.g. A = (0, 1, 0, 1, 1) and B = (1, -1, ?, ?, ?). We can ignore vectors, where the first ? = 1, because the A * cycled(B) > 0, for all these vectors. I hope you can follow. It's probably not the best example.

With this I can calculate n = 15 in 6 minutes.

edit 4:

Quickly implemented kuroi neko's great idea, which says, that B and -B produces the same results. Speedup x2. Implementation is only a quick hack, though. n = 15 in 3 minutes.

Code:

For the complete code visit Github. The following code is only a representation of the main features. I left out imports, multicore programming, printing the results, ...

count = [0] * n
count[0] = oeis_A081671(n)

#generating all important vector A
visited = set(); todo = dict()
for A in product((0, 1), repeat=n):
    if A not in visited:
        # generate all vectors, which have the same probability
        # mirrored and cycled vectors
        same_probability_set = set()
        for i in range(n):
            tmp = [A[(i+j) % n] for j in range(n)]
            same_probability_set.add(tuple(tmp))
            same_probability_set.add(tuple(tmp[::-1]))
        visited.update(same_probability_set)
        todo[A] = len(same_probability_set)

# for each vector A, create all possible vectors B
stack = []
for A, cycled_count in dict_A.iteritems():
    ones = [sum(A[i:]) for i in range(n)] + [0]
    # + [0], so that later ones[n] doesn't throw a exception
    stack.append(([0] * n, 0, 0, 0, False))

    while stack:
        B, index, sum1, sum2, used_negative = stack.pop()
        if index < n:
            # fill vector B[index] in all possible ways,
            # so that it's still possible to reach 0.
            if used_negative:
                for v in (-1, 0, 1):
                    sum1_new = sum1 + v * A[index]
                    sum2_new = sum2 + v * A[index - 1 if index else n - 1]
                    if abs(sum1_new) <= ones[index+1]:
                        if abs(sum2_new) <= ones[index] - A[n-1]:
                            C = B[:]
                            C[index] = v
                            stack.append((C, index + 1, sum1_new, sum2_new, True))
            else:
                for v in (0, 1):
                    sum1_new = sum1 + v * A[index]
                    sum2_new = sum2 + v * A[index - 1 if index else n - 1]
                    if abs(sum1_new) <= ones[index+1]:
                        if abs(sum2_new) <= ones[index] - A[n-1]:
                            C = B[:]
                            C[index] = v
                            stack.append((C, index + 1, sum1_new, sum2_new, v == 1))
        else:
            # B is complete, calculate the sums
            count[1] += cycled_count  # we know that the sum = 0 for i = 1
            for i in range(2, n):
                sum_prod = 0
                for j in range(n-i):
                    sum_prod += A[j] * B[i+j]
                for j in range(i):
                    sum_prod += A[n-i+j] * B[j]
                if sum_prod:
                    break
                else:
                    if used_negative:
                        count[i] += 2*cycled_count
                    else:
                        count[i] += cycled_count

Usage:

You have to install pypy (for Python 2!!!). The parallel python module isn't ported for Python 3. Then you have to install the parallel python module pp-1.6.4.zip. Extract it, cd into the folder and call pypy setup.py install.

Then you can call my program with

pypy you-do-the-math.py 15

It will automatically determine the number of cpu's. There may be some error messages after finishing the program, just ignore them. n = 16 should be possible on your machine.

Output:

Calculation for n = 15 took 2:50 minutes

 1  83940771168 / 470184984576  17.85%
 2  17379109692 / 470184984576   3.70%
 3   3805906050 / 470184984576   0.81%
 4    887959110 / 470184984576   0.19%
 5    223260870 / 470184984576   0.05%
 6     67664580 / 470184984576   0.01%
 7     30019950 / 470184984576   0.01%
 8     20720730 / 470184984576   0.00%
 9     18352740 / 470184984576   0.00%
10     17730480 / 470184984576   0.00%
11     17566920 / 470184984576   0.00%
12     17521470 / 470184984576   0.00%
13     17510280 / 470184984576   0.00%
14     17507100 / 470184984576   0.00%
15     17506680 / 470184984576   0.00%

Notes and ideas:

I have a i7-4600m processor with 2 cores and 4 threads. It doesn't
matter If I use 2 or 4 threads. The cpu-usage is 50% with 2 threads and 100% with 4 threads, but it still takes the same amount of time. I don't know why. I checked, that each thread only has to the the half amout of data, when there are 4 threads, checked the results, ...
I use a lot of lists. Python isn't quite efficient in storing, I have to copy lots of lists, ... So I thought of using an integer instead. I could use the bits 00 (for 0) and 11 (for 1) in the vector A, and the bits 10 (for -1), 00 (for 0) and 01 (for 1) in the vector B. For the product of A and B, I would only have to calculate A & B and count the 01 and 10 blocks. Cycling can be done with shifting the vector and using masks, ... I actually implemented all this, you can find it in some of my older commits on Github. But it turned out, to be slower than with lists. I guess, pypy really optimizes list operations.


Roman Numeral Counting Roman numerals can be (mostly) written in a one column format, because each letter intersects the top and the bottom of the line. For example: I, or 1 intersects both the top and bottom of the line, and V or 5 intersects the bottom and top lines, the top twice and the bottom at one place.

The value of all roman numerals is as follows:
I = 1
V = 5
X = 10
L = 50
C = 100
D = 500
M = 1000

and the number of intersections (top, bottom) is:
I = 1,1
V = 2,1
X = 2,2
L = 1,2
C = 1,1
D = 1,1
M = 2,3

Your job is to take in 2 numbers, which represent the number of intersections on the top and bottom of your line (in that order), and output all possible valid combinations of roman numerals, from smallest by literal value to largest. Inputs will always be at or above 1.

Here are some test cases:

Input: 1,1
Output: I,C,D

Input: 1,2
Output: L

Input: 2,1
Output: V

Input: 2,2
Output: II, X, IC, CI, CC, ID, DI
(note that DD is not a valid roman numeral, and thus should not be outputted, the value of all of these is (in order) 2, 10, 99, 101, 499, 501)

Input: 3,3
Output: III, IX, XI, LV, XC, CII, CX, CCI, CCC, DII, DX, DCI, DCC
(note that IIC, and IID are not valid numbers. DD (1000) is also not a valid number, as the correct numeral is M) The value of these numbers (in order) is: 3, 9, 11, 55, 90, 102, 110, 201, 300, 502, 510, and 601)

This is a usual code-golf, and needless to say, I'm interested to see how golf languages implement roman numeral counting rules. Best of luck!

05AB1E, 32 29 25 bytes
žDL.Xʒ•BÌË"•4в2ôsÇ87%èøOQ

-7 bytes thanks to @Grimy.
Try it online or verify all test cases.
Explanation:

žD                # Push builtin 4096 (the maximum Roman number is 3999)
  L               # Create a list in the range [1,4096]
   .X             # Convert each integer to a Roman number
     ʒ            # Filter this list by:
      •BÌË"•     "#  Push compressed integer 195646806
            4в    #  Convert it to base-4 as list: [2,3,2,2,2,1,1,1,1,1,1,1,1,2]
              2ô  #  Split it into parts of size 2:
                  #   [[2,3],[2,2],[2,1],[1,1],[1,1],[1,1],[1,2]]
      s           #  Swap to get the current Roman number we're filtering on
       Ç          #  Convert its characters to their unicode values
        87%       #  Take modulo-87 for each (I=73; V=86; X=1; L=76; C=67; D=68; M=77)
           è      #  Index those into the list of pairs (with automatic wrap-around)
            ø     #  Zip/transpose; so we have inner lists of top/bottom values
             O    #  Sum each inner list
              Q   #  And check if it's equal to the (implicit) input-pair
                  # (after the filter, the result is output implicitly)

See this 05AB1E tip of mine (sections How to compress large integers? and How to compress integer lists?) to understand why •BÌË"• is 195646806 and •BÌË"•4в is [2,3,2,2,2,1,1,1,1,1,1,1,1,2].


Calculate a user's privileges on CodeGolf.SE The Challenge

Your goal is to write the shortest program possible that will take a list of events (such as upvote, downvote, etc) and return the user's reputation and the privileges that he has earned.

What sort of events?

Here is a chart of the events, listed in order of reputation earned:

-15 answer unaccepted
-10 answer unupvoted
-5  question unupvoted
-2  answer downvoted
-2  question downvoted
-2  unaccept answer
-1  downvote answer
+1  join website
+1  undownvote answer
+2  accept answer
+2  question undownvoted
+2  answer undownvoted
+5  question upvoted
+10 answer upvoted
+15 answer accepted
+100 association bonus

What sort of privileges?

Here is a list of privileges, in order of reputation required.

1 create posts
5 participate in meta
10 remove new user restrictions
10 create wiki posts
15 vote up
15 flag posts
20 talk in chat
50 comment everywhere
75 set bounties
100 edit community wiki
100 create chat rooms
125 vote down
150 create tags
200 retag questions
250 view close votes
500 cast close and reopen votes
750 established user
1000 edit questions and answers
1000 create gallery chat rooms
1250 create tag synonyms
1500 approve tag wiki edits
2000 access to moderator tools
3500 protect questions
4000 trusted user

Input

Input (on STDIN) will be a list of events, one per line, exactly how they appear in the first chart (except for the amount of reputation). A blank line represents the end of input. Here is an example (there should be a blank line at the end):

join website
association bonus
answer upvoted
answer upvoted
question upvoted
answer accepted
answer upvoted
accept answer
unaccept answer
question unupvoted
accept answer
question upvoted

Output

The first line of output (to STDOUT) should name the amount of rep accumulated. Each line after that should list one privilege earned, exactly as they appear and in the same order as the second chart. The expected output for the above input:

153 reputation
1 create posts
5 participate in meta
10 remove new user restrictions
10 create wiki posts
15 vote up
15 flag posts
20 talk in chat
50 comment everywhere
75 set bounties
100 edit community wiki
100 create chat rooms
125 vote down
150 create tags

Rules, Restrictions, and Notes

This is code golf. Standard code golf rules apply.

(EDIT: Since I have had two entries that access files, I would like to point out that the length of the file needs to be added to code length as part of the standard rules for code golf)


Solve a game of Accordion Accordion is a solitaire card game I recently came across where nearly every layout is solvable, but incredibly hard.  You can play it here.
Rules
52 face cards are placed face-up in a random order.  Each turn, you replace a card with a later card, where the two cards:

Share a suit or number and
Are at a distance of 1 (adjacent) or 3 (two cards in between).

The game is won when there is only 1 card remaining.  You can assume that each input is solvable.  The replaced card must always precede the replacing card.
Example
As an example, consider the following layout:
2H,2S,1S,2D  (H: Hearts, S: Spades, D: Diamonds)

There are 3 possible moves here:

Replace the 2H with the adjacent 2S, so we end up with 2S,1S,2D
Replace the 2S with the adjacent 1S, so we end up with 2H,1S,2D
Replace the 2H with the 2D (at a distance of 3), so we end up with 2D,2S,1S

Of those 3 moves, only the last one has the possibility of winning (You win by replacing 2D <- 2S, then 2S <- 1S).
Input/Output
Your job is to write an Accordion solver.  You are passed a list of cards, and you need to return a list of moves to solve the game.
You are passed a list of cards as a comma-delimited string, where each card is passed as an integer representing their numeric value, then a character representing their suit.
You must return a list of replacements as a comma-delimited string, where each replacement is in the format Card <- Card (following the card format described above).  The first card in each pair is the card being replaced.
Test cases:
5H,1C,12S,9C,9H,2C,12C,11H,10C,13S,3D,8H,1H,12H,4S,1D,7H,1S,13D,13C,7D,12D,6H,10H,4H,8S,3H,5D,2D,11C,10S,7S,4C,2H,3C,11S,13H,3S,6C,6S,4D,11D,8D,8C,6D,5C,7C,5S,9D,10D,2S,9S
5H,9C,11H,7S,7D,12D,6H,10S,3H,4D,12C,2S,3C,5C,7H,6S,1H,8S,2H,11S,4C,10D,12H,9H,2D,4H,6C,13H,11C,2C,10H,8C,1S,11D,3S,12S,7C,5D,13S,8D,4S,6D,13C,3D,8H,13D,1D,9D,9S,1C,5S,10C
7H,11C,8C,7S,10D,13H,4S,10C,4D,2C,4H,13D,3C,2H,12C,6C,9H,4C,12H,11H,9S,5H,8S,13S,8H,6D,2S,5D,11D,10S,1H,2D,5C,1C,1S,5S,3H,6S,7C,11S,9C,6H,8D,12S,1D,13C,9D,12D,3D,7D,10H,3S

While this competition is a code-golf, I am particularly interested in time-efficient solutions, and am likely to reward ingenious solutions with bounties.  That said, solutions that take astronomical amounts of time are still acceptable (I'd recommend testing with a smaller deck, such as a 16-card, 4 suit deck).

Python 3, 274 272 271 bytes
2 bytes saved thanks to @orlp.

def g(p):
 q=lambda a:[[i,a]for i in range(len(p)-a)if p[i][:-1]==p[i+a][:-1]or p[i][-1]in p[i+a]]
 for n in q(1)+q(3):
  s=sum(n);c=p[:s]+p[s+1:];c[n[0]]=p[s]
  if g(c):return p[n[0]]+' <- '+p[s]+','+g(c)
 return' 'if len(p)<2else[]
print(g(input().split(','))[:-2]or'')

This is extremely slow. However, you can try it with a memoize. This has a few extra list-tuple conversions, but is otherwise equivalent.
import functools
@functools.lru_cache(maxsize=None)
def g(p):
 q=lambda a:[[i,a]for i in range(len(p)-a)if p[i][:-1]==p[i+a][:-1]or p[i][-1]in p[i+a]]
 for n in q(1)+q(3):
  s=sum(n);c=list(p[:s]+p[s+1:]);c[n[0]]=p[s]
  if g(tuple(c)):return p[n[0]]+' <- '+p[s]+','+g(tuple(c))
 return' 'if len(p)<2else[]
print(g(tuple(input().split(',')))[:-2]or'')

Even this one is astronomically slow with certain inputs.
The code uses strings, not numbers, so it also supports notation like KH instead of 13H.
Example:
$ python accordion.py
5H,9C,11H,7S,7D,12D,6H,10S,3H,4D,12C,2S,3C,5C,7H,6S,1H,8S,2H,11S,4C,10D,12H,9H,2D,4H,6C,13H,11C,2C,10H,8C,1S,11D,3S,12S,7C,5D,13S,8D,4S,6D,13C,3D,8H,13D,1D,9D,9S,1C,5S,10C
7S <- 7D,7D <- 12D,3C <- 5C,12H <- 9H,11C <- 2C,3S <- 12S,13D <- 1D,1D <- 9D,9D <- 9S,2S <- 6S,7H <- 1H,6S <- 8S,1H <- 2H,8S <- 11S,2H <- 9H,10D <- 2D,9H <- 4H,4H <- 4C,5C <- 4C,4D <- 4C,4C <- 12C,10S <- 11S,11H <- 11S,6H <- 3H,12D <- 2D,12C <- 2C,2C <- 6C,6C <- 8C,12S <- 13S,5D <- 6D,6D <- 8D,8D <- 3D,4S <- 9S,13S <- 9S,11D <- 3D,7C <- 1C,1S <- 1C,1C <- 13C,8C <- 13C,13C <- 13H,13H <- 10H,2D <- 3D,3D <- 3H,3H <- 8H,8H <- 10H,11S <- 5S,5H <- 10H,5S <- 9S,10H <- 10C,10C <- 9C,9C <- 9S


Generate a Portmantout! Background

Three years ago, this guy Tom Murphy got it into his head to extend the idea of a portmanteau to all words in a language and called this a portmantout (portmanteau plus tout [French for all]). Defining English as a list of 108,709 words, he managed to find a sequence of 611,820 letters with the following two properties:

Every English word is contained in the string.
Some neighborhood containing any two adjacent letters in the string is an English word.

Here's a link to a page on which this portmantout can be found (along with a video explanation).

A portmantout

The first of the two properties of a portmantout is easy to understand. The second may require some explanation.

Basically, words must overlap. "golfcode" will never appear in a portmantout of English, as there is no word there that contains the "fc". However, you might find "codegolf" in a portmantout, for "ego" bridges the gap (and all other pairs of letters are in either "code" or "golf").

Your task:

Write a program or function that takes a list of strings and returns any portmantout of the list.

This Python 3 code will verify a portmantout.

Test cases

All lists are unordered; that is,

{"code", "ego", "golf"} -> "codegolf"
{"more", "elm", "maniac"} -> "morelmaniac" or "morelmorelmaniac" or "morelmorelmorelmaniac" or...
    Would a morelmaniac be some sort of mycologist?
{"ab", "bc", "cd", "de", "ef", "fg", "gh", "hi", "ij", "jk", "kl", "lm", "mn", "no", "op", "pq", "qr", "rs", "st", "tu", "uv", "vw", "wx", "xy", "yz", "za"} -> "abcdefghijklmnopqrstuvwxyza" or "rstuvwxyzabcdefghijklmnopqrstuvwxyzabcdef" or any 27+ letters in order

And why not? The massive one on Murphy's site, if your code executes within reasonable time.

Rules

Your code must halt.
You need not return the same portmantout with each execution.
You may assume all strings consist of only lowercase letters a through z.
If no portmantout is possible, your program may do anything. Ex: {"most", "short", "lists"}
Standard rules for I/O and loopholes apply.

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

Python 2, 204 202 bytes

def f(l,s=''):
 if all(w in s for w in l):return s
 for i,w in enumerate(l):
	a=next((s+w[i:]for i in range(len(w)-1,0,-1)if s[-i:]==w[:i]),0)if s else w;x=a and f(l[:i]+l[i+1:]+[l[i]],a)
	if x:return x

Try it online!

Saved

-2 bytes, thanks to recursive


Help! My calculator malfunctions! Introduction

My calculator is behaving weird. Sometimes when I type in an 8 it displays a 2. And sometimes when I type in a 6 it displays a +. Some buttons are mixed up!
Could anyone help me determine which?

Challenge:

Input: List of incorrect equations, with correct results.

Output: The two buttons that are swapped.

For example:
An input could be:

123    = 3
8423   = 252
4+4    = 8
4*7-10 = 417
9/3    = 3
42-9   = -36

For which the expected outputs are: 2 and *.

Why? Because ALL the equations would be correct if we swap the 2's and *'s:

1*3    = 3
84*3   = 252
4+4    = 8
427-10 = 417
9/3    = 3
4*-9   = -36

Challenge rules:

Input can be in any reasonable format. Can be a single string with space delimited; a string-list or -array; a list with equations and another list with the correct results. Your call. Please state which input format you've used!
NOTE: This also means you are allowed to input the test case -5--15 as -5- -15 or -5 - -15. However, a number resulting in -- should either be inputted without spaces or with a space between every digit. So test case 9119 can be inputted like 9119 or 9 1 1 9 (reason 91 19 isn't allowed is because you can then be guided by the space for finding - -). So spaces are (somewhat) optional and allowed.
Output format can be in any reasonable format as well. Can be two characters; a single two-character string; a string-list containing the two characters. Your call. Again, please state which output format you've used!
You are allowed to use any distinct 14 outputs that map to 0123456789+-*/. So you are even allowed to output two distinct integers if you want to (again, please specify the mapping you've used, if any).
You only have to support integers. So there won't be any test cases like 1/8=0.125 or 1/8=0.
Arithmetic operands you'll have to support: addition (+); subtraction (-); multiplication (* or × or ·); division (/ or ÷). (NOTE: Characters between parenthesis are only added as clarification.)
You'll have to support negative numbers. This means - can be interpreted in the equation as both a mathematical operand or a negative indicator.
You can assume the given incorrect equations and supposed correct equations are always valid (so there won't be things like 4-/2 or 9+-+8 for example).
The incorrect input-equations can contain a division by 0, but the corrected and expected equations will never contain division by 0.
The incorrect input-equations can already be correct even if you swap the intended buttons back.
A given input equation can be irrelevant for the buttons  to swap (like the 4+4=8 and 9/3=3 equations, with the swapped buttons 2 and *).
You can assume there will always be only one possible swap that can be made with the given test cases.
Both buttons to swap will always be present in at least one of the incorrect equations.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, please add an explanation if necessary.

Test cases:

Input:
123    = 3
8423   = 252
4+4    = 8
4*7-10 = 417
9/3    = 3
42-9   = -36

Output: 2 *

Input:
4/2   = 6
3/0   = 3
0/8+2 = 4
95-5  = 90
4+2   = 2

Output: + /

Input:
7+4    = 11
5-15   = 46
212-23 = -2121

Output: 1 -

Input:
4+8/2-9*1 = -5
99/3-13   = 20
1+2+3+4   = 10
4-3-2-1   = -6

Output: 2 4

Input:
18/18  = 1
98-8   = 90
55*88  = 4840
-5--15 = 10

Ouput: 5 8

Input:
9119    = 18
5-3     = 513
8*-9    = 152
13116/3 = -1

Output: 1 -

JavaScript (ES7), 159 158 bytes

Edit: new version to comply with the updated rules regarding --
Saved 1 byte thanks to @Shaggy

Takes input in currying syntax (e)(r) where e is the array of equations and r is the array of expected results. Returns an array of characters.

e=>r=>(l=[...2**29+'4+-*/']).filter(x=>l.some(y=>eval("try{eval((S=(s=`[${e}]`).replace(/./g,c=>c==x?y:c==y?x:c)).split`--`.join`+`)+''==r&S!=s}catch(e){}")))

Test cases

let f =

e=>r=>(l=[...2**29+'4+-*/']).filter(x=>l.some(y=>eval("try{eval((S=(s=`[${e}]`).replace(/./g,c=>c==x?y:c==y?x:c)).split`--`.join`+`)+''==r&S!=s}catch(e){}")))

console.log(JSON.stringify(f
  ([ '123', '8423', '4+4', '4*7-10', '9/3', '42-9' ])
  ([ 3, 252, 8, 417, 3, -36 ])
));

console.log(JSON.stringify(f
  ([ '4/2', '3/0', '0/8+2', '95-5', '4+2' ])
  ([ 6, 3, 4, 90, 2 ])
));

console.log(JSON.stringify(f
  ([ '7+4', '5-15', '212-23' ])
  ([ 11, 46, -2121 ])
));

console.log(JSON.stringify(f
  ([ '4+8/2-9*1', '99/3-13', '1+2+3+4', '4-3-2-1' ])
  ([ -5, 20, 10, -6 ])
));

console.log(JSON.stringify(f
  ([ '18/18', '98-8', '55*88', '-5--15' ])
  ([ 1, 90, 4840, 10 ])
));

console.log(JSON.stringify(f
  ([ '9119', '5-3', '8*-9', '13116/3' ])
  ([ 18, 513, 152, -1 ])
));

Formatted and commented

e => r =>                                  // given e and r
  (l = [...2 ** 29 + '4+-*/'])             // generate l = [...'5368709124+-*/']
  .filter(x =>                             // for each character x of l
    l.some(y =>                            // for each character y of l
      eval("try {                          // we need to 'try', because we don't know
        eval(                              // whether the following expression is valid
          (S = (s = `[${e}]`).             // s = list of equations coerced to a string
            replace(/./g, c =>             // S =
              c == x ? y : c == y ? x : c  //   s with x and y exchanged
            )                              // end of replace()
          ).split`--`.join`+`              // replace '--' with '+'
        ) + '' == r                        // does the resulting list match r?
        & S != s                           // and was at least one character modified?
      } catch(e){}")                       // if we try, we oughta catch
    )                                      // end of some()
  )                                        // end of filter()


Next number with k fives Challenge:

Your program will take two integers n and k as input, and output the smallest integer greater than (but not equal to) n that contains at least k occurrences of the digit 5.

You can assume 1 ≤ k ≤ 15 and 1 ≤ n < 10**15.

This is a restricted-time challenge. Your program must run on TIO for all of the test cases and complete within 10 seconds in total.

General rules:

This is code-golf, so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for any programming language.
Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call. The function parameters may be taken in either order, but please specify in your answer.
Default Loopholes are forbidden.
You must add a link with a test for your code (i.e. TIO).
The answer header should list the score in bytes but also the total time taken for all test cases on TIO
If your language is not on TIO, the code should finish far under 10 seconds on your machine so that you're confident it's fast enough on any reasonable computer.
Adding an explanation for your answer is highly recommended.

Test Cases:

(n, k) ->  output
(53, 2) -> 55
(55, 1) -> 56
(65, 1) -> 75
(99, 1) -> 105
(555, 3) -> 1555
(557, 1) -> 558
(5559, 3) -> 5565
(6339757858743, 5) -> 6339757859555
(99999999999999, 15) -> 555555555555555

Program Example:

This program is correct.

R, 85 84 76 74 bytes, 0.250s on TIO

f=function(n,k,m=nchar(gsub("[^5]","",n+1))-k)`if`(m<0,f(n+.1^m/50,k),n+1)

Try it online!
-1 byte thanks to Robert S.
-8 bytes thanks to Giuseppe.
The nchar(gsub(...)) part counts the number of 5s.
A simple recursive solution would be to increment by 1 until the answer is found, but this would not meet the time restriction. To meet the time restriction, this function makes use of the fact that if there are p missing 5s, we can increment by 2*10^(p-2) (represented as the golfier .1^m/50, with m=-p).
Note that when p=1, the increment becomes 0.2. This is OK, since after 5 steps we come back to an integer, and none of the decimal numbers encountered in the mean time have an extra 5. If instead we were to increment by 5*10^(p-2) or by 1*10^(p-2), then we would find f(24, 1)=24.5 instead of 25 for example.


Cops and Robbers: Redacted Primality (Robbers' Thread) This is the robbers' thread. The cops' thread is here.

Your challenge is to take an uncracked submission from the cops' thread and try to find the original unredacted program. Please comment on the cop's submission when you've cracked their code.


Portal Maze Shortest Path Your goal is to write a program that creates a random 10x10 map using 0, 1, and 2, and finds the shortest path from top-left to bottom-right, assuming that:

0 represents a grass field: anyone can walk on it;
1 represents a wall: you cannot cross it;
2 represents a portal: when entering a portal, you can move to any other portal in the map.

Specs:

The top-left element and the bottom-right one must be 0;
When creating the random map, every field should have 60% chance of being a 0, 30% of being a 1 and 10% of being a 2;
You can move in any adjacent field (even diagonal ones);
Your program should output the map and the number of steps of the shortest path;
If there isn't a valid path that leads to the bottom-right field, your program should output the map only;
You can use any resource you'd like to;
Shortest code wins.

Calculating steps:
A step is an actual movement; every time you change field, you increment the counter.

Output:

0000100200
0100100010
1000000111
0002001000
1111100020
0001111111
0001001000
0020001111
1100110000
0000020100

9

Mathematica (344)
Bonus: highlighting of the path
n = 10;
m = RandomChoice[{6, 3, 1} -> {0, 1, 2}, {n, n}];
m[[1, 1]] = m[[n, n]] = 0;

p = FindShortestPath[Graph@DeleteDuplicates@Join[Cases[#, Rule[{ij__}, {k_, l_}] /;
      0 < k <= n && 0 < l <= n && m[[ij]] != 1 && m[[k, l]] != 1] &@
   Flatten@Table[{i, j} -> {i, j} + d, {i, n}, {j, n}, {d, Tuples[{-1, 0, 1}, 2]}],
  Rule @@@ Tuples[Position[m, 2], 2]], {1, 1}, {n, n}];

Grid@MapAt[Style[#, Red] &, m, p]
If[# > 0, #-1] &@Length[p]

I create the graph of all possible movies to neighbor vertices and add all possible "teleports".


Code-Challenge: Farey sequence (II) Challenge

  In this task you would be given an integer N
  (less than 10^6), output the number of terms in the Farey
  sequence of order N.

The input N < 106 is given in a single line, the inputs are terminated by EOF.

The challenge is to implement the fastest solution so that it can process a maximum of 106-1 values as fast as possible.

Input

7
10
999
9999
79000
123000

Output

19
33
303793
30393487
1897046599
4598679951

Constraints

You can use any language of your choice
Take care about your fingers, do not use more than 4096 bytes of code.
Fastest solution, based on the running time measured for N = 106-1.

C - 0.1 Secs on Ideone

http://www.ideone.com/E3S2t

Explanation included in code.

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

long long A[1000001]={0};
int main()
{
    int isprime[1001],d,n,k,i,e,p;

    for (n=2;n<1001;n++)
        isprime[n]=1;

    //Sieve of Eratosthenes for Prime
    //Storing the smallest prime which divides n.
    //If A[n]=0 it means it is prime number.
    for(d=2;d<1001;d++)
    {
        if(isprime[d])
        {
            for (n=d*d;n<1001;n+=d)
            {
                isprime[n]=0;
                A[n]=d;
            }
            for (;n<=1000000;n+=d)
                A[n]=d;
        }
    }

    //Uses multiplicative property of
    //Euler Totient Function
    //Phi(n)=Phi(p1^k1)*Phi(p2^k2)...*Phi(pr^kr)
    //and Phi(pi^ki)=(pi-1)*(pi^(ki-1))
    A[1]=1;
    for(n=2;n<=1000000;n++)
    {
        if (A[n]==0)
           A[n]=n-1;
        else
        {
           p=A[n],k=n/p,e=1;
           while (k%p==0)
                 k/=p,e*=p;
           A[n]=A[k]*e*(p-1);
        }
    }
    //Number of terms in Farey Series
    //|F(n)| = 1 + Sigma(i,1,n,phi(i))
    A[1]=2;
    for(n=2;n<=1000000;n++)
        A[n]+=A[n-1];

    while (~scanf("%d",&i))
        printf("%lld\n",A[i]);
    return 0;
}

A little more explanation:

  For all numbers we get a prime factor
  of it from the sieve(or 0 if it is a
  prime). Next we use the fact that ETF
  is multiplicative. That is if m and n
  are coprime then
  phi(m*n)=phi(m)*phi(n). Here we take
  out the multiple of prime factor out
  and hence the left part and the
  multiple part are co-prime. We already
  have the ETF for the left part since
  it is either smaller then current
  value or equal to 1. We only need to
  calculate the ETF for the multiple
  which we calculate using the formula
  phi(pi^ki)=(pi-1)*(pi^(ki-1)).