text:
Delete some bits and count
Consider all 2^n different binary strings of length n and assume n > 2.  You are allowed to delete exactly b < n/2 bits from each of the binary strings, leaving strings of length n-b remaining. The number of distinct strings remaining depends on which bits you delete. Assuming your aim is to leave as few remaining different strings as possible, this challenge is to write code to compute how few can you leave as a function of n.
Example, n=3 and b = 1.  You can leave only the two strings 11 and 00.
For n=9 and b = 1,2,3,4 we have 70,18,6,2
For n=8 and b = 1,2,3 we have 40,10,4
For n=7 and b = 1,2,3 we have 20,6,2
For n=6 and b = 1,2 we have 12,4
For n=5 and b = 1,2 we have 6,2
This question was originally posed by me in 2014 in a different form on MO.
Input and output
Your code should take in an integern and output a single integer for each value of b starting at b = 0 and increasing.
Score
Your score is the largest n for which your code completes for all b < n/2 in under a minute on my Linux based PC.  In case of tie breaks, the largest b your code gets to for the joint largest n wins. In case of tie breaks on that criterion too, the fastest code for the largest values of n and b decides. If the times are within a second or two of each other, the first posted answer wins.
Languages and libraries
You can use any language of library you like. Because I have to run your code, it would help if it was free (as in beer) and worked in Linux.

I'm assuming b > 0 as additional input-requirement? Or would n=3 and b=0 simply output 2^n as result?

@KevinCruijssen It should output 2^n indeed.

Also, you say the input is a single n and a single b, but the score is the largest n for which the code completes all b < n/2 in under a minute. Wouldn't it be better to have a single input n in that case, and output all results for 0 <= b < n/2? Or should we provide two programs/functions: one taking two inputs n and b, and one taking only input n and outputting all results in the range 0 <= b < n/2?

@KevinCruijssen Thanks. I have applied your fix.

Well, I had already upvoted your challenge, so can't do it again. :) Although I have no idea how to calculate this efficiently (efficient O algorithms were something I've always been bad at.. and one of the few subjects at IT college I had to redo a couple of times), it does seem like a very interesting challenge. I'm curious to see what answers people come up with.

@KevinCruijssen Brute force. With some smart optimizations.

Is there a working example? It would be a good place to start, both in terms of correctness, but also for comparison of speed.

For each b the first few n seem always [2,4,6,10]?

but there are so many lists that match [2,4,6,10,18] on OEIS

@maxb Hopefully the examples in the question cover correctness. I don't have sample code, sorry.

I had to read over this several times. Am I correct to assume that for n = 4 and b = 1 that the answer would be 4? (000, 111, 011, and 100)

@Centijo Yes that works.

"the first posted answer wins" Shouldn't the tie breaker be fastest completion of the highest completed? For example, if two answers both can complete up to n=12;b=4 and timeout on n=12;b=5, shouldn't the win go to the code that completes n=12;b=4 the fastest?

@mypetlion You are right. I have changed it now.

Out of curiosity: what's the motivation for considering such a problem? You mention that you asked about it some time ago on MO. Does this problem have some applications in practice or theory? It looks really interesting.

@Radek Just recreational math I am afraid.

How many cores does your PC have? In other words: is it worth considering a concurrent solution?

@UdoBorkowski Yes! I has 4 real cores.

Python 2.7 / Gurobi n=9
This solution is very straight usage of Gurobi's ILP solver for the boolean Mixed-Integer Problems (MIP).
The only trick is to take out symmetry in 1's complement to halve the problem sizes.
Using Gurobi LLC's limited time "free" licence we are restricted to 2000 constraints, but solving 10 del 1 is well outside the 60 second time-limit anyway on my laptop.
from gurobipy import *
from itertools import combinations

def mincover(n,d):
    bs = pow(2,n-1-d)
    m = Model()
    m.Params.outputFlag = 0
    b = {}
    for i in range(bs):
      b[i] = m.addVar(vtype=GRB.BINARY, name="b%d" % i)
    m.update()
    for row in range(pow(2,n-1)):
      x = {}
      for i in combinations(range(n), n-d):
        v = 0
        for j in range(n-d):
          if row & pow(2,i[j]):
            v += pow(2,j)
        if v >= bs:
          v = 2*bs-1-v
        x[v] = 1
      m.addConstr(quicksum(b[i] for i in x.keys()) >= 1)
    m.setObjective(quicksum(b[i] for i in range(bs) ), GRB.MINIMIZE)
    m.optimize()
    return int(round(2*m.objVal,0))

