"Factorise" a quadratic When learning to factorise quadratics in the form \$x^2 + ax + b\$, a common technique is to find two numbers, \$p, q\$ such that
$$pq = b \\
p + q = a$$
as, for such numbers, \$x^2 + ax + b = (x + p)(x + q)\$
You are to take two integers \$a, b \in (-\infty, +\infty)\$ and output the two integers \$p, q\$ such that
$$pq = b \\
p + q = a$$
You may take input in any convenient method and you may assume that a solution always exists.
This is code-golf so the shortest code in bytes wins
Test cases
2, -15 -> 5, -3
-22, 85 -> -5, -17
6, -16 -> -2, 8
-8, -240 -> -20, 12
-1, -272 -> 16, -17
17, 16 -> 1, 16
-4, 0 -> 0, -4
3, -54 -> 9, -6
13, 40 -> 8, 5
-29, 198 -> -11, -18
11, -12 -> -1, 12
4, -320 -> 20, -16
4, 4 -> 2, 2

Scala 3, 49 44 bytes
a=>b=>(-b*b to b*b)map(p=>a-p->p)find(_*_==b)

Try it onlne!
Takes (a)(b) and returns an Option[(Int, Int)]. It's now a little more inefficient since it goes from \$-b^2\$ to \$b^2\$ instead of \$-|b|\$ to \$|b|\$, including values that \$p\$ and \$q\$ could never be, but it saves 4 bytes.
a => b =>
  (-b*b to b*b)              //Make a range of all possible q's and then some
    map(q => (a - q, q))     //Make a tuple of (p, q)
    find(_ * _ == b)         //Find a pair such that p * q = b


Convert between SI prefixes Introduction
The International System of Units is a system of measuring all around the world, except for a few countries including the US. The SI system (or metric system) is based on powers of ten, listed below (note that this is an incomplete table):
femto(f) pico(p) nano(n) micro(μ) milli(m) centi(c) (base unit) hecto(h) kilo(k) mega(M) giga(G) tera(T) peta(P)
10^-15   10^-12  10^-9   10^-6    10^-3    10^-2    10^0        10^2     10^3    10^6    10^9    10^12   10^15

Your job will to be to take in one of these measures and convert it into another.
Input
Input will be a decimal number 10^-16 < x < 2^31 - 1, an SI prefix, a letter representing a quantity, another SI prefix to convert to, and the same quantity letter. Input will be in the format 1234.56 mC to TC, and will always match with the regex ^\d+(\.\d+)? [fpnμmchkMGTP](?'letter'[a-zA-Z]) to [fpnμmchkMGTP](?P=letter)$. You will never have to convert to/from the base unit (10^0)
Output
Output will be the same number as the input, just converted to a new SI prefix. Specifically, the program should convert the number from SI prefix 1 to SI prefix 2 in the input. Examples:
Input: 1 nm to μm
Output: 0.001

Input: 82 kC to cC
Output: 8200000

Input: 6.54 MK to hK
Output: 65400

Input: 2000 MB to GB
Output: 2

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

JavaScript (ES7), 113 109 bytes

s=>(p=s.split` `)[m={f:-9,p:-6,n:-3,µ:0,m:3,c:4,h:8,k:9,M:12,G:15,T:18,P:21},0]/(10**(m[p[3][0]]-m[p[1][0]]))

Edit: Apparently we can use µ(U+00B5 MICRO SIGN) for the micro sign now, so replacing with that saves a byte.

For ES6 compatibility (10**(m[p[3][0]]-m[p[1][0]])) can be replaced with Math.pow(10,m[p[3][0]]-m[p[1][0]]) for 114 bytes.

Explanation

s=>                                  // s = input string
  (p=s.split` `)                     // p = input parts

    // m = dictionary of SI prefix digit powers of 10
    //     the exact values don't matter as long as they are relative to each other
    [m={f:-9,p:-6,n:-3,µ:0,m:3,c:4,h:8,k:9,M:12,G:15,T:18,P:21},

    0]                               // get the number
      /(10**(m[p[3][0]]-m[p[1][0]])) // get the factor to divide by from the difference
                                     //     between the SI prefix powers of 10

Test

This test uses Math.pow instead of ** so that common browsers can test it.

<input type="text" id="input" value="2000 MB to GB" /><button onclick="result.innerHTML=(

  s=>(p=s.split` `)[m={f:-9,p:-6,n:-3,µ:0,m:3,c:4,h:8,k:9,M:12,G:15,T:18,P:21},0]/Math.pow(10,m[p[3][0]]-m[p[1][0]])

)(input.value)">Go</button>


Who said that? 2016 Presidential election In this challenge, your task is to make write a program with less than 300 characters that takes a short paragraph or a few sentences that a candidate has said and output who said it.

Input: Can be taken as a parameter to a function, input to a program etc. It will be a short paragraph, properly punctuated.

Output: The candidate that you think it is. This could be one of

Ben Carson (1)
Ted Cruz (2)
John Kasich (3)
Marco Rubio (4)
Donald Trump (5)
Hillary Clinton (6)
Bernie Sanders (7)

I've left off the names of people who have dropped out as of March 1st. You may output the name itself, or, more conveniently, the number that corresponds to the name.

Scoring:
Your score is the percentage of test cases you get right. Highest score wins. Ties (or perfect scores) are broken by code length as in a code golf.

The test cases can be pulled from:

http://www.presidency.ucsb.edu/debates.php

Click on each debate, both Democrat and Republican that has happened so far (before March 1st). Every paragraph is a test case, unless the "paragraph" is less than 20 characters long.

Here is code that pulls out the test cases from a particular page:

var t = $(".tools").parentNode.querySelectorAll("p");
var categ = {}, cur = 0;
for (var i = 0; i < t.length; ++i) {
  var p = t[i], str = p.innerText;
  if (p.querySelector("b")) {
    cur = p.querySelector("b").innerText.replace(':', '');
    str = str.replace(/^.*?:\s/, '');
  }
  str = str.replace(/\[applause\]/g, '')
  if (str.length < 20) continue;
  if (categ[cur] == null) categ[cur] = [];
  categ[cur].push(str);
}

You can then do categ.SANDERS to get a list of all the paragraphs that Senator Sanders has said.

You can discard anything that isn't said by the candidates listed above (e.g. categ.BUSH or categ.CHRISTIE).

Here is the file with all the test cases: https://drive.google.com/file/d/0BxMn8--P71I-bDZBS2VZMDdmQ28/view?usp=sharing

The file is organized by candidate

CANDIDATE CANDIDATE_LAST_NAME
(empty line)
Series of statements. Each paragraph is separated by (NEW PARAGRAPH)-
(empty line)
CANDIDATE NEXT_CANDIDATE_LAST_NAME
(empty line)
etc.

An example partial submission would be:

if (/ win | wall | great | beautiful/.test(p)) return 5;
if (/ percent | top one | rigged /.test(p)) return 7;
// etc. for all candidates

or

var words = p.split(' ');
// majority of words have less than 5 characters
if (words.length - words.filter(a => a.length < 5).length < 4) evidence[5]++;
// at the end
return /* index with the most evidence */

Here is a place where you can test javascript solutions: https://jsfiddle.net/prankol57/abfuhxrh/

The code uses the parameter p to represent the phrase to classify. Example code that scores around 20% (guessing would get around 11%):

if (/ rigged | top | percent | Wall Street /.test(p)) return 'Sanders';
return 'Trump';

Exactly what I'm asking: Write a program/function in less than 300 characters that takes as input a phrase that a candidate has said and returns as output which candidate said it. Your score is the percentage of test cases you get right. Highest score wins.

Yes, I know that a lot of lines have [laughter] or [cheering] in them. These will not be removed. At worst, they are extra information you can ignore; at best, they are extra information you can use (e.g. I made this up, but maybe people laughter is evidence that Marco Rubio is speaking). The test cases are as they appear in the text file.

Polyglot, ~18.6%

This works in: Cjam, Pyth, TeaScript, Japt, Seriously, 05AB1E, GolfScript, Jelly, and probably many more.

6

This outputs Hillary for all inputs. This is because Hillary said the most. While it's not the most
ingenious way to do this. It works ¯\_(ツ)_/¯


Does the sum of 2 numbers in the list equal the desired sum? The Task

This is my first challenge so apologies if it is very simple!  In this challenge, your task is to write a program or function which takes in a list of integers and a desired sum and outputs a truthy or falsey value based on whether the list contains two numbers that can be summed together to achieve the desired sum.

Input

The input must be acquired in a standard way for your language.  The list of integers can be any standard collection type for your language but cannot be a hashed set, sorted set, or any highly functional collection type.  Don't assume the input is sorted, any valid integer type is acceptable.

The desired sum is also an integer and must be provided to your program as input.

Output

The output may be a function return, console log, writing to a file, etc...  Any valid Truthy or Falsey value is acceptable.

Additional Rules

The input list may or may not be sorted.
Duplicate values may occur in the list
The same item in the list may not be summed to itself to achieve the desired sum (Eg. [3,4,5] with desired sum 6 will expect False because 3 cannot be used twice)
Standard loopholes are not allowed.

Test Cases

INPUT                 OUTPUT
[3,4,5], 6            Falsey
[1,2,3,4,5,6],11      Truthy
[4,23,8174,42,-1],41  Truthy
[1,1,1,1,1,3],3       Falsey
[2,1,1,1,53,2],4      Truthy
[2,2,2,2],4           Truthy
[3],3                 Falsey
[],-43                Falsey

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

Brachylog, 3 bytes

⊇Ċ+

Try it online!

⊇Ċ+   input as STDIN, output as ARG1
      (prove that:)
⊇     the input is a superset of
 Ċ       a list of two elements
  +         which sums up to the output


Answer-Chaining - Positive divisors of a number This answer-chaining challenge is officially over, resulting in the win of Wheat Wizard, with a total of 7 answers. Any other answer is welcome, but it won't influence the accepted answer for this challenge, nor the winner.

Task:

Print all the positive divisors of a number x taken as input.

Input:

A single number x which is the number (in base 10) whose positive divisors should be computed.

Output:

All the positive divisors of x. Any format is allowed, including \n,,,; and whitespace as separators, as long as it's understandable. The output can be an array of Integers or Strings, too (e.g: [1, 2, 3, 5, 30]). You may output the divisors to stdout, console or the equivalent in your language or they can be returned from a function.

Rules

A user may not answer twice in a row
Your answer may remove, add or replace at most 15 characters from the previous answer (whitespace does not count), besides for Answer 2 which can "transform" up to 20 characters to get things started
You are not allowed to post an answer in a programming language that already has an answer, the exception being a completely different version of that language (e.g: If I post an answer in Python 2.7, you can submit one in Python 3, but not in Python 2.6)
Standard loopholes are not allowed
You are not allowed to use built-ins for getting divisors, for the sake of this challenge
You must include the answer's number and the language name in the question's title and the number of characters changed from the previous answer

Scoring

The user with the most submissions once the things settle out wins. In case of a tie, the user with the highest score on one of their answer wins. If there is a tie at the score as well, then the user with the oldest submission(oldest highest-scored answer) will be declared the winner.

Note: "settle out" <=> 7 3 days have passed since the last answer was submitted

Examples:

Input, Output:

14 => [1, 2, 7, 14]
25 => [1, 5, 25]
65 => [1, 5, 13, 65]
114 => [1, 2, 3, 6, 19, 38, 57, 114]

Or any other equivalent output satisfying the mentioned conditions.

Final Note: This question is better if you sort the answers by the oldest. I'll post the first answer in Python 2.7, so you should post the second answer depending on that one. Good luck and have fun!

Leaderboard:

