lwap She tirst fetters! Given a list or delimited string, output a list or delimited string with the first character of each word one word later.

For this challenge, a "word" consists of only all printable ASCII characters, except the space, newline, and tab character.

For example, take the string "Good afternoon, World!" (space-delimited):

1. String
"Good afternoon, World!"

2. Get the first characters:
"[G]ood [a]fternoon, [W]orld!"

3. Move the characters over. The character at the end gets moved to the beginning.
"[W]ood [G]fternoon, [a]orld!"

4. Final string
"Wood Gfternoon, aorld!"

This is code-golf, so shortest code wins!

Test cases:

Input -> output (space-delimited)

"Good afternoon, World!" -> "Wood Gfternoon, aorld!"
"This is a long sentence." -> "shis Ts i aong lentence."
"Programming Puzzles and Code Golf" -> Grogramming Puzzles Pnd aode Colf"
"Input -> output" -> "onput I> -utput"
"The quick brown fox jumped over the lazy dog." -> "dhe Tuick qrown box fumped jver ohe tazy log."
"good green grass grows." -> "good green grass grows."

05AB1E, 7 6 bytes

€ćÁ2ôJ

Explanation:

€ć      Extract head of each
  Á     Rotate to the right
    2ô  Split into pieces of length two
      J Join

Try it online!


Count the videos in a Youtube Playlist Challenge

Given a Youtube playlist, output the number of videos in it.

I/O

The playlist will be given as an URL; for example, https://www.youtube.com/playlist?list=PL_3jnZNPYn7qUatgDYBS5NShkfXoehSRC (this is a playlist a friend sent me to try to get me to listen to K-Pop because she's obsessed with it and I don't like it :P)

The link to a playlist is of the form https://www.youtube.com/playlist?list=<id>. The input is the URL, not the ID.

The output is to be a single integer indicating how many videos are in this playlist. You can either output the total number of videos or the number of non-deleted videos, whichever one is more golfy for you.

Test Cases

https://www.youtube.com/playlist?list=PL_3jnZNPYn7qUatgDYBS5NShkfXoehSRC -> 12
https://www.youtube.com/playlist?list=PLIEbITAtGBebWGyBZQlkiMXwt30WqG9Bd -> 114 OR 1

Feel free to add more test cases.

05AB1E, 22 bytes
Assumes that the URL is passed without the https://.
Code:
.w’®Ã-ƒ¢’¡`"<li>"¡2è#¬

Uses the 05AB1E encoding. Cannot be tried online, because of internet access.
Explanation:
.w                       # Receive implicit input and read all data from the url
  ’®Ã-ƒ¢’¡               # Split on the string "header-details"
          `              # Flatten once which leaves the last element on top of the stack
           "<li>"¡       # Split on the string "<li>"
                  2è     # Get the third element
                    #    # Split on spaces
                     ¬   # Retrieve the first element

This is what I get when running in the command line:


Party all week end for my birthday? Knowing a given date (11/28/1973), and supposing I will die when I'm 99, what are the years when my birthday will be a thursday so that I will be able to party all week-end?


Dig to Australia - antipodes Background

Countless generations of children have wondered where they would end up if they dug a hole directly downwards. It turns out that this would, unsurprisingly, be rather dangerous, but anyway...

Antipodes are points that are directly opposite each other on the Earth's surface. This means that if a line was drawn between the two points, it would pass through the centre of the Earth.

Challenge

Write a program or function that, given a point, finds its antipode.

In this challenge, points are represented using the longitude-latitude system and degrees, arc minutes and arc seconds. To find the antipode, swap the directions of each ordinate (N <-> S and W <-> E) and subtract the longitude ordinate from 180 degrees.

Example:
Take the point N 50 26 23 W 4 18 29. Swap the directions to give S 50 26 23 E 4 18 29. Subtract the longitude ordinate from 180 0 0 to give 175 41 31, leaving the antipode coordinates as S 50 26 23 E 175 41 31.

Rules

Input

A set of latitude-longitude coordinates, in any reasonable format, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds.

Output

The latitude-longitude coordinates of the antipode, in any reasonable format, where each ordinate contains a direction, a number of degrees, a number of arc minutes, and a number of arc seconds.

Take reasonable to mean that each part of the coordinate can be distinguished unambiguously.

Specs

The direction for the latitude ordinate is N or S, and that for the longitude ordinate is W or E.
All coordinate values are integers. The degree value will be between 0 and 90 for latitude, and between 0 and 180 for longitude. The arc minute and arc second values for both ordinates will be between 0 and 59.
If all the values for an ordinate are 0, either direction is acceptable.
There is no need to zero-pad any values.
No latitude ordinate will ever  be larger than 90 degrees, and no longitude ordinate will ever be larger than 180 degrees.
Standard loopholes apply.

Test cases

N 50 26 23 W 4 18 29 -> S 50 26 23 E 175 41 31

S 43 9 9 E 0 0 5     -> N 43 9 9 W 179 59 55

N 0 0 0 E 0 0 0      -> S/N 0 0 0 W/E 180 0 0 (either direction fine in each case)

S 1 2 3 W 4 5 6      -> N 1 2 3 E 175 54 54

S 9 21 43 W 150 7 59 -> N 9 21 43 E 29 52 1

S 27 40 2 W 23 0 0   -> N 27 40 2 E 157 0 0

N 0 58 37 W 37 0 0   -> S 0 58 37 E 143 0 0

Useful links

Latitude and longitude
Antipodes
Arc minutes and arc seconds

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

MATL, 51 bytes
'NS'tPXEii'WE'tPXE648e3i60:qXJZA-JYAtn3-?2:&)wJZAwh

Input format:
'N'
[50 26 23]
'W'
[4 18 29]

Output format:
S
50 26 23
E
175  41  31

Try it online!
Explanation
'NS'tPXE     % Take input (string) implicitly. Exchange 'N' and 'S'
i            % Take input (array)
i'WE'tPXE    % Take input (string). Exchange 'W' and 'E'
648e3        % Push 648000
i            % Take input (array)
60:qXJ       % Push [0 1 ... 59]. Copy into clipboard J
ZA           % Convert second input array from base 60 to decimal
-            % Subtract
JYA          % Convert to base 60
tn3-?        % If length exceeds 3
  2:&)       %   Split into first two elements and then the rest
  w          %   Swap
  JZA        %   Convert from base 60 to decimal
  wh         %   Swap, concatenate


How's your string theory? Back to the basics! You're in you comp sci class again, except wiser and golfier. You have the tools, you have the power… but do you have the skill? Probably.