for n in range(4,10):
    for d in range((n//2)+1):
        print n, d, mincover(n,d)

UPDATE+CORR: 10,2 has optimal solution size 31 (see e.g.) Gurobi shows no symmetric solution of size 30 exists (returns problem infeasible) .. [my attempt to show asymmetric feasibility at 30 remained inconclusive after 9.5hrs runtime]
e.g. bit patterns of integers 0 7 13 14    25 28 35 36 49 56 63 64 95 106 118 128 147 159 170 182 195 196 200 207 225 231 240 243 249 252 255 or 0 7 13 14 19 25 28 35 36 49 56 63 64 95 106 118 128     159 170 182 195 196 200 207 225 231 240 243 249 252 255

You broke the "fastest claimed infinite bounty" record?

I don't see any bounty here, what do you mean?

@user202729 Yes.. I set it too low. I should have set it at n = 10 :)

Actually solving it at n=9 is not an easy thing. That's why OP use an existing library (which is supposed to be better than a hand-written solution, like mine).

Does your remark about symmetry mean that you assume that (at least) some optimal solution has a set of remaining binary strings  that is closed under bitwise complement? That seems plausible, but not obvious, and the question on MO claims that some (this?) symmetry does not hold.

Thanks @ChristianSievers I see MO claim that 10,2 has only asymmetric optima which I cannot refute nor verify.  If I remove the symmetry assumption shortcut which works up to n=9 it turns out Gurobi can still solve up to n=9 in the time required.

@Christian - I have now confirmed 10,2 has optimum size of 31

Why are you sure that no asymmetric solution of size 30 can exist? And shouldn't the all-1 pattern (255) appear among the numbers?

Your skepticism is entirely justified .. working on fixing both those errors.

I updated the bounty by the way.

C++, n=6
Brute force with some small optimizations.
#include<cassert>
#include<iostream>
#include<vector>

// ===========
/** Helper struct to print binary representation.
`std::cout<<bin(str,len)` prints (str:len) == the bitstring
represented by last (len) bits of (str).
*/
struct bin{
    int str,len;
    bin(int str,int len):str(str),len(len){}
};
std::ostream& operator<<(std::ostream& str,bin a){
    if(a.len)
        return str<<bin(a.str>>1,a.len-1)<<char('0'+(a.str&1));
    else if(a.str)
        return str<<"...";
    else
        return str;
}
// ===========

/// A patten of (len) bits of ones.
int constexpr pat1(int len){
    return (1<<len)-1;
}

// TODO benchmark: make (res) global variable?

/**Append all distinct (subseqs+(sfx:sfxlen)) of (str:len)
with length (sublen) to (res).
*/
void subseqs_(
    int str,int len,int sublen,
    int sfx,int sfxlen,
    std::vector<int>& res
){
    // std::cout<<"subseqs_ : str = "<<bin(str,len)<<", "
    // "sublen = "<<sublen<<", sfx = "<<bin(sfx,sfxlen)<<'\n';

    assert(len>=0);

    if(sublen==0){ // todo remove some branches can improve perf?
        res.push_back(sfx);
        return;
    }else if(sublen==len){
        res.push_back(str<<sfxlen|sfx);
        return;
    }else if(sublen>len){
        return;
    }

    if(str==0){
        res.push_back(sfx);
        return;
    }

    int nTrail0=0;
    for(int ncut;str&&nTrail0<sublen;

        ++nTrail0,
        ncut=__builtin_ctz(~str)+1, // cut away a bit'0' of str
        // plus some '1' bits
        str>>=ncut,
        len-=ncut
    ){
        ncut=__builtin_ctz(str)+1; // cut away a bit'1' of str
        subseqs_(str>>ncut,len-ncut,sublen-nTrail0-1,
            sfx|1<<(sfxlen+nTrail0),sfxlen+nTrail0+1,
            res
        ); // (sublen+sfxlen) is const. TODO global var?
    }

    if(nTrail0+len>=sublen) // this cannot happen if len<0
        res.push_back(sfx);
}

std::vector<int> subseqs(int str,int len,int sublen){
    assert(sublen<=len);
    std::vector<int> res;
    if(__builtin_popcount(str)*2>len){ // too many '1's, flip [todo benchmark]
        subseqs_(pat1(len)^str,len,sublen,0,0,res);
        int const p1sublen=pat1(sublen);
        for(int& r:res)r^=p1sublen;
    }else{
        subseqs_(str,len,sublen,0,0,res);
    }
    return res;
}

// ==========

/** Append all distinct (supersequences+(sfx:sfxlen)) of (str:len)
with length (suplen) to (res).
Define (a) to be a "supersequence" of (b) iff (b) is a subsequence of (a).
*/
void supseqs_(
    int str,int len,int suplen,
    int sfx,int sfxlen,
    std::vector<int>& res
){
    assert(suplen>=len);

    if(suplen==0){
        res.push_back(sfx);
        return;
    }else if(suplen==len){
        res.push_back(str<<sfxlen|sfx);
        return;
    }

    int nTrail0; // of (str)
    if(str==0){
        res.push_back(sfx);
        // it's possible that the supersequence is '0000..00'
        nTrail0=len;
    }else{
        // str != 0 -> str contains a '1' bit ->
        // supersequence cannot be '0000..00'
        nTrail0=__builtin_ctz(str);
    }
    // todo try `nTrail0=__builtin_ctz(str|1<<len)`, eliminates a branch
    // and conditional statement

    for(int nsupTrail0=0;nsupTrail0<nTrail0;++nsupTrail0){
        // (nsupTrail0+1) last bits of supersequence matches with
        // nsupTrail0 last bits of str.
        supseqs_(str>>nsupTrail0,len-nsupTrail0,suplen-1-nsupTrail0,
            sfx|1<<(nsupTrail0+sfxlen),sfxlen+nsupTrail0+1,
            res);
    }

    int const strMatch=str?nTrail0+1:len;
    // either '1000..00' or (in case str is '0000..00') the whole (str)

    for(int nsupTrail0=suplen+strMatch-len;nsupTrail0-->nTrail0;){
        // because (len-strMatch)<=(suplen-1-nsupTrail0),
        // (nsupTrail0<suplen+strMatch-len).

        // (nsupTrail0+1) last bits of supersequence matches with
        // (strMatch) last bits of str.
        supseqs_(str>>strMatch,len-strMatch,suplen-1-nsupTrail0,
            sfx|1<<(nsupTrail0+sfxlen),sfxlen+nsupTrail0+1,
            res);
    }

    // todo try pulling constants out of loops
}

// ==========

int n,b;
std::vector<char> done;
unsigned min_undone=0;

int result;
void backtrack(int nchoice){
    assert(!done[min_undone]);
    ++nchoice;
    std::vector<int> supers_s;
    for(int s:subseqs(min_undone,n,n-b)){
        // obviously (s) is not chosen. Try choosing (s)
        supers_s.clear();
        supseqs_(s,n-b,n,0,0,supers_s);
        for(unsigned i=0;i<supers_s.size();){
            int& x=supers_s[i];
            if(!done[x]){
                done[x]=true;
                ++i;
            }else{
                x=supers_s.back();
                supers_s.pop_back();
            }
        }

        unsigned old_min_undone=min_undone;
        while(true){
            if(min_undone==done.size()){
                // found !!!!
                result=std::min(result,nchoice);
                goto label1;
            }
            if(not done[min_undone])
                break;
            ++min_undone;
        }
        if(nchoice==result){
            // backtrack more will only give worse result
            goto label1;
        }

        // note that nchoice is already incremented
        backtrack(nchoice);

        label1: // undoes the effect of (above)
        for(int x:supers_s)
            done[x]=false;
        min_undone=old_min_undone;
    }
}

int main(){
    std::cin>>n>>b;

    done.resize(1<<n,0);
    result=1<<(n-b); // the actual result must be less than that

    backtrack(0);
    std::cout<<result<<'\n';
}

Run locally:
[user202729@archlinux golf]$ g++ -std=c++17 -O2 delbits.cpp -o delbits
[user202729@archlinux golf]$ time for i in $(seq 1 3); do ./delbits <<< "6 $i"; done
12
4
2

real    0m0.567s
user    0m0.562s
sys     0m0.003s
[user202729@archlinux golf]$ time ./delbits <<< '7 1'
^C

real    4m7.928s
user    4m7.388s
sys     0m0.173s
[user202729@archlinux golf]$ time for i in $(seq 2 3); do ./delbits <<< "7 $i"; done
6
2

real    0m0.040s
user    0m0.031s
sys     0m0.009s

Mostly to encourage others to post their code if it's faster than mine.

Please?... (note: This is an instance of a set cover problem.)

I'm working on it. I just can't come up with any smart way of doing it. If nobody else posts an answer, I'll put mine up that can only go as high as n=4 so far.

MATLAB, n=9
Mixed-integer linear programming (MILP)
Use the intlinprog function of the optim package
% mincover.m

function result = mincover(n, d)
    bs = 2^(n - 1 - d);

    % define problem
    f = ones(bs, 1);
    intcon = 1:bs;
    lb = zeros(bs, 1);
    ub = ones(bs, 1);
    A = [];
    b = [];

    for row = 0:(2^(n-1) - 1)
        x = zeros(bs, 1);
        combs = nchoosek(1:n, n-d);
        for i = 1:size(combs, 1)
            v = 0;
            for j = 1:(n-d)
                if bitand(row, 2^(combs(i, j) - 1))
                    v = v + 2^(j - 1);
                end
            end
            if v >= bs
                v = 2*bs - 1 - v;
            end
            x(v + 1) = 1;
        end
        A = [A; x'];
        b = [b; 1];
    end

    options = optimoptions('intlinprog','Display','off');
    [x, fval] = intlinprog(f, intcon, -A, -b, [], [], lb, ub, options);
    result = round(2 * fval);
end

% run_mincover.m

for n = 3:9
    for d = 0:floor(n/2)
        fprintf('n=%d, d=%d, mincover=%d\n', n, d, mincover(n, d))
    end
end

n=3, d=0, mincover=8
n=3, d=1, mincover=2
n=4, d=0, mincover=16
n=4, d=1, mincover=4
n=4, d=2, mincover=2
n=5, d=0, mincover=32
n=5, d=1, mincover=6
n=5, d=2, mincover=2
n=6, d=0, mincover=64
n=6, d=1, mincover=12
n=6, d=2, mincover=4
n=6, d=3, mincover=2
n=7, d=0, mincover=128
n=7, d=1, mincover=20
n=7, d=2, mincover=6
n=7, d=3, mincover=2
n=8, d=0, mincover=256
n=8, d=1, mincover=40
n=8, d=2, mincover=10
n=8, d=3, mincover=4
n=8, d=4, mincover=2
n=9, d=0, mincover=512
n=9, d=1, mincover=70
n=9, d=2, mincover=18
n=9, d=3, mincover=6
n=9, d=4, mincover=2

How long does it take to run?

scipy now also has a MILP solver. It would be great to see how it compares.


text:
Binary tree rotations
Balanced binary search trees are essential to guarantee O(log n) lookups (or similar operations). In a dynamic environment where a lot of keys are randomly inserted and/or deleted, trees might degenerate to linked lists which are horrible for lookups. Thus there are various kinds of self-balancing binary trees that counteract this effect (such as AVL trees or splay trees). These trees are based on different kinds of rotations that re-balance the tree.
Rotations
In this challenge we'll only look at single right-rotations, such a rotation (left-rotation would be symmetric) looks like this:
    5            3
   / \          / \
  3   6   =>   1   5
 / \              / \
1   4            4   6

If any of the leaves 1,4 or 6 had left or right sub-trees a rotation would simply keep them there. If this is a subtree of a larger tree, we'd simply "cut it off" at the node 5 and "re-attach" the rotated tree (now node 3) to that node.
Challenge
Given a binary search tree1 and a key right-rotate the tree on that node as described above. The key provided in the above example would be 5.
Rules and I/O

you may use any type for keys as long as there is a bijection between the keys of your choice and those of the test cases
you may choose any representation for binary trees as long there's no ambiguity (eg. [3,[]] is ambiguous unless otherwise specified) and it's natural for your language of choice
since the input will always be a binary search tree there are no duplicate keys
you may assume that the key is contained in the tree
you may assume that node containing the key has a left child
you may not assume a right subtree under the provided key
you may not assume that the tree is unbalanced before the rotation
you may not assume that the tree is balanced after the rotation
you may use any default I/O method
your submission may be a function returning the tree or full program printing the solution

Test cases
These examples represent a tree as follows

if it's a leaf: []
if it's a tree with key x and both subtrees are leaves: [x]
if it's a tree with key x and subtrees left right: [x,left,right]

The first example is the one provided in the section Rotations. If for some reason you need a graphical representation of them, here2 you go.
5 [5,[3,[1],[4]],[6]]  ->  [3,[1],[5,[4],[6]]]
5 [5,[3,[1],[4]],[]]  ->  [3,[1],[5,[4],[]]]
5 [5,[3,[],[4]],[6]]  ->  [3,[],[5,[4],[6]]]
5 [5,[3,[1],[]],[]]  ->  [3,[1],[5]]
4 [8,[4,[2,[1],[3]],[6,[5],[7]]],[12,[10,[9],[11]],[14,[13],[15]]]]  ->  [8,[2,[1],[4,[3],[6,[5],[7]]]],[12,[10,[9],[11]],[14,[13],[15]]]]
8 [10,[8,[6,[4,[2,[],[3]],[5]],[7]],[9]],[11]]  ->  [10,[6,[4,[2,[],[3]],[5]],[8,[7],[9]]],[11]]
10 [10,[8,[6,[4,[2,[],[3]],[5]],[7]],[9]],[11]]  ->  [8,[6,[4,[2,[],[3]],[5]],[7]],[10,[9],[11]]]
9 [6,[3,[2],[5]],[9,[8],[12,[11],[15,[14],[]]]]]  ->  [6,[3,[2],[5]],[8,[],[9,[],[12,[11],[15,[14],[]]]]]]
7 [7,[5,[3,[1],[4]],[6]],[8]]  ->  [5,[3,[1],[4]],[7,[6],[8]]]
15 [17,[9,[5,[2,[0],[4]],[8]],[15,[13,[11,[10],[12]],[14]],[16]]],[40,[27,[21,[19,[18],[20]],[24,[22],[25]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]]  ->  [17,[9,[5,[2,[0],[4]],[8]],[13,[11,[10],[12]],[15,[14],[16]]]],[40,[27,[21,[19,[18],[20]],[24,[22],[25]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]]
21 [17,[9,[5,[2,[0],[4]],[8]],[15,[13,[11,[10],[12]],[14]],[16]]],[40,[27,[21,[19,[18],[20]],[24,[22],[25]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]]  ->  [17,[9,[5,[2,[0],[4]],[8]],[15,[13,[11,[10],[12]],[14]],[16]]],[40,[27,[19,[18],[21,[20],[24,[22],[25]]]],[28]],[44,[42,[41],[]],[51,[47],[59,[55],[61]]]]]]

1: meaning that for any node all the keys in the left subtree will be smaller than that key and all the keys in the right subtree are greater than it
2: to prevent link-rot, I embedded them as a comment

Haskell, 93 92 84 83 82 bytes
data B=B[B]Int|L
k!B[l@(B[x,y]a),r]n|k<n=B[k!l,r]n|k>n=B[l,k!r]n|1>0=B[x,B[y,r]k]a

Thanks to @BMO, @alephalpha and @Laikoni for a byte each and @nimi for eight bytes!
Try it online!

Using data B=B[B]Int would save some more bytes.

@Laikoni just one byte I think but I'll take it

You could save 2 bytes by first merging the two cases, k<n=B[k!l,r]n and k>n=B[l,k!r]n, into one: k/=n=B[k!l,k!r]n, and then adding k!x=x to make the pattern matching exhaustive.

Vim, 25 bytes
Takes the input in the buffer - space separated key and tree. The tree is expected to be represented as follows:

leaf: []
node with key k, left child <left> and right child <right>: [ k <left><right>]

Not the spaces around the key k which are important, such that the solution works for arbitrary trees.
"adw/ <C-r>a⏎3dw%l"apr[%xl%i]

Try it online!
Explanation
"adw                           " delete the key and trailing space, keep in register a
    / <C-r>a⏎                  " move cursor to the key surrounded with spaces
             3dw               " remove key and [ (move left node to top)
                %l             " move cursor to the right subtree
                  "ap          " insert key there
                     r[        " insert a [ (appending subtree to key)
                       %       " move to the end of new left subtree
                        x      " remove ] (fix parentheses)
                         l%    " move to the end of new right subtree
                           i]  " insert ] (fix parentheses)

Preview
Here's a preview of the first test case, generated with this script by Lynn:

Wolfram Language (Mathematica), 30 bytes
#2/.a_~b_~c_~#~d_:>b[a,c~#~d]&

Try it online!
A tree represented as follows:

if it's a leaf: $ (you can replace it by any value which is not a key)
if it's a tree with key x and subtrees left right: x[left,right]

For example, the tree in the first test case is represented by 5[3[1[$,$],4[$,$]],6[$,$]].
Explanation:
#2                                the second input
  /.                              replace
    a_~b_~c_~#~d_                 #[b[a,c],d], where # is the first input
                 :>               by
                   b[a,c~#~d]     b[a,#[c,d]]
                             &    define a function

Common Lisp, 146 bytes
(defun r(k a)(cond((not a)a)((=(car a)k)`(,(caadr a),(cadadr a)(,(car a),(car(cddadr a)),(caddr a))))(t`(,(car a),(r k(cadr a)),(r k(caddr a))))))

Try it online or verify all the testcases!
A tree is represented as follows:

an empty tree is represented as nil (or equivalently in Common Lisp as the empty list ())
a non-empty tree is represented as a list of three elements (node left-subtree right-subtree)
(so a leaf L is represented as (L nil nil)).

You could change your representation to (node . (left . right)) to save some characters in your implementation; also, if you do that, the code for actually doing the rotation becomes (rotatef (cadr a) (cddadr a) a) a (or minimized, (rotatef(cadr a)(cddadr a)a)a) which saves some more characters

JavaScript (Node.js), 70 bytes
n=>f=a=>n-a[0]?(a[i=n<a[0]?1:2]=f(a[i]),a):(i=a[1],a[1]=i[2],i[2]=a,i)

Try it online! Link includes test cases. All nodes must have left and right entries but they can be [] indicating no subtree on that side. As an abbreviation the test suite uses l(N) to indicate that N is a leaf and l(N,L) to indicate that N has a left subtree L but no right subtree both on input and output.

Python 2, 85 bytes
R=lambda T,k:k in T and T[1][:2]+[[T[0],T[1][2],T[2]]]or T[:1]+[R(i,k)for i in T[1:]]

Try it online!
Input format:

Tree: [KEY, LEFT_SUBTREE, RIGHT_SUBTREE]
Leaf: []

Jelly, 24 bytes
ñ
Ḣ,1ịṪƊṭ@ṪṭḢð{Ḣ;ç€ɗ¹¡i?

Try it online!
Warning: Normally, the top line shouldn't exist, and the bottom line should have a ß, not a ç. However, clever chain tricks and ß don't go well together, due to ß's variable arity. Technically, I could have still omitted the top line, but then the result would have had to be a full program, since otherwise it would have to be able to be incorporated as its own line inside any program, which isn't possible unless you're lucky. This means that, unfortunately, the output would've had an ambiguous representation, because, when you submit a full program, what gets actually output counts, and not what the result technically is before the program closes. So, in order to not make a mess with both recursion and proper string representation, I've decided to submit a 2-line function, where the top line's job is just to call the bottom one. The consequence? A huge waste of 2 precious and valuable bytes. In Jelly's (and Dennis's, as well as every other contributor's) defense, the language is still under active development, and is now experiencing a big wave of new features.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Treasure Map Drawing Bot
You're organizing a treasure hunt for your friends. To conduct things more easily, you want to draw a map of all locations where you hid the precious objects.
Input
Any form of input denoting a list of points consisting of (nonnegative) x- and y-coordinate, 0 0 being the upper left corner is permitted (Note: You may also use 1-based indexing in your answer, please comment on that if you do). Example:
1 2
3 0
0 1

Challenge
Your function or program should be able to construct a map denoting every given location with an x where the mark is found in row y + 1 and column x + 1 in the output. Unmarked locations are represented with a  . The map also consists of a frame where the corners are +s, the vertical lines are |s and the horizontal lines are -s. Your solution should output the smallest possible frame. Map for the input example given above:
+----+
|   x|
|x   |
| x  |
+----+

Possible Test Cases

"0 0"
=>
+-+
|x|
+-+

"0 10
 5 5
 10 0"
=>
+-----------+
|          x|
|           |
|           |
|           |
|           |
|     x     |
|           |
|           |
|           |
|           |
|x          |
+-----------+

""
=>
++
++

"0 0
 0 2
 2 0"
=>
+---+
|x x|
|   |
|x  |
+---+

Of course, this is code-golf, meaning that the solution with the lowest byte count wins! Explanations of your solution are encouraged.

Not really, but i couldn't really think about another input format. But I'm willing to change that if it benefits the challenge.

Can there be non square maps?

Of course, the example used in the explanation uses a nonsquare map. It all depends on the input coordinates

@racer290 I'd suggest just saying something like the input is a list of locations (e.g. nested list, list of tuples, space & newline separated, separate inputs, ect.)

Can the output be a 2d array of characters?

Can I submit a function taking the x- and y-coordinates as two separate arguments?

Should the frame be as small as possible?

@ovs It should be a string consisting of the printable ascii characters as stated above.

@SolomonUcko Yes, I'll add that to the challenge description, thank you.

@BMO Yes, the challenge permits any form of input denoting the coordinates you like.

Testcase: 10 10. Should the output be the same as 0 0?  Smallest possible frame.

@edc Okay, well you can interpret it that way, but what i mean here is no overhead in the positive x or y direction.

"This wouldn't be so bad in 05AB1E" [10... minutes... later] "What the !@$*..."

J, 37 34 bytes
0<@|:' x'{~((i.@]e.#.~)1+>./) ::#:

Try it online!
                       1+>./          maximum for each coordinate + 1
             i.@]                     make an array with these dimensions filled with 0..x*y
                                      /* if the input is empty,
                                         1+>./ is negative infinity
                                         and i.@] throws an error  */
                   #.~                mixed base conversion of input
                 e.                   replace the elements of i.@]
                                        with 1 if it's present in the
                                        converted input, 0 otherwise
           (                ) ::      if there's an error do the other thing instead
                                #:    "to binary", for empty input this returns a 0x0 matrix
0<@|:' x'{~                           index into character string, transpose and put in a box

I guess that output formatting is better than the one I proposed ;)

Why is the ::empty so verbose? What's it do? Why can't it be simplified to 1 byte or so? (I have no knowledge of J)

I ran it on TIO without ::empty and it seemed to work(dont know J either)

Actually ::empty seems to handle the “” input case

@MagicOctopusUrn I don’t know a shorter way to output a truly empty box, they are 1 row high by default.

Turns out it can be avoided if the input is a 0×2 nothing.
6 bytes shorter

JavaScript (ES6), 150 bytes
Takes input as a list of 1-indexed coordinates in [x,y] format. Returns a string.
a=>(g=w=>y<h?' |-+x'[4*a.some(a=>a+''==[x,y])|2*(-~y%h<2)|++x%w<2]+[`
`[x=x<w?x:+!++y]]+g(w):'')((M=i=>Math.max(2,...a.map(a=>a[i]+2)))(x=y=0),h=M(1))

Try it online!

Haskell, 127 123 bytes
This defines the operator (!) which takes a list of x-coordinates and a list of the corresponding y-coordinates:
x!y|l<-'+':('-'<$m x)++"+"=unlines$l:['|':[last$' ':['x'|(i,j)`elem`zip x y]|i<-m x]++"|"|j<-m y]++[l];m x=[1..maximum$0:x]

Try it online!
Ungolfed/Explanation
The helper function m expects a list and returns indices (1-based) up to the maximum, if the list is empty it returns []:
m x | null x    = []
    | otherwise = [1 .. maximum x]

The actual operator (!) is just a list-comprehension, traversing all the coordinates and choosing a  or x character, which gets joined with newlines:
x ! y
  -- construct the top and bottom line
  | l <- "+" ++ replicate (maximum (0:x)) '-' ++ "+"
  -- join the list-comprehension with new-lines
  = unlines $
  -- prepend the top line
      [l]
  -- the actual map:
    -- begin the line with | and add the correct chars for each coordinate
      ++ [ "|" ++ [ if (i,j) `elem` zip x y then 'x' else ' '
    -- "loop" over all x-coordinates
                 | i <- m x
                 ]
    -- end the line with a |
           ++ "|"
    -- "loop" over all y-coordinates
         | j <- m y
         ]
  -- append the bottom line
      ++ [l]

Canvas, 22 bytes
ø╶｛X；┤╋｝ｌ|＊ｅＬ┤-×+ｅ：└∔∔

Try it here!
Takes 1-indexed inputs.
Finally decided to fix a bug that's been annoying me for ages and golfed this down to 21 bytes.
Explanation (half-ASCII-fied for monospace):
ø╶{X;┤╋}l|*eL┤-×+e:└++  full program, implicitly outputting ToS at the end
ø                       push an empty Canvas - the map
 ╶{    }                for each array in the input array
   X                      push "X"
    ;┤                    and push the two coordinates separately on the stack
      ╋                   and overlap the "X" there in the map
        l               get the vertical length of the map
         |*             repeat "|" vertically that many times
           e            encase the map in two of those vertical bars
            L           get the horizontal length of the map
             ┤          subtract 2 (leave place for the "+"es)
              -×        repeat "-" that many times
                +e      encase that line in "+"es
                  :└    push a copy of that below the map
                    ++  and join the 3 items vertically

Python 2, 151 140 138 bytes
-2 bytes thanks to Jo King.
Input is 1-indexed.
m=input()
w,h=map(max,zip((0,0),*m))
b=['+'+'-'*w+'+']
M=b+['|'+' '*w+'|']*h+b
for x,y in m:M[y]=M[y][:x]+'x'+M[y][x+1:]
print'\n'.join(M)

Try it online!

I suspect that you're using 1-based indexing, please leave a note on that in your answer as stated in the challenge.

Charcoal, 37 bytes
≔Ｅ²⁺²⌈Ｅθ§λιηＢ⊟⮌η⊟ηＦθ«Ｊ⊟⮌ι⊟ιx

Try it online! Link is to verbose version of code. 1-indexed. Explanation:
¿¬ＬθＵＲ²+«

Special-case empty input by drawing a 2x2 rectangle of +s.
≔Ｅ²⁺²⌈Ｅθ§λιη

Transpose the input, take the maximum of each column (now row) and add 2 to get the box size in Charcoal co-ordinates.
Ｂ⊟⮌η⊟η

Draw the box.
Ｆθ«

Loop over each co-ordinate.
Ｊ⊟⮌ι⊟ι

Jump to its position.
x

Mark with a cross.

Seems to fail for empty input: https://tio.run/##VYq7CsIwGIXn5ilCpz8QF9dOdVMoBHErHUKNJpBbk6YExGePjeDgWc7tmyUPs@O6lD5G9bQwcA9HiplOsfrAszLJfOeF4n4927vIoClWpIpiSTp0chmY83AVmwhRgKxHHfbQoYcLGBaCX6i5JONv7o9VP1ZVtmFB2RXa3O7lXco4omkqh01/AA

@wastl Thanks, I've come up with a workaround.

Stax, 32 31 24 bytes
╩╠ee%╙æM■↓^⌐╧ΩΓ¡c¥èf¢○ [

Run and debug it
Takes 0-based indices as array of [y, x] pairs.
Explanation:
zs'X&|<cM%'-*'+|S]s{'||Smn++m Unpacked program, implicit input
zs                            Tuck empty array under input
  'X                          Push "X"
    &                         Assign element at all indices (create map)
                                As the indexing arrays are an array of arrays, treat them as a path to navigate a multidimensional array.
                                Extend array if needed.
     |<                       Left-align all to the length of the longest.
       cM%                    Copy, transpose, length (width)
          '-*                 Repeat "-"
             '+|S             Surround with "+"
                 ]s           Make a singleton and tuck it below the map
                   {    m     Map:
                    '||S        Surround with "|"
                         n++  Surround with the above/below border (built above)
                            m Map:
                                Implicit output

Nicely done.  You can get a little more mileage out of the |S surround instruction, and a trailing shorthand map. (m)  Surround takes a and b from the stack and produces b+a+b.  And you can use m instead of the final |J to iterate over the rows and produce output.  For example

One more thing: you can replace z]n+H% with cM%.  This is the piece that gets the map width, but has a special case for empty maps.  If you transpose the map before measuring it, the special case goes away.

@recursive I had been looking for something like surround, but I searched for the wrong keywords

What would you naturally call that operation?  I may add it to the docs so the next person can find it.

@recursive I don't remember what it was, and I would naturally call it surround now

@recursive After reading my old explanation, it turns out I called it "wrap a in b"

That makes sense.  It will be in the 1.1.2 (next release) docs for easy ctrl+F.

R, 133 125 122 bytes
function(m)cat(z<-c("+",rep("-",u<-max(m[,1])),"+","
"),rbind("|",`[<-`(matrix(" ",u,max(m[,2])),m,"x"),"|","
"),z,sep="")

Try it online!
1-indexed. Takes a matrix as argument. Saved 8 bytes thanks to digEmAll, 3 thanks to Giuseppe!
Explanation (earlier version of code):
function(m){                           #x and y are the 1st and 2nd col of m
s=matrix(32,u<-max(m[,1]),max(m[,2]))  #s (treasure map) has dim max(x), max(y)
s[m]=120                               #place the X's on the map
cat(                                   #print:
    z<-c("+",rep("-",u),"+","\n"),     #the top line
    intToUtf8(rbind(124,s,124,13)),    #the map
    z,                                 #the bottom line.
    sep="")
}

If you use normal chars instead of utf8 codes you save 8 characters : https://tio.run/##ZU7NDoIwDL7zFEu9tKEzDONF4UkMhzmGchgYNhKC@uwIaozRpG36/TXtpkpkcqr6xoS6bdDR1edOh64eEARwn0mnB3QHVgXxe00Lor0/uCKHAfZGBxwzaRBi4M5eEOScI14gREDcHeumRLgBe17mkxzZ20sOQNF9Wik5O@xgy53QZVk3JxErEVoRzlYE64Mw2lu/jip8v2ZQ8YYTTudWFM@A6FtNOFlY9ctuWSVLbV/6f@p5Mf2o0wM

122 bytes by using [<- directly to remove the braces.

@Giuseppe indeed! I knew there had to be a way.

coords taken of the format [y,x]
JavaScript (Node.js), 191 184 bytes
c=f=a=>{a.map(([y,x])=>(c[M<++y?M=y:y]=c[y]||[])[m<++x?m=x:x]="x",M=m=0)
m++
M++
s=""
for(i=0;i<=M;s+=`
`,i++)for(j=0;j<=m;j++)s+=(c[i]||0)[j]||(j%m?i%M?" ":"-":i%M?"|":"+")
return s}

Try it online!

I think you accidentally swapped the x- and y-coordinates somewhere..

@racer290 could you be more specific?

Trying your solution, I found that changing the x coordinate in the test cases led to a change in the vertical direction of the coordinate. I guess the bug is in the first row (a.map(([y,x]))

but x is the right paramter as can be seen by the test cases

So in your solution you take the y coordinate first? I think it'd be better to leave a note on that in your answer then.

JavaScript, 180 bytes

F =

s=>s.map(([x,y])=>(t[y]=t[Y<y?Y=y:y]||[])[X<x?X=x:x]='x',t=[X=Y=0])&&[...t,0].map((_,y)=>[...Array(X+2)].map((_,x)=>[(t[y]||0)[x]||' ',...'-|+'][!(y%~Y)+2*!(x%~X)]).join``).join`
`

console.log(F([[1,11],[6,6],[11,1]]))

C (gcc), 246 234 bytes
Thanks to ceilingcat for the suggestion.
Zero-indexed. The function takes a list of co-ordinates and buffer, finds the maximum x and y values, fills the buffer with spaces, generates the frame, and then plots the 'x's.
f(int*a,char*c){int*b=a,x,y=x=-1,i=0;for(;~*b;*++b>y?y=*b:0,++b)*b>x?x=*b:0;for(x+=4,y+=3,memset(c,32,x*y);++i<x;c[i]=c[y*x-i]=45);for(i=0;i<y;c[x*++i-1]=10*(i<=y))c[x*i]=c[x*i+x-2]=i&&y/i?124:43;for(b=a;~*b;b+=2)c[*b+1-~b[1]*x]='x';}

Try it online!

fix bug in bottom row 235 bytes

Java 10, 238 223 220 219 bytes
c->{var r="";int w=0,h=0,x,y;for(var l:c){w=(x=l.get(0))>w?x:w;h=(y=l.get(1))>h?y:h;}for(w++,h-=x=-1;x++<w;r+="\n")for(y=-1;y++<h;)r+=x%w+y%h<1?"+":x%w<1?"-":y%h<1?"|":(c+r).contains("["+x+", "+y+"]")?"x":" ";return r;}

-3 bytes thanks to @ceilingcat.
1-indexed coordinates.
Try it online.
Explanation:
c->{                      // Method with 2D Lists as parameter and String return-type
  var r="";               //  Result-String, starting empty
  int w=0,h=0,            //  Width and height, starting at 0
      x,y;                //  Temp x,y coordinates
  for(var l:c){           //  Loop over the Inner Lists containing the coordinates
    w=(x=l.get(0))>w?x:w; //   Determine width based on max x-coordinate
    h=(y=l.get(1))>h?y:h;}//   Determine height based on max y-coordinate
  for(w++,h-=             //  Increase both the width and height by 1
      x=-1;x++<w;         //  Loop `x` in the range [0, width]:
      r+="\n")            //    After every iteration: append a new-line to the result
    for(y=-1;y++<h;)      //   Inner loop `y` in the range [0, height]:
      r+=                 //    Append the following character to the result-String:
         x%w+y%h<1?       //    If it's one of the corners:
          "+"             //     Append "+"
         :x%w<1?          //    Else-if it's the top or bottom row:
          "-"             //     Append "-"
         :y%h<1?          //    Else-if it's the right or left column:
          "|"             //     Append "|"
         :(c+r).contains("["+x+", "+y+"]")?
                          //    Else-if the current `x,y` is part of the input-coordinates:
          "x"             //     Append "x"
         :                //    Else:
          " ";            //     Append " "
  return r;}              //  Return the result-String

rwhxy; lcwxlgetw? xw; hylgeth? yh; forwhxxwr. foryyhrxwyh? xwyhcxy? xr.

@MagicOctopusUrn What are you naming all the variables and get/for for? :S XD

05AB1E, 44 42 bytes
ζεZ}>`UX'-×'+.ø©,F'|NVXF¹YN‚.å„ xè}'|J,}®,

Try it online!

 ζεZ}>`                                     # Push the max of X and Y to the stack +1.
       UX                                   # Store the max X.
         '-×'+.ø©,                          # Print the top border.
                  F                     }   # From 0 to Y...
                   '|                       # Push left border.
                     NV                     # Store current Y in Y.
                       XF          }        # From 0 to X...
                         ¹                  # Push input.
                          YN‚               # Group current X and Y.
                             .å             # Exists in original input ? 1 : 0
                               „ xè         # Exists ? 'X' : ' '
                                    '|J,    # Right border, join, print.
                                         ®, # Print bottom border.

X and Y may be reversed, didn't know if that mattered at all.

I think I have this in less bytes, but we'll see... Nope.
ζεZ}>`D'-×'+.øUð×'|.øs.D)X.ø©svy>`s®sUXès'xsǝXǝ}

It's not much, but you can save 1 byte by changing the first F to Lv, remove NV and change Y to y. 41 bytes

As mentioned by @Emigna in the chat, εZ} can be €à.

Hate editing this on mobile will wait until  near pc.

@KevinCruijssen Ýv not Lv, but still a good edit :).

Ah, you're right. Ýv instead of Lv. My bad.

@KevinCruijssen pretty smart way to get around vvy, I didn't think about how a double-nested v-loop would work until hitting it on this problem.

Yeah, and in the Elixir rewrite it's even worse, since the map and other loops will have their own y as well now, instead of just the v-loop. Caused me some confusion and rethinking for a recent answer of mine. PS: You still have to update your answer. ;)

C (gcc), 229 220 216 bytes
-9 bytes thanks to ceilingcat.
Zero-indexed. Takes coordinates as list of numbers, where even numbers are X and odd numbers are Y.
X,Y,i,j,k,x,z;f(l,n)int*l;{for(X=Y=0,i=n*=2;i--;X=fmax(l[i],X))Y=fmax(l[i--],Y);n&&X++-Y++;for(--i;i++<Y;puts(""))for(j=-1;j<=X;z=i<0|i==Y,putchar(j++<0|j>X?z?43:'|':x?z?45:32:'x'))for(x=k=n;k--;)x*=l[k--]-i|l[k]-j;}

Try it online!

@ceilingcat Cheers!

Suggest for(n&&X++-Y++;i<=Y;i+=puts("")) instead of n&&X++-Y++;for(--i;i++<Y;puts(""))

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
It's getting harder and harder to be composite these days
Given a non-empty list L of integers greater than 1, we define d(L) as the smallest positive integer such that n + d(L) is composite for each n in L.
We define the sequence an as:

a0 = 2
ai+1 is the smallest integer greater than ai such that d(a0, ..., ai, ai+1) >  d(a0, ..., ai)

Your task
You may either:

Take an integer N and return the N-th term of the sequence (0-indexed or 1-indexed)
Take an integer N and return the first N terms of the sequence
Take no input and print the sequence forever

This is code-golf, so the shortest answer in bytes wins!
It's OK if your code is getting slow as N gets larger, but it should at least find the 20 first terms in less than 2 minutes.
First terms

a0 = 2 and d(2) = 2 (we need to add 2 so that 2+2 is composite)
a1 = 3 because d(2, 3) = 6 (we need to add 6 so that 2+6 and 3+6 are composite)
a2 = 5 because d(2, 3, 5) = 7 (we need to add 7 so that 2+7, 3+7 and 5+7 are all composite), whereas d(2, 3, 4) is still equal to 6
etc.

Below are the 100 first terms of the sequence (unknown on OEIS at the time of posting).
  2,   3,   5,   6,  10,  15,  17,  19,  22,  24,
 30,  34,  35,  39,  41,  47,  51,  54,  56,  57,
 70,  79,  80,  82,  92,  98, 100, 103, 106, 111,
113, 116, 135, 151, 158, 162, 165, 179, 183, 186,
191, 192, 200, 210, 217, 223, 226, 228, 235, 240,
243, 260, 266, 274, 277, 284, 285, 289, 298, 307,
309, 317, 318, 329, 341, 349, 356, 361, 374, 377,
378, 382, 386, 394, 397, 405, 409, 414, 417, 425,
443, 454, 473, 492, 494, 502, 512, 514, 519, 527,
528, 560, 572, 577, 579, 598, 605, 621, 632, 642

Pyth, 24 bytes
Pu+GfP_+Tf!fP_+ZYG)eGQ]2

Demonstration
Basically, we start with [2], then add elements 1 at a time by alternately finding d, then adding an element, and so forth. Outputs the first n elements of the sequence.
Contains a filter inside a first integer filter inside a first integer filter inside an apply repeatedly loop.
Explanation:
Pu+GfP_+Tf!fP_+ZYG)eGQ]2
 u                   Q]2    Starting with `[2]`, do the following as many times
                            as the input
         f        )         Starting from 1 and counting upward, find d where
          !f     G          None of the elements in the current list
            P_+ZY           plus d give a prime.
    f              eG       Starting from the end of the current list and counting
                            upward, find the first number which
     P_+T                   plus d gives a prime.
  +G                        Append the new number to the current list
P                           Trim the last element of the list

There's obvious repeated effort between the two "Add and check if prime" calls, but I'm not sure how to eliminate it.

Jelly, 31 bytes
ṛ,;1+ÆPẸṆʋ1#ⱮẎ</
Ḷß€‘Ṫç1#ƊḢƲ2⁸?

Try it online!
Jelly sucks at recurrence sequences. :/

Retina, 74 bytes
K`__;
"$+"{/;(?!(__+)\1+\b)/+`;
;_
.+$
$&¶$&
)/;(__+)\1+$/+`.+$
_$&_
%`\G_

Try it online! 0-indexed. Explanation:
K`__;

Each line i in the workarea contains two unary values, aᵢ;d+aᵢ. We start with a₀=2 and d+a₀=0 (because it's golfier).
"$+"{
...
)

Repeat the loop N times.
/;(?!(__+)\1+\b)/+`

Repeat while there is at least one non-composite number.
;
;_

Increment d.
.+$
$&¶$&

Duplicate the last line, copying aᵢ₋₁ to aᵢ.
/;(__+)\1+$/+`

Repeat while d+aᵢ is composite.
.+$
_$&_

Increment aᵢ.
%`\G_

Convert the results to decimal.

Clean, 138 130 128 bytes
import StdEnv
$l=until(\v=all(\n=any((<)1o gcd(n+v))[2..n+v-1])l)inc 1

map hd(iterate(\l=hd[[n:l]\\n<-[hd l..]| $[n:l]> $l])[2])

Try it online!
Expanded:
$l=until(\v=all(\n=any((<)1o gcd(n+v))[2..n+v-1])l)inc 1
$l=until(                                         )inc 1  // first value from 1 upwards where _
         \v=all(                                )l        // _ is true for everything in l
                \n=any(              )[2..n+v-1]          // any of [2,3..n+v-1] match _
                             gcd(n+v)                     // the gcd of (n+v) and ^
                           o                              // (composed) ^ is _
                       (<)1                               // greater than 1

map hd(iterate(\l=hd[[n:l]\\n<-[hd l..]| $[n:l]> $l])[2])
map hd(                                                 ) // the first element of each list in _
       iterate(                                     )[2]  // infinite repeated application of _ to [2]
               \l=hd[                              ]      // the head of _
                     [n:l]                                // n prepended to l
                          \\n<-[hd l..]                   // for every integer n greater than the head of l
                                       | $[n:l]> $l       // where d(n0..ni+1) > d(n0..ni)

Julia 0.6, 145 130 bytes
~L=(x=1;while any(map(m->all(m%i>0 for i=2:m-1),L+x));x+=1;end;x)
!n=n<1?[2]:(P=!(n-1);t=P[end]+1;while ~[P;t]<=~P;t+=1;end;[P;t])

Try it online!
(-15 bytes using my new and improved golfing skills - operator overloads, replacing conditional by ternary and hence removing return keyword.)
Expanded:
function primecheck(m)
    all(m%i>0 for i∈2:m-1)
end

function d(L)
    x = 1
    while any(map(primecheck, L+x))
        x += 1
    end
    return x
end

function a(n)
    n > 0 || return [2]
    Prev = a(n-1)
    term = Prev[end] + 1
    while d([Prev;term]) ≤ d(Prev)
        term += 1
    end
    return [Prev;term]
end


text:
The N Queens Problem, but with Fairy Chess Pieces
Fairy Chess is a sort of generalized chess that allows unconventional pieces. The eight queens puzzle is a classic problem where you have to put 8 queens on a chess board such that no two queens threaten each other. This challenge is sort of a generalized combination of the two.
Challenge
Given a list of fairy chess pieces and their quantities, output a board such that all pieces are used and no piece threatens any other piece. The board is not directional and all pieces have symmetric movement. Your goal is to generate a solution on the smallest, squarest board you can in under 30 seconds.
Pieces
Each piece has a list of valid move types. For the sake of simplicity, moves will be one of the following types:

Leaper movement. A generalized form of knights. A leaper has two numbers, m and n that describe its movement. A leaper moves m spaces in one orthogonal direction and then n in a direction perpendicular to the other, "leaping" over intervening spaces.
Rider movement. Moves in a straight line. Can be unlimited or restricted to a specific range. Can either be orthogonal or diagonal. It is possible for a piece to be in a rider's movement range without being threatened by it if there is a piece blocking its path that is too close to be captured. For instance, a 3-5 orthogonal rider could be blocked from taking a piece 4 spaces away if a non-threatening piece was one space away along the path
Hopper movement. Hoppers are similar to riders in that they travel in a straight line, but they are different in that they have to "hop" over a piece to take the piece on the other side of the hopped-over piece. As such, they can only capture the second piece along a line of movement. Hoppers may also have minimum and maximum range.

How these are to be represented in the input is up to the implementation.
Piece Examples
A 3-1 leaper moves like this: (x represents spaces that can be moved to)
. . x . x . .
. . . . . . .
x . . . . . x
. . . L . . .
x . . . . . x
. . . . . . .
. . x . x . .

Note: in the following diagrams, rather than make a full diagram for each possible interaction, each row in the diagram represents one direction along the movement path.
A 3-5 hopper moves like this in each direction (O represents another piece that cannot be taken)
H . . . . . .
H O . x x x .
H . O x x x .
H . . O x x .
H . . . O x .
H . . . . O .
H . . . . . O

Limited range on riders can have interesting effects when they have a minimum range. A 3-5 rider behaves in an interesting way when a piece is blocking its path to the minimum range. (X represents another piece that can be taken.)
R . . x x x .
R O . . . . .
R . O . . . .
R . . X . . .
R . . x X . .
R . . x x X .
R . . x x x X

Hoppers can only take the second piece along their travel path. Once again, with the 3-5 range hopper:
H . . . . . .
H O O . . . .
H O O . . O .
H . O x X . .
H . . O X . .
H . . . O x .
H . . . . O O
H . O . . . O

Input
Your program input will be passed via stdin in lines of plain text, where each line describes the piece type and the number of instances of that piece. It follows this general format:
<Letter><copies, decimal>: <movements, comma separated>
Movements follow this format:

Leaper: Lmn, where m and n are decimal digits representing the distances in each direction of movement.
Rider: Rdmn, where d is + or x for orthogonal or diagonal, respectively; and where m and n are decimal digits representing the minimum and maximum distance, respectively. n may also be -, indicating there is no maximum range.
Hopper: Hdmn, where d, m, and n have the same meanings as for riders.

Output
Your program should output to stdout with each row of the board on each line. The letters in the piece definitions input should be used to represent each piece type and dots (.) should be used to represent empty spaces on the board. Whitespace between board spaces are optional and will be ignored by the test driver. All solutions shown in the examples section are in a valid format.
Coding
Your solution should be a program that reads definitions from stdin (as a redirected file) and outputs boards to stdout. Logging, should you choose to use it, should go through stderr, as that is not captured by the test driver.
An example baseline solver can be found here. It's not very smart, but it does a decent job at making compact boards. There is room for improvement.
Scoring
Your solution will be scored across 10 test cases (below) and each run will be scored with the following formula:
score = height **2 + width ** 2
This will be totaled across all solutions. Lowest score wins. All boards returned must be valid solutions and be calculated in under 15 seconds or else your solution will be disqualified.
Ties will be broken by first solution posted.
A test driver that scores solutions automatically can be found here. You will need Python 3.5+ to run it. There are no third-party dependencies.
Examples
With the input:
A2: L21
B1: Rx1-
C2: H+1-

You have these pieces:

(A) 2 Knights (2-1 Leapers)
(B) 1 Unlimited-range diagonal rider
(C) 2 Unlimited-range orthogonal hoppers

A valid solution is:
A . A B .
. . . . .
C . . . C

This solution would score 34 points (3*3 + 5*5 = 9 + 25 = 34)

With the input:
A5: L32
B1: R+1-,Rx1-,L21
C2: H+3-
D4: Rx14,L30

You have these pieces:

(A) 5 3-2 Leapers
(B) 1 Unlimited-range 8-way rider with 2-1 Leaps (a queen and knight combined)
(C) 2 Range 3+ orthogonal hoppers
(D) 4 Range 4- diagonal riders with 3-0 leaps

A valid solution is:
. . . . . . . . . B
A . . . . D . . . .
. . . . . . . . . .
. . . . . . . . D .
. . . C D . . . . .
. . . . . . . . A .
. . . . D . . . . .
A . . . . . . . . .
. . . C A . . . . .
. . . . . A . . . .

This solution would score 200 points (10*10 + 10*10 = 100 + 100 = 200)
Test Cases
The following test cases will be used for scoring:
8 Queens
Q8: R+1-,Rx1-

Standard Chess Set (without pawns)
K2: L10,L11
Q2: R+1-,Rx1-
R4: R+1-
B4: Rx1-
N4: L21

10 Amazons
A10: R+1-,Rx1-,L21

Compound Pieces
K2: L10,L11
A2: R+1-,Rx1-,L21
R4: R+1-,L11
B4: Rx1-,L10
C4: R+1-,L21
P4: Rx1-,L21

Archbishops and Super Rooks
B14: Rx1-,L10
R8: R+1-,L11

Wazirs and Ferzes
W21: L10
F24: L11

10 Lords-A-Leaping (x3)
W3: L10
F3: L11
D3: L20
N3: L21
A3: L22
H3: L30
L3: L31
J3: L32
G3: L33
X3: L40

20 Frog Queens
A20: H+1-,Hx1-

Things are Really Hoppin'
A12: Hx36
B8: H+36
C6: H+2-
D10: Hx2-

Blindspots
A6: R+36,L22
B16: Hx59
C10: L21,L33
D6: Rx22,R+44
E6: H+47,L31
F8: H+22,Hx22

Rules and Notes

No abusing standard loopholes
Your program will be limited to running on a single CPU
Final scoring will be done on my 2.8 GHz i5, using Windows Subsystem for Linux
You may assume input files are valid.
You may assume that leapers will never be L00 so that you never have to check for self-threatening.
There is no hard limit on the size of board in a calculated solution. All that matters is that it is a valid solution.

tl;dr: Programs should try to make boards as small and as square as possible in less than 30 seconds. Lowest Score Wins. Ties will be broken by first solution posted. Once again, the test driver can be found here

If we are being tested on only test cases we have access to the optimal solutions for each can theoretically be attached to something which reads the input for uniqueness.

in under 15 seconds I suggest that you remove this constraint. If you intend to encourage optimization, perhaps you could use the tag [tag:fastest-algorithm], which would require the answerers to include the time complexity of their solutions. Alternatively, you could employ a time-complexity constraint. Right now, the strict time requirement seems to do more harm than good (and with a complex challenge like this, an added constraint would discourage people from even attempting to create a solution).

@fəˈnɛtɪk: that sounds like abuse of a standard loophole.

@JungHwanMin: The reason for the time limit is twofold (though it could perhaps be longer- maybe 30s to 1 minute). 1. I don't want runaway solutions that take an hour to score. 2. It allows for more variance in algorithmic choice. There is definitely an optimum size for all boards that is an upper bound, which brute-force solutions can (at least theoretically) find. A time limit forces cleverness.

I guess a time complexity constraint would solve #1, but I feel it's too easy to calculate wrong. I guess I could require polynomial complexity or make it O(n^4) or so, but that also bans backtracking solutions. I think time limits are the way to go, but I sorta see your point, so I raised the time limit to 30 seconds.

@Beefster the issue I found is that some languages have slow implementations or are just slow by nature, but there may be some clever tricks involved with those languages. With a flat time constraint, solutions in those languages cannot compete. My time-complexity suggestion would fix this issue (coming up with something with a polynomial time would require cleverness anyway). I also disagree that having a flat time constraint "allows for more variance," since a fast algorithm in one language should be fast in another language.

@JungHwanMin I think that can be the case for fastest-code challenges, but algorithm complexity still matters more than language speed. I would consider raising the time limit again if there are no submissions in a week. Most of the slower languages wouldn't be very practical for this sort of challenge anyway. I don't think anyone in their right mind would use bash, for instance. I say let it play out, but your advice is noted.


text:
Grouping Array Data
Given an integer matrix a and a nonnegative integer i, output a mapping b that maps the distinct values in the ith column of a to rows of a who have that value in the ith column.
You may assume that i is in the half-open range [0, num_cols(a)) (or [1, num_cols(a)] if you choose to use 1-based indices), and that all integers are within the representable range for your language. Input and output may be done in any reasonable manner, so long as it satisfies the basic requirements of the challenge (2D array -> mapping from ints to 2D arrays of ints). So long as the mapping is clear and consistent, the keys do not need to be included in the output.
Examples
[[1]], 0 -> {1: [[1]]}
[[3, 4, 5], [1, 4, 2], [5, 5, 5], [7, 7, 7], [1, 5, 9]], 1 -> {4: [[3, 4, 5], [1, 4, 2]], 5: [[5, 5, 5], [1, 5, 9]], 7: [[7, 7, 7]]}
[[1, 2, 3, 4, 5], [5, 4, 3, 2, 1], [2, 3, 4, 5, 6], [8, 9, 100, 0, 2]], 4 -> {5: [[1, 2, 3, 4, 5]], 1: [[5, 4, 3, 2, 1]], 6: [[2, 3, 4, 5, 6]], 2: [[8, 9, 100, 0, 2]]}

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

Sandbox

Just to check, can the mapping be a function? I'm not aware if this is a default, but it seems like something you intend to allow.

@FryAmTheEggman Yes, a function that meets our usual requirements is allowed. The I/O is extremely flexible.

I like this I/O format very much because the output does not actually need to contain the input in itself. It's completely fine to return a function that accesses the input by reference as long as the function is a mapping.

@JungHwanMin I'm glad. I wanted to experiment with a very loose I/O format, and it's going well so far

Octave, 24 bytes
@(a,i)@(n)a(a(:,i)==n,:)

Try it online!
This creates an anonymous function that returns a matrix whose rows match the criteria. Octave indexes arrays at 1, not zero, and rows of a matrix are separated by a ;.
Matrices are what Octave does best—so well, in fact, that this challenge can be solved using pure syntax, no built-in functions.
Explanation
@(a,i)                   % creates an anonymous function that...
      @(n)               % returns another function that takes input n and
                         % maps it to the rows of a.
          a(         ,:) % Return all the columns of a, with the rows filtered by...
            a(:,i)       % whether the ith column of each row of a...
                  ==n    % equals n

Wolfram Language (Mathematica), 21 bytes
#~GroupBy~Extract@#2&

1-indexed. Returns an Association mapping.
Try it online!
This is a rare case in which a longer function (Extract) reduces the byte count (the shorter one being Part or [[ ... ]]) because Extract can curry. The result is this extremely concise two-function solution.
Explanation
Extract@#2

Function that extracts the <second input>th element.
#~GroupBy~ ...

Group the <first input> into lists associated with distinct keys <above function>[element].

Ruby, 26 bytes
->a,i{a.group_by{|x|x[i]}}

Try it online!

Clean, 40 bytes
import StdEnv

\n l i=filter(\a=a!!n==i)l

Try it online!
A lambda (:: Int [[Int]] Int -> [[Int]]) where a partial application of just the first two arguments gives a mapping on the third argument.

J, 16 bytes
-3 bytes thanks to FrownyFrog!
{"1(~.@[;"0</.)]

Try it online!
Explanation:
A dyadic verb, taking i as its left argument and a as its right one.
] is the right argument, a
{"1 finds the numbers at ith column on each row
</. boxes groups from the right argument, selected by the keys, provided by the left one
~.@[ finds the unique keys
;"0 links the keys to the selected groups

;"0 instead of ,: saves 3

@FrownyFrog  Of course! I think I tried it, but apparently not the right way.

Haskell, 64 60 bytes
import Data.List
i!l=[(k,[a|a<-l,a!!i==k])|k<-nub$map(!!i)l]

Try it online!

jq, 100 bytes
uses an object for output, takes a command line argument $f plus an array on standard input
([.[]|.[$f]]|unique) as $c|[$c[] as $d|{($d|tostring):([.[]|[select(.[$f]==$d)]]|add)}]|add

deobfuscated:
.fieldnum as $field |
.input as $input |
([$input[] | .[$field]] | unique) as $categories |
[
    $categories[] as $category |
    {
        ($category | tostring) :
            ([$input[] | [select(.[$field]==$category)]] | add)
    }
] | add

Is this the language you're using?

R, 79 55 bytes
function(a,i)for(z in unique(a[,i]))print(a[a[,i]==z,])

Try it online!
24 bytes shaved off by @JayCe

Save some bytes by extracting more directly. You can add a cat(z) before print to also print the key (I am unclear if this is required).

Proton, 29 bytes
a=>i=>n=>filter(r=>r[i]==n,a)

Try it online!
-3 bytes thanks to Mr. Xcoder using currying and filter (TBH I'm kind of surprised that filter actually worked)

Currying and using filter save you three bytes.

@Mr.Xcoder Cool, thanks :D

Python 3, 45 bytes
lambda a,i:lambda n:[r for r in a if r[i]==n]

Try it online!
Returns the mapping represented as an anonymous lambda.

JavaScript (Node.js), 29 bytes
a=>i=>n=>a.filter(e=>e[i]==n)

Try it online!
Updated now that I realize the loose output requirements. This uses currying as a golfing technique, and it also returns a function that takes an input n and maps that to the proper arrays.

Jelly, 5 bytes
ịⱮ⁹¹ƙ

Try it online!
Omits the keys, but should be clear.
Argument 1: i + 1
Argument 2: a

I don't think this would qualify as a mapping without the keys.

@Dennis Hm, I had asked in the comments about it and OP said we can omit the keys (exactly what I edited into the question), and I had also linked this solution there (maybe shouldn't have flagged so early...). I did include the keys in a previous revision of this answer (waiting for an answer), so I'll just post another comment and let's see what OP says.

Java 10, 135 64 bytes
m->i->n->new java.util.Stack(){{for(var a:m)if(a[i]==n)add(a);}}

Returns a Function<Integer, List<int[]>> accepting an integer-input n, which returns a List of arrays (matrix-rows) where the i'th values equal the given n.
Try it online.
Explanation:
m->i->               // Method with int-matrix and int parameters and Function return-type
  n->                //  Return a Function with integer as parameter
    new java.util.Stack(){{
                     //  and List of integer-arrays as return-type
      for(var a:m)   //   Loop over the arrays of the input-matrix
        if(a[i]==n)  //    If the `i`'the value of the current array equals `n`:
          add(a);}}  //     Add it to the return-List

Husk, 7 bytes
fo=⁰!²⁴

Try it online! This function is 1-indexed and, when partially applied, returns a function of type TNum -> [[TNum]] which implements the desired mapping.


text:
Self-enumerating pangrams
Pangrams

The quick brown fox jumped over the lazy dog.

This is an example of a pangram - a sentence that contains every letter of the alphabet at least once.
A self-enumerating pangram is a sentence that fulfills the criteria to be a pangram by producing an analysis of its own letter count.
An example of achieving this is the sentence

This pangram contains four As, one B, two Cs, one D, thirty Es, six Fs, five Gs, seven Hs, eleven Is, one J, one K, two Ls, two Ms, eighteen Ns, fifteen Os, two Ps, one Q, five Rs, twenty-seven Ss, eighteen Ts, two Us, seven Vs, eight Ws, two Xs, three Ys, & one Z.

The Challenge
Produce a function with the input being the string leading into the letter inventory. In the example, the input would be "This pangram contains". The quantity of each letter must be in the written form and contribute to the displayed letter count.

Rules

Oxford comma is optional
Use an ampersand before Z (or, for hard mode, include the ability to switch between "&" and "and" in the function)
Every letter counts towards the total letter count
No non-written numbers
This is code-golf so the shortest code in bytes wins
In honour of the married couple this weekend, the numbers are to be written in the Queen's English. e.g. nine hundred and ninety-nine Gs for 999 occurrences of the letter G and nine hundred and nine Gs for 909.
Orders of magnitude are to be written in the standard short-scale naming convention

Edge cases

There are some cases where the code will get stuck in a loop - for example, if there are two Os the code will increase the count to three Os, which causes the code to count two Os again. If calculating every other letter before coming back to this can't resolve the issue, consider the input to be a false starter and output false, null or an empty string.
If a letter has over 999 occurrences, the input should be considered a false starter.

Test Cases

"This pangram contains" should output the example sentence

related

Also welcome to to Programming Puzzles and codegolf. Nice first challenge

I haven't tested it, but I'm pretty sure there are some cases where you can't construct a valid solution, what should the output be in that case? For example, if you have a string that contains two o-s without the word for the count, then when you spell it out with two, the whole string now has three o-s, meaning the word is now incorrect, switching it makes it incorrect again, etc.

What's the largest written number the solution has to support? A hundred, a thousand, a million?

@Nit do your best to resolve the loop by solving other letters first, but in the event that this loop persists consider the input a false starting input. If someone finds an example of this where no solutions exist it would be great to put it in the test cases section.

Nice first question! However, I'd personally recommend to limit the maximum number of letters to 999 or maybe even just 99. This would make the challenge more accessible to languages that don't have decimal to text built-ins, while preserving all the fun. (Also, it may not even be possible to test entries with millions of letters in some languages.)

Related: Converting integers to English words

@Arnauld Good idea!

Are we allowed to determine in advance whether we're using "and" or "&" before Z? Or do we have to try both and output whichever works?

@Draconis for testing purposes it's probably best to use "&" so you know it's going to match the test case. In fact, I should probably make this the standard for simplicity sake.

Rob enjoys any sentence with two As, two Bs, two Cs, one D, thirty five Es, four Fs, three Gs, nine Hs, eight Is, two Js, one K, two Ls, one M, twenty two Ns, eighteen Os, one P, one Q, nine Rs, twenty three Ss, twenty three Ts, three Us, four Vs, eleven Ws, one X, seven Ys, & one Z.

How are these found?

Python 2, 615 bytes
def g(n):S=str.split;D=S('z one two three four five six seven eight nine');K=' fif six seven eigh nine';n,m=n/100,n%100;e,d=m/10,m%10;return' '.join([D[n],'hundred']*(n>0)+([S('ten eleven twelve thir four'+K)[d]+'teen'*(d>2)]if 9<m<20else[S('twen thir for'+K)[e-2]+'ty']*(e>0)+[D[d]]*(d>0)))
from random import*
X='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
def f(p):
 T=set();s='';i=0
 while 1:
	Q=s.upper().count;t=p+' '+', '.join(['& '*(c=='Z')+g(Q(c))+' '+c+'s'*(Q(c)!=1)for c in X])+'.'
        if s==t:return i,t
	if t in T:t=''.join(c*max(1,t.upper().count(c)+(randint(0,6)-3)*(random()<0.25))for c in X)
	T.add(t);s=t;i+=1

Try it online!
The function f takes p as the string prefix; and returns a tuple of an integer representing the number of steps taken, and the autogram.
The function g encodes a number 1<=n<=999 to its english string; it takes up 291 bytes, roughly half the total byte count. The code
Q=s.upper().count
t=p+' '+', '.join(['& '*(c=='Z')+g(Q(c))+' '+c+'s'*(Q(c)!=1)for c in X])+'.'

encodes the string s into a (potentially autogram-matic) pangram t.
We loop over the process, hoping for the situation where we find a t such that t is an autogram (i.e., where t==s). If When we get into a loop, we randomly nudge the counts of letters in a completely ad hoc manner.
For most values of p, this process will time out on TIO. Typically, millions of possibilities are examined before finding a 'winning' combination.
I don't have any proof at all, but my guess is: (a) apart from an exhaustive brute force search similar to what the originator Lee Sallows describes here and implements in hardware (!), this sort of random heuristic is about as good as you can get; and (b) there will be no solutions for many (most?) initial phrases p.

map(chr,range(65,91)) saves some bytes.


text:
Function clipboard: paste
This challenge is related to some of the MATL language's features, as part of the May 2018 Language of the Month event. Associated challenge: Function clipboard: copy.

Introduction
MATL's function clipboard stores ("copies") the inputs to the four most recent calls to normal, input-taking functions. Normal functions are the most common type of functions in MATL. Input-taking means that the function takes at least one input. The stored clipboard contents can be pushed onto the stack ("pasted").
This challenge will take the clipboard contents as input. It will be assumed that all functions that have produced that clipboard state took one or more positive integers as inputs. So the clipboard state can be represented by a list of lists of numbers. (For more information on how the clipboard is actually filled see the related challenge; but that's not necessary for the current one).
Interpreting the clipboard contents
Example 1
The first inner list refers to the most recent function call, and so on, Thus the clipboard state
[[11, 28], [12, 16], [4], [5, 6]]

indicates that the last function call took two inputs, namely 11, 28; the second-last call took inputs 12, 16; etc. (This clipboard state is produced by the code in the first example of the related challenge).
Example 2
If there have not been enough function calls, some trailing inner lists in the clipboard will be empty:
[[7, 5], [], [], []]

(This is produced by a program that simply adds 7 and 5).
Example 3
Function calls can have any number of inputs, but always at least 1 (functions taking no inputs do not change the clipboard state). So the following is also possible.
[[3], [2, 40, 34], [7, 8, 15], []]

Accessing the clipboard contents
The contents of the function clipboard are pushed onto the stack using MATL's function M (which, by the way, is not a normal function, but a clipboard function). This function takes a positive integer as input, and pushes some of the clipboard contents onto the stack, as follows. With reference to the clipboard state in example 1:
[[11, 28], [12, 16], [4], [5, 6]]

1M returns all inputs to the most recent function call. So, for the considered example, it gives 11, 28.
Similarly, 2M, 3M and 4M return all inputs to the second, third and fourth most recent function calls. So 2M gives 12, 16; 3M gives 4; and 4M gives 5, 6.
Numbers beyond 4 select individual inputs to function calls that took more than one input. So 5M returns the last input to the most recent such call. In our case this gives 28. 6M returns the preceding individual input, which is 11. 7M returns the last input of the second-last call, that is, 16, and 8M gives 12. Now, 9M gives 6. Note how input 4 is skipped because it was the only input in its function call. Lastly, 10M gives 5.

For the clipboard state in example 3:
[[3], [2, 40, 34], [7, 8, 15], []]

1M gives 3. 2M gives 2, 40, 34. 3M gives 7, 8, 15.
4M has undefined behaviour (for the purposes of this challenge), because there have only been three function calls.
5M gives 34. 6M gives 40. 7M gives 2. 8M gives 15. 9M gives 8,  10M gives 7.
11M, 12M, ... also have undefined behaviour.

The challenge
Input:

the clipboard state, as a list of lists, or any other reasonable format;
a positive integer n.

Output: the result of calling function M with n as input. The output will be one or several numbers with an unambiguous separator, or in any reasonable format such as a list or array.
Clarifications:

The clipboard state consists of four lists of numbers. Some of the trailing lists may be empty, as in examples 2 and 3. If preferred, you can input the clipboard without those trailing empty lists. So example 3 would become [[3], [2, 40, 34], [7, 8, 15]].
All numbers in the clipboard will be positive integers, possibly with more than one digit.
The number n is guaranteed to be valid. So for example 3 above, n cannot be 4 or 11.

Additional rules:

Input and output can be taken by any reasonable means.
Programs or functions are allowed, in any programming language. Standard loopholes are forbidden.
Shortest code in bytes wins.

Test cases
Clipboard state
Number
Output(s)

[[11, 28], [12, 16], [4], []]
2
12, 16

[[11, 28], [12, 16], [4], []]
5
28

[[7, 144], [12], [4, 8], [3, 4, 6]]
1
7, 144

[[7, 144], [12], [4, 8], [3, 4, 6]]
10
4

[[30], [40], [50, 60], [70, 80, 90]]
2
40

[[30], [40], [50, 60], [80, 90]]
7
90

[[15], [30], [2, 3, 5], [4, 5, 10]]
3
2, 3, 5

[[15], [30], [2, 3, 5], [4, 5, 10]]
7
2

Can we take a 0-indexed n?

@Arnauld I’m going to say no, as this is based on MATL’s actual behaviour

Jelly, 8 bytes
ḊƇUẎ⁸;⁹ị

Try it online!

Do you mind adding an explanation?

@LordColus ḊƇ select all non-singletons, U reverse and Ẏ flatten. For input [[11, 28], [12, 16], [4], []] this gets [16, 12, 28, 11], the values of 5M through 8M. Now prepend the original input to this list ⁸; and index into the resulting list by the other input ⁹ị.

@LordColus Ah, sorry, I only add explanations on request (because ninja), but I was asleep. Lynn pretty much explained it, however I would like to add that U doesn't reverse the result of ḊƇ, but rather each of its elements. Only if I could somehow reduce ḊƇUẎ⁸;...

Haskell, 56 51 47 bytes
-5-9 bytes thanks to Laikoni (pattern match to ensure length > 1 and using do-notation over list comprehension)!
c!n=([]:c++do l@(_:_:_)<-c;reverse$pure<$>l)!!n

Try it online!
Pointfree, 58 55 bytes
-3 bytes thanks to Laikoni (moving ([]:) and replacing id)!
Alternatively we could use this pointfree version
(!!).(([]:)<>map pure.(>>=reverse).filter((1<).length)).

APL (Dyalog Unicode), 17 bytes
{⍺⊃⍵⍪∊⊖¨⍵⌿⍨1<≢¨⍵}

Try it online!

JavaScript (Node.js), 57 bytes
a=>n=>a.map(e=>e[1]&&a.push(...[...e].reverse()))&&a[n-1]

Try it online!
This is an anonymous, curried function. Run it with ( function code )(clipboard)(n)
Explanation
a=>n=>{
    // The strategy is to append the individual clipboard inputs to the end of a,
    // after the function calls (lists). We then return a[n-1] to offset JavaScript's
    // zero indexing.
    a.map(e=>{
        e[1]&& // if this list has more than one element...
            a.push(...[...e].reverse()) // add each element to a, in reverse order.
            // reverse() modifies the original array, so we have to use [...e] to "clone" e
    })
    return a[n-1]
}

Stax, 12 14 13 bytes
àJ├∙ε╝F▀ÿi☻Ia

Run and debug it
Explanation:
vsc{%vfr$r+@]|u Full program, unpacked, implicit input
vs              Decrement the number and get the list
  c{  f         Copy and filter:
    %v            Length not equal to 1?
       r$r      Reverse, flatten, and reverse again
          +     Concat orig array and and modified array
           @]|u Index, wrap into array, uneval

Stax, 12 bytes
Å{b≈\☼╣Δ@░ ‼

Unpacked:
{vsc{%vfr$r+@}

This is a block, so I can get rid of the ]|u, but I don't know if this is valid as it's packing a block.

JavaScript (ES6), 72 bytes
Takes input in currying syntax (clipboard)(n).
a=>m=>a[m-1]||(g=r=>(r=r|a[k][1]&&a[k].pop())?--m<5?r:g(1):g(!++k))(k=0)

Try it online!

Python 2, 60 56 bytes
thanks to Jonathan Allan for -4 bytes.
lambda l,n:(l+sum([b[::-1]for b in l if b[1:]],[]))[n-1]

Try it online!

Java 8, 110 bytes
A lambda (curried) taking the clipboard state as an int[][] and the number as an int and returning int or int[] (a single number may be returned through either type).
s->n->{if(--n<4)return s[n];else{int i=0,l;for(n-=4;(l=s[i].length)<=n|l<2;i++)n-=l>1?l:0;return s[i][l+~n];}}

Try It Online
Ungolfed
s ->
    n -> {
        if (--n < 4)
            return s[n];
        else {
            int i = 0, l;
            for (
                n -= 4;
                (l = s[i].length) <= n | l < 2;
                i++
            )
                n -= l > 1 ? l : 0;
            return s[i][l + ~n];
        }
    }

05AB1E, 12 bytes
Díʒg<Ā}˜«s<è

Try it online!
Explanation
D              # duplicate input list
 í             # reverse each
  ʒg<Ā}        # filter, keep only elements that are longer than 1
       ˜       # flatten
        «      # append to original list
         s<    # decrement the second input
           è   # get the element in the list at that index

Husk, 12 bytes
!S+(m;ṁ↔f(¬ε

Try it online!
Explanation
Pretty much a direct port of the Haskell answer:
!S+(m;ṁ↔f(¬ε  -- example inputs: [[1],[2,3],[4],[5,6,7],[]] 7
 S+           -- concatenate itself with itself modified by
        f(    -- | filter
           ε  -- | | length 1
          ¬   -- | | not
              -- | : [[2,3],[5,6,7],[]]
      ṁ       -- | map and flatten
       ↔      -- | | reverse
              -- | : [3,2,7,6,5]
              -- | map
              -- | | pure
              -- | : [[3],[2],[7],[6],[5]]
              -- : [[1],[2,3],[4],[5,6,7],[],[3],[2],[7],[6],[5]]
!             -- index into it: [2]

R, 58 bytes
function(M,n)c(M,unlist(lapply(M[lengths(M)>1],rev)))[[n]]

Try it online!
Takes M as a list of vectors c(); so replacing [[ with list(, [ with c( and ] with ) should transform the test cases into R test cases.
For inputs n<=4 with "undefined behavior", returns NULL and for other invalid inputs, throws a "subscript out of bounds" error.
function(M,n)
                                        [[n]]	# take the nth element of
c(M,                                   )	# M concatenated with:
    unlist(                           )		# the individual elements of
           lapply(               ,rev)		# in-place reversals of
                  M[lengths(M)>1]		# elements of M with length > 1

Could probably get away with using [n] instead of [[n]].

J, 33 22 bytes
-11 bytes (1/3 shorter) thanks to  FrownyFrog's solution!
{0;],|.&.>;/@;@#~1<#&>

Try it online!
My initial solution:
J, 33 bytes
<:@[{(,[:<"0@;[:|.&.>(1<#)&>#])@]

Not happy - I'm pretty sure it can be golfed much further.
Explanation:
A dyadic function, taking the clipboard state as its rigth argument, the left argument is n
<:@[ subtract 1 from the left argument
{ selects the ith element (calculated above) from the list on its right
(...) the entire list
# copy
] from the list of clipboard state
(1<#) the sublists with length greater than 1
|.&.> rotate each copied sublist
<"0@; raze and box - puts each number into a separate box
, append the new list to the list of clipboard state
@] makes the entire verb in (...) monadic
Try it online!

@FrownyFrog I like 0; the most. Thanks!

That’s entirely your solution, just golfed :)

V + coreutils, 53 45 43 42 40 bytes
-9 bytes thanks to DJMcMayhem (using VGÇ /d over :,$g/^[^ ]*$/d, D@"dd over "aDÀdd and !! over :.!)!
My very first attempt at V (tips welcome!), the below code is using circled characters (eg. ⓞ for \xf) for readability:
jäGⓞVGÇ /d
ⓞò!!tr \  \\n|tac
jòHD@"ddjdG

Try it online!
Hexdump
00000000: 6ae4 470f 5647 c720 2f64 0a0f f221 2174  j.G.VG. /d...!!t
00000010: 7220 5c20 205c 5c6e 7c74 6163 0a6a f248  r \  \\n|tac.j.H
00000020: 4440 2264 646a 6447                      D@"ddjdG

Explanation
The first line contains n and the lines below contain the entries of the clipboard, each entry is separated by spaces if there were multiple inputs:
j                        " move to the beginning of the clipboard entries
 äG                      " duplicate the clipboard
   ⓞ                    " <C-o> move cursor to the beginning of the 2nd copy
     VG                  " select everything from cursor to the end of buffer and ..
       Ç /d              " .. delete every line that doesn't contain a space

ⓞ                       " <C-o> move cursor to the beginning of the 2nd copy (now without single arguments)
  ò                   ò  " do the following until the end of buffer
   !!                    "   on the current line execute the shell command
     tr \  \\n           "   replace spaces with newlines
              |tac⮠     "   and reverse the lines
                    j    "   move to next line

H                        " go to the beginning of buffer (where n is)
 D                       " delete n (stores it in register ")
  @"                     " that many times ..
    dd                   " .. remove the line
      j                  " move cursor to next line
       dG                " delete everything from here to the end of buffer

Red, 91 bytes
func[b n][a: copy[]foreach c b[if 1 < length? c[append a reverse copy c]]pick append b a n]

Try it online!

C (gcc), 176 bytes
#define p printf("%d ",
int*_,i;f(x,n)int**x;{if(n<5){for(_=x[2*n-2];_-x[2*n-1];++_)p*_);}else{n-=4;for(i=0;i<8;i+=2)if(n&&x[i]+1-x[i+1])for(_=x[i+1];_-x[i]&&n;--_,--n);p*_);}}

Try it online!
Takes the array as a list of 4 start/end pointer pairs, then n.
Description:
#define p printf("%d ",  // This gives us the short-hand for printing
int*_,                   // This defines _ as a pointer to int
i;                       // This defines i as an integer
f(x,n)int**x;{           // This defines f as a function taking int **x and int n
                         // NOTE: x is {start, end, start, end, start, end, start, end}
if (n<5) {               // This is for the 1-4 case
  for(_=x[2*n-2];        // Loop _ from the 'end pointer'
  _-x[2*n-1];++_)        // Until the 'start pointer'
  p*_);                  // Using the short-hand, print *_
}else{                   // This is for the 5+ case
  n-=4;                  // Cut n to improve indexing
  for(i=0;i<8;i+=2)      // Loop over each 'start pointer index'
    for(_=x[i+1];        // Loop _ from the 'end pointer'
        _-x[i]&&n;       // Until the 'start pointer' or n becomes 0
        --_,--n);        // Decreasing n each time
  p*_);}}                // _ now points to the 'correct' index, so print it

159 bytes


text:
Mathematical parser
Challenge :
Given a string representing a mathematical expression return the result

Input :
A string representing a mathematical expression : '1 + 2 - 3 * (2/3 * 1)'.
Output :
The result after performing all operations.

Operators :
Possible operators
+     ---> plus
-     ---> minus
*     ---> multiplication
/     ---> division
(     ---> opening parenthesis
)     ---> closing parenthesis

operator precedence :
Operators are always evaluated from left-to-right going from here ---> there, and * and / must be evaluated before + and -
Parenthesis take precedence over everything else and must be completed before all.
Parenthesis :
You should be able to support multiple(nested) levels of parenthesis.
e.g :
 1 - ( 2 * ( 3 / 9 + ( 2 * 6 ) ) )

White space :
Whitespace doesn't matter, you can have whitespace between operators or you can't (Consistency is required though)

Note :

Given input will always be valid. It will consist of nothing except

Numbers (0-9) of arbitary length
operators (+ , - , * , /)
parenthesis (( / )) nested
white space (optional with consistency)

Use of eval and Function or their equivalent counter-parts in any language is forbidden
using built-in functions designed specifically for this is also forbidden
all standard loopholes are forbidden by default.
You need to support floats to a reasonably high value (depending on the language) but after that integers will work. alternately after that floating point error (if reasonable) will be acceptable.
This is code-golf so shortest code in bytes for each language wins.

Examples :
 1 + 2 * 3              ---> 7
 10 * 2 / (2 - 3) * 2   ---> -10 (expression is (2*10) / ((2-3)*2) => 20/-2
 1-(2*(3/9+(2*6)-3))    ---> -53/3 (3/9 is the fraction and not the whole)
 -1 * --10              ---> -10 (support for unary minus)

Is unary minus one of the operations ?

@HatsuPointerKun : Yep

Should floating point numbers also be supported or only integer is okay ?

@HatsuPointerKun : supported till your language can hold them after the floating point error is acceptable.

Can we output floating point numbers instead of fractions?

@ovs : You can output that way

Looking at your final example, to maintain white space 'consistency' , shouldn't the unary minus be expressed as "- 1 * - - 10"? And further to that, considering you use two unary minus signs in a row, as in your example, can you also use a unary plus sign, "+1" for example, and if so can you arbitrarily mix unary signs: "-+1*+--+10"?

Mathematica, 0 bytes

@StanStrum haha, nice one (but you would still need something like #&, which costs 2 bytes). But I think that's invalid because it relies on Mathematica's internal auto-evaluation.

Shouldn't your second example equal -40 instead of -10?

"White space consistency": does this mean we can choose whether we allow whitespace or not? Or does it mean that an input may contain whitespace, and if it does, it is consistent?

Also, may I suggest changing the title to something like "Arithmetic interpreter", since this is really more than just a parser?

I'm confused by your second example. Since * and / have the same precedence, and we go left to right, shouldn't it be ((2*10)/-1)*2?