These are my lucky dice Implement a program or function which simulates common dice for role playing games. It should handle at least the d6 and d20, the two most common dice.

However, it should work as stereotypical gamers expect them to work, and not as real dice work.

It is an in-joke between gamers, that one can have a specially lucky die for a very very important roll, by previously throwing a lot of dice, selecting those which resulted in a "1", then throwing them again, until you get a few which rolled a "1" multiple times. You then carefully preserve them, because they rolled a 1 multiple times in sequence, so the probability to roll a 1 next time should be extremely low.

Of course, this is not how dice work in real life, because the rolls are statistically independent.

Your simulated dice have to take previous rolls into account, and work similarly to how the gambler in the gambler's fallacy expects it to work. For example, if a lot of low numbers were rolled, the probability of rolling a higher number should be increased.

However, as this is cheating, you have to hide it well. This means, a casual glance upon the program should not reveal that you cheated. This means, explicitly saving the previous results and reading them on every throw would be too suspicious. You have to hide this "property" of your dice, and bonus points if you make it plausible deniable and disguise it as an honest mistake. (for example, you make your own RNG with an "unintentional" flaw)

Voters, please take into account how well hidden this "flaw" is.

The programs should be clear, and not obfuscated. It's too easy to hide evil code in an obfuscated program.

Java

public class GamerDie {
    private final java.util.Random rnd;
    private final int sides;

    public GamerDie(int sides) {
        this.sides = sides;
        this.rnd = new java.util.Random();
    }

    public int throw() {
        return rnd.nextInt(sides) + 1;
    }
}

It's so simple that it's obviously not hiding anything: but java.util.Random is a straightforward linear congruential generator, and it uses a discard technique to ensure uniformity, so it guarantees that in any run of the largest multiple of size smaller than 2^48 samples it will distribute the numbers evenly, satisfying the requirement.


Recursive Prime Factorization Your job is to take the prime factors of a number taken from input (omitting any exponents equal to 1) then take the prime factors of all of the exponents, and so on, until no composite numbers remain; and then output the result.

To make what I'm asking slightly clearer, here's a javascript program that does it, but, at 782 bytes, it's not very well golfed yet:

var primes=[2,3];
function nextPrime(){
    var n=2;
    while(isAMultipleOfAKnownPrime(n)){n++}
    primes.push(n);
}
function isAKnownPrime(n){return primes.indexOf(n)!=-1};
function isAMultipleOfAKnownPrime(n){
    for(var i=0;i<primes.length;i++)if(n%primes[i]==0)return true;
    return false;
}
function primeFactorize(n){
    while(primes[primes.length-1]<n)nextPrime();
    if(isAKnownPrime(n)||n==1)return n;
    var q=[];while(q.length<=n)q.push(0);
    while(n!=1){
        for(var i=0;i<primes.length;i++){
            var x=primes[i];
            if(n%x==0){q[x]++;n/=x}
        }
    }
    var o="";
    for(var i=2;i<q.length;i++){
        if(q[i]){if(o)o+="x";o+=i;if(q[i]>1){o+="^("+primeFactorize(q[i])+")"}}
    }
    return o;
}
alert(primeFactorize(+prompt()));

You are required to make order of operations as clear as possible, and sort the prime factors in ascending order on each level.

You get a -50 byte bonus if you produce the output as formatted mathprint or valid latex code.

Pyth, 27 - 50 = -23 bytes

Lj\*m+ed?+\^jyhd`HthdkrPb8

This defines a recursive function y. Try it online: Demonstration

The output is valid LaTeX code, so I claim the bonus. The call y66430125 returns the string 3^{2^{2}*3}*5^{3}, which renders to

Quite proud for finding a way to print the curly brackets without using curly brackets in my code.

Explanation:

L                            define a function y(b): return ...
                       Pb       prime factorization of b
                      r  8      run-length-encoded, gives pairs of (exponent, prime)
    m                           map each pair d (exponent, prime) to:
      ed                          prime
     +                            +
             yhd                    recursive call
            j   `H                  join repr(H) by ^
                                      H is preinitialized with an empty dictionary
                                      so the repr(H) gives the string "{}"
                                      and join inserts the prime-factorization
                                      of the exponent between the chars of "{}"

         +\^                        add "^" at the beginning
        ?         thd               if exponent - 1 != 0 else
                     k              "" (empty string)
 j\*                            join by "*"


Measure the lengths of binary patterns Let's consider the sequence of the binary representation of positive integers (without any leading zero):
1 2  3  4   5   6   7   8    9    10   11   12   ...
1 10 11 100 101 110 111 1000 1001 1010 1011 1100 ...

If we join them together, we get:
1101110010111011110001001101010111100 ...

If we now look for the patterns /1+0+/, we can split it as follows:
110 11100 10 1110 1111000 100 110 10 10 111100 ...

We define \$s_n\$ as the length of the \$n\$-th pattern built that way. Your task is to generate this sequence.
The first few terms are:
3, 5, 2, 4, 7, 3, 3, 2, 2, 6, 3, 5, 9, 4, 4, 2, 3, 4, 3, 2, 2, 3, 3, 2, 8, 4, 4, 2, 3, 7, 4, 6, 11, 5, 5, ...

Related OEIS sequence: A056062, which includes the binary representation of \$0\$ in the initial string and counts \$0\$'s and \$1\$'s separately.
Rules
You may either:

take \$n\$ as input and return the \$n\$-th term, 1-indexed
take \$n\$ as input and return the \$n\$-th term, 0-indexed
take \$n\$ as input and return the \$n\$ first terms
take no input and print the sequence forever

This is a code-golf challenge.
Some more examples
The following terms are 1-indexed.
s(81)    = 13
s(100)   = 3
s(101)   = 2
s(200)   = 5
s(1000)  = 5
s(1025)  = 19
s(53249) = 29

Husk, 7 bytes

mLġ≤ṁḋN

Try it online!

Takes no input and prints ALL the numbers!

Explanation

mLġ≤ṁḋN
      N        The list of all positive integers [1,2,3...]
    ṁḋ         Convert each to binary and concatenate the resulting digits
  ġ≤           Split them in groups where each digit is less than or equal to the previous one (basically cuts wherever there is a 0 followed by a 1)
mL             Compute the length of each group


Most logical rectangle formula from numbers Introduction
The task is simple. When given a number, output the most logical rectangle. To explain what a logical rectangle is, I provided some examples:
Input: 24.
All possible rectangles have the form A x B, (A and B are both positive integers). So, all possible rectangles for 24 are:

1 x 24
2 x 12
4 x 6

From this list, the most logical rectangle has the lowest A + B:

1 + 24 = 25
2 + 12 = 14
4 + 6 = 10

You can see that 4 x 6 is the most logical rectangle, so we will output 4 x 6 (or 6 x 4).
The rules

Given an integer from 1 to 99999, output the most logical rectangle.
You may write a function or a program.
The spaces in the output are not required.
This is code-golf, so the submission with the least amount of bytes wins!

Test cases
Input >   Output

1     >   1 x 1
4     >   2 x 2
8     >   4 x 2 (or 2 x 4)
15    >   5 x 3 (or 3 x 5)
47    >   1 x 47 (or 47 x 1)
5040  >   72 x 70 (or 70 x 72)
40320 >   210 x 192 (or 192 x 210)

CJam, 26 bytes

ri_mQ),W%{1$\%!}=:X/" x "X

or

ri_mQ{)1$\%!},W=):X/" x "X

Test it here.

Finds the largest divisor less than or equal to the square root of the input as one of the two side lengths.


Input text from one file, output it to another The challenge:

  Input text from one file and output it to another.  Solution should be a complete, working function.

Note: This is a code-trolling question. Please do not take the question and/or answers seriously. More information here.

C
The whole point of having multiple programming languages, is that you need to use the right tool for the job.
In this case, we want to copy bytes from one file to another.
While we could use something fancy like bash or ruby, or fall to the power of ASM, we need something quick, good with bits and fast.
The obvious choice is C.
The SIMPLEST way of doing it would be like so:
#include <stdio.h>
#define THEORY FILE
#define AND *
#define PRACTICE myfile1
#define SOLUTIONS myfile2
#define ARE fopen
#define IMPORTANT "r"
#define BAD "w"
#define LOL fclose
#define PLEASE fgetc
#define HELP fputc
#define ME return
#define NEVER for
#define SURRENDER !=
#define VERY filename1
#define NOT filename2
#define _ 1

int copyFile(char* filename1, char* filename2)
{
  THEORY AND PRACTICE = ARE (VERY, IMPORTANT);
  THEORY AND SOLUTIONS = ARE (NOT, BAD);
  NEVER (;_;)
  {
    HELP(PLEASE(PRACTICE),SOLUTIONS);
  }
  ME _SURRENDER_;
}

This  is evil because it will read garbage on things like cygwin, is completely chinese for a beginner, will scare him when he realizes it's a call for help and, obviously, because C.


Unsorted majorization of two lists Definition

A vector a containing n elements is said to
majorize or
dominate a vector b with n
elements iff for all values k such that 1 ≤ k ≤ n, the sum of the first
element of a↓ through the kth element of a↓ is
greater than or equal to the sum of the first through kth elements of
b↓, where v↓ represents the vector v sorted in
descending order.

That is,

                          a_1 >= b_1
                    a_1 + a_2 >= b_1 + b_2
              a_1 + a_2 + a_3 >= b_1 + b_2 + b_3
                              ...
      a_1 + a_2 + ... + a_n-1 >= b_1 + b_2 + ... + b_n-1
a_1 + a_2 + ... + a_n-1 + a_n >= b_1 + b_2 + ... + b_n-1 + b_n

where a and b are sorted in descending order.

For the purpose of this challenge, we will be using a slight generalization of
majorization: we will say a list is an unsorted majorization of another if
all of the above inequalities are true without sorting a and b. (This is,
of course, mathematically useless, but makes the challenge more interesting.)

Challenge

Given an input of two distinct lists a and b of integers in the range 0
through 255 (inclusive), both lists of length n ≥ 1, output whether the first
list unsorted-majorizes the second (a > b), the second unsorted-majorizes
the first (b > a), or neither.

You may optionally require the length of the two lists to be provided as input.
The output must always be one of three distinct values, but the values
themselves may be whatever you want (please specify which values represent a
> b, b > a, and neither in your answer).

Test cases for a > b:

[255] [254]
[3,2,1] [3,1,2]
[6,1,5,2,7] [2,5,4,3,7]

Test cases for b > a:

[9,1] [10,0]
[6,5,4] [7,6,5]
[0,1,1,2,1,2] [0,1,2,1,2,1]

Test cases for no majorization:

[200,100] [150,250]
[3,1,4] [2,3,3]
[9,9,9,9,9,0] [8,8,8,8,8,9]

Jelly, 10 8 6 bytes

2 bytes thanks to @orlp.

2 bytes thanks to @Dennis.

_+\ṠQS

Try it online!

1 for a>b, -1 for a<b, 0 for no majorization.

_+\ṠQS

_       Difference (vectorized)
 +\     Cumulative sum.
   Ṡ    Sign of every difference
    Q   Deduplicate
     S  Sum

If there were both 1 and -1 present (some cumulative sums are bigger, some smaller), then the last step would produce 0.


ASCII Mountain Range This is a CC-BY-SA challenge from the CCSC Mid-South Programming Contest 2018.
Author(s): Brent Yorgey
Source: Consortium for Computing Sciences in Colleges Mid-South Programming contest 2018
https://ccsc18.kattis.com/problems/ccsc18.mountainrange

  Good news: you have been hired to do all the special effects for a film! One of the scenes will take place outside, on a windswept plain with a towering mountain range in the background. Your job is to turn a description of the mountain range into a rendered image.

  The bad news: the film’s producers have an extremely small budget, and so they can’t afford luxuries like rendered 3D graphics made up of pixels. Hence, you will be making your image out of ASCII characters.