Crash Course for the non-Computer Scientist (skip if you don't need it)

A string is symbolically represented by an arbitrary letter (usually, for our purposes, will be  etc. Of course, we know a string as something like "Hello, World!" or 'Hello, World!', or, if you're the snarky Python user, """Hello, World!""".

An alphabet can be thought of as a set (i.e. no repeating characters) of symbols, of which strings can be made. For example, ; this is the binary alphabet, of which contains strings like  and .  These strings can said to be strings over , or, alternatively, .

The length of any string is denoted . For example, .

There is the empty or null string , which is equivalent to "". It is a valid string in over any alphabet. In other words,  is the unique string satisfying the property .

The set  is the set of all strings  over  for which .

The set  is called the Kleene closure of , and is the set of all strings over . This can be considered the language of .

The concatenation of two strings  and  is denoted , and is the string containing the characters of  followed by the characters of .

 is said to be a prefix of  if there is some string  that satisfies the equality . (If , then  is said to be a proper prefix of .)

The alphabet of a string  is denoted , and is the minimal alphabet  so that  is a string over

The projection of a string  relative to an alphabet  is defined as

and is essentially the removal of all characters in  not in .

TL;DR

Objective Write a program, series of functions, series of programs etc. that can calculate as many of the following tasks as possible:

(1) Calculate, given a string s, its length.
(2) Arrive at, given a string s and an alphabet Σ, whether or not (output a truthy/falsy value) that string is over said alphabet.
(1) Given an alphabet, arrive at whether or not (output a truthy/falsy value) the alphabet is valid (a valid alphabet can have no repeating characters, but is otherwise valid).
(4) Given an alphabet Σ and a positive integer n, display .
(6) Given an alphabet Σ and an integer n, display the first n entries in  (Remember that ε ∈ Σ!)
(1) Given a string s and a string t, output st.
(3) Given a string s, output Al(s).
(5) Given a string s and an alphabet Σ, output πΣ(s).

Input is given by a string or your language's closest equivalent for a string input, an array, tuple, or n-ordinate of characters for an alphabet  (your language's closest equivalent), and a number for a number (or your language's closest equivalent, heaven forbid your language does not support numbers!).

Each task has a score (the number in parenthesis). Your submission's score is calculated as follows:

        sum points scored
score = —————————————————
         length of bytes

Highest score wins.

Bonuses

×4 final score iff you output (with the correct symbols!) the input query. E.g., outputting \pi_{\{0,1\}}(012345678910111213)=01101111 for an input of Σ = [0,1]; s = 012345678910111213. (You may choose to do this in either HTML or (La)TeX. Either counts.)
(I'm open to suggestions.)

APL, score 3

Task 7: 3 / 1

∪

This is a built-in that – according to this discussion – can be considered an unnamed function.

Try it online on TryAPL.


Duplicate & switch case The goal is, having taken a string as input, duplicate each latin letter and "toggle" its case (i.e. uppercase becomes lowercase and vice-versa).

Example inputs & outputs:

Input      Output
bad        bBaAdD
Nice       NniIcCeE
T e S t    Tt eE Ss tT
s E t      sS Ee tT
1!1!1st!   1!1!1sStT!
n00b       nN00bB
(e.g.)     (eE.gG.)
H3l|@!     Hh3lL|@!

The input consists of printable ASCII symbols.

You shouldn't duplicate non-latin letters, numbers, special chars.

Python, 56 54 bytes

lambda s:''.join(c+c.swapcase()*c.isalpha()for c in s)

Test it on Ideone.


Write a function that returns an iterable object of all valid points 4-directionally adjacent to (x, y) A very common need in algorithms classes and computer science in general is to iterate 4-directionally over a grid or matrix (such as in BFS or DFS). This seems to often result in a lot of clunky and verbose code with a lot of arithmetic and comparisons within loops. I've seen many different approaches to this, but I can't shake the feeling that there's a more concise way to do this.

The challenge is to write a pure function that, given the width and height of a finite plane n, m originating at point (0,0), and coordinates (x,y) that can represent any valid point within that plane, returns an iterable object of all points within the plane that are 4-directionally adjacent to (x,y).

The goal is to define that function in as few bytes as possible.

Some examples to help illustrate valid input/output:

n = 5 (y-axis), m = 3 (x-axis) (zero-based)

matrix = [
    [A, B, C],
    [D, E, F],
    [G, H, I],
    [J, K, L],
    [M, N, O],
]

(x, y) => [valid iterable points]

E: (1, 1) => [(1, 0), (2, 1), (1, 2), (0, 1)]
A: (0, 0) => [(1, 0), (0, 1)]
L: (2, 3) => [(2, 2), (2, 4), (1, 3)]
N: (1, 4) => [(1, 3), (2, 4), (0, 4)]

n = 1 (y-axis), m = 1 (x-axis) (zero-based)

matrix = [
    [A],
]

(x, y) => [valid iterable points]

A: (0, 0) => []

n = 2 (y-axis), m = 1 (x-axis) (zero-based)

matrix = [
    [A],
    [B],
]

(x, y) => [valid iterable points]

A: (0, 0) => [(0, 1)]
B: (0, 1) => [(0, 0)]

And here's an example (this one in Python) of a function that satisfies the conditions:

def four_directions(x, y, n, m):
    valid_coordinates = []
    for xd, yd in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
        nx, ny = x + xd, y + yd
        if 0 <= nx < m and 0 <= ny < n:
            valid_coordinates.append((nx, ny))
    return valid_coordinates

The example above defined a named function, but anonymous functions are also acceptable.

The inputs n, m, x, y are all unsigned 32-bit integers within the following ranges:

n > 0
m > 0
0 <= x < m
0 <= y < n

The output must take the form of an iterable (however your language of choice defines that) of (x, y) pairs.

Additional clarifications:

Complex numbers (and other representations/serializations) are OK as long as the consumer of the iterable can access x and y as integers knowing only their location.

Non-zero-based indexes are acceptable, but only if the language of choice is a non-zero-indexed language. If the language uses a mix of numbering systems, default to the numbering system of the data structure most commonly used to represent a matrix. If these are still all foreign concepts in the given language, any starting index is acceptable.

Python 2, 66 bytes

lambda m,n,x,y:[(x-1,y),(x+1,y)][~x:m-x]+[(x,y-1),(x,y+1)][~y:n-y]

Try it online!

Lists the four neighbors, then uses list slicing to remove those that are out-of-bounds.

Python 2, 71 bytes

lambda m,n,x,y:[(k/n,k%n)for k in range(m*n)if(k/n-x)**2+(k%n-y)**2==1]

Try it online!

Instead of checking which of the four neighbors are in-bounds, we do it the slower way of checking all in-bounds points for those that are neighbors, that is have Euclidian distance exactly 1 from (x,y). We also use the classic div-mod trick to iterate over a grid, saving the need to write two loops like for i in range(m)for j in range(n).

I tried using complex arithmetic to write the distance condition, but it turned out longer to write abs((k/n-x)*1j+k%n-y)==1.

Python 2, 70 bytes

lambda m,n,x,y:[(x+t/3,y+t%3-1)for t in-2,0,2,4if m>x+t/3>=0<y+t%3<=n]

Try it online!


Quickly regrouping lists Grouping takes a list and splits it into new lists of equal adjacent elements.  For example

[1,1,2,1,1] -> [[1,1],[2],[1,1]]

If you then take the length of these groups you get a new list of integers

[1,1,2,1,1] -> [2,1,2]

Your task is to write a program that takes a list of positive integers and find the number of times you can group and length it before the resulting list has a single element.  For example the list [1,2,3,3,2,1] can be regrouped 4 times

[1,2,3,3,2,1]
[1,1,2,1,1]
[2,1,2]
[1,1,1]
[3]

This is code-golf so answers will be scored in bytes with fewer bytes being better.

Test cases

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

Haskell, 49 bytes

import Data.List
f[_]=0
f c=1+f(length<$>group c)

Try it online!


Multiply elements of the dihedral group This is a copy cat question of Simplify ijk string applied to the other nonabelian group of order 8. See also Dihedral group composition with custom labels.
Challenge
Given a string made of r and s interpret it as the product of elements of the dihedral group \$D_8\$ and simplify it into one of the eight possible values "", "r", "rr", "rrr", "s", "rs", "rrs", and "rrrs". The empty string denotes the identity element \$1\$.
The evaluation rules are as follows:
$$
rrrr = 1\\
ss = 1\\
sr = rrrs
$$
The multiplication on the dihedral group is associative but not commutative. This means that you may do the simplification in any order, but you cannot reorder the items.
For the I/O format, function parameter and return from a function should be done as a string or list. You may output any amount of leading and trailing whitespace (spaces, tabs, newlines). You may use any other pair of distinct characters for r and s except for a tab, space, or newline. (If you really want to you can pick r or s to be whitespace, you can as long as you don't have leading or trailing whitespace.) It's also fine to use numbers for r and s, for example if you take 0 for r and 1 for s, it would be okay to do I/O like [1, 0] ==> [0, 0, 0, 1].
Test cases
"" -> ""
"r" -> "r"
"rrr" -> "rrr"
"s" -> "s"
"rs" -> "rs"
"rrs" -> "rrs"
"rrrr" -> ""
"rrrrrr" -> "rr"
"sr" -> "rrrs"
"rsr" -> "s"
"srsr" -> ""
"srr" -> "rrs"
"srs" -> "rrr"
"rsrsr" -> "r"
"rrsss" -> "rrs"
"sssrrr" -> "rs"

Reference implementation
Here is a Javascript reference implementation.
function f(x) {
  let lastx;
  while(lastx !== x){
    lastx = x;
    x = x.replace("rrrr", "");
    x = x.replace("sr", "rrrs");
    x = x.replace("ss", "");
  }
  return x;
}

J, 23 bytes
~:/I.@,~4|[:-/1#;._1@,]

Try it online!
Takes a boolean vector where 0 represents r and 1 represents s, and returns the result in the same encoding.
How it works
Imagine evaluating the chunks of \$r^n s r^m s\$ from the start. If we evaluate \$sr\$ in the middle \$m\$ times, we get \$r^{n+3m}s^2 = r^{n+3m}\$. We can repeat the process to the end. Let's represent the input as a sequence of integers which represent the number of \$r\$'s when separated by \$s\$'s, like sssrrr -> [0, 0, 0, 3]. Then the following holds:

The alternating sum ([a, b, c, d, ...] -> a - b + c - d + ...) modulo 4 is the final number of \$r\$'s.
The length plus 1 modulo 2 is the final number of \$s\$'s.

~:/I.@,~4|[:-/1#;._1@,]  NB. Input: a boolean vector
              1#;._1@,]  NB. Get the lengths of runs of r's between s's
        4|[:-/  NB. Alternating sum modulo 4 = the number of final r's
~:/             NB. Reduction by unequal on the original input,
                NB. i.e. the number of s's in the input mod 2
                NB. = the number of final s's
   I.@,~        NB. Reverse concat and generate that many 0's and 1's

Jelly, 15 bytes
ṣ1ẈṚḅ3%4,SḂ$Ø.x

Try it online!
Same algorithm as above. Doesn't feel well golfed to me though; maybe I missed some good alternative built-ins.
ṣ1ẈṚḅ3%4,SḂ$Ø.x  Input: a list of zeros and ones
s1Ẉ              Split at ones, then get length of each chunk
   Ṛḅ3%4         Reverse, evaluate in base 3, modulo 4
        ,        Pair with...
         SḂ$     Sum % 2
            Ø.x  Generate that many zeros and ones respectively


Write the longest sentence using keywords of a programming language As the title said, the challenge is to write the longest sentence by only using the keywords of 1 programming language.

For instance, using the keywords of C++, it is possible to write this sentence:

  do not try this float

What can you come up with?

C++, 25 unique words, 28 total

  True friend, do goto register for this new short public class for
  private auto operator (while inline, return this signed template),
  else break & void this long volatile union.


Champernowne up to me Inspired by this question.

Champernowne's constant is an infinite decimal number that consists of "0." followed by all natural numbers concatenated together.  It begins like so: 0.123456781011121314151617181920212223242526272829303132333435363738394041424344454647484950, etc. The digits of Chamernowne's constant are sequence A033307 in the OEIS.

Your Task:

Write a program or function that, when given an integer as input, outputs/returns Champernowne's constant up to the first occurance of the input.  For example, if the input is 13, you should output 0.12345678910111213.  If you wish, for inputs greater than 0, you may drop the leading "0." in your output.

Input:

An integer, or a string containing only numbers.

Output:

Champernowne's constant up to the first occurance of the input.

Test Cases:

0   -> 0
1   -> 0.1 OR 1
14  -> 0.1234567891011121314 OR 1234567891011121314
91  -> 0.1234567891 OR 1234567891
12  -> 0.12 OR 12
101 -> 0.123456789101 OR 123456789101

Scoring:

This is code-golf, lowest score in bytes wins!

05AB1E, 6 bytes

Code

LJ¹¡н«

Uses the 05AB1E encoding. Try it online!

Explanation

L         # Create the range [1, 2, ..., input]
 J        # Join into a single string
  ¹¡      # Split at occurences of the input
    н     # Take the first element
     «    # Append the input to the first element and implicitly output


Sort an Option String Background

In C, there is a function to help parse command-line arguments: getopt.

Getopt takes the argument count (argc), the argument list (argv), and a string representing the options the program should take (optstring).

The option string (optstring) is a series of option characters each followed by one colon (for an option requiring an argument), two colons (for an option with an optional argument), or zero colons (for an option without an argument).

For example: one might use the following option string for their company's new widget.

"v::x:hy:S:G::dns:f::"

But that looks horrible! The options are all mixed together! This option string would look much better if it were sorted:

"f::G::v::S:s:x:y:dhn"

Specifications

The input will be a string matching the regular expression ([A-Za-z]:{0,2})+
You should take input as a string or list of characters.
You should output the string sorted by the method detailed below.
You do not need to handle empty input.
You do not need to handle input with repeated options of the same type ("aa" is not valid, but "aa:a::" is valid).

Sorting Method

In the sorted option string:

The characters followed by two colons come first, sorted alphabetically, with uppercase letters before their respective lowercase letters (i.e. "aBb", not "Bab").
Then are the characters with one colon, sorted alphabetically, with uppercase letters before their respective lowercase letters.
Last are the characters with no colon, sorted alphabetically, with uppercase letters before their respective lowercase letters.

Rules

Standard Loopholes are forbidden.

Scoring

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

Examples

# "input" => "output"
"v::x:hy:S:G::dns:f::" => "f::G::v::S:s:x:y:dhn"
"aa:a::" => "a::a:a"
"B:" => "B:"
"Confusio:n::" => "n::o:Cfinosu"
"Confusio:n:" => "n:o:Cfinosu"
"m:qW:X:xc:vViI" => "c:m:W:X:IiqVvx"
"V:omo:V" => "o:V:moV"
"agg:ra:va::ting::" => "a::g::a:g:aginrtv"
"input" => "inptu"

Long test case (312 characters)

Invaid Inputs (you don't have to handle):

"gg" (duplicated option)
"" (empty string)
":w:" (first colon isn't after a character)
"x:y:0:fhn" ('0' is not alphabetic)
"A:::" (3 colons is invalid)

Husk, 11 bytes

ΣÖom_↔Oġλ¬√

Try it online!

Explanation

ΣÖom_↔Oġλ¬√  Implicit input, say "kH::r:R:Hk:"
       ġ     Split between characters for which this gives a falsy result:
        λ      Take two arguments, ignore the first.
          √    Is the second argument a letter?
         ¬     Negate.
             Now we have the options: ["k","H::","r:","R:","H","k:"]
      O      Sort: ["H","H::","R:","k","k:","r:"]
 Ö           Sort by
     ↔       reversing and
  om_        converting everything to lowercase: ["H::","k:","R:","r:","H","k"]
Σ            Concatenate: H::k:R:r:Hk


Passwords Strong Against Bishops Not to be confused with Password Bishop Goodness!

Given a string, answer (truthy/falsy or two consistent values) if it constitutes a password which is strong against bishops.

A password is strong against bishops if it is a string consisting of alternating letters (in a-h) and digits (in 1-8) such that each pair of characters can be interpreted as a square on a chessboard, and if you place a white pawn on each square named in the password, then there is no way for a white bishop to travel, in any number of consecutive moves, from any square in the first (1) row to any square in the last (8) row.

Examples

Passwords strong against bishops

a1b1c1d1e1f1g1h1
a8b8c8d8e8f8g8h8
a1b2c3d4d5f5f4g3g4h2b5
h4g4f4e4c4b4a4c3e3
a1b1c1d1e1f1g1a8b8c8d8e8f8g8
b4b5d4d5f4f5g3h5

   For example, a1b1c1d1e1f1g1a8b8c8d8e8f8g8 corresponds to the position  and b4b5d4d5f4f5g3h5 corresponds to the position

Passwords weak against bishops

a4c4e4g4g5d6f6e3d2b2 (well-formed but not strong — thanks Jo King for this example!)
b1c1d1e1f1g1h1a8b8c8d8e8f8g8 (well-formed but not strong)
h4g4f4e4c4b4a4c3 (well-formed but not strong)
d4 (well-formed but not strong)
b4b5d4d5f4f5g2h5 (well-formed but not strong)
correct horse battery staple (ill-formed)
1a1b1c1d1e1f1g8a8b8c8d8e8f8g (ill-formed)
a (ill-formed)
aa (ill-formed)

Ruby, 115 182 163 bytes

->s{z=('00'..'99').map{|x|x=~/[09]/||s[(x[1].ord+48).chr+x[0]]};(11..18).map &g=->x{z[x]||[x-11,x-9,x+z[x]=9,x+11].map(&g)};s=~/^([a-h][1-8])*$/&&(z[81,9]-[9])[8]}

Try it online!

Returns 1 for strong and nil for weak. (The +67 bytes was for taking into account "backtracking.")

->s{
 z=                             # this is the board
 ('00'..'99').map{|x|           # coordinates are described as y*10 + x
  x=~/[09]/||                   # truthy if out of bounds...
  s[(x[1].ord+48).chr+x[0]]     # ...or impassable
 }                              # now only the passable squares are falsey
 (11..18).map                   # for each x position at y=1,
  &g=->x{                       # call helper function on that square
   z[x]||                       # if the square is passable (i.e. falsey),
    [x-11,x-9,x+z[x]=9,x+11]    # mark it impassable by setting to 9 (truthy)
     .map(&g)                   # call helper recursively for each neighbor
  }
 s=~/^([a-h][1-8])*$/           # make sure the input was valid,
 &&(z[81,9]-[9])[8]             # and check that the last row was never reached
}

A few tricks that were used:

Instead of the numerical range 0..99, we use the string range '00'..'99' so that the number is automatically left-padded to 2 digits and stringified. This makes out of bounds checking very short -- match with regex /[09]/.
Inside the helper function, while building the list of new coordinates [x-11, x-9, x+9, x+11], we simultaneously assign z[x] to 9 in the process, which happens to be a truthy value (marking the square visited).
In the last line, we want to check that the array z[81,9] does not contain 9. We do this by removing all instances of 9 (z[81,9]-[9]), then asking for the 9th element of the resulting array ([8]). Since we know the array originally had 9 elements, if any were removed, we'll get nil, whereas if they all remained, we'll get the last element of the array (which happens to always be 1).


Fastest algorithm for decomposing a perfect power A perfect power is a positive integer that's equal to one positive integer, to the power of another positive integer (e.g. ab is a perfect power). Note that trivial solutions (e.g. b=1) are excluded; specifically, the definition requires a ≥ 2 and b ≥ 2.

The task

Write a full program that takes any number of positive integers (separated by newlines) from standard input, and for each such input n, outputs all pairs of positive integers a, b (with a ≥ 2 and b ≥ 2) such that ab = n. Use the syntax a^b for these pairs. If multiple pairs of outputs are possible for a given input, print all of them, separated by spaces.

Note the victory condition below: the aim here is to optimize the program for speed, not size.

Example test cases

Input

 1745041
 1760929
 1771561
 1852321
 1868689
 1874161
 1885129
 1907161
 1953125
 113795717542678488615120001
 113795717546049421004105281

Output

 1745041 = 1321^2
 1760929 = 1327^2
 1771561 = 11^6 121^3 1331^2
 1852321 = 1361^2
 1868689 = 1367^2
 1874161 = 37^4 1369^2
 1885129 = 1373^2
 1907161 = 1381^2
 1953125 = 5^9 125^3
 113795717542678488615120001 = 10667507560001^2
 113795717546049421004105281 = 10667507560159^2

Clarifications

No more than 10000 inputs will be given on any single run of the program.
Your program, as written, should be able to handle numbers up to at least 30 digits long (meaning you will likely need to use bignum support). In order for the victory condition to be meaningful, though, the underlying algorithm behind your submission must be capable of working for arbitrary perfect powers, no matter how large they are.
Each input n will actually be a perfect power, i.e. there will always be at least one output corresponding to each given input.
There are no restrictions on programming language (as long as the language has sufficient power to complete the task).

Victory condition

The program with the fastest algorithm (i.e. with the fastest complexity) will be the winner. (Note that the fastest known perfect power decomposition algorithms can determine whether a number is a perfect power, and what the base and exponent are, without having to actually factorise the number; you may want to take this into account when choosing the algorithm for your problem.)

In the case that two programs are equally fast by this measure, the tiebreak will be to see which program runs faster in practice (on the stated testcases or, to avoid hard-coding, a similar set of test cases).

Python, 207 chars

This takes O(log2 N) bigint ops.  O(log N) different exponents to try, and O(log N) binary search to find each base.

import sys
for N in map(int,sys.stdin.readlines()):
 p,s=2,''
 while 1<<p<=N:
  i,j=2,N
  while j>i+1:
   m=(i+j)/2
   if m**p>N:j=m
   else:i=m
  if i**p==N:s+=' %d^%d'%(i,p)
  p+=1
 if s:print N,'=',s[1:]


Gerrymander North Carolina The challenge

How well can you gerrymander North Carolina into 13 voting districts?

In this challenge, you use the following files to draw different maps for Republicans and Democrats.

File 1: NC_2016_presidential_election.csv

File 2: NC_county_adjacency.csv

File 1 gives county-level voting data from the 2016 presidential election (based on this and that), while File 2 gives adjacency information between counties (based on this). For File 2, the first entry of each row is adjacent to the other entries in that row. For example, Alexander is adjacent to Alexander, Caldwell, Catawba, Iredell and Wilkes. (Note that every county is adjacent to itself.)

Admissibility

Your code should be written in a way that can gerrymander arbitrary maps. In particular, your code must take each of the following as inputs:

A set \$C\$ of counties and a set \$P\$ of parties.
Weights \$(v_{cp})\$ that count voters in county \$c\in C\$ who vote for party \$p\in P\$. (E.g., File 1.)
A connected graph \$G\$ with vertex set \$C\$. (E.g., File 2.)
A number of districts \$k\$.
A party \$p^\star\in P\$ to gerrymander in favor of.

The output must be an assignment of counties to districts such that the counties in each district induce a connected subgraph of \$G\$. For example, for the counties in Files 1 and 2 (listed in alphabetical order), the following is one of 13! sequences that specify the partition of counties into districts pictured below:

3,5,5,10,5,5,13,11,10,8,9,12,1,12,13,13,3,9,3,12,13,12,9,8,13,10,13,13,4,4,8,11,11,5,7,9,11,12,11,13,4,11,7,12,12,11,1,13,4,12,7,13,3,13,9,12,12,11,12,2,12,1,1,7,8,11,13,3,13,13,8,13,3,11,9,3,10,10,3,1,9,8,10,1,5,5,12,12,13,10,11,6,11,11,5,8,5,7,5,12

(This map is loosely based on the current map of U.S. congressional districts in North Carolina.)

Scoring

Your score is determined by how your code performs for various problem instances.

Given a district assignment, let \$d\$ denote the number of districts for which party \$p^\star\$ receives the plurality of votes cast, and let \$a\$ and \$b\$ denote the minimum and maximum number of voters in a district, respectively. Then the score for the district assignment is given by

$$ \text{assignment score} = d - \frac{b}{a}. $$

For example, if \$p^\star\$ is the Republican party, then the district assignment described above has \$d=10\$, \$a=247739\$, and \$b=527337\$, leading to a score of about \$7.87\$.

To compute your score, gerrymander North Carolina (as specified in Files 1 and 2) into \$k=13\$ districts in favor of the Republican party, and then in favor of the Democratic party. Let \$S_1\$ denote the sum of these two assignment scores. Next, gerrymander 10 different modifications of North Carolina, each obtained by removing one of the following counties from Files 1 and 2:

Cleveland,Davidson,Hyde,Johnston,Madison,Montgomery,Pender,Scotland,Warren,Wilkes

(Since North Carolina is biconnected, each of these are acceptable problem instances.) For each modification, gerrymander into \$k=13\$ districts in favor of the Republican party, and then in favor of the Democratic party. Let \$S_2\$ denote the sum of these 20 assignment scores. Then the score of your submission is given by

$$ \text{submission score} = S_1+\frac{S_2}{10}. $$

In addition to your code, you are encouraged to provide an illustration of your two maps that gerrymander all of North Carolina for Republicans and for Democrats. (DRA2020 might be a helpful resource.)

C++, score = 33.526203, all test cases in 2min34s
(of course, the score can be improved by running the program for more time; please do not do that to claim a victory or something)
That score is usually 11 won districts for the Republicans and from 9 to 11 for the Democrats.
In this revision, the score decreased significantly, because I found some really large bugs in the input parsing. My program also verifies its solution now.
//#define _GLIBCXX_DEBUG
#include <iostream>
#include <streambuf>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <bitset>
#include <cassert>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
#include <climits>
#include <random>
#include <set>
#include <map>
#include <deque>
#include <string>

constexpr uint64_t rotl(uint64_t x, char k)
{
    return (x<<k) | (x>>(64-k)); //typo of the day: replace the >> with <<
}
uint64_t xs128()
{
    static uint64_t s_0 = 0, s_1 = 1;
    const uint64_t s0 = s_0;
    uint64_t s1 = s_1;
    uint64_t res = s0 + s1;
    s1 ^= s0;
    s_0 = rotl(s0, 24) ^ s1 ^ (s1 << 16);
    s_1 = rotl(s1, 37);
    return res >> 4;
}
std::vector<std::string> getCsvLine(std::istream& str)
{
    https://stackoverflow.com/a/1120224 - saved some time writing a parser...
    std::vector<std::string> result;
    std::string line; std::getline(str,line);
    std::stringstream lineStream(line);
    std::string cell;
    while(std::getline(lineStream,cell, ','))
        result.push_back(cell);
    return result;
}
struct county
{
    int good = 0;
    int sum = 0;
    std::vector<int> others;
    std::string name;
};
struct district
{
    int good = 0;
    int sum = 0;
    std::vector<int> others;
    void operator += (county& rhs)
    {
        good += rhs.good; sum += rhs.sum;
        for(int i = 0; i < others.size(); i++)
            others[i] += rhs.others[i];
    }
    void operator -= (county& rhs)
    {
        good -= rhs.good; sum -= rhs.sum;
        for(int i = 0; i < others.size(); i++)
            others[i] -= rhs.others[i];
    }
};
//seems like exactly 100 districts exist, below CHAR_MAX
std::vector<std::vector<char>> graph;
std::vector<char> curdistrict;
std::vector<county> counties;
std::vector<district> districts;
std::vector<char> marks;
bool pluralityCheck(const district& d)
{
    return d.good > *std::max_element(d.others.begin(), d.others.end());
}
int n, k, excluded;
double getFitness(std::vector<char>& dmap)
{
    std::vector<district> districts(k);
    for(district& d : districts)
        d.others.resize(counties[excluded==0?1:0].others.size());
    for(int i = 0; i < n; i++)
        if(i != excluded) districts[dmap[i]] += counties[i];
    double score = 0;
    int min = INT_MAX, max = INT_MIN;
    for(int i = 0; i < k; i++)
        score += pluralityCheck(districts[i]),
        min = std::min(min, districts[i].sum), max = std::max(max, districts[i].sum);
    score -= double(max) / min;
    return score;
}
void dfs(char v, char color)
{
    marks[v] = color;
    for(int to : graph[v])
        if(marks[to] != color && curdistrict[to] == curdistrict[v])
            dfs(to, color);
}
bool dfsFor(char at, char target, char color)
{
    marks[at] = color;
    if(at == target) return true;
    if(at == excluded) return false;
    bool ans = false;
    for(int to : graph[at])
        if(marks[to] != color && curdistrict[to] == curdistrict[at])
            ans |= dfsFor(to, target, color);
    return ans;
}
bool isCutpoint(int v)
{
    static int call = 0;
    char color = call + 1;
    call = (call + 1) % 255;
    if(color == 1) for(char& el : marks) el = 0; //reset every 256 calls
    marks[v] = color;
    int calls = 0;
    for(char to : graph[v])
    {
        if(curdistrict[to] != curdistrict[v]) continue;
        if(marks[to] == color) continue;
        calls++;
        if(calls == 2) break;
        dfs(to, color);
    }
    return calls != 1; //0 -> kills a district, >=2 -> a cutpoint -> splits a district
}
std::map<std::string, int> dnamemap;
double solve(int n, int k, int target, int excluded)
{
    ::n = n; ::k = k; ::excluded = excluded;
    marks = std::vector<char>(n);
    curdistrict = std::vector<char>(n, -1); graph = std::vector<std::vector<char>>(n);
    districts = std::vector<district>(k); counties = std::vector<county>(n);
    dnamemap = std::map<std::string, int>();
    std::ifstream data("NC_2016_presidential_election.csv");
    getCsvLine(data); //skip header
    for(int i = 0; i < n; i++)
    {
        std::vector<std::string> row = getCsvLine(data);
        dnamemap[row[0]] = i;
        counties[i].name = row[0];
        if(i == excluded) continue;
        for(int j = 1; j < row.size(); j++)
        {
            int v = std::stoi(row[j]);
            if(j - 1 == target)
                counties[i].good = v;
            else counties[i].others.push_back(v);
            counties[i].sum += v;
        }

    }
    data = std::ifstream("NC_county2.csv"); //no header
    //NC_county2.csv is obtained by cat NC_county_adjacency.csv | sort | tr -d '\r'
    //the default counties file caused not one but TWO horrible parsing bugs
    //they silently increased the score.
    //There were \r\n line endings instead of \n, and my program mishandled them.
    //and *the worst*. It seems to be in alphabetic order, but it actually simply isn't.
    for(int i = 0; i < n; i++)
    {
        std::vector<std::string> row = getCsvLine(data);
        if(i == excluded) continue;
        for(int j = 1; j < row.size(); j++)
        {
            if(row[j] == row[0]) continue;
            int to = dnamemap[row[j]];
            if(to == excluded) continue;
            graph[i].push_back(to);
        }
    }
    for(district& d : districts)
        d.others.resize(counties[excluded==0?1:0].others.size());
    int di = 0;
    for(int i = 0; di < k; i++) if(i != excluded) curdistrict[i] = di++;
    for(int it = n; it --> 0;)
        for(int i = 0; i < n; i++)
        {
            if(i == excluded || curdistrict[i] != -1) continue;
            for(int to : graph[i])
            {
                if(to == excluded || curdistrict[to] == -1) continue;
                curdistrict[i] = curdistrict[to];
                break;
            }
        }
    if(excluded >= 0) curdistrict[excluded] = -1;
    for(int i = 0; i < n; i++) printf("%d ", curdistrict[i]);
    printf("%d\n", excluded);
    for(int i = 0; i < n; i++) if(excluded != i) districts[curdistrict[i]] += counties[i];
    double temp = 3;
    int its = 2e7;
    std::vector<char> bestplacement = curdistrict;
    std::vector<district> bestdistricts = districts;
    int lastimprovement = 0;
    double bestscore = getFitness(curdistrict);
    int perblock = 2e4; //max number of iterations without improvement
    double delta = 1.01 * temp / its;
    double curscore = bestscore;
    double withoutimprovement = 0;
    for(int it = 0; it < its; it++)
    {
        temp -= delta;
        if(it % 1048576 == 0)
            printf("it=%d, cs=%lf       \r", it, curscore);
        int i = xs128() % n;
        while(i == excluded) i = xs128() % n;
        if(isCutpoint(i)) continue; //<- around 50% of program time
        std::vector<int> nearby;
        bool ok = false;
        for(int to : graph[i])
            if(curdistrict[to] != curdistrict[i] && curdistrict[to] != -1) ok = true;
        if(!ok) continue;
        int nd = -1;
        while(nd == curdistrict[i] || nd == -1)
            nd = curdistrict[graph[i][xs128() % graph[i].size()]];
        //calculate new min size, new max size etc.
        //can be done via std::set and other tree-based stuff, but it's much simpler to use a normal arrays (for k=13)
        //*might* use a segment tree to optimize later, but it's not spending a lot of time here
        char oldmaj1 = pluralityCheck(districts[curdistrict[i]]);
        char newmaj1 = pluralityCheck(districts[nd]);
        int maxs = INT_MIN, mins = INT_MAX;
        for(int i = 0; i < k; i++)
            maxs = std::max(maxs, districts[i].sum), mins = std::min(mins, districts[i].sum);
        double pen1 = double(maxs) / mins;
        districts[curdistrict[i]] -= counties[i];
        districts[nd] += counties[i];
        char oldmaj2 = pluralityCheck(districts[curdistrict[i]]);
        char newmaj2 = pluralityCheck(districts[nd]);
        maxs = INT_MIN, mins = INT_MAX;
        for(int i = 0; i < k; i++)
            maxs = std::max(maxs, districts[i].sum), mins = std::min(mins, districts[i].sum);
        double pen2 = double(maxs) / mins;
        double delta = pen1 - pen2 + (oldmaj2 + newmaj2 - oldmaj1 - newmaj1);
        if(delta <= 0 && (temp <= 0 || ldexpf(std::exp(delta / temp), 60) < xs128()))
        {
            districts[nd] -= counties[i], districts[curdistrict[i]] += counties[i];
        }
        else
        {
            curdistrict[i] = nd;
            curscore += delta;
            if(curscore > bestscore)
            {
                bestscore = curscore; lastimprovement = it;
                bestplacement = curdistrict; withoutimprovement = 0;
                bestdistricts = districts;
            }
        }
        if(curscore < bestscore) withoutimprovement += bestscore - curscore;
        if(it - lastimprovement > perblock || withoutimprovement > 3e4)
        {
            //restart at best score so far
            withoutimprovement = 0;
            lastimprovement = it;
            curdistrict = bestplacement;
            districts = bestdistricts;
            curscore = bestscore;
        }
    }
    for(int i = 0; i < n; i++)
        printf("%d ", curdistrict[i]);
    printf("\n");
    for(district& d : districts)
    {
        printf("%d total, maj=%d, %d good; rest:", d.sum, (int)pluralityCheck(d), d.good);
        for(int el : d.others) printf(" %d", el);
        printf("\n");
    }
    for(int i = 0; i < n; i++) //verify validness
    for(int j = i+1; j < n; j++)
    {
        if(i == excluded || j == excluded) continue;
        if(curdistrict[i] != curdistrict[j]) continue;
        for(char& el : marks) el = 0;
        bool good = dfsFor(i, j, 1);
        if(!good) printf("invalid: i=%d, j=%d, d=%d!\n", i, j, curdistrict[i]);
    }
    double score = getFitness(curdistrict);
    printf("%lf\n", score);
    return score;
}
int main()//int64_t argc, char*argv[])
{
    //randomly choose and recolor vertices
    //do not recolor a vertex if it is a cutpoint (more known as an articulation point or cut vertex) or alone
    //to check, DFS over same-colored vertices from it. If != 1 calls were done, it's alone or a cutpoint
    //initial state: all counties belong to district 0, but first 13 belong to district i (dumb but why bother)
    //for each district maintain the voters for both parties and total number
    //oh, and don't merely randomly recolor: use Simulated Annealing (TM) (it actually improves a lot!)
    setbuf(stdout, 0);
    int k = 13, n = 100;
    std::vector<int> toExclude { -1, 22, 28, 47, 50, 57, 61, 70, 82, 92, 97 }; //the final score computing
    //std::vector<int> toExclude { -1 };
    double score = 0;
    for(int el : toExclude)
    {
        double s = 0;
        s += solve(n, k, 0, el);
        s += solve(n, k, 1, el);
        if(el == -1) score += s;
        else score += s / 10;
    }
    printf("%lf\n", score);
}

Uses (attempts to use) simulated annealing to improve from a dumb assignment by making random changes if they do not ruin things (that is, destroy or split districts). Restarts from the best known assignment when either 20000 iterations passed without an improvement or the accumulated difference between the best score and the current score since the last improvement exceeds 30000.
Can be compiled with clang++ hax.cpp -Ofast -march=native -flto -no-pie -o a.out. Assumes files NC_2016_presidential_election.csv and NC_county2.csv are in the current directory, where NC_county2.csv is the NC_county_adjacency.csv, but with its lines actually sorted in alphabetical order, and with Unix (\n) line endings.
Quoting from the question, "you are encouraged to provide an illustration". I am definitely encouraged (I would really like to know whether or not the code has no bugs), but I have no idea how to create an illustration. I also have no idea how to export the output into a format readable by the linked website.
Assignment information on the normal map for the Democrats, then for the Republicans:

begin assignment for target=0, excluded=-1
Alamance,4
Alexander,8
Alleghany,8
Anson,12
Ashe,8
Avery,5
Beaufort,6
Bertie,6
Bladen,9
Brunswick,9
Buncombe,5
Burke,10
Cabarrus,8
Caldwell,8
Camden,7
Carteret,9
Caswell,0
Catawba,10
Chatham,12
Cherokee,10
Chowan,7
Clay,10
Cleveland,10
Columbus,2
Craven,9
Cumberland,2
Currituck,7
Dare,7
Davidson,12
Davie,8
Duplin,6
Durham,12
Edgecombe,6
Forsyth,3
Franklin,7
Gaston,10
Gates,7
Graham,10
Granville,0
Greene,6
Guilford,4
Halifax,7
Harnett,12
Haywood,10
Henderson,10
Hertford,7
Hoke,2
Hyde,7
Iredell,8
Jackson,10
Johnston,12
Jones,6
Lee,12
Lenoir,6
Lincoln,11
Macon,10
Madison,10
Martin,6
McDowell,5
Mecklenburg,11
Mitchell,5
Montgomery,12
Moore,12
Nash,7
New Hanover,9
Northampton,7
Onslow,9
Orange,0
Pamlico,9
Pasquotank,7
Pender,9
Perquimans,7
Person,0
Pitt,6
Polk,10
Randolph,4
Richmond,12
Robeson,2
Rockingham,0
Rowan,8
Rutherford,10
Sampson,9
Scotland,2
Stanly,8
Stokes,0
Surry,3
Swain,10
Transylvania,10
Tyrrell,7
Union,8
Vance,7
Wake,1
Warren,7
Washington,6
Watauga,5
Wayne,9
Wilkes,8
Wilson,6
Yadkin,8
Yancey,10
end assignment for target=0, excluded=-1
begin assignment for target=1, excluded=-1
Alamance,0
Alexander,1
Alleghany,11
Anson,7
Ashe,11
Avery,10
Beaufort,6
Bertie,6
Bladen,8
Brunswick,12
Buncombe,10
Burke,10
Cabarrus,7
Caldwell,11
Camden,9
Carteret,6
Caswell,0
Catawba,1
Chatham,2
Cherokee,4
Chowan,9
Clay,4
Cleveland,4
Columbus,12
Craven,9
Cumberland,8
Currituck,6
Dare,6
Davidson,0
Davie,7
Duplin,9
Durham,0
Edgecombe,9
Forsyth,1
Franklin,6
Gaston,4
Gates,9
Graham,10
Granville,6
Greene,6
Guilford,11
Halifax,6
Harnett,8
Haywood,10
Henderson,4
Hertford,9
Hoke,2
Hyde,6
Iredell,7
Jackson,4
Johnston,8
Jones,9
Lee,2
Lenoir,9
Lincoln,10
Macon,4
Madison,10
Martin,9
McDowell,10
Mecklenburg,5
Mitchell,10
Montgomery,2
Moore,2
Nash,9
New Hanover,12
Northampton,9
Onslow,12
Orange,2
Pamlico,9
Pasquotank,6
Pender,12
Perquimans,6
Person,0
Pitt,6
Polk,4
Randolph,0
Richmond,7
Robeson,8
Rockingham,0
Rowan,2
Rutherford,4
Sampson,12
Scotland,2
Stanly,2
Stokes,11
Surry,11
Swain,10
Transylvania,4
Tyrrell,6
Union,7
Vance,6
Wake,3
Warren,9
Washington,6
Watauga,11
Wayne,9
Wilkes,1
Wilson,9
Yadkin,1
Yancey,10
end assignment for target=1, excluded=-1


Sort all the pixels of an image by the number of occurrences Input

The name of a file in the raster graphics format of your choice. The chosen format must support at least 8 bits per channel and 3 channels.

Output

A file in the same format, with the same dimensions and pixels as the first, but whose pixels are grouped in descending order of the number of times they occur, sorted from left-to-right, top-to-bottom.

If certain colours of pixels appear the same number of times, their order is unspecified.
You must not overwrite the input file (use a different file name for the output).
Any and all third-party image processing libraries are permitted.

Example

Will give output similar to:

Especially in the lower parts of the image some variation may occur, due to different tie breaking between colours of equal frequency.

Mathematica, 125 123 bytes

Export["a"<>#,i=ImageData@Import@#;Image@ArrayReshape[Join@@ConstantArray@@@SortBy[Tally[Join@@i],-Last@#&],Dimensions@i]]&

This defines an unnamed function which takes the file name in any common image format and writes the result to the a file with the same name but prepended with a. The result looks a bit different from the OP's, since Mathematica's SortBy breaks ties by default sort order, so the bottom bits where loads of ties occur look a bit neater:

The implementation itself is really straightforward:

ImageData to get a grid of colour values.
Join to flatten the array.
Tally to count the occurrence of each colour.
SortBy[...,-Last@#&] to sort by frequencies from highest to lowest.
ConstantArray and Join to expand the tallies again.
ArrayReshape to recover the original image shape (obtained with Dimensions).
Image to convert the data back to an image object.

FYI, 22 bytes are used on file I/O. An equivalent version that takes and returns an image object comes in at 103 bytes:

(i=ImageData@#;Image@ArrayReshape[Join@@ConstantArray@@@SortBy[Tally[Join@@i],-Last@#&],Dimensions@i])&


Tips for golfing in Lisp What general tips are these for golfing in Lisp (any dialect)? Please post one tip per answer, and only answers that are specific to a dialect of Lisp (e.g. "remove comments" is not an answer).

Please post the dialect of Lisp your tip applies to with your tip.

Order function parameters to minimize whitespace
Instead of
(defun f(a b)(...))
...
(f x(1+ y))

try something like
(defun f(b a)(...))
...
(f(1+ y)x)


Using the smallest number of bytes of code, write a program that produces this image Context:

Gynvael Coldwind, a famous security researcher, published a contest in his blog post (that is now complete). The goal was similar to the one described here, but with certain restrictions depending on which of the three allowed programming languages was chosen. I found the exercise fun and wanted to extend the challenge to all programming languages allowed.

Goal:

The goal of this golf is to write a program as short as possible that generates a PNG file which, after converting to bitmap shares the same resolution and pixel color values as the following image (alternate link, SHA256: ab18085a27c560ff03d479c3f32b289fb0a8d8ebb58c3f7081c0b9e1895213b6):

Rules:

The program must work offline, i.e. when the language runtime/interpreter is installed, no internet connectivity is installed to build/run the program,
The program may not rely on any external libraries (only use standard library of your language, as opposed to adding libraries from pip/npm/cargo/maven/whatever repositories),
The program must complete its operation within 60 seconds on a regular desktop computer (i.e. no brute-forcing the results).

C#, 849 793 771 bytes

using System;using System.Drawing;using System.IO;class P{static void Main(){dynamic x,y,i=new Bitmap(Bitmap.FromStream(new MemoryStream(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAGAAAAA2BAMAAADKYYHhAAAAGFBMVEUAAABdAgSMAwb///+jBAfFgYLRgYOugIE5HrT9AAAA20lEQVR4AWKgHIwCQThAFmVECAsA2qsDk4qBGIzjD7qAn5ngvlvAJJ3AdyscTqAr3PqaQwMgVYATKvQPlED5kQaAng2QBVnoCywBVeFQqKu6im83gcP1GFgVqEMVqiIP25MIzRjlmgSPZNufK/Qj1wC+bSKk2w/gHkDUaFZrEXht+85jcDc6FAHcqgsqvX3fkCxfcFZiaK3xL8EckS0ArfVO8u31C4y+FAQBBgbLAOYE9v8HxgDAgiiPXgk6gPykz8ctOzPIgHl0f8mjB1aDGQuyxeDgx3KB37t6B3NXgUgfIi7ZAAAAAElFTkSuQmCC"),0,312))),d=new Bitmap(1920,1080),g=Graphics.FromImage(d);for(y=0;y<54;y++)for(x=0;x<96;x++)g.FillRectangle(new SolidBrush(i.GetPixel(x,y)),new Rectangle(x*20,y*20,20,20));d.Save("s.png");}}

Tested with the following code:

class P
{
    static void Main()
    {
        Bitmap a = new Bitmap(@"c:\projects\confidence_2019_golf.png");
        Bitmap b = new Bitmap(@"c:\projects\s.png");

        Console.WriteLine(a.Width + ", " + b.Width);
        Console.WriteLine(a.Height + ", " + b.Height);

        for (int y=0; y<a.Height; y++)
        {
            for (int x=0; x<a.Width; x++)
            {
                Color ca = a.GetPixel(x, y);
                Color cb = b.GetPixel(x, y);

                if (ca.R != cb.R || ca.G != cb.G || ca.B != cb.B)
                {
                    Console.WriteLine(x + ", " + y);
                    Console.WriteLine(ca.R + ", " + ca.G + ", " + ca.B);
                    Console.WriteLine(cb.R + ", " + cb.G + ", " + cb.B);
                }
            }
        }
    }
}

Ungolfed:

using System;
using System.Drawing;
using System.IO;
class P
{
    static void Main()
    {
        dynamic x = 0;
        dynamic y = 0;
        dynamic b = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAGAAAAA2BAMAAADKYYHhAAAAGFBMVEUAAABdAgSMAwb///+jBAfFgYLRgYOugIE5HrT9AAAA20lEQVR4AWKgHIwCQThAFmVECAsA2qsDk4qBGIzjD7qAn5ngvlvAJJ3AdyscTqAr3PqaQwMgVYATKvQPlED5kQaAng2QBVnoCywBVeFQqKu6im83gcP1GFgVqEMVqiIP25MIzRjlmgSPZNufK/Qj1wC+bSKk2w/gHkDUaFZrEXht+85jcDc6FAHcqgsqvX3fkCxfcFZiaK3xL8EckS0ArfVO8u31C4y+FAQBBgbLAOYE9v8HxgDAgiiPXgk6gPykz8ctOzPIgHl0f8mjB1aDGQuyxeDgx3KB37t6B3NXgUgfIi7ZAAAAAElFTkSuQmCC");
        dynamic i = new Bitmap(Bitmap.FromStream(new MemoryStream(b, 0, 312)));
        dynamic d = new Bitmap(1920, 1080);
        dynamic g = Graphics.FromImage(d);
        for (y = 0; y < 54; y++)
        {
            for (x = 0; x < 96; x++)
            {
                g.FillRectangle(new SolidBrush(i.GetPixel(x, y)), new Rectangle(x * 20, y * 20, 20, 20));
            }
        }
        d.Save(@"c:\projects\s.png");
    }
}


Arithmetic Sequences An arithmetic sequence is a sequence of numbers of the form a,a+n,a+2n,a+3n, etc. In this case, a and n will both be either integers or decimals.

Given two inputs, a, n, and a top number value, return a list of numbers where the last term is less than or equal to the top number value.

The input can be formatted in any way, as well as the output.

The catch to this problem is dealing with floating point arithmetic errors.
For example, 0.1 + 0.3 * 3 is 1, however this will display 0.99999999999... if you simply go 0.1 + 0.3 * 3. We want 1, not 0.99999999999...

Test Cases

a=2, n=3, top=10: [2, 5, 8]
a=3, n=1.5, top=12: [3, 4.5, 6, 7.5, 9, 10.5, 12]
a=3.14159, n=2.71828, top=10: [3.14159, 5.85987, 8.57815]
a=0.1, n=0.3, top=2: [0.1, 0.4, 0.7, 1, 1.3, 1.6, 1.9]

Shortest code wins. Good luck!

Non-golfed haskell, 32

f a n t=takeWhile(<=t)[a,a+n..]

I'd love to change takeWhile to take, but integer division can't be done with /, it needs to be done with div. If I go with / then I need to do implicit conversion which makes it that much longer.


Generate n digits of Gijswijt's sequence Introduction

Gijswijt's sequence (A090822) is famously really, REALLY slow. To illustrate:

The first 3 appears in the 9th term (alright).
The first 4 appears in the 220th term (a long way away, but feasible).
The first 5 appears at (approximately) the 10^(10^23)th term (just no).
No one really even knows where the first 6 is... it's suspected it's at the...

2^(2^(3^(4^5)))th term.

You can assume that you won't have to deal with a two-digit number.

The sequence is generated like so:

The first term is 1.
Each term after that is the amount of repeating "blocks" previous to it (if there are multiple repeating "blocks", the largest amount of repeating blocks is used).

To clarify, here are the first few terms.

1 -> 1, 1 (one repeating block (1), so the digit recorded is 1)

1, 1 -> 1, 1, 2 (two repeating blocks (1), so the digit recorded is 2)

1, 1, 2 -> 1, 1, 2, 1 (one repeating block (2 or 1, 1, 2), so the digit recorded is 1)

1, 1, 2, 1 -> 1, 1, 2, 1, 1 (you get the idea)

1, 1, 2, 1, 1 -> 1, 1, 2, 1, 1, 2

1, 1, 2, 1, 1, 2 -> 1, 1, 2, 1, 1, 2, 2 (two repeating blocks (1, 1, 2), so the digit recorded is 2)

Task

Your task is, as stated in the question, to generate n digits of the Gijswijt sequence.

Instructions

The input will be an integer n.
Your code can output the digits in any form (a list, multiple outputs, etc.).

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

Pyth, 25 22 21 bytes

t_u+eSmtfxG*Td1._GGQN

OP confirmed that we only need to handle single-digit numbers. This allowed to store the list as a string of digits. -> Saved 3 bytes

Try it online: Demonstration

Explanation:

t_u+...GQN      implicit: Q = input number
         N      start with the string G = '"'
  u     Q       do the following Q times:
    ...            generate the next number
   +   G           and prepend it to G
 _              print reversed string at the end
t               remove the first char (the '"')

And here's how I generate the next number:

eSmtfxG*Td1._G
           ._G    generate all prefixes of G
  m               map each prefix d to:
    f     1          find the first number T >= 1, so that:
       *Td              d repeated T times
     xG                 occurs at the beginning of G
 S                  sort all numbers
e                   take the last one (maximum)

21 bytes with lists

_u+eSmhhrcGd8SlGGtQ]1

Try it online: Demonstration

Uses the same ideas of Martin and Peter. At each step I split the string into pieces of length 1, pieces of length 2, ... Then I range-length-encode them and use the maximal first run as next number.

20 bytes with strings

t_u+eSmhhrcGd8SlGGQN

Try it online: Demonstration

Combines the ideas of the two codes above.


Write a square program that outputs the number of times it has been "unrolled" Consider a square block of text, N characters wide by N tall, for some odd integer N greater than 1.

As an example let N = 5 and the text be:

MLKJI
NWVUH
OXYTG
PQRSF
ABCDE

Notice that this is the alphabet (besides Z) spiraled around counter-clockwise from the lower left corner. It's kind of like a rolled up carpet.

"Unrolling" the text by one quarter turn clockwise so FGHI are on the same level as ABCDE results in:

     PONM
     QXWL
     RYVK
     STUJ
ABCDEFGHI

This unrolling can be done 7 more times until the text is a single line:

         SRQP
         TYXO
         UVWN
ABCDEFGHIJKLM

             UTS
             VYR
             WXQ
ABCDEFGHIJKLMNOP

                WVU
                XYT
ABCDEFGHIJKLMNOPQRS

                   XW
                   YV
ABCDEFGHIJKLMNOPQRSTU

                     YX
ABCDEFGHIJKLMNOPQRSTUVW

                       Y
ABCDEFGHIJKLMNOPQRSTUVWX

ABCDEFGHIJKLMNOPQRSTUVWXY

Challenge

The challenge is to write a program that is an N×N block of text that outputs the number of times it has "unrolled" by a quarter turn when it is rearranged into the unrolling patterns and run.

There are really two contests here: (hopefully it won't be too messy)

Do this with the smallest N. (down to a limit of N = 3)
Do this with the largest N. (no limit)

There will not be an accepted answer but the winner in each of these categories will receive at least 50 bounty rep from me. In case of ties the oldest answers win.

Example

If your code block is

MyP
rog
ram

running it as is should output 0.

Running

   rM
   oy
ramgP

should output 1.

Running

     or
ramgPyM

should output 2.

Running

       o
ramgPyMr

should output 3.

Finally, running ramgPyMro should output 4.

Details

The output should be printed to stdout (or the closest alternative) by itself. There is no input.
You may only use printable ASCII (hex codes 20 to 7E, that includes space) in your code.
Spaces fill the empty space in the unrolling arrangements. (Unless you're unrolling to the left.)
Only the arrangements from completely square to completely flat need to have valid output. No other arrangements will be run.
You may not read your own source.
You may use comments.
N = 1 is excluded since in many languages the program 0 would work.
If desired you may unroll to the left rather than the right. So e.g.

MyP
rog
ram

becomes

Pg
yo
Mrram

and so on. No extra spaces are added when rolling this way. The lines just end

(Related: Write a Rectangular Program that Outputs the Number of Times it was Rotated)

Golfscript, N <- [5,7..]

.   .
 . .
 ..
.  .#
],9\-

Fully unrolled:

],9\-#  .   .  .  . . ...

Explanation:

. (multiple times) - duplicate the input
] - collect the stack into a single array
, - take its length
9\- - subtract it from 9
# - line comment

Whitespace is a NOP, but any other NOP would have worked just as well.

Fully rolled up, it uses nine copies of the input (contents ignored) as the stack; 9 - 9 = 0; it has not been unrolled.

Each unroll hides one more dot (duplicate) behind the comment, shrinking the stack once, incrementing the output.

Fully unrolled, it uses only the input (contents ignored) as the stack; 9 - 1 = 8; it has been unrolled 8 times.

The same approach works for any N > 4: Change 9 to the appropriate value of 2*N+1, then extend the pattern of dots (duplicate) using the same spiral pattern that ensures exactly one dot gets unrolled during each unroll.


Make a code square with your favorite word Pick your favorite 6 letter common English word that has no repeated letters, such as wombat.
Write a program in an N×N grid of characters without comments such that each row and column contains all the letters of your word in lowercase in any order. The program must output a definition of your word in 36 characters or more.
Rules

Output to stdout. There is no input.
Your word must be on Dictionary.com and only contain a-z. No proper nouns, no acronyms, no abbreviations, no contractions.
Your program and output may only contain printable ASCII characters (hex codes 20 to 7E). (This isn't counting the necessary newlines in the program grid.)
Comments are anything that the compiler or interpreter traditionally ignores. You may use code that does not contribute to the output or doesn't officially get executed.
The output definition should be grammatical and accurate, but certainly may be funny or clever.
Any row or column that at least contains your word`s 6 unique letters in lowercase is valid. Diagonals do not matter.

Scoring
This is code golf but since all submissions must be in the same square format you can simply specify your score with N. The lowest N wins, and of course an N below 6 is impossible. In case of ties, the highest voted answer wins.
Example
If your word was wombat your program might look like this (N = 7):
wombatD
ombatEw
mbatFwo
bat(wom
atWwomb
tBwomba
)wombat

Notice that every row and every column has the characters w o m b a t.
The output might be: (40 chararacters)
Cute short-legged Australian marsupials.

Javascript - action - 15x15
"Definetly not the shortest one, but PEW PEW PEW." - James Bond
ction="action "
ction+="means "
actionac="PEW "
ctionact="PEW "
tionacti="PEW "
ionactio="PEW "
onaction="PEW "
nactiona="PEW "
ction+=actionac
ction+=ctionact
ction+=tionacti
ction+=ionactio
ction+=onaction
ction+=nactiona
alert(""+ction)

Link to the jsfiddle
Output (37 chars):
action means PEW PEW PEW PEW PEW PEW


A greeting bot for a colleague from work I have a colleague at work that works from home every Tuesday and Thursday. At around 8:00 AM he sends us a message with the following text:

  Hello today I'm working from home

In order to relieve him from the burden of doing this every day he stays at home, we would like to automate this task for him.

The challenge

Write in as few bytes as possible a piece of code that:

Receives the current time: your code may receive values for the current year, month (1-12), day of month (1-31), hour (0-23) and minute (0-59) and the day of the week (you can choose whether this number starts from 0 or 1, and if 0/1 means Sunday, Monday or any other day); alternatively you may receive a structure such as Date, DateTime, Calendar or any other time-related structure, if your language allows it. You can also receive a string with the date in yyyyMMddHHmm if you want, or two separate strings for date and time, and then an integer with the day of week. Feel free.
Returns two consistent truthy and falsey values, indicating if the message must be sent to the work chat or not.

Rules

This piece of code is assumed to be invoked periodically. The exact periodicity is irrelevant, nonetheless.
The truthy value must be returned if the day of week is Tuesday or Thursday and the time is 8:00 AM with an error margin of 10 minutes (from 7:50 to 8:10 inclusive).
The truthy value must be sent only if it is the first time the code is invoked between those hours for the specified day. We don't want the bot to send the same message several times in a row. The way you manage this restriction will be entirely up to you.
Your code may be an independent program executed repeatedly or it may be part of a bigger code that is always running. Your choice.
You may assume that there will be no reboots between executions of the code.
You may assume that the date will always be correct.
Explanations about your code and specifically about the method used to achieve persistence are encouraged.

Examples

(Week starts on Monday: 1, the following invokations will be made in succession)
2018,08,27,08,00,1 = falsey (not Tuesday or Thursday)
2018,08,28,07,45,2 = falsey (out of hours)
2018,08,28,07,55,2 = truthy (first time invoked this day at the proper hours)
2018,08,28,08,05,2 = falsey (second time invoked this day at the proper hours)
2018,08,28,08,15,2 = falsey (out of hours)
2018,08,29,08,00,3 = falsey (not Tuesday or Thursday)
2018,08,29,18,00,3 = falsey (not Tuesday or Thursday)
2018,08,30,07,49,4 = falsey (out of hours)
2018,08,30,07,50,4 = truthy (first time invoked this day at the proper hours)
2018,08,30,07,50,4 = falsey (second time invoked this day at the proper hours)
2018,08,30,08,10,4 = falsey (third time invoked this day at the proper hours)
2018,08,30,08,11,4 = falsey (out of hours)
2018,09,04,08,10,2 = truthy (first time invoked this day at the proper hours)

This is code-golf, so may the shortest code for each language win!

JavaScript (ES6), 43 bytes

f=(D,t,d)=>5>>d&t>749&t<811&&!f[D]*(f[D]=1)

Try it online!
Input

the date as a string in yyyymmdd format
the time as a string in hhmm format
the day of week as a 0-indexed integer, with 0 = Tuesday, 1 = Wednesday, ..., 6 = Monday

Output
Returns 0 or 1.
Commented
f = (            // named function, as the underlying object will be used as storage
  D,             // D = date (string)
  t,             // t = time (string)
  d              // d = day of week (integer)
) =>             //
  5              // 5 is 0000101 in binary, where 1's are set for Tuesday and Thursday
  >> d &         // test the relevant bit for the requested day of week
  t > 749 &      // test whether we are in the correct time slot
  t < 811        //
  && !f[D] *     // make sure that this date was not already invoked at a correct time
  (f[D] = 1)     // and store it in the underlying object of f()


Find the numbers and calculate output Objective

Given an input list of 6 distinct digits, find 3 numbers a, b and c such that a × b = c, with a having 2 digits, b having 1 digit and c having 3 digits. In a more visual way, your program must arrange those 6 digits in the boxes of this image:

If more than one solution exists, you may output any of them.

Input

6 distinct digits. You may take them in any reasonable way for your language.

Output

The 3 numbers a, b and c. The output format is relatively free, as long as the 3 numbers are separated and are always printed in the same order (but not necessarily in the order a, b, c).

Test Cases

1, 2, 3, 4, 5, 6 -> 54,3,162
2, 3, 4, 5, 6, 7 -> 57,6,342 or 52,7,364

Scoring

The shortest code in bytes wins.

JavaScript (ES6), 90 88 bytes

Takes input as an array of 6 digits. Returns a string describing a possible solution (such as '54*3==162') or exits with a 'too much recursion' error if (and only if) there's no solution.

f=(a,k=1)=>eval(s='01*2==345'.replace(/\d/g,n=>a[n],a.sort(_=>(k=k*2%3779)&2)))?s:f(a,k)

How it works

This is a deterministic algorithm.

The primes P=2 and Q=3779 were chosen in such a way that the sort callback (k = k * P % Q) & 2 is guaranteed to generate all 720 possible permutations of the input array over time. More precisely, all permutations are covered after 2798 sorts -- which should be within the recursion limit of all browsers.

We inject each permutation in the expression 01*2==345 by mapping the digits to the corresponding entries in the array.

We evaluate this expression and do recursive calls until it's true.

Test

f=(a,k=1)=>eval(s='01*2==345'.replace(/\d/g,n=>a[n],a.sort(_=>(k=k*2%3779)&2)))?s:f(a,k)

console.log(f([1,2,3,4,5,6])); // 54*3==162
console.log(f([2,3,4,5,6,7])); // 52*7==364
console.log(f([1,2,3,4,6,7])); // 73*2==146


Implement map()...with bugs EDIT: The behavior may be inconsistent. Also, associative arrays are permitted.

Make a function that iterates through an indexed array, mapping a function of a single argument to each member of the array. The catch: introduce a hidden bug where the function is not correctly applied to at least one index of the input array.

Example:

map(lambda a: a+1, [1, 2, 3, 4])
# Should be [2, 3, 4, 5]
# Could be: [2, 3, 5, 4] or [2, 4, 6, 5] or anything else

Rules:

Use either a static method with two arguments, function and array, or a non-static method with one, an array or function (this being of the other type). Examples:

std::vector<F> map(F (*fn)(E), std::vector<E> array); (C++)
def map(fn, array): ... (Python)
Array.prototype.map = function (fn) {...}; (JavaScript)

If your language features a method already to do this, re-implement it.
The ignored entry may be of any type desired.
Assume the arguments to actually be correct (if the language has dynamic type checking).
It may or may not be in place.
Hide your malice.
Highest vote count wins.

Here's an example of a correct, bug-free implementation in JavaScript (excluding type checking):

Array.prototype.map = function (fn) {
  var i   = this.length,
  ret = new Array(i);
  while (i--) { // decrements to 0 after evaluation
    ret[i] = fn(this[i]);
  }
  return ret;
};

Perl

sub mymap (&@) {
  my $fn = shift;
  my @ret;
  while (my $val = shift) {
    local $_ = $_[0]; # map calling convention is element in $_
    push @ret, $fn->();
  }
  return @ret;
}

Looks plausible for at least a moment, until you have the sense to go "why isn't he using $val?"


Counting rods; count your rods Some background

Counting rods are small bars (3-14 cm long) that were used by mathematicians from many asian cultures for more than 2000 years to represent any whole number or fraction. (In this chqllenge we'l focus on unsigned integers though) There was also a written version, called rod numerals.

Here's how it works:

(If at any point you get confused, go check out the ascii representation of each digit and some examples I have included at the bottom)

Rod numerals are a true positional numeral system with digits for 1-9 and blank for 0.
The digits consist of horizontal and vertical lines; the more lines, the higher the digit. Once you get past five, you put a horizontal line on top to add 5 to the numer of lines below.
One vertical line is 1, two vertical lines 2, five vertical lines is 5, one vertical line with a horizontal line on top is 6, four vertical lines with a horizontal line on top is 9 (the highest digit).

A vertical 3 digit:

 |||
 |||
 |||
 |||
 |||

To make reading rod numerals easier though, they used different notation for each alternating digit. The second notation swaps the role of the horizontal and vertical lines. so that 3 is represented by three horizontal lines and 8 by three horizontal lines with a vertical line on top.

A horizontal 8 digit:

  |
  |
__|__
_____
_____

Knowing which notation to use is easy, as previously said, tehy are used alternatingly and Sun Tzu wrote that "one is vertical, ten is horizontal". So the rightmost digit is vertical and we alternate from there on.

The challenge

These rods were used to represent negative numbers and fractions (as explained in the wikipedia article on them. For the purpose of this challenge we'll only focus on positive integers though. The objective is simple:

Write a function or full program that takes an integer value as input in any way and prints the rod numeral representation of this integer to STDOUT (you may also write to a file if that works out better). Shortest code in bytes wins.

Every digit will be represented by 5x5 ascii characters and seperated by two collumns of 5 spaces. The exact representation you'll use for each digit is as follows:

space between two digits (two colums):

0 digit, both vertical and horizontal (five columns):

1 digit, vertical:
  |
  |
  |
  |
  |

2 digit, vertical:
 | |
 | |
 | |
 | |
 | |

3 digit, vertical:
 |||
 |||
 |||
 |||
 |||

4 digit, vertical:
|| ||
|| ||
|| ||
|| ||
|| ||

5 digit, vertical:
|||||
|||||
|||||
|||||
|||||

6 digit, vertical:
_____
  |
  |
  |
  |

7 digit, vertical:
_____
 | |
 | |
 | |
 | |

8 digit, vertical:
_____
 |||
 |||
 |||
 |||

9 digit, vertical:
_____
|| ||
|| ||
|| ||
|| ||

1 digit, horizontal:

_____

2 digit, horizontal:

_____
_____

3 digit, horizontal:

_____
_____
_____

4 digit, horizontal:

_____
_____
_____
_____

5 digit, horizontal:
_____
_____
_____
_____
_____

6 digit, horizontal:
  |
  |
  |
  |
__|__

7 digit, horizontal:
  |
  |
  |
__|__
_____

8 digit, horizontal:
  |
  |
__|__
_____
_____

9 digit, horizontal:
  |
__|__
_____
_____
_____

The digits are to be printed next to each other. Trailing spaces beyond the bounding box of the last digit are not allowed. Trailing spaces to complete the bounding box of the last digit(s) are required. You should end the output with a single trailing newline. Leading spaces that do not belong to the bounding box of the first digit are also forbidden.

Standard loopholes apply.

Example output

Lines starting with > are to be interpreted as input.

>12
        | |
        | |
        | |
        | |
_____   | |

>8037
  |                  _____
  |                   | |
__|__         _____   | |
_____         _____   | |
_____         _____   | |

>950
_____  _____
|| ||  _____
|| ||  _____
|| ||  _____
|| ||  _____

Python 2 - 216
My first shot, might be some stuff to take out, but my brain hurts, so it's good enough for now
x=raw_input()
for l in range(5):print'  '.join((' '*7+'|   | |  ||| || '+'|'*7+'__|'+'_'*7)[[7*(4-l<n%6+n/6)+(n>5)*(l<10-n)-(l==10-n),n%6+n/6+(l<1)*(n>5)*(12-n)][(len(x)-i)%2]*5:][:5]for i,n in enumerate(map(int,x)))


Semi-Diagonal Alphabet Given a letter of the English alphabet, your task is to build a semi-diagonal alphabet to the input.

How to build a Semi-Diagonal alphabet?

Brief Description:
First, you take the position of the letter in the alphabet, P (P is 1-indexed here). Then, you print each letter until the input (inclusive) on a line, preceded by P-1 and repeat that letter P times, interleaving with spaces.

Examples:

Given F, your program should output:

A
 B B
  C C C
   D D D D
    E E E E E
     F F F F F F

Given K, your program should output:

A
 B B
  C C C
   D D D D
    E E E E E
     F F F F F F
      G G G G G G G
       H H H H H H H H
        I I I I I I I I I
         J J J J J J J J J J
          K K K K K K K K K K K

Given A, your program should output:

A

Rules

You may choose either lowercase or uppercase characters, but that should be consistent.
You may have extraneous spaces as follows:

One consistent leading space (on each line).
A trailing or leading newline(s).
Trailing spaces.

Input and output can be taken by any standard mean, and default loopholes apply.
You are allowed to output a list of lines instead, as long as you also provide the ascii-art version.
This is code-golf, so the shortest code in bytes wins!

Inspired by this challenge.

Python 3, 59 bytes

lambda l:[' '*i+'%c '%(i+65)*-~i for i in range(ord(l)-64)]

Try it online!

Python 3, 61 bytes

lambda l:[' '*i+-~i*(chr(i+65)+' ')for i in range(ord(l)-64)]

Try it online! (link to pretty-print version)


Hilbert-Curvify a Matrix Inspired by this question

Another way to unroll a 2D image into a 1D string is to use an Hilbert Curve.

There are many version of this curve, depending on the number of iterations used while computing it. Below follow example of Hilbert Curves from first order to fifth order.

The way of computing this curve is the following. First we define the first order Hilbert Curve as the one shown in figure (the one for n = 1), so that it fits in a 1x1 square. We than make four copies of this curve, spacing them in a 4x4 square, so that they all present the "concavity" towards the left side. We then flip the two leftmost order 1 curves, so that the top one concavity faces toward the top, while the bottom's faces the bottom. We finally connect the the corners of the adjacent Hilbert Curves. If wanting to obtain a (n+1)-order Curve, we just need to repeat the process with four n-order Curves. We can see a visualisation of the process here (I will also add an image detailing the process soon)

Your task in this challenge is to unroll a matrix of integers along the lowest order Hilbert Curve for that matrix.

For simplicity's sake, we will have the curve starting from the top left corner of the matrix.

You can receive the input either as a list of list of integers, where each
sub-list represents a row of the matrix.

You can assume that the input will be a square matrix (n*n).

For example:

Input:

[[ 1, 2,]
 [ 3, 4 ]]

Output:

[ 1, 2, 4, 3 ]

Since we are using the first order Hilbert Curve shown in figure

Input:

[[ 1, 2, 3, 4,    ]
 [ 5, 6, 7, 8,    ]
 [ 9, 10, 11, 12, ]
 [ 13, 14, 15, 16 ]]

Output:

[ 1, 5, 6, 2, 3, 4, 8, 7, 11, 12, 16, 15, 14, 10, 9, 13 ]

Using the second order Hilbert Curve

As usual, standard loopholes are not permitted.

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

APL (Dyalog Unicode), 41 bytesSBCS

Saved 30 bytes (!) by consulting the wisdom of the APL Orchard, especially @ngn and @Sherlock9.

{0::⍵⋄∊∇¨⌽∘⊖¨@4,⌽@1⊢∘⍉\⌽↑∘⍵¨∘.,⍨2 ¯2÷⍨≢⍵}

Try it online!

Explanation as follows:

{0::⍵⋄∊∇¨⌽∘⊖¨@4,⌽@1⊢∘⍉\⌽↑∘⍵¨∘.,⍨2 ¯2÷⍨≢⍵} ⍝ Recursive function - takes input as an
                                          ⍝ n*n square matrix
 0::⍵                                     ⍝ Our base case - this is an error guard
                                          ⍝ If there's any error, catch it and
                                          ⍝ return the function's input
                                      ≢⍵  ⍝ Find the number of rows in the input
                                2 ¯2÷⍨    ⍝ Divide the above by 2 and negative 2,
                                          ⍝ resulting in a 2-element vector
                            ∘.,⍨          ⍝ Outer product - take the above vector and
                                          ⍝ apply concatenation (,) with each element
                                          ⍝ against all elements in the vector. Since
                                          ⍝ we have a 2-element vector, this results in
                                          ⍝ a 2-by-2 matrix, e.g.
                                          ⍝ [[(2,2),(2,¯2)],[(¯2,2),(¯2,¯2)]]
                        ↑∘⍵¨              ⍝ For each element in the matrix, we apply
                                          ⍝ "take" against our original input matrix.
                                          ⍝ Take, given a negative number, will take
                                          ⍝ elements from the end of a particular rank.
                                          ⍝ With our argument above, this means that we end
                                          ⍝ up with our original original input matrix
                                          ⍝ split by quadrant into a 2-by-2 matrix.
                                          ⍝ It is also worth noting that take expects
                                          ⍝ an integer argument, so for matrices whose
                                          ⍝ rowcount divided by two results in a decimal
                                          ⍝ (i.e., 1-by-1 matrices), we throw an error
                                          ⍝ which is caught by the guard above, returning
                                          ⍝ the original input.
                       ⌽                  ⍝ Flip the above matrix about the vertical axis.
                   ⊢∘⍉\                   ⍝ Apply a "monadic transpose scan". More details
                                          ⍝ on how this works below, but for our purposes
                                          ⍝ this applies transpose to each of the two
                                          ⍝ sub-matrices on the right half.
                ⌽@1                       ⍝ Swap the two upper sub-matrices. Given our
                                          ⍝ flip for the overall matrix above, this returns
                                          ⍝ the two upper quadrants to their original
                                          ⍝ positions.
               ,                          ⍝ Ravel: flatten the 2-by-2 matrix into a
                                          ⍝ 4-element vector
         ⌽∘⊖¨@4                           ⍝ Take the last element of the list (the lower
                                          ⍝ right quadrant originally) and flip it
                                          ⍝ along the vertical and horizontal axes. Given
                                          ⍝ the transposition above, this has the final
                                          ⍝ effect of transposition along the antidiagonal.
       ∇¨                                 ⍝ For each element in the above vector, recurse.
      ∊                                   ⍝ Recursively flatten the results into a single
                                          ⍝ vector.

More details on "monadic transpose scan".

Dyalog documentation on error guards.


Make the pattern from composition notebooks This challenge was xnor's idea, taken from Digital Trauma's challenge donation thread.

Your challenge is to write a program that, as xnor put it, "procedurally generate[s] the splotchy black-and-white marbled pattern on the covers of composition notebooks":

Your program can either display it on the screen or save it in a file. The image should be at least 300 pixels in each dimension, and it should be different between runs of the program. Your program should not just load an external image and use that as its output; the image should be generated by your program.

This is a popularity-contest, and it will use xnor's criteria for voting:

Similarity to the reference texture above.
Simplicity of generation method.

Mathematica

Blur[Binarize[Blur[RandomImage[1, {1000, 1000}, ImageSize -> Large], 6], .52]]

Quite simple. Creates a random grayscale image, blurs it, takes the pixels above a threshold, and blurs it again. It uses a couple of hand-tweaked values. The result:


Compactify the query string Introduction
Just on Hacker news, John Resig contemplates
transforming a query “foo=1&foo=2&foo=3&blah=a&blah=b” into one that looks like this: “foo=1,2,3&blah=a,b", https://johnresig.com/blog/search-and-dont-replace/.
He claims "being 10 lines shorter than Mark’s solution".
Query strings consist of sequences of name-value pairs. Name-value pairs consist of a name and value, separated by =. names and values are possibly empty sequences of alphanumeric characters.
Name-value pairs are separated by the & character in the sequence. Values are unique for each name.
Challenge
10 lines shorter than Mark's solution is not enough.

Read a query string.
Combine name value pairs with equal name into a single name value pair, with values concatenated and separated by comma.
Output the combined query string, with name-value pairs in the order the names are found from left to right in the query string.

This is code golf, the standard loopholes are closed.
Example Input and Output
Input:

foo=1&foo=&blah=a&foo=3&bar=x&blah=b&=1&=2

Output:

foo=1,,3&blah=a,b&bar=x&=1,2

Input:

foo=bar&foo=foo

Output:

foo=bar,foo

JavaScript (ES6),  103 99 87  86 bytes
Saved 1 byte thanks to @MatthewJensen

s=>Object.values(o=/(\w*=)(\w*)/g,s.replace(o,(s,k,v)=>o[k]=o[k]?o[k]+[,v]:s)).join`&`

Try it online!
Commented
s =>                  // s = query string
  Object.values(      // get the values of ...
    o =               //   ... the object of this regular expression, which is
      /(\w*=)(\w*)/g, //   re-used to store the keys and values of the query
    s.replace(        //   match each key with the '=' sign and the corresponding
      o,              //   value, using the regular expression defined above
      (s, k, v) =>    //   for each matched string s, key k and value v:
        o[k] =        //     update o[k]:
          o[k] ?      //       if it's already defined:
            o[k] +    //         get the current value
            [, v]     //         append a comma, followed by v
          :           //       else:
            s         //         set it to the entire matched string
                      //         (key, '=', first value)
    )                 //   end of replace()
  ).join`&`           // end of Object.values(); join with '&'


91 Bottles of ASCII-beer on the Wall Given a single integer x where 0 <= x <= 91 output a stack of bottles of beer with that many bottles (and shelves) missing. For simplicity sake I'll only show the first 6 bottles and what it would be for each of the first inputs.
Here's the stack of bottles, each number is the bottle you should remove for that input (1-indexed):
https://pastebin.com/wSpZRMV6

Note, we're using 91 instead of 99 because 99 would result in an unstable stack of bottles.

Example
With 0 bottles missing (x=0):
             |=|
             | |
             | |
            /   \
           .     .
           |-----|
           |     |
           |-----|
           |_____|
        =============
         |=|     |=|
         | |     | |
         | |     | |
        /   \   /   \
       .     . .     .
       |-----| |-----|
       |     | |     |
       |-----| |-----|
       |_____| |_____|
    =====================
     |=|     |=|     |=|
     | |     | |     | |
     | |     | |     | |
    /   \   /   \   /   \
   .     . .     . .     .
   |-----| |-----| |-----|
   |     | |     | |     |
   |-----| |-----| |-----|
   |_____| |_____| |_____|
=============================
 [THERE ARE MORE UNDER THIS]

For the full output of 0, see here: https://pastebin.com/ZuXkuH6s

With 1 bottle missing (x=1):
         |=|     |=|
         | |     | |
         | |     | |
        /   \   /   \
       .     . .     .
       |-----| |-----|
       |     | |     |
       |-----| |-----|
       |_____| |_____|
    =====================
     |=|     |=|     |=|
     | |     | |     | |
     | |     | |     | |
    /   \   /   \   /   \
   .     . .     . .     .
   |-----| |-----| |-----|
   |     | |     | |     |
   |-----| |-----| |-----|
   |_____| |_____| |_____|
=============================
 [THERE ARE MORE UNDER THIS]

Once again, this is the first two rows from here: https://pastebin.com/ZuXkuH6s (with 1 removed)...

With 2 bottles missing:
                 |=|
                 | |
                 | |
                /   \
               .     .
               |-----|
               |     |
               |-----|
               |_____|
    =====================
     |=|     |=|     |=|
     | |     | |     | |
     | |     | |     | |
    /   \   /   \   /   \
   .     . .     . .     .
   |-----| |-----| |-----|
   |     | |     | |     |
   |-----| |-----| |-----|
   |_____| |_____| |_____|
=============================
 [THERE ARE MORE UNDER THIS]

[ADDITIONAL INPUTS REMOVED]

With 91 bottles missing (n = 91):
:(

You must output an unhappy face, because you're out of beer.

Rules

Bottles are to be removed left to right.
Shelves are removed when no beer remains on the top of the shelves.
For an input of 0, you are outputting 91 bottles stacked in a triangle.

The bottom row has 13 bottles, the top has 1.

1 space between each bottle on each shelf.
Shelves must be input between each row of bottles.

Shelves may use =, - or # as the character.
Shelves must be 3 wider (on each side) than the bottles they hold.

This is code-golf, lowest byte-count wins.

Charcoal, 99 91 bytes

Ａ⁻⁹¹ＮθＡ¹³η:(Ｗθ«Ａ⌊⟦θη⟧ζＡ⁻θζθＡ⁻η¹ηＦζ«↑⁴↖.\↑²←|=↓³←↙¹↓.Ｐ⁶↓²Ｐ⁶↓¹Ｐ______←| »¿θ«Ｍ⁹↑Ｍ³→×=⁻×⁸ζ³↑Ｍ⁴←

Try it online! Link is to verbose version of code. Actually the real version is only 83 70 bytes:

Ｆ¹⁵Ｆι⊞υκ:(Ｆ⁻⁹¹Ｎ«Ｆ¬⊟υ«Ｍ³±⁹×=⁺⁵×⁸⊟υ↑Ｍ⁴←»↑⁴↖.\↑²←|=↓³←↙¹↓.Ｐ⁶↓²Ｐ⁶↓¹Ｐ×_⁶←|←

Explanation:

Ｆ¹⁵Ｆι⊞υκ

Populate an array providing information as to where the shelves go and how long they are.

:(

Print an unhappy face, although this will be immediately overwritten by the first bottle of beer (if any).

Ｆ⁻⁹¹Ｎ«

Loop through the remaining bottles of beer.

   Ｆ¬⊟υ«

Check to see whether a shelf needs to be drawn.

        Ｍ³±⁹×=⁺⁵×⁸⊟υ↑Ｍ⁴←»

Print the shelf and position ready to draw the next bottle above it.

   ↑⁴↖.\↑²←|=↓³←↙¹↓.Ｐ⁶↓²Ｐ⁶↓¹Ｐ×_⁶←|←

Draw a bottle and position ready to draw another bottle.


Find the closest palindromic number Given a number N, output/return X so that N+X is a palindrome, where |X| has to be as small as possible.

Palindrome: A number is a palindrome, if its sequence of digits is the same when reading them from left to right as when reading from right to left. 95359 and 6548456 are symmetric, 123 and 2424 are not. Numbers with leading zeros such as 020 are not a palindrome.

Input is a positive integer smaller than 1015. Read it from stdin, as a method-parameter, whatever.

Output has to be an integer (positive or negative) and ought to be 0 if the input is already a palindrom. You may write your output to stdout, return it from a function or whatever you like. If there are 2 numbers (e.g. 2 and -2) that satisfy the requirements, output only one of them.

Examples:

Input             Output
3                 0
234               -2
1299931           -10
126               5 or -5 (only one of them)

Pyth, 26 20
Lnb_bWP`+QZ=Z-g0ZZ)Z

Updated to meet the new rules.
The program runs in an infinite loop which tests every possible increment, in the order 0, -1, 1, -2, -2 ...
Explanation:
Q=eval(input())     implicit
Z=0                 implicit
Lnb_b               def P(b): return b != rev(b)
WP`+QZ              while P(repr(Q+Z)):
=Z-g0ZZ             Z=(0>=Z)-Z
)                   <end while>
Z                   print(Z)

Example run:
python3 pyth.py programs/palin.pyth <<< 965376457643450
-2969881

This took 23 seconds.

Bonus solution, same character count:
Wn`+QZ_`+QZ=Z-g0ZZ)Z


Percent-Encode a String Introduction

As some of you may know, URLs actually have a list of characters that do special things. For example, the / character separates parts of the URL, and the ?, &, and = characters are used to pass query parameters to the server. In fact, there is a bunch of characters with special functions: $&+,/:;=?@. When you need to use these characters in the URL for any other reason besides the special functions, you have to do something called percent-encoding.

Percent encoding is when you take a character's hexadecimal value and prepend a % character to the beginning of it. For example, the character ? would be encoded as %3F, and the character & would be encoded as %26. In a URL specifically, this allows you to send these characters as data via the URL without causing parsing problems. Your challenge will be to take a string, and percent-encode all of the characters that need to be encoded.

The Challenge

You shall write a program or function that takes in a single string consisting of characters with codepoints 00-FF (ASCII and Extended ASCII characters). You will then have to output or return the same string with each character percent-encoded if necessary. Built-ins that accomplish this task are not allowed, nor are standard loopholes. For reference, here is a list of every character that needs to be percent encoded:

Control characters (Codepoints 00-1F and 7F)
Extended ASCII characters (Codepoints 80-FF)
Reserved characters ($&+,/:;=?@, i.e. codepoints 24, 26, 2B, 2C, 2F, 3A, 3B, 3D, 3F, 40)
Unsafe characters (" <>#%{}|\^~[]`, i.e. codepoints 20, 22, 3C, 3E, 23, 25, 7B, 7D, 7C, 5C, 5E, 7E, 5B, 5D, 60)

Here is a the same list, but instead as a list of decimal codepoints:

0-31, 32, 34, 35, 36, 37, 38, 43, 44, 47, 58, 59, 60, 62, 61, 63, 64, 91, 92, 93, 94, 96, 123, 124, 125, 126, 127, 128-255

This is code golf, so shortest code in bytes (or approved alternative scoring method) wins!

Test Cases

http://codegolf.stackexchange.com/  =>  http%3A%2F%2Fcodegolf.stackexchange.com%2F
[@=>]{#}  =>  %5B%40%3D%3E%5D%7B%23%7D
Test String  =>  Test%20String
ÑÉÐÔ®  =>  %D1%C9%D0%D4%AE
  =>  %0F%16%7F (Control characters 0F, 16, and 7F)
 ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ  =>  %80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF (Extended ASCII characters 80-FF)
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~  =>  %20!%22%23%24%25%26'()*%2B%2C-.%2F0123456789%3A%3B%3C%3D%3E%3F%40ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E

Vim, 67 bytes/keystrokes
:s/\c[^a-z!'()*0-9._-]/\='%'.printf("%02x",char2nr(submatch(0)))/g<cr>

Note that <cr> represents the enter key, e.g. 0x0D which is a single byte.
This is a pretty straightforward solution. Explanation:
:s/                                                                    "Search and replace
   \c                                                                  "Case-insensitive
     [^a-z!'()*0-9._-]/                                                "A negative range. Matches any character not alphabetc, numeric or in "!'()*0-9._-"
                       \=                                              "Evaluate
                         '%'                                           "a percent sign string
                            .                                          "Concatenated with
                             printf("%02x",char2nr(submatch(0)))       "The hex value of the character we just matched
                                                                /g     "Make this apply to ever match
                                                                  <cr> "Actually run the command

That printf("%02x",char2nr(submatch(0))) garbage is terribly ungolfy.


GCD / LCM Polyglots! Your challenge is to make a program or function that outputs the GCD of its inputs in one language and the LCM of its inputs in another. Builtins for GCD or LCM (I'm looking at you, Mathematica) are allowed but not encouraged. There will be 2 inputs, which will always be positive integers, never greater than 1000.

Test Cases

Each line is one test case in the format x y => GCD(x,y) LCM(x,y):

1 1 => 1 1
1 2 => 1 2
4 1 => 1 4
3 4 => 1 12
7 5 => 1 35
18 15 => 3 90
23 23 => 23 23
999 1000 => 1 999000
1000 999 => 1 999000
1000 1000 => 1000 1000

See this pastebin for all possible inputs with 0 < x, y < 31. Note that different versions of the same languages count as different languages.

C / C++, 79 78 73 bytes

Thanks to @ETHproductions for saving a byte!

int f(int a,int b){int c,d=a*b;for(;a;b=c)c=a,a=b%a;auto e=.5;c=e?d/b:b;}

C calculates the GCD: Try it online!

C++ calculates the LCM: Try it online!

In C, auto e=.5 declares an integer variable with the auto storage class (which is the default), which is then initialized to 0, whereas in C++11 it declares a double, which is initialized to 0.5. So the variable's value will be truthy in C++ and falsy in C.

The function calculates the GCD with Euclid's algorithm, and the LCM by dividing the product of a and b by the GCD.

Omitting the return statement works at least on GCC. The 78 byte solution below should work with any compiler:

int f(int a,int b){int c,d=a*b;for(;a;b=c)c=a,a=b%a;auto e=.5;return e?d/b:b;}