Network wide reputation survey Given a PPCG user's user ID, calculate how much times is their Each SE site reputation is from average reputation in the Stack exchange sites they have made accounts.
Let me explain, If someone's total network reputation (Total reputation in the stack exchange sites he has participated) is 10k, and if he has participated in 4 sites, then the average network wide reputation will be 2500
And assume he/she participated in these 4 sites and has these reputation
Stack overflow 3000
Code golf and Coding challenges 2000
Mathematics 1500
Super User 4000

So your final output should be:
Stack overflow 1.2x
Code golf and coding challenges 0.8x
Mathematics 0.6x
Super User 1.8x

Here the x is to express how much times each site reputation is of the average, such as 2500*1.2=3000

(No obligation to floor the 1.2)
(Order of the sites does not matter)
(You can write the site names uppercase or lowercase or anything, that does not also matter)

Your code will be able to access internet freely.
Input is the PPCG User ID.
Trailing/leading whitespace allowed in output, Standard loopholes apply, this is code-golf shortest code wins.
Test case
user 95516 (@rak1507, chosen him/her because have participated in less sites)
For average 943:
Code golf and coding challenges 3.57x
Stack overflow 0.21x
Meta stack exchange 0.107x
Puzzling 0.107x

JavaScript (Node.js), 465 bytes
(i,C)=>(p='https://codegolf.stackexchange.com',n=t=a=[],g=(u,c)=>require('https').get(u,r=>r.on('data',d=>i+=d,r.on('end',_=>c(r.headers.location)))))(p+'/users/'+i,l=>g(p+l,_=>g(s=i.match(/ht.+\/s[^"]+\d\/[^?]/)+0,l=>g(new URL(l,s)+'?tab=accounts',_=>i.replace(/unt-[^]+?\n *([\w&].+)[^]+?r".+?([\d,]+)/g,(_,s,r)=>a.push([s,r=r.split`,`.join``,t-=r,n--]))&&C(a.map(([s,r])=>s.replace(/&#?(.+?);/g,(_,m)=>String.fromCharCode('0'+m|0||38))+` ${r/t*n}x`).join`
`)))))

Function which accepts a the ID as a string and returns the result to a callback.
I tried to make it robust and it should work for any profile as of time of submission with one possible exception: the accounts tab on the network profile contains a profile summary which can be edited by the user so it's possible for a user to write something to fool the regex in their bio.
Explanation
(i,C)=>(p='https://codegolf.stackexchange.com',
// n = count of sites, t = total sum of reputation, a = array of (siteName, rep) tuples
n=t=a=[],
// Function which performs a GET request.
// The body is appended to `i` and the callback is called with the location header.
g=(u,c)=>require('https').get(u,r=>r.on('data',d=>i+=d,r.on('end',_=>c(r.headers.location))))
// Load the user's PPCG profile.
)(p+'/users/'+i,l=>
// Since we only provided the ID and not the name in the URL, it will return a 301 redirect.
// Load the redirect.
g(p+l,_=>
// The first URL on the body to match this regex is the network profile URL of the user.
// Note that this comes before the custom content in the profile
// (which could contain other network profile URLs).
// This request will result in a 301 if the user's name is different on the
// network profile than PPCG, so the first character plus 0 will force a redirect
// because display names are a minimum of 3 characters long.
g(s=i.match(/ht.+\/s[^"]+\d\/[^?]/)+0,l=>
// Load the accounts tab of the network profile.
g(new URL(l,s)+'?tab=accounts',_=>
// Find each site and reputation count.
i.replace(/unt-[^]+?\n *([\w&].+)[^]+?r".+?([\d,]+)/g,
// Remove the commas from the rep value, populate `a` and add them up for the average.
// decodeURIComponent is annoyingly long but there's no shorter way to correctly display
// sites like the Japanese site which is made solely of URI encoded characters.
(_,s,r)=>a.push([s,r=r.split`,`.join``,t-=r,n--]))&&
// Calculate and print the results.
// There is a lot of bytes dedicated here to unescaping HTML entities because
// unfortunately there's no easy way to correctly display sites like the Japanese site
// which is made solely of HTML encoded characters.
// As far as I can tell the only escapes used in site names are the `&#xXX` style
// and `&amp;`.
C(a.map(([s,r])=>s.replace(/&#?(.+?);/g,(_,m)=>String.fromCharCode(0+m|0||38))+` ${r/t*n}x`).join`
`)))))


The Return of FizzBuzz Intro

Beauty lies in the eye of the beholder. Output lies in the choice of the compiler. There are some codes that give different outputs based on what language they are executed in. Take for instance, the code given below:

# include <stdio.h>
# define print(a) int main(){printf("C is better"); return 0;}
print("Python is better")

When executed in C, it prints "C is better". When using a python interpreter, it prints "Python is better".

Challenge

The challenge is a modification of the FizzBuzz challenge. Write a code that gives different outputs based on language it is executed in. When executed with the first language, it prints all numbers from 1 to 1000 (both inclusive) which are not divisible by 2. If a number is divisible by 2, it outputs "FizzBuzz". When executed with the second language, if a number is not divisible by 3, it is printed. Else, the string "FizzBuzz" is printed.

Example

Output when executed in language 1 would be

1 FizzBuzz 3 FizzBuzz 5 FizzBuzz 7 FizzBuzz 9 FizzBuzz ... (upto FizzBuzz 999 FizzBuzz)

Output when executed in language 2 would be

1 2 FizzBuzz 4 5 FizzBuzz 7 8 FizzBuzz 10 11 FizzBuzz 13 14 FizzBuzz ... (upto 998 FizzBuzz 1000)

Optional Challenge

You can optionally allow the program to execute in more than 2 languages. For the ith language, every multiple of (i+1) is substituted with FizzBuzz. It isn't necessary, but at least 2 languages are compulsory.

Constraints

Need to write a fully functioning code. For instance, a method/function/procedure alone (which could not independently execute) would not be acceptable

Can use only 1 file

All outputs to be printed to standard output (not to standard error)

All other standard rules of code-golf apply

EDIT: Fixed a loophole:

No taking of user inputs during execution

Edit I got a comment saying  the question wasn't clear if a non-empty separator is mandatory between the numbers. Assume it's not mandatory

Scoring

Total score = Number of bytes in the program.

Winning

Consider different participation brackets (based on number of languages being used). Person with least characters in each bracket can be considered a winner.

05AB1E / 05AB1E (legacy) / 2sable, 27 bytes
3°Lv®dтнOÌyDrÖi"FizzBuzz"},

2: Try it online in 2sable.
3: Try it online in 05AB1E.
4: Try it online in 05AB1E (legacy).
Explanation:
Let's start with a bit of history of these three languages. The development of 05AB1E started at the start of 2016 (or actually, the very first git-commit was on December 21st, 2015). This new codegolf language was being built in Python as backend. Mid 2016 2sable was branched of the 05AB1E version (July 7th, 2016 to be exact), and the strength of 2sable in comparison to that old 05AB1E version was added: implicit inputs. Later on implicit input was also added to 05AB1E, and 2sable was basically a forgotten version right after it was created on that day July 7th, 2016.
Then in mid-2018, a new 05AB1E version was being started, this time completely rewritten in Elixir instead of Python, with loads of new builtins added and some builtins changed or even removed.
So, let's go over the code and see what it does in each of the three languages:

3°                          # Push 10^3: 1000 (NOTE: I'm unable to use builtin `₄` for
                            # 1000, since it wasn't available in 2sable yet)
  Lv                        # Loop `y` in the range [1,1000] (NOTE: I'm unable to use
                            # builtin `E` for the [1,n] loop, since it wasn't available
                            # in 2sable nor the legacy version yet)
    ®                       #  Push -1
     d                      #  2sable: check if -1 only consist of digits (falsey / 0)
                            #  05AB1E (legacy): check if -1 is an integer (truthy / 1)
                            #  New 05AB1E: check if -1 is non-negative ≥0 (falsey / 0)
      т                     #  2sable: no-op, so does nothing
                            #  05AB1E (legacy) / new 05AB1E: push 100
       н                    #  Pop and push its first character
                            #   2sable: does this for the 0 of the `d` falsey result
                            #   05AB1E (legacy) / new 05AB1E: 100 → 1
        O                   #  Sum all values on the stack:
                            #   2sable: 0
                            #   05AB1E (legacy): 2 (1+1)
                            #   New 05AB1E: 1 (0+1)
         Ì                  #  Increase it by 2
                            #   2sable: 2
                            #   05AB1E (legacy): 4
                            #   New 05AB1E: 3
          yD                #  Push the loop value `y` two times
            r               #  Reverse the values on the stack
             Öi          }  #  If `y` is divisible by the value we calculated earlier:
               "FizzBuzz"   #   Push string "FizzBuzz"
                          , #  Pop and print the top value with trailing newline

Note: the O to sum the stack will also add the previous value that was divisible (since we've duplicated it with D, but only popped and printed "FizzBuzz"). But since we know it's divisible, the increased sum in that next iteration doesn't make a difference to the divisibility check.


Make a simple pretty-comment tool Challenge:

Some ascii-art is a pain to make, but makes code comments easier to read, especially when the code is dense. The challenge is to make a simple tool that converts comments to simple ascii-art with arrows. The comments to modify are delimited by empty comments.

For example, supposing Haskell comment syntax, convert this:

--
-- Here's a thing
-- Here's another thing
-- The most important thing
-- *    *     *
--
f x=x+1*x*1*1*0

To this:

-- /------------< Here's a thing
-- |    /-------< Here's another thing
-- |    |     /-< The most important thing
-- |    |     |
-- v    v     v
f x=x+1*x*1*1*0

Rules:

Your answer may be either a function or full program
You may pick the language this is made to work with, replacing the "--" with two or more characters that delimit a comment in some language
If using another comment format that requires beginning and ending delimiters, each line of the reformatted sections must be a proper comment
The sections to be reformatted are delimited by the empty comment "\n--\n"
Besides adding newlines, the program must not change any of the input except the delimited sections
A comment filled with an arbitrary number of spaces may come immediately before a properly formatted section of output
Standard loopholes are disallowed

Additional Examples:

(input)
--
--
(output)
nothing

(input)
[Code Here]
--
-- important
--    *
--
(output)
[Code Here]
--    /-< important
--    |
--    v

(input)
--
-- Do
-- Re
-- Mi
-- Fa
-- So
-- *****
--
(output)
-- /-----< Do
-- |/----< Re
-- ||/---< Mi
-- |||/--< Fa
-- ||||/-< So
-- |||||
-- vvvvv

Scoring:

Fewest bytes wins
Submissions without explanations or non-trivial example input/output will not be considered (though I will leave a grace period to allow time to add such)

JavaScript(ES6), 418, 237, 233, 236 bytes

f=(s)=>(d='\n//',s.split(d+'\n').map((x,y)=>y%2?'//'+(l=x.slice(2).split(d),t=l.pop().split('*'),l.map((i,j)=>t.map((k,m)=>m==j?k+'/':m<j?k+'|':k.replace(/ /g,'-')+'-').join('')+'<'+i).join(d)+d+t.join('|')+d+t.join('v')):x).join('\n'))

Whew, this is my first submission on CG. Took, I think, a totally different tack from Washington Guedes. Ended up 54 bytes shorter than his first pass. Minifying all this by hand was grueling. My one regret is not being able to eliminate the while loop yet, which would also let me cut the return.

Total rewrite, taking partial inspiration from a couple of the other answers. I got to close the whole thing in maps, making returning much better. The code snippet contains the commented version.

Took a few more bytes off, and made the example operate on itself. (You're gonna need a bigger monitor.) :)

Forgot an entire letter in the spec! Fortunately, adding the leading '<' was a tiny, trivial fix.

var comments = `
//
// New function, declare the comment delimiter
// Chop the string by the fancy comment delimiter
// Iterate over the array.
// Because of how it's delimited, and how JS splits strings, only the even elements will contain fancy comments.
// Add the original comment delimiter to the front of the first line, because join won't.
// we've got a single fancy comment, split it into lines.
// Take the last line, our asterisk template, and split it on the asterisks themselves. We were only gonna replace them anyway.
// Now we get to the real work. Iterate the remaining lines.
// For each chunk of whitespace in the template array, toss a different character on the end based on where we are in the series of lines.
// if we're at the matching asterisk, insert a slash
// Otherwise, if we're at a prior asterisk, add a pipe.
// Finally, replace anything afer the matching asterisk with dashes, join the template, and add it to the line text.
// Join the lines with the delimiter
// Add the pipe line...
// And the v line...
// For odd chunks, just return the chunk.
// Join all the code chunks and autoreturn.
//      *        *               *          *   *     *                     *                    *            *            *          *         *                                        *           *             *          *  *
//
`
f=(s)=>(d='\n//',s.split(d+'\n').map((x,y)=>y%2?'//'+(l=x.slice(2).split(d),t=l.pop().split('*'),l.map((i,j)=>t.map((k,m)=>m==j?k+'/':m<j?k+'|':k.replace(/ /g,'-')+'-').join('')+'<'+i).join(d)+d+t.join('|')+d+t.join('v')):x).join('\n'))

str = `
//
// This is a test
// with two lines
// actually three
// *  *       *
//
var myCode = function () {

}
// This doesn't cause any trouble.

moreCode(stuff--)

//
// another test?
//  *
//

`
document.getElementById('before').textContent = str;
document.getElementById('after').textContent = f(str);
document.getElementById('self').textContent = f(comments)+'f='+f.toString();
Test cases before:

Test cases after:

Self-annotated:


Regex Golf: Regions of Italy vs. States of USA We've already got a meta-regex-golf problem as inspired by the xkcd comic

But, this regex golf looks fun, too!  I want to distinguish between the states of the US and the regions of Italy.  Why?  I'm a citizen of both countries, and I always have trouble with this*.

The regions of Italy are

Abruzzo, Valle d'Aosta, Puglia, Basilicata, Calabria, Campania, Emilia-Romagna, Friuli-Venezia Giulia, Lazio, Liguria, Lombardia, Marche, Molise, Piemonte, Sardegna, Sicilia, Trentino-Alto Adige/Südtirol, Toscana, Umbria, Veneto

and the states of the USA are

Alabama, Alaska, Arizona, Arkansas, California, Colorado, Connecticut, Delaware, Florida, Georgia, Hawaii, Idaho, Illinois, Indiana, Iowa, Kansas, Kentucky, Louisiana, Maine, Maryland, Massachusetts, Michigan, Minnesota, Mississippi, Missouri, Montana, Nebraska, Nevada, New Hampshire, New Jersey, New Mexico, New York, North Carolina, North Dakota, Ohio, Oklahoma, Oregon, Pennsylvania, Rhode Island, South Carolina, South Dakota, Tennessee, Texas, Utah, Vermont, Virginia, Washington, West Virginia, Wisconsin, Wyoming

Your job is to write a program which distinguishes these lists with a regular expression.  This is a new game, so here's the

Rules

Distinguishing between lists must be done with a single matching regular expression.
Your score is the length of that regular expression, smaller is better.

To be clear: all work must be done by the regular expression -- no filtering, no replacements, no nothing... even if those are also done with regular expressions.  That is, the input should be passed directly into a regular expression, and only the binary answer (match / no match) can be used by later parts of the code.  The input should never be inspected or changed by anything but the matching expression.  Exception: eating a newline with something akin to Ruby's chomp is fine.

Your program should take a single entry (optionally followed by \n or EOF if it makes things easier) from either list from stdin, and print to stdout the name of that list.  In this case, our lists are named Italy and USA.

To test your code, simply run both lists through it.  Behavior may be undefined for strings which do not occur in the list.

Scoring Issues

This might have to be done on a language-by-language basis.  In Perl,

m/foobarbaz/

is a matching regular expression.  However, in Python,

import re
re.compile('foobarbaz')

does the same thing.  We wouldn't count the quotes for Python, so I say we don't count the m/ and final / in Perl.  In both languages, the above should receive a score of 9.

To clarify a point raised by Abhijit, the actual length of the matching expression is the score, even if you generate it dynamically.  For example, if you found a magical expression m,

n="foo(bar|baz)"
m=n+n

then you should not report a score of 12: m has length 24.  And just to be extra clear, the generated regular expression can't depend on the input.  That would be reading the input before passing it into the regular expression.

Example Session

input> Calabria
Italy
input> New Hampshire
USA
input> Washington
USA
input> Puglia
Italy

* Actually, that's a lie.  I have never had any trouble with this at all.

Perl - 51 36 bytes (for regex)

print<>=~/.A|ise|net|te|z.o|[cp]a|[lr]ia|r[cd]/?"Italy
":"USA
"

Nothing special, but may as well post it, because it's different to other 51 bytes solution.

Or alternatively, shorten my already short solution by 15 bytes. This wins for now, I think.


Evaluate a minimax tree Alice and Bob are playing a little game. First, they draw a tree from a root node (indicated by a thick dot), with no internal nodes, with numbers at the leaves. Any node may have any number of children.

We start at the root, and first to play is Alice (A). She must select one of the current node's children. Then it's Bob's turn, and he similarly selects a child node. This continues until a leaf node is reached.

When a leaf node is reached, the game is over. It is Alice's goal to end at a node with as large of a value as possible, and Bob's goal to end at a node with as small of a value as possible.

Given a tree in nested array form, return the value of the leaf that will be reached if both Alice and Bob play perfectly.

Examples:

18: [[67, [[100, [[67, 47], [86], 21, 16], [[46, [14], 35, 85], [71, [18, 63, 69], 99, 22], 3]]], [[18, 32, 42, 80]], [[36, 70], [86, 53, 46, 59], [[41], 86, 35]]], 3]
60: [[[84, 35], [44, 60]], [[24, 98], [16, 21]]]
58: [[53, 77], [58, [82, 41]], 52]
59: [[93, [100, 53], 58, 79], [63, 94, 59], [9, [55, 48]], [40, 10, 32]]
56: [[20, 10, [[[89, 22, 77, 10], 55], [24, 28, 30, 63]]], [[49, 31]], 17, 56]
0: [0]

You may assume that the root node never is a leaf node and points to at least one leaf node. You may assume that leafs are nonnegative numbers.

Shortest code in bytes wins.

Python 2, 53 bytes
f=lambda l,c=1:c*l if l<[]else-min(f(x,-c)for x in l)

The main question is how to alternate between max and min each layer. Using the fact that max(l) == -min([-x for x in l]), we instead negate every second layer and recurse with -min. To negate every second layer, we pass down a multiplier c that alternates +1 and -1, and when we reach a leaf, we adjust its value by the multiplier. We recognize being at a leaf via the condition l<[], since Python 2 treats numbers as less than lists.
It's hard to shorten the else/if ternary because either branch could give a Truthy (nonzero) or Falsey (zero) value.


ASCII-art logic gate diagram I challenge you to write a code to make an (extended) ASCII-art logic gate diagram for the sum of products form of an equation.

Use the following notation to represent gates:

AND

    INPUT───|&&
            |&&───OUTPUT
    INPUT───|&&

OR

    INPUT───|OR
            |OR───OUTPUT
    INPUT───|OR

Gates with more than 2 inputs

    INPUT───|OR
            |OR
    INPUT───|OR───OUTPUT
            |OR
    INPUT───|OR

NOT

    INPUT───│>o───OUTPUT

Character set

Note that │ is not an ASCII pipe sign but a box-drawing character. Use box-drawing characters such as ─ │ ┌ ┐ └ ┘ for connections.

Example

Input

    A'*B'+B*C

Output

    A────│>o────│&&
                │&&─────┐
    B────│>o────│&&     └│OR
                         │OR─────A*B+B*C
    B───────────│&&     ┌│OR
                │&&─────┘
    C───────────│&&

Winner

The winner is the answer with the most up-votes in 5 days

C++11
Done at last. And it only took me most of the day.
Before I list the code and sample output, some quick notes:
Things this program does support

Any number of terms, each with any number of inputs
Reusing inputs
Omitting AND/OR gate representation when only one input would be present
Use of both codepage 437 line-drawing characters and 7-bit ASCII-friendly characters (use -DCP437 or whatever your compiler's equivalent is for codepage 437 support)

Things this program does not support

Grouping with parentheses (because, seriously?)
Multiple NOTing
Any whitespace that isn't a plain ASCII space
Proper golfification (although I did remove all the comments in spirit)
Sane coding practices
Making eye contact with the input parsing code
Portable, Unicode line-drawing characters. I couldn't support Unicode because the rendering logic relies on being able to draw "down" a two-dimensional char buffer.

Code
#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <stdexcept>
#include <set>
#include <map>
#include <valarray>
#include <cmath>

using namespace std;

vector<string> split(const string str, const string delim)
{
    vector<string> v;

    set<char> d;
    for (char c : delim) d.insert(c);

    string current {};
    for (char c : str)
    {
        if (d.find(c) != d.end())
        {
            v.push_back(current);
            current = "";
        }
        else
        {
            current += c;
        }
    }
    v.push_back(current);

    return v;
}

using Input = string;
struct TermInput
{
    Input name;
    int ypos;
    bool neg;
};
using Term = vector<TermInput>;
using Expr = vector<Term>;

#ifdef CP437
constexpr char VERT    = '\xB3';
constexpr char HORIZ   = '\xC4';
constexpr char RBRANCH = '\xC3';
constexpr char LUP     = '\xD9';
constexpr char LDOWN   = '\xBF';
constexpr char RUP     = '\xC0';
constexpr char RDOWN   = '\xDA';
#else
constexpr char VERT    = '|';
constexpr char HORIZ   = '-';
constexpr char RBRANCH = '}';
constexpr char LUP     = '\'';
constexpr char LDOWN   = '.';
constexpr char RUP     = '`';
constexpr char RDOWN   = ',';
#endif

string repeat(string s, int n)
{
    stringstream ss;
    for (int i = 0; i < n; i++)
    {
        ss << s;
    }

    return ss.str();
}
string repeat(char c, int n)
{
    stringstream ss;
    for (int i = 0; i < n; i++)
    {
        ss << c;
    }

    return ss.str();
}

enum class Direction
{
    RIGHT,
    DOWN
};

void matrixPut(char *matrix, int h, int w, int x, int y, const string s, Direction dir)
{
    if (x >= w || y >= h)
    {
        stringstream ss;
        ss << "matrixPut: point (" << x << ", " << y << ") out of matrix bounds!";
        throw new out_of_range(ss.str());
    }

    char *ins = matrix + (y * w) + x;
    char *end = matrix + (h * w);
    for (char c : s)
    {
        if (ins >= end) break;
        *ins = c;

        if (dir==Direction::RIGHT)
        {
            ins++;
        }
        else
        {
            ins += w;
        }
    }
}

void matrixPrint(char *matrix, int h, int w)
{
    for (int i = 0; i < (h * w); i++)
    {
        cout << matrix[i];
        if ((i+1)%w == 0) cout << endl;
    }
}

int main (int argc, char *argv[])
{
    string expression;

    if (argc == 1)
    {
        cout << "Enter expression:" << endl;
        getline(cin, expression);
    }
    else
    {
        expression = argv[1];
    }

    expression.erase(remove(expression.begin(), expression.end(), ' '), expression.end());

    Expr expr {};
    auto inputs = set<Input>();
    auto termInputs = multimap<Input, TermInput>();

    int inputYPos = 0;

    auto e = split(expression, "+");
    for (string term : e)
    {
        Term currTerm {};

        auto t = split(term, "*");
        for (string in : t)
        {
            bool neg = false;
            if (in.back() == '\'')
            {
                in.pop_back();
                neg = true;
            }

            Input currInput {in};
            inputs.insert(currInput);

            TermInput ti {currInput, inputYPos, neg};
            currTerm.push_back(ti);

            termInputs.insert(pair<Input, TermInput>{in, ti});
            inputYPos++;
        }

        expr.push_back(currTerm);
        inputYPos++;
    }

    int height = inputs.size() + termInputs.size() + expr.size() - 1;

    int width = 0;

    width += max_element(inputs.begin(), inputs.end(), [](Input a, Input b){ return a.length() < b.length(); })->length() + 2;
    int inputWidth = width;
    width += inputs.size()*2;

    int notAndStart = width;

    width += 7;
    width += expr.size()+1;

    int orStart = width;

    width += 4;

    width += 4;

    width += expression.length();

    char matrix[height * width];
    for (int i = 0; i < height*width; i++) matrix[i] = ' ';

    int  baseY = inputs.size();

    {
        int x = width - 4 - expression.length();
        int y = baseY + ((height-baseY) / 2);
        matrixPut(matrix, height, width, x, y, repeat(HORIZ, 4) + expression, Direction::RIGHT);
    }

    {
        int x = orStart;
        int y = baseY + (height-baseY)/2 - expr.size()/2;

        if (expr.size() == 1)
        {
            matrixPut(matrix, height, width, x, y, repeat(HORIZ, 4), Direction::RIGHT);
        }
        else {
            matrixPut(matrix, height, width, x  , y, repeat(HORIZ, expr.size()), Direction::DOWN);
            matrixPut(matrix, height, width, x+1, y, repeat(VERT , expr.size()), Direction::DOWN);
            matrixPut(matrix, height, width, x+2, y, repeat('O'  , expr.size()), Direction::DOWN);
            matrixPut(matrix, height, width, x+3, y, repeat('R'  , expr.size()), Direction::DOWN);
        }
    }

    {
        int x = notAndStart;
        int y = baseY;
        for (Term t : expr)
        {
            string layer[7];
            for (TermInput ti : t)
            {
                layer[0] += HORIZ;
                layer[1] += (ti.neg ? '>' : HORIZ);
                layer[2] += (ti.neg ? 'o' : HORIZ);
                layer[3] += HORIZ;
                layer[4] += (t.size() > 1 ? VERT : HORIZ);
                layer[5] += (t.size() > 1 ? '&' : HORIZ);
                layer[6] += (t.size() > 1 ? '&' : HORIZ);
            }

            for (int i = 0; i < 7; i++)
            {
                matrixPut(matrix, height, width, x+i, y, layer[i], Direction::DOWN);
            }

            y += t.size() + 1;
        }
    }

    {
        int x = 0;
        int y = 0;

        for (Input i : inputs)
        {
            string str = i + ": ";
            str += repeat(HORIZ, inputWidth - str.length());

            matrixPut(matrix, height, width, x, y, str, Direction::RIGHT);

            y++;
        }
    }

    {
        int x = inputWidth;
        int num = 0;
        int offset = inputs.size() * 2 - 1;

        for (Input in : inputs)
        {
            int y = 0;
            int len = inputs.size() * 2 - 1;
            auto it = inputs.find(in);
            while (it != inputs.begin())
            {
                it--;
                y++;
                len -= 2;
            }
            matrixPut(matrix, height, width, x, y, repeat(HORIZ, len) + LDOWN, Direction::RIGHT);
        }

        for (Input in : inputs)
        {
            auto yBreakRange = termInputs.equal_range(in);
            valarray<int> yBreaks(termInputs.count(in));
            int idx = 0;
            for (auto ti = yBreakRange.first; ti != yBreakRange.second; ti++)
            {
                yBreaks[idx++] = baseY + ti->second.ypos;
            }

            for (int y : yBreaks)
            {
                matrixPut(matrix, height, width, x+offset, y, repeat(HORIZ, inputs.size()*2 - offset), Direction::RIGHT);
            }

            int y = num + 1;
            int maxBreak = yBreaks.max();
            string branch = repeat(VERT, maxBreak - y + 1);

            for (int i : yBreaks)
            {
                branch[i-y] = RBRANCH;
            }
            branch.back() = RUP;

            matrixPut(matrix, height, width, x+offset, y, branch, Direction::DOWN);

            offset -= 2;
            num++;
        }
    }

    {
        int x = notAndStart + 7;
        int outY = baseY + (height-baseY)/2 - expr.size()/2;
        int breakx = expr.size()/2;

        for (Term t : expr)
        {
            int inY = baseY + (t.front().ypos + t.back().ypos) / 2;

            matrixPut(matrix, height, width, x, inY, repeat(HORIZ, abs(breakx)+1), Direction::RIGHT);

            matrixPut(matrix, height, width, x+abs(breakx)+1, outY, repeat(HORIZ, expr.size()-abs(breakx)), Direction::RIGHT);

            if (inY < outY)
            {
                string branch = LDOWN + repeat(VERT, outY-inY-1) + RUP;
                matrixPut(matrix, height, width, x+abs(breakx)+1, inY, branch, Direction::DOWN);
            }
            else if (inY > outY)
            {
                string branch = RDOWN + repeat(VERT, inY-outY-1) + LUP;
                matrixPut(matrix, height, width, x+abs(breakx)+1, outY, branch, Direction::DOWN);
            }

            outY++;
            breakx--;
        }
    }

    cout << endl;
    matrixPrint(matrix, height, width);
    cout << endl;
}
Sample output
$ ./gates "A'*B'+B*C"

A: -----.
B: ---. |
C: -. | |
    | | `->o-|&&--.
    | }--->o-|&&  `-|OR
    | |          ,--|OR----A'*B'+B*C
    | `------|&&-'
    `--------|&&

$ ./gates "A*B'*C+B*D'+F*C'*D+G*E*A'+F"

A: -------------.
B: -----------. |
C: ---------. | |
D: -------. | | |
E: -----. | | | |
F: ---. | | | | |
G: -. | | | | | |
    | | | | | | }----|&&
    | | | | | }--->o-|&&---.
    | | | | }--------|&&   |
    | | | | | | |          |
    | | | | | `------|&&--.|
    | | | }------->o-|&&  ||
    | | | | |   |         |`---|OR
    | }--------------|&&  `----|OR
    | | | | `----->o-|&&-------|OR----A*B'*C+B*D'+F*C'*D+G*E*A'+F
    | | | `----------|&&  ,----|OR
    | | |       |         |,---|OR
    `----------------|&&  ||
      | `------------|&&--'|
      |         `->o-|&&   |
      |                    |
      `--------------------'
Sample output (with CP437 enabled)
A: ─────────────┐
B: ───────────┐ │
C: ─────────┐ │ │
D: ───────┐ │ │ │
E: ─────┐ │ │ │ │
F: ───┐ │ │ │ │ │
G: ─┐ │ │ │ │ │ │
    │ │ │ │ │ │ ├────│&&
    │ │ │ │ │ ├───>o─│&&───┐
    │ │ │ │ ├────────│&&   │
    │ │ │ │ │ │ │          │
    │ │ │ │ │ └──────│&&──┐│
    │ │ │ ├───────>o─│&&  ││
    │ │ │ │ │   │         │└───│OR
    │ ├──────────────│&&  └────│OR
    │ │ │ │ └─────>o─│&&───────│OR────A*B'*C+B*D'+F*C'*D+G*E*A'+F
    │ │ │ └──────────│&&  ┌────│OR
    │ │ │       │         │┌───│OR
    └────────────────│&&  ││
      │ └────────────│&&──┘│
      │         └─>o─│&&   │
      │                    │
      └────────────────────┘


Codebreakers and Codewriters Let's say you have some text, and you want it to send it to your friend, but you don't want anyone else to read it.  That probably means you want to encrypt it so that only you and your friend can read it.  But, there is a problem: you and your friend forgot to agree on an encryption method, so if you send them a message, they won't be able to decrypt it!

After thinking about this for a while, you decide to just send your friend the code to encrypt your message along with the message.  Your friend is very smart, so they can probably figure out how to decrypt the message by studying the encryption method.

Of course, since other people might be reading the message, you want to choose an encryption scheme that makes it as hard as possible to crack (figure out the decryption scheme).

Cops' Task

In this challenge, Cops will play the role of the writer: you will design an encryption scheme that converts strings to strings.  However, this encryption scheme must be bijective, meaning that no two strings must map to another string, and every string can be mapped to by an input.  It must take only one input—the string to be encoded.

You will then post some code that performs the encryption, and a single message encrypted with the scheme detailed by your code.

Since you are paying by the byte to send messages, your score will be the length of your code plus the length of the ciphertext.  If your answer is cracked, you will have a score of infinity.

After one week, you may reveal the text and mark your answer as Safe.  Safe answers are those that cannot be cracked.

Robbers' Task

Robbers will play either as the friend of the writer or the malicious middle man (there is no material difference, but you can role-play as either if it makes it more fun to do so).  They will take the encryption schemes and the ciphertext and attempt to figure out the encrypted message.  Once they figure out the encrypted message, they will post it in a comment. (There will not be a separate robbers' thread for this question.)

The winner will be the robber with the most cracks.

Here is an example of what a cracked solution might look like:

Jelly, 57 + 32 = 89 bytes (cracked)

“¡ḟċ⁷Ḣṡ⁵ĊnɠñḂƇLƒg⁺QfȥẒṾ⁹+=?JṚWġ%Aȧ’
O‘ḅ256b¢*21%¢ḅ¢ḃ256’Ọ

Encrypted message:

EªæBsÊ$Ê³¢?r×Q4e²?ò[Ý6

As a hex-string:

4518AAE6421973CA
9724CAB3A23F72D7
AD18855134651810
B23F1CF25BDD9036

Explanation:

O‘ḅ256b¢*21%¢ḅ¢ḃ256’Ọ
O                     convert each into codepoint
 ‘ḅ256                convert from bijective base 256 to integer
      b¢              convert from integer to base N
        *21           map each to its 21th power
           %¢         modulo N
             ḅ¢       convert to integer from base N
               ḃ256’  convert from integer to bijective base 256
                    Ọ convert each from codepoint

Where N is encoded by the string “¡ḟċ⁷Ḣṡ⁵ĊnɠñḂƇLƒg⁺QfȥẒṾ⁹+=?JṚWġ%Aȧ’, which is the number 105587021056759938494595233483151378724567978408381355454441180598980268016731.

Also, this is the RSA method with N given above and public key 21. Cracking this is equivalent to finding the two prime factors of N.


Conjugation in Real Life In @Adám's Dyalog APL Extended, the ⍢ (under) operator means conjugation:  apply one function, then a second function, then the inverse of the first. It's fun to think of real-life actions in terms of conjugation:

  A problem is transformed by g into another domain where it more
  readily solved by f , and then transformed back into the original
  domain. An example from real life is “under anesthetics”:

apply anesthetics
    perform surgery
wake up from anesthetics

Challenge

The inverse of a line g is "un" prepended to g, and vice versa. Define any line between s and its inverse, in that order, as being "under" s. For each line f in input in order:

If f and its inverse both occur, do nothing
If f is not "under" any other action, print f
If f is "under" a line g, print f + " under " + g where + is concatenation.

Input

A nonempty multiline string, or list of strings, etc., consisting of spaces and lowercase letters (you may instead use uppercase). Exactly one line will begin with "un"; and it will be the inverse of some other line. No line will be empty.

Output

Output in the same format you took input in, or as allowed by Standard I/O.

Test cases:

Input:
apply anesthetics
perform surgery
unapply anesthetics

Output:
perform surgery under apply anesthetics

Input:
unite asia
establish the silk road
ite asia

Output:
establish the silk road under unite asia

Input:
desire a book
walk to store
take the book
pay for the book
unwalk to store
read the book

Output:
desire a book
take the book under walk to store
pay for the book under walk to store
read the book

Input:
drink excessively
undrink excessively

Output:
[empty string]

Brachylog, 90 bytes

;Ṡ{hhH↰₂gB&hb~c[A,B,C]&tT;C↔↰U∧" under ",H,T;A↔↰,U|tT&hh,TgJ&hb;T↰Q∧J,Q|h}
~↰₃|↰₃
∧"un";?c

I made this while being under the impression that this could be recursive and multiple unders could be stacked. Probably not optimized. Also as this is bracylog, plumbing takes quite some bytes.

Try it online!


Keep/Drop/Increase Sequence Here is the sequence I'm talking about:

{1, 4, 5, 9, 10, 11, 16, 17, 18, 19, 25, 26, 27...}

Starting from 1, keep 1, drop the next 2, keep the next 2, drop 3, keep 3 and so on. Yes, it's on OEIS (A064801), too!

The Challenge

Given an integer n>0, find the nth term of the above sequence

Test Cases

Input -> Output
1->1
22->49
333->683
4444->8908
12345->24747

This is code golf so the shortest answer in bytes wins! Good luck!

Java (OpenJDK 8), 45 44 bytes

n->{int i=0;for(;++i<n;n-=i);return~-n+i*i;}

Try it online!

-1 byte thanks to @Nevay

After staring at this for a while, I noticed a pattern. Every time we drop n numbers, the next number in the sequence is a perfect square. Seeing this, I mentally broke the sequence into convenient chunks: [[1],[4,5],[9,10,11],...] Basically, the ith chunk starts with i*i, and iterates upwards for i elements.

To find the nth number in this sequence, we want to find first which chunk the number is in, and then which position in the chunk it occupies. We subtract our increment number i from n until n is less than i (which gives us our chunk), and then simply add n-1 to i*i to get the correct position in the chunk.

Example:

n = 8
n > 1? Yes, n = n - 1 = 7
n > 2? Yes, n = n - 2 = 5
n > 3? Yes, n = n - 3 = 2
n > 4? No, result is 4 * 4 + 2 - 1 = 17


Minimal number of banknotes to pay a bill Suppose denominations of banknotes follow the infinity Hyperinflation sequence: \$ $1, $2, $5, $10, $20, $50, $100, $200, $500, $1000, $2000, $5000, \cdots \$. How many banknotes are required, at minimum, to pay a \$$n\$ bill?
Consider Alice needs to pay \$ $992 \$ to Bob. It is possible for Alice to use 7 banknotes \$ $500, $200, $200, $50, $20, $20, $2 \$ to pay the bill, but that uses a lot of banknotes. We can see that a better solution is: Alice pays 2 banknotes (\$ $1000, $2 \$), and Bob gives her \$ $10 \$ in change. So, we only need 3 banknotes here.
Formal Definition
Banknotes follow an infinite sequence \$b_i\$:
$$ b_n=10\cdot b_{n-3} $$
with base cases
$$ b_1=1, b_2=2, b_3=5 $$
When Alice pays \$ $x \$ to Bob, Alice pays \$ a_i \$ banknotes with denominations \$b_i\$. \$ a_i \in \mathbb{Z} \$ And
$$ \sum a_ib_i=x $$
\$ a_i \$ may be negative which means Bob gives Alice these banknotes in change.
You are going to calculate:
$$ f\left(x\right)=\min_{\sum a_ib_i=x} \sum\left|a_i\right| $$
Input / Output
Input a non-negative number representing the amount of money to pay. Output the minimum number of banknotes required.
Rules

This is code-golf: Shortest codes in bytes win.
Your program should be able to handle inputs \$ 0 \le n < 100{,}000 \$ at least. Your algorithm should work for arbitrary large numbers in theory.
As this questions is only focused on integers, floating point errors are not allowed.

Testcases
Input -> Output
    0 -> 0
    1 -> 1
    2 -> 1
    3 -> 2
    4 -> 2
    5 -> 1
    6 -> 2
    7 -> 2
    8 -> 2
    9 -> 2
   10 -> 1
   11 -> 2
   12 -> 2
   13 -> 3
   14 -> 3
   15 -> 2
   16 -> 3
   17 -> 3
   18 -> 2
   19 -> 2
   20 -> 1
   40 -> 2
   41 -> 3
   42 -> 3
   43 -> 3
   44 -> 3
   45 -> 2
   46 -> 3
   47 -> 3
   48 -> 2
   49 -> 2
   50 -> 1
   90 -> 2
   91 -> 3
   92 -> 3
   93 -> 3
   94 -> 3
   95 -> 2
   96 -> 3
   97 -> 3
   98 -> 2
   99 -> 2
  100 -> 1
  980 -> 2
  981 -> 3
  982 -> 3
  983 -> 4
  984 -> 4
  985 -> 3
  986 -> 4
  987 -> 4
  988 -> 3
  989 -> 3
  990 -> 2
  991 -> 3
  992 -> 3
  993 -> 3
  994 -> 3
  995 -> 2
  996 -> 3
  997 -> 3
  998 -> 2
  999 -> 2
 1000 -> 1
 1341 -> 6
 2531 -> 5
 3301 -> 5
 4624 -> 6
 5207 -> 4
 6389 -> 6
 6628 -> 7
 6933 -> 6
 7625 -> 6
 8899 -> 4
13307 -> 7
23790 -> 5
33160 -> 7
33325 -> 8
40799 -> 5
55641 -> 7
66472 -> 8
77825 -> 6
89869 -> 6
98023 -> 5

Python 2, 87 80 68 bytes

f=lambda x:x>1and min((y%10)**6%305%3+f(y/10*x/y)for y in[x,-x])or x

Try it online!
-7 bytes thanks to @tsh, and -12 bytes thanks to @dingledooper. Thanks to everyone else for their own golf suggestions.
Instead of tearing down the banknotes in the top-down way, this solution builds up the answer from the bottom. Since the number of banknotes needed to pay \$10n\$ is exactly the same as that for \$n\$, we can tear down the banknotes from the one's digit in the following sense:

If the one's digit is 0, remove the 0 and recurse.

Otherwise, consider two ways to fulfill the one's digit:

Alice pays n%10 to Bob, and then Alice pays whatever banknotes are needed to pay floor(n/10) * 10. Recurse with floor(n/10).
Bob pays 10-n%10 to Alice, and then Alice pays whatever banknotes are needed to pay ceil(n/10) * 10. Recurse with ceil(n/10).

Then we can evaluate the two cases and take their minimum.

In the code, an infinite recursion happens if we don't special-case x=1 as well as x=0, because the ceiling of 1/10 is still 1.


Placing Dominoes On A Chequerboard How many ways can one place (unlabelled) dominoes on a square chequerboard such that the number placed horizontally is equal to the number placed vertically?

The dominoes must align with, and may not protrude, the chequerboard and may not overlap.

This is OEIS sequence A330658, 1, 1, 1, 23, 1608, 371500, 328956227, 1126022690953, ...

Challenge

Given the side length of the chequerboard, \$n\$, produce the number of ways to arrange dominoes as described above, \$a(n)\$, in as few bytes as possible in your chosen programming language. Alternatively you may use any of the sequence defaults.

You do not have to handle \$n=0\$
If you're producing a list/generator/etc. it may start either:

1, 1, 23, 1608, ... or,
1, 1, 1, 23, 1608, ...

A Worked Example, \$n=3\$

There are \$23\$ ways to place an equal number of horizontal and vertical dominoes on a three by three board. Here they are represented as 0 where no dominoes lie and labelling cells where distinct dominoes lie as positive integers:

There is one way to place zero in each direction:

0 0 0
0 0 0
0 0 0

There are twenty ways to place one in each direction:

1 1 0   1 1 0   1 1 0   1 1 2      0 0 2      2 0 0      2 1 1   0 1 1   0 1 1   0 1 1
2 0 0   0 2 0   0 0 2   0 0 2      1 1 2      2 1 1      2 0 0   2 0 0   0 2 0   0 0 2
2 0 0   0 2 0   0 0 2   0 0 0      0 0 0      0 0 0      0 0 0   2 0 0   0 2 0   0 0 2

2 0 0   0 2 0   0 0 2   0 0 0      0 0 0      0 0 0      0 0 0   2 0 0   0 2 0   0 0 2
2 0 0   0 2 0   0 0 2   0 0 2      1 1 2      2 1 1      2 0 0   2 0 0   0 2 0   0 0 2
1 1 0   1 1 0   1 1 0   1 1 2      0 0 2      2 0 0      2 1 1   0 1 1   0 1 1   0 1 1

There are two ways to place two in each direction:

1 1 2   2 1 1
3 0 2   2 0 3
3 4 4   4 4 3

There are no ways to place more than two in each direction.

\$1+20+2=23 \implies a(3)=23\$

APL (Dyalog Extended), 61 bytes

{+/∊{(∪≡⊢)¨(,2,/m)[M],.,⍉C[M←⍵⌂cmat≢C]}¨0,⍳≢C←,2,⌿⊢m←⍵⊥¨⍳,⍨⍵}

Try it online!

Finally got how to circumvent the funky inner assignment on Extended ;-)

The difference with the one below is that dfns is auto-loaded under ⌂, and a no-op is added after assignment into m.

I have a 68-byte Unicode and 60-byte Extended solution by rewriting from scratch; it is left as an exercise for the reader.

APL (Dyalog Unicode), 72 69 bytes

⎕CY'dfns'
{+/∊{(∪≡⊢)¨(,2,/m)[M],.,⍉C[M←⍵cmat≢C]}¨0,⍳≢C←,2,⌿m←⍵⊥¨⍳,⍨⍵}

Try it online!

Non-recursive brute force. This works the other way around: generate all possible horizontal/vertical domino placements, generate all possible combinations of n horizontal and n vertical placements, and count the ones that don't have any duplicated cells.

Ungolfed with comments

⎕CY'dfns'  ⍝ Load dfns library to access function "cmat"

f←{  ⍝ Main function; ⍵←1-based index n (does not handle 0)

  m←⍵⊥¨⍳,⍨⍵  ⍝ n-by-n matrix of unique integers
        ,⍨⍵  ⍝ [n n]
       ⍳     ⍝ Nested matrix having [1..n;1..n]
    ⍵⊥¨      ⍝ Compute n×i+j for each cell containing [i j]

  R←,2,/m  ⍝ Horizontal domino placements
     2,/m  ⍝ From the matrix m, pair horizontally consecutive cells
    ,      ⍝ Flatten the outermost layer to make it a nested vector
  C←,2,⌿m  ⍝ Vertical domino placements, using ⌿ instead of /

  +/(0,⍳≢R){M←⍺cmat⍵⋄+/(∪≡⊢)¨,R[M],.,⍉C[M]}¨≢R  ⍝ Count the placements
    (0,⍳≢R){                              }¨≢R  ⍝ For each ⍺←0..length(≢) of R with ⍵←R,
            M←⍺cmat⍵                        ⍝ Generate all combinations to use for R and C
                    ⋄        ,R[M],.,⍉C[M]  ⍝ Concatenate all combinations of R with all combinations of C
                     +/(∪≡⊢)¨  ⍝ Count the ones whose cell values are all unique
  +/  ⍝ Sum all the counts
}


Decompose a range in aligned blocks of size 2^n Given an arbitrary contiguous range of positive integers, find the decomposition in the minimum number of sub-ranges of size L = 2^n, with the constraint that each range must be aligned, that is the first integer i in the sub-range must satisfy i = 0 (mod L).

Background: some (especially old) netblocks aren't a simple single CIDR, that is a range in the form 192.0.2.0/24, but are a composition of several contiguous blocks, and the whois query returns explicitly the first and last ip in the block. Try yourself with whois 220.72.0.0:

[...]
IPv4 Address       : 220.72.0.0 - 220.91.255.255 (/12+/14)
[...]

Solving this problem means finding the list of valid CIDR blocks that summed up constitute this range.

The following greedy algorithm works optimally:

  Choose the larges block allowed which is aligned with the lower bound
  and does not exceed the total range. Add this range to your result set
  and remove it from the search space. Loop until the entire range is
  covered.

In the following lines I took your example and simplified it to the interesting part, i.e. take the range 72-91:

0)  Range: 72 - 91 (Size 20)

1a) Largest block size allowed @72: 8
1b) Subrange #1: 72 - 79
1c) Remaining: 80 - 91 (Size 12)

2a) Largest  block size allowed @80: 16 (exceeds size) -> 8
2b) Subrange #2: 80 - 87
2c) Remaining: 88 - 91 (Size 4)

3a) Largest  block size allowed @88: 8 (exceeds size) -> 4
3b) Subrange #3: 88 - 91
3c) Remaining: empty

Result: (72-79) (80-87) (88-91)

The structure can be seen even better, if we express the numbers in binary format.

0)  Range: 01001000, Size 10100

1a) Largest block size allowed @01001000: 1000
1b) Subrange #1: 01001000, Size 1000
1c) Remaining: 01010000, Size 1100

2a) Largest block size allowed @01010000: 10000 (exceeds size) -> 1000
2b) Subrange #2: 01010000, Size 1000
2c) Remaining: 01011000, Size 100

3a) Largest  block size allowed @01011000: 1000 (exceeds size) -> 100
3b) Subrange #3: 01011000, Size 100
3c) Remaining: empty

A note for implementation: the block size for the subrange to be chosen corresponds either to the rightmost 1 bit of the lower bound or the leftmost 1 bit of the size of the range (whichever is smaller).


True and false and true Challenge is to write a function/program which outputs a truthy or falsey value alternately each time you call it. No input.

It can start with either true or false.

Jelly, 3 bytes

®¬©

Try it online!

How it works

®¬©  Main link. No arguments.

®    Retrieve the value stored in the register.
 ¬   Negate it.
  ©  Copy the result to the register.


Calculate Knuth's up arrow notation Inspired by Expand exponentation.
Knuth's up arrow notation is used for big numbers such as Graham's number.
If we look deeper, we can see how it makes big numbers.
One arrow means exponentiation. e.g. 2↑3 equals 2^3 = 8.
Two or more arrows means repeating the instructions of n-1 arrows. e.g. 2↑↑3 equals 2↑2↑2 equals 2^(2^2)=16.
You will be given three integers, n, a, and m. n is the first number, a is the amount of arrows, and m is the second number.
Your code should output the final answer, which is the calculation of n ↑a m(↑x means there are x up-arrows, where x is an integer)
Examples
2 1 2 -> 4
2 1 3 -> 8
2 2 3 -> 16
2 3 3 -> 65536

Java 7, 121 bytes
int c(int n,int a,int m){return(int)(a<2?Math.pow(n,m):d(n,a));}double d(int n,int a){return Math.pow(n,a<2?n:d(n,a-1));}

Explanation:
int c(int n, int a, int m){         // Main method with the three integer-parameters as specified by OP's challenge
  return (int)                      // Math.pow returns a double, so we cast it to an integer
          (a < 2 ?                  // if (a == 1):
                   Math.pow(n, m)   //  Use n^m
                 :                  // else (a > 1):
                   d(n, a));        //  Use method d(n, a)
}

double d(int n, int a){             // Method d with two integer-parameters
  return Math.pow(n, a < 2          // n ^ X where
                      ? n           //  X = n    if (a == 1)
                      : d(n, a-1)); //  X = recursive call d(n, a-1)    if (a > 1)
}

// In pseudo-code:
c(n, a, m){
  if a == 1: return n^m
  if a > 1:  return d(n, a);
}
d(n, a){
  if a == 1: return n^n
  if a > 1:  return d(n, a-1);
}

Test code:
Try it here.
class M{
  static int c(int n,int a,int m){return(int)(a<2?Math.pow(n,m):d(n,a));}
  static double d(int n,int a){return Math.pow(n,a<2?n:d(n,a-1));}

  public static void main(String[] a){
    System.out.println(c(2, 1, 2));
    System.out.println(c(2, 1, 3));
    System.out.println(c(2, 2, 3));
    System.out.println(c(2, 3, 3));
  }
}

Output:
4
8
16
65536


Gerrymandering with Logic Gates The majority function is a boolean function which takes three boolean inputs and returns the most common. For instance if maj(x,y,z) is the majority function and T denotes true and F denotes false then:

maj(T,T,T) = T
maj(T,T,F) = T
maj(T,F,F) = F
maj(F,F,F) = F

This question concerns writing boolean functions as compositions of majority functions. An example of a 5-ary composition of majority functions is (x1,x2,x3,x4,x5) => maj(x1,x2,maj(x3,x4,x5)). This function returns the following output on these sample input vectors:

(T,T,F,F,F) => maj(T,T,maj(F,F,F)) = maj(T,T,F) = T
(T,F,T,T,F) => maj(T,F,maj(T,T,F)) = maj(T,F,T) = T
(T,F,T,F,F) => maj(T,F,maj(T,F,F)) = maj(T,F,F) = F
(F,F,F,T,T) => maj(F,F,maj(F,T,T)) = maj(F,F,T) = F

Task

Write a program which inputs a positive integer n and a list of length n vectors of booleans and outputs a tree of majority gates that returns true on all of the given vectors if possible.  The function may return either true or false on vectors not in the list of constraints.

The list of vectors may be input in any format you like. If you prefer, instead of inputting the vector, you may input the list of true positions in the vector. So for instance, [TTF,TFT,FTT] or [[T,T,F],[T,F,T],[F,T,T]] or [[1,2],[1,3],[2,3]] (list of true positions) are all fine.
Output can be any valid tree format. For instance, maj(maj(x1,x2,x3),x4,x5) works. You will probably want to use single numbers as stand-ins for variables, as in [[1,2,3],4,5]. Reverse polish 123m45m is also okay, for instance.
If there is no function that works, your program should generate an error or output a falsey value.
If there are multiple functions that work, your program can return any of them. The function does not need to be simplified. For instance, maj(x1,x1,x2) or x1 are equivalent.

Scoring

This is code golf: Shortest solution in bytes wins.

Test cases:

Note that there are many possible outputs for each of these cases, so you should write a checker script that converts your output to a function and check that your function returns true on each of the specified input vectors.

Input: 3, [TFF]
Output: 1 or [1,1,2] or [1,[1,2,2],[1,1,3]] or other equivalent

Input: 3, [TFF,FTF]
Output: Falsey or error (it's not possible)

Input: 3, [TTF,TFT]
Output: [1,2,3] or 1 or other equivalent

Input: 3, [TTF,TFT,FTT]
Output: [1,2,3] or [1,3,2] or other equivalent

Input: 4, [TTFF,TFTF,FFTT]
Output: Falsey or error

Input: 4, [TTTF,TTFT,TFTT,FTTT]
Output: [1, 2, 3] or [2,3,4], or many other options

Input: 5, [TTTFF,FTTFT,TFFFT]
Output: [1,[1,[1,2,5],[2,4,5]],3] or many other options

Input: 6, [TTTFFF,FTFTTF,TFFTFT]
Output: [1, 2, 4] or [1, [1, 2, 4], [2, 3, 4]] or others

Input: 5, [TTTFF,TTFTF,TTFFT,TFTTF,TFTFT,TFFTT,FTTTF,FTTFT,FTFTT,FFTTT]
Output: [[1, [1, 3, 5], 4], [1, 2, [2, 4, 5]], [2, 3, [3, 4, 5]]] or others

Input: 7, [TTTTFFF,TTTFTFF,TTTFFTF,TTTFFFT,TTFTTFF,TTFTFTF,TTFTFFT,TTFFTTF,TTFFTFT,TTFFFTT,TFTTTFF,TFTTFTF,TFTTFFT,TFTFTTF,TFTFTFT,TFTFFTT,TFFTTTF,TFFTTFT,TFFTFTT,TFFFTTT,FTTTTFF,FTTTFTF,FTTTFFT,FTTFTTF,FTTFTFT,FTTFFTT,FTFTTTF,FTFTTFT,FTFTFTT,FTFFTTT,FFTTTTF,FFTTTFT,FFTTFTT,FFTFTTT,FFFTTTT]
Output: [[[1, [1, [1, 4, 7], 6], 5], [1, [1, 3, [3, 6, 7]], [3, 5, [5, 6, 7]]], [3, 4, [4, [4, 5, 7], 6]]], [[1, [1, [1, 4, 7], 6], 5], [1, 2, [2, [2, 5, 7], 6]], [2, [2, 4, [4, 6, 7]], [4, 5, [5, 6, 7]]]], [[2, [2, [2, 4, 7], 6], 5], [2, 3, [3, [3, 5, 7], 6]], [3, [3, 4, [4, 6, 7]], [4, 5, [5, 6, 7]]]]]

JavaScript (ES6), 260 bytes

Takes input as an array of arrays of booleans. Returns a tree of 1-indexed majority gates or throws a recursion error (1) if no solution exists.

The main function f() recursively attempts to find a solution by calling the solver F() and incrementing the maximum nesting level m at each iteration.

(1) after a long time, and assuming infinite memory

f=(a,m)=>(F=(a,d,I=a[i=0].map(_=>++i),g=(a,b)=>b[1]?b.reduce((s,i)=>s+g(a,i),0)>1:a[b-1])=>I.find(i=>a.every(a=>g(a,i)))||d&&(I.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).some(b=>r=b.length==3&&F(a.map(a=>[...a,g(a,b)]),d-1,[...I,b]))&&r))(a,m)||f(a,-~m)

Demo

f=(a,m)=>(F=(a,d,I=a[i=0].map(_=>++i),g=(a,b)=>b[1]?b.reduce((s,i)=>s+g(a,i),0)>1:a[b-1])=>I.find(i=>a.every(a=>g(a,i)))||d&&(I.reduce((a,x)=>[...a,...a.map(y=>[...y,x])],[[]]).some(b=>r=b.length==3&&F(a.map(a=>[...a,g(a,b)]),d-1,[...I,b]))&&r))(a,m)||f(a,-~m)

test = a => console.log(JSON.stringify(f(a.split(',').map(s => [...s].map(c => c == 'T')))))

test('TFF')
test('TTF,TFT')
test('TTF,TFT,FTT')
test('TTTF,TTFT,TFTT,FTTT')
test('TTTFF,FTTFT,TFFFT')
test('TTTFFF,FTFTTF,TFFTFT')
test('TTTFF,TTFTF,TTFFT,TFTTF,TFTFT,TFFTT,FTTTF,FTTFT,FTFTT,FFTTT')

Example

Below is a validation table of the solution found for the last test case of the demo.

12345 | [5,[1,2,4],[3,4,[1,2,3]]]
------+-------------------------------------------------------------
TTTFF | [F,[T,T,F],[T,F,[T,T,T]]] --> [F,T,[T,F,T]] -> [F,T,T] --> T
TTFTF | [F,[T,T,T],[F,T,[T,T,F]]] --> [F,T,[F,T,T]] -> [F,T,T] --> T
TTFFT | [T,[T,T,F],[F,F,[T,T,F]]] --> [T,T,[F,F,T]] -> [T,T,F] --> T
TFTTF | [F,[T,F,T],[T,T,[T,F,T]]] --> [F,T,[T,T,T]] -> [F,T,T] --> T
TFTFT | [T,[T,F,F],[T,F,[T,F,T]]] --> [T,F,[T,F,T]] -> [T,F,T] --> T
TFFTT | [T,[T,F,T],[F,T,[T,F,F]]] --> [T,T,[F,T,F]] -> [T,T,F] --> T
FTTTF | [F,[F,T,T],[T,T,[F,T,T]]] --> [F,T,[T,T,T]] -> [F,T,T] --> T
FTTFT | [T,[F,T,F],[T,F,[F,T,T]]] --> [T,F,[T,F,T]] -> [T,F,T] --> T
FTFTT | [T,[F,T,T],[F,T,[F,T,F]]] --> [T,T,[F,T,F]] -> [T,T,F] --> T
FFTTT | [T,[F,F,T],[T,T,[F,F,T]]] --> [T,F,[T,T,F]] -> [T,F,T] --> T


A train crosses a labeled bridge Consider a bridge of length B formed by tiles labeled with the digits of the positive integers concatenated. For example, if B was 41, then it would look like this:

-----------------------------------------
12345678910111213141516171819202122232425

Now imagine a train of length T crossing the bridge. The leftmost point of the train starts at position X (1-indexed). To get a better understanding of the problem, let's make a scheme of the event, with B = 41, T = 10, X = 10. The train is drawn using equal signs (=) and lines:

         __________
         |========|
         |========|
-----------------------------------------
12345678910111213141516171819202122232425

The train can advance, at each step, by sum of the unique tiles it is located on. For example, the tiles the train stands on above are: [1, 0, 1, 1, 1, 2, 1, 3, 1, 4], the unique (deduplicated) tiles are: [1, 0, 2, 3, 4], and their sum is 10. Hence, the train can advance by 10 tiles. We should draw it again and repeat the process until the leftmost point of the train has passed the last tile:

                   __________
                   |========|
                   |========|
-----------------------------------------
12345678910111213141516171819202122232425

Sum of unique tiles: 1 + 5 + 6 + 7 + 8 + 9 = 36. The train advances by 36 tiles...

                                                       __________
                                                       |========|
                                                       |========|
-----------------------------------------
12345678910111213141516171819202122232425

The train obviously crossed the bridge completely, so we should stop now.

Since the people inside are bored, they count the tiles the train has advanced each time. In this specific case, 10 and 36. Summing everything up, the train has moved 46 before it passed the bridge.

Task

Given three positive integers, B (the bridge length), T (the train length) and X (the starting position, 1-indexed), your task is to determine how many tiles the train has moved until it crossed the bridge following the rules above.

You can assume that:

B is higher than T.
X is lower than B.
T is at least 2.
The train eventually crosses the bridge.

All our standard rules apply.
This is code-golf, so the shortest code in bytes wins!

Test cases

Input ([B, T, X]) -> Output

[41, 10, 10] -> 46
[40, 10, 10] -> 46
[30, 4, 16] -> 24
[50, 6, 11] -> 50

Another worked example for the last test case:

The bridge is of length 50, the train 6, and the starting position is 11.

          ______
          |====|
          |====|
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Unique tiles: [0, 1, 2]. Sum: 3.

             ______
             |====|
             |====|
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Unique tiles: [1, 2, 3, 4]. Sum: 10.

                       ______
                       |====|
                       |====|
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Unique tiles: [1, 7, 8, 9]. Sum: 25.

                                                ______
                                                |====|
                                                |====|
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Unique tiles: [9, 3]. Sum: 12.
                                                            ______
                                                            |====|
                                                            |====|
--------------------------------------------------
12345678910111213141516171819202122232425262728293

Train exists the bridge. Total sum: 3 + 10 + 25 + 12 = 50.

Python 2, 110 105 104 103 100 97 96 bytes

Saved five bytes thanks to Mr. Xcoder; removed unnecessary assignment, moved negation into available whitespace.
Saved a byte thanks to Mr. Xcoder; golfed [~-x:x+~-t] to [~-x:][:t].
Saved a byte; golfed ...range(1,-~b)))[:b] to ...range(b)))[1:-~b].
Saved three bytes; golfed [1:-~b][~-x:] to [:-~b][x:].
Saved three bytes; golfed [:-~b][x:] to [x:-~b].
Saved a byte thanks to Lynn; golfing the while loop to an exec statement.

b,t,x=input();S=x;exec"x+=sum(set(map(int,''.join(map(str,range(b)))[x:-~b][:t])));"*b;print-S+x

Try it online!


Tips for golfing in V What general tips do you have for golfing in V? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to V (e.g. "remove comments" is not an answer).

Since V is heavily based on vim, most of the tips for golfing vim would apply too. But there are some features in V that don't really apply to vim.

Please post one tip per answer.

Take advantage of implicit endings!

In V, every single command will be implicitly finished if you don't actually finish out the command. For example, if the program ends in insert mode, the <esc> will be filled in automatically. Usually, this doesn't make any difference. However, if you have a count before the i, you have to actually hit <esc> at the end for the text to be inserted multiple times. So you can do 2i2i for a quine, whereas in vim you would need 2i2i<esc>, which is no longer a quine.

This also applies to ex commands, and psuedo ex-commands such as compressed regexes. So where vim needs

:foo<cr>

V can do

:foo

if it's at the end of the program.

But here is where it gets really cool: The implicit ending applies several layers deep. For example, consider this command:

òçfoo/óa

This translates to:

ò           " Recursively:
 çfoo/      "   On every line matching 'foo'
      óa    "     Remove the first 'a'

Without implicit endings, the ó needs a <cr>, the ç needs a <cr>, and the ò needs another ò. But none of these are needed with implicit endings! The interpreter will fill in the needed ò, the recursive command will fill in the <cr> that ç needs, and the ç command will fill in the <cr> that ó needs. This saves us 3 bytes.


Calculate the Ultraradical What is the Ultraradical?
The ultraradical, or the Bring radical, of a real number \$a\$ is defined as the only real root of the quintic equation \$x^5+x+a=0\$.
Here we use \$\text{UR}(\cdot)\$ to denote the ultraradical function. For example, \$\text{UR}(-100010)=10\$, since \$10^5+10-100010=0\$.
Challenge
Write a full program or a function, that takes a real number as input, and returns or outputs its ultraradical.
Requirements
No standard loopholes are allowed. The results for the test cases below must be accurate to at least 6 significant digits, but in general the program should calculate the corresponding values for any valid real number inputs.
Test Cases
9 decimal places rounded towards 0 are given for reference. Explanation is added for some of the test cases.
 a                         | UR(a)
---------------------------+---------------------
             0             |   0.000 000 000        # 0
             1             |  -0.754 877 (666)      # UR(a) < 0 when a > 0
            -1             |   0.754 877 (666)      # UR(a) > 0 when a < 0
             1.414 213 562 |  -0.881 616 (566)      # UR(sqrt(2))
            -2.718 281 828 |   1.100 93(2 665)      # UR(-e)
             3.141 592 653 |  -1.147 96(5 385)      # UR(pi)
            -9.515 716 566 |   1.515 71(6 566)      # 5th root of 8, fractional parts should match
            10             |  -1.533 01(2 798)
          -100             |   2.499 20(3 570)
         1 000             |  -3.977 89(9 393)
      -100 010             |  10.000 0(00 000)      # a = (-10)^5 + (-10)
 1 073 741 888             | -64.000 0(00 000)      # a = 64^5 + 64

Winning Criteria
The shortest valid submission in every language wins.

Wolfram Language (Mathematica), 20 bytes

Root[xx^5+x+#,1]&

Try it online!

Still a built-in, but at least it isn't UltraRadical.

(the character  is displayed like |-> in Mathematica, similar to => in JS)


Extendify the ASCII Sun Write a program that takes in (via STDIN/command line) a non-negative integer N.
When N is 0, your program should print O (that's capital Oh, not zero).
When N is 1, your program should print
\|/
-O-
/|\

When N is 2 your program should print
\ | /
 \|/
--O--
 /|\
/ | \

When N is 3 your program should print
\  |  /
 \ | /
  \|/
---O---
  /|\
 / | \
/  |  \

For larger N, this pattern continues on in the same exact fashion. Each of the eight rays of the "sun" should be made of N of the appropriate -, |, /, or \ characters.
Details

Instead of a program, you may write a function that takes an integer. The function should print the sun design normally or return it as a string.

You must either

have no trailing spaces at all, or
only have enough trailing spaces so the pattern is a perfect (2N+1)*(2N+1) rectangle.

The output for any or all N may optionally have a trailing newline.

Scoring
The shortest code in bytes wins.

C: 116 102 99 95 92 90

s(n){for(int c=-n,r=c;r<=n;c++)putchar(c>n?c=-c,r++,10:c?r?c-r?c+r?32:47:92:45:r?124:79);}

I think that I am getting fairly close to a minimal solution using this approach, but I can't stop feeling that there is a much better approach in C. Ungolfed:

void s(int n) {
  for(
    int c = -n, r = c;
    r <= n;
    c++
  )
    putchar(
      c > n
        ? c = -c, r++, '\n'
        : c
          ? r
            ? c - r
              ? c + r
                ? ' '
                : '/'
              : '\\'
            : '-'
          : r
            ? '|'
            : 'O'
    );
}


Letters associated with prime numbers If we assign each letter a respective integer, starting from 1, then a is 1, b is 2, c is 3, and so on. After z, the letters loop back around, but with a in front (aa, ab, ac). It then goes to ba, bb, bc... After this is completed, as you may have figured, another letter is added (aaa, aab, aac).  "Prime letters" would be letters that are associated with a prime number. b would be the first prime letter, followed by c, e, g, et cetera.

The Challenge

Given an input n, find the nth "prime letter."

Examples

Input:

1

Output:

b

Input:

4

Output:

g

Input:

123

Output:

za

Scoring Criteria

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

Python 3,262 236 209 196 179 114 93 92  97 bytes

def f(n):
 m=k=1;s=''
 while n:m*=k*k;k+=1;n-=m%k
 while k:s=chr(~-k%26+97)+s;k=~-k//26
 return s

Try it online!

Fixed a bug mentioned by @benrg about getting a wrong output for the input 123.

Thanks to:
- @AdmBorkBork for help me getting started and save a few bytes
- @Sriotchilism O'Zaic for saving me 6 bytes
- @mypetlion for saving me 65 bytes and bringing me under 150 bytes :)
- @dingledooper for saving me 21 bytes and bringing me under 100 bytes :D
- @Jitse for saving 1 byte

98 bytes

f=lambda n,i=1,p=1:n and-~f(n-p%i,i+1,p*i*i)
g=lambda n,s='':n and g(~-n//26,chr(~-n%26+97)+s)or s

Try it online!


Help Beth escape the desert While similar to the other water-carrying puzzle, the unique aspects of this challenge make it entirely different.

Beth is located at an oasis in the middle of a desert. There is plenty of water in the lake, but unfortunately there are only X buckets, each of which has a capacity of Y liters of water.

Beth can carry 2 buckets in her hands, but to survive, she must drink exactly 1 liter after each kilometer she travels. She can also leave some buckets half-way (water does not evaporate).

The challenge

Figure out the formula and write the shortest solution that will work for positive integer values of X and Y and calculate the maximum distance Beth can travel from the oasis. Moving water between the buckets is permitted.

Example

X=3, Y=5

Beth walks 3km with two full buckets. Leaves 1 full bucket behind. The other bucket now has 2L left, which is enough to get home (Beth can have the last drink from the oasis).
She leaves with another two full buckets, arriving with 1 full, plus 2 litres in the other (12L total: 5 + 5 + 2).
Beth can advance to 6KM point and leave bucket with 4L of water in it.
She returns to the 3KM point. She now has exactly 2L to get back to the oasis.
Fill up buckets and travel to 6KM point. She now has 8L of water.
Continue all the way to 15KM point.

Answer is: 15

Input / Output

You can define X/Y directly in the code or read from input. Result could be placed in variable or output, whichever is shortest.

JavaScript (ES6), 25 bytes

x=>y=>((x<3?x:3)+x)*y/2+1
x=>y=>(x<3?x+x:x+3)*y/2+1
x=>y=>(x<3?x:(x+3)/2)*y+1
x=>y=>(x<3?x:x/2+1.5)*y+1

All of these compute the same value; I can't seem to come up with a shorter formulation.

When x is less than 3, you take as much water as you can and walk as far as you can, which is simply x*y+1.

When x is at least 3, you have to start building caches.

From the oasis, you can leave a full bucket at a distance y/2 and return to the oasis. You need 2 buckets to do this, but this is not useful if you only have 2 buckets because you want to be able to fill up 2 buckets when you return to the oasis.

From the oasis, with a bucket at a distance y/2, you can leave a full bucket at a distance y and return to the oasis. You need 3 buckets to do this.

From the oasis, with full buckets at both y and y/2, you can leave a full bucket at a distance 3y/2 and return to the oasis. You need 4 buckets to do this. You then have to leave a full bucket at a distance of y/2 and return to the oasis.

Eventually you can end up with a full bucket at (x-1)y/2. (You cannot leave a full bucket at xy/2 because you would not be able to get back to the oasis, as the round trip is xy, the total capacity of the buckets.)

Using your remaining buckets, you can leave full buckets at (x-3)y/2 ... y or y/2. At this point you simply walk as far as you can, picking up your full buckets as you go. When you reach (x-1)y/2 you still have two full buckets left, allowing you to reach (x+3)y/2.

The extra 1 comes from the quirk in the rules allowing you to walk your last mile without having any water. Although the example shows that you can leave the buckets slightly further away than described above, this actually does not help you walk any further, as you either have to leave less water or drink the water from the bucket as you reach it before you can move on.


Counting N-bit integer multiplication overflows Given a positive integer N, output the number of pairs of integers 0 <= a <= b < 2**N such that a*b >= 2**N.
Rules

You may assume that N is less than or equal to the maximum bit width for integers in your language (e.g. for C, N will not exceed 32 or 64, depending on the architecture of the machine). If your language is capable of handling arbitrary-width integers, then there is no upper bound on N.

Test Cases
1 0
2 3
3 19
4 96
5 437
6 1876
7 7804
8 31904
9 129170
10 520135
11 2088143
12 8369175
13 33512744
14 134128704
15 536681553
16 2147082274


Return the flipped version of a number When a number is shown on a calculator, it's possible to consider what various transformations of that number would look like. For example, on a seven-segment display, 2 is shown like this:

And when flipped horizontally it looks like this:

As such, the mirror image of 2 is 5.

The task in this challenge is to take a single-digit number, and return the number that's its mirror image (if possible). If its mirror image does not look like a number, return the number rotated 180 degrees (if possible). If neither of these are the case, return -1.

Here's the full list of inputs and outputs your program needs to handle:

Input   Output
0       0
1       -1
2       5
3       -1
4       -1
5       2
6       9
7       -1
8       8
9       6

As a code-golf challenge, the shortest code wins!

Haskell - 43 31

43 characters without anything fancy.
f 0=0
f 8=8
f 2=5
f 5=2
f 6=9
f 9=6
f _= -1

Got it down to 31 characters by making it a partial function.
f=([0,-1,5,-1,-1,2,9,-1,8,6]!!)


How to find the item in a list whose f(item) is the smallest? I have a list, l and a function f. f is not strictly increasing or decreasing. How can I find the item in the list whose f(item) is the smallest? For example, let's say the list is:

l = [1, 2, 3, 4]

and list(f(x)for x in l) is:

[2, 9, 0, 3]

f(3) is smaller than f of any of the other ones, so it should print "3". What's the shortest way to do this? I initially tried:

min(f(x) for x in l)

But this gives 0, not 3. If I was shooting for readability, not brevity, I would do:

index = 0
smallest = f(l[0])
for i in range(len(l)):
    value = f(l[i])
    if value < smallest:
        smallest = value
        index = i

This is fine, but horrendous for code-golf. Even if it was golfed

i,s=0,f(l[0])
for x in range(len(l)):
 v=f(l[x])
 if v<s:s,i=v,x

This is a bad solution. The shortest solution I can think of is:

g=[f(x)for x in l];print(l[g.index(min(g))])

(44 bytes) How can I golf this down further?

Use key property of min

As @vaultah said, use min(l,key=f). min(l,key=f) takes the minimum of f(i) for i in l.

It is also possible to apply this to max, and sorted. For example, max(l,key=f) is the maximum of f(i) for i in l. For sorted, the usage would be: sorted(l,key=f).


Equality up to Swapping inputs / outputs
your program/function/routine/... will be a predicate on two tuple sequences; call it relation ≡. for the purpose of simplicity we use natural numbers:

the input will be two list of pairs of numbers from ℕ (including 0); call them Xs and Ys
the output will be a "truthy" value

specification
≡ checks the sequences for equality up to permuting elements where the first elements u and u' don't match.
in other words ≡ compares lists with (u,v)s in it for equality. but it doesn't completely care about the order of elements (u,v)s. elements can be permuted by swapping; swaps of (u,v) and (u',v') are only allowed if u ≠ u'.
formally: write Xs ≡ Ys iff ≡ holds for Xs and Ys as inputs (the predicate is an equivalence relation hence symmetric):

[] ≡ []
if rest ≡ rest then [(u,v),*rest] ≡ [(u,v),*rest] (for any u, v)
if u ≠ u' and [(u,v),(u',v'),*rest] ≡ Ys then [(u',v'),(u,v),*rest] Ys

examples
[] [] → 1
[] [(0,1)] → 0
[(0,1)] [(0,1)] → 1
[(0,1)] [(1,0)] → 0
[(1,0)] [(1,0)] → 1
[(1,2),(1,3)] [(1,2),(1,3)] → 1
[(1,2),(1,3)] [(1,3),(1,2)] → 0
[(1,2),(1,3)] [(1,2),(1,3),(0,0)] → 0
[(0,1),(1,2),(2,3)] [(2,3),(1,2),(0,1)] → 1
[(1,1),(1,2),(2,3)] [(2,3),(1,2),(0,1)] → 0
[(1,2),(0,2),(2,3)] [(2,3),(1,2),(0,1)] → 0
[(1,2),(2,3),(0,2)] [(2,3),(1,2),(0,1)] → 0
[(1,1),(1,2),(1,3)] [(1,1),(1,2),(1,3)] → 1
[(3,1),(1,2),(1,3)] [(1,2),(1,3),(3,1)] → 1
[(3,1),(1,2),(1,3)] [(1,3),(1,2),(3,1)] → 0
[(2,1),(3,1),(1,1),(4,1)] [(3,1),(4,1),(1,1)] → 0
[(2,1),(4,1),(3,1),(1,1)] [(3,1),(1,1),(2,1),(4,1)] → 1
[(2,1),(3,1),(1,1),(4,1)] [(3,1),(2,1),(4,1),(1,1)] → 1

(keep in mind the relation is symmetric)

Husk, 4 bytes
¤=Ö←

Try it online! (header runs function on all test cases)
¤       # combin: applies one function to two values and combines the results
 =      # combining function: are they equal?
  Ö←    # function to apply: sort on first element
        # values (implicit): inputs


Let's play some Reaper - Closed for Submissions NOTE: The winner of this competition is Jack!!!. No more submissions will be accepted.

Here is the chat room for this king-of-the-hill challenge. This is my first one so I'm open to suggestions!

Reaper is a game concept developed by the Art of Problem Solving which involves patience and greed. After modifying the game to fit a KOTH style contest (Thanks to @NathanMerrill and @dzaima for your suggestions and improvements), here is the challenge.

The game works as the following: we have a value known as the Reap that multiplies by a given constant every tick. After each tick, each bot has the option of "reaping", which means adding the current value of Reap to one's score, and reducing Reap down to 1.

However, there's a fixed number of ticks that a bot must wait in between "reaps", and a fixed number of points necessary to win the game.

Simple enough? Here are your inputs:

I/O

You are to write a function in Python 3 that takes 3 inputs. The first is self, used for referencing class objects (shown later). The second is the Reap, the current value of the Reap that you would earn if you were to "reap". The third is prevReap, a list of the bots that reaped during the previous tick.

Other objects you can access in your function:

self.obj: An object for your use to store information between ticks.
self.mult: The multiplier that Reap is multiplied by each tick
self.win: The score you need to win
self.points: Your current set of points
self.waittime: The amount of ticks that you must wait between reaps during the game
self.time: The number of ticks since your last reap
self.lenBots: The number of bots (including you) in the game.
self.getRandom(): Use to produce a random number between 0 and 1.

You MUST not edit any of the contents of these objects, except for self.obj.

You must output 1 to reap, and anything else (or nothing) to not reap. Note that if you reap when you haven't waited enough ticks, I'll ignore the fact that you have chosen to reap.

Rules

The parameters I will be using are winning_score=10000, multiplier=1.6-(1.2/(1+sqrt(x))), waittime = floor(1.5*x) where x is the number of bots in the KOTH.

The game ends when a player (or multiple) reach the winning score.
When multiple bots ask to reap at once, priority is given to the bots who have waited longer(in case of ties, the bots that have waited the max time all are allowed to reap and gain the points in the Reap)
Your bot must take no more than 100 ms on average across 5 ticks.
If you want to import libraries, ask! I'll try to add any libraries that I can run on my desktop version of Python (math is already imported: feel free to use it)
All of the standard loopholes for KoTHs, such as duplicate bots, 1-up bots, etc, are similarly banned.
Any bots that use any sort of randomness must use the getRandom function I've provided.

You can find the controller in the TIO link below. To use it, add the name of your function to BotList as a string, and then add the function to the code. Modify multiplier to change what the Reap is multiplied by each tick, modify winning_score to change what score is necessary to end the game, and modify waittime to change the number of ticks to wait between reaps.

For your convenience, here are some sample (and rather silly) bots. Submitting bots similar to these will not be permitted. However, they demonstrate how the controller works.

def Greedybot(self,Reap, prevReap):
    return 1
def Randombot(self,Reap, prevReap):
    if self.obj == None:
        self.obj=[]
    self.obj.append(prevReap)
    if self.getRandom()>0.5:
        return 1

For those interested, here is the Controller with the 15 submissions built into it: Try it Online

FINAL RESULTS

WOO THEY ARE FINALLY HERE! Check the TIO Link above to see what code I used to generate the final standings. The results are not terribly interesting. Over the 1000 runs I did with different random seeds, the results were

1000 wins - Jack
0 wins - everyone else

Congratulations to the Bounty winner Jack!! (aka @Renzeee)

Sniper

A bot fueled by spite. Keeps track of opponent's cooldowns and scores. Attempts to keep others from winning. Pretty much never actually wins, but makes the game frustrating to play for others.

EDIT:

If reaping would cause it to win, reap.
If no one is >= 70% of the winning score:

If everyone else is on their cooldown, wait until the last possible moment to reap.
If anyone else would win by reaping the current value, and they are active now or would be active next turn, reap.
If at least half of the other users are on their cooldown, attempt to reap. This makes it difficult to target specific opponents, and so was removed.
Otherwise, reap 25% of the time (essentially to guarantee that this bot does reap SOMETIMES, just in case something weird happens, like everyone is waiting several turns).

If someone IS >= 70% of the winning score:

If Sniper can win a tiebreaker, and next round would be above the average Reap value for the highest scoring opponent, reap
If highest scoring opponent will leave their cooldown next turn, reap.

def Sniper(self, Reap, prevReap):
    # initialize opponents array
    if not hasattr(self.obj, "opponents"):
        self.obj.opponents = {}

    # initialize previous Reap value
    if not hasattr(self.obj, "lastReap"):
        self.obj.lastReap = 0

    # increment all stored wait times to see who will be "active" this turn
    for opponent in self.obj.opponents:
        self.obj.opponents[opponent]["time"] += 1

    # update opponents array
    for opponent in prevReap:
        # don't track yourself, since you're not an opponent
        if opponent != "Sniper":
            # initialize opponent
            if opponent not in self.obj.opponents:
                self.obj.opponents[opponent] = {"time": 0, "points": 0, "num_reaps": 0, "avg": 0}
            self.obj.opponents[opponent]["time"] = 0
            self.obj.opponents[opponent]["points"] += self.obj.lastReap
            self.obj.opponents[opponent]["num_reaps"] += 1
            self.obj.opponents[opponent]["avg"] = self.obj.opponents[opponent]["points"] / self.obj.opponents[opponent]["num_reaps"]

    # done "assigning" points for last round, update lastReap
    self.obj.lastReap = Reap

    # get current 1st place(s) (excluding yourself)
    winner = "" if len(self.obj.opponents) == 0 else max(self.obj.opponents, key=lambda opponent:self.obj.opponents[opponent]["points"])

    # you are ready now
    if self.time >= self.waittime:
        # current Reap is sufficient for you to win
        if self.points + Reap >= self.win:
            return 1

        if (
                # a 1st place exists
                winner != ''
                # if current 1st place is close to winning
                and self.obj.opponents[winner]["points"] / self.win >= .7
        ):
            if (
                    # next round's Reap value will be above opponent's average Reap
                    (Reap * self.mult >= self.obj.opponents[winner]["avg"])
                    # we have been waiting at least as long as our opponent (tiebreaker)
                    and self.time >= self.obj.opponents[winner]["time"]
            ):
                return 1

                # current 1st place opponent will be active next round
            if self.obj.opponents[winner]["time"] + 1 >= self.waittime:
                return 1

        else:
            if (
                    # everyone is waiting for their cooldown
                    all(values["time"] < self.waittime for key, values in self.obj.opponents.items())
                    # and we're tracking ALL opponents
                    and len(self.obj.opponents) == self.lenBots - 1
                    # at least one person will be ready next turn
                    and any(values["time"] + 1 >= self.waittime for key, values in self.obj.opponents.items())
            ):
                return 1

            if (
                    # opponent will be active next round
                    any( (values["time"] + 1 >= self.waittime)
                         # current Reap value would allow opponent to win
                         and (values["points"] + Reap >= self.win) for key, values in self.obj.opponents.items())
            ):
                return 1

            if (
                    # a 1st place exists
                    winner != ''
                    # current 1st place opponent will be active next round
                    and (self.obj.opponents[winner]["time"] + 1 >= self.waittime)
                    # next round's Reap value will be above their average Reap
                    and (Reap * self.mult >= self.obj.opponents[winner]["avg"])

            ):
                return 1

            # # at least half of opponents are waiting for their cooldown
            # if sum(values["time"] < self.waittime for key, values in self.obj.opponents.items()) >= (self.lenBots - 1) / 2:
            #     return 1

            # 25% of the time
            if self.getRandom() <= .25:
                return 1

    # default return: do not snipe
    return 0

Bored

Just for fun, this bot was brought along by a friend and doesn't actually want to be here. They roll a d16 until they get a number in 1-9, then they attempt to reap anytime a number contains the chosen digit. (Going to look for a d10 would disrupt the game, which is rude, and 0 is just too easy!)

def Bored(self, Reap, prevReap):
    # if this is the first round, determine your fav number
    if not hasattr(self.obj, "fav_int"):
        r = 0

        while r == 0:
            # 4 bits are required to code 1-9 (0b1001)
            for i in range(0, 4):
                # flip a coin. Puts a 1 in this bit place 50% of the time
                if self.getRandom() >= .50:
                    r += 2**i
            # if your random bit assigning has produced a number outside the range 1-9, try again
            if not (0 < r < 10):
                r = 0

        self.obj.fav_int = r

    # you are ready now
    if self.time >= self.waittime:
        # current Reap is sufficient for you to win
        if self.points + Reap >= self.win:
            return 1
        # do you like this value?
        if str(self.obj.fav_int) in str(Reap):
            return 1
        # do you like your wait time?
        if self.time % int(self.obj.fav_int) == 0:
            return 1

    # default return: do not reap
    return 0


Print an ascii spiral in O(log n) memory You may write a program or function that receives an odd, positive integer n, where n >= 3, as either a function argument, command line arguments, or on STDIN (or equivalent for your system), and prints to STDOUT (or system equivalent) an ASCII spiral that spins inward clockwise where the top edge is exactly n characters long. The first right edge should be n+1 characters long, obviously. For instance,

Input:

11

Output:

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

The catches:

Your program must use no more than O(log n) memory.
Your program may only print the characters * (ASCII 42),  (ASCII 32), <CR> (ASCII 13) and <LF> (ASCII 10).
Your program must print the string, not return it from the function.
The Big-O restriction is only on memory, there are no restrictions on runtime.
A trailing newline is optional.
If your language does not support large integer types, you do not have to support higher than what it does support, but you may not use this as a trick to say "oh, well, I don't have to support above X so I can just make a huge array the maximum size every time"

Standard loopholes are banned, as usual.

C, 125 121 bytes
Golfed version This has no variable k. The variable k is used in the ungolfed version just to aid readability. Also for loop conditionals are rearranged and one set of unnecessary {} removed. Another set of {} can be removed by migrating puts("") inside the brackets of the j loop in the initialization position, but this would mean a newline at the beginning of the output, so I haven't done it.
f(n){int i,j;n/=2;for(i=-n-2;i++-n-1;){if(i){for(j=-n-1;j++-n;)putchar(32+10*(n+(j*j<i*i?i:j+(i!=j|i>0))&1));puts("");}}}

Prints an n wide by n+1 high spiral like the example.
Explanation
Basically I halve the value of n (rounding down) and run two loops: an outer one i from -n/2-1 to n/2+1 to print the rows (i=0 is suppressed so we get n+1 rows) and an inner one j from (-n/2 to n/2 to print the characters.) We use expression & 1 to print stripes, and the condition j*j<i*i to decide whether to print vertical or horizontal stripes (vertical at the sides where absolute magnitude of i is larger, and horizontal at the top and bottom.) An adjustment +n is required to help with the correct termination depending on whether n/2 is odd or even.
k is normally 1, and provides an adjustment for the fact that the absolute values of i range from 1 to n/2+1 while the absolute values of j range from 0 to n/2. If k was always 1 we would get concentric rectangles, but it is inverted to 0 when i==j&i<=0 so that a diagonal row of cells is inverted, producing the spiral.
ungolfed in test program
f(n){
  int i,j,k;
  n/=2;
  for(i=-n-1;i<=n+1;i++){
    if(i){
       for(j=-n;j<=n;j++){
           k=i!=j|i>0;
           putchar(32+10*(n+(j*j<i*i?i:k+j)&1));
         }
       puts("");
     }
  }
}

int m;
main(){
  scanf("%d",&m);
  f(m);
}

Output
11
***********
          *
********* *
*       * *
* ***** * *
* *   * * *
* * * * * *
* * *** * *
* *     * *
* ******* *
*         *
***********

9
*********
        *
******* *
*     * *
* *** * *
* * * * *
* *   * *
* ***** *
*       *
*********

3
***
  *
* *
***

1
*
*


How to reduce EXE size of x86 ASM compiled with FASM? As an exercise, I've created a simple solution for this challenge, in x86 Assembly Language. I'm running this with FASM on Windows. Here's my source code:

format PE console
entry start

include 'WIN32A.inc'

section '.text' code executable
start:
    push    char            ; Start at 'A'
    call    [printf]        ; Print the current letter 4 times
    call    [printf]
    call    [printf]
    call    [printf]
    inc     [char]          ; Increment the letter
    cmp     [char], 'Z'     ; Compare to 'Z'
    jle     start           ; char <= 'Z' --> goto start

section 'r.data' data readable writeable
    char    db  'A', 10, 0  ; Stores the current letter

section '.idata' data readable import
    library  msvcrt,   'msvcrt.dll'
    import   msvcrt, printf, 'printf'

When I compile this, I get an executable larger than I expected. Here's a hexdump:

https://pastebin.com/W5sUTvTe

I notice there's a lot of empty space between the code section and the data and library import sections, as well as a message saying "This program cannot be run in DOS mode" embedded in the code. How can I assemble my source code to a small file, suitable for Code Golf?

As a side note, suggestions for better ways to print to stdout without importing msvcrt and calling printf are welcome.

Quite a bit general tip, but

Use COM file format instead of PE EXE.

PE EXE has a few flaws making the format pretty much useless in code-golf. First one is the image aligning (Windows won't run the EXE file if it's not aligned properly), and the second one is the header size. There are a few factors that aren't this important (dividing the executable into sections).

Advantages of using COM file format (that is pretty much equivalent to flat binary) are:

Zero header code, file isn't divided into sections
No image aligning (so the image size might not be divisible by a strictly defined power of two, but it has to be smaller than 65K. It doesn't change much though, because if your submission is larger than 65K, you're doing something wrong).
You can't use external libraries - this is actually a plus, because you without doubt have other way to perform I/O. That's where BIOS interrupts come handy.
You have direct control over the memory and devices linked up to the system, therefore there is no paging, no access violations, no memory protection, no concurrency, so on and so forth. These features make it easier to golf really creative programs.

I've revised your code to work as flat binary. It's dead simple:

ORG 100H

MOV DX, P
MOV AH, 9

L:
    INT 21H
    INT 21H
    INT 21H
    INT 21H

    INC BYTE [P]
    CMP BYTE [P], 'Z'
    JLE L

MOV AX, 4C00h
INT 21h

P DB "A", 10, "$"

The output binary is just 32 bytes big. I believe, it's possible to reduce the size even further, but this is just a starting point.

Assemble with nasm -fbin file.asm -o file.com. Note, this example has been made for NASM, but you can translate it freely to FASM, and it will work flawlessly.


Where to point a low-orbit ion cannon (asking for a friend) Challenge

Premise

Bob lost1 Alice's precious grand piano. Big mistake. Alice has now stolen Bob's low-orbit ion cannon.

Alice refuses to just make up with Bob, so let's help her give him a light tap on the roof. Suppose that from the top Bob's house looks like a lattice polygon, where all points have integer coordinates...

1. So he says.

Task

Input: an \$n\times2\$ matrix of integers (where \$3\leq n\leq16\$) representing the coordinates of the points of an \$n\$-gon, given in the order in which you would join them up. To be absolutely clear, the first and second values in each of the \$n\$ rows are respectively an \$x\$- and a \$y\$-coordinate.

If it would be far more natural to take something other than a 2D matrix in your language or it's impossible to take one, you can use something else. Should this happen, please clearly state what you're doing.
\$x\$-coordinates or \$y\$-coordinates may be negative, zero or positive.
The polygon formed by joining up the points in the given order may be convex or concave.
There's no need to consider degenerate polygons.
No input polygon will be self-intersecting, thank goodness.

Output: two numbers of any numeric type, respectively representing the \$x\$-coordinate and \$y\$-coordinate of a point within the polygon.

No, your numbers needn't be integers.
Your output needn't be consistent for any single input. You're allowed to generate an output in any valid way that shortens your code.
Corners and edge points are forbidden. Sorry.

Example 1

Input:

0 0
3 0
3 4

Possible output: 1 1

Example 2

Input:

-3 -1
0 1
-1 -1
-1 0

Possible output: -0.31416 0.42

Remarks

This is code-golf, so fewest bytes wins.
The random tag is here only to be on the safe side. I expect that not every answer will use randomness.
Standard rules, I/O rules and loophole rules apply.
If possible, link an online demo of your code.
Please explain your code.

Python 3.8, 116 110 bytes

lambda p:[x:=min(p)[0]+.1,sum(sorted(b+(d-b)*(x-a)/(c-a)for(a,b),(c,d)in zip(p,p[-1:]+p)if(a<x)^(c<x))[:2])/2]

Try it online!
Input: A list of points, each is a tuple of 2 integers.
Output: A point as a list of 2 numbers.
Approach
Draw a vertical line through the polygon. Select the first 2 points where the line intersects with the polygon edges. Any point between those 2 points must be inside the polygon.

Note that the line should be chosen such that it doesn't intersect any polygon vertex.
Code explanation
The x-coordinate of the line is selected as the minimum x of all vertices, plus a small amount (0.1 is used in this case):
x:=min(p)[0]+.1

This ensures that the line intersects the polygon, and that it doesn't pass through any vertex (since vertices all have integer coordinates).
For each edge through vertices \$(a,b)\$ and \$(c,d)\$, the line intersects the edge if \$a<x<c\$ or \$a>x>c\$. Golfed using xor trick:
if (a<x)^(b<x)

The y-coordinate of each intersection is calculated using the following formula:
$$\frac{y-b}{x-a}=\frac{d-b}{c-a}$$
or b+(d-b)*(x-a)/(c-a)
The y-coordinate of the final point is calculated as the average of the smallest 2 y-coordinates.


Partition it into as few disjoint contiguous increasing subsequences as possible Specification

This challenge is simple to state: your input is a non-empty array of nonnegative integers, and your task is to partition it into as few substrings as possible, such that each substring is a permutation of a consecutive integer range.
More formally, if the input array is A, then the output is minimum number of partition of A into B(s):

Each arrays B form a partition of A into substrings. Inductively, this means that either B is the singleton array containing 1 element from A, or the elements of B is a subsequence of A, which when sorted are contiguous like x,x+1,x+2,...
The number of arrays B is minimal.

Example

Consider the input array A = [1,2,3,4,3,5].
Output is 2
One possible minimal partitions are B = [1,2,3],[4,3,5]. That's the only partition to 2 substrings.

{4,3,5} in sorted order is {3,4,5} which is contiguous.

Input

An array of integers A.

Output

A number, indicate the smallest number of parts A can be splitted to.

Winning criteria

Your submissions will be scored in bytes, with less bytes being better.

Kotlin, 91 bytes

fold(mutableListOf<Int>()){r,i->r.indexOfFirst{it<i}.let{if(it<0)r+=i else r[it]=i
r}}.size

Beautified

fold(mutableListOf<Int>()) {r,i->
    r.indexOfFirst { it<i }.let {
        if (it<0) r+=i else r[it]=i
        r
    }
}.size

Test

fun MutableList<Int>.f() =
fold(mutableListOf<Int>()){r,i->r.indexOfFirst{it<i}.let{if(it<0)r+=i else r[it]=i
r}}.size

fun main(args: Array<String>) {
    val i = mutableListOf(1,2,3,4,3,5)
    println(i.f())
}

TIO

TryItOnline


Implement range function without using numbers in code You have to create a function range, such that it takes two (integer) arguments a and b (a < b) and returns all the numbers in between them. So:

range(5, 10) // should output 6, 7, 8, 9
range(-5, 2) // should output -4, -3, -2, -1, 0, 1
range(5, 0) // can throw an error/empty/null/undefined/whatever (a is not < b)
// bonus points for non integer handling
range(0.5, 4.5) // 1.5, 2.5, 3.5
range(0.5, 4) // range doesn't make sense, error/null/empty
range(5, 5) // etc. should return empty/null/undefined/whatever

Your code must not use any numbers at all, but you can use arithmetic operators. If your language has a range function in-built, you cannot use that as well.

Shortest code wins.

Javascript (49)(45)
As feersum said, I do not know why anyone would have to use numbers here.
f=(a,b)=>{for(c=[];a<b;c.push(a++));return c}

Old:
f=(a,b)=>{c=[];for(;a<b;a++){c.push(a);}return c}

I am sure it can be golfed down further=)