Write a function or full program to produce mountain range ASCII art according to the spec below. This is code-golf; tie breaker is earlier submission.

Input

You will receive a list of 5-tuples in any standard input format for PPCG and/or your language. Each 5-tuple is the values (x, h, z, t, s) representing one mountain of the range you will draw.

x is the x-coordinate of the mountain's peak, with 1≤x≤199.
h is the height of the mountain, with 1≤h≤100.
z indicates the relative distance of the mountain from the viewer, with 1≤z≤m. The smaller the value of z, the closer the mountain is to the viewer. Closer mountains hide ones that are farther away.
t is the height of the treeline. The side of the mountain up to the treeline should be filled with trees, represented by the ASCII character Y.
s is the height of the snowline. The side of the mountain above the snowline should be filled with snow, represented by the ASCII character *.

The base of each mountain will not extend beyond 0 or 200 horizontally; you may assume that 0≤x−h and x+h≤200. The height of each mountain is no more than 100, so all mountains will fit within a 100x200 grid. The snow and trees will not overlap or exceed the height of the mountain; you may assume that 0≤t≤s≤h. All numbers are non-negative, and all z-values will be unique.

Output

The output should consist of an ASCII drawing of the specified mountain range. Each mountain is triangular in shape with its sides drawn using / and \ characters. For example, here is a mountain of height 4:

   /\
  /  \
 /    \
/      \

This mountain has x-coordinate 4, since the horizontal distance from the left margin to its peak is 4 units.

