text:
Fill the histogram with water
Imagine a histogram. Pour an infinite amount of water on to it. Then stop. How much water does the histogram hold?
Let's say we have a histogram with columns of these heights:
1 3 2 1 4 1 3
That would look like this:
    #
 #  # #
 ## # #
#######
1321413

If we pour an infinite amount of water on this histogram, some of those holes will fill up, and we'll end up with this:
    #
 #..#.#
 ##.#.#
#######
1321413

Apparently, this histogram can hold 5 slots of water.
Your task, should you choose to accept it, is to calculate the number of slots of water that a given histogram can hold. You may accept the input as a list, string, array, matrix, bitmap or whatever format you like. The output should be nothing but a single integer, in any format you like.
The input will only contain column heights between 1 and 1000, and the input size is between 1 and 1000 columns.
Test cases:
1 -> 0
2 1 2 -> 1
1 3 2 1 4 1 3 -> 5
1 3 5 7 6 4 2 1 -> 0
7 1 1 1 1 1 1 1 1 1 7 -> 54
2 6 3 5 2 8 1 4 2 2 5 3 5 7 4 1 -> 35

If you're looking for possible ways to solve this problem, here's four.
This is code golf, so the least bytes of source code wins.

Unfortunately we've had this challenge already: Find the capacity of 2D printed objects

Ah, okey. Didn't find it while searching. We'll just mark this as a dupe then.

Retina, 16 bytes
(?<=# *) (?= *#)

Try it online! Link includes test case. Works by counting the spaces which are surrounded by #s.

How did you answer this 14 minute ago if this question was closed 22 minutes ago? :o

Python 2, 68 bytes
lambda l:sum(min(max(l[:i+1]),max(l[i:]))-v for i,v in enumerate(l))

Try it online!

How did you answer this 1 minute ago if this question was closed 22 minutes ago? :o


text:
Ordered sequence of ascending integer combinations
Write a program or function to produce the following output in the correct order.
EDIT: The symbols are not mathematical! The numbers just represent unique data and the + and - could be any two arbitrary symbols.
Take an non-negative integer input n. The first line is always -, even for n=0.

If the current line is -, the next line is 1+2+ ... (n-1)+n-

n=4: - => 1+2+3+4-

If the last integer is equal to n, remove all integers from the end that are immediately followed by a -, then change the last + to a -

n=4: 1-2+3-4- => 1-2-
EDIT: When the string is full (all the integers from 1 to n are included), remove all integers from the end that are followed by a -, until you reach an integer followed by a +. Leave that integer but change its following + to a -
Using the same example as immediately above (which does not follow -), remove 4-, remove 3-, change 2+ to 2-. 1- doesn't change since we stop at 2. Result:  1-2-

If the last integer is less than n, append the remaining integers with a + after each one, except the final integer which should have a - appended

n=4: 1+2- => 1+2-3+4-
EDIT: If the current string is not full (does not contain all the integers from 1 to n), add each integer not already included in ascending order up to n-1 with a + after each one, and then append the last integer n followed by a -
If the current line is 1-, append 2+, append 3+ which is n-1 if n=4. Then append 4-. Result: 1-2+3+4-

If the current line contains all the integers and each one is immediately followed by a -, exit the code

n=4: 1-2-3-4- => END

There must be no leading or trailing spaces on any line. There must be a line break between each line. There may or may not be a line break on the last line.
EDIT: You should test your code up to at least n=10 (over 1000 lines of output so I can't include it here). Any number that doesn't cause your code to run out of resources should (eventually!) produce the correct output but you don't have to wait for the universe to end!
This is code-golf, so shortest code in bytes wins!
Input n=0:
-

Input n=1:
-
1-

Input n=2:
-
1+2-
1-
1-2-

Input n=4:
-
1+2+3+4-
1+2+3-
1+2+3-4-
1+2-
1+2-3+4-
1+2-3-
1+2-3-4-
1-
1-2+3+4-
1-2+3-
1-2+3-4-
1-2-
1-2-3+4-
1-2-3-
1-2-3-4-

Haskell, 89 bytes
g takes an integer and returns a string.
g n=unlines$max"-".foldr(\(s,i)r->id=<<[show i++s:r|s:r>"+"])""<$>mapM(mapM(,)"+-")[1..n]

Try it online!
How it works

Loosely speaking, the algorithm constructs a list of all 2^n combinations 1+2+...n+, 1+2+...n- up to 1-2-...n-, strips away the final +-terminated numbers, and if the result is empty, replaces it with -.
mapM(,)"+-" is a shorter way (using the function monad) to write \i->[('+',i),('-',i)].
mapM(mapM(,)"+-")[1..n] generates (using the list monad for the outer mapM) a list with all combinations as lists of tuples e.g. [(1,'+'),(2,'-'),...,(n,'+')].
foldr ... <$> ... combines each of these lists of tuples into a string, using the lambda expression to build it from the right.

(s,i) is a tuple of a sign and a number, and r is the string constructed from the tuples to its right.
id=<<[show i++s:r|s:r>"+"] prepends i and s to the string r constructed so far, but not if the sign s is positive and r is empty.

This is tested by comparing s:r to "+". By luck this is the lexicographically smallest string that can result from concatenating them, so the comparison can use > rather than /=.

Also by luck, "-" is smaller than any nonempty string that can be constructed by the fold, so the empty string can be replaced with it by using max.
Finally unlines turns the strings into a single string of lines.

Python 2, 101 bytes
n=input()
for i in range(2**n):s='';m=n;exec"s=`m`+'+-'[i%2]+s;s*='-'in s;i/=2;m-=1;"*m;print s or'-'

Try it online!

Nice use of s*=<condition>

Python 2, 136 141 133 bytes
def f(n,s="+"):
 while"+"in s:s=s[:s.rfind("+")]+"-";print s[s>"-":];s+="+".join(map(str,range(len(s)/2+1,n+1)))+"-";print(n>0)*s[1:]

Try it online!
The first - (un)surprisingly added a fair few bytes to the code.

So the string manipulation solution was shorter after all?

Or I'm just bad :P

The approach does seem to be shorter, but there are a few things that could be improved on yours; I'll post a comment with some tips in a bit.

n=0 incorrectly produces two - lines.

@CJDennis Fixed.

Yep, looks right now!

Python 2, 150 164 159 154 146 118 bytes 115 112 bytes
def f(n,i=0):
 while i<2**n:t=''.join(`j+1`+'+-'[i>>n+~j&1]for j in range(n));print t[:t.rfind('-')+1]or'-';i+=1

Try it online!
Edit: Oops! It has to work for numbers greater than 4 as well... then chip away... until I realized I was overthinking it and saved 28 bytes... and then 6 more via little golfs.

Output is incorrect for input above n=4.

@CJ Dennis I think it works now; output is the same as notjagan for,e.g, n=5

The output appears to be correct now! I'll add that you should test to at least 10...

I just noticed that you set i=0 in the input! That means I can just generate lines from i onwards, such as f(24,16777200)! :-)

Pyth, 23 bytes
j+\-mssVSQd<Lx_d\-t^"+-

Demonstration
The basis of this program is noticing that other than the initial -, the plus and minus sequence corresponds to the standard sequence of combinations of + and - with replacement, with all trailing + removed.
Explanation:
j+\-mssVSQd<Lx_d\-t^"+-
j+\-mssVSQd<Lx_d\-t^"+-"Q    Implicit string completion and variable introduction
                   ^"+-"Q    Form all sequences of + and - of length equal to
                             the input, ordered lexicographically.
                  t          Remove the first one, which we don't use.
           <L                Take the prefix of each one of length
             x               index in
              _d             the reversed string
                \-           of '-'.
    m                        Map the results to
      sV                     Apply the sum function to pairs of
        SQ                   [1, 2, 3 ... input]
          d                  and the previous string
     s                       Sum the pairs.
 +\-                         Add a '-' on to the front of the list
j                            Join on newlines.

Python 2, 73 bytes
f=lambda n,a=2,d='\n1':a<n+2and f(n,a+1,d+'+'+`a`)+d+f(n,a+1,d+`-a`)or'-'

Try it online!

Haskell, 70 bytes
f n=unlines$"-":foldr(\i x->tail[show i++s:y|s<-"+-",y<-"":x])[][1..n]

Try it online!

Python 3, 305 bytes
x=int(input())
o=lambda:list(range(1,x+1))or[0]
q=o()
q[-1]*=-1
print('-')
def f(a):print(''.join(str(abs(x))+'-+'[x>0]for x in a))
while any([k>0 for k in q])or[-k for k in q]!=o():
	f(q)
	if-q[-1]==x:
		while q[-1]<0:q=q[:-1]
		q[-1]*=-1
	elif-q[-1]<x:
		while q[-1]<x:q+=[abs(q[-1])+1]
		q[-1]*=-1
f(q)

Try it online!

I'm a bit confused by your tab/space mixing.  First I didn't even think you COULD in Python 3, and second it seems to serve little purpose?  Why bother doing <tab><space> when <space><space> would be the same # of bytes?  I guess perhaps if you did the small indents with <space> and the larger with <tab> it would be saving a byte...

@nmjcman101 erm. I must be really tired, or stupid, or both. I was trying to save bytes by doing that space/tab indent not tab/tabspace >< thanks!

This is 17 bytes shorter, but it does exit on an error. Still trying to shorten that pesky q[-1] to q[0]. BTW: mixing tabs and spaces doesn't work in Python 3, so the current code yields an error.

@notjagan oh hm. never mind then, it must have been because earlier I was being dumb :P but okay, thanks for the suggestion; i'll try to work from there

source: Stack Exchange

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

sort: votes


text:
Complex Dice Rolling Expressions
Background
I play D&D on a regular basis with some friends. While talking about the complexity of some systems/versions when it comes to rolling dice and applying bonuses and penalties, we jokingly came up with some additional complexity for dice rolling expressions. Some of them were too outrageous (like extending simple dice expressions like 2d6 to matrix arguments1), but the rest make for an interesting system.
The Challenge
Given a complex dice expression, evaluate it according to the following rules and output the result.
Basic Evaluation Rules

Whenever an operator expects an integer but receives a list for an operand, the sum of that list is used
Whenever an operator expects a list but receives an integer for an operand, the integer is treated as a one-element list containing that integer

Operators
All operators are binary infix operators. For the purpose of explanation, a will be the left operand, and b will be the right operand. List notation will be used for examples where operators can take lists as operands, but actual expressions consist only of positive integers and operators.

d: output a independent uniform random integers in the range [1, b]

Precedence: 3
Both operands are integers
Examples: 3d4 => [1, 4, 3], [1, 2]d6 => [3, 2, 6]

t: take the b lowest values from a

Precedence: 2
a is a list, b is an integer
If b > len(a), all values are returned
Examples: [1, 5, 7]t1 => [1], [5, 18, 3, 9]t2 => [3, 5], 3t5 => [3]

T: take the b highest values from a

Precedence: 2
a is a list, b is an integer
If b > len(a), all values are returned
Examples: [1, 5, 7]T1 => [7], [5, 18, 3, 9]T2 => [18, 9], 3T5 => [3]

r: if any elements in b are in a, reroll those elements, using whatever d statement generated them

Precedence: 2
Both operands are lists
Rerolling is done only once, so it is possible to still have elements of b in the result
Examples: 3d6r1 => [1, 3, 4] => [6, 3, 4], 2d4r2 => [2, 2] => [3, 2], 3d8r[1,8] => [1, 8, 4] => [2, 2, 4]

R: if any elements in b are in a, reroll those elements repeatedly until no elements of b are present, using whatever d statement generated them

Precedence: 2
Both operands are lists
Examples: 3d6R1 => [1, 3, 4] => [6, 3, 4], 2d4R2 => [2, 2] => [3, 2] => [3, 1], 3d8R[1,8] => [1, 8, 4] => [2, 2, 4]

+: add a and b together

Precedence: 1
Both operands are integers
Examples: 2+2 => 4, [2]+[2] => 4, [3, 1]+2 => 6

-: subtract b from a

Precedence: 1
Both operands are integers
b will always be less than a
Examples: 2-1 => 1, 5-[2] => 3, [8, 3]-1 => 10

.: concatenate a and b together

Precedence: 1
Both operands are lists
Examples: 2.2 => [2, 2], [1].[2] => [1, 2], 3.[4] => [3, 4]

_: output a with all elements of b removed

Precedence: 1
Both operands are lists
Examples: [3, 4]_[3] => [4], [2, 3, 3]_3 => [2], 1_2 => [1]

Additional Rules

If the final value of an expression is a list, it is summed before output
Evaluation of terms will only result in positive integers or lists of positive integers - any expression that results in a non-positive integer or a list containing at least one non-positive integer will have those values replaced by 1s
Parentheses can be used to group terms and specify order of evaluation
Operators are evaluated in order of highest precedence to lowest precedence, with evaluation proceeding from left to right in the case of tied precedence (so 1d4d4 would be evaluated as (1d4)d4)
The order of elements in lists does not matter - it is perfectly acceptable for an operator that modifies a list to return it with its elements in a different relative order
Terms that cannot be evaluated or would result in an infinite loop (like 1d1R1 or 3d6R[1, 2, 3, 4, 5, 6]) are not valid

Test Cases
Format: input => possible output
1d20 => 13
2d6 => 8
4d6T3 => 11
2d20t1 => 13
5d8r1 => 34
5d6R1 => 20
2d6d6 => 23
3d2R1d2 => 3
(3d2R1)d2 => 11
1d8+3 => 10
1d8-3 => 4
1d6-1d2 => 2
2d6.2d6 => 12
3d6_1 => 8
1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3)) => 61