This list may be outdated, fell free to edit it:

  1) Wheat Wizard [Current Leader ]: 7 answers - Python 1.6,
   05AB1E, Actually, Del|m|t, WSF, Brain-Flak, Lenguage

  2) Riley: 3 answers - Seriously, CJam, 2sable

  3) Jonathan Allan: 2 answers - Python 3, Jelly

  3) ETHproductions: 2 answers - Japt, Pyth

  3) Mistah Figgins: 2 answers - Befunge-98, Brain-Flak Classic

  6) Riker: 1 answer - MATL

  6) dzaima: 1 answer - SOGL 0.8.2

  6) LegionMammal978: 1 answer - Whitespace

  6) Nick Clifford: 1 answer - Ohm

  6) Lynn: 1 answer - GolfScript

  6) MickyT: 1 answer - Cubix

Distance calculator

You can use this snippet to calculate the distance between two entries:

function L(s,t){if(s===t)return 0;var S=s.length,T=t.length;if(S*T===0)return S+T;for(var i=0,v0=[],v1=[];i<=T;i++)v0[i]=i;for(i=0;i<S;i++){v1[0]=i+1;for(var j=0;j<T;j++)v1[j+1]=Math.min(v1[j]+1,v0[j+1]+1,v0[j]+(s[i]!=t[j]));for(j=0;j<=T;j++)v0[j]=v1[j]}return v1[T]}
<textarea id=A rows=10></textarea><textarea id=B rows=10></textarea>

Distance: 0 <button onclick="O.innerHTML=L(A.value.replace(/\s/g,''),B.value.replace(/\s/g,''))">Run</button>

Answer 20, Brain-Flak, 11

I would like to just take the time to thank everyone that has helped contribute to this goal:

Riley, 20 bytes
LegionMammal, 15 bytes
ETHproductions, 11 bytes
Lynn, 1 byte

The following users were not able to contribute bytes directly but did help in other ways:

Mistah Figgins
DJMcMayhem
feersum

Thanks everyone for making this possible!

"qd:A(),(;{A\%!},pe#&f!0pv'%QTS|Q@░┼_¥f::+!vUGw
)((({})<>)){((({}[()]<n=int(input({})(<>))><>)<{i=1div=wvhile(({})){({}[()])<>}{}}{}<>([{}()]{})><>)<>{ifn%i==g00div.append(<{}<>{}<>>i)i=i+1}{}printdiv)}
#R
{}T:.eX╜R;j`;╜0%Y*`M∩\"ILD¹s%_Ï,

Try it online!


Coercing a string to an integer in GolfScript GolfScript automatically coerces values, according to the following ‘priority’ sequence:

  integer → array → string → block

(listed from lowest to highest.)

This means that "1"7+ leaves the string "17" on the stack (and not 8), because strings have a higher priority than integers.

[To those GolfScript veterans – apologies for insulting your respective intelligences.]

How would it be possible to do this the other way? That is, to coerce a string into an integer?

There's an operator ~ in golfscript, which does the following: bitwise not, dump, eval.

Therefore, "1" will give the string "1" while "1"~ will evaluate that string (into the integer 1).

Then, all you need to do is "1"~7+.

Try it online!


Returning the range of a number as a palindrome I like to do programming challenges in my free time to teach myself and keep fresh, this one I can't seem to optimize though and it's driving me insane.

The goal is essentially, "Given a number, return the numbers leading up to it as a palindrome."

For example if you are given the input 5 the answer your program should return is: 123454321

The catch? You have to solve it in as few characters as possible. The minimum needed seems to be 41 characters and I can't condense it past 76.

I have tried all sorts of solutions, here are a few:

# Note: "Palindromic_Number" is required. "def P(N):" will not work.
def Palindromic_Number(N):
    a = ''
    for x in range(1,N+1):
        a += str(x)
    return a + a[::-1][1:]

def Palindromic_Number(N):
    a = ''.join(map(str, range(1,N+1)))
    return a + a[::-1][1:]

def Palindromic_Number(N):
    a = ''.join([str(x) for x in range(1, N+1)])
    return a + a[::-1][1:]

# This one uses Python 2.7
Palindromic_Number = lambda N: ''.join(map(str, range(1,N+1) + range(1,N+1)[::-1][1:]))

Does anyone have any ideas as to how I could shorten my code? I'm just looking for a point in the right direction where to look as this point.

You could try:

def Palindromic_Number(N):
    return int('1'*N)**2

just preforms 11111 * 11111 which equals 123454321

47 chars.

Or, as a lambda:

Palindromic_Number=lambda N:int('1'*N)**2

41 chars.


Circle packing in a rectangle Your task is to write a program that finds the largest radius that N circles can have and still fit inside of a rectangle that is X by Y pixels large. (similar to this wikipedia article) Your program must find the largest possible radius and optimal position of these  N circles so that

No two circles overlap
All of the circles fit inside of the rectangle.

Your program should then print this to the console:

Highest possible radius: <some_number>
Circle 1 Focus: (x, y)
Circle 2 Focus: (x, y)
...
Circle N-1 Focus: (x, y)
Circle N Focus: (x, y)

(Obviously, you must replace some_number with the radius your program calculates, N with the number of circles you end up using, and x and y with the actual coordinates of the circle)

Lastly, it should create and save a picture with these circles drawn.

Rules:

This program must run with any size of rectangle, and any number of circles and still get a valid answer. You can use command line arguments, user input, hard coded variables, or anything else you want.
If any circle overlaps or does not fit entirely inside of the box, your submission is invalid.
Each circle must have the same radius.
Just to make this reasonable and do-able, all numbers must be precise to the 2nd decimal place.

This is code golf, so shortest program (as of 10/28/2014) wins.

JavaScript 782 725 characters

first post, be gentle!

The program is now called via the wrapped function. Eg: (function(e,f,g){...})(100,200,10).

function C(e,f,g,c,a,d){if(0>g-a||g+a>e||0>c-a||c+a>f)return d;for(var b in d)if(Math.sqrt(Math.pow(d[b].x-g,2)+Math.pow(d[b].y-c,2))<2*a)return d;d.push({x:g,y:c});for(b=0;b<Math.PI;)XX=Math.cos(b)*a*2+g,YY=Math.sin(b)*a*2+c,d=C(e,f,XX,YY,a,d),b+=.01;return d}
(function(e,f,g){var c=e+f,a,d;for(a=[];a.length<g;)a=d=c,a=C(e,f,a,d,c,[]),c-=.01;console.log("Highest possible radius: "+Math.round(100*c)/100);e='<svg width="'+e+'" height="'+f+'"><rect width="'+e+'" height="'+f+'" style="fill:red" />';for(var b in a)console.log("Circle "+b+" Focus: ("+Math.round(100*a[b].x)/100+", "+Math.round(100*a[b].y)/100+")"),e+='<circle cx="'+a[b].x+'" cy="'+a[b].y+'" r="'+c+'" fill="blue" />';console.log(e+"</svg>")})(400,300,13);

Test 1

(function(e,f,g){...})(200,200,4)

Highest possible radius: 49.96
Circle 1 Focus: (49.97, 49.97)
Circle 2 Focus: (149.91, 49.97)
Circle 3 Focus: (149.99, 149.91)
Circle 4 Focus: (50.05, 149.91)
<svg width="200" height="200"><rect width="200" height="200" style="fill:blue;" /><circle cx="49.97000000021743" cy="49.97000000021743" r="49.960000000217434" fill="white" /><circle cx="149.9100000006523" cy="49.97000000021743" r="49.960000000217434" fill="white" /><circle cx="149.98958489212322" cy="149.90996831285986" r="49.960000000217434" fill="white" /><circle cx="50.04958489168835" cy="149.90996831285986" r="49.960000000217434" fill="white" /></svg>

Obviously we would expect the radius to be exactly 50, but for reasons discussed in the question's comments, I couldn't reasonably make it happen. The SVG looks like this...

Test 2

(function(e,f,g){...})(100,400,14)

Highest possible radius: 26.55
Circle 1 Focus: (26.56, 26.56)
Circle 2 Focus: (79.68, 26.56)
Circle 3 Focus: (132.8, 26.56)
Circle 4 Focus: (185.92, 26.56)
Circle 5 Focus: (239.04, 26.56)
Circle 6 Focus: (292.16, 26.56)
Circle 7 Focus: (345.28, 26.56)
Circle 8 Focus: (372.63, 72.1)
Circle 9 Focus: (319.52, 73.25)
Circle 10 Focus: (265.47, 72.64)
Circle 11 Focus: (212.35, 73.25)
Circle 12 Focus: (159.23, 72.64)
Circle 13 Focus: (106.11, 73.25)
Circle 14 Focus: (52.99, 72.64)
<svg width="400" height="100"><rect width="400" height="100" style="fill:blue;" /><circle cx="26.560000000311106" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="79.68000000093332" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="132.80000000155553" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="185.92000000217774" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="239.04000000279996" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="292.16000000342217" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="345.2800000040444" cy="26.560000000311106" r="26.550000000311105" fill="white" /><circle cx="372.6271770491687" cy="72.09972230654316" r="26.550000000311105" fill="white" /><circle cx="319.5195599732359" cy="73.24663493712801" r="26.550000000311105" fill="white" /><circle cx="265.47097406711805" cy="72.63752174440503" r="26.550000000311105" fill="white" /><circle cx="212.35454341475625" cy="73.25330971030218" r="26.550000000311105" fill="white" /><circle cx="159.23097406587362" cy="72.63752174440503" r="26.550000000311105" fill="white" /><circle cx="106.11454341351183" cy="73.25330971030218" r="26.550000000311105" fill="white" /><circle cx="52.99097406462921" cy="72.63752174440503" r="26.550000000311105" fill="white" /></svg>

And the SVG looks like this...

Test 3

(function(e,f,g){...})(400,400,3)

Highest possible radius: 101.68
Circle 1 Focus: (101.69, 101.69)
Circle 2 Focus: (298.23, 153.98)
Circle 3 Focus: (154.13, 298.19)
<svg width="400" height="400"><rect width="400" height="400" style="fill:blue;" /><circle cx="101.69000000059772" cy="101.69000000059772" r="101.68000000059772" fill="white" /><circle cx="298.2343937547503" cy="153.97504264473156" r="101.68000000059772" fill="white" /><circle cx="154.13153961740014" cy="298.19269546075066" r="101.68000000059772" fill="white" /></svg>

And the SVG looks like this...

They aren't all pretty.

How it works

Ungolfed code below. This program has two assumptions:

One circle will always be in the corner. This seems like a pretty safe bet.
Every circle will always be touching another circle. I don't see why they wouldn't be.

The program starts by calculating a large radius based on the box dimensions. It then tries to fit one circle in the corner of the box. If that circle fits, it extends a diameter line from that circle and tries to create a circle at the end of the line. If the new circle fits, another line will be extended from the new circle. If it doesn't fit, the line will swing 360 degrees, checking for open spaces. If the box fills up before the desired number of circles are created, the radius is reduced and it all starts over again.

Ungolfed Code (snippet)

// this functions attempts to build a circle
// at the given coords. If it works, it will
// spawn additional circles.
function C(x, y, X, Y, r, cc){

 // if this circle does not fit in the rectangle, BAIL
 if(X-r < 0 || X+r > x || Y-r < 0 || Y+r > y)
  return cc;

 // if this circle is too close to another circle, BAIL
 for(var c in cc){
  if( Math.sqrt(Math.pow(cc[c].x - X, 2) + Math.pow(cc[c].y - Y, 2)) < (r*2) )
   return cc;
 }

 // checks passed so lets call this circle valid and add it to stack
 cc.push({"x": X, "y": Y});

 // now rotate to try to find additional spots for circles
 var a = 0; // radian for rotation
 while(a < Math.PI){
  XX = Math.cos(a)*r*2 + X;
  YY = Math.sin(a)*r*2 + Y;
  cc = C(x, y, XX, YY, r, cc);
  a += .01; // CHANGE FOR MORE OR LESS PRECISION
 }

 return cc;
}