Trees and snow should fill the interior of the mountain but not obscure the sides of the mountain. For example, here is a mountain with height 6, treeline height 2, and snowline height 3:

     /\
    /**\
   /****\
  /      \
 /YYYYYYYY\
/YYYYYYYYYY\

That is, the trees extend from the base of the mountain up to a height of 2
units, and the snow starts at a height of 3 units and extends to the top of the mountain.

Mountains with a smaller z-coordinate may hide all or part of a mountain with a larger z-coordinate; see the third sample input/output below.

Leading whitespace is significant, and should be as specified by the x-position and width of the drawn mountains. Leading/trailing newlines are allowed, and any amount of spaces after each line.

Examples

(8, 5, 1, 2, 3)

       /\
      /**\
     /    \
    /YYYYYY\
   /YYYYYYYY\

(2, 2, 1, 0, 1)

 /\
/  \

(8, 5, 2, 2, 3),
(2, 2, 1, 0, 1),
(9, 8, 3, 1, 4),
(17, 4, 4, 4, 4)

        /\
       /**\
      /****\
     /*/\***\
    / /**\   \  /\
   / /    \   \/YY\
 /\ /YYYYYY\   \YYY\
/  \YYYYYYYY\YYY\YYY\

If you find other interesting examples, please share in your answers!

Python 2, 194 191 186 bytes

g=map(list,[' '*200]*100)
for x,h,z,t,s in sorted(input(),key=lambda m:-m[2]):
 for i in range(h):g[-h+i][x+~i:x-~i]=['/']+[' *Y'[(i<h-s)-(i>=h-t)]]*2*i+['\\']
for l in g:print''.join(l)

Try it online!

Prints the whole 100x200 grid.


Largest smallest gap Write a function or program which takes as input a set of distinct, non-negative integers \$\{x_1, \ldots, x_n\}\$ and outputs the smallest gap between any two values in the set, i.e. \$\min_{i\neq j}|x_i-x_j|\$.
Scoring
This is not code golf. Your score is the smallest gap of the set of code points of characters in your code (highest score wins). In other words: convert your code to integer code points (using ASCII or whatever code page is standard for your language); remove duplicates; use that as input to your program; the output is your score.
For instance, if your code is min(alldifferences(input)), to get your score convert m->109, i->105, n->110, (->40, ... and your score will be 1, since the codepoints for m and n are only 1 apart.
You may assume that the input contains at least 2 distinct values; behaviour is undefined otherwise. Your code must include at least two distinct characters.
If your encoding is ASCII, you can use this online R code to verify your score.
Test cases
Input         | Output
0 1 2 3 4     | 1
2 4 8 16 32   | 2
1             | undefined
3 14 159 2653 | 11
4 6 8 9 12 14 | 1
3 14 2        | 1

Default rules for input/output apply. In particular, since the input is a set, you may assume any structure for the input.

05AB1E, score: 22 49 69 (5 4 bytes)
ê¥êн

Uses the 05AB1E encoding, where the bytes have the codepoints [234,165,234,14] (ê¥ are 69 apart).
+27 score by porting @Arnauld's approach of sorting.
+20 score (and even -1 byte at the same time) thanks to @Grimmy.
Try it online or verify all test cases.
Explanation:

ê     # Sort and uniquify the (implicit) input-list (in ascending order)
 ¥    # Get the deltas of this sorted list
  ê   # Sort and uniquify this again
   н  # Pop this list and push its first item
      # (which is output implicitly as result)


How varied is my obstacle course? Background

I have constructed a simple obstacle course by placing boxes in a rectangular room.
Now I want to count the number of essentially different ways in which it can be solved.
I need you to write me a program for that.

Input

Your input is a non-empty rectangular array of the characters .#.
The dots . are empty space, and the # are obstacles.

A path through the obstacle course begins at the top left corner and ends at the bottom right corner, and goes only right or down.
Also, a valid path cannot go through an obstacle.
Here are some examples drawn with +-characters:

Valid path  Invalid path  Invalid path  Invalid path
++........   ++........    +++++.....    ..+.......
.++++++#..   .+.....#..    ....+++#++    ..++...#..
......+#..   .+.++++#..    .......#.+    ...+++.#..
....#.++++   .+++#.++++    ....#....+    ....#+....

Two paths are essentially similar1 if one can be transformed into the other by moving one + at a time.
The intermediate paths must also be valid, so you can't bend a path over an obstacle.
For example, the first two paths here are essentially similar, but the third is essentially different from them, since it can't be wiggled over the two obstacles:

++........   +.........   +++++++++.
.+++++.#..   ++.....#..   .......#+.
.....+.#..   .++++++#..   .......#++
....#+++++   ....#.++++   ....#....+

Output

Your output is the number of essentially different paths through the obstacle course.
In other words, if all the valid paths are divided into classes of essentially similar paths, the output is the number of classes.
Note that this number may be 0, if there are no valid paths.

Rules and scoring

You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
There are no time bounds, except that you should evaluate your program on every test case before submitting it.

Test cases

....
....
.... => 1

...#
....
...# => 0

#..#
..#.
.... => 0

......
......
..##..
......
...... => 2

......
...#..
......
..#...
#..... => 3

......
..#...
......
....#.
#..... => 4

.......
##.....
....###
...#...
..##.#.
#....#.
..#.... => 0

......#.
..##....
...#....
.......#
....#...
.##...#.
....#...
##...... => 7

.........
.#.#.#.#.
.........
#.#...#.#
.........
.#.#.#.#.
......... => 17

..........
.#........
..........
.....#....
#.........
........#.
......#...
.......... => 10

.........
.#.......
.........
...#.....
.........
.....#...
.........
.......#.
......... => 16

1 The correct technical term is "homotopic".

Python 2, 170 131 112 bytes

def f(C,t=1):i="#".join(C).find("#")+1;return([]<C)*(i<1or(i<t
and f([r[i:]for r in C],t-i))+(i>1)*f(C[1:],i-1))

A function, f, taking the obstacle course as a list of rows, and returning the number of essentially different paths.

Explanation

The basic concept is this:
We choose a certain obstacle, o, such that there are no other obstacles in the box bounding o and the top-left corner.

+--+....
|..|....
+--#<==== o
.....#..
.#......
........

We then consider the two sub-courses to the east and to the south of o.
We only consider either of these sub-courses if o can actually be crossed from a direction that leads to them, that is, crossed from the north to get to the east, and crossed from the west to get to the south.
We solve the problem for each of the selected sub-courses, and return the sum of the results.
These numbers correspond to the number of essentially different paths when crossing o from the left and from the right, respectively,
therefore the two resulting sets of paths are essentially different.
Since there are no obstacles between the starting point and o, there is a path between the starting point and any entry point into each of these regions, and all such paths that lead to the same point are essentially similar, hence the above sum is the complete number of essentially different paths in the entire course.

                               A
_
........       ...|////      |....
........       ...|////      |....
...#....  -->  ...#////  -->  ....
.#....#.       .#..//#/       ..#.
........       ....////       ....

   |                           |
   v                           v
                  B
........       ___
........       .#....#.
___#....  -->  ........  -->   +
/#////#/
////////

Things are slightly complicated by the fact that the obstacle course alone doesn't convey all the information needed.
For example, consider course B in the diagram above.
Taken by itself, we can't determine whether each of the obstacles can be crossed from the north.
If B were the input course, then, since all paths start at the top-left corner, neither obstacle could have been crossed from the north, but, since we can reach B from either side of the left obstacle when crossing o from the east, we should treat this obstacle as though it can be crossed from the north when solving the course; the same doesn't hold for the right obstacle, however, which can't be crossed from this direction.

We convery this extra information by specifying, along with the obstacle course, the number of characters along the first row, starting from the left, that the path can start at.
In the diagram above, this is depcited as the solid line next to each course.
While, technically, we also need to specify the corresponding number of characters along the first column that the path can start at, as in the case of sub-course A, in practice we always selected the highest obstacle, so this information is not required.

The actual selection of o is as follows:
We pretend that each row, other than the last, is followed by an obstacle (i.e., has a # appended to it), and select the first obstacle in the resulting course, in reading order.
For rows (other than the last) that had no obstacle originally, this effectively mean that we skip them (while noting that the path below may start at any character along the top row).
Eventually, we end up with a course that has a single row with no obstacles, for which there is only one possible path.


Octal, Decimal, or Hexadecimal? Given an input string containing only letters and numbers, write a program or function that prints the possible printable ASCII characters (Hex 20-7E) that correspond with the string's value in bases 8, 10, and 16 (where possible). The characters must be written in increasing order in terms of the bases with which they correspond (base 8 first, etc). The output can be in array format (like [& . F]) or separated by spaces or newlines (a trailing newline is optional) like the samples.

If there is not a possible printable ASCII character that can be formed, the program must not have any output.

Samples

31
==> 1

47
==> ' / G

69
==> E i

7A
==> z

100
==> @ d

156
==> n

189
==> <empty>

potaTO
==> <empty>

5G
==> <empty>

19
==> <empty>

This is code-golf, so the answer with the fewest bytes wins. Standard rules apply.

JavaScript (SpiderMonkey 30+), 74 bytes

s=>[for(b of'o0x')if((c=+(0+b+s))>31&c<127)String.fromCharCode(c)].join` `


Manchester encode a data stream Manchester coding is a telecom protocol used in radio communications that guarantees bit transitions at a regular interval so a receiver can recover the clock rate from the data itself. It doubles the bitrate, but is cheap and simple to implement.  It is widely used by amateur radio operators.

The concept is very simple: at a hardware level, the clock and data lines are simply XORed together.  In software, this is portrayed as converting an input stream of bits into a double-rate output stream, with each input '1' translated to a '01' and each input '0' translated to a '10'.

This is an easy problem, but open to a lot of implementations because of its bitstream nature.  That is, the encoding is conceptually a bit-by-bit process instead of a byte-by-byte process.  So we all agree on endianness, the least significant bits of the input become the least significant byte of the output.

Golfing time!  Write a function that, given an arbitrary length array of bytes, returns an array of that data manchester encoded.

Input and output should be considered little-endian, least significant byte first, and least significant BIT first in the bit stream.

ASCII bitstream drawing:

bit #      5 4 3 2 1 0                                5  4  3  2  1  0
IN ------- 1 0 1 0 1 1 ---> [manchester encoder] ---  01 10 01 10 01 01 ----> OUT

Examples:

Example 1 (hex):
       LSB              MSB     <-- least sig BYTE first
IN : [0x10, 0x02]
OUT: [0xAA, 0xA9, 0xA6, 0xAA]

Example 1 (binary):
      msb  lsb                      msb  lsb  <-- translated hex, so msb first
BIN: [00010000, 00000010]                     <-- least sig NIBBLE...
BIN: [10101010, 10101001, 10100110, 10101010] <-- becomes least sig BYTE
         LSB                           MSB

Example 2
IN :  [0xFF, 0x00, 0xAA, 0x55]
OUT: [0x55, 0x55, 0xAA, 0xAA, 0x66, 0x66, 0x99, 0x99]

Example 3
IN : [0x12, 0x34, 0x56, 0x78, 0x90]
OUT: [0xA6, 0xA9, 0x9A, 0xA5, 0x96, 0x99, 0x6A, 0x95, 0xAA, 0x69]

Example 4
IN : [0x01, 0x02, 0x03, 0xF1, 0xF2, 0xF3]
OUT: [0xA9, 0xAA, 0xA6, 0xAA, 0xA5, 0xAA, 0xA9, 0x55, 0xA6, 0x55, 0xA5, 0x55]

Rules:

Solution only requires algorithm to convert input to output.
Acquiring input and printing output are NOT a required part of the solution, but may be included.  You are encouraged to provide your test/print code if not included in your solution.
Input is an array of 8-bit bytes (whatever that may mean in your language of choice), NOT a text string.  You can use strings as the storage format if convenient in your language, but non-printable characters (i.e. 0xFF) must be supported.  Input can also take a length if necessary.
Memory for output must be allocated by your routine, not provided. edit: unnecessary requirement
Output is also an array of 8-bit bytes, and a length if necessary.
Must support at least 16KB input
Performance must not be too horrible: < 10s for 16KB
Least-significant byte first in memory.

Side-channel challenge:

Challenge another user's answer by proving your code is faster, more memory efficient, or produces a smaller binary!

Get golfing!  Shortest code wins!

GolfScript 28 characters
{2{base}:|~4|43691-~256|~\}%

Equivalent version without obfuscating optimization:
{2base 4base 43691-~256base~\}%

The code accept input as an array of integers, and return ditto.
For each number in the array the number is converted to base 2 array form, it is then converted back to a number as if it was base 4, this has the effect of spacing out the bits with a 0 in between each. 43691 is then subtracted from the number, and the result is binary inverted, this is equivalent to subtracting the number from 43690 (43690 = 0b1010101010101010). The number is then split into two parts by converting it to a base 256 array, the array is decomposed and the order of the two resulting numbers is inverted.
Example input:
[1 2 3 241 242 243]

Example output:
[169 170 166 170 165 170 169 85 166 85 165 85]


Double a number's continued fraction Your task is, given x, output 2*x. Easy right!? But there's a catch: x will be given as a (possibly infinite) continued fraction, and the output must be a continued fraction. The input is guaranteed to be a real algebraic number whose degree is at most 2.

Input: The continued fraction of x. This is split into 3 parts: the integer part, the prefix, and the repeating part. The integer part consists of a single integer. The prefix and repeating part are (possibly empty) arrays of positive integers which describe the prefix and repeating part of the continued fraction. For example, the input (3, [1], [2, 4]) represents the continued fraction [3; 1, 2, 4, 2, 4, ...].

If the repeating part is empty, that indicates a rational number. For example, (3, [1, 2], []) represents [3; 1, 2] = 11/3. You must accept both forms of a rational number (i.e. (3, [1, 1, 1], []), which is [3; 1, 1, 1] = 11/3 should also be valid input).

Output: Output the continued fraction of twice the input, in the same format as the input. If the output is rational, you may output either form of the continued fraction. As long as the answer is equivalent to the correct answer, it is fine; no "compression" is necessary, so the infinite part might be "unrolled" a little (e.g. [1; 4, 2, 3, 2, 3...] may be written (1, [4], [2, 3]) or (1, [4, 2, 3], [2, 3])). All answers must be exact.

Test cases: The exact form column is given for convenience.

Input               Exact Form       Output
(0, [] [])          0                (0, [] []) or (-1, [1], [])
(-5, [1, 1], [])    -4.5             (-9, [], []) or (-10, [1], [])
(3, [1, 2], [])     11/3             (7, [3], []) or (7, [2, 1], [])
(1, [], [2])        sqrt(2)          (2, [], [1, 4])
(-1, [2], [2, 1])   -1/sqrt(3)       (-2, [1, 5], [2, 6])

And finally a slightly larger test case to ensure precision: (0, [1], [6, 1, 3, 1, 42, 1, 3, 1, 6, 2]) --> (1, [], [1, 2, 1, 8, 1, 20, 1, 8, 1, 2, 1, 2]).

Shortest code wins!

Hint: You can perform arithmetic in a rather straightforward manner on continued fractions as described here. Doubling a continued fraction is just a special case of this algorithm (although the tricky part may be to find when the continued fraction repeats).

Wolfram Language (Mathematica), 44 bytes

ContinuedFraction[2FromContinuedFraction@#]&

Try it online!

Mathematica has a builtin! Yay! Mathematica's builtin is super long. Aww.

Mathematica's continued fractions look like {integer, ...prefix, {...repeating}}

-1 thanks to JungHwan Min


Iterated phi sequence Related: Iterated phi(n) function.
Your challenge is to compute the iterated phi function:
f(n) = number of iterations of φ for n to reach 1.

Where φ is Euler's totient function.
Related OEIS.
Here's the graph of it:

Rules:
Your goal is to output f(n) from n=2 to n=100.
This is code-golf, so shortest code wins.
Here's the values you can check against:
1, 2, 2, 3, 2, 3, 3, 3, 3, 4, 3, 4, 3, 4, 4, 5, 3, 4, 4, 4, 4, 5, 4, 5, 4, 4, 4, 5, 4, 5, 5, 5, 5, 5, 4, 5, 4, 5, 5, 6, 4, 5, 5, 5, 5, 6, 5, 5, 5, 6, 5, 6, 4, 6, 5, 5, 5, 6, 5, 6, 5, 5, 6, 6, 5, 6, 6, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 5, 6, 7, 5, 7, 5, 6, 6, 7, 5, 6, 6, 6, 6, 6, 6, 7, 5, 6, 6

Haskell, 53 52 bytes

Thanks nimi for saving 1 byte!

f<$>[2..100]
f 1=0
f n=1+f(sum[1|1<-gcd n<$>[1..n]])

Try it online!

sum[1|1<-gcd n<$>[1..n]] gives φ(n) (Taken from flawr,  thanks!)

f is a recursive function that calculates 1+φ(n) if n is not 1, and outputs 0 if n is 1, as there are no more iterations to be taken to reach 1

Finally f<$>[2..100] creates a list of f applied to each element of [2..100]


It’s time to do the math Introduction
This is one of my favorite math puzzles.
Given a digit (say 3) and the number of times to use that digit (say 5), generate 10 expressions which result to 1, 2, 3, 4, 5, 6, 7, 8, 9 and 10 using just +, −, ×, ÷, ^ and √ (root) (brackets are allowed to group operations).
For example:
(3^3 + 3)/(3 + 3) = (33 - 3)/(3 + 3) = 3 + 3/3 + 3/3 = 5

Note that all of the above use five 3’s and the mathematical operations and result to 5. You can also use a 3 before √ to denote a cube root. Same goes for using 4 before √ to denote a fourth root.
Also note that two 3’s can be used to form 33, or three 3’s can be used to form 333 and so on.
Challenge

You will be given two numbers (both ranging from 1 to 5) as a function argument, STDIN or command line argument.
The first number denotes which digit to use and the second number denotes the number of times that digit is to be used in the expression.
Your program should output an array of size 10 (or 10 space-separated numbers) where each element denotes whether a mathematical expression (using just the allowed operators) resulting into the (index + 1) number is possible or not using a truthy/falsy value.

For example, if the input is
1 3

Then the output should be
[1, 1, 1, 0, 0, 0, 0, 0, 0, 1]

because only 1, 2, 3 and 10 can be expressed using three 1’s.
Score

This is a code-golf so the minimum code length in bytes wins.

Bonus
Print-em-all [−50]
Subtract 50 from your score if the output array elements are equal to the total number of plausible combinations to get the (index + 1) value instead of truthy or falsy values.
For example, if there are only 3 possible combinations of five 3’s which result to 5, then the output array’s 4th entry should be 3.
Extreme Maths [−100]
Subtract 100 from your score if the output array elements contain at least one of the actual expressions which result to the (index + 1) value.
For example, if using five 3’s, the output array’s 4th entry can be either (3^3 + 3)/(3 + 3), (33 - 3)/(3 + 3) or 3 + 3/3 + 3/3
Overkilled [−200]
Subtract 200 from your score if the output array elements contain all possible combinations (separated by |). This bonus is added on top of the Extreme Maths bonus, so you get −300 in total.
For example, if using five 3’s, the output array’s 4th element should be (3^3 + 3)/(3 + 3)|(33 - 3)/(3 + 3)|3 + 3/3 + 3/3
Note: Any two expressions to achieve the same result should be logically different with a different approach in both of them.
For instance, to get 5 using five 3’s, 3 + 3/3 + 3/3 is same as 3/3 + 3 + 3/3 or 3/3 + 3/3 + 3 because the same approach is taken for each of them. (3^3 + 3)/(3 + 3) and (33 - 3)/(3 + 3) differ, as the 30 in the numerator is achieved via different approaches.
UPDATE : After going through all answers, it was found that all answers had imperfections due to edge cases of unary - and √. Thus, missing those edge cases was considered okay as far as completeness of answers is involved.
This is a tough question, but a rather interesting one.
Happy golfing!

Python (imperfect) 493 474 - 300 = 174
There are a fair number of issues with this solution, firstly  that it ignores any exponent that is too large (any in which the exponent is greater than 100). I actually don't think this removes any possibilities for inputs less than or equal to 5, but I'm not 100% sure.
Another thing is that it does not consider any unary square roots, as it would get complicated (any solution with any term equal to 0 or 1 would produce an infinite number of solutions). It also does not consider any unary negation (the '-' symbol) for the same reason, as well as the fact that I'm not actually sure if the question asked for it.
I also considered what criteria should decide if two expressions were equivalent, but I couldn't find a way to rigorously define it in a way I found to be intuitive, so (for now at least) I didn't implement anything like that. This does mean that it outputs quite a few results, and it also uses parenthesis in a fairly naive way.
On a side note I think that this might include the longest single line of code I've written, especially before it was fully golfed.
R=range
F=lambda s:lambda a,b:eval(s)
L=lambda D,N:[(int(str(D)*N),str(D)*N)]+[(o(u,v),"(%s%s%s)"%(s,c,t))for p in R(1,N)for u,s in L(D,p)for v,t in L(D,N-p)for c,o in[('+',F('a+b')),('-',F('a-b')),('*',F('a*b')),('/',F("1.*a/b if b else''")),('^',F("''if(a<0 and int(b)!=b)|(a and b<0)|(b>99)else a**b")),('v',F("b**(1./a)if a and(a>=0 or b)and(b>=0 or int(1./a)==1./a)&(1./a<99)else''"))]if o(u,v)!='']
A=L(*input())
for i in R(11):
 for v,s in A:
    if v==i:print i,s[1:-1]

Example: ('v' represents '√')
2,3

0 2*(2-2)
0 2v(2-2)
0 (2-2)*2
0 (2-2)/2
0 (2-2)^2
1 2^(2-2)
1 2-(2/2)
1 2v(2/2)
1 (2/2)^2
2 2v(2+2)
2 2+(2-2)
2 2-(2-2)
2 2v(2*2)
2 2*(2/2)
2 2/(2/2)
2 2^(2/2)
2 2v(2^2)
2 (2+2)-2
2 (2+2)/2
2 (2-2)+2
2 (2*2)-2
2 (2*2)/2
2 (2/2)*2
2 (2/2)v2
2 (2^2)-2
2 (2^2)/2
3 2+(2/2)
3 (2/2)+2
6 2+(2+2)
6 2+(2*2)
6 2+(2^2)
6 (2+2)+2
6 (2*2)+2
6 (2^2)+2
8 2*(2+2)
8 2*(2*2)
8 2*(2^2)
8 (2+2)*2
8 (2*2)*2
8 (2^2)*2


Print a string in as few distinct characters as possible The task is simple: print The quick brown fox jumps over the lazy dog using as few distinct characters in your source code as possible.
print "The quick brown fox jumps over the lazy dog" has a score of 29 characters, as all 26 lowercase letters appear at least once, as well as an uppercase T, spaces, and quote characters. I'm sure you can get more creative than that, though!
In the event of a tie, the shorter answer will be accepted.


How random is the Gettysburg Address Your program must print out the Gettysburg Address.

I copied this text from Wikipedia:

  Four score and seven years ago our fathers brought forth on this continent a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal.
  Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battlefield of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.
  But, in a larger sense, we can not dedicate, we can not consecrate, we can not hallow this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom—and that government of the people, by the people, for the people, shall not perish from the earth.

There are two different tests:

You may use system decompression software
No using system decompression software

Additionally, none of the words in the Address can appear in plain text in your code (with a non-alpha character before and after). Shortest code wins. Good luck!

Mathematica 40
Note: Not to be taken as a serious answer.  ;)
Just for fun:
ExampleData@{"Text","GettysburgAddress"}

Four score and seven years ago, our fathers brought forth upon this
continent a new nation: conceived in liberty, and dedicated to the
proposition that all men are created equal. Now we are engaged in a
great civil war...testing whether that nation, or any nation so
conceived and so dedicated. . . can long endure. We are met on a
great battlefield of that war. We have come to dedicate a portion of
that field as a final resting place for those who here gave their
lives that this nation might live. It is altogether fitting and
proper that we should do this. But, in a larger sense, we cannot
dedicate...we cannot consecrate... we cannot hallow this ground. The
brave men, living and dead, who struggled here have consecrated it,
far above our poor power to add or detract. The world will little
note, nor long remember, what we say here, but it can never forget
what they did here. It is for us the living, rather, to be dedicated
here to the unfinished work which they who fought here have thus far
so nobly advanced. It is rather for us to be here dedicated to the
great task remaining before us...that from these honored dead we take
increased devotion to that cause for which they gave the last full
measure of devotion... that we here highly resolve that these dead
shall not have died in vain...that this nation, under God, shall have
a new birth of freedom...and that government of the people, by the
people, for the people, shall not perish from this earth.


Output the Iccanobif Sequence Write a program or named function that will output or return the sequence up to the nth integer in the Iccanobif sequence, documented on OEIS as A014258. Note that only the zeroth element in the sequence (0) will be printed if n is zero.
The sequence is generated by starting like the standard Fibonacci sequence, but after adding the two previous numbers, you flip the result and drop any leading zeros. An interesting fact, to me at least, is that this sequence is not strictly increasing (see the list below). It also seems to be (and probably is) strictly greater than or equal to the Fibonacci sequence.
Your program's input must be an integer.
The first 20 numbers of the sequence are provided here for your viewing pleasure:
0, 1, 1, 2, 3, 5, 8, 31, 93, 421, 415, 638, 3501, 9314, 51821, 53116, 739401, 715297, 8964541, 8389769

Standard loopholes are forbidden.
Shortest program wins.
EDIT: Added a note to clarify that the sequence starts with the zeroth element and should be included if n is zero.
Example IO possibilities:
0    ->    0
1    ->    0 1
6    ->    0 1 1 2 3 5 8
17   ->    [0, 1, 1, 2, 3, 5, 8, 31, 93, 421, 415, 638, 3501, 9314, 51821, 53116, 739401, 715297]

Now that there are several answers, below are my implementations in Python 2 that I worked hard to hide with markup:
Iterative:

#Closest to my initial program. 73 bytes. It should also be noted that this program
 cannot reach a stack overflow. It runs for n=5000 in less than 10 seconds.

i,a,b=input(),0,1
print a
while i:print b;i,a,b=i-1,b,int(str(a+b)[::-1])

Recursive:

#Note that this prints n trailing newlines. 64 bytes.
 Will hit a stack overflow error for large values of n.

def f(n,i=0,j=1):print i,n and f(n-1,j,int(str(i+j)[::-1]))or'';

Python 2, 58 bytes

a=0;b=1
exec"print a;a,b=b,int(str(a+b)[::-1]);"*-~input()

Uses str to convert rather than backticks because large enough numbers in Python 2 are written with an L at the end. I tried a recursive function, but it turned out longer (61):

f=lambda n,a=0,b=1:-~n*[0]and[a]+f(n-1,b,int(str(a+b)[::-1]))


Crack the code to the combination lock Given a standard combination lock like the one in the picture. The way to unlock it is to align the 4 numbers in the code on the combination line. After years of loyal service you have been fired from the lock factory and have decided to exact revenge by not jumbling up the locks before you send them off, thus leaving every lock with the combination to unlock it on the combination line.

You also know that by looking at the order of the numbers in the other lines it is possible to work out what numbers must be on the combination line (and therefore the combination to unlock it is).

If every line on the lock is given a number starting from line 0 for the combination line (the line which unlocks the lock) to line 9. For example, if the numbers on line 4 are 5336, then the combination to unlock it would be 1992.

Unfortunately the locks have already been packaged and your view of each lock is obscured, so you can only see numbers on different lines of the lock.

The Challenge

Given 4 pairs of digits, where the first digit of the integer represents the line number and the second digit represents the the number which appears on that line, work out the combination to the lock.
For example if you input:

57 23 99 45

Then it should output:

2101

Or

25 78 63 15

and

3174

Assume the input will always be 4 positive integers in the form `25 64 72 18.

This is code-golf, so the shortest programs in number of bytes wins.

Also this is my first question, so any feedback is appreciated.

CJam, 9 8 bytes

ea9fbAf%

Reads the digit pairs as command-line arguments. To try the code online, change ea to lS/ to read from simulated STDIN.

Example run

$ cjam <(echo ea9fbAf%) 57 23 99 45; echo
2101
$ cjam <(echo ea9fbAf%) 25 78 63 15; echo
3174

How it works

The character code of the digit d is 48 + d. Thus, considering the two-digit string xy a base 9 number yields 9 * (48 + x) + (48 + y) = 10 * (48 + x) + y - x ≡ y - x (mod 10).

ea       " Push the array of command-line arguments.                                      ";
  9fb    " Mapped base 9 conversion; replace each string 'xy' with (9 * ord(x) + ord(y)). ";
     Af% " Take the results modulo 10.                                                    ";


Covering Array Validator A covering array is an N by k array in which each element is one of {0, 1, ..., v-1} (so v symbols in total), and for any t columns chosen (so an N x t array) contains all possible v^t tuples at least once. The applications of Covering Arrays range from software and hardware testing, interaction testing, and many other fields. A research question (and which will be a follow-up to this question) is to find the minimal Covering Array of given t,k,and v; an analogue of this would be designing a software system with the minimal number of tests required to test all t-way interactions of the system. Only for t=v=2 is the optimal case known for all k (some values of t and v have some optimal CA designs for one value of k, but this is not the common case).

Here, we focus on validation of Covering Arrays, as this is a very time-consuming process for very large Covering Arrays.

Input: A file that contains the Covering Array. The format is described in Scoring below.

Output: Valid if the input is a valid covering array, and Invalid if it is not.

Goal: in any language you want, write a program that validates if the input is a covering array in the fastest time. I will run programs on my machine, which is a Mac Pro 3.5 Ghz 6-Core Intel Xeon E5 (2013) with 16 GB RAM (1866 MHz).

Rules:

Any language is allowed, as long as it can read from a file, where the filename is given as input.
All you need to print is Valid or Invalid, nothing else.
No third-party libraries; you can only use the libraries/modules that are already built-in to the language.
No use of the Internet for validation (i.e., the validation must be done within the program itself).
You are allowed to have multi-threading/multi-core solutions. However, I will test it on the machine described above.
If your program requires a compilation, describe in your answer what compilation options that you selected (i.e., like g++ -O3 validator.cpp ca.5.6^7.txt).

Scoring: the total score is the total amount of time in milliseconds to produce all of the valid outputs. I will test your program against a number of CAs, and it reports the total amount of time required to execute validation of all sample CAs as input. The CAs will be selected from this link (the text files are provided there, and is linked to from the first link above also).

The format of the files posted there is provided as follows: the first line of the file is N, the name of the file is ca.t.v^k.txt, and the next N rows of the file contain k space-separated integers.

Fastest code (i.e., lowest score) wins!

Edit: after looking at some sample covering arrays on the site, the format is not entirely consistent. If you can change (or provide the file) the format to match the format described above, that would be very helpful.

C, 7.29min for ca.5.4^64.txt on an Intel Core i5-4570 + 8GB ram

Update: Sometimes gives wrong results

I've compiled it with gcc -O3 cav.c -o cav. Simply run it with the CA file's name as first (and only) parameter.
In my case: ./cav ca.2.2^4.txt

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>

int t, v, k, N; /* initial parameters */
uint16_t *ca; /* The CA */
uint16_t *cia; /* Column index array - the columns we selected to compare */
uint8_t *combos;
int num_combos; /* Size of the combo 'hash map' (see compareColumns()) */