All but the last test case were generated with the reference implementation.
Worked Example
Expression: 1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3))

8d20t4T2 => [19, 5, 11, 6, 19, 15, 4, 20]t4T2 => [4, 5, 6, 11]T2 => [11, 6] (full: 1d(([11, 6])d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3)))
6d6R1r6 => [2, 5, 1, 5, 2, 3]r1R6 => [2, 5, 3, 5, 2, 3]R6 => [2, 5, 3, 5, 2, 3] (1d([11, 6]d[2, 5, 3, 5, 2, 3]-2d4+1d2).(1d(4d6_3d3)))
[11, 6]d[2, 5, 3, 5, 2, 3] => 17d20 => [1, 6, 11, 7, 2, 8, 15, 3, 4, 18, 11, 11, 1, 10, 8, 6, 11] (1d([1, 6, 11, 7, 2, 8, 15, 3, 4, 18, 11, 11, 1, 10, 8, 6, 11]-2d4+1d2).(1d(4d6_3d3)))
2d4 => 7 (1d([1, 6, 11, 7, 2, 8, 15, 3, 4, 18, 11, 11, 1, 10, 8, 6, 11]-7+1d2).(1d(4d6_3d3)))
1d2 => 2 (1d([1, 6, 11, 7, 2, 8, 15, 3, 4, 18, 11, 11, 1, 10, 8, 6, 11]-7+2).(1d(4d6_3d3)))
[1, 6, 11, 7, 2, 8, 15, 3, 4, 18, 11, 11, 1, 10, 8, 6, 11]-7+2 => 133-7+2 => 128 (1d128).(1d(4d6_3d3)))
4d6_3d3 => [1, 3, 3, 6]_[3, 2, 2] => [1, 3, 3, 6, 3, 2, 2] (1d128).(1d[1, 3, 3, 6, 3, 2, 2]))
1d[1, 3, 3, 6, 3, 2, 2] => 1d20 => 6 (1d128).(6))
1d128 => 55 (55.6)
55.6 => [55, 6] ([55, 6])
[55, 6] => 61 (done)

Reference Implementation
This reference implementation uses the same constant seed (0) for evaluating each expression for testable, consistent outputs. It expects input on STDIN, with newlines separating each expression.
#!/usr/bin/env python3

import re
from random import randint, seed
from collections import Iterable
from functools import total_ordering

def as_list(x):
    if isinstance(x, Iterable):
        return list(x)
    else:
        return [x]

def roll(num_sides):
    return Die(randint(1, num_sides), num_sides)

def roll_many(num_dice, num_sides):
    num_dice = sum(as_list(num_dice))
    num_sides = sum(as_list(num_sides))
    return [roll(num_sides) for _ in range(num_dice)]

def reroll(dice, values):
    dice, values = as_list(dice), as_list(values)
    return [die.reroll() if die in values else die for die in dice]

def reroll_all(dice, values):
    dice, values = as_list(dice), as_list(values)
    while any(die in values for die in dice):
        dice = [die.reroll() if die in values else die for die in dice]
    return dice

def take_low(dice, num_values):
    dice = as_list(dice)
    num_values = sum(as_list(num_values))
    return sorted(dice)[:num_values]

def take_high(dice, num_values):
    dice = as_list(dice)
    num_values = sum(as_list(num_values))
    return sorted(dice, reverse=True)[:num_values]

def add(a, b):
    a = sum(as_list(a))
    b = sum(as_list(b))
    return a+b

def sub(a, b):
    a = sum(as_list(a))
    b = sum(as_list(b))
    return max(a-b, 1)

def concat(a, b):
    return as_list(a)+as_list(b)

def list_diff(a, b):
    return [x for x in as_list(a) if x not in as_list(b)]

@total_ordering
class Die:
    def __init__(self, value, sides):
        self.value = value
        self.sides = sides
    def reroll(self):
        self.value = roll(self.sides).value
        return self
    def __int__(self):
        return self.value
    __index__ = __int__
    def __lt__(self, other):
        return int(self) < int(other)
    def __eq__(self, other):
        return int(self) == int(other)
    def __add__(self, other):
        return int(self) + int(other)
    def __sub__(self, other):
        return int(self) - int(other)
    __radd__ = __add__
    __rsub__ = __sub__
    def __str__(self):
        return str(int(self))
    def __repr__(self):
        return "{} ({})".format(self.value, self.sides)

class Operator:
    def __init__(self, str, precedence, func):
        self.str = str
        self.precedence = precedence
        self.func = func
    def __call__(self, *args):
        return self.func(*args)
    def __str__(self):
        return self.str
    __repr__ = __str__

ops = {
    'd': Operator('d', 3, roll_many),
    'r': Operator('r', 2, reroll),
    'R': Operator('R', 2, reroll_all),
    't': Operator('t', 2, take_low),
    'T': Operator('T', 2, take_high),
    '+': Operator('+', 1, add),
    '-': Operator('-', 1, sub),
    '.': Operator('.', 1, concat),
    '_': Operator('_', 1, list_diff),
}

def evaluate_dice(expr):
    return max(sum(as_list(evaluate_rpn(shunting_yard(tokenize(expr))))), 1)

def evaluate_rpn(expr):
    stack = []
    while expr:
        tok = expr.pop()
        if isinstance(tok, Operator):
            a, b = stack.pop(), stack.pop()
            stack.append(tok(b, a))
        else:
            stack.append(tok)
    return stack[0]

def shunting_yard(tokens):
    outqueue = []
    opstack = []
    for tok in tokens:
        if isinstance(tok, int):
            outqueue = [tok] + outqueue
        elif tok == '(':
            opstack.append(tok)
        elif tok == ')':
            while opstack[-1] != '(':
                outqueue = [opstack.pop()] + outqueue
            opstack.pop()
        else:
            while opstack and opstack[-1] != '(' and opstack[-1].precedence > tok.precedence:
                outqueue = [opstack.pop()] + outqueue
            opstack.append(tok)
    while opstack:
        outqueue = [opstack.pop()] + outqueue
    return outqueue

def tokenize(expr):
    while expr:
        tok, expr = expr[0], expr[1:]
        if tok in "0123456789":
            while expr and expr[0] in "0123456789":
                tok, expr = tok + expr[0], expr[1:]
            tok = int(tok)
        else:
            tok = ops[tok] if tok in ops else tok
        yield tok

if __name__ == '__main__':
    import sys
    while True:
        try:
            dice_str = input()
            seed(0)
            print("{} => {}".format(dice_str, evaluate_dice(dice_str)))
        except EOFError:
            exit()

[1]: Our definition of adb for matrix arguments was to roll AdX for each X in a * b, where A = det(a * b). Clearly that's too absurd for this challenge.

Sandbox link

With the guarantee on - that b will always be less than a I see no way to get non-positive integers, so the second additional rule seems pointless. OTOH, _ could result in an empty list, which seems useful in same cases but what does it mean when an integer is needed? Normally I'd say the sum is 0...

@ChristianSievers 1) I added the additional note about non-positive integers for clarity. 2) The sum of an empty list is 0. By the no-non-positives rule, it would be evaluated as a 1.

Okay, but is it okay as intermediate result? So [1,2]_([1]_[1]) is [1,2]?

@ChristianSievers No. That would result in [2], because [1]_[1] -> [] -> 0 -> 1 -> [1].

But why would I reinterpret the empty list as a number and then turn it into a list again? Isn't that like arguing that [1].[2] -> [1,2] -> 3 -> [3], therefore [1,2,3]_([1].[2]) results in [1,2]? (Or maybe even [6], if we do the same with the first argument...)

@ChristianSievers I misread. In the case of [1,2]_([1]_[1]), the result would be [1, 2]. Non-positive integers are changed to 1s (even in intermediate results), but empty lists are acceptable for operators that take list arguments. For operators that take integer arguments, an empty list would become a 1 (by the sequence of evaluations above).

Python 3, 803 788 753 749 744 748 745 740 700 695 682  680 bytes
exec(r'''from random import*
import re
class k(int):
 p=0;j=l([d(randint(1,int(b)),b)range(a)]);__mul__=l(sorted()[:b]);__matmul__=l(sorted()[-b:]);__truediv__=l([d(randint(1,int(_.i)),_.i)if _==b else _ ]);__sub__=k(max(1,int.__sub__(a,b)))
 def __mod__(a,b):
  x=[]
  while x!=:x=;a=a/b
  l(x)
 def :
  if b.p:p=b.p;del b.p;l(+b.l)if~-p else l([_ if~-(_ in b.l)])
  k(int.)
 def __neg__(a):a.p+=1;a
def l(x):a=k(sum(x)or 1);=x;a
def d(v,i):d=k(v);d.i=i;d
w=lambda a:eval(re.sub("(\d+)","(k(\\1))",a).translate({100:".j",116:"*",84:"@",114:"/",82:"%",46:"+--",95:"+-"}))'''.translate({2:" for _ in ",3:"a.l",4:"lambda a,b:",5:"return ",6:"__add__(a,b)"}))