// this function slowly reduces the radius
// and checks for correct solutions
// also prints svg graphic code

(function B(x, y, n){

 var r = x + y; // pick a big radius
 var X, Y; // these are the coords of the current circle. golf by combining this with `var r..`?
 var cc = []; // array of coordinates of the circles

 // while we cant fit n circles, reduce the radius and try again
 while(cc.length < n){
  X = Y = r;
  cc = C(x, y, X, Y, r, []);
  r-=.01; // CHANGE FOR MORE OR LESS PRECISION
 }

 console.log('Highest possible radius: ' + Math.round(r*100)/100);
 var s = '<svg width="' + x + '" height="' + y + '"><rect width="' + x + '" height="' + y + '" style="fill:red" />';
 for(var c in cc){
  console.log('Circle '+c+' Focus: (' + Math.round(cc[c].x*100)/100 + ', ' + Math.round(cc[c].y*100)/100 + ')');
  s += '<circle cx="' + cc[c].x + '" cy="' + cc[c].y + '" r="' + r + '" fill="blue" />';
 }
 s += '</svg>';
 console.log(s);
 document.write(s);
})(150, 150, 5);


Brainf*ck Loop Problem I have a problem for a cyber club that asks you to print:

ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9876543210/.-,+*)('&%$#"!

Using Brainf**k in 29 bytes or less without using the ',' character.

I have a working code:

++++++++++[>++++++>+++++++++<<-]>-->.<[>-.<-]

However my loop is too long, sending me 16 bytes over the limit.

Is there a more efficient way to set the second and third cell to 58 and 90 so I can run my second loop? Or is there a better way to do this all together that I am just not seeing?

27 24 bytes

++[<++[++<]>>>+]<[-<-.>]

Spent a whole day basically writing up a brute forcer and watching the results come in. Now I can get back to doing some actual work... Another day of brute forcing later...

Try it online!

The component ++[<++[++<]>>>+] initialises the tape to

[130, 0, 0, 0, 91, 59, 0]
                       ^

which is just perfect for what we need!


Score a game of Load, Defend and Shoot When I was a child, I used to play this game a lot.

Rules

There are two players (let's call them A and B), and each player uses his hands as guns. There are three possible moves:

Hands up to load ammunition to your gun.

Each gun starts empty. Loading increases the ammunition by one.
Hands pointing to the other player to shoot.

This decreases the ammunition by one. You must have at least one unit of ammo to shoot.
Crossed arms to protect yourself from a shot.

Both players move simultaneously. If both players shoot at the same time, the bullets hit each other, and the game continues. The game ends when one player shoots while the other is loading ammunition.

Shooting and empty gun is considered cheating. If a player cheats while the other one performs a legal action, the cheater loses immediately. If both players cheat at the same time, the game continues.

Cheating attempts do not decrease ammunition, so it can never be negative.

Challenge

Given the moves made by players A and B, output which player won the game: 1 for player A, -1 for player B, and 0 for a draw. You can use any other triple of return values, but you need to state in your answer which ones you use.

The game may:

end without having to process all moves;
not end with the given moves, and thus it is considered a draw.

The input can be taken:

as strings
as arrays/lists of integers
in any other way that does not pre-process the input

Full program or functions allowed. Since this is code-golf, the shortest answer in bytes wins!

Test cases

A: "123331123"
B: "131122332"
    -----^                Player B shoots player A and wins.

Output: -1

A: "111322213312"
B: "131332221133"
    -------^              Player B cheats and loses.

Output: 1

A: "1333211232221"
B: "1213211322221"
    ----------^^          Both players cheat at the same time. The game continues.

Output: 0

A: "12333213112222212"
B: "13122213312232211"
         |       || ^---- Player A shoots player B and wins.
         ^-------^^------ Both players cheat at the same time. The game continues.

Output: 1

Jelly, 33 32 24 bytes

Zæ%1.»0$+¥\>-‘żZḅ3Ff5,7Ḣ

This prints 5 instead of -1, and 7 instead of 1. Try it online! or verify all test cases.

How it works

Zæ%1.»0$+¥\>-‘żZḅ3Ff5,7Ḣ  Main link. Argument: A (digit list array)

Z                         Zip; group corresponding digits.
 æ%1.                     Map the digits in (-1.5, 1.5].
                          This replaces [1, 2, 3] with [1, -1, 0].
          \               Cumulatively reduce the pairs by doing the following.
     »0$                    Take the maximum of the left value and 0, i.e., replace
                            a -1 with a 0.
        +¥                  Add the modified left value to the right value.
                          This computes the available ammo after each action. An
                          ammo of -1 indicates a cheating attempt.
           >-             Compare the results with -1.
             ‘            Increment. And unilateral cheating attempt is now [1, 2]
                          or [2, 1], where 1 signals the cheater and 2 the winner.
              żZ          Pair each result with the corr., original digits.
                ḅ3        Convert each pair from base 3 to integer.
                          This maps [1, 2] and [2, 1] to 5 and 7.
                  F       Flatten the resulting, nested list.
                   f5,7   Discard all but 5's and 7's.
                       Ḣ  Grab the first element (5 or 7).
                          If the list is empty, this returns 0.


Alphanumerical order Task is to output this text:

ABCDEFGHIJKLMNOPQRSTUVWXYZA
A 00000000000000000000000 Z
B                         Y
C  101010101010101010101  X
D                         W
E                         V
F   2101210121012101210   U
G                         T
H                         S
I                         R
J    12321012321012321    Q
K                         P
L                         O
M     234321012343210     N
N     123432101234321     M
O                         L
P                         K
Q    23210123210123210    J
R                         I
S                         H
T                         G
U   1210121012101210121   F
V                         E
W                         D
X  010101010101010101010  C
Y                         B
Z 00000000000000000000000 A
ABCDEFGHIJKLMNOPQRSTUVWXYZA

Rules

shortest code wins, but you are encouraged to post answers even if your language is among more verbose ones
trailing newline allowed,
lowercase letters allowed


Count # of Cookie Chocolate Chips Note: this is my first post here.

The Challenge

The challenge is to count the number of chocolate chips in a cookie. A cookie in this case is a circle with dots (the chips) in it. Given any square cartoon image of this cookie, you are to write a bot that counts and outputs the number of chocolate chips.

Rules

Has to take in an image type of png.
It has to be able to take in any file size, as long as it is square.
It has to be able to handle both color and B&W images.
Output can be in any  human-understandable form.
The circle will be filled with color and will have an outline.
Chips will all be the same size and color.
There is only one cookie in the image
Chocolate chips may be irregularly spaced, but are perfect circles.
You can use a library.
There is nothing in the image except the cookie and the chocolate chips.
-All other cookies will look like the example images.

This is code-golf; the shortest code gets accepted.

Examples

Cookie 1 => 8 or 1000 (binary)
Cookie 2 => 8 or 1000 (binary)
Cookie 3 => 10 or 1010 (binary)
Cookie 4 => 7 or 0111 (binary)

Mathematica 134 Bytes

Max@ComponentMeasurements[ArrayComponents[ImageData@ColorQuantize[RemoveAlphaChannel[#,White],4,Dithering->False],2],"Holes"][[All,2]]&

Usage (applied to .png images)

%/@cookies

Output:

{8,8,10,7}

Here's the code to bring in the cookie examples:

cookieURLs={"https://i.stack.imgur.com/UCV1A.png","https://i.stack.imgur.com/5n7AY.png","https://i.stack.imgur.com/ZbZx6.png","https://i.stack.imgur.com/M8jTo.png"};
cookies=Import/@cookieURLs;

I'm sure this can be shortened, but I think it's fairly bullet-proof as is. The original images have many more colors than the eye can see.

Here are the original cookies:

Here are the cookies after cleanup to get them into a 4 component array:

ArrayPlot[ArrayComponents[ImageData@ColorQuantize[RemoveAlphaChannel[#,White],4,Dithering->False],2]]&/@cookies//Row

After that, all is needed is to use ComponentMeasurements to count holes.
This will always report at least 1.  You could have one really big chocolate chip filling the cookie border, so the 0 or 1 case will always be ambiguous.


When will SE be down? SE will be down/read only today 2017-05-04 at 00:00 UTC until 00:20 UTC.

Your challenge is to output a truthy value if SE is down/read only and a falsy value if SE is not. You may not have any input, and you must use date builtins to determine if SE is down/read only (no actually querying the SE api!) Example output:

12:34 UTC 03 May 2017 -> false

00:00 UTC 04 May 2017 -> true

00:20 UTC 20 May 2017 -> undefined, see below

That's undefined behavior, because it's too far after the window of time.
 To be clear, you can assume your program will be run from UTC 8:00 today (5/3/17) to UTC 1:00 tomorrow (5/4/17).

00:21 UTC 04 May 2017 -> false

00:20 UTC 04 May 2017 -> true

00:10 UTC 04 May 2017 -> true

Note that any truthy or falsy values are allowed, not just true and false. You must be accurate to the nearest second, and no changing the system clock! You may assume that your program is being run on a machine on the +0 UTC time zone.

JavaScript (ES6), 26 24 23 22 21 bytes

Saved 3 bytes thanks to Shaggy and 1 byte thanks to Luke.

_=>new Date/12e5%72<1

Checks if time passed in current day is less than 1200000ms (1200s or 20min). Assumes downtime to be 20 minutes not 21, which appears to be the case in the linked post. 00:20UTC is the exclusive upper bound.


Factorials and never ending cycles! As you may know it, the factorial of a positive integer n is the product of all the positive integers which are equal or smaller to n.
For instance :
6! = 6*5*4*3*2*1 = 720
0! = 1

We will now define a special operation with an irrelevant name like sumFac:
Given a positive integer n, sumFac(n) is the sum of the factorials of the digits.
For instance :
sumFac(132) = 1! + 3! + 2! = 9
Task
Your mission, whether or not you choose to accept it, is to return the sequence (potentially infinite) of the applications of sumFac to an integer given in input.
Example : 132 -> 132, 9, 362880, 81369, 403927, ...
But that's not all! Indeed, the applications of sumFac will eventually create a cycle. You must also return this cycle!
If your language has a built in factorial you can use it.
I'm not picky about the return type, you just have to return the sequence of sumFac applications and the cycle in a format understandable by a human.
EDIT : To help you visualize better what should the output look like I copied Leaky Nun's just below:
[132, 9, 362880, 81369, 403927, 367953, 368772, 51128, 40444, 97, 367920, 368649, 404670, 5810, 40442, 75, 5160, 842, 40346, 775, 10200, 6, 720, 5043, 151, 122, 5, 120, 4, 24, 26, 722, 5044, 169, 363601, 1454]

You just need to stop the sequence when the cycle is about to start for the second time!
But this is code-golf so the shortest answer in bytes wins!

Jelly, 6 bytes

D!SµÐĿ
    ÐĿ  Repeat until the results are no longer unique. Collects all intermediate results.
D           Convert from integer to decimal (list of digits)
 !          Factorial (each digit)
  S         Sum

Try it online!

I don't see any other way to make it shorter other than to do as told.

Specs

Input: 132 (as command-line argument)
Output: [132, 9, 362880, 81369, 403927, 367953, 368772, 51128, 40444, 97, 367920, 368649, 404670, 5810, 40442, 75, 5160, 842, 40346, 775, 10200, 6, 720, 5043, 151, 122, 5, 120, 4, 24, 26, 722, 5044, 169, 363601, 1454]


Enklactify these strings Inspired by this comment chain...

I wanna enklact my way out of this challenge but I can't...
@ETHproductions to enklact (v): to implement a lookup table using a subsection consisting of unique elements.

Enklacting is a very useful way to compress a lookup table. For example, let's say you had the following list of colors:
red
green
blue
yellow
purple
orange

If you want to be able to take a color as input and return it's index in this list, there's obviously the straightforward way:
["red", "green", "blue", "yellow", "purple", "orange"].index(input())

But there's a way we could do this in way less bytes:
"rgbypo".index(input()[0])

This works because the first (or 0'th) index of each string is unique. This example is obvious, but sometimes it's a little bit harder. What if we wanted to make a lookup table for this list?
Sweet Onion Chicken Teriyaki
Oven Roasted Chicken
Turkey Breast
Italian BMT
Tuna
Black Forest Ham
Meatball Marinara

In this case, we can't do this:
"SOTITBM".index(input()[0])

because there are two different inputs that start with a 'T', namely "Tuna" and "Turkey". We must look at a different index. If you look at the 4th index of each string, you'll notice that they are all unique. So we can do this...
"enklact".index(input()[3])

In this case, the "enklaction string" is "enklact".
That leads us to today's challenge...
Given a list of strings, return any valid enklaction string. Or in other words, given a list of strings, return any new string where each letter is unique, and the string is formed by joining the i'th letter of each string.
If there is no valid enklaction string, your submission must return an empty string or a consistent falsy value instead. As usual, either functions or full programs are allowed, and the input/output formats are permissive (within reason).
Each string will only contain printable ASCII, and this challenge is case sensitive.
This is code-golf, so try to write the shortest program possible in your language of choice!
Test cases
Input:
Programming
Puzzles
Code
Golf

Output (any one of these):
"ozdl"
"gzef"

Input:
the quick
brown fox
jumped over
lazy dogs

Output:
"tbjl"
"hrua"
"eomz"
" wpy"
"qne "
"if o"
"kxvs"

Note that "u dd" and "coog" are not valid.

Input:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Output:
""

Input:
AbC
aBc
bbC

Output:
"Aab"

Input:
@#$%^_
Hello_World
How are you?

Output:
"#eo"
"$lw"
"%l "
"^oa"

Input:
a
ab
ac

Output:
""

Python 2, 68 67 61 bytes

lambda a:`{0:j for j in zip(*a)if len(set(j))==len(j)}`[6::5]

Try it online!

Improvements

From 68 bytes to 67 bytes by Jo King
From 66 to 65 bytes by Lynn

If output would not have to be a string:

Python 3, 49 bytes

lambda a:[j for j in zip(*a)if len({*j})==len(j)]

Try it online!


Write a CFG acceptor Write a program that, given a context free grammar and a string, returns whether the string is a word of the language defined by the grammar.
Input
Your program should read a context free grammar and an input string in an implementation defined way during runtime. Hardcoding the input is acceptable as long as it is trivial to change the input.
The context free grammar is a set of rules as defined by the regex [A-Z][a-zA-Z]*, that is: One capital letter denoting the nonterminal to be replaced and an arbitrary number of terminals (minuscules) and nonterminals (capitals) to replace it. The grammar may contain up to 256 rules. The initial symbol is always S. You may not assume that the grammar is unambigous. The grammar must contain at least one production rule for S.
The input string must match the regex [a-z]*. It has a length of no more than 65536 characters.
Output
Output is to be done in an implementation defined manner. Your program must output whether the input string is a word of the language defined by the grammar.
Constraints

Your program must terminate in reasonable time
You may not use any libraries that provide parsers or parser generators
You may not run any program that generates a parser
You may not use compression utilities or libraries

Scoring
This is code-golf. The submission with the smallest number of bytes wins
Example
The rules
S
SaSb

represent a grammar which defines the language anbn for n≥0. So given string aaabbb it would indicate that it accepts it, but given string aaabb it would indicate that it does not accept it.
The ruleset
S
SaSbS
ScSdS

describes the Dyck language. It describes the language of all balanced pairs of ab's. and cd's. For instance, string ababacabdb matches but cabdacb doesn't.

Python 2.7, 325 chars

R=['S','SaSb']
I='aaabbb'

L=len(I)
def P(x,y,n):
 if n<3:return[[x,y]][:n>1or x==y]
 return[[x]+w for z in range(x,y+1)for w in P(z,y,n-1)]
S={(i,i+1,c):1for i,c in enumerate(I)}
T=0
while S!=T:
 T=dict(S)
 for r in R:
  for a,x,y,b in P(0,L,4):
   if any(all(t in S for t in zip(p,p[1:],r[1:]))for p in P(x,y,len(r))):S[x,y,r[0]]=1
print(0,L,'S')in S

The rules are listed in R and the input is in I.

The code uses dynamic programming, similar to the Earley algorithm.  S contains tuples (i,j,N) if the symbol N can generate the input from indexes i to j.  We iterate through all rules and indexes looking for new entries we can put in S.

P is a helper function that calculates all possible partitions of the range [x,y] into n-1 ranges (assigning one symbol in the rule to each).  For instance, P(0,7,4) contains, among many others, [0,3,6,7].

The run time is exponential in the longest rule, but shouldn't be too bad in the number of rules and length of the input.


How many characters per character? At http://shakespeare.mit.edu/ you can find the full text of each of Shakespeare's plays on one page (e.g. Hamlet).

Write a script that takes in the url of a play from stdin, such as http://shakespeare.mit.edu/hamlet/full.html, and outputs the number of text characters each play character spoke to stdout, sorted according to who spoke the most.

The play/scene/act titles obviously do not count as dialogue, nor do the character names. Italicized text and [square bracketed text] are not actual dialogue, they should not be counted. Spaces and other punctuation within dialogue should be counted.

(The format for the plays looks very consistent though I have not looked at them all. Tell me if I've overlooked anything. Your script does not have to work for the poems.)

Example

Here is a simulated section from Much Ado About Nothing to show what I expect for output:

  More Ado About Nothing

  Scene 0.

  Messenger

  I will.

  BEATRICE

  Do.

  LEONATO

  You will never.

  BEATRICE

  No.

Expected output:

LEONATO 15
Messenger 7
BEATRICE 6

Scoring

This is code golf. The smallest program in bytes will win.

PHP (240 characters)

Divides the html into strings (using  as a delimeter), then runs a couple of regular expressions to extract name and words spoken. Saves length of words spoken into array.
Golfed:

<?@$p=preg_match_all;foreach(explode('/bl',implode(file(trim(fgets(STDIN)))))as$c)if($p('/=s.*?b>(.*?):?</',$c,$m)){$p('/=\d.*?>(.*?)</',$c,$o);foreach($m[1]as$n)@$q[$n]+=strlen(implode($o[1]));}arsort($q);foreach($q as$n=>$c)echo"$n $c\n";

Ungolfed:

<?php
$html = implode(file(trim(fgets(STDIN))));
$arr = explode('/bl',$html);
foreach($arr as $chunk){
    if(preg_match_all('/=s.*?b>(.*?):?</',$chunk,$matches)){
        $name = $matches[1];
        preg_match_all('/=\d.*?>(.*?)</',$chunk,$matches);
        foreach($name as $n)
            @$names[$n] += strlen(implode($matches[1]));
    }
}
arsort($names);
foreach($names as $name=>$count)
    echo "$name $count\n";

Note: This considers 'All' to be a separate character.

Example:

$php shakespeare.php <<< "http://shakespeare.mit.edu/hamlet/full.html"
HAMLET 60063
KING CLAUDIUS 21461
LORD POLONIUS 13877
HORATIO 10605
LAERTES 7519
OPHELIA 5916
QUEEN GERTRUDE 5554
First Clown 3701
ROSENCRANTZ 3635
Ghost 3619
MARCELLUS 2350
First Player 1980
OSRIC 1943
Player King 1849
GUILDENSTERN 1747
Player Queen 1220
BERNARDO 1153
Gentleman 978
PRINCE FORTINBRAS 971
VOLTIMAND 896
Second Clown 511
First Priest 499
Captain 400
Lord 338
REYNALDO 330
FRANCISCO 287
LUCIANUS 272
First Ambassador 230
First Sailor 187
Messenger 185
Prologue 94
All 94
Danes 75
Servant 49
CORNELIUS 45


Generate ordered combinations with repetition Given a string of different characters, and a number n, generate all the ordered combinations with repetition, of length 1 to n, using those characters.

Another way to define it is to see the given characters as "custom" digits in the base (radix) of the number of characters, then the program should generate all the "numbers" with 1 to n digits in that base, however, leading "zeros" are included too.

The combinations should be ordered by their length (1 character first, then 2, etc), but other than that they can be in any order. You can choose the most convenient ways of handling input and output. Shortest code wins.

Examples:

ab, 3 -> a,b,aa,ab,ba,bb,aaa,aab,aba,baa,abb,bab,bba,bbb
0123456789, 2 -> 0,1,2,3,4,5,6,7,8,9,00,01,...,09,10,11,...,99

Python 2, 56 bytes
n is the maximum length and s is expected to be a list of characters. It is not clear to me whether n = 0 or an empty character list are valid inputs, but this function also handles them correctly.

f=lambda s,n:n*s and s+[x+c for x in f(s,n-1)for c in s]


Arithmetic... tock... tick... tock This question brought to you by a game I like to play when stuck in long phone meetings.

Given any two times from a 24 hour clock (from 00:00 to 23:59), how many valid mathematical equations can be generated with all of the times in between using only basic arithmetic operations?

Input: two four digit strings (no colon) representing valid times in a 24 hours cycle.

Examples:

For input=0000, 1300

03:26 produces: "0+3*2=6" and "03*2=6" etc.
11:10 produces quite a few, including: "1*1=1+0" and "1=1=1^0" and  "1=11^0" etc.
12:24 produces: "1/2=2/4" and "1=(2*2)/4" etc.

Valid operations are:

addition
subtraction
multiplication
division (floating point)
exponentiation
factorial

Other allowable symbols

Parentheses
Equal signs

Shortest code wins.

Notes

The goal is to find the number of valid expressions between two times, not the number of times that contain a valid expression.
The two times given as input are included in the range of times.
You may group the digits in any way possible, so "1223" can be "12 23" or " 1 2 23" or "1 223" etc. etc.
You may use as many parentheses as needed.
You may use more than one = sign. For instance, the time 11:11 has the valid expression 1=1=1=1.
If the first time occurs chronologically after the second time, the range of times should wrap as if crossing into the next day.
The numbers must remain in their original order- you may not re-order the digits.
When clustering numbers, zero's may absolutely be the front most digit, in which case, they are ignored ("0303" clustered as "03 03" is just two digits with the value of 3.)
You MAY NOT use the minus sign as unary negation. Therefore, "12:01" does NOT produce "1-2=-(01)", but DOES produce "1-2=0-1".
You MAY NOT add decimal points to digits. Therefore, "12:05" does NOT produce "1/2=0.5".
No chaining of factorials- a digit may be followed by at most one "!", no more, otherwise, many times would have infinite solutions. Ex: "5!" is valid but "5!!" is not valid.

Python3, 363 chars

Since no answer is given till today, I hand in what I got. Sadly, the try/except block is too fat, I didn't found a way to save chars there. It is really tricky with the nested loops there, not all can be done with list comprehensions I think, but maybe someone can tell me how.

However, I restricted the challenge myself to only use basic math '+-*/' and no parentheses.

a,b = input().split()
r=0
for time in [c for c in range(int(a),int(b)) if c/10%10<6]:
 t,*ts='%04d'%time
 e=[t]
 for d in ts:
  e=[(n+o+d,n+d)[o==' '] for o in ' -+*/=' for n in e]
 for h in [g for g in [e.split('=') for e in e if '='in e] if len(g)>1]:
  for k in h:
   try:
    if eval(h[0]) != eval(k):
     break
   except:
    break
  else:
   r+=1
print(r)

My full code (hope something explanatory) on this CodeGolf can be found on my pastebin.


Write ASCII-Art Obfuscated Code, read as, and resulting in: "DFTBA" The challenge is to write the most elaborate code, embedded in ASCII art that reads and prints "DFTBA".  For example, the following reads DFTBA:

oooooooooo.   oooooooooooo ooooooooooooo oooooooooo.        .o.
`888'   `Y8b  `888'     `8 8'   888   `8 `888'   `Y8b      .888.
 888      888  888              888       888     888     .8"888.
 888      888  888oooo8         888       888oooo888'    .8' `888.
 888      888  888    "         888       888    `88b   .88ooo8888.
 888     d88'  888              888       888    .88P  .8'     `888.
o888bood8P'   o888o            o888o     o888bood8P'  o88o     o8888o

And the following, in bash prints DFTBA

echo "DFTBA"

The challenge is to write one that does both.

Winning conditions

Valid answers, (all conditions at my discretion)

Can be clearly read as DFTBA
Print DFTBA when executed
Must be functional with no Internet connection
have letters of equal height
must not have more than 80 columns
must not have more than 10 rows

Points (highest sum wins)

Rows * Columns / 32
Readability: 25 for legible, 50 for very clear
1 point for each different non-whitespace character used

Restrictions

These may be used for something, so all responses are assumed to be released into the public domain.  If you can't, or choose not to release your answer into the public domain: post a comment/response to the original question saying "The answer authored and/or shared by me, may not be considered to be in the public domain".

Non-public domain answers are welcome too!  Just make sure to specify :-)

What is DFTBA?

It sometimes stands for "Don't Forget To Be Awesome", but not always... Long story...  This related song might help explain (or confuse).

Piet, Score Uncertain (153ish)

I understand that this doesn't strictly fit within the specifications (requiring ASCII art), however the source code does provide a very readable DFTBA. The trace is below.

Piet ignores every colour that doesn't mean anything. As a result, I used gray as the generic "comment colour" to outline and the like. The gray doesn't get interpreted (as you'll see in the trace). I wanted to make it clear which pixels were in the program and which were not.

I've used 15 colours, which is 13 without whitespce. It is 89x32 pixels, though could be compressed more. I used 4 op-codes (subtract, divide, push and outputc). Maybe if using scoring how I would think, 153?

Probably doesn't warrant a score, but was an interesting exercise. Having never used Piet before, I've never done so much trial-and-error programming! I needed npiet extensively, and its trace. I still can't figure out how the movement of the cursor works with any stability!

How it works:

D, F, T are constants for their respective ASCII letters that are then pushed to the stack, and the OUTC command called
B is the ASCII for B x 2 (needed to be to look good), which is pushed to the stack, then divided by two, then duplicated on the stack and the OUTC command called
Note the earlier duplication. That was because I couldn't make A look good in so few characters. I push 1 to the stack, subtract (making the ASCII code for A) and then the whole A character is the opcode for OUTC - doesn't matter the size, because it's an operation not a constant


Tips for golfing in 2D languages What general tips do you have for golfing in 2 dimensional programming languages? I'm looking for tips which can be applied to code-golf problems and are  specific to 2D programming languages, but not specific to any one language (Responses like "remove comments" and "use the M operation" are not answers).

Please post one tip per answer.

Avoid horizontal gaps
Often, code will leave largs gaps of whitespace to the left hand side of the program, like so.
abc
  d
  e

This adds 4 bytes, when this could be avoided by left aligning.
cde
b
a

If you need to use large gaps of whitespace, try to make them vertical, instead of horizontal.
########
#      #
#      #
#      #

vs
####
#
#
#
#
#
#
####


Manipulate destiny, fake random numbers: Be Dirty Harry bool doYouFeelLuckyPunk, actuallyIsLucky;
doYouFeelLuckyPunk = Harry.catchyPhrase();
actuallyIsLucky = Bandit.rollDice();
if(doYouFeelLuckyPunk) {
    Bandit.grabGun();
    if(!actuallyIsLucky)
        Harry.useMagnum()
    else {
        Harry.tisButAScratch()
    }
else
    Bandit.surrender();

We all know how this plays out and we like it that way.
The task:
Write functions

bool Harry.catchyPhrase()
bool Bandit.rollDice()

Design them so the situation ends either in Harry.uswMagnum() or Bandit.surrender(), at random.
Challenge and key criterion: Obfuscate the fact that bandit cannot win, fake and manipulate the "randomness" in your functions. The less obvious the better of course.
Explain your manipulation in a non-spoilering way (white text etc.)
Language: Doesn't matter
Forbidden moves: none

How about this? Solution at the very bottom, encoded in base64. Language is C.

#include <stdio.h>
int lfsr = 0xACE1u;
/*Toy LFSR implementation stolen from wikipedia.*/
int random_bit(){
    /* taps: 16 14 13 11; feedback polynomial: x^16 + x^14 + x^13 + x^11 + 1 */
    int bit  = ((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 5) )&1 ;
    lfsr =  (lfsr >> 1) | (bit << 15);
    return ((lfsr >> 14)&(lfsr >> 15))^bit;
}
int surrendered=0,scratched=0,shot =0;

void harry_tis_but_a_scratch(){scratched++;}
int harry_catchy_phrase(){return random_bit();}
void bandit_surrender(){surrendered++;}
void harry_use_magnum(){shot++;}
int bandit_roll_dice() {return random_bit();}
void bandit_grab_gun() {}

int main()
{
    int random_number=0;
    /*Test bench random bit*/
    for(int y=1;y<51;++y){
        for(int x=0;x<8*sizeof(int);++x)random_number= (random_number<<1)|random_bit();
        printf("%-15d%c",random_number,y%5?' ':'\n');
    }
    printf("\nLooks pretty random\n\n");
    /*Play the game*/
    for(int x=0;100000 >=++ x;){
        int doYouFeelLuckyPunk = harry_catchy_phrase();
        int actuallyIsLucky = bandit_roll_dice();
        if(doYouFeelLuckyPunk) {
            bandit_grab_gun();
            if(!actuallyIsLucky) harry_use_magnum();
            else harry_tis_but_a_scratch();
        }else bandit_surrender();
    }
    printf("Shot: %d Surrendered: %d  Scratched: %d\n",shot,surrendered,scratched);
    return 0;
}
/*
                               Example Output
   1414529544,  -2071427967,     89395234,    690094340,    704663586,
     41977888,  -1572861663,   1107591810,    143171844,    546578948,
  -1542942712,  -1600056768,  -1571682240,     84415044,  -2138746864,
    705971264,    302123561,    168036485,    553717833,    545294674,
     71909648,  -1994096044,   1426227848,   1218611781,    138707496,
     16810505,    553783616,  -1861155808,  -1803283192,   1111626024,

Looks pretty random

Shot: 24941 Surrendered: 75059  Scratched: 0

                                  SOLUTION

IFRoZSB3YXkgdGhpcyB3b3JrcyBpcyBxdWl0ZSBzaW1wbGUsIHRoZSBMRlNSIGlzIHJlYWwgYW5k
IGRvZXMgaW4gZmFjdCBnZW5lcmF0ZQ0KIGdvb2QgcHNldWRvLXJhbmRvbSBudW1iZXJzLkFuZCBp
dCBpcyBpbmZhY3QgYW4gZXhhY3QgaW1wbGVtZW50YXRpb24gb2YgdGhlIG9uZQ0KIGZyb20gd2lr
aXBlZGlhLCBleGNlcHQgZm9yIG9uZSBhZGRpdGlvbjoNCiANCiBUaGUgb3V0cHV0IGJpdCBpcyB4
b3InZCB3aXRoICgobGZzcj4+MTQpJihsZnNyPj4xNSkpDQogDQogTm9ybWFsbHkgdGhpcyBzaG91
bGRuJ3QgYmUgYSBwcm9ibGVtLCBhcyB0aGUgcmVzdWx0IG9mIGEgcmFuZG9tIGJpdCB4b3InZCB3
aXRoDQogYW55IGZ1bmN0aW9uIGJlc2lkZXMgaXRzZWxmIGlzIHNlbGYgaXMgc3RpbGwgYSByYW5k
b20gYml0Lg0KIA0KIEhvd2V2ZXIsICgobGZzcj4+MTQpJihsZnNyPj4xNSkpIGlzIG5vdCBhIG5v
cm1hbCBmdW5jdGlvbi4gRHVlIHRvIHRoZSBMRlNSIGFsc28NCiBiZWluZyBhIHNoaWZ0IHJlZ2lz
dGVyIHRoZSBvdXRwdXQgb2YgdGhlIHJhbmRvbSBiaXQgZnVuY3Rpb24gaXMgYWN0dWFsbHkgdGhp
czoNCiANCiByZXR1cm4gKGxhc3RfYml0JmJpdCleYml0Ow0KIA0KIFNvLCBpZiB0aGUgbGFzdCBi
aXQgd2FzIGEgMSB0aGUgYml0IHJldHVybmVkIGlzIGd1YXJhbnRlZWQgdG8gYmUgMC4NCiANCiBT
byBpdCBpcyBpbXBvc3NpYmxlIHRvIGdldCB0byB0aGUgJ3RpcyBidXQgYSBzY3JhdGNoJyBmdW5j
dGlvbiwgYXMNCiBpdCBpcyBpbXBvc3NpYmxlIGZvciBib3RoIGRvWW91RmVlbEx1Y2t5UHVuayBh
bmQgYWN0dWFsbHlJc0x1Y2t5IHRvIGJlIHRydWUu

*/


2D javascript table graphics The challenge

Make a JavaScript program that can use a HTML table as a canvas, having each cell a pixel.
You can either input the position and color values in a form or by using the console.

Score calculation

+10 points for not using JQuery
+15 points for the cells scaling equally to keep the same table aspect ratio when the browser is scaled
+15 points for accomplishing the last thing without using any kind of CSS
+[number of upvotes]
+20 points if you do not label the cells' tags with coordinates (it counts if you make an JavaScript array like {"cell1-1": ..., "cell1-2": ..., "cell1-3": ...} but it doesn't count when you label the  tag itself, like  or )

So if you have 67 upvotes, no JQuery (+10), the cells scaling (+15) but by using CSS (no +15) and you do not label the cells (+20), then your score will be 67 + 10 + 15 + 0 + 20 = 112.

The challenge ends on 20 Feb 2014, 4:00 PM GMT+0.

WINNERS:
Doorknob -> 61 + 3 = 64 points
Victor, with 60 + 1 = 61 points
they have very close scores so I couldn't exclude Victor.

Score: 61

10 (no jQuery) + 15 (scaling cells) + 15 (the scaling part uses no CSS) + 20 (no labels) + 1 (upvotes)

When you click on a cell, it turns the current color.

JavaScript

var w = h = 20, color = 'red'
function createTable() {
    var tbl = document.createElement('table')
    tbl.id = 'tbl'
    for (var i = 0; i < h; i++) {
        var tr = document.createElement('tr')
        for (var i2 = 0; i2 < w; i2++) {
            var td = document.createElement('td')
            td.addEventListener('mousedown', draw)
            tr.appendChild(td)
        }
        tbl.appendChild(tr)
    }
    document.body.appendChild(tbl)
    return tbl
}
function killTable(tbl) {
    tbl.parentNode.removeChild(tbl)
}
var tbl = createTable()

function draw(e) {
   e.preventDefault()
   this.style.backgroundColor = color
}

document.getElementById('finalize').addEventListener('click', finalize)
function finalize() {
    var tds = document.getElementsByTagName('td')
    for (var i = 0; i < tds.length; i++) {
        tds[i].style.border = 'none'
        tds[i].removeEventListener('mousedown', draw)
    }
    document.getElementById('optionsWrapper').style.display = 'none'
}

document.getElementById('changeColor').addEventListener('click', changeColor)
function changeColor() {
    color = document.getElementById('color').value
}

document.getElementById('changeDims').addEventListener('click', changeDims)
function changeDims() {
    var dims = document.getElementById('dims').value.split('x')
    w = +dims[0], h = +dims[1]

    killTable(tbl)
    tbl = createTable()
}

HTML

    <button id='finalize'>Finalize</button>

    Color: <input id='color' type='text' value='red' /><button id='changeColor'>Go</button>

    Change dimensions (WARNING: will erase drawing): <input id='dims' type='text' value='20x20' /><button id='changeDims'>Go</button>

CSS

td {
    width: 5px;
    height: 5px;
    padding: 0;
    border: 1px solid black;
}

table {
    border-collapse: collapse;
}

JSFiddle

http://jsfiddle.net/D9u2N/1/

Screenshots

Zoomed in view (while editing, click to enlarge to full size):

Finalized view (zoomed out):


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

Criterias

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

Python 3.4

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

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

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

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

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

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

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

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

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

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

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

For contrast here are some that really do rotate:

...or do they?

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

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

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

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

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

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


The Primitive and Basic Numbers Your task is to generate the "Primitive and Basic" numbers, which are made like so:

Start with 110. Take the digits of its base-1 representation (110 = 11) and interpret them as base-2 digits. This gives 12 = 110. Now, add the second prime number – 310 – to the result. This will give you 410, which is our first "Primitive and Basic" (PB) number, or PB(1) (you can now see where I got the name from).

Next, take 410 = 1002 and interpret the digits of its base-2 representation as base-3 digits. This gives 1003 = 910. Add the third prime number – 510 – to the result, which gives 1410. That's the second PB number, or PB(2).

You can see where this is going: take 1410 = 1123 and interpret the digits of its base-3 representation as base-4 digits. This gives 1124 = 2210. Add the fourth prime number – 710 – to the result, which gives 2910.

This continues on and on forever.

In general, PB(n) is equal to PB(n-1), converted to base n and from base n+1 to integer, plus the (n+1)th prime.

The first few terms of this sequence are:

4, 14, 29, 52, 87, 132, 185...

You must write a function or program that creates these numbers. It must take a positive integer n as input, and return PB(n).

I/O:

1 -> 4
5 -> 87

Rules and specs:

Your program must be able to handle all PB numbers below 231-1.
Standard loopholes apply.
The input may be 0-indexed or 1-indexed, whichever you prefer.
The input is guaranteed to be a valid index.
The output must be in base 10.

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

Unfortunately, there isn't an OEIS sequence for this. You can propose to OEIS to add this sequence in if you want.

Ruby, 126 bytes

require("prime")
->n{o=4
(2..n).map{|i|j=i+1
r=[]
(r.unshift o%i;o/=i)while o>0
o=r.inject{|s,k|s*j+k}+Prime.first(j)[-1]}
o}


Arranging pins on a microchip Since no one has posted a "good quality question" recently, i feel it is my duty to...

Task:

  You work at an electronics company in the design department. The designers that work with you have asked you to make a program that will calculate the optimum configuration of pins on a microchip they are designing. With your ninja golfing skills, you are confident you can handle it.

Your company also has these requirements for each chip:

The chips your company makes are known as TQFP, they have pins on each edge, but none in the middle.
Each chip must be square, and have the same number of pins on each side.
If the chip doesn't have enough pins to be square, pins will be added.

Extra pins are either a ground or voltage supply pin.
Half are ground, half are voltage supply.
If there is an odd number of extra pins, the odd one out is ground

Your program will take input as a single integer, which is the minimum number of pins the manufacturing needs. You will then output 4 integers:

The number of pins (total)
The number of pins per side
The number of ground pins added
The number of voltage supply pins added

Rules:

You can use any language
This is code-golf, to the shortest answer in bytes wins
Bonus: -50 for printing an ASCII chip:

Something like this:

 +++++
 +   +
 +   +
 +   +
 +++++

(For example with an input of 20)

Python: 64 53 46 bytes
x=input()
m=x+3&~3
t=m-x
print m,m/4,t-t/2,t/2

Second Third attempt seems pretty minimal. Thanks for the help.
First attempt seems sort of long, we'll see what an hour or two of mulling it over will shave off of the byte count. Could also probably make it shorter if a function is allowed instead of program.
> python chip.py
9
(12, 3, 2, 1)

Also made a version that prints chips, seems like the -50 isn't worth it in python. Total score of 102-50=52.
x=input()
m=x+3&~3
n=m/4
t=m-x
s=['+'*-~n]
print'\n'.join(s+['+'+' '*~-n+'+']*~-n+s+[`m,n,t-t/2,t/2`])

Example:
> python chip.py
9
++++
+  +
+  +
++++
(12, 3, 2, 1)


Output programming language name Challenge:

In the programming language of your choice, take no input and output your programming language's name.

Fair enough, right?

Restrictions:

You can't use any character that is included in your programming language's name in your code. E.g., if I use Batch, I must not use the chars 'B' 'a' t' 'c' 'h' in my code. Note that this is case sensitive. I can still use the char 'b' because it's different from 'B'.
You can have "junk output" before or after the name of the language
Version number doesn't count as part of the name of the language. E.g., I can use the number 3 in the code in my answer if it's in Python 3
The output of the programming language name is not case sensitive.
Brute-forcing all possible letter combinations and hoping you get your language name is forbidden.

Example outputs: (let's say my programming language is called Language) (✔ if valid, else ✖)

Language ✔
Body language is a type of non-verbal communication in which physical behavior, as opposed to words, is used to express or convey information. Such behavior includes facial expressions, body posture, gestures, eye movement, touch and the use of space. ✔
Language 2.0 - © 1078 AD some company ✔
foobar ✖

This is code-golf thus shortest code wins.

Outputs to STDERR
Outputting to STDERR is now at +33/-21 as an allowed default, which is positive but contested. This is a CW answer to collect answers that just invoke an error in a language where error messages includes the language name.
Haskell, 1 byte
1

Error:
Parse error: naked expression at top level
Perhaps you intended to use TemplateHaskell

Lua, 1 byte
1

Error:
lua: .code.tio:1: syntax error near <eof>

(file name is unimportant)
Batch, 1 byte
~

Error:
'~' is not recognized as an internal or external command,
operable program or batch file.

tinylisp, 5 bytes
(c()1

Error:
Error: cannot cons to Int in tinylisp

R, 1 byte
)

Error:
Error: unexpected ')' in ")"

Java bytecode, 0 bytes
Error:
Exception in thread "main" java.lang.ClassFormatError: Truncated class file

Groovy, 1 byte
a

Note that a can be replaced with any other character
Error:
groovy.lang.MissingPropertyException: No such property: a ...

MATLAB, 1 byte
\

Error:
Error: Unexpected MATLAB operator.

PHP, 3 bytes
<?=

Error:
PHP Parse error:  syntax error, unexpected end of file in /home/runner/.code.tio on line 1

CJam, 1 byte
/

Error:
/
^
RuntimeException: The stack is empty
Java exception:
java.lang.RuntimeException: The stack is empty
    at net.aditsu.cjam.CJam.pop(CJam.java:75)
    at net.aditsu.cjam.Op2.run(Op2.java:10)
    at net.aditsu.cjam.Block.run(Block.java:304)
    at net.aditsu.cjam.CJam.runCode(CJam.java:210)
    at net.aditsu.cjam.CJam.main(CJam.java:240)

Twig, 2 bytes
Twig is a template language written in PHP. It's possible that this is a polyglot.
{{
{%
{#

Error:
PHP Fatal error:  Uncaught exception 'Twig_Error_Syntax' with message [...] in [...][...]:n:
Stack trace:
#0 [...]

The message varies depending on which program you choose.
[S.I.L.O.S], 2 bytes
x+

[Try it online!]
[S.I.L.O.S]: https://github.com/rjhunjhunwala/S.I.L.O.S
[Try it online!]: https://tio.run/nexus/silos#@1@h/f8/AA "S.I.L.O.S – TIO Nexus"
Trivially invokes undocumented behavior. Silos is the name of the language.
Python, 6 bytes
pYTHON

As the character restriction is case insensitive, and the output doesn't have to be in the correct case, this is a valid answer. The error message it produces is something like this:
Traceback (most recent call last):
  File ".code.tio", line 1, in <module>
    pYTHON
NameError: name 'pYTHON' is not defined

Try it online! (outputs to 'debug' tab)
JavaScript, 10 bytes
jAVAsCRIPT

This produces the following error message or similar in all environments:
ReferenceError: jAVAsCRIPT is not defined

QBIC, 6 bytes
?b(12)

In 6 bytes, we can put QBIC encountered error: 9 on the screen, signifying an out-of-bounds error.
ForceLang, 2 bytes
()

Error produced:
Exception in thread "main" lang.exceptions.IllegalInvocationException: null is not a function.
    at lang.ForceLang.parse(ForceLang.java:99)
    at lang.ForceLang.main(ForceLang.java:129)

Pip, 5 bytes
1~`[`

(Note: this works in the current version as of this writing, 0.17.09.01. No guarantees the interpreter won't change to handle this error differently in the future.)
Tries to regex match with a syntactically invalid pattern. The error produced will look something like this:
Traceback (most recent call last):
  File "/opt/pip/pip.py", line 221, in <module>
    pip(interactive=False)
  File "/opt/pip/pip.py", line 206, in pip
    state.executeProgram(tree, args)
  File "/opt/pip/execution.py", line 56, in executeProgram
    returnVal = self.functionCall(mainFunction, cmdLineArgs)
  File "/opt/pip/execution.py", line 368, in functionCall
    returnVal = self.getRval(returnExpr)
  File "/opt/pip/execution.py", line 235, in getRval
    expr = self.evaluate(expr)
  File "/opt/pip/execution.py", line 213, in evaluate
    result = opFunction(*args)
  File "/opt/pip/execution.py", line 1134, in FIRSTMATCH
    matchObj = regex.asRegex().search(str(string))
  File "/opt/pip/ptypes.py", line 175, in asRegex
    self._compiled = re.compile(pyRegex)
  File "/usr/lib64/python3.6/re.py", line 233, in compile
    return _compile(pattern, flags)
  File "/usr/lib64/python3.6/re.py", line 301, in _compile
    p = sre_compile.compile(pattern, flags)
  File "/usr/lib64/python3.6/sre_compile.py", line 562, in compile
    p = sre_parse.parse(p, flags)
  File "/usr/lib64/python3.6/sre_parse.py", line 855, in parse
    p = _parse_sub(source, pattern, flags & SRE_FLAG_VERBOSE, 0)
  File "/usr/lib64/python3.6/sre_parse.py", line 416, in _parse_sub
    not nested and not items))
  File "/usr/lib64/python3.6/sre_parse.py", line 765, in _parse
    p = _parse_sub(source, state, sub_verbose, nested + 1)
  File "/usr/lib64/python3.6/sre_parse.py", line 416, in _parse_sub
    not nested and not items))
  File "/usr/lib64/python3.6/sre_parse.py", line 523, in _parse
    source.tell() - here)
sre_constants.error: unterminated character set at position 8

Stax, 2 bytes
0u

Error:
Stax runtime error: rational divide by zero

zh also works.
###ink, 1 byte
~

~ at the start of a line marks that the line is a statement to be executed, rather than text to be printed. As of whichever version of inklecate TIO is using, if there's nothing after the ~, the interpreter crashes with the following error:
System.NullReferenceException: Object reference not set to an instance of an object
  at Ink.InkParser.LogicLine () [0x000b1] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.StringParser.ParseObject (Ink.StringParser+ParseRule rule) [0x00012] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.StringParser.OneOf (Ink.StringParser+ParseRule[] array) [0x0000a] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.InkParser.StatementAtLevel (Ink.InkParser+StatementLevel level) [0x00009] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.InkParser+<>c__DisplayClass134_0.<StatementsAtLevel>b__0 () [0x00000] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.StringParser.ParseObject (Ink.StringParser+ParseRule rule) [0x00012] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.StringParser.Interleave[T] (Ink.StringParser+ParseRule ruleA, Ink.StringParser+ParseRule ruleB, Ink.StringParser+ParseRule untilTerminator, System.Boolean flatten) [0x00040] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.InkParser.StatementsAtLevel (Ink.InkParser+StatementLevel level) [0x0004f] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.InkParser.Parse () [0x00000] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.Compiler.Compile () [0x00033] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.CommandLineTool..ctor (System.String[] args) [0x001a3] in <d64e27e7788347b2a5377c9e19bbdcab>:0
  at Ink.CommandLineTool.Main (System.String[] args) [0x00000] in <d64e27e7788347b2a5377c9e19bbdcab>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.NullReferenceException: Object reference not set to an instance of an object
  at Ink.InkParser.LogicLine () [0x000b1] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.StringParser.ParseObject (Ink.StringParser+ParseRule rule) [0x00012] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.StringParser.OneOf (Ink.StringParser+ParseRule[] array) [0x0000a] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.InkParser.StatementAtLevel (Ink.InkParser+StatementLevel level) [0x00009] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.InkParser+<>c__DisplayClass134_0.<StatementsAtLevel>b__0 () [0x00000] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.StringParser.ParseObject (Ink.StringParser+ParseRule rule) [0x00012] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.StringParser.Interleave[T] (Ink.StringParser+ParseRule ruleA, Ink.StringParser+ParseRule ruleB, Ink.StringParser+ParseRule untilTerminator, System.Boolean flatten) [0x00040] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.InkParser.StatementsAtLevel (Ink.InkParser+StatementLevel level) [0x0004f] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.InkParser.Parse () [0x00000] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.Compiler.Compile () [0x00033] in <b1e5e74f4ee842fc961297862cf23e07>:0
  at Ink.CommandLineTool..ctor (System.String[] args) [0x001a3] in <d64e27e7788347b2a5377c9e19bbdcab>:0
  at Ink.CommandLineTool.Main (System.String[] args) [0x00000] in <d64e27e7788347b2a5377c9e19bbdcab>:0


Take first letter of each word, leave spaces and punctuation Shrink each word in a string of group of strings to single letters delineated by spaces or punctuation.

Example

I'm a little teapot,  short and stout. Here is my handle, here is my spout. When I get all steamed up - hear me shout!   Tip me over and pour me out.

becomes

I' a l t, s a s. H i m h, h i m s. W I g a s u - h m s! T m o a p m o.

Edit  -  if there are multiple spaces,  preserve only one space.  All punctuation should be preserved,  I missed the apostrophe.  Yes this is code  golf :-).

CJam, 13 bytes
r{(\'A,f&Sr}h

Works if I can consider only the common punctuation characters, and the output can have trailing spaces. (Thanks to Dennis.)
This question needs much more clarification...
CJam, 17 16 bytes
r{(\eu_elf&Sr}h&

Try it online.
Explanation
r          e# Read one word from input.
{          e# While it is not EOF:
    (\     e# Extract the first character.
    eu     e# Convert the rest to uppercase.
    _el    e# And lowercase.
    f&     e# Delete characters in the first string if not in the second string.
    S      e# Append a space.
    r      e# Read the next word.
}h
&          e# Discard the last space by intersecting with empty string.


The best base is 10... Let's reach it! Input:

A positive integer n consisting of digits in the range 0-9.

Challenge:

If d is the highest digit in the integer, assume the base of the number is d+1. E.g. if the integer is 1256 then you shall assume it's in base-7, if it's 10110 then you shall assume it's base-2 (binary), and if it's 159 then it's decimal.

Now, do the following until you either, 1: reach a base-10 integer, or 2: reach a single digit integer.

Convert the integer from base-(d+1) to base-10
Find the base of this new integer (again, base-(d+1) where d is the highest digit in the new number)
Go to step 1.

Examples:

Assume the input is n = 413574. The highest digit d=7, so this is base-8 (octal). Convert this to decimal and get 137084. The highest digit d=8, so this is base-9. Convert this to decimal and get 83911. The highest digit is 9, so this is a decimal number and we stop. The output shall be 83911.

Assume the input is n = 13552. The highest digit is d=5, so this is base-6. Convert this to decimal and get 2156. The highest digit d=6, so this is base-7. Convert this to decimal and get 776. The highest digit is d=7, so this is base-8. Convert this to decimal and get 510. The highest digit is d=5 so this is base-6. Convert this to decimal and get 186. The highest digit is 8, so this is base-9. Convert this to decimal and get 159. The highest digit is 9, so this is a decimal number and we stop. The output shall be 159.

Assume the input is n=17. This will give us 15, then 11, then 3, which we will output since it's a single digit.

Test cases:

5
5

17
3

999
999

87654321  (base-9 -> 42374116 in decimal -> base-7 -> 90419978 in decimal)
9041998

41253  (5505 -> 1265 -> 488 -> 404 -> 104 -> 29)
29

Notes:

Standard rules regarding I/O, loopholes etc. You may take the input as a string
Explanations are encouraged
You may use builtin base-conversion commands

Solutions that don't use the language's builtin base-conversion functions (if they exist) are welcome, even if they end up being much longer than the obvious approach using builtin functions.

Apparently, this is OEIS A091047.

Mathematica, 56 bytes

#//.x_/;(b=Max[d=IntegerDigits@x]+1)<11:>d~FromDigits~b&

Try it online! (Using Mathics.)

I thought I'd check out what the sequence looks like:

And here is a plot of the number of steps it takes to find the result:

(Click for larger versions. See the revision history for plots only up to n = 1000.)

Looks like a very interesting mixture of large scale structure and fine scale chaos. I wonder what's up with the wider gaps around 30,000 and 60,000.


Matching Adjacent Words In this challenge, you are passed two words: Your job is to determine if they are adjacent.
Two letters are adjacent if:

They are the same letter, or
They are lexicographically adjacent.

For example, J is adjacent to I,J, and K only.  Z is not adjacent to A
Two words are adjacent if:

They are the same length, and
Each letter is adjacent to a unique letter in the other word.

For example, CAT is adjacent to SAD, as C>D, A>A, T>S.
FREE is not adjacent to GRRD (each E needs a letter to pair with).
Input/Output
You are passed two strings, and you need to return a truthy value if they are adjacent, otherwise a falsy value.  You should return within a minute for all test cases below.
You can assume that the strings will only contain uppercase, alphabetic letters.
The two strings can be passed as a list, or concatenated, with or without quotes.
Test Cases
Truthy:
A A
A B
C B
DD CE
DE FC
ABCD BCDE
AACC DBBB
DJENSKE FDJCLMT
DEFGHIJKL HJLEHMCHE
IKLIJJLIJKKL LJLJLJLJLJHI
ACEGIKMOQSUWY BLNPRDFTVHXJZ
QQSQQRRQSTTUQQRRRS PQTTPPTTQTPQPPQRTP
ELKNSDUUUELSKJFESD DKJELKNSUELSDUFEUS

Falsy:
A C
A Z
B J
JK J
CC BA
CE D
DJENSKE GDJCLMT
DEFGHIJKL HJLHMCHE
IJKLIJKLKIJL LIJLLHJLJLLL
AWSUKMEGICOQY RSHXBLJLNQDFZ
QQSQQRRQSTTUQQQRRS PQTTPPTTQTPQPPQRTT
ELKNSDUVWELSKJFESD DKJELKNSUELSDUFEUS

This is code-golf, so the shortest valid answer wins!

CJam, 14 13 12 bytes

r$r$.-:)3,-!

Try it online! or verify all test cases at once.

Algorithm

Let s and t be two sorted words of the same length. For s and t to be lexicographically adjacent (LA), it is necessary and sufficient that all pairs of its corresponding characters are also LA.

The condition is clearly sufficient for all words, and necessary for words of length 1.

Now, assume s and t have length n > 1, and let a and b be the first characters, resp., of s and t.

Since s and t are LA, there is some bijective mapping φ between the characters of s and the characters of t such that x and φ(x) are LA for all x in s, meaning that |x - φ(x)| ≤ 1 for all x in s.

Let c = φ(a) and d = φ-1(b). Because of a's and b's minimality, a ≤ d (1) and b ≤ c (2).

Furthermore, since b and d, and a and c, and LA, d ≤ b + 1 (3) and c ≤ a + 1 (4).

By combining (1) and (3), and (2) and (4), we get that a ≤ d ≤ b + 1 and b ≤ c ≤ a + 1, from which we deduce that a - 1 ≤ b ≤ a + 1 and, therefore, that a and b are LA.

Now, by combining (1) and (4), and (2) and (3), we get that c - 1 ≤ a ≤ d and d - 1 ≤ b ≤ c, from which we deduce that c - 1 ≤ d ≤ c + 1 and, therefore that c and d are LA.

Thus, if we redefine φ by φ(a) = b and φ(d) = c, |x - φ(x)| ≤ 1 will still hold for all x in s and, in particular, for all x in s[1:].

This way, s[0] = a and t[0] = b, and s[1:] and t[1:], are LA.

Since s[1:] has length n - 1, this proves the necessity by induction.

Code

r               e# Read the first word from STDIN.
 $              e# Sort its characters.
  r             e# Read the second word from STDIN.
   $            e# Sort its characters.
    .-          e# Perform vectorized subtraction.
                e# This pushes either the difference of char codes of two
                e# corresponding characters or a character that has no does not
                e# correspond to a character in the other, shorter word.
      :)        e# Increment all results.
                e# In particular, this maps [-1 0 1] to [0 1 2].
        3,      e# Push the range [0 1 2].
          -     e# Perform set difference, i.e., remove all occurrences of 0, 1 and
                e# 2 from the array of incremented differences.
           !    e# Apply logical NOT. This gives 1 iff the array was empty iff
                e# all differences gave -1, 0 or 1.


How far away is n to the next power of b? Let n and b be positive integers larger than 1.

Output the distance from n to the next power of b.

For n=5 and b=3, the next power of 3 from 5 is 9 (3^2 = 9), so the output is 9 - 5 = 4.

For n=8 and b=2, the next power of 2 from 8 is 16 (2^4 = 16), so the output is 16 - 8 = 8. Note that n is a power of 2 in this example.

Testcases:

  n b output
212 2 44
563 5 62
491 5 134
424 3 305
469 8 43
343 7 2058
592 7 1809
289 5 336
694 3 35
324 5 301
  2 5 3

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

Jelly,  4  3 bytes

ạæċ

A dyadic link taking n on the left and b on the right and returning the result.

Try it online!

How?

ạæċ - Link: number n, number b | n,b ∈ ℕ
 æċ - ceiling n to the next power of b
ạ   - absolute difference between n and that


Is it raining? I can't tell These are raindrops:

! | . " :

These are clouds particles:

( ) _ @ $ &

I want you to verify, when given a block of text, whether or not it is raining. It is raining if, for every raindrop, there is a cloud particle somewhere above it. There must be one cloud particle for every raindrop. Output a truthy or falsy value denoting your conclusions.

Valid examples

(@@@@@@)
 ( $ &  )
Q   (  )
..  .  !
 : .
  |"   !
    .

()()()
......

@_$ &
errrr
h_r-5
.:. .
 "

Invalid examples

!
()

$$$$$
(   )
:::::
.....

This is a code-golf so the shortest program in characters wins.

C++11, 186 184 bytes

#include<map>
int i,c;int main(){std::map<int,int>p;while(~(c=getchar())){for(int m:{40,41,95,64,36,38})p[i]+=c==m;for(int m:{33,124,46,34,58})if(c==m&&!p[i]--)return 1;i=c-10?i+1:0;}}

Ungolfed

#include <map>
int i, c;
int main()
{
    std::map<int, int> p;
    while (~(c = getchar()))
    {
//        for (int m : { '(', ')', '_', '@', '$', '&'})
        for (int m : { 40, 41, 95, 64, 36, 38})
            p[i] += c == m;
//        for (int m : { '!', '|', '.', '"', ':'})
        for (int m : { 33, 124, 46, 34, 58})
            if (c == m && !p[i]--)
                return 1;
        i = c - '\n' ? i + 1 : 0;
    }
    return 0;
}

Basic approach, storing positions of cloud particles in a row and if rain particle is encountered, it checks whether the cloud particle is above it and decreases the counter of cloud particles in that column. The program returns 0 if it's valid and 1 otherwise.


Make an infinite chain Lets define a class of functions.  These functions will map from the positive integers to the positive integers and must satisfy the following requirements:

The function must be Bijective, meaning that every value maps to and is mapped to by exactly one value.
You must be able to get from any positive integer to any other positive integer by repeated applications of the function or its inverse.

Now, write some code that will perform any one function in this class on its input.

This is a code-golf question so answers will be scored in bytes, with less bytes being better.

Python 3, 24 bytes

lambda n:n-(-1)**n*2or 1

Try it online!


Restricted-source polyglot string Your goal is to write a program that prints the string abc in two languages. However, while the full code will print abc in one language (we'll call it Language 1), the other one (Language 2) must print abc if (and only if) every other character is skipped starting from the second character. If the full code is run in language 2, it must throw an error. If the skipped code is run in language 1, likewise, it must throw an error.

Rules and Clarification

Trailing newlines are allowed.
Output must be lowercase.
"Run" means compiled for compiled languages.
We will define "throwing an error" as outputting nothing to STDOUT and something to STDERR.

Test Cases

Language 1: 12345 -> abc
Language 1: 135 -> error
Language 2: 135 -> abc
Language 2: 12345 -> error

Scoring

The shortest code in bytes wins (the full code, not the skipped code).

Edit: I have clarified the rules based on feedback in the comments. The existing answers should still be valid.

brainfuck, 28 26 bytes

a+b[c-/[/---<]>>- ]<-.+.+.

Try it online!

Got the bf code from here.

Fails in Ink due to Expected target for new thread but saw '.+.+.'.

ink

abc//-<>-]-++

Try it online!

Ink will just print abc and the rest is a comment.

Fails in brainfuck due to mismatched bracket.


How many IP addresses are in a given range? Inspired by...

  Networking - How can I work out how many IP addresses there are in a given range?

Write a program or function that takes two strings as input, each being an IPv4 address expressed in standard dotted notation and outputs or returns the number of IP addresses covered by this range, including the two IP addresses input.

You must not use any external code, libraries or services designed to parse an IP address. (Other string processing standard library functions are acceptable.)
All 2^32 IP addresses are equal. No distinction is made to broadcast, class E, etc.
Normal code-golf rules apply.

For example:

"0.0.0.0","255.255.255.255" returns 4294967296.
"255.255.255.255","0.0.0.0" also returns 4294967296.
"1.2.3.4","1.2.3.4" returns 1.
"56.57.58.59","60.61.62.63" returns 67372037.
"1","2" is invalid input. Your code may do anything you like.

GolfScript, 20 bytes

~]7/${2%256base}/)\-

Try it online.

Test cases

$ echo 0.0.0.0 255.255.255.255 | golfscript range.gs
4294967296
$ echo 255.255.255.255 0.0.0.0 | golfscript test.gs
4294967296
$ echo 1.2.3.4 1.2.3.4 | golfscript test.gs
1
$ echo 56.57.58.59 60.61.62.63 | golfscript test.gs
67372037

How it works

~]        # Evaluate and collect into an array.
          #
          # “.” duplicates, so for "5.6.7.8 1.2.3.4", this leaves
          # [ 5 5 6 6 7 7 8 1 1 2 2 3 3 4 ] on the stack.
          #
7/        # Split into chunks of length 7: [ [ 5 5 6 6 7 7 8 ] [ 1 1 2 2 3 3 4 ] ]
$         # Sort the array of arrays: [ [ 1 1 2 2 3 3 4 ] [ 5 5 6 6 7 7 8 ] ]
{         # For each array:
  2%      # Extract every second element. Example: [ 1 2 3 4 ]
  256base # Convert the IP into an integer by considering it a base 256 number.
}/        #
)         # Add 1 to the second integer.
\-        # Swap and subtract. Since the integers were sorted, the result is positive.


Output code-sized Lorem Ipsum Output the same length of Lorem ipsum your code is!

Rules:

Code can't be identical to output
No compression libraries
Shortest program in two weeks wins
No network usage, file reading and other tricks which with one could easily solve any code golf problem (with eval, exec, etc)

Example

Your code with length 25.

Output

Lorem ipsum dolor sit ame

rot13 (1)

i'm surprised nobody came up with this before :)

Y

and as a bonus, a very simple perl solution

Perl (252)

s//LoremIpsumDolorSitAmet,ConsectetuerAdipiscingElit,SedDiamNonummyNibhEuismodTinciduntUtLaoreetDoloreMagnaAliquamEratVolutpat. UtWisiEnimAdMinimVeniam,QuisNostrudExerciTationUllamcorperSuscipitLobortisNislUtAliquipExE/;s,([^ ])([A-Z]),$1$"\l$2,g;print


Solving variants of the blue-eyes puzzle The original "Blue Eyes" puzzle is given here (and below).

  A group of people with assorted eye colors live on an island. They are
  all perfect logicians -- if a conclusion can be logically deduced,
  they will do it instantly. No one knows the color of their eyes. Every
  night at midnight, a ferry stops at the island. Any islanders who have
  figured out the color of their own eyes then leave the island, and the
  rest stay. Everyone can see everyone else at all times and keeps a
  count of the number of people they see with each eye color (excluding
  themselves), but they cannot otherwise communicate. Everyone on the
  island knows all the rules in this paragraph.

  On this island there are 100 blue-eyed people, 100 brown-eyed people,
  and the Guru (she happens to have green eyes). So any given blue-eyed
  person can see 100 people with brown eyes and 99 people with blue eyes
  (and one with green), but that does not tell him his own eye color; as
  far as he knows the totals could be 101 brown and 99 blue. Or 100
  brown, 99 blue, and he could have red eyes.

  The Guru is allowed to speak once (let's say at noon), on one day in
  all their endless years on the island. Standing before the islanders,
  she says the following:

  "I can see someone who has blue eyes."

  Who leaves the island, and on what night?

The answer is that they all leave on the hundredth day. This is due to the following logic:

  If there is one blue-eyed person only, he will leave on day 1. If
  there are two-blue-eyed people only, nobody leaves on day 1. Following
  this, they both leave on day 2. Now if there are 3 blue-eyed people,
  nobody leaves on day 1. Nobody leaves on day 2 either. Now everyone
  knows that there are 3 blue-eyed people, because if there were only
  one, he would have left on day 1 and if there are two, they both would
  have left on day 2. Hence all 3 leave on day 3.

  We can now write an inductive proof that if n blue-eyed people require
  n days to figure out their eye colours and leave, then n+1 blue-eyed
  people require n+1 days to do the same.

However, the code you write should be capable of solving not just the original puzzle, but also some variants that require slightly different inductive steps.

You will be told how many of the islanders have blue eyes and how many don't. You will also be given a statement by the oracle (a system of equations/inequations) that everyone on the island hears. You need to determine when the island will be free of the blue-eyed people.

The oracle's statements will use b for the number of blue-eyed people and r for the number of non-blue-eyed people. The equations can include < > <= >= = + - and any whole numbers.

Test cases

Based on this set of variants

50 50
b>=1
b<b+r

Output: 50

The second equation gives no new information, hence this problem becomes exactly the same as the original puzzle.

100 50
b+3>=r+4

Output: 25

100 0
b-2>8+1-1

Output: 90

50 50
b>=10
b<=75

Output: 41

Python 2, 60 48 bytes

f=lambda b,r,c:all(map(eval,c))and-~f(b-1,r+1,c)

Try it online!

How it works

By induction:

If the island composition is (b, r) and it is known that (b − 1, r + 1) is not possible, then on day 1, the blue-eyed islanders, seeing (b − 1, r), will conclude that they are blue-eyed and leave.
If the island composition is (b, r) and it is known that the blue-eyed islanders would have left on day n if the composition were (b − 1, r + 1), then on day n + 1, the blue-eyed islanders, seeing (b − 1, r), will conclude that they are blue-eyed and leave.

This second inference fails if b = 1, but in that case, the blue-eyed islander would never leave if they hadn’t already, and the test case would be invalid.

Note that non-blue-eyed islanders will never leave, in this version of the puzzle, because even if they use similar logic to conclude that they are not blue-eyed, they still don’t know which non-blue color their eyes are.


Find the longest snake on a grid Background

A snake is a path over the cells of a square grid, such that it doesn't touch itself on a side of a unit square. Touching at a corner is allowed.

An example snake:

##.#.
.#.##
##..#
#.###
###..

Some example non-snakes:

###.#
#.#.#
#####
.#...
.####

###
.#.

##
##

Challenge

Given an empty grid with the two endpoints of a snake marked on it, find the longest possible snake that fits on the grid. If there are multiple answers having the same length, you may choose to output one or all of them.

The input can be given as a character matrix (or equivalent) with two endpoints marked on it, or the dimensions (width, height) and the coordinates of the endpoints. You may choose to output the grid containing the snake or a list of coordinates of cells occupied by the snake (or equivalent).

Standard code-golf rules apply. The shortest code in bytes wins.

Example I/O

Each I/O example is given as a character matrix, # being the part of the snake.

Input:
..#...#...
Output:
..#####...

Input: (corner case)
......
......
..##..
......
......
......
Output: same as input (no way to get longer without violating no-touch condition)

Input:
..#.#
.....
.....
.....
Output:
###.#
#...#
#...#
#####

Input:
#....
.....
.....
.....
....#
Output:
#####
....#
#####
#....
#####

Python 3.8 (pre-release), 207 194 181 bytes

-7 bytes thanks to @ovs

Input

The width \$ w \$, the height \$ h \$, the starting point \$ s \$, and the ending point \$ e \$. \$ s \$ and \$ e \$ are complex numbers which represent the coordinates of the endpoints.

Output

A list of points, in the form of complex numbers.

C={1,-1,1j,-1j}
def f(w,h,s,e):P=[[s]];exec("P=[j+[t+(t==e==(A:=j+[t]))]for j in P for k in C if w>(t:=j[-1]+k).real>-1<t.imag<h>0<all({t+l}-{*j}for l in{0}|C-{-k})];"*w*h);return A

Try it online!

Explanation

We use a breadth-first search to search for all possible snakes, starting at \$ s \$, making sure that the next tile is not adjacent to any previous tile, and that we do not go past the boundary. After each iteration, we check for all paths whose last element is \$ e \$, meaning that we have found a complete path from \$ s \$ to \$ e \$. Instead of storing all complete paths and returning the one with maximum length, we can simply return the last path found, since breadth-first search already searches for paths by length.