int ipow(int base, int exp) /* basic integer pow function 'stolen' from StackOverflow ;) */
{
    int result = 1;
    while(exp)
    {
        if(exp & 1)
            result *= base;
        exp >>= 1;
        base *= base;
    }
    return result;
}

char compareColumns(int base, int child)
{
    int pos = base, maxpos = k - child, child_dec = child - 1;
    if(child == 0)
    {
        while(pos != maxpos)
        {
            cia[child] = pos++;
            memset(combos, 0, num_combos);
            int rv = 0; /* The offset in the CA for the current row */
            int n;
            for(n = 0; n < N; n++) /* For every row */
            {
                int key = 0; /* This is basically a HashMap key, using the same algorithm that you use for accessing 2D data in a 1D array. */
                int df = 1; /* Dimension factor - needed for the hash-map-key-like algorithm */
                int i;
                for(i = 0; i < t; i++) /* For every selected column */
                {
                    key += df * ca[cia[i] + rv]; /* Calculate the key */
                    df *= v;
                }
                combos[key] = 1; /* Set the 'boolean' at 'key' in the 'hash map' to 1 */
                rv += k;
            }
            if(memchr(combos, 0, num_combos) != NULL) /* If there are still any 0s (any needed combinations that aren't found), exit immediately! */
                return 0;
        }
    }
    else
    {
        while(pos != maxpos)
        {
            cia[child] = pos++;
            if(!compareColumns(pos, child_dec))
                return 0;
        }
    }
    return 1;
}