Try it online!
Contains a lot of unprintables, see the TIO link for the full code
-5 bytes thanks to Mr.Xcoder
-5 more bytes thanks to NGN
-about 40 bytes thanks to Jonathan French
Yuck, what a kludge!
This works by using a regular expression to wrap all numbers in my k class, and converting all of the operators into operators python understands, then using the magic methods of the k class to handle the math. The +- and +-- at the end for . and _ are a hack to keep the precedence correct. Likewise, I can't use the ** operator for d because doing so would make 1d4d4 be parsed as 1d(4d4). Instead, I wrap all numbers in an extra set of parens and do d as .j, since method calls have higher precedence that operators. The last line evaluates as an anonymous function that evaluates the expression.

def __mod__(a, b)... Why the space between a, and b?

744 bytes

@Mr.Xcoder I think you can save a byte by removing an unnecessary space: ; __sub__. And possibly also here: lambda a,b: l(.

You could save some bytes by wrapping your entire code in an exec("""...""".replace("...","...")) statement and replacing strings that occur often (like return ) with a single character. However, to me the exec-strategy always seems a bit unelegant...

the bodies of __mod__ and __add__ don't need that much indent

Would it be possible to replace __mod__ and __add__ with __lt__ and __gt__?

No, because of comparison chaining 1<2<3 is parsed as 1<2 and 2<3, which I don't want.

APL (Dyalog Classic), 367 bytes
d←{(⊢⍪⍨1+?)⍉⍪⊃⍴/⊃¨+/¨⍺⍵}⋄r←{z←⊣⌿⍺⋄((m×?n)+z×~m←z∊⊣⌿⍵)⍪n←⊢⌿⍺}⋄R←{⍬≡⊃∩/⊣⌿¨⍺⍵:⍺⋄⍵∇⍨⍺r⍵}
u←{⍺[;((⊃+/⍵)⌊≢⍉⍺)↑⍺⍺⊣⌿⍺]}⋄t←⍋u⋄T←⍒u⋄A←+/,⋄S←+/,∘-⋄C←,⋄D←{⍺/⍨~⊃∊/⊣⌿¨⍺⍵}
h←v←⍬⋄o←'drRtT+-._'⋄f←{8<i←o⍳⊃⍵:0⋄v⊢←(¯2↓v),(⍎i⊃'drRtTASCD')/¯2↑v}
{⊃⍵∊⎕d:v,←⊂⍪2↑⍎⍵⋄'('=⍵:h,←⍵⋄')'=⍵:h↑⍨←i-1⊣f¨⌽h↓⍨i←+/∨\⌽h='('⋄h,←⍵⊣h↓⍨←-i⊣f¨⌽h↑⍨-i←+/∧\⌽≤/(1 4 4 1/⌽⍳4)[o⍳↑⍵,¨h]}¨'\d+' '.'⎕s'&'⊢⍞
f¨⌽h⋄1⌈+/⊣⌿⊃v

Try it online!
This is the shunting yard algorithm from the reference implementation merged with evaluate_dice(), without the cruft and object-oriented nonsense. Only two stacks are used: h for the operators and v for the values. Parsing and evaluation are interleaved.
Intermediate results are represented as 2×N matrices where the first row are the random values and the second row are the number of sides on the dice that produced them. When a result is not produced by the dice-throwing "d" operator, the second row contains arbitrary numbers. A single random value is a 2×1 matrix and thus indistinguishable from a 1-element list.

Python 3: 723 722 714 711 707 675 653 665 bytes
import re
from random import*
S=re.subn
e=eval
r=randint
s=lambda a:sum(g(e(a)))or 1
g=lambda a:next(zip(*a))
def o(m):a,o,b=m.groups();A=sorted(e(a));t=g(e(b));return str(o in"rR"and([([v,(r(1,d)*(o>"R")or choice([n+1for n in range(d)if~-(n+1in t)]))][v in t],d)for(v,d)in A])or{"t":A[:s(b)],"T":A[-s(b):],"+":[(s(a)+s(b),0)],"-":[(s(a)-s(b),0)],".":e(a)+e(b),"_":[t for t in e(a)if~-(t[0]in g(e(b)))]}[o])
def d(m):a,b=map(s,m.groups());return str([(r(1,b),b)for _ in" "*a])
p=r"(\[[^]]+\])"
def E(D):
 D,n=S(r"(\d+)",r"[(\1,0)]",D)
 while n:
  n=0
  for e in[("\(("+p+")\)",r"\1"),(p+"d"+p,d),(p+"([tTrR])"+p,o),(p+"(.)"+p,o)]:
   if n<1:D,n=S(*e,D)
 return s(D)

The entry point is E.  This applies regular expressions iteratively.  First it replaces all integers x with a singleton list tuple [(x,0)].  Then the first regular expression performs the d operation, by replacing all [(x,0)]d[(b,0)] with the string representation of an array of tuples like [(1,b),(2,b),(3,b)].  The second element of each tuple is the second operand to d.  Then, subsequent regular expressions perform each of the other operators.  There is a special regex to remove parens from fully calculated expressions.

Clojure, 731 720 bytes
(when newlines are removed)
Update: a shorter implementation of F.
(defn N[i](if(seq? i)(apply + i)i))
(defn g[i](let[L(fn[i](let[v(g i)](if(seq? v)v(list v))))R remove T take](if(seq? i)(let[[o a b :as A]i](if(some symbol? A)(case o d(repeatedly(N(g a))(fn[](inc(rand-int(N(g b))))))t(T(N(g b))(sort(g a)))T(T(N(g b))(sort-by -(g a)))r(for[i(L a)](if((set(L b))i)(nth(L a)0)i))R(T(count(L a))(R(set(L b))(for[_(range)i(L a)]i)))+(+(N(g a))(N(g b)))-(-(N(g a))(N(g b))).(into(L a)(L b))_(R(set(L b))(g a)))A))i)))
(defn F[T](if(seq? T)(if(next T)(loop[[s & S]'[_ . - + R r T t d]](let[R reverse[b a](map R(split-with(comp not #{s})(R T)))a(butlast a)](if a(cons s(map F[a b]))(recur S))))(F(first T)))T))
(defn f[i](N(g(F(read-string(clojure.string/replace(str"("i")")#"[^0-9]"" $0 "))))))

This consists of four main parts:

N: coerces a list into a number
g: evaluates an abstract syntax tree (S-expressions with 3 items)
F: converts an infix AST to prefix notation (S-expressions), also applies operand order precedence
f: uses read-string to convert a string into a nested sequence of numbers and symbols (infix AST), pipes them through F -> g -> N, returning the result number.

I'm not sure how to thoroughly test this, maybe via statistical tests against a reference implementation? At least the AST and its evaluation is relatively easy to follow.
Example S-expression from 1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3)):
(. (d 1 (- (d (T (t (d 8 20) 4) 2)
              (R (d 6 6) (r 1 6)))
           (+ (d 2 4)
              (d 1 2))))
   (d 1 (_ (d 4 6) (d 3 3))))

Less golfed with internediate results and tests:
(def f #(read-string(clojure.string/replace(str"("%")")#"[^0-9]"" $0 ")))

(defn F [T]
  (println {:T T})
  (cond
    (not(seq? T))T
    (symbol?(first T))T
    (=(count T)1)(F(first T))
    1(loop [[s & S] '[_ . - + R r T t d]]
      (let[[b a](map reverse(split-with(comp not #{s})(reverse T)))
           _ (println [s a b])
           a(butlast a)]
        (cond
          a(do(println {:s s :a a :b b})(cons s(map F[a b])))
          S(recur S))))))

(->> "3d6" f F)
(->> "3d6t2" f F)
(->> "3d2R1" f F)
(->> "1d4d4" f F)
(->> "2d6.2d6" f F)
(->> "(3d2R1)d2" f F)
(->> "1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3))" f F)

(defn N[i](if(seq? i)(apply + i)i))

(defn g[i]
  (let[L(fn[i](let[v(g i)](if(seq? v)v(list v))))]
    (if(seq? i)
      (let[[o a b :as A] i]
        (println {:o o :a a :b b :all A})
        (if(every? number? A)(do(println{:A A})A)
           (case o
            d (repeatedly(N (g a))(fn[](inc(rand-int(N (g b))))))
            t (take(N (g b))(sort(g a)))
            T (take(N (g b))(sort-by -(g a)))
            r (for[i(L a)](if((set(L b))i)(nth(L a)0)i))
            R (take(count(g a))(remove(set(L b))(for[_(range)i(g a)]i)))
            + (+(N (g a))(N (g b)))
            - (-(N (g a))(N (g b)))
            . (into(L a)(L b))
            _ (remove(set(L b))(g a)))))
      (do(println {:i i})i))))

(g '(. (d 3 5) (d 4 3)))
(g '(. 1 (2 3)))
(g '(+ 1 (2 3)))
(g '(R (d 10 5) (d 1 3)))
(g '(T (d 5 20) 3))
(g '(t (d 5 20) 3))
(g '(d (d 3 4) 10))
(g '(d 4 3))
(g '(_ (d 4 6) (d 3 3)))

(->> "1d(4d6_3d3)" f F g)
(->> "1r6" f F g)
(->> "(8d20t4T2)d(6d6R1r6)" f F g)
(->> "(8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3)" f F g)
(->> "1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3))" f F g))

Python 3, 695 bytes
import random,tatsu
A=lambda x:sum(x)or 1
H=lambda x:[[d,D(d.s)][d in x[2]]for d in x[0]]
R=lambda x:R([H(x)]+x[1:])if{*x[0]}&{*x[2]}else x[0]
class D(int):
 def __new__(cls,s):o=super().__new__(cls,random.randint(1,s));o.s = s;return o
class S:
 o=lambda s,x:{'+':[A(x[0])+A(x[2])],'-':[A(x[0])-A(x[2])],'.':x[0]+x[2],'_':[d for d in x[0]if d not in x[2]]}[x[1]]
 f=lambda s,x:{'r':H(x),'R':R(x),'t':sorted(x[0])[:A(x[2])],'T':sorted(x[0])[-A(x[2]):]}[x[1]]
 d=lambda s,x:[D(A(x[2]))for _ in' '*A(x[0])]
 n=lambda s,x:[int(x)]
 l=lambda s,x:sum(x,[])
lambda i:tatsu.parse("s=e$;e=o|t;o=e/[-+._]/t;t=f|r;f=t/[rRtT]/r;r=d|a;d=r/d/a;a=n|l|p;n=/\d+/;l='['@:','.{n}']';p='('@:e')';",i,semantics=S())

An interpreter built using tatsu, a PEG parser library.  The first argument to tatsu.parser() is the PEG grammar.
class D (for Die) subclasses the built in int type.  It's value is the result of a roll. The attribute .s is the number of sides on the die.
class S has the semantic actions for the parser, and implements the interpreter.

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

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


text:
Shoes for seahorses
Seahorses, of course, need shoes. However, a seahorse, having just one tail, needs just one shoe. Unfortunately, the shoes only come in pairs. Money is tight for the seahorse government, so they need to buy as few pairs as possible. Each seahorse has a shoe size x where x is a positive integer. However, a seahorse can wear a shoe of size x - 1 or x + 1 if need be.
Your task is to output the minimum number of pairs the seahorse government must buy to put shoes on all their seahorses.
You may take input however you want, standard loopholes, etc.
As this is code-golf, shortest code in bytes wins.
Test cases
2 4 6 6 8 14 ->        4
2 1 3 1 1 ->           3
4 1 4 9 1 8 9 1 8 4 -> 6
1 2 3 5 7 8 10 12 ->   4

This can be done trivially by sorting the array and looping through it, but I would like to see something creative (this has no bearing on the actual scoring, I just think it would be interesting to see another approach)

I don't see how it can be done trivially...

If I'm not missing anything about my own problem (hopefully not...) you can sort it and then try to pair each element with the element immediately right of it.
So if you have 4 1 4 9 1 8 9 1 8 4, you sort it to get 1 1 1 4 4 4 8 8 9 9, then pair 1 and 1, then the 1 is a singleton, then 4 and 4, 4 is a singleton, 8 and 8, and 9 and 9, to get 6. Maybe there is some case I can't think of, I'm new to this

What about 1 5 5 6 6?

Wouldn't 1 5 5 6 6 make 1  its own pair, then pair 5 with 5, and 6 with 6, to get the optimal solution?

@LEaky, each input can have many combinations as solutions
ex. 15566--> 1,55,66 or 1,56,56, you just need to find the minimum number or pairs, so in your example, just output 3

Right. I can't find any counter-example yet, but it can be hard to implement the algorithm for something like 1 4 4 7 10 10, considering that Jelly does not have "loop" per se

In a non-golfing language, you would just increment the counter by 2 if you find a pair, and 1 otherwise. Not sure how Jelly works

Are shoe sizes positive integers?

@bushdid911 I suppose I can't explain how Jelly works in a comment

yes, edited OP to show this also @xnor

I can't help thinking that the OP is a Douglas Adams fan.  +1

@CodyGray You can have a size 3 pair, which covers 2 and 4.

Zgarb is correct. @CodyGray

Potential Title edit: Sea-horseshoes

05AB1E, 13 bytes
Uses the approach OP described in the comments.
{¥3‹J0¡€gÌ2÷O

Try it online!
Explanation
{¥3‹J0¡€gÌ2÷O   Argument l
{               Sort l
 ¥              Push deltas
  3‹            Map to lower than 3 (1 for true, 0 for false)
    J0¡         Join and split on 0
       €g       Map to length
         Ì      Each + 2
          2÷    Integer division by 2
            O   Sum

The returns 3 for 2 4 6 6 8 14.

Husk, 15 14 bytes
Γ0(→₀?tI↑<+3)O

Uses the greedy algorithm: sort and pair from the left.
Try it online!
Thanks to Leo for saving 1 byte.
Explanation
This is the first Husk answer that uses Γ, the function for pattern matching a list.
In this use case, if a is a value and g is a function, then Γag corresponds to the function f defined by the Haskell snippet
f [] = a
f (x:xs) = g x xs

I define the base case as a = 0 and
g x xs = 1 + line0 (if head xs < x+3 then tail xs else xs)

where line0 refers to the entire line.
In the Husk code, x and xs are implicit arguments to the lambda function, and line0 is ₀.
The list is sorted again in each recursive call, but that doesn't matter in a golf challenge.
Γ0(→₀?tI↑<+3)O
             O  Sort
Γ               and pattern match
 0              giving 0 for an empty list
  (         )   and applying this function to a non-empty list:
          +3     Add 3 to first argument (x),
         <       make a "test function" for being less than that,
        ↑        take values from second argument (xs) while they pass the test.
     ?           If that prefix is nonempty (next value can be paired),
      t          take tail of xs,
       I         otherwise take xs as is.
    ₀            Apply the main function (line0) to this list
   →             and add 1 for the singleton/pair we just processed.

All these people using their own languages makes me want to create my own. First I have to come up with a name :P

Python 2, 49 bytes
f=lambda a:a>[a.sort()]and-~f(a[[3+a.pop(0)]>a:])

Try it online!
Based on Leaky Nun's recursive solution.

Python 2, 59 bytes
p=c=0
for x in sorted(input()):c+=x>p;p=(x>p)*(x+2)
print c

Try it online!
Iterates through the sizes x in sorted order. Remembers the upper threshold p for the current size to the paired with the previous one. If so (x>p), reset the threshold to 0 to make it impossible for the next one to be paired. If not, increment the output count c and set the next threshold p to x+2.
The new threshold p=(x>p)*(x+2) is a bloated expression. I'd like to find a way to shorten it.

Python 3, 69 66 60 bytes
9 bytes thanks to xnor.
f=lambda a:a[1:a.sort()]and-~f(a[1+(a[1]-a[0]<3):])or len(a)

Try it online!

I think you can do a.sort().

@xnor done, thanks.

The sorting can be stuck into a lambda: f=lambda a:a[1:a.sort()]and-~f(a[1+(a[1]-a[0]<3):])or len(a)

or[]<a to save 3 bytes

Jelly, 20 18 bytes
ṢLµIḢ<3+2⁸ṫß‘µLỊ$?

Try it online!
Fork of my Python answer.

-4 bytes: IḢ<3+2⁸ṫß‘µLḊ? (basically I don't see any reason to do Ṣ before L, and Ḋ would return [] if list if of length 1 or 0, and then I can remove an µ from LµḊ?)

But you didn't sort anywhere...

Now I'm a bit confused tbf...I think your intent is a bit different than what your code actually does? You may want to prepend an Ṣ to my golf if I understand correctly.

Something is wonky with your sort. [1, 1, 1, 1, 4, 4, 4, 8, 8, 9, 9] works but [4,1,4,9,1,8,9,1,8,4,1] doesn't.

@bushdid911 They both work. Could you demonstrate?

Is it a bug with TIO then? They are the exact same shoe sizes (in a different order), but one gives 6 and the other 7. @LeakyNun

@bushdid911 Could you include a link?

C#, 111 108 137 102 bytes
This will never win but I wanted to solve the exercise anyway:
Array.Sort(a);var c=0;for(var i=0;i<a.Length;i++){c++;i+=a.Length-i>1&&a[i+1]-a[i]<3?1:0;}Console.WriteLine(c);

Thanks to the comment of @grabthefish, I was able to nibble of a few more bytes:
Array.Sort(a);int c=0,i=0;for(;i<a.Length;i++){c++;i+=a.Length-i>1&&a[i+1]-a[i]<3?1:0;}Console.WriteLine(c);

Following the PC&G special C# rules:
class P{static void Main(){Array.Sort(a);int c=0,i=0;for(;i<a.Length;i++){c++;i+=a.Length-i>1&&a[i+1]-a[i]<3?1:0;}Console.WriteLine(c);}}

Using a lambda function:
a=>{System.Array.Sort(a);int c=0,i=0;for(;i<a.Length;c++)i+=a.Length-i>1&&a[i+1]-a[i]<3?2:1;return c;}

Comments are not for extended discussion; this conversation has been moved to chat.

Thank you for keeping the progression through the answers - that's just as interesting as the final answer.

Perl, 113 bytes
say sub{for(1..$#_){$x{$i}++;$i++if$_[$_]-$_[$_-1]>2}$x{$i}++;$-+=$_/2+$_%2for values%x;$-}->(sort{$a<=>$b}@ARGV)

Takes list of arguments from command line (as @ARGV), prints to STDOUT by default.
In Seahorseville...
A neighbourhood is a sequence of neighbouring shoe sizes. When sorted, each seahorse has immediate neighbours that can share the same shoe size. There can be multiple neighbours in the neighbourhood and no neighbours can differ in value by more than two:
e.g. 3 3 4 5 5 6 is a single neighbourhood, as are 2 4 6 6, and 1 2 3 5 7 8 10 12
e.g. 1 1 1 4 5 6 contains two neighbourhoods: 1 1 1 and 4 5 6.
Basis of the algorithm
There are two types of neighbourhood:

Even-sized
For these, n/2 pairs is always sufficient:
e.g. 3 3 4 5 5 6 requires three pairs for 3 3, 4 5 and 5 6
Odd-sized
For these, ceil(n/2) pairs is always sufficient:
e.g. 12 13 13 14 15 requires three pairs for 12 13, 13 14, and 15 alone.

Ungolfed code to test the algorithm
sub pairs {
    @_ = sort { $a <=> $b } @_;
    my @hood;
    my $i = 0;
    for (1..$#_) {
        push @{$hood[$i]}, $_[$_-1];
        $i++ if $_[$_]-$_[$_-1]>2
    }
    push @{$hood[$i]}, $_[$#_];
    my $pairs;
    $pairs += int(@{$hood[$_]} / 2) + @{$hood[$_]} % 2 for 0..$#hood;
    return "$pairs : @{[map qq([@$_]), @hood]}\n";
}

Sample Results
(Neighbourhoods enclosed in [ ] )
4 : [2 4 6 6 8] [14]
3 : [1 1 1 2 3]
6 : [1 1 1] [4 4 4] [8 8 9 9]
4 : [1 2 3 5 7 8 10 12]
17 : [1 2 3] [6 8 9 11 13 13 15 17 19 20 21] [27 28 29 30 32 33 35 35] [38 38 40] [43 45 45 46] [49]
18 : [3 3 3] [8 10 11 11 11 12 14] [18] [21 22 23] [29] [32 33 34 34 34 35 37 38 39 41] [44 46 48 49 49]
18 : [1 2 3] [6] [9] [12 13 15 17 18 19 20 21 21 23 24 25 25] [35 36] [40 41 41 41 43 45 46 46 46] [49]
16 : [1 3] [6 6 6 6] [11 12 14 14 15 17 19 20 20 21 21 22] [25 25 27 29 31 32 33] [38 39] [44 45] [49]
16 : [2 4] [7 7 8 10 12 13 15 16] [22 22 24 24] [27 29 31 31 33 34] [37 38 39] [42 43 43 44 45 46 47]
17 : [2 4 5 6 7] [11 11 13 13 14 15 16 17 17 17 19] [29] [34 35 36] [39 39 41 41 41 42 44 46] [49 49]
18 : [3 4 5 7 7] [10 10 12 12 12 14 15 15 17 18] [21] [24 24] [28] [32] [39 40 41 42 43 44 44] [47 47] [50]
16 : [2 4] [7 7 8 8] [11 11] [14 16 17 17 18 19] [22 24 26 26] [30 31 33 34 34 35] [38 38 39] [42 43] [50]
16 : [1 3 4 5] [11 11] [15 15 17 18 19 21 22 23 23 25 27 27 27 27 28 29 30 30] [33 34] [41 41] [45] [48]
17 : [2 2 3 4 6 6 7] [10 10] [13 14 15 16 17 19] [23 25] [28 30 31 32 33 34 36 37 38] [42] [48 49 50]
17 : [2] [7 9 9 9 9 10 10 12] [16 16] [19 21 21 22 24] [27 27 27] [36 36 36 37 39 39 40 40 40 41] [46]
18 : [1] [5 6 6 8] [11 11 12] [19 19 20 21 22 24 26 26] [29 30 31 32 34 35 35] [38] [42] [45] [48 48 49 49]
16 : [2 4 4 6] [11 12 13 13 13] [21 21 21 23] [30 31 31 33 35] [41 41 41 43 45 46 47 48 48 49 49 50]
16 : [2 2] [8 10 12] [15 15 15 15 16 16] [19 20] [23 24] [28 28 29] [32 34 36 36 36 37 39 41] [44 45 47 48]
17 : [3 3] [6] [9 10 11] [17 18] [21 23 23] [27 28 29 29 30 31 31 33] [37 37 39 39 39 40] [43 44] [47 48 49]
17 : [4] [7 9 10 10] [14 14 14] [17] [21] [25 25 27 27 28 30] [33 35 37 37 38 40 41 43 44 45 47 48 49 50]
18 : [3 4 5 6 7] [10 11 12 12 14 15 16 17] [20] [23 24 25 25 26 26] [31] [35] [38 40 41 42] [45 46 47] [50]
17 : [1 3] [8 10] [16 16 18 19 20 20] [23 23] [26] [30 31 33 34 35] [39 39 39 40 41 42 43] [46 46 47 47 49]
18 : [2 4 4 4 4 6 7 8 8 10 10] [13] [16 17] [20 22 23 25 25] [29 29 29] [33] [39 40 42] [48 48 49 49]
16 : [1 1 3 4] [7 8 10 10] [18 18 20 21] [24 25 26 27 29 31 33 33 34 34] [37 37 39] [45 46 48 49 49]
17 : [1] [4 4] [7 9 9 11 12] [15 16 17 17 18 19 21 21 21 22 23] [27 28 30 31] [37 39] [42] [48 49 49 50]
17 : [3 4 6 7 7 8 9 10 10 11 13 14 14] [21 21 23] [26 27] [31 32] [35 36] [39 40 41 41 41] [44 44] [49]
16 : [1] [4 6 6 8 10 12 13 15] [20 20 21 21] [29 29 30] [34 36 36 37 37 38 38 40] [44 45 46 47 47 48]
17 : [3 4 4 6] [12 14 15 16 17] [20 21 22 22 22 23 24 26 26] [29 30 32] [35 37 37 37 38 39 41 42] [48]
19 : [1] [5] [8 9] [14 14 14 16 16 17 17 17 17] [21] [24 24 24] [30] [34 35 36 37 39 40 40] [45 46 46 47 48]

Mathematica, 67 bytes
Length@Flatten[Partition[#,UpTo@2]&/@Split[Sort@#,Abs[#-#2]<3&],1]&

Try in Wolfram sandbox.

Any way we can test? Like the Wolfram thing?

@LiefdeWen You could Try it online! in Mathics. Mathics doesn't support all the functions of the Wolfram language, but the ones used in this entry are all implemented, so either Mathics is broken or this solution is invalid.

It works on https://sandbox.open.wolframcloud.com, so the problem is on  Mathics' side

@Phoenix don't think Mathics supports UpTo

K (ngn/k), 31 bytes
{#,/0N 2#/:(0,&~t)_t:3>-':x@<x}

Try it online!

x@<x sort the input (ascending)
t:3>-': generate boolean array indicating where the difference between values is less than 3, storing in t
(0,&~t)_t split t on where 0's are present, e.g. 1 1 1 0 1 1 0 1 1 1 => (1 1 1;0 1 1;0 1 1 1)
0N 2#/: split each of the right-side arguments into length 2 chunks (i.e. valid "pairs" of shoes)
#,/ flatten the chunks and take their count

Perl, 103 bytes
say sub{for(1..$#_+1){$x{$i}++;$i++if$_[$_]-$_[$_-1]>2}@_/2+.5*grep$_%2,values%x}->(sort{$a<=>$b}@ARGV)

Takes list of arguments from command line (as @ARGV), prints to STDOUT by default.
This is an alternative approach, based on the following relationship:
Minimum pairs = ( Population size + # Odd neighbourhoods ) / 2

(See this answer for how neighbourhood is defined)

Javascript, 67 bytes
a=>(a=a.sort((a,b)=>a-b)).filter((n,i)=>m=!m|n-a[i-1]>2,m=0).length

Example code snippet:

f=
a=>(a=a.sort((a,b)=>a-b)).filter((n,i)=>m=!m|n-a[i-1]>2,m=0).length

v=[[2,4,6,6,8,14],[2,1,3,1,1],[4,1,4,9,1,8,9,1,8,4],[1,2,3,5,7,8,10,12]]
for(k=0;k<4;k++)
  console.log(`f([${v[k]}])=${f(v[k])}`)

J, 29 28 bytes
[:#(([#~_2>-&{.),_:0}])/@/:~

Try it online!
Basic idea:

/:~ Sort.
(...)/ Fold from the right, collapsing pairs into the single value infinity _, and appending the new value otherwise.
[:# Return the length of the result.

Specifically, step 2 works like this:

_:0}] Update the first element 0} of the right-hand fold argument ] (the list we're "building", the "memo" of the reduce, etc) to infinity _:.
_2>-&{. When the difference between the left-hand fold argument and the first element of the right-hand fold argument is less than negative 2 _2, append the left-hand argument [#~...,.  This condition will hold when either:

The values are too far apart to wear the same shoe.
The previous value was already "used up" by a preceding pair.  The right argument will always be infinity in this case.

Jelly, 13 bytes
Ṣ3+þŒpŒɠ€HĊ§Ṃ

Try it online!
Explatation
Ṣ3+þŒpŒɠ€HĊ§Ṃ   Main monadic link
Ṣ               Sort
 3+þ            Add [1,2,3] to each element
    Œp          Cartesian product
      Œɠ        Run lengths
        €         of each sublist
         H      Halve all numbers
          Ċ     Ceil all numbers
           §    Sum each sublist
            Ṃ   Minimum


text:
Output the n-th Bell Number
A Bell number (OEIS A000110) is  the number of ways to partition a set of n labeled (distinct) elements. The 0th Bell number is defined as 1.
Let's look at some examples (I use brackets to denote the subsets and braces for the partitions):
1: {1}
2: {[1,2]}, {[1],[2]}
3: {[1,2,3]}, {[1,2],[3]}, {[1,3],[2]}, {[2,3],[1]}, {[1],[2],[3]}

There are many ways to compute Bell numbers, and you are free to use any of them. One way will be described here:
The easiest way to compute Bell numbers is to use a number triangle resembling Pascal's triangle for the binomial coefficients. The Bell numbers appear on the edges of the triangle. Starting with 1, each new row in the triangle is constructed by taking the last entry in the previous row as the first entry, and then setting each new entry to its left neighbor plus its upper left neighbor:
1
1    2
2    3    5
5    7   10   15
15  20   27   37   52

You may use 0-indexing or 1-indexing. If you use 0-indexing, an input of 3 should output 5, but should output 2 if you use 1-indexing.
Your program must work up to the 15th Bell number, outputting 1382958545. In theory, your program should be able to handle larger numbers (in other words, don't hardcode the solutions).
EDIT: You are not required to handle an input of 0 (for 0-indexing) or 1(for 1-indexing) because it is not computed by the triangle method.
Test cases (assuming 0-indexing):
0 ->  1 (OPTIONAL)
1 ->  1
2 ->  2
3 ->  5
4 ->  15
5 ->  52
6 ->  203
7 ->  877
8 ->  4140
9 ->  21147
10 -> 115975
11 -> 678570
12 -> 4213597
13 -> 27644437
14 -> 190899322
15 -> 1382958545

Answers using a built-in method (such as BellB[n] in the Wolfram Language) that directly produces Bell numbers will be noncompetitive.
Shortest code (in bytes) wins.

If you use 0-indexing, an input of 3 should output 5 It would ouput 15,  right? And with 1-indexing it would output 5

The reasoning behind that was counting the 0th bell number as index 0 in 0-indexing and index 1 in 1-indexing. Your way might be more clear, but the existing answers work like that, so I can't change it now. I just joined this site a few hours ago

But you say that with 1-indexing, input 3 should output 2. Then what would input 1 give with 1-indexing?

1 -> 1,
2 - > 1,
3 -> 2 (corresponding to the 0th,1st, and 2nd Bell numbers)
as opposed to
0 -> 1,
1 -> 1,
2 -> 2
Maybe i am using the wrong terminology

I think I get it. The first 1 is missing in your example table and output, which confused me

And welcome to the site!

"You are not required to handle an input of 0 (for 0-indexing) or 1(for 1-indexing) because it is not computed by the triangle method" makes no sense. I'm using Aitken's triangle and my code gives the correct answer for input 0.

Jelly, 9 bytes
ṖµṀcæ.ß€‘

This uses the formula

which is closed whenever n < 2.
Try it online!
How it works
ṖµṀcæ.ß€‘  Main link. Argument: n

Ṗ          Pop; yield A := [1, ..., n-1].
 µ         Begin a new, monadic chain with argument A.
  Ṁ        Maximum; yield n-1.
   c       Combinatons; compute (n-1)C(k) for each k in A.
      ß€   Recursively map the main link over A.
    æ.     Take the dot product of the results to both sides.
        ‘  Increment; add 1 to the result.

JavaScript (ES6), 47 bytes
f=(n,a=[b=1])=>n--?f(n,[b,...a.map(e=>b+=e)]):b
f=(n,a=[b=1])=>--n?f(n,[b,...a.map(e=>b+=e)]):b

First one is 0-indexed, second is 1-indexed.

Haskell, 36 bytes
head.(iterate(last>>=scanl(+))[1]!!)

Uses the triangle method, correctly handles 0, 0-based.

R, 31 bytes
sum(gmp::Stirling2.all(scan()))

uses the Stirling Number of the Second Kind formula and calculates those numbers with the gmp package; reads from stdin and returns the value as a Big Integer; fails for 0; 1-indexed.

Mathematica , 24 bytes
Sum[k^#/k!,{k,0,∞}]/E&

-13 bytes from @Kelly Lowder!

Sum[k^#/k!,{k,0,∞}]/E& is only 24 bytes

Jelly, 14 12 11 bytes
ṫ0;⁸+\
1Ç¡Ḣ

Try it online!
Didn't exactly hit the strong points of Jelly with dynamic input to ¡, Ṫ always modifying the array and the lack of a prepending atom (one-byte ;@ or reverse-ṭ).

CJam (19 bytes)
Xa{X\{X+:X}%+}qi*0=

Online demo
Dissection
Xa         e# Start with an array [1]
{          e# Repeat...
  X\       e#   Put a copy of X under the current row
  {X+:X}%  e#   Map over x in row: push (X+=x)
  +        e#   Prepend that copy of last element of the previous row to get the next row
}
qi*        e# ... input() times
0=         e# Select the first element

MATL, 14 bytes
:dtEw1Zh1Ze/Yo

Input is 0-based. Try it online!
Explanation
This uses the formula

where p Fq (a1, ..., ap; b1, ..., bq; x) is the generalized hypergeometric function.
:      % Implictly input n. Push array [1 2 ... n]
d      % Consecutive differences: array [1 ... 1] (n-1 entries)
tE     % Duplicate, multiply by 2: array [2 ... 2] (n-1 entries)
w      % Swap
1      % Push 1
Zh     % Hypergeometric function
1Ze    % Push number e
/      % Divide
Yo     % Round (to prevent numerical precision issues). Implicitly display

Python, 42 bytes
f=lambda n,k=0:n<1or k*f(n-1,k)+f(n-1,k+1)

Try it online!
The recursive formula comes from placing n elements into partitions. For each element in turn, we decide whether to place it:

Into an existing partition, of which there are k choices
To start a new partition, which increases the number of choices k for future elements

Either way decreases the remaining number n of elements to place. So, we have the recursive formula f(n,k)=k*f(n-1,k)+f(n-1,k+1) and f(0,k)=1, with f(n,0) the n-th Bell number.

Python 2, 91 bytes
s=lambda n,k:n*k and k*s(n-1,k)+s(n-1,k-1)or n==k
B=lambda n:sum(s(n,k)for k in range(n+1))

Try it online!
B(n) calculated as a sum of Stirling numbers of the second kind.

That's a nice solution. Note that using a built in for Stirling numbers of the second kind would be allowed to compute the Bell numbers (if using Mathematica or similar)

You can save two bytes directly in the definition of s: since the recursive calls always reduce n and there's no division by k you can lose the *k in the first term.

Or you can save a bunch by flattening into one lambda, working on entire rows: B=lambda n,r=[1,0]:n and B(n-1,[k*r[k]+r[k-1]for k in range(len(r))]+[0])or sum(r)

as your function B is not recursive and it is your final answer, you can omit the B= to save 2 bytes

MATLAB, 128 103 bytes
function q(z)
r(1,1)=1;for x=2:z
r(x,1)=r(x-1,x-1);for y=2:x
r(x,y)=r(x,y-1)+r(x-1,y-1);end
end
r(z,z)

Pretty self explanatory. Omitting a semicolon at the end of a line prints the result.
25 bytes saved thanks to Luis Mendo.

MATL, 19 18 bytes
1i:"t@q@:qXn*sh]0)

Uses 0-based input. Based on the recurrence relation

Try it online!

R, 46 bytes
r=1;for(i in 1:scan())r=cumsum(c(r[i],r));r[1]

Try it online!

42 bytes -- T defaults to TRUE (aka 1)  unless it's been set somewhere else

Ohm, 15 bytes
2°M^┼ⁿ^!/Σ;αê/≈

Try it online!
Uses Dobinski's forumla (even works for B(0) yay).
Explanation
2°M^┼ⁿ^!/Σ;αê/≈
2°        ;     # Push 100
  M             # Do 100 times...
   ^             # Push index of current iteration
    ┼ⁿ           # Take that to the power of the user input
      ^!         # Push index factorial
        /        # Divide
         Σ       # Sum stack together
           αê   # Push e (2.718...)
             /  # Divide
              ≈ # Round to nearest integer (Srsly why doesn't 05AB1E have this???)

Python (79 bytes)
B=lambda n,r=[1]:n and B(n-1,[r[-1]+sum(r[:i])for i in range(len(r)+1)])or r[0]

Online demo in Python 2, but it also works in Python 3.
This builds Aitken's triangle using a recursive lambda for a golfy loop.

Haskell, 35 bytes
(%0)
n%k|n<1=1|m<-n-1=k*m%k+m%(k+1)

Try it online!
Formula explained in my Python answer.

PHP, 72 bytes
recursive function 1-indexed

function f($r,$c=0){return$r?$c?f($r-1,$c-1)+f($r,$c-1):f($r-1,$r-2):1;}

Try it online!
PHP, 86 bytes
0-indexed

for(;$r++<$argn;)for($c=~0;++$c<$r;)$l=$t[$r][$c]=$c?$l+$t[$r-1][$c-1]:($l?:1);echo$l;

Try it online!
PHP, 89 bytes
recursive function 0-indexed

function f($r,$s=NULL){$c=$s??$r-1;return$r>1?$c?f($r-1,$c-1)+f($r,$c-1):f($r-1,$r-2):1;}

Try it online!

J, 17 bytes
0{]_1&({+/\@,])1:

Uses the triangle calculation method.
Try it online!
Explanation
0{]_1&({+/\@,])1:  Input: integer n
               1:  The constant 1
  ]                Identity function, get n
   _1&(       )    Call this verb with a fixed left argument of -1 n times
                   on itself starting with a right argument [1]
             ]       Get right argument
       {             Select at index -1 (the last item)
            ,        Join
        +/\@         Find the cumulative sums
0{                 Select at index 0 (the first item)

Python 3, 78 bytes
from math import*
f=lambda n:ceil(sum(k**n/e/factorial(k)for k in range(2*n)))

I decided to try and go a different route for calculation. This uses Dobinski's formula, 0-indexed, doesn't work for 0.
Try it online!

as your function f is not recursive, you can omit the f= and save 2 bytes

Python 3, 68 60 bytes
Simple recursive construction of the triangle, but it's wildly inefficient for practical purposes. Calculating up to the 15th Bell number causes TIO to time out, but it works on my machine.
This uses 1-indexing, and returns True instead of 1.
f=lambda r,c=0:r<1or c<1and f(r-1,r-1)or f(r-1,c-1)+f(r,c-1)

Try it online!

Thanks to @FelipeNardiBatista for saving 8 bytes!

60 bytes. returning booleans instead of numbers (0,1) is acceptable in python

Pari/GP, 36 bytes
n->n!*Vec(exp(exp(x+O(x^n++))-1))[n]

Try it online!

Alice, 22 bytes
/oi
\1@/t&wq]&w.q,+k2:

Try it online!
This uses the triangle method.  For n=0, this calculates B(1) instead, which is conveniently equal to B(0).
Explanation
This is a standard template for programs that take input in ordinal mode, process it in cardinal mode, and output the result in ordinal mode.  A 1 has been added to the template to put that value on the stack below the input.
The program uses the stack as an expanding circular queue to calculate each row of the triangle.  During each iteration past the first, one implicit zero below the stack becomes an explicit zero.
1     Append 1 to the implicit empty string on top of the stack
i     Get input n
t&w   Repeat outer loop that many times (push return address n-1 times)
q     Get tape position (initially zero)
]     Move right on tape
&w    On iteration k, push this return address k-1 times
      The following inner loop is run once for each entry in the next row
.     Duplicate top of stack (the last number calculated so far)
q,    Move the entry k spaces down to the top of the stack: this is the appropriate entry
      in the previous row, or (usually) an implicit zero if we're in the first column
+     Add these two numbers
k     Return to pushed address: this statement serves as the end of two loops simultaneously
2:    Divide by two: see below
o     Output as string
@     Terminate

The first iteration effectively assumes an initial stack depth of zero, despite the required 1 at the top of the stack.  As a result, the 1 ends up getting added to itself, and the entire triangle is multiplied by 2.  Dividing the final result by 2 gives the correct answer.

Mathematica, 5 bytes
Definitely, Mathematica has built-in.
Try it online!
BellB


text:
Code Golfinator-3000
As everyone knows, adding inator-3000 to the end of any noun makes it way cooler. But what else can make a word cooler?
Given an ASCII string as input, output the coolness of the word.
Calculating the coolness
There are 4 elements to calculating the coolness of a word.

The word itself. The base score is the number of capital letters multiplied by 1000
The end number. A number at the end of the word (such as burninator-3000) is added to the base score, but if the number is more than 4 digits, they're being too greedy and the number should be ignored.
The connector. A space before the end number adds 1000, while a hyphen adds 2000, any other symbol, or no symbol at all, has no effect.
The suffix. If the word ends in ator, double the final score. If it ends in inator, triple the score. These are case insensitive.

So for example Burninator-3000 can be calculated as follows:
1 Capital letter - Base Score: 1000
(1000(base) + 3000(number) + 2000(hyphen)) * 3(suffix) = 18000

Testcases
Burninator-3000 -> 18000
Burnator3000 -> 8000
BurNinator 100 -> 9300
BuRnInAtOr-7253 -> 42759
burn -> 0
burn- -> 0
bUrn-1 -> 3001
inator-7 -> 6021
ator 56 -> 2112
burninators 1000 -> 2000
burn_1000 -> 1000
BURNINATOR-9999 -> 65997
burninator 99999 -> 3000
burninator_99999 -> 0
Code Golfinator-3000 -> 21000
inator ator hello world-1000 -> 3000
javaiscool_99999 -> 0
hypen-ated -> 0
1000 -> 1000
-1000 -> 3000
10000 -> 0
-10000 -> 2000
BURN1N470R-3000 -> 11000

Scoring
This is code-golf, so fewest bytes in each language wins!

Test case: inator ator hello world-1000 (or similar)

@TheLethalCoder Added

@Mr.Xcoder not sure what it covers that hasn't already been covered, but it's funny so I'll add it anyway

Ok, now a helpful test case: 9028 and -7282 (Only digits)

Can you have a hyphen in the middle of the string like a space?

added testcase for hyphen in the word, and 2 testcases for only digits and only digits + connector

Isn't burninator 99999 3000 no 1000? Space adds 1000 and tripled for ending in inator.

@TheLethalCoder so it is, good catch!

Can we get digits in the middle of a word, e.g. BURN1N470R-3000?

The output of while(1)printf("A"); is way cooler than your examples ;)

JavaScript (ES6), 138 133 128 bytes
s=>(([,a,b,,c,d]=s.match(/((in)?ator)?((\D?)(\d+))?$/i),s.split(/[A-Z]/).length-1+(c=='-'?2:c==' '))*1e3+(d<1e4&&+d))*(b?3:2-!a)

How?
The number of capital letters is given by:
s.split(/[A-Z]/).length - 1

All other criteria are deduced from the result of the following regular expression, which is split into 4 variables:
/((in)?ator)?((\D?)(\d+))?$/i     criterion  | code                    | outcome
 \_________/  \___/\___/          -----------+-------------------------+----------
      a         c    d            end number | d < 1e4 && +d           | 0 or +d
  \___/                           connector  | c == '-' ? 2 : c == ' ' | 0, 1 or 2
    b                             suffix     | * (b ? 3 : 2 - !a)      | 1, 2 or 3

Test cases

let f =

s=>(([,a,b,,c,d]=s.match(/((in)?ator)?((\D?)(\d+))?$/i),s.split(/[A-Z]/).length-1+(c=='-'?2:c==' '))*1e3+(d<1e4&&+d))*(b?3:2-!a)

let test = s => console.log((s + ' '.repeat(32)).slice(0, 32), f(s));

test("Burninator-3000")               // -> 18000
test("Burnator3000")                  // -> 8000
test("BurNinator 100")                // -> 9300
test("BuRnInAtOr-7253")               // -> 42759
test("burn")                          // -> 0
test("burn-")                         // -> 0
test("bUrn-1")                        // -> 3001
test("inator-7")                      // -> 6021
test("ator 56")                       // -> 2112
test("burninators 1000")              // -> 2000
test("burn_1000")                     // -> 1000
test("BURNINATOR-9999")               // -> 65997
test("burninator 99999")              // -> 3000
test("burninator_99999")              // -> 0
test("Code Golfinator-3000")          // -> 21000
test("inator ator hello world-1000")  // -> 3000
test("javaiscool_99999")              // -> 0
test("hypen-ated")                    // -> 0
test("1000")                          // -> 1000
test("-1000")                         // -> 3000
test("10000")                         // -> 0
test("-10000")                        // -> 2000
test("BURN1N470R-3000")               // -> 11000

Vanilla C, 447 bytes
(Wrapped for readability)
#include<stdio.h>
int main(int c,char**a){char*v=a[1];while(*v++);int m=0,i=
0,bn=0,s=0,b=0,mul=1;char l[256],*lp=l;v--;while(a[1]<v--)
{if(!m){i=!i?1:(i*10),('0'<=*v&&*v<='9')?(bn=bn+i*(*v-'0')
):m++;}if(m==1){(*v=='-'||*v==' ')?(s+=bn?((*v=='-')?2000:
1000):0,v--):0,m++;}if(m==2){(*v>='A'&&*v<='Z')?(s+=1000,*
v+=32):0,*lp++=*v;}}s+=(bn<10000)?bn:0;for(i=0;i<lp-l;i++)
{if(*(l+i)=="rotani"[i]){mul=(i==5)?3:((i==3)?2:mul);}}s*=
mul;printf("%d\n",s);}

...or even... Friday mood!
(I didn't use any tools for alying the code. Actually, I'm really lucky I picked right column widths without any precalculations. And it even compiles!)
Vanilla C, 789 bytes
#include<stdio.h>
int main(int c,     char**a){char       *v=a[1];while      (*v++);int m=0,i=
        0,bn=0,     s=0,     b=0,       mul=1   ;char      l[256],    *lp=l;
          v--;      while  (a[1]<       v--)    {if(!      m){i=!i    ?1:(i*
          10),      ('0'   <=*v&&       *v<=    '9')?      (bn=bn+    i*(*v-
'0')):m++;}if(      m==1)  {(*v==       '-'||    *v==      ' ')?(s    +=bn?(
(*v=='-')?2000      :1000) :0,v--       ):0,m    ++;}      if(m==2     ){(*v
       >='A'&&      *v<=    'Z')?       (s+=    1000,      *v+=32)    :0,*lp
          ++=*      v;}}s  +=(bn<       10000   )?bn:      0;for(i     =0;i<
         lp-l;      i++){  if(*(l       +i)==   "rot"      "ani"[i]   ){mul=
(i==5) ?3: ((i      ==3)?2:mul);}       } s *= mul;        printf("%d\n",s);}

Original code:
#include <stdio.h>
#include <math.h>

int main(int argc, char** argv) {
    char *v = argv[1];
    while(*v++);
    int m=0,i=-1;
    int bonus_number=0;
    int score=0;
    int b=0;
    int mul=1;
    char letters[256];
    char* lp=letters;
    v--;
    while(argv[1]<v--) {
        printf(" * %c %x\n", *v, *v);
        if (m == 0) {
            if ('0'<=*v&&*v<='9') {
                bonus_number=bonus_number+powl(10,++i)*(*v-'0');
                printf("Digit, bonus is now %d\n", bonus_number);
            } else {
                m++;
            }
        }
        if (m == 1) {
            if (*v=='-'||*v==' ') {
                printf("Dash/space\n");
                if (bonus_number) score += (*v=='-') ? 2000 : 1000;
                v--;
            }
            m++;
        }
        if (m == 2) {
            if(*v>='A'&&*v<='Z') {
                printf("Upper letter\n");
                score += 1000;
                *v += 32;
            }
            *lp++ = *v;
        }
    }
    score += (bonus_number<10000)?bonus_number:0;
    for(i=0;i<lp-letters;i++) {
        // printf("%d: %c\n\n", i, *(letters+i));
        if (*(letters+i) == "rotani"[i]) {
            if (i == 3) {
                printf("2x!\n");
                mul = 2;
            }
            if (i == 5) {
                printf("3x!\n");
                mul = 3;
            }
        }
    }
    score *= mul;
    printf("Score: \n%d\n", score);
}

After 1st minimization:
#include <stdio.h>

int main(int c, char** a) {
    char *v = a[1];while(*v++);
    int m=0,i=0,bn=0,s=0,b=0,mul=1;
    char l[256],*lp=l;
    v--;
    while(a[1]<v--) {
        if (!m) {
            i=!i?1:(i*10),
            ('0'<=*v&&*v<='9') ? (bn=bn+i*(*v-'0')) : m++;
        }
        if (m == 1) {
            (*v=='-'||*v==' ') ? (s += bn ? ((*v=='-') ? 2000 : 1000) : 0, v--):0,m++;
        }
        if (m == 2) {
            (*v>='A'&&*v<='Z') ? (s += 1000, *v += 32):0,
            *lp++ = *v;
        }
    }
    s += (bn<10000)?bn:0;
    for(i=0;i<lp-l;i++) {
        if (*(l+i) == "rotani"[i]) {
            mul=(i==5)?3:((i==3)?2:mul);
        }
    }
    s *= mul;
    printf("%d\n", s);
}

Test cases
#!/usr/bin/env python3
import subprocess

TESTCASES = '''
Burninator-3000 -> 18000
Burnator3000 -> 8000
BurNinator 100 -> 9300
BuRnInAtOr-7253 -> 42759
burn -> 0
burn- -> 0
bUrn-1 -> 3001
inator-7 -> 6021
ator 56 -> 2112
burninators 1000 -> 2000
burn_1000 -> 1000
BURNINATOR-9999 -> 65997
burninator 99999 -> 3000
burninator_99999 -> 0
Code Golfinator-3000 -> 21000
inator ator hello world-1000 -> 3000
javaiscool_99999 -> 0
hypen-ated -> 0
1000 -> 1000
-1000 -> 3000
10000 -> 0
-10000 -> 2000
BURN1N470R-3000 -> 11000
'''

TESTCASES = dict(map(lambda x: x.split(' -> '), filter(None, TESTCASES.split('\n'))))

def process(arg):
    return subprocess.Popen(['./a.out', arg], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].strip().split(b'\n')[-1].decode('utf-8')

for key, value in TESTCASES.items():
    assert value == process(key), '"{}" should yield {}, but got {}'.format(
        key, value, process(key)
    )

C#, 322 317 bytes
namespace System.Linq{s=>{var m=Text.RegularExpressions.Regex.Match(s,"(.*?)([- ])?(\\d+)$");string t=m.Groups[1].Value.ToLower(),c=m.Groups[2].Value,n=m.Groups[3].Value;return(s.Count(char.IsUpper)*1000+(n.Length>4|n==""?0:int.Parse(n))+(c==" "?1000:c=="-"?2000:0))*(t.EndsWith("inator")?3:t.EndsWith("ator")?2:1);}}

Try it online!
Full/Formatted Version:
namespace System.Linq
{
    class P
    {
        static void Main()
        {
            Func<string, int> f = s =>
            {
                var m = Text.RegularExpressions.Regex.Match(s, "(.*?)([- ])?(\\d+)$");
                string t = m.Groups[1].Value.ToLower(), c = m.Groups[2].Value, n = m.Groups[3].Value;

                return (
                           s.Count(char.IsUpper) * 1000 +
                           (n.Length > 4 | n == "" ? 0 : int.Parse(n)) +
                           (c == " " ? 1000 : c == "-" ? 2000 : 0)
                        )
                        * (t.EndsWith("inator") ? 3 : t.EndsWith("ator") ? 2 : 1);
            };

            string[] testCases =
            {
                "Burninator-3000", "Burnator3000", "BurNinator 100", "BuRnInAtOr-7253",
                "burn", "burn-", "bUrn-1", "inator-7", "ator 56", "burninators 1000",
                "burn_1000", "BURNINATOR-9999", "burninator 99999", "burninator_99999",
                "Code Golfinator-3000", "inator ator hello world-1000", "javaiscool_99999",
                "hypen-ated", "1000", "-1000", "10000", "-10000"
            };

            foreach (string testCase in testCases)
            {
                Console.WriteLine($"{testCase} -> {f(testCase)}");
            }

            Console.ReadLine();
        }
    }
}

Splitting the regex off into it's own method is now 4 bytes longer (unless I missed something) due to only being allowed one lambda. This it comes in at 321 bytes:
namespace System.Linq{string m(string s,int n)=>Text.RegularExpressions.Regex.Match(s,"(.*?)([- ])?(\\d+)$").Groups[1].Value.ToLower();s=>{string t=m(s,1),c=m(s,2),n=m(s,3);return(s.Count(char.IsUpper)*1000+(n.Length>4|n==""?0: int.Parse(n))+(c==" "?1000:c=="-"?2000:0))*(t.EndsWith("inator")?3:t.EndsWith("ator")?2:1);}}

I don't know if this is legal after that last meta post, but you do believe it is. Wouldn't another function like this b=c=>d=>c.Groups[d].Value save a bit?

@LiefdeWen After the last meta post I believe I'd have to declare it as a full method. I could do string m(string s,int n)=>Text.RegularExpressions.Regex.Match(s,"(.*?)([- ])?(\\d+)$").Groups[n].Value.ToLower();string t=m(s,1),c=m(s,2),n=m(s,3); But I believe that then makes it 3 bytes more.

Perl, 108 bytes
107 bytes code + 1 for -p.
$\+=1e3*y/A-Z//;s/( |-)?(\d+)$//;$\+=$2*($2<1e4);$\+={$",1e3,"-",2e3}->{$1};s/(in)?ator$//i&&($\*=$1?3:2)}{

Try it online!

PHP>=7.1, 165 bytes
preg_match("#((in)?ator)?((\D)?(\d+))?$#i",$argn,$m);[,$a,$i,,$c,$d]=$m;echo($d*($d<1e4)+(preg_match_all("#[A-Z]#",$argn)+($c!="-"?$c==" "?:0:2))*1e3)*($a?$i?3:2:1);

Testcases


text:
Logical Order of Operations
Task
Given an input, evaluate it as a mathematical equation following the order of operations.
But, instead of the using PEMDAS, we drop the parentheses and exponentiation and introduce spaces - SMDAS - spaces, then multiplication & division, then addition & subtraction.
How does that work?
Every operator with more spaces around it gets more precedence - but that can change from one side to the other. Usual precedence test - 2+2*2 still gets evaluated to 6 - so does 2 + 2*2 - which would be spelled out like two .. plus .. two-times-two, but 2+2 *2 or 2+2 * 2 would equal 8 - twoPlusTwo .. times two.
So, from any operator to any side every operator and number with less spaces can be grouped as in parentheses and then calculated as normal.
Alternatively, you can think of it as spaces around operators dropping the operator lower in precedence, or if the spaces are different on each side, drop the precedence on each side differently.
Examples
input = output
2+2*2 = 6
2+2-2 = 2
2+12/6 = 4
228+456/228 = 230
2+0*42 = 2
73-37-96+200 = 140

2+2 * 2 = 8
5*6  +  7*8   -3  *5 = 415
4+4*4+ 4*4-4*2  /  4*4-2 = 2
228+456 /228 = 3
2+2 * 3-6 * 4/2 + 4*3  +  1000 / 5*5 / 5-3  +  1 = 9
2+0 * 42 = 84
5*5 *7-1 = 174

Notes

The input will always be valid - it will always contain at least 2 numbers, separated by a sign (-+/* (for which you may use alternatives such as ∙ or ÷))
The input will never end or start in spaces.
There will never be unary subtraction - -4*-6.
There will never be division by zero.
There may be negative integers in the process but never in the output.
Division is only required to work for integers.
Floating-point inaccuracies at any step of the process are fine.
This is code-golf, shortest answer per language wins!

Is a trailing .0 okay?

@Okx Yeah, and even some .000001 as covered by Floating-point inaccuracies at any step of the process are fine

Could u plz add an intermediate well parenthesize expression for your list of example?

@mdahmoune As the challenge doesn't require to be done with parentheses, I'd say it's not required.

Japt, 15 bytes
OvUr" +%d"_rS'(

Test it online!
How it works
This challenge was practically made for Japt. I shall attempt to explain how:
Japt is basically a shortened version of JavaScript. In fact, after making some changes to the code ("transpiling" to JS), it is evaluated directly as JavaScript. What comes in handy here is that a space in Japt becomes ) in JavaScript (a feature I occasionally regret adding, as it makes it hard to write "ungolfed" Japt code), and missing parentheses are automatically added.
What this all means for this challenge is that we can obtain the correct result simply by changing all spaces after an operator (before a number) to left-parentheses:
5*6  +  7*8   -3  *5    Original string
5*6  +((7*8   -3  *5    Japt code that evaluates to the correct number

When transpiled to JS, the changes mentioned above are made, which results in this:
     5*6  +((7*8   -3  *5    Japt code
(((((5*6))+((7*8)))-3))*5    transpiled JS code

The JS code is then evaluated, which gives the expected result.
OvUr" +%d"_rS'(    Implicit: U = input string
  Ur" +%d"         Replace each match of / +\d/ in U with
          _rS'(      the match with each Space replaced with a '('.
Ov                 Evaluate the result as Japt.
                   Implicit: output result of last expression

Wow, talk about the right language for the job.

V, 59 bytes
òÍ ¨Ä*[+*¯-]©/)±
Í¨[+*¯-]Ä*© /±(ò
Ïò])|é(kòJïò[(Á)jòHDi="

Try it online!
I'm looking into golfing this down more later.  The idea is that it turns spaces on the left of an operator into ) and ( on the right, the surrounds with appropriate () to make all parens match, and calculates the line.  Mostly my regexes need work:
 \(\D*[+*\/-]\)/)\1
\([+*\/-]\D*\) /\1(

JavaScript (ES6), 116 bytes

f=
s=>(s=s.replace(/./g,c=>c>` `?(b=1/c?`)`:`(`,c):b),g=c=>s.split(c).length,eval(`(`.repeat(g`)`)+s+`)`.repeat(g`(`)))
<input><input type=button value=Evaluate onclick=o.textContent=``,o.textContent=f(this.previousSibling.value)><pre id=o>

Changes the spaces into the appropriate brackets, then adds matching brackets on each side (at least one pair of which will be redundant, not that it matters) and evaluates the result.


text:
ASCII reflections in a box
ASCII reflections in a box
You probably all know the Law of Reflection, in this challenge you'll visualize the trajectory of a ball in a box.
Related: ASCII Ball in Box Animation and ASCII Doodling: Laser in a Box
Task
You're given three integer pairs W,H, x,y and dx,dy - the first represents the size of the box, the second the starting position and the third pair is the direction in which the ball starts moving.
The task is to visualize the movement of the ball until it stops rolling, this happens as soon as the ball is at a position that it was before or it hits a corner.
The character * shall visualize the trajectory of the ball and + marks its final position, the rest of the box must consist of  (whitespace).
Examples
To lay it out a bit clearer, in these examples _ will represent a whitespace. Also the intermediate stages are only here for clarification, you'll only need to output the last stage, these examples are 1-indexed.

Given W = 3, H = 5, x = 3, y = 2 and dx = -1, dy = 1:
___    ___    ___    ___
__*    __*    __*    __*
___ -> _*_ -> _*_ -> _+_
___    *__    *__    *_*
___    ___    _*_    _*_

Ball starts at point (3,2) and
moves in direction (-1,1), hits the wall at (1,4) and
gets reflected, new direction is (1,1). It hits the wall again at (2,5)
where it gets gets reflected. The new direction is (1,-1) and it hits the wall immediately at (3,4),
again it gets reflected into the direction (-1,-1). It would now travel through points (2,3),(1,2), reflected etc. but since it already visited the position (2,3) it stops there.

This example demonstrates, what happens if a ball hits a corner. For this let W = 7, H = 3, x = 1, y = 3 and dx = 1, dy = -1:
_______    __*____    __*____    __*___+
_______ -> _*_____ -> _*_*___ -> _*_*_*_
*______    *______    *___*__    *___*__

Start position is (1,3),
the ball now travels in direction (1,-1) until it hits the wall at (3,1)
where it gets reflected into the new direction (1,1).
At (5,3) it gets reflected and travels into the new direction (1,-1). It comes to an abrupt stop at (7,1) because that's a corner.

Given W = 10, H = 6, x = 6, y = 6 and dx = 1, dy = 1:
__________    __________    ________*_    ________*_    ________*_    __*_____*_    __*_____*_
__________    _________*    _________*    _______*_*    _______*_*    _*_____*_*    _*_*___*_*
__________ -> ________*_ -> ________*_ -> ______*_*_ -> *_____*_*_ -> *_____*_*_ -> *___*_*_*_
__________    _______*__    _______*__    _____*_*__    _*___*_*__    _*___*_*__    _*___+_*__
__________    ______*___    ______*___    ____*_*___    __*_*_*___    __*_*_*___    __*_*_*___
_____*____    _____*____    _____*____    ___*_*____    ___*_*____    ___*_*____    ___*_*____

Input specification
The input consists of the three integer pairs W,H, x,y and dx,dy, you may take input in any format that makes most sense for your programming language and the order doesn't matter. However the accepted input must not encode more information than these pairs contain (see this answer for an example).

W,H >= 1
x,y are either 1-indexed (1 <= x <= W and 1 <= y <= H) or 0-indexed (0 <= x < W and 0 <= y < H), please specify what indexing you chose
dx,dy are always either -1 or 1

Invalid input can be ignored.
Output specification

No leading whitespaces are allowed
Trailing whitespaces may be omitted
Trailing whitespaces are not allowed if they don't fit the box
Trailing newlines (after all output related lines) are allowed

Let's take the first example:
       (good by 2)
__*
_+     (good by 2)
*_*_   (bad by 3)
       (bad by 4)
_*_
       (good by 4)

Test cases
Assuming the input has the format (W,H,x,y,dx,dy) and 1-indexing was chosen, here are some test cases (again _ is here to represent whitespaces!):
Input: 1,1,1,1,1,1
Output:
+

Input: 3,3,3,3,1,1
Output:
___
___
__+

Input: 3,3,3,3,-1,-1
Output:
+__
_*_
__*

Input: 7,3,1,3,1,-1
Output:
__*___+
_*_*_*_
*___*__

Input: 10,6,6,6,1,1
Output:
__*_____*_
_*_*___*_*
*___*_*_*_
_*___+_*__
__*_*_*___
___*_*____

Input: 21,7,6,4,-1,-1
Output:
__*_______*_______*__
_*_*_____*_*_____*_*_
*___*___*___*___*___*
_*___*_*_____*_*___*_
__*___*_______+___*__
___*_*_________*_*___
____*___________*____

This is code-golf, so the shortest program/function wins, but any effort is appreciated.

I suspect one of the 2D languages (Turtle?) might do really well with this challenge.

Would it be allowed to encode the four possible dx/dy values as four consecutive odd integers? How important is it that x and y are 1-indexed?

I'll drop the 1-indexed constraint if you like(?) About that first question, not sure what you mean but it sounds ok. I guess anything that is a bijection ({-1,1}x{-1,1} ≡ "Your space") would be good.

Edited in the indexing, can you be more specific on your other question?

I want to see a charcoal answer for this lol.

See my answer for what I meant about encoding dx and dy. @MagicOctopusUrn Your wish is my command!

Yeah, I don't see a problem with that.

Charcoal, 50 bytes
ＵＯＮＮ ＪＮＮ↷ＮＷ⁼ ＫＫ«*¿¬ＫＫ«↷²¶*¿¬ＫＫ«↷²¶↷²*¿¬ＫＫ«↷²¶»»»»+

Try it online! Link is to verbose version of code. Takes five inputs: w, h, x, y, a. x and y are zero-indexed. a represents dx and dy according to the following encoding:
a mod 8 == 1 => dx = 1, dy = 1
a mod 8 == 3 => dx = -1, dy = 1
a mod 8 == 5 => dx = -1, dy = -1
a mod 8 == 7 => dx = 1, dy = -1

Explanation:
ＵＯＮＮ

(note trailing space) Fills the background with spaces to the input width and height. (Normally each square of the background is an empty string, which is then converted to a space on output.)
ＪＮＮ

Moves the cursor to the initial coordinates.
↷Ｎ

Rotates to the initial angle.
Ｗ⁼ ＫＫ«

Repeats as long as the current square is a space.
    *

Prints an asterisk and moves forward in the current direction.
    ¿¬ＫＫ«

If the cursor moved outside of the original oblong,
        ↷²¶*

Rotate the direction, then print a newline (which conveniently takes us back to the previous square) and an asterisk, which moves in the new direction.
        ¿¬ＫＫ«

If the cursor moved back outside of the original oblong,
            ↷²¶↷²*

Take the cursor back to the previous square, then rotate again, thus printing the asterisk in the other direction.
            ¿¬ＫＫ«

If the cursor is still outside of the oblong, we must be at a corner.
                ↷²¶

So go back to the previous square and give up.
»»»»+

When we can't move any more, print a "+" sign and stop.

Nice! Here's a TIO for those that want to try it.

@BruceForte Thanks, but I didn't want to link to TIO until I had a solution using Peek() (which I do now).

Oops, Peek works again now

Desmos Calculator - Non Competing to Help Further Knowledge
Try it online!
Inputs:
X as X position to Start
Y as Y position to Start
s as slope -> -1 for dX/dY = -1, +1 for dX/dY = +1
h as height of box, with 0-indexing
w as width of box, with 0-indexing

Intermediates:
Let b = gcd(h,w),
Let c = |b-(X-sY)%2b| Or |b-mod(X-sY,2b)|

gcd(h,w) represents the greatest common denominator
A % B, as in Javascript, or mod(A,B), as in Fortran, represents the modulus operation, on the interval [0,B).

Formula, abbreviated:
(|b-(x+y)%2b|-c)(|b-(x-y)%2b|-c)=0

Outputs:
x as x position, 0-indexed, where the ball will land when released
y as y position, 0-indexed, where the ball will land when released

How it Works:
(|b-(x+y)%2b|-c)*(|b-(x-y)%2b|-c)=0
                ^ OR operation - |b-(x+y)%2b|-c=0 or |b-(x-y)%2b|-c=0
|b-(x+/-y)%2b|-c = 0
|b-(x+/-y)%2b| = c
|b-(x+/-y)%2b| = c means (b-(x+/-y))%2b = + or -c
b-(x+/-y)%2b = +/- c -> b +/- c = (x+/-y)%2b -> (x+/-y) = n*2*b + b +/- c
Where n is integer.  This will force patterns to repeat every 2b steps in x and y.
Initial pattern n=0: (x +/- y) = b +/- c -> y = +/- x + b +/- c
In the x positive and y positive plane only, these correspond to lines of positive and
negative slope, set at intercept b, offset by c on either side.

Program fails to meet final criterion - stopping at intersection point and marking with a +, so is submitted as non-competitive for information to help others complete the challenge.  Note that to get Desmos to work when c = 0 or c=b, a small offset factor of 0.01 was introduced, as Desmos seems to have bounds of Mod(A,B) of (0,B) instead of [0,B)

I suppose you have seen this?

Actually, I self nerd sniped and lost about 4 days of my at-home time.  I really, really liked this problem.

You're welcome ;P Also, relevant.

Python 3, 293 279 bytes
w,h,x,y,i,j=map(int,input().split());x-=1;y-=1;l=[x[::]for x in[[' ']*w]*h]
while 1:
 a,b=((x,i)in[(0,-1),(w-1,1)]),((y,j)in[(0,-1),(h-1,1)])
 if a and b or l[y][x]!=' ':l[y][x]='+';break
 i,j=i*(-a*2+1),j*(-b*2+1);l[y][x]='*';x+=i;y+=j
print('\n'.join([''.join(x) for x in l]))

Try it online!

Nice! You can save a few bytes by shortening fx,fy and replacing True by something like 1, see here

@BruceForte thanks! I forgot to replace these.

-13 bytes by turning it into a function.

Wait, just seen how old this question is... Yet I got here from HNQ...