int main(int argc, char **argv)
{
    /* Fetch user input & allocate memory */
    sscanf(argv[1], "ca.%d.%d^%d.txt", &t, &v, &k);

    FILE *file = fopen(argv[1], "r");
    fscanf(file, "%d", &N);

    int num_vals = k * N, i;
    num_combos = ipow(v, t);

    ca  = (uint16_t*)malloc(num_vals * sizeof(uint16_t));
    cia = (uint16_t*)malloc(t * sizeof(uint16_t));
    combos = (uint8_t*)malloc(num_combos * sizeof(uint8_t));

    for(i = 0; i < num_vals; i++)
    {
        int val;
        fscanf(file, " %d", &val);
        ca[i] = val;
    }
    fclose(file);

    /* The main algorithm implementation */
    if(compareColumns(0, t - 1))
        printf("Valid!\n");
    else
        printf("Invalid!\n");

    /* Free memory */
    free(combos);
    free(cia);
    free(ca);
    return 0;
}

I'll try to explain: I'll begin with compareColumns: if it has children (int child), it goes through (allmost) all the columns and kicks off a new call to compareColumns after each step, which itself then walks from the last position of its parent until the end (minus it's own children) of the CA. However, if the function is called with no children (child = 0), it will take all the selected rows and generate something like a hash map key from it. This key will then be used to set a specific cell of the array combos to 1. At the end, it checks if all cells of 'combos' are 1 (i.e. if all combinations appeared at least once). If all cells are 1, it will proceed. If at least one cell is 0, it will abort immediately and print "Invalid!".


1D Shikaku Validation Shikaku is a 2D puzzle. The basic rundown of it is that a rectangular grid has some numbers in it, and you want to partition the grid into rectangular components such that each component contains exactly one number which is the number of grid squares in that component.

This challenge involves a 1D simplification of this: it is a line of N squares with K numbers \$\{a_1, a_2, \cdots, a_K\}\$, and a solution would be a division of the line into K partitions such that each partition contains \$a_i\$ squares. However, in this simplification, not all squares need to be used.

Challenge

Given a list of N numbers (where 0 is an empty square), determine if a valid solution to that problem exists.

Truthy Cases

(_ is a blank; it will be given as 0 in the input. you may not take the input as an index:element mapping)

 _ _ 3 _ _ 5 _ _ 3 _ _
([   ] [       ] [   ])

 2 _ _ _ _ 6 _ _ _ 4 _ _
([ ] [         ] [     ])

 _ 5 _ _ _ 3 _ _ _ _ _ 4
([       ] [   ] [     ])

 _ _ 2 _ _ _ _ 4 _ _
(  [ ]       [     ])
(    [  ]  [     ]  ) just to give 2 examples

Falsy Cases

_ _ 2 _ 4 _
_ 3 _ _ 5 _ _ 3 _
_ _ 5 _ _ _ 3
_ 2 _ 2 _ 2 _ 3

Rules and Specifications

Input can be taken as any convenient way to take a list of numbers. You can input it as a string with _ for blanks as well; etc. Any reasonable method; however, you may not change the general structure of the input as a list.

Output is a true/false value. Any truthy/falsy value is acceptable. The true/false value does not have to be consistent across cases, but your program must give the same exact answer for the same test case every run, and please specify how truthy/falsy is distinguished if it's not conventional. For example, you can output 1 for a true case and 2 for another, and 0 for false cases, but the first case must always yield 1 every time, and the second must give 2 every time.

To prevent a loophole brought up thanks to @xnor, your output must be successful / failed completion as a result, numbers, booleans, or other similar "primitive-like" datatypes (basically, you cannot submit the identity function and say that the Truthy/Falsy sets are divided by this problem's specifications).

Standard loopholes are forbidden.
This is code-golf, therefore the shortest answer in each language wins. No answer will be accepted.

JavaScript (ES6),  56  52 bytes
Returns a Boolean value.

a=>![...a,1].some(x=>t>0/x?1:(t+=x-1)*x<0?t=0:0,t=0)

Try it online!
Commented
The accumulator \$t\$ is decremented whenever an empty slot is encountered. For each non-zero value \$x\$, we update \$t\$ to \$max(t+x-1,0)\$. The test fails if we reach a non-empty slot (or the end of the list) with \$t>0\$.
a =>               // a[] = input
  ![...a, 1]       // append a '1' at the end of a[] to force a last test
  .some(x =>       // for each value x in the updated array:
    t > 0 / x ?    //   if x = 0, this test is always falsy (0 / 0 -> NaN)
                   //   if x ≠ 0 and t is greater than 0:
      1            //     failed: yield 1
    :              //   else:
      (t += x - 1) //     add x - 1 to t
      * x < 0 ?    //     if t is negative and x ≠ 0:
        t = 0      //       we have accumulated more empty slots than
                   //       we can consume here: set t to 0
      :            //     else:
        0,         //       do nothing
    t = 0          //   start with t = 0
  )                // end of some(); return the opposite result


Generating a single string with an Oxford comma from a list What are some clever (brief and idiomatic) approaches to taking a list of strings and returning a single properly punctuated string built from the list, with each element quoted.

This came up for me while experimenting with Groovy, for which my too-literal, but illustrative solution is

def temp = things.collect({"\'${it}\'"})
switch (things.size()) {
    case 1:
        result = temp[0]
        break
    case 2:
        result = temp.join(" and ")
        break
    default:
        result = temp.take(temp.size()-1).join(", ") + ", and " + temp[-1]
        break
}

That is, ['1'] should yield '1', ['1','2'] should yield '1 and 2', [see what I did there?] and ['1','2','3'] should yield '1, 2, and 3'.

I have some good answers for Groovy, but I'd like to see what other languages can do.

What are some compact clever approaches in various languages that take advantage of the features and idioms of those languages?

CSS, 132 116 115 bytes

a:not(:last-child):nth-child(n+2):after,a:nth-last-child(n+3):after{content:","}a+:last-child:before{content:"and "

  one

  one
  two

  one
  two
  three

  one
  two
  three
  four

a:not(:last-child):nth-child(n+2):after,a:nth-last-child(n+3):after{content:","}a+:last-child:before{content:"and "

CSS is not seen too often in code golf because it can only format text, but it actually works for this challenge and I thought it would be fun to do. See it in action using the snippet above (click "Show code snippet").

List should be in a linked HTML file with each element surrounded by  tags and separated by line breaks. The list items should be the only elements in their parent element, e.g.

one
two
three

Explanation

a:not(:last-child):nth-child(n+2)::after,
a:nth-last-child(n+3)::after {
    content: ",";
}

a + :last-child::before {
    content: "and ";
}

Let's consider the ungolfed version above. If you're not familiar with how CSS works, everything outside the curly braces is a selector that determines the set of HTML elements to which the declarations inside the braces apply. Each selector-declaration pair is called a rule. (It's more complicated than that but will suffice for this explanation.) Before any styling is applied, the list appears separated by only spaces.

We want to add commas after every word except the last, except for two-word lists, which get no commas. The first selector, a:not(:last-child):nth-child(n+2):after, selects all elements except the first and the last. :nth-child(n+2) is a shorter way of saying :not(:first-child), and it basically works by selecting elements whose index (starting at 1) is greater than or equal to 2. (Yes, it still confuses me a little. The MDN docs might help.)

Now we just need to select the first element to get a comma if there are three or more elements total. a:nth-last-child(n+3):after works like :nth-child, but counting from the back, so it selects all elements except the last two. The comma takes the union of the two sets, and we use the :after pseudo-element to add content immediately after each selected element.

The second rule is easier. We need to add "and" before the last element in the list, unless it is a single element. In other words, we need to select the last element that is preceded by another element. + is the adjacent sibling selector in CSS.


Classify a region by its slope Definitions

The kth ring of a square matrix of size N, where 1 ≤ k ≤ ceiling(N/2) is the list formed by the elements of the kth and (N-k+1)th rows and columns, but without the first and last k-1 elements.

Example:

Matrix:

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

Delimited in rings:

+-------------------+
| 1   2   3   4   5 |
|   +-----------+   |
| 6 | 7   8   9 | 1 |
|   |   +---+   |   |
| 8 | 7 | 6 | 5 | 4 |
|   |   +---+   |   |
| 3 | 2   1   9 | 8 |
|   +-----------+   |
| 7   6   5   4   3 |
+-------------------+

The first ring of the above is 1,2,3,4,5,1,4,8,3,4,5,6,7,3,8,6, the second is 7,8,9,5,9,1,2,7 and the third is 6.

An N by N matrix of positive integers is (for the purposes of this challenge):

concave if all the integers on the kth ring are strictly greater than those on the (k+1)th ring, where k is any integer between 1 and N  (those on the first ring are greater than those on the second, which are in turn greater than those on the third etc.). Example:

4 5 6 4 7   -> because 4,5,6,4,7,4,8,5,5,4,6,5,9,5,5,4 are all higher than
4 3 2 2 4      any of 3,2,2,3,2,3,3,2, which are all higher than 1
5 2 1 3 8
5 3 3 2 5
9 5 6 4 5

flat if all the integers in the matrix are equal. Another example (perhaps redundant):

2 2 2 2
2 2 2 2
2 2 2 2
2 2 2 2

convex if all the integers on the kth ring are strictly lower than those on the (k+1)th ring, where k is any integer between 1 and N  (those on the first ring are lower than those on the second, which are in turn lower than those on the third etc.). Example:

1 2 1   -> because 1 and 2 are both lower than 6
2 6 2
1 2 1

mixed if the matrix doesn't satisfy any of the above criteria. Example:

3 3 3 3 3
3 2 2 2 3
3 2 3 2 3
3 2 2 2 3
3 3 3 3 3

Challenge

Given a square matrix of positive integers of size at least 3, classify it according to the definitions above. That is, output one of four different consistent values based on whether the matrix is concave, flat, convex or mixed.

You can compete in any programming language and can take input and provide output through any standard method and in any reasonable format, while taking note that these loopholes are forbidden by default. This is code-golf, so the shortest submission (in bytes) for every language wins.

Test cases

Here's a bunch of examples for you to choose from – I selected 6 from each category.

Concave

[[3, 3, 3], [3, 1, 3], [3, 3, 3]]
[[2, 3, 4], [5, 1, 6], [7, 8, 9]]
[[19, 34, 45], [34, 12, 14], [13, 13, 13]]
[[3, 4, 3, 4], [4, 2, 1, 3], [3, 1, 2, 4], [4, 3, 4, 3]]
[[4, 5, 6, 4, 7], [4, 3, 2, 2, 4], [5, 2, 1, 3, 8], [5, 3, 3, 2, 5], [9, 5, 6, 4, 5]]
[[7, 7, 7, 7, 7], [7, 6, 6, 6, 7], [7, 6, 5, 6, 7], [7, 6, 6, 6, 7], [7, 7, 7, 7, 7]]

Flat

[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
[[2, 2, 2], [2, 2, 2], [2, 2, 2]]
[[8, 8, 8], [8, 8, 8], [8, 8, 8]]
[[120, 120, 120], [120, 120, 120], [120, 120, 120]]
[[10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10], [10, 10, 10, 10]]
[[5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 5, 5]]

Convex

[[1, 2, 1], [2, 6, 2], [1, 2, 1]]
[[1, 1, 1], [1, 2, 1], [1, 1, 1]]
[[19, 34, 45], [34, 76, 14], [13, 6, 13]]
[[3, 3, 3, 3], [3, 4, 4, 3], [3, 4, 4, 3], [3, 3, 3, 3]]
[[192, 19, 8, 6], [48, 324, 434, 29], [56, 292, 334, 8], [3, 4, 23, 23]]
[[291, 48, 7, 5], [47, 324, 454, 30], [58, 292, 374, 4], [9, 2, 53, 291]]

Mixed

[[1, 2, 3], [4, 5, 9], [6, 7, 8]]
[[10, 14, 21], [100, 8, 3], [29, 2, 19]]
[[5, 5, 5, 5], [5, 4, 4, 5], [5, 4, 6, 5], [5, 5, 5, 5]]
[[3, 3, 3, 3], [3, 1, 2, 3], [3, 3, 2, 3], [3, 3, 3, 3]]
[[12, 14, 15, 16], [12, 18, 18, 16], [12, 11, 11, 16], [12, 14, 15, 16]]
[[5, 5, 5, 5, 5], [5, 4, 4, 4, 5], [5, 4, 6, 4, 5], [5, 4, 4, 4, 5], [5, 5, 5, 5, 5]]

Jelly,  18 17  16 bytes
I believe there is a lot of potential for this effort to be out-golfed
L‘HạŒỤṀ€IṠQṢ«FE$

A monadic link accepting a list of lists of numbers which returns a list of integers:
Concave ->  [0, 0]
Flat    ->  [-1, 0, 1]
Convex  ->  [-1, 0]
Mixed   ->  [-1, 0, 0]

Try it online! Or see the test-suite.
L‘H could be replaced with the less efficient but atomically shorter JÆm.
How?
L‘HạŒỤṀ€IṠQṢ«FE$ - Link: list of (equal length) lists of numbers
L                - length
 ‘               - increment
  H              - halve
                 -   = middle 1-based index (in both dimensions as the input is square)
    ŒỤ           - sort multi-dimensional indices by their corresponding values
                 -   = a list of pairs of 1-based indexes
   ạ             - absolute difference (vectorises)
                 -   = list of [verticalDistanceToMiddle, horizontalDistanceToMiddle] pairs
      Ṁ€         - maximum of €ach
                 -   each = N/2-k (i.e. 0 as middle ring and N/2 as outermost)
        I        - incremental deltas (e.g. [3,2,2,3,1]->[3-2,2-2,3-2,1-3]=[-1,0,1,-2])
         Ṡ       - sign (mapping -n:-1; 0:0; and +n:1)
          Q      - de-duplicate
           Ṣ     - sort
                 -   = concave:[0, 1]; convex:[-1, 0]; flatOrMixed:[-1, 0, 1]
               $ - last two links as a monad
             F   -   flatten
              E  -   all equal? (1 if flat otherwise 0)
            «    - minimum (vectorises)
                 -   = concave:[0, 0]; convex:[-1, 0]; mixed:[-1, 0, 0]; flat:[-1, 0, 1]


Draw the Hilbert curve using slashes The Hilbert curve is a space filling fractal that can be represented as a Lindenmayer system with successive generations that look like this:

Thanks to http://www.texample.net/tikz/examples/hilbert-curve/ for the image.
Goal
Write the shortest program possible (in bytes) that takes a positive integer n from stdin and draws the nth order Hilbert curve to stdout using only forward slash, backward slash, space, and newline.
For example, if the input is 1 the output must be
 \
\/

If the input is 2 the output must be
  /
  \/\
/\   \
 / /\/
 \ \
  \/

If the input is 3 the output must be
       \
     /\/
    /   /\
    \/\ \ \
  /\  / / /
 / /  \/  \/\
 \ \/\  /\   \
\/   / / / /\/
  /\/ /  \ \
  \   \/\ \/
   \/\   \
     / /\/
     \ \
      \/

And so on. (They look nicer if you paste them into something with less line spacing.)
The output should not contain newlines above or below the extremities of the curve, nor any trailing spaces on any lines.


Tips for storage in a golfing language I am writing a golfing language.

Do you suggest variables, stack(s), tapes, registers, etc for storage in a code-golf language? What about implicit input?

Rough definitions:

A variable is simply a name (usually one character long in golfing languages) that a value can be assigned to, and later retrieved by that name.
A register is like a variable, but it has its own (usually single-byte) commands for setting/getting the value.
A stack is a variable-length array/list of values, where the most recently added values (the values "on top") are the ones that are being modified.
A queue is like a stack, except the values "on the bottom" are the ones that are being modified.
A tape is a static array/list of values where each value has an index. The main difference between a stack and a tape is that values on a tape are modified in-place.

I would appreciate to know the advantages and disadvantages of each option for different scenarios, and overall. Please avoid opinions, and backup statements with reasoning.

I suggest all of them!

More seriously, they all come in handy some of the time, and the more the better! Implicit input is never bad, just have a flag to turn it off. Variables are helpful so they don't need to be found on a stack or tape; same with registers. Stacks are helpful to store data, and so are tapes. I recommend trying to implement multiple, say a stack and registers, or a stack and variables, like GolfScript. If you can make each function one byte, then your language will probably be effective at golfing, as you can use the advantages of each.

An example:

Say I want to take two numbers as inputs, and add their string lengths
Variables might be better for this (a stack might not)
Example code in GolfScript (with implicit input):

~,\,+
~ # Eval input (e.g. "1 2" > 1, 2)
, # Take Length
\ # Reverse items on the stack
, # Take Length
+ # Add
  # Implicit output

However, with variables (I know it's longer, it just doesn't have to swap places on the stack):

~,:a;,:b;ab+
~ # Eval input
, # Get length
:a# Store in "a"
; # Discard value left on stack
, # Length
:b# Store in "b"
; # Discard
a # Recall a
b # Recall b
+ # Add
  # Implicit output

Overloads

Another thing that can be helpful is overloads. For example, if you have a variable storing function, maybe it could be used as a monad (one-input function; I'm not sure of the term out side of J/K/APL) to add to the stack or tape.

Example:

c12 # Stores "1" into register 2
c1] # Pushes "1" onto the stack ("]" is used to denote the end of the monad)


Write a compressing util for gzip files The task of this challenge is as following:
Write a program that reads a file of reasonable size (let's say <16 MB) from stdin or anywhere else (however you like, but must not be hardcoded), and put's the compressed output onto stdout. The output must be a valid gzip compressed file and if the compressed file runs through gunzip, it should yield exactly the same file as before.
Rules

The programming language used must be known before this competition started
The score of your program is the number of characters of the source code or the assembled program (whatever is shorter)
You're not allowed to use any kind of existing compression libraries.
Have fun!

C# (534 characters)

using System.IO;using B=System.Byte;class X{static void Main(string[]a){var f=File.ReadAllBytes(a[0]);int l=f.Length,i=0,j;var p=new uint[256];for(uint k=0,r=0;k<256;r=++k){for(j=0;j<8;j++)r=r>>1^(r&1)*0xedb88320;p[k]=r;}uint c=~(uint)0,n=c;using(var o=File.Open(a[0]+".gz",FileMode.Create)){o.Write(new B[]{31,139,8,0,0,0,0,0,4,11},0,10);for(;i<l;i++){o.Write(new B[]{(B)(i<l-1?0:1),1,0,254,255,f[i]},0,6);c=p[(c^f[i])&0xFF]^c>>8;}c^=n;o.Write(new[]{(B)c,(B)(c>>8),(B)(c>>16),(B)(c>>24),(B)l,(B)(l>>8),(B)(l>>16),(B)(l>>24)},0,8);}}}

Much more readable:

using System.IO;
using B = System.Byte;
class X
{
    static void Main(string[] a)
    {
        // Read file contents
        var f = File.ReadAllBytes(a[0]);
        int l = f.Length, i = 0, j;

        // Initialise table for CRC hashsum
        var p = new uint[256];
        for (uint k = 0, r = 0; k < 256; r = ++k)
        {
            for (j = 0; j < 8; j++)
                r = r >> 1 ^ (r & 1) * 0xedb88320;
            p[k] = r;
        }

        uint c = ~(uint) 0, n = c;

        // Write the output file
        using (var o = File.Open(a[0] + ".gz", FileMode.Create))
        {
            // gzip header
            o.Write(new B[] { 31, 139, 8, 0, 0, 0, 0, 0, 4, 11 }, 0, 10);
            for (; i < l; i++)
            {
                // deflate block header plus one byte of payload
                o.Write(new B[] { (B) (i < l - 1 ? 0 : 1), 1, 0, 254, 255, f[i] }, 0, 6);
                // Compute CRC checksum
                c = p[(c ^ f[i]) & 0xFF] ^ c >> 8;
            }
            c ^= n;
            o.Write(new[] {
                // CRC checksum
                (B) c, (B) (c >> 8), (B) (c >> 16), (B) (c >> 24),
                // original file size
                (B) l, (B) (l >> 8), (B) (l >> 16), (B) (l >> 24)
            }, 0, 8);
        }
    }
}

Comments:

Expects path to file as first command-line argument.
Output file is input file + .gz.
I am not using any libraries to do the gzip, deflate or CRC32. It’s all in there.
This “compressor” increases the filesize by a factor of 6. But it’s in valid gzip format!
Tested using GNU gunzip and WinRAR.


Implement a Graphing Calculator There have been many questions involving calculators; however, it does not appear that any involve implementing a graphing calculator.

The Challenge

You are to write a complete program that takes multiple formulas as input from STDIN and graphs them to STDOUT. Input will take the form f1(x)=x^2-x-1. There will be an f followed by a number 0-9 (inclusive), followed by (x)=, followed by the formula to graph. Your program should be able to take input, graph, take more input, graph, etc.

This is code golf.

Your graph should have the X-axis range from -5 to 5, with a resolution of at least one point every 1/2 unit. Y-axis requirements are the same. This may seem like a small range compared to modern calculators, but it will most likely be trivial in increase this. The graph should have the axis drawn on them, with tick marks in the form of + on the integers.

The formula should be evaluated with the normal order of operation. There will not be any vertical asymptotes/undefined regions in these formulas. The variable will always be x.  If two formulas are entered with the same equation number, the oldest one should be erased and replaced with the new formula. Blank formulas should evaluate to zero. Since it is likely that the formula will not always give a nice multiple of 1/2, you are to round to the nearest 1/2.

When a formula is graphed, its line should be formed out of the number of the formula. When a line crosses an axis, the axis should be drawn on top. When two lines cross each other, it does not matter which is shown.

Example Input

f1(x)=x+1

Output

          +       1
          |      1
          +     1
          |    1
          +   1
          |  1
          + 1
          |1
          +
         1|
+-+-+-+-+-+-+-+-+-+-+
       1  |
      1   +
     1    |
    1     +
   1      |
  1       +
 1        |
1         +
          |
          +

Input

f2(x)=(x^2)^0.25

Output

          +       1
          |      1
          +     1
          |    1
          +   1
          |  1
2222      + 1    2222
    222   |1  222
       22 + 22
         2|2
+-+-+-+-+-+-+-+-+-+-+
       1  |
      1   +
     1    |
    1     +
   1      |
  1       +
 1        |
1         +
          |
          +

Input

f1(x)=-x

(note, it is acceptable for your program to reject this input and only except 0-x or x*-1, but this should be documented)

Output

1         +
 1        |
  1       +
   1      |
    1     +
     1    |
2222  1   +      2222
    2221  |   222
       22 + 22
         2|2
+-+-+-+-+-+-+-+-+-+-+
          |1
          + 1
          |  1
          +   1
          |    1
          +     1
          |      1
          +       1
          |        1
          +         1

Ruby, 200 characters
f={}
r=0..20
(f[gets[1]]=$_[6..-1].gsub /\^/,'**'
s=r.map{' '*21}
f.map{|n,k|r.map{|y|x=y*0.5-5
v=(2*eval(k)).round
v.abs<11&&y!=10&&s[10-v][y]=n
s[y][10]='+|'[y%2]
s[10][y]='+-'[y%2]}}
puts s)while 1

A plain ruby implementation using the standard evaluator for expressions (^ will be replaced so that the examples given above work fine). It is not very robust and assumes the input exactly as specified in the question.


Magic square generator Create the shortest function to print a magic square of given size.

A magic square is a NxN matrix of distinct numbers and the sum of each row, column and diagonal is equal to a constant.

A magic square of size 4 is:

07 12 01 14
02 13 08 11
16 03 10 05
09 06 15 04

And the constant is 34.

The function should be able to handle inputs up to N = 30 and doesn't need to show leading zeroes.

Using Matlab's magic function or similar built-in function is not allowed.

More useful information: http://mathworld.wolfram.com/MagicSquare.html

::Edit::

The output doesn't need to be pretty printed and may contain [](){}, or List/Array delimiters of your language. Although, it should use one line for each row

E.g.

1, 2,
3, 4,

((9,8),
 (6,7))

[10 2]
[3 456]

PS: The corner case, when N = 2 is undefined behavior as there's no magic square of that size.

Also, the function should complete in less than 1 minute to avoid brute force.

Ruby, 344 characters
q=->n{r=0...n;n%2>0?(m=r.map{[]*n};x=n/2;y=i=0;r.map{r.map{m[y%=n][x%=n]=i+=1;x+=1;y-=1};x-=1;y+=2};m):n<5?[[16,3,2,13],[5,10,11,8],[9,6,7,12],[4,15,14,1]]:(d=q[n/2];r.map{|y|r.map{|x|4*d[b=y/2][a=x/2]-[0,3,2,1,3,0,2,1,3,0,1,2][(n/2%2<1?b<n/4?0:8:a==n/4&&b==n/4?4:a==n/4&&b==n/4+1?0:b<=n/4?0:b==n/4+1?4:8)+y%2*2+x%2]}})}
Q=->n{q[n].map{|s|p s}}

You can use it e.g. like
Q[3]

and the output will be
[8, 1, 6]
[3, 5, 7]
[4, 9, 2]

The solution is not yet fully golfed. Also huge squares are generated reasonably fast. It uses a recursive function q to generate the squares unless n is odd in which case the square is generated directly or n==4 which is hard-coded.


Console print a bar graph The objective is to print a graph from an array of numbers, of the design below. Printing the X and Y scale exactly as in the "design", with padding, is part of the challenge. The input array of numbers can be of virtually any range of integers in X and Y, but not 0 and not negative - though I would suggest keeping it small considering this is ASCII art! (x < 15, y < 50 or so).

Specifics

1) the graph should print the Y scale on the left, padded to the max length of the input, and with a pipe '|' between the number and the first column.

2) the bar should have all empty spaces with periods '.' filled spaces with pipes '|' and the number itself should be an 'o'.

3) there are three "tween" columns between each number that interpolates between the two numbers. These cannot just be a duplication of the previous or next column, but need to interpolate between the values linearly. (Unless two adjacent numbers in the list are only 1 apart or the same.)

4) The bottom of the graph should look: "  +---------" to the length of the graph.

5) There should be an X scale padded to the length of the max number, similar to the Y scale. The last digit of the x scale should align with the value (I guess that means we're limited to two digits...)

6) Lastly, there should be an "empty" column in the beginning of the graph and an "empty" column at the end.

Example

This:

 [5, 3, 7, 8, 10, 7, 8, 7, 9, 2]

Generates:

10|.................o.....................
09|................||...............o.....
08|.............o|||||......o......||.....
07|.........o||||||||||.o|||||..o||||.....
06|........|||||||||||||||||||||||||||....
05|.o.....||||||||||||||||||||||||||||....
04|.||...|||||||||||||||||||||||||||||....
03|.|||.o||||||||||||||||||||||||||||||...
02|.|||||||||||||||||||||||||||||||||||.o.
01|.|||||||||||||||||||||||||||||||||||||.
  +---------------------------------------
   01  02  03  04  05  06  07  08  09  10

Trailing spaces on each line, or trailing newlines at the end are permitted. As long as the output is visually the same.

Here's a working Python3 example, in "long hand" if you wish:

Try it online!


Primitive roots density of number Definition:

A number m is called a primitive root of a prime p the condition that  the smallest integer k for which p dividies mk-1 is p-1

Your task
Given a tuple (a,b) of positive integers, return the fraction:
(number of primes p equal to or less than a which has b as a primitive root) divided by (number of primes equal to or less than a)
Test Cases
Assuming Artin's Conjecture to be true, giving (A very big number, 2) should return a value around .3739558136...
The challenge is for the fastest code, not necessarily the shortest one.
Timing
My crappy code takes 10 seconds for a million on my PC (intel i3 6th Gen, 8GB RAM, others I forgot), so your code should naturally beat that speed.
This is my first challenge. Feeback is appreciated. :)

C (gcc)

Around 0.6 sec for 1,000,000.

int modpow(long b,int e,long n){
	long r=1;
	while(e){
		if(e&1) r=r*b%n;
		b=b*b%n;
		e>>=1;
	}
	return r;
}
float f(int a,int b){
	int ln=1;
	for(int p=2;p<=a;p*=ln,ln++);
	int* primes = malloc((a+1)*(sizeof(int)));
	int** factors = malloc((a+1)*sizeof(int*));
	primes[0] = 0;
	primes[1] = 0;
	for(int i=2;i<=a;i++){
		primes[i] = 1;
		factors[i] = malloc(ln*sizeof(int));
	}
	factors[1] = malloc(sizeof(int));
	factors[1][1] = 0;
	for(int p=2;p*p<=a;p++){
		if(primes[p]){
			for(int j=p*2;j<=a;j+=p){
				primes[j] = 0;
				factors[j][0]++;
				factors[j][factors[j][0]] = p;
			}
		}
	}
	int count1 = 0;
	int count2 = 0;
	for(int p=2;p<=a;p++){
		if(!primes[p]) continue;
		count2++;
		int n=p-1;
		int m=p-1;
		int prim=1;
		for(int j=1;j<=factors[n][0];j++){
			int q=factors[n][j];
			if(modpow(b,n/q,p)==1){
				prim=0;
				break;
			}
			while(m%q==0){
				m/=q;
			}
		}
		if(m>1){
			if(modpow(b,n/m,p)==1){
				prim=0;
			}
		}
		count1 += prim;
	}
	return (float)count1/count2;
}

Try it online!


Find the rate of change at a point on a polynomial Given the equation of a polynomial and an x-coordinate find the rate of change of the point at that x-coord on the curve.

A polynomial is in the form: axn + axn-1 + ... + ax1 + a, where a ϵ Q and n ϵ W. For this challenge, n can also be 0 if you don't want to have to deal with special cases (constants) where there is no x.

To find the rate of change at that x-coord, we can get the derivative of the polynomial and plug in the x-coord.

Input

The polynomial can be taken in any reasonable form, but you must state what that format is explicitly. For example, an array of the form [..[coefficient, exponent]..] is acceptable.

Output

The rate of change of the point at the x-coord given.

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

Examples

[[4, 3], [-2, 4], [5, 10]]   19    ->   16134384838410
                  [[0, 4]]  400    ->   0
           [[4, 0], [5,1]]  -13    ->   5
      [[4.14, 4], [48, 2]]   -3    ->   -735.12
         [[1, 3], [-5, 0]]    5.4  ->   87.48

Mathematica, 6 bytes
#'@#2&

(Beat THAT, MATL and 05AB1E)
The first argument must be a polynomial, with # as its variable and with & at the end (i.e. a pure function polynomial; e.g. 3 #^2 + # - 7 &). The second argument is the x-coordinate of the point of interest.
Explanation
#'

Take the derivative of the first argument (1 is implied).
... @#2&

Plug in the second argument.
Usage
#'@#2&[4 #^3 - 2 #^4 + 5 #^10 &, 19] (* The first test case *)

16134384838410


Return each number from a group of numbers The challenge

The program must return all numbers included into a group (comma and hyphen separated sequence) of numbers.

Rules

s is the sequence string;
all numbers included in s are positive;
numbers will always increase;
numbers will never repeat
when you answer, show the output for s="1,3-5,9,16,18-23"

Examples

input(s)    outputs
-----------------
1           1
1,2         1,2
1-4         1,2,3,4
1-4,6       1,2,3,4,6
1-4,8-11    1,2,3,4,8,9,10,11

Good luck. =)

Perl 25 26 25

$_ is the sequence string

s/-/../g;$_=join",",eval

Sample session:

[~/] $ perl -M5.010 -pe 's/-/../g;$_=join",",eval' <<< "1,3-5,9,16,18-23"
1,3,4,5,9,16,18,19,20,21,22,23

Added 1 character to the character count for the -n-p option (thanks Gareth, ..kinda).


Finding Exclusive Area in Circle Intersections Here's a deceptively challenging geometry puzzle for you!
Given a circle A, and n other circles B[n], find the total area contained within A that is not within any circle of B.
Your code should be as short as possible.
Input
Your input should contain the following information:

A floating-point number to represent the radius of circle A.
A list of floating-point numbers to represent the radii of circles in B.
A list of the centers of circles in B. Your program may expect the centers in either polar or Cartesian coordinates.
Optionally, you may receive the number n of circles in B. This input is not required.

It shall be assumed that the center of circle A is the origin, that is, the point (0, 0).
It is guaranteed that no two circles in B are identical, but it is not guaranteed that: all circles of B intersect A, all centers of B are outside A, or no two circles in B intersect each other. Ensure that your solution can handle various edge cases.
You may receive input in any order, and in the form of text input (through stdin or your language's equivalent), function parameters, or command-line arguments.
If you choose to receive text input, there should be one or two-character printable ASCII delimiters between pieces of input.
Output
Your program or function should output a single floating-point number representing the total area of A not within any of the circles of B. Your answers should be accurate to at least three significant figures for all test cases.
General code-golf rules apply.
Your solution should not rely on sampling points within the circles to determine an area.
Built-ins that automatically locate intersections of circles, find areas within intersections of circles, or solve this problem immediately are disallowed.
Test Cases
In each image, circle A is outlined in blue, with circles B outlined in green and filled black. The area that should be returned is filled red.
(Special thanks to Rainer P. for checking my solutions)
Test case 1:
A = {x: 0, y: 0, rad: 50}
B[0] = {x: 0, y: 0, rad: 100}

Result: 0.00

Test case 2:
A = {x: 0, y: 0, rad: 100.000000}
B[0] = {x: 100.000000, y: 0.000000, rad: 50.000000}
B[1] = {x: 30.901699, y: -95.105652, rad: 50.000000}
B[2] = {x: -80.901699, y: -58.778525, rad: 50.000000}
B[3] = {x: -80.901699, y: 58.778525, rad: 50.000000}
B[4] = {x: 30.901699, y: 95.105652, rad: 50.000000}

Result: 1.3878e+04

Test case 3:
A = {x: 0, y: 0, rad: 138}
B[0] = {x: 100, y: 0, rad: 100}
B[1] = {x: -50, y: -86, rad: 100}
B[2] = {x: -93, y: 135, rad: 50}

Result: 1.8969e+04

Test case 4:
A = {x: 0, y: 0, rad: 121.593585}
B[0] = {x: 81.000000, y: 107.000000, rad: 59.841457}
B[1] = {x: -152.000000, y: -147.000000, rad: 50.000000}
B[2] = {x: 43.000000, y: -127.000000, rad: 105.118980}
B[3] = {x: 0.000000, y: -72.000000, rad: 57.870545}
B[4] = {x: -97.000000, y: -81.000000, rad: 98.488578}
B[5] = {x: -72.000000, y: 116.000000, rad: 66.468037}
B[6] = {x: 2.000000, y: 51.000000, rad: 50.000000}

Result: 1.1264e+04

Test case 5:
A = {x: 0, y: 0, rad: 121.605921}
B[0] = {x: 0.000000, y: -293.000000, rad: 250.000000}
B[1] = {x: 0.000000, y: -56.000000, rad: 78.230429}
B[2] = {x: 0.000000, y: -102.000000, rad: 100.000000}

Result: 2.6742e+04

Suggested reading:
Fewell, M. P. "Area of Common Overlap of Three Circles." Oct. 2006. Web. http://dspace.dsto.defence.gov.au/dspace/bitstream/1947/4551/4/DSTO-TN-0722.PR.pdf.

Python 2, 631 bytes

from cmath import*
C=input()
O,R=C[0]
def I(p,r,q,s):
 try:q-=p;d=abs(q*q);x=(r*r-s*s+d)/d/2;return[p+q*(x+z*(r*r/d-x*x)**.5)for z in-1j,1j]
 except:return[]
S=sorted
V=S(i.real for p,r in C for c in C for i in[p-r,p+r]+I(p,r,*c)if-R<=(i-O).real<=R)
A=pi*R*R
for l,r in zip(V,V[1:]):
 H=[]
 for p,t in C:
    try:
     for s in-1,1:a,b=[p.imag+s*(t*t-(p.real-x)**2)**.5for x in l,r];H+=[a+b,a,b,s,t,p],
    except:0
 a,b=H[:2];H=S(H[2:]);n=0;c=a
 for d in H:
    s=d[3];z=.5;H*=d<b
    for q,w,e,_,t,y in(c,min(d,b))*(n-s<(a<d)or[0]*n>H):\
g=phase((l+w*1j-y)/(r+e*1j-y));A-=abs(g-sin(g)).real*t*t/2-z*q*(r-l);z=-z
    n-=s
    if(a<d)*s*n==-1:c=d
print A

Line-breaks preceded by \ are for easy reading, and aren't counted in the score.

Reads input through STDIN as a list of (center, radius) pairs, where center is a complex number in the form X+Yj.
The first circle in the list is A (whose center doesn't have to be at the origin), and the rest of the list is B.
Prints the result to STDOUT.

Example

Input:  (0+0j, 138),  (100+0j, 100), (-50+-86j, 100), (-93+135j, 50)
Output: 18969.6900901

Explanation

This is a (longer, and much uglier :P) variation on my solution to Martin Büttner's Area of a Self-Intersecting Polygon challenge.
It uses the same trick of breaking the problem down into small-enough pieces, for which it becomes more manageable.

We find the points of intersection between all pairs of circles (considering both A, and the circles in B), and pass a vertical line through each of them.
Additionally, we pass all the vertical lines tangent to any of the circles.
We throw away all the lines that don't intersect A, so that all the remaining lines are between the left and right tangents of A.

We're looking for the area of the intersection of A and the union of the circles in B—the dark red area in the illustration above.
This is the area that we have to subtract from A to get the result.

Between each pair of consecutive vertical lines, this area can be broken down into a set of vertical trapezoids (or triangles, or line segments, as special cases of trapezoids), with an "excess" arc segment next to each leg.
The fact that we pass as many vertical lines as we do guarantees that the bounded area is indeed no more complicated than that, since otherwise there would have to be an additional point of intersection, and hence an additional vertical line, between the two lines in question.

To find these trapezoids and arc segments, for each pair of consecutive vertical lines, we find the arc segments of each of the circles that properly lie between these two lines (of course, some circles may have no arc segment between a given pair of lines.)
In the illustration below, these are the six (bright and dark) yellow arc segments, when considering the two red vertical lines.
Note that, since we pass all vertical lines tangent to the circles, if a circle has an arc segment between the two lines, it necessarily intersects both lines, which simplifies the rest of the algorithm.

Not all of these arcs are relevant; we're only interested in the ones that are on the boundary of the intersection between A and the union of B.
To find those, we sort the arcs top-to-bottom (note that the arcs may not properly intersect each other, since this would imply the existence of another vertical line between the two we're considering, and so it makes sense to talk about an arbitrary arc being above, or below, any other one.)

We traverse the arcs, in order, while keeping count of the number of B circles we're currently inside, n.
If n changes from 0 to 1 while we're inside A, or if we're at the top arc of A while n is nonzero, then the current arc corresponds to one leg of a trapezoid.
If n changes from 1 to 0 while we're inside A, or if we're at the bottom arc of A while n is nonzero, then the current arc corresponds to the other leg of the same trapezoid.
Once we find such a pair of arcs (the two bright yellow arcs in the above illustration), we calculate the area of the corresponding trapezoid, and of the two arc segments, and add it to the total area to be subtracted from A.

Calculating the area of A, as well as the areas of the trapezoids, is fairly straight forward.
The area of each arc segment is the area of the corresponding circular sector, minus the area of the triangle whose vertices are the two endpoints of the arc segment, and the center of the corresponding circle.


Point in convex hull (2D) Background

The convex hull of a finite number of points is the smallest convex polygon that contains all of the points, either as vertices or on the interior. For more information, see this question on PGM which defines it very well.

Input

N+1 2-D coordinates (N >= 3) passed through STDIN (with other usual golf inputs allowed too) in the following format (the number of decimals can vary but you can assume it remains "reasonable" and each number can be represented as a float):

0.00;0.00000
1;0.00
0.000;1.0000
-1.00;1.000000

Output

A truthy value printed to STDOUT (or equivalent) if the first point in the list ((0.00;0.00000) in the example above) is in the convex hull of the other N points, and a falsy value otherwise.

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

Border cases: you can return any value (but don't crash) if the point lies on the border of the convex hull (i.e. on a side or on a vertex on the outer frontier of the hull), since it is a zero probability event (under any reasonable probability).
Forbidden: anything (language, operator, data structure, built-in or package) that exists only to solve geometric problems (e.g. Mathematica's ConvexHull). General purpose mathematical tools (vectors, matrices, complex numbers etc.) are allowed.

Tests

Should return TRUE: spiralTest1-TRUE, squareTest1-TRUE
Should return FALSE: spiralTest2-FALSE, squareTest2-FALSE

J, 40 39 34 bytes

3 :'(o.1)<(>./-<./)12 o.y*+{.y'@:-

An anonymous dyadic function, taking a point, p, as one of its arguments, and a list of points, P, as the other argument (it doesn't matter which argument is which), and returning 0 or 1, if p is outside or inside the convex hull of P, respectively.
The point p, and the points in P, are taken as complex numbers.

Example

  is_inside =: 3 :'(o.1)<(>./-<./)12 o.y*+{.y'@:-

  0.5j0.5  is_inside  0j0 0j1 1j0 1j1
1
  1.5j0.5  is_inside  0j0 0j1 1j0 1j1
0

or...

Python 2, function, 121 103, full program, 162

Python 3, 149 bytes

import sys,cmath as C
p,q,*P=[complex(*eval(l.replace(*";,")))for l in sys.stdin]
A=[C.phase((r-p)/(q-p+(q==p)))for r in P]
print(max(A)-min(A)>C.pi)

Takes input, in the same format as the original post, through STDIN, and prints a boolean value indicating whether p is in the convex hull of P

Explanation

The program tests whether the difference between the maximum and minimum (signed) angles between any point r in P, p, and a fixed arbitrary point q in P (we just use the first point in P), is less than 180°.
In other words, it tests whether all the points in P are contained in an angle of 180° or less, around p.
p is in the convex hull of P if and only if this condition is false.

At the cost of a few more bytes, we can use a similar method that doesn't require us to explicitly calculate angles:
Note that the above condition is equivalent to saying that p is outside the convex hull of P if and only if there exists a line l through p, such that all the points in P are on the same side of l.
If such a line exists, then there's also such a line that is incident to one (or more) of the points in P (we can rotate l until it touches one of the points in P.)

To (tentatively) find this line, we start by letting l be the line through p and the first point in P.
We then iterate over the rest of the points in P; if one of the points is to the left of l (we assume some directionality throughout, left or right doesn't really matter,) we replace l with the line passing through p and that point, and continue.
After we iterated over all of P, if (and only if) p is outside the convex hull, then all the points in P should be to the right of (or on) l.
We check that using a second pass over the points in P.

Python 2, 172 bytes

import sys
P=[eval(l.replace(*";,"))for l in sys.stdin]
x,y=P.pop(0)
C=lambda(a,b),(c,d):(a-x)*(d-y)-(b-y)*(c-x)>0
l=reduce(lambda*x:x[C(*x)],P)
print any(C(l,q)for q in P)

Alternatively, to do the same thing in a single pass, let to-the-left-of be a realtion between any two points, q and r, in P, such that q is to the left of r if q is to the left of the line passing through p and r.
Note that to-the-left-of is an order relation on P if and only if all the points in P are on the same side of some line passing through p, that is, if p is outside the convex hull of P.
The procedure described above finds the minimum point in P w.r.t. this order, i.e., the "leftmost" point in P.
Instead of performing two passes, we can find the maximum (i.e., the "rightmost" point), as well as the minimum, points in P w.r.t. the same order in a single pass, and verify that the minimum is to the left of the maximum, i.e., effectively, that to-the-left-of is transitive.

This would work well if p is outside the convex hull of P, in which case to-the-left-of is actually an order relation, but may break when p is inside the convex hull (for example, try to figure out what will happen if we ran this algorithm where the points in P are the vertices of a regular pentagon, running counter-clockwise, and p is its center.)
To accommodate, we slightly alter the algorithm:
We select a point q in P, and bisect P along the line passing through p and q (i.e., we partition P around q w.r.t. to-the-left-of.)
We now have a "left part" and a "right part" of P, each contained in a halfplane, so that to-the-left-of is an order relation on each; we find the minimum of the left part, and the maximum of the right part, and compare them as described above.
Of course, we don't have to physically bisect P, we can simply classify each point in P as we look for the minimum and maximum, in a single pass.

Python 2, 194 bytes

import sys
P=[eval(l.replace(*";,"))for l in sys.stdin]
x,y=P.pop(0)
C=lambda(a,b),(c,d):(a-x)*(d-y)-(b-y)*(c-x)>0
l=r=P[0]
for q in P:
 if C(P[0],q):l=q*C(l,q)or l
 elif C(q,r):r=q
print C(l,r)


Check if 2 arrays contain the same element Write a program which will take for input 2 integer arrays and return a truthy value if there exists an element which is present in both of arrays, or a falsy one otherwise. The obvious solution to this problem would be to iterate through each element in the first array and compare it against each element in the second, but here's the catch: Your program must have an algorithmic complexity of at most, in the worst case, O(NlogN), where N is the length of the longer array,

Test cases:

 {1,2,3,4,-5},{5,7,6,8} -> false
 {},{0}                 -> false
 {},{}                  -> false
 {1,2},{3,3}            -> false
 {3,2,1},{-4,3,5,6}     -> true
 {2,3},{2,2}            -> true

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

Actually, 1 byte
∩

Try it online!
This is merely the set intersection built-in. The resultant value is the intersection of the two sets - a non-empty list (which is a truthy value) if there is an intersection, and an empty list (which is a falsey value) otherwise.
Complexity
According to the Python Wiki, set intersection has a worst-case time complexity of O(N*M) (where N and M are the lengths of the two sets). However, the time complexity is only that bad when the two sets contain distinct objects that all have the same hash value (for example, {"some string"} & {hash("some string")}). Since the set elements are only integers in this case (and no two integers hash to the same value unless they are equal), the actual worst-case complexity is O(min(N, M)) (linear in the length of the smaller of the two sets). The construction of each set is O(N) (linear in the number of elements), so the overall complexity is O(max(N, M)) (the complexity is dominated by the construction of the larger set).