text:
Alternating Pattern
In a now deleted stackoverflow question, someone posted the following:
Write a program or function to print alternating patterns in * and # based on a given integer n. Some examples:
Input: n=1
Output:
*

Input n=5
Output:
*####
###**
***##
###**
*####

Input: n=8
Output:
*#######
######**
***#####
####****
****####
#####***
**######
#######*

Since it looked like a pretty cool code-golfing challenge, here it is.
How are these patterns build?
The first line starts with a single *, followed by n-1 amount of trailing #.
The second line then contains two *, with n-2 amount of leading #.
The third line starts with three *, followed by n-3 amount of trailing #.
etc.
Once we've reached the middle (n/2), we count back again with the amount of *, which can be seen in the examples above.
NOTE that for odd input numbers the inversed pair of lines (so first and last; second and next to last; etc.) are exactly the same. In the n=5 example the first and last lines are *####; the second and next to last lines are ###**.
For even input numbers however the inversed pair of lines are reversed. In the n=8 example the first and last lines are *####### and #######*; the second and next to last lines are ######** and **######; etc.
Challenge rules:

You can use any two distinct printable characters instead of * and #. You can use A and B; 3 and 7; < and >; etc. Please state in your answers what you've used.
You can assume n will be a positive integer (>= 1)
You are allowed to output a list/array of strings for each line or a 2D matrix of characters, instead of printing them to STDOUT.

General rules:

This is code-golf, so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
Standard rules apply for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
Default Loopholes are forbidden.
If possible, please add a link with a test for your code.
Also, adding an explanation for your answer is highly recommended.

Test cases (first n=1 through n=10)
*

*#
#*

*##
#**
*##

*###
##**
**##
###*

*####
###**
***##
###**
*####

*#####
####**
***###
###***
**####
#####*

*######
#####**
***####
###****
***####
#####**
*######

*#######
######**
***#####
####****
****####
#####***
**######
#######*

*########
#######**
***######
#####****
*****####
#####****
***######
#######**
*########

*#########
########**
***#######
######****
*****#####
#####*****
****######
#######***
**########
#########*

"You can use any two distinct characters instead of * and #." - Do they have to be printable? Can we use NUL and SOH (ASCII codes 0 and 1)?

@ngn Sorry, printable characters only. Will clarify in the challenge description.

Jelly, 9 bytes
>þµoṚUÐeY

Try it online!
Explanation
>þ           Create a table of (x>y) over [1…n]×[1…n]:
               [0 1 1 1 1]
               [0 0 1 1 1]
               [0 0 0 1 1]
               [0 0 0 0 1]
               [0 0 0 0 0]
  µ          Take this array, and...
   oṚ        OR it with its reverse:
               [0 1 1 1 1]
               [0 0 1 1 1]
               [0 0 0 1 1]
               [0 0 1 1 1]
               [0 1 1 1 1]
    UÐe      Apply U (reverse) to even-indexed rows.
       Y     Join by newlines.

Python 2, 62 bytes
lambda n:["%*s"%(i%2*2*n-n,"x"*min(i+1,n-i))for i in range(n)]

Try it online!
Uses x and space.
The rows are computed like this:
"%-5s" % "x"      == "x    "
"%5s"  % "xx"     == "   xx"
"%-5s" % "xxx"    == "xxx  "
"%5s"  % "xx"     == "   xx"
"%-5s" % "x"      == "x    "

Using the %*s specifier to choose between n and -n.

APL (Dyalog Classic), 18 bytes
⎕a[↑⊢∘⌽\(⊂>⊢⌊⌽)⍳⎕]

Try it online!
outputs AB instead of *#
⎕ evaluated input n
⍳⎕ the vector 0 1 ... n-1
⊢⌊⌽ min (⌊) between themselves (⊢) and their reverse (⌽) - see trains
⊂>⊢⌊⌽ where is the ⍳ vector as a whole (⊂) less than each of its ⊢⌊⌽ - return a vector of boolean (0/1) vectors
⊢∘⌽\ reverse every other vector
↑ mix into a matrix
⎕a the uppercase English alphabet, 'AB...Z'
⎕a[ ] replace 0 1 with 'A' 'B'

Out of curiosity. How many bytes would it be to simply output the matrix of 0s and 1s without spaces? I'm assuming ⎕a[...} converting them to A and B without spaces is shorter than keeping them as 0 and 1 without spaces considering you've used that, but just curious if there is much difference in bytes if you keep them as 0 and 1.

@KevinCruijssen As far as I can golf, it would be the same length - either ⎕d[...] or ⊃¨⍕¨... In the latter expression ⍕¨ is "format each" - it turns each number into a nested char vector, so we need "first each" (⊃¨) to get only char scalars (and therefore no whitespace when printing).

Perl 6, 57 bytes
{map ^$^a: {fmt -$a*(-1)**$_=>\*x($_+1 min$a-$_): "%*s"}}

Try it online!
Uses the same method as Lynn's Python answer. Outputs using * and space.

MATL, 34 31 18 bytes
:t!>tPY|!"@X@oQ&P!

Try it on MATL Online
Uses 0 for * and 1 for #. Based on Lynn's Jelly answer.

Older answer, 31 bytes:
2/tk:wXk:Ph"X@ot~XHh@Gy-hHQ&PY"

Try it on MATL Online
Uses 1 for * and 0 for #.
         % implicit input, say 5
2/       % divide input number by 2 [2.5]
tk       % make a copy and floor that [2.5, 2]
:        % create range 1 to the floored value [2.5, [1, 2]]
wXk      % bring out the division result and this time ceil it
         %  [[1, 2], 3]
:        % create range 1 to that [[1, 2], [1, 2, 3]]
Ph       % flip the last array and concatenate horizontally
         %  [[1, 2, 3, 2, 1]]
"        % loop through the array
  X@o    % Is the current loop index odd? 1 for odd, 0 for even
  t~     % duplicate and logical negate that
  XH     % copy that value to clipboard H
  h      % and concatenate the values ([1 0] on odd iterations, [0 1] on even)
  @      % push current value from array (say 2, then stack is [[0 1], 2)
  G      % push input again
  y-     % subtract current array value from input [[0 1], 2, 3]
  h      % concatenate those two [[0 1], [2, 3]]
  H      % get the stored value from clipboard H (1 for even iterations, 0 for odd)
  Q      % increment that
  &P     % flip the array in that dimension: in even iterations, this flips
         %   across columns and hence inverts the two values. [[0 1], [3, 2]]
         %   in odd iterations, it's a no-op
  Y"     % run-length decoding - repeat the element from first array the number of times
         %  specified in the second array
         % implicit loop end, implicit output

Jelly,  12  15 bytes
+3 fixing n=1 edge-case bug :(
R«Ṛ$‘r⁸ṬUÐe0YE?

A full program accepting an integer which prints the output as defined in the OP using 0 and 1 for * and # respectively.
Try it online!
How?
R«Ṛ$‘r⁸ṬUÐe0YE? - Main Link: integer, n
R               - range -> [1,2,3,4,...,n]
   $            - last two links as a monad:
  Ṛ             -   reverse -> [n,...,4,3,2,1]
 «              -   minimum (vectorises) -> [1,2,3,4,...,4,3,2,1]
    ‘           - increment (vectorises) -> [2,3,4,5,...,5,4,3,2]
      ⁸         - chain's left argument, n
     r          - inclusive range (vectorises) -> [[2,3,...,n],[3,4,...n],[4,5,...n],[5,...n],...,[5,...n],[4,5,...n],[3,4,...n],[2,3,...,n]]
       Ṭ        - untruth (vectorises) -> [[0,1,1,...,1],[0,0,1,1,...,1],[0,0,0,1,...,1],[0,0,0,0,1,...,1],...,[0,0,0,0,1,...,1],[0,0,0,1,...,1],[0,0,1,1,...,1],[0,1,1,...,1]]
         Ðe     - apply to entries with even indices:
        U       -   upend              -> [[0,1,1,...,1],[1,1,...,1],[0,0,0,1,...,1],[1,...,1,0,0,0,0],...]
              ? - if...
             E  - ...condition: all equal? (only true when n=1, where we have [1,1])
           0    - ...then: zero
            Y   - ...else: join with newline characters
                - implicit print

It looks like this is exactly my algorithm, but a different implementation which outputs 0s instead of 1s and vice versa.

Yes effectively the same thing ...and I hadn't updated my post to show the fix I made.

Charcoal, 21 bytes
≔⮌…⁰ＮθＥθ⭆θ›§⟦μλ⟧κ⌊⟦κι

Try it online! Uses 0 and 1. Link is to verbose version of code and includes §*# which translates the output to the * and # in the question. Explanation:
    Ｎ                   Input number
  …⁰                    Range from 0
 ⮌                      Reversed
≔    θ                  Assign to `q`
      Ｅθ                Map over reversed range
        ⭆θ              Map over reversed range and join
           §⟦μλ⟧κ       Alternate between range and reversed range column
                 ⌊⟦κι   Minimum of range and reversed range row
          ›             Greater
                        Implicitly print each row on its own line

Jelly, 15 bytes
r1«RR;ṬṖɗ€‘UÐeY

Try it online!
Full program.
* = 1
# = 0

Java 10, 145 bytes
n->{var r=new char[n][n];for(int j=0,k;j<n;++j)for(k=0;k<n;)r[j][k]=k++<(j<n/2?j%2<1?j+1:n+~j:j%2>0?j:n-j)?j%2<1?'*':'#':j%2>0?'*':'#';return r;}

All the ternary makes it a bit messy, but it works fine. I tried flattening the nested loop, and various other things, but they only increased the byte count. Try it online here.
Ungolfed:
n -> { // lambda taking an integer as output and returning a char[][]
    var r = new char[n][n]; // the output array; we make use of Java 10's var here (replace with char[][] for another 4 bytes to make this work in Java 8)
    for(int j = 0, k; j < n; ++j) // iterate over the lines
        for(k = 0; k < n; )       // iterate over the j'th line
            r[j][k] = // set the current character
                      k++ < // determine if we're in the first or second portion of the line:
                            (j < n/2 ? // for the first half of the output:
                                 j%2 < 1  // on even lines ...
                                 ? j + 1  // ... print the first symbol j+1 times ...
                                 : n + ~j // ... on odd lines, print it n-j-1 times.
                             : j%2 > 0 ?  // for the second half of the output, on odd lines ...
                                 j :      // ... print the first symbol j times ...
                                 n - j)   // ... on even lines, print it n-j times.
                      ? j%2 < 1 ? '*' : '#'  // for the first part of the line, use '*' on even lines, '#' otherwise
                      : j%2 > 0 ? '*' : '#'; // for the second part of the line, use '*' on odd lines, '#' otherwise
    return r; // return the completed array
}

Java 8 11, 179 127 bytes
n->{String r="",a,b;for(int j=0;j<n;b="#".repeat(j<n/2?n+~j:j),r+=(j++%2<1?a+b:b+a)+"\n")a="*".repeat(j<n/2?j+1:n-j);return r;}

Try it online here (TIO does not have Java 11 yet, so this uses a custom method that results in the same byte count as String#repeat()).
Thanks to Kevin Cruijssen for golfing a whopping 52 bytes!
Ungolfed:
n -> { // lambda taking an int argument and returning a String
    String r = "", // the output String
           a,      // temporary String containing the '*'s
           b;      // temporary String containing the '#'s
    for(int j = 0; j < n; // loop over the lines
        b = "#".repeat( // repeat the '#' character ...
            j < n/2 ? n + ~j // ... n-j-1 times in the first half of the output ...
            : j), // ... j times in the second half
        r += (j++ % 2 < 1 ? a + b : b + a) + "\n") // assemble the j'th line and append it to the output: on even lines, the '*'s go first; on odd lines, the '#'s go first
        a = "*".repeat( // repeat the '*' character ...
              j < n/2 ? j + 1 // ... j+1 times in the first half of the output ...
              : n - j); // n-j times in the second half
    return r; // return the completed output
}

If you change to Java 11 you can golf it to 127 bytes by using "*".repeat(...) and "#".repeat(...) (as well as returning a String instead of printing directly and golfing n-j-1 to n+~j): n->{String r="",a,b;for(int j=0;j<n;b="#".repeat(j<n/2?n+~j:j),r+=(j++%2<1?a+b:b+a)+"\n")a="*".repeat(j<n/2?j+1:n-j);return r;}

Thanks, that's a great saving in bytes. I have managed to create a 145-byte version for Java 10 using nested loops – can't wait for the release of Java 11, that repeat() method is really nice for golfing.

Lua,  148  133  Bytes
function(n)t,a,b={},".","#"for i=1,n do r=i<n/2+1 and i or-~n-i s=a:rep(r)..b:rep(n-r)t[i]=i%2<1 and s:reverse()or s end return t end

Try it online!
-15 bytes thanks to @KevinCruijssen and @JoKing.
function(n)
   t = {}; a = "."; b = "#"          -- initialize variables, output is in table
                                     -- strings are needed in variables for
                                     --   the str:rep and str:reverse syntax

   for i = 1, n do                          -- build the rows of the table
      r = i<=(n+1)/2 and i or n-i+1         -- logic used to count up then down
      str = a:rep(r)..b:rep(n-r)            -- append correct number of '.'s, fill
                                            --   in the rest with '#'s
      t[i]=i%2==0 and str:reverse() or str  -- logic used to control reversing
   end
   return t                                 -- return table
end

I don't know Lua too well, but it seems you can save five bytes: (n+1)/2 to -~n/2; or n-i+1 to or-~n-i; i%2==0 to i%2<1; and reverse() or to reverse()or. Also, your TIO version and byte-count both contain a trailing semi-colon which doesn't seems to be necessary. Nice first answer, though. +1 from me. And welcome to PPCG! :)

You actually don't need any of the semi-colons. 133 bytes including Kevin's suggestions.

@KevinCruijssen Thanks! Could I ask what the -~n is doing in your suggestions? It definitely works, but I don't understand why.

@AzureHeights Sure. ~ is a unary bitwise negation operator. What's important for codegolfing however, is that ~i holds the same value as -i-1. We can therefore use -~i instead of i+1 and ~-i instead of i-1. This is useful in two cases, which I could both utilize in your answer: getting rid of parenthesis, because - and ~ have operator precedence over other mathematical operations, so (n+1)/2 can therefore be -~n/2. And the other useful part is to get rid of spaces in some cases, as I did with or-~n-i.

Here are the two relevant tips if you want to read a bit more about it: Use unary ~ for x+1 and x-1 and Use unary ~ for a-b-1 and a+b+1. All general tips, as well as language specific tips (Tips for golfing in Lua in this case), might be interesting to read through. :)

Kotlin, 86 bytes
{n:Int->for(i in 0..n)println("%${i%2*2*n-n}s".format("x".repeat(Math.min(i+1,n-i))))}

Try it online!
Uses x and space as output symbols. Derivates from Lynn Answer

C (gcc), 104 99 bytes
h,j,k;f(i){char s[h=i++];for(j=0;k=++j>i/2?i-j:j,j<i;memset(memset(s,42,h)+j%2*k,35,h-k),puts(s));}

Try it online!

Perl 5 + -pa -MPOSIX -M5.010, 58 bytes
say+sort{$|--}1x abs,2x("@F"-abs)for(1..ceil$_/=2),-$_..-1

Try it online!

C (gcc), 118 108 bytes
This one isn't going to win, but it's  a different approach (or at least, I think so!) Instead of doing string manipulations, I make use of the fact that \$10^x-1\$ over \$[1..n] = \{9, 99, 999, ...\}\$, which then can be multiplied to get the appropriate pattern; printf() then does the zero-padding for right-justification.
Sadly, int only has sufficient range to do up to 9 digits (on 32-bit platforms), so you need to go to long for larger patterns; a language that natively does MP arithmetic might be able to use this for something.
Thanks to ceilingcat for the suggestion.
h,j,k;p(h){h=h?10*p(--h):1;}f(i){for(j=0,h=i++;k=++j>i/2?i-j:j,j<i;printf("%0*d\n",h,~-p(k)*p(j%2*(h-k))));}

Try it online!

Proof of concept that this works with MP arithmetic:
C# (Mono C# compiler), 187 165 bytes
(143 bytes + 22 bytes for the using System.Numerics; in the header)
q=>{var r="";for(int j=0,h=q+1,k;j<q;r+=((BigInteger.Pow(10,k)-1)*BigInteger.Pow(10,j%2*(q-k))).ToString("D"+q)+"\n")k=++j>h/2?h-j:j;return r;}

Try it online!

Proof of concept with numbers outside of the maximum native integer ranges (using C# and BigIntegers): Try it online!

Vim, 99 keystrokes
It's always interesting to try to do vim with input arguments. It's very unnatural, so it's not going to be amazingly short. There probably are other good approaches to this.
Input is assumed to be by itself in a buffer. Registers are assumed to be empty. Editor is assumed to be tall enough to contain the result without scrolling (this could technically be avoided at the cost of some keystrokes).
"nD@ni<cr><esc>MmaGddM
<c-v>'aI*<esc>qwgvjokoI*<esc>@wq@w<esc>
:set ve=all<cr>@nlh<c-v>@nkr#
:%s/ /#/g<cr>o<esc>
2Gqqdt#$p2j0@qq@q

Explanation
 | Buffer state (odd and even case):
 | 5                    6

"nD              read input into register n
@ni<cr><esc>     add n newlines
MmaGddM<c-v>'a   visual block select center row(s)
I*<esc>          prepend a column of *
qw               record macro w
  gvjoko         expand selection up and down
  I*<esc>
  @w             recurse
q
@w<esc>          run macro w and exit visual block select

 | Buffer state:
 | *                    *
 | **                   **
 | ***                  ***
 | **                   ***
 | *                    **
 |                      *

:set ve=all<cr>  move anywhere!
@nlh<c-v>@nkr#   add last column of #s

 | Buffer state:
 | *   #                *    #
 | **  #                **   #
 | *** #                ***  #
 | **  #                ***  #
 | *   #                **   #
 |                      *    #

:%s/ /#/g<cr>      replace spaces with #

 | Buffer state:
 | *####                *#####
 | **###                **####
 | ***##                ***###
 | **###                ***###
 | *####                **####
 |                      *#####

o<esc>2G           prep and jump to line 2
qqdt#$p2j0@qq@q    (effectively) flip every other onward

 | Buffer state:
 | *####                *#####
 | ###**                ####**
 | ***##                ***###
 | ###**                ###***
 | *####                **####
 |                      #####*

And in base64, with actual characters (put input in input and keystrokes in keys and run using vim -u NONE -s keys input)
Im5EQG5pDRtNbWFHZGRNFidhSSobcXdndmpva29JKhtAd3FAdxs6c2V0IHZlPWFsbA1AbmxoFkBua3IjOiVzLyAvIy9nDW8bMkdxcWR0IyRwMmowQHFxQHE=

R, 75 bytes
function(n)outer(1:n,1:n,function(x,y,a=x<y|x>n-y+1)+ifelse(x%%2,a,rev(a)))

Try it online!

Inspired by @Lynn answer
function getting n as parameter and returning a matrix of 0/1 where 0 corresponds to '*' and 1 corresponds to '#'

K (ngn/k), 22 bytes
{"*#"i|:/'i>/:i&|i:!x}

Try it online!
{ } function with argument x
!x the list (0;1;...;x-1)
i: assign to i
i&|i minima (&) of i and its reverse (|)
i>/: compare with greater than (>) i against each element from the list on the right (/:) - return a boolean matrix (list of lists)
i|:/' for each (') j in i, reverse (|: - we need the : to force | to be unary) the corresponding element j times (n f/ x applies f n times on x). Effectively, reverse every other row.
"*#" use matrix elements as indices in the string "*#"

Python 3, 251 bytes
n = int(input())

for i in range(1,n+1):
  if i%2 != 0:
    for j in range(1,n-i+2):
      print("*",end=" ")

  for j in range(1,i+1):
    print("#",end=" ")

  if i%2 == 0:
    for j in range(1,n-i+2):
      print("*",end=" ")

  print()

Try it online!

Welcome to Code Golf, and nice first answer! Be sure to check out our Tips for golfing in Python page for ways you can golf your program. I've edited your answer slightly to include a link to an online testing environment and to improve the formatting. It looks like you can remove a lot of whitespace to save bytes: Try it online!


text:
White Elephant Exchange
It's Christmas in July, so what better way to celebrate than a virtual white elephant gift exchange!
For this King of the Hill challenge, you must create a bot that plays in a White Elephant exchange simulation, trying to get the highest-valued present it can.
Game Rules

The game will be played over many rounds, each made up of a variable number of turns.
Round Setup: There will be as many presents as there are players in the game, each valued randomly uniformly in the range [0...1), with this value being unknown until the present is "opened". Players will be put in a random order in a queue. The first player will be popped from the front of the queue.
When it is a player's turn, they may either open a present or steal another player's present, passing turn to the player whose present was stolen.

Each present may be stolen up to 3 times.
You cannot steal from the player that just stole from you.
Each player can only have one present at a time.

After a present is opened, play advances to the next player popped from the front of the queue. This will be the next player in turn order who has not yet had a turn.
Round End: When all presents have been opened, the round ends, and the value of the present held by each player is added to that player's score. A new round begins, with each player now holding no present and the player order shuffled.
Game End: The game will end when at least one player has at scored 100 500 points, with victory being awarded to the player with the highest total value of presents.

Coding
All submissions should be compatible with Python 3.7. You must write a class that directly inherits from WhiteElephantBot. For instance:
class FooBot(WhiteElephantBot):
    # Your implementation here

You may provide an __init__ method (which takes one argument, name) in your bot class, which must call super().__init__(name). Your class must have a take_turn method expecting the following arguments in this order:

players: The list of player names, in turn order, of all players that do not yet have presents.
presents: A dictionary that maps player names to 2-tuples containing the present value held by that player and the number of times that present has been stolen. This will only include other players who are currently holding presents.
just_stole: If the last action taken was a steal, this will be the name of the player who just stole. If not, it will be None.

Each argument will be immutable or a new object so that mutating any of them will not have an effect on the game. You may keep a copy of any of the arguments if you so desire.
An example value for presents:
{
    'Alice':   (0.35, 0),
    'Bob':     (0.81, 2),
    'Charlie': (0.57, 1)
}

Your take_turn method should return the name of the player you wish to steal from or None to open a present. If it raises an exception, returns something other than a str or None, or the name of a player you cannot steal from, you will open a present by default.
Your constructor will be called at the beginning of each round, so you do not get to remember state from round to round.
By inheriting from WhiteElephantBot, you will have access to a steal_targets method that will take the presents dict and just_stole and return a list of names of players you can steal from.
Any modules your script needs must be imported at the top of your entry.
Test Driver
The test driver can be found here. You do not need to include from white_elephant import WhiteElephantBot in your posted answer, however a local module will need to do that.
Baseline Competitors

Random: Chooses randomly whether to open a new present or to steal, with the steal target chosen uniformly randomly.
Greedy: steal the most valuable present that can be stolen. If no presents can be stolen, open a present.
Nice: Always opens a new present. Never steals.

Additional Rules

It is your responsibility to catch all exceptions. If your class fails to catch an exception, it will be disqualified. In addition, please do not catch KeyboardInterrupts.
Do not use files or other methods to bypass the inability to save state between games. You may not, for instance, save a neural network state to a file mid-run.
Your bot must be self-contained within class code and related constants.
You may only use standard library imports.
There is no strict performance requirement. Be reasonable and prudent. If performance becomes an issue, I reserve the right to add time limits.
One entry per person. If you submit more than one entry, your bots may not work together. I'm going to allow multiple entries per person for now, though I may reban it later if it becomes a problem.
This is an open competition with no distinct end date. It will be rerun any time I am able when there have been significant changes.

EDIT1: Changed winning score from 100 to 500 so that rankings are more consistent. The test driver has a new bugfix and also reflects the win score changes.
EDIT2: Clarifying note on required imports.

Leaderboard (as of Aug 8, 2018)

SampleBot            (500.093)
LastMinuteBot        (486.163)
RobinHood            (463.160)
OddTodd              (448.825)
GreedyBot            (438.520)
SecondPlaceBot       (430.598)
ThresholdBot         (390.480)
Gambler              (313.362)
NiceBot              (275.536)
RandomBot           (256.172)
GoodSamaritan       (136.298)

Can there be any number of steals in a row? When I have played, usually there is a limit of 2 steals in a row or something, and the third person from would have to open one. This prevents the same gift from being stolen more than once per turn.

@mbomb007 Yes. Chain-stealing is unlimited, except by the other rules that make certain presents immune to stealing: each present can only be stolen 3 times and you can't steal from the player who just stole from you.

Can you steal a present and then re-steal the original one you had?

@EriktheOutgolfer: yes, as long as there was another turn in between. You just can't re-steal immediately after your present is stolen.

No, I meant something like 1) Steal most valuable present 2) Check if now there's something more valuable 3) If so, steal again 4) Open, and let next turn to come.

Why only one entry per person? I have several fundamentally distinct ideas, and I'd rather not have to throw out old ones to implement something new.

@EriktheOutgolfer Once you steal the most valuable present, its no longer your turn to choose, so that doesn't work. The player (bot) that just had its present stolen takes another turn.

@Mnemonic: one of the big issues is that you can make multiple bots work together. Since each bot present affects the metagame, you can use different bots to make one of your others do better. Maybe that's not a real problem. I'll have to think about it.

Yankee swap!? What's next, a shared birthday party?

It would be nice to know how many rounds you had to play before one bot reached 500 points

@Heiteira That's a good idea. I'll think about it. I think it might also be good to run games until there is a clear winner, but I don't really know the best way to determine that statistically.

LastMinuteBot
(With big thanks to @Mnemonic for the skeleton of the code, since I barely know Python.)
class LastMinuteBot(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):
        targets = self.steal_targets(presents, just_stole)
        if len(targets) <= 1:
            return None

        target = None

        # If most of the presents are already distributed, try to steal an
        #  un-restealable gift of high value
        if len(presents) > (len(players) + len(presents)) * 0.75:
            at_threshold = [t for t in targets if presents[t][1]==2 and presents[t][0]>=0.8]
            if at_threshold:
                target = max(at_threshold, key=lambda x: presents[x][0])

        # Otherwise, take the best available
        if not target:
            target = max(targets, key=lambda x: presents[x][0])

        return target if presents[target][0] > 0.5 else None

Take advantage of the fact that gifts can't be stolen more than thrice, do the third stealing yourself if you find a high value gift and most presents have been opened.

Simple, yet beautifull

Odd Todd
class OddTodd(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):

        targets = self.steal_targets(presents, just_stole)

        # if none to steal, pick present
        if len(targets) <= 1:
            return None

        # steals the best gift that he can, as long as he's the 1st/3rd steal
        targets = [t for t in targets if presents[t][1] % 2 == 0]
        if targets:
            return max(targets, key=lambda x:presents[x][0])

        else:
            return None

Steals the best gift that he can, but doesn't want to be the second person to steal a gift, because if it gets stolen from him he can't get it back.

Syntax error on line 11. You need a == instead of a = in your list comprehension.

fixed, thanks! Don't use Python much.

SecondPlaceBot
class SecondPlaceBot(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):
        targets = self.steal_targets(presents, just_stole)
        if len(targets) <= 1:
            return None

        # If most of the presents are already distributed, take the second best.
        if len(presents) > (len(players) + len(presents)) * 0.8:
            target = sorted(targets, key=lambda x: presents[x][0])[-2]
        # Otherwise, take the best and hope someone steals it later.
        else:
            target = max(targets, key=lambda x: presents[x][0])

        return target if presents[target][0] > 0.5 else None

Everyone's going to be fighting for the most valuable gift.  The next best gift is almost as good, but much less likely to be stolen.

ThresholdBot
import random

class ThresholdBot(WhiteElephantBot):
    def __init__(self, name):
        self.name = name
        # Choose a minimum value to be happy.
        self.goal = 1 - random.random() ** 2

    def take_turn(self, players, presents, just_stole):
        # Find who has a gift that's sufficiently valuable.
        targets = self.steal_targets(presents, just_stole)
        targets = [x for x in targets if presents[x][0] >= self.goal]
        targets = sorted(targets, key=lambda x: presents[x][0])

        if not targets:
            return None

        # Choose a target (biased toward the best gifts).
        weighted = []
        for i, target in enumerate(targets, 1):
            weighted += [target] * i ** 2
        return random.choice(weighted)

We don't really care about getting the best gift, just something good enough.  So long as there's something worth stealing, we'll do it.

SampleBot
import random

class SampleBot(WhiteElephantBot):
    def rollout(self, values, counts, just_stole, next_move):
        targets = set()
        move_chosen = False
        for i, (v, n) in enumerate(zip(values, counts)):
            if v and n < 3 and i != just_stole and i != 0:
                targets.add(i)
        for i in range(len(values)):
            if values[i]:
                break
            while True:
                if not targets:
                    break
                if move_chosen:
                    j = max(targets, key=lambda i: values[i])
                    if values[j] < 0.5:
                        break
                else:
                    move_chosen = True
                    if next_move is None:
                        break
                    j = next_move
                values[i] = values[j]
                counts[i] = counts[j] + 1
                values[j] = 0
                counts[j] = 0
                if just_stole is not None and counts[just_stole] < 3:
                    targets.add(just_stole)
                if j in targets:
                    targets.remove(j)
                just_stole = i
                i = j
            values[i] = random.random()
            for player in (just_stole, i):
                if player is not None and values[player] and counts[player] < 3:
                    targets.add(player)
        return values[0]
    def take_turn(self, players, presents, just_stole, n_rollouts=2000):
        names = [self.name] + players + list(presents.keys())
        values = [presents[name][0] if name in presents else None for name in names]
        counts = [presents[name][1] if name in presents else 0 for name in names]
        if just_stole is not None:
            just_stole = names.index(just_stole)
        targets = [None]
        for i, (v, n) in enumerate(zip(values, counts)):
            if v and n < 3 and i != just_stole and i != 0:
                targets.append(i)
        if len(targets) == 1:
            return targets[0]
        scores = [0. for _ in targets]
        n = n_rollouts // len(targets)
        for i, target in enumerate(targets):
            for _ in range(n):
                scores[i] += self.rollout(list(values), list(counts), just_stole, target) / float(n)
        target_index = targets[scores.index(max(scores))]
        if target_index is None:
            return None
        return names[target_index]

Runs 2000 simulations with each player acting greedily and chooses the best action.

What does this bot do exactly?

@Beefster Runs 2000 random games with each player acting greedily, and picks the move with the highest average final score.

Name error. You need to import random.

RobinHood
class RobinHood(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):
        #get the possible steal targets
        targets = self.steal_targets(presents, just_stole)
        #who stole his gift?
        targets = [x for x in targets if presents[x][1] > 0]
        #sort by value
        targets = sorted(targets, key=lambda x: presents[x][0])
        #only steal back if it's worth it
        targets = [x for x in targets if presents[x][0] > 0.5]

        if len(targets)>0:
           return targets.pop()

Steal from the rich who didn't earn their present

You have an indentation error.

GoodSamaritan
class GoodSamaritan(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):
        targets = self.steal_targets(presents, just_stole)

         #if only one player has a gift, don't steal it!
        if len(presents)<=1 or len(targets)==0:
             return None
        else:
             #Steal the worst present
             return min(targets, key=lambda x: presents[x][0])

Give unlucky people another chance at good fortune

Gambler
class Gambler(WhiteElephantBot):
    def take_turn(self, players, presents, just_stole):
        #get the possible steal targets
        targets = self.steal_targets(presents, just_stole)

        #last player
        if len(players)==0:
            #lets gamble! Try and get the highest score
            return None

        #If you are not last, steal the best gift that can be restolen so maybe you can become the last player
        targets = [t for t in targets if presents[t][1]<2 ]
        if targets:
            return max(targets, key=lambda x: presents[x][0])

The Gambler is addicted, he tries to be the last player, then he gambles on a new present to beat all the other players.

Top3Bot
class Top3Bot(WhiteElephantBot):
    def __init__(self, name):
        super().__init__(name)
        self.firstturn = True

    def take_turn(self, players, presents, just_stole):
        if self.firstturn:
            num_presents = len(players) + len(presents) + 1
            self.value_limit = (num_presents - 3) / num_presents
            self.firstturn = False

        targets = self.steal_targets(presents, just_stole)

        if players:
            targets += None

        return max(
            targets,
            key=lambda name: self.steal_ranking(name, presents, len(players))
        )

    def steal_ranking(self, name, presents, presents_remaining):
        if name is None:
            return (0, 0)

        present_value = presents[name][0]
        num_steals = presents[name][1]
        if present_value >= self.value_limit:
            if num_steals == 2:
                return (5, present_value)
            elif  num_steals == 0:
                return (4, -presemt_value)
            elif num_steals == 1 and presents_remaining == 0:
                return (3, -present_value)
            else:
                return (-1, present_value)
        else:
            if num_steals < 2:
                return (2, present_value)
            else:
                return (-2, present_value)

This bot does not try to get the best present possible, but tries to get a present that is valued >= (n-3)/n, where n is the number of presents. In most of the cases, there will be presents valued that much, and Top3Bot will try to get its hands on one of these, but he doesn't really care which of those he gets.

your __init__ is missing its self argument

source: Stack Exchange

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

sort: votes


text:
Einstein's Sorter
Challenge
Given a list of integers and a velocity, \$v\$, implement a sorting algorithm which simulates a program sorting the list from smallest to biggest at the given velocity.
Einstein's Theory of Special Relativity
What do I mean? Well assume your program takes a time, \$T\$, to sort a particular list. If you ran the program again at a higher velocity, \$v\$, according to a stationary observer your program would run slower and would take a different time, \$T'\$, to sort the same list.
How do you relate \$T\$ to \$T'\$? You use the equation for time dilation:
$$T' = \frac{T}{\sqrt{1-v^2}}$$
If we use geometrised units where \$v\$ is a fraction of the speed of light, and \$0\leq v \lt 1\$.
So you must change your program's running time by a factor of
$$\frac{1}{\sqrt{1-v^2}}$$
Output
You must output the sorted list
Rules

You are allowed an error of \$\pm0.1 \text{ s}\$
The length of the list, \$l\$, will be in the range \$1 \leq l \leq 50\$
The list will contain only integers
The velocity will be given in geometrised units
You may sort the list then wait before outputting

Examples
For these examples, assume my program takes a time of \$T = l^2 \text{ s}\$ to run, where \$l\$ is the length of the list, regardless of the contents of the list:
List, Velocity > Sorted list, Time taken
[9,8,7,6,4,3,2,1], 0.5 > [1,2,3,4,5,6,7,8,9], 93.5307
[8,0,0,5,6], 0.1 > [0,0,5,6,8], 25.1259
[7,7,7,7,7,7,7], 0.999 > [7,7,7,7,7,7,7,7], 453.684

Your timings do not need to be as accurate.
Winning
Shortest code wins.

Suppose your program sorts a list L in time T in the 'normal' rest frame (v=0). Then, if we run with the same list L with v=sqrt(0.5), how long should your program take to run? 2*T or 3*T or some other number?

Perhaps use the [tag:time] or [tag:restricted-time] tags?

@ChasBrown your program should take T/sqrt(1-v**2) to run. For v=sqrt(0.5), then your program should run for sqrt(2)*T

@ChasBrown If your program runs for a time T,  then it should pause for a time of T/sqrt(1-v**2) - T

@Beta Decay: I agree with your latter comment ("... should pause... - T"); but your previous with "should run for sqrt(2)*T..." still seems a bit off, computationally...

@ChasBrown What do you mean?

@Beta Decay: I mean that, given that v=0 your program runs for T; then "For v=sqrt(0.5), then your program should run for sqrt(2)*T" is not correct as a calculation. However, more generally,  "If your program runs for a time T (with v=0), then it should pause for a time of T/sqrt(1-v**2) - T" is correct, as a calculation.

@ChasBrown Overall your program should run for T' = T/sqrt(1-v**2). The sorting section of the program will run for T, so the pausing section of the program will run for T/sqrt(1-v**2) - T. When v=sqrt(0.5), then the program as a whole should run for T' = T/sqrt(1-0.5) = sqrt(2) * T. When v=0 then the program as a whole will run for T' = T/sqrt(1-0) = T. I'm still not sure what the problem is.

@Beta Decay: I see now; you're correct.

Bash, 56 55 bytes
-1 bytes thanks to Digital Trauma (using z instead of pushing 1)
for n in $2;{
sleep `dc -e"9k$n z$1d*-v/f"`&&echo $n&
}

Try it online!
Explanation
Sleep sort loops over all the integers, for each \$n\$ it does the following in the background:

set a timer of \$n\$ seconds (or another time unit)
print \$n\$

Instead of using one second we divide \$n\$ by \$\frac{1}{\sqrt{1-v^2}}\$ which is achieved by the following dc code:
9k              # set precision to 9 digits
  $n            # push n                    [n]
     z          # push size of stack        [1,n]
      $1        # push v                    [v,1,n]
        d*      # duplicate & multiply      [v^2,1,n]
          -     # subtract                  [1-v^2,n]
           v    # square root               [sqrt(1-v^2),n]
            /   # divide                    [n/sqrt(1-v^2)]
             f  # print

A couple of bytes off

Python 2, 88 87 91 bytes
-1 byte thanks to Mr. Xcoder

from time import*
def f(l,v):t=time();s=sorted(l);d=time()-t;sleep(d/(1-v*v)**.5-d);print s

Try it online!

print instead of return should, as usual in Python 2, save a byte.

Suppose v=.5**.5; then 1/(1-v*v)**.5 = 2; and suppose the actual sort takes T=time()-t seconds. Your function then takes a total of 3*T seconds to complete, which is too long; it should only take 2*T seconds. So I think you want something like: u=(1-v*v)**.5;sleep((time()-t)*(1-u)/(u)).

@ChasBrown hmm, I followed the OP's equation

@Rod: I've asked the question to OP. They key to me is when v=0, it should take the same amount of time as it would just to sort the list normally with none of this funny business; but using the (not unreasonable) interpretation you give, it would take twice that long.

@ChasBrown I realised the error now, fixed it!

APL (Dyalog), 52 bytes
{t←2⊃⎕AI⋄r←⍵[⍋⍵]⋄r⊣⎕DL 1e¯3×s-(s←t-2⊃⎕AI)÷.5*⍨1-⍺*2}

Try it online!

Clean, 168 bytes
import StdEnv,System.Time,System._Unsafe,Debug.Performance
?u=:(Clock m,l)n#!(Clock i)=accUnsafe clock
|toReal i>toReal m*1E4/sqrt(one-n*n)=l= ?u n

?o(measureTime sort)

Try it online!
A composed function literal which times the sorting of the list, and then loops until an appropriate additional number of ticks have passed.

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


text:
Shared Birthday Party
An office (let's call it "The Office") is going to cut down on wasted time in 2019 by consolidating office birthday parties. Any two people with a birthday between Monday and Friday (inclusive) of the same week will be celebrated with a Shared Birthday Party some time that week. People whose birthdays fall on a Saturday or Sunday get no party at all.
Some people do not like sharing a birthday party with people who do not share their actual birthday. They will be Very Angry to have a Shared Birthday Party.
We are going to simulate an office and find the first week in which someone gets Very Angry about their Shared Birthday Party.
The Challenge
Write a program or function that outputs the first ISO week number for 2019 in which someone in a simulated office gets Very Angry about their Shared Birthday Party, subject to the following basic rules:

input an integer N > 1, which is the number of workers in the office.
the N birthdays themselves are distributed uniformly at random from Jan 1 to Dec 31 (ignore Feb 29).
but the working weeks for the purposes of determining Shared Birthday Parties are the 2019 ISO Week Dates, which are between 2019-W01-1 (2018-12-31) and 2019-W52-7 (2019-12-29). A new ISO week starts every Monday. (I think this is all you really need to know about ISO weeks for this challenge).
for the N people in the office, each has a 1/3 chance of having a Very Angry Shared Birthday Party personality type, so you'll have to simulate that too.
but they will not be angry if the party is shared with people who have the same birthday.
output the ISO week number (exact format for this is flexible as long as the week number is clear) for the first occurrence of a Very Angry person. If there are no angry people, you can output anything that isn't confused with an ISO week or the program can error out etc.

Some simplifying assumptions:

as I mentioned, ignore the February 29 issue completely (an unneeded complication)
ignore public holidays (this is an international community so our holidays will differ) and just assume the office is open on each weekday.

Rules
This is code-golf. Shortest answer in bytes for each language wins. Default loopholes forbidden.
Code explanations welcome.
Worked Examples
Contrived Example 1 with input N = 7. First and second columns are random as described in the rules (but not actually random here of course).
Angry Type
Person?    Birthday   ISO Week   Comment
================================================================================
   N       2018-12-31      W01   In the 2019 ISO week date year
   Y       2018-12-31      W01   Same birthday, so no anger happens
   N       2019-02-05      W06
   Y       2019-03-15      W11   No anger happens because other W11 b-day is a Saturday
   N       2019-03-16      W11
   N       2019-09-08      W36   My birthday!
   Y       2019-12-30       -    Not in the 2019 ISO week date year

So no anger happens. The program or function can error out or output something not confused with an ISO week number.
Example 2 with N unspecified.
Angry Type
Person?    Birthday   ISO Week   Comment
================================================================================
   N       2019-01-19      W03
   Y       2019-02-04      W06
   N       2019-02-05      W06   No anger because not an angry person
  ...             ...      ...   (No angry people until...)
   Y       2019-03-12      W11   Very Angry Person!
   N       2019-03-14      W11
  ...             ...      ...   ...

The output would be W11 or something equivalent.

... There is no 29th of February in 2019! Can you add a worked example, please?

What should the output be if no-one is "very angry"? This could pretty easily happen for small $ N $.

@Shaggy there could be people who work there whose birthday is February 29. I'm saying to just ignore that possibility since it just adds a pointless egde case IMO.

I can add an example in a few hours.

If there are no angry people, any suitable output that is not W01 to W52 or equivalent, or an error message, is fine. I'll edit the question to reflect this when I am off mobile.

December 30, (2019 or 2018) presents a conundum: it is not part of any 2019 ISO week, yet two Very Angry people could share that birthday

@ChasBrown there are no days not in ISO weeks. They run from Mon to Sun inclusive such that week 1 contains the 1st Thu of the Gregorian year. 2019 has 52 but some years have 53. See Wikipedia.

@Jonathan Allan: Sure every day is in some ISO week; but still there are days not in ISO weeks of 2019. For a trivial example, Jan. 1 1980 is not in any ISO week of 2019. Also note that Dec 31, 2018 is in ISO week 1 of 2019; see here. In the context here, suppose both myself and my Very Angry sole workmate (so n=2) share a birthday of Dec 30. What should the OP's function output?

@ChasBrown Ah, yes that does cause a little difficulty I had not thought about!

@Jonathan Allan: Indeed! This is why I hate dates! And date coding in general! Grrrr! :)

Maybe it's me, but I rather have a shared birthday party than none at all. Rip all those who have their birthdays in the weekend.

@Kevin Cruijssen: Is this the contrapositive? "Dude, I like when I can share a b-day party with my friends on the weekend!"

Python 2, 172 202 bytes
def f(n):
 D=set();A=[];R=randint
 while n:
	n-=1;w,d=R(1,52),R(1,5)
	if R(0,364)>104:D|={(w,d)};A+=[w]*(R(0,2)>1)
 return next((a for a in sorted(A)if[w for w,d in D].count(a)>1),0)
from random import*

Try it online!
oops! Missed a requirement; cost 30 bytes.
It is given by the OP that your birthday is not 29 February.
If your birthday is 30 December, it will not fall in any ISO week of 2019, so in any case you cannot be a Very Angry ISO week of 2019.
That leaves 364 other birthdays to consider you being Very Angry about. 104 of these fall on weekends when we have stipulated that you won't get Very Angry about it. So we only care about you 260/365 of the time; i.e., when R(0,364)>104 (randint's range is inclusive). Given that constraint, it is equiprobable that your weekday birthday falls in any of the 52 ISO weeks of 2019, and any weekday of that week; and, independently, that you are 1 in 3 likely to be a Very Angry person.
D is then a set of (weeknum,weekday) so that if a potentially Angry person shares an actual birthday, then there's no need to be Amgry unless there's yet another person having a birthday that week.
0 is returned if no Very Angry people manifest during any ISO 2019 week; otherwise, the ISO week number of the earliest meltdown is returned.

Shouldn't you also consider the edge case of December 31, 2019?

@Charlie: Sure! But December 31 2018 is in the same ISO week 2019 as Jan 1 2019 thus would be a part of that "jealous party week", so it works out.

I'm no Python expert, but I believe your answer fails to account for this: "but they will not be angry if the party is shared with people who have the same birthday." You still got my upvote though.

@O.O.Balance: Ooops! Missed that; amended!

Jelly,  36 32  33 bytes
+1 byte to fix the 30-Dec edge-case I had not noticed (as pointed out by Chas Brown has in comments below the OP)
-4 thanks to Erik the Outgolfer (inline helper and use of outer product)
7R2<52×þFX)Ġị$,3XỊ¤€ṁ@\PṢ€Ḋ€Fḟ0Ḣ

A monadic link which yields an integer in \$[0,52]\$ where \$0\$ means no Very Angry people at all during the year and other outputs are ISO week numbers.
Try it online!
Or see this version which prints the weeks in which each person's birthday lies (0 for weekends) grouped up, then prints a same-ordered list of lists of whether those people are of the Very Angry type, and finally prints the result.

Java 8, 198 bytes
double r(){return Math.random();}

n->{int r=52,a[]=new int[r];for(;n-->0;)if(r()*364>104)++a[(int)(r()*r)];for(;++n<52;)r=r>51&a[n]>1&r()<1-5/Math.pow(5,a[n])&r()<1-Math.pow(2./3,a[n])?n:r;return r;}

Output is zero-based (0-51); a value of 52 indicates no Very Angry people. Try it online here.
Ungolfed:
double r() { return Math.random(); } // shortcut for Math.random(), saves a few bytes

n -> { // lambda taking an intger argument and returning an integer
    int r = 52, // this will hold the result; set to the value for "no Very Angry people" for now
    a[] = new int[r]; // array counting the people whose birthday lies in each week
    for(; n-- > 0; ) // for each person:
        if(r() * 364 > 104) // determine whether their birthday is on a weekday that is not the 30th of December ...
            ++a[(int) (r() * r)]; // ... only if so, increment the counter for a random ISO week
    for(; ++n < 52; ) // loop through the weeks; n is -1 before the loop
        r = r > 51   // if r is still the default ...
          & a[n] > 1 // ... and there is more than one person with a birthday that week ...
          & r() < 1 - 5/Math.pow(5, a[n]) // ... and at least two people have a different birthday ...
          &r() < 1 - Math.pow(2./3, a[n]) // ... and at least one person has the Very Angry personality type ...
          ? n  // ... set the current week as the result ...
          : r; // ... otherwise leave it the same
    return r;  // return the result
}

Suggest 91>26 instead of 364>104


text:
Calculate a tip using the smallest number of coins
Most tip calculator apps simply take a flat percentage of the meal price.  So, for example, if your meal is $23.45, you can leave a 15% tip = $3.52, or a more generous 20% tip = $4.69.
Convenient enough for credit card users.  But not so if you prefer to leave cash tips, in which case these oddball cent amounts get in the way.  So let's modify the idea to be more convenient for cash users.
Your assignment
Write, in as few bytes as possible, a program or function that takes as input:

Price of the meal
Minimum tip percentage
Maximum tip percentage

And output any tip amount within the range [price * min_percentage / 100, price * max_percentage / 100] that minimizes the number of bills/banknotes and coins required.
Assume the US monetary denominations of 1¢, 5¢, 10¢, 25¢, $1, $5, $10, $20, $50, and $100.
Example
Here is a non-golfed example program in Python:
import math
import sys

# Do the math in cents so we can use integer arithmetic
DENOMINATIONS = [10000, 5000, 2000, 1000, 500, 100, 25, 10, 5, 1]

def count_bills_and_coins(amount_cents):
    # Use the Greedy method, which works on this set of denominations.
    result = 0
    for denomination in DENOMINATIONS:
        num_coins, amount_cents = divmod(amount_cents, denomination)
        result += num_coins
    return result

def optimize_tip(meal_price, min_tip_percent, max_tip_percent):
    min_tip_cents = int(math.ceil(meal_price * min_tip_percent))
    max_tip_cents = int(math.floor(meal_price * max_tip_percent))
    best_tip_cents = None
    best_coins = float('inf')
    for tip_cents in range(min_tip_cents, max_tip_cents + 1):
        num_coins = count_bills_and_coins(tip_cents)
        if num_coins < best_coins:
            best_tip_cents = tip_cents
            best_coins = num_coins
    return best_tip_cents / 100.0

# Get inputs from command-line
meal_price = float(sys.argv[1])
min_tip_percent = float(sys.argv[2])
max_tip_percent = float(sys.argv[3])
print('{:.2f}'.format(optimize_tip(meal_price, min_tip_percent, max_tip_percent)))

Some sample input and output:
~$ python tipcalc.py 23.45 15 20
4.00
~$ python tipcalc.py 23.45 15 17
3.55
~$ python tipcalc.py 59.99 15 25
10.00
~$ python tipcalc.py 8.00 13 20
1.05

Can we take the percentages as decimals? (i.e. 0.15 for 15%)

@pizzapants184: Sure.

If you're not using a credit card then you are paying in cash, right? Wouldn't the total of check+tip be the relevant amount then, not just the tip?

related

a program that takes as input (stdin, command-line arguments, or GUI input box, whichever is most convenient in your language) Is this intended to override our defaults for inputs and outputs? That is, would e.g. a function that takes three numbers and returns the result be allowed?

Am I correct in saying that 3.51 and 3.75 are also valid outputs for the test case 23.45 15 17? They use the same amount of coins and are also inside the range.

@Sparr Even people who pay the bill by card like to leave a cash tip; there are various reasons given for this so I won't repeat them here.

Can tips be floats? i.e. 25.5% tip?

If there is no such interger cent tip in the range can we have undefined behaviour (or should we floor the lower end and ceil the upper end or something?) e.g. meal_price = 100; min_tip_percent = 0.115; max_tip_percent = 0.117 (the example code would raise an error).

... or maybe meal_price = 0.49; min_tip_percent = 11; max_tip_percent = 12 would be more appropriate.

@KevinCruijssen: If there's a tie, you can use either value.

@Laikoni: I have edited the requirements to use the site-default "program or function", and so am retroactively accepting the existing function-only answers.

@KevinCruijssen 3.51 is not in the specified range - 3.55, 3.60 and 3.75 are.

When clarifying specifications please update the post rather than just leaving such information to be found in the comments.

@JonathanAllan Ah, you're indeed right. The range starts at 3.5175. Fixed my code (and golfed it by 1 byte at the same time). Thanks for letting me know. (And I agree it should be mentioned in an edit of the challenge description that 3.60 and 3.75 are also allowed outputs.)

Charcoal, 60 bytes
Ｎθ≔×θＮη≔×θＮζ≔⁰θＦＩ⪪”;‴üφ↷Σ↗SEX&¿h'⊟”³«Ｗ‹θη≧⁺ιθ¿›θζ≧⁻ιθ»﹪%.2fθ

Try it online! Takes input as decimals. Link is to verbose version of code. Explanation:
Ｎθ

Input the bill.
≔×θＮη≔×θＮζ

Input the tip decimal fractions and compute the minium and maximum tip.
≔⁰θ

Start with zero tip.
ＦＩ⪪”;‴üφ↷Σ↗SEX&¿h'⊟”³«

The SEXy string expands to 10050.20.10.5.01.0.250.1.05.01 which is split into groups of three characters and cast to float.
Ｗ‹θη≧⁺ιθ

Add as many of the current denomination as necessary to reach the minimum tip.
¿›θζ≧⁻ιθ»

Remove one denomination if the maximum tip has been exceeded.
﹪%.2fθ

Format the tip for display.

I don't think the formatting was a requirement (rather just something the example code does).

@JonathanAllan Well in that case you could save 4 bytes by using Ｉ instead of ﹪%.2f.

JavaScript (ES6), 93 bytes
(x,m,M)=>(g=(t,c=1e4)=>t>x*M?0:t<x*m?[...'1343397439'].some(d=>g(t+(c/=-~d/2)))*r:r=t)(0)/100

Try it online!
How?
We recursively compute a sum of bill/coin values until it falls within the acceptable range, always trying the highest value first.
This is guaranteed to use the minimum amount of bills and coins because for any solution \$\{b_0,\dots,b_n\}\$ returned by this algorithm:

all terms \$b_0\$ to \$b_n\$ are required, otherwise the algorithm would have selected \$\{b_0,\dots,b_{k-1},x\}\$ with \$x \ge b_k\$ for some \$0 \le k < n\$
for any \$0 \le k < n\$ and any \$x \le b_n\$, \$\{b_0,\dots,b_{k-1},b_k-x,b_{k+1},\dots,b_n\}\$ cannot be a solution, otherwise \$\{b_0,\dots,b_{n-1}\}\$ would have been selected
there may exist some \$0 < x < b_n\$ such that \$\{b_0,\dots,b_{n-1},x\}\$ is also valid, but that would not use less bills/coins than the selected solution

The bill/coin values \$c_n\$ expressed in cents are computed with:
$$\begin{cases}c_0=10000\\c_{n+1}=\dfrac{c_n}{(d_n+1)/2}\end{cases}$$
where \$(d_0,\dots,d_9) = (1,3,4,3,3,9,7,4,3,9)\$.
 n | c(n)  | d(n) | k = (d(n)+1)/2 | c(n+1) = c(n)/k
---+-------+------+----------------+-----------------
 0 | 10000 |   1  | (1+1)/2 = 1    |      10000
 1 | 10000 |   3  | (3+1)/2 = 2    |       5000
 2 |  5000 |   4  | (4+1)/2 = 2.5  |       2000
 3 |  2000 |   3  | (3+1)/2 = 2    |       1000
 4 |  1000 |   3  | (3+1)/2 = 2    |        500
 5 |   500 |   9  | (9+1)/2 = 5    |        100
 6 |   100 |   7  | (7+1)/2 = 4    |         25
 7 |    25 |   4  | (4+1)/2 = 2.5  |         10
 8 |    10 |   3  | (3+1)/2 = 2    |          5
 9 |     5 |   9  | (9+1)/2 = 5    |          1

Python 3.x: 266 185 bytes
A straightforward modification to my example program in the question.  Note that the output is no longer formatted to require 2 decimal places.
Edit: Thanks to Jo King for making it smaller.
import sys
p,m,M,T=*map(float,sys.argv[1:]),0
C=p*M
for t in range(-int(-p*m),int(p*M)+1):
 n,a=0,t
 for d in 1e4,5e3,2e3,1e3,500,100,25,10,5,1:n+=a//d;a%=d
 if n<C:T,C=t,n
print(T/100)

Some quick golfing to get it to 185 bytes

Java 10, 186 185 bytes
(p,m,M)->{double r=0,t,Q=99,q;for(m*=p+.02;m<M*p;m+=.01){q=0;t=m;for(var c:new double[]{100,50,20,10,5,1,.25,.1,.05,.01})for(;t>=c;t-=c)q++;if(q<Q){Q=q;r=m;}}return"".format("%.2f",r);}

Takes the minimum and maximum percentages as /100 decimals (i.e. 15% as 0.15).
-1 byte to fix the issue with 3.51 as potential output and golfing the way to fix rounding errors by 1 byte at the same time.
Try it online.
Explanation:
(p,m,M)->{                // Method with three double parameters and String return-type
  double r=0,             //  Result-double, starting at 0
         t,               //  Temp-double
         Q=99,            //  Min amount of coins, starting at 99
         q;               //  Temp-double for the amount of coins
  for(m*=p-.02;m<M*p;     //  Loop in the range [`m*p-0.02`, `M*p`]
           m+=.01){       //  in steps of 0.01 (1 cent) per iteration
                          //  (the -0.02 (minus 2 cents) is to fix rounding errors)
    q=0;                  //   Reset `q` to 0
    t=m;                  //   Reset `t` to the current iteration `m`
    for(var c:new double[]{100,50,20,10,5,1,.25,.1,.05,.01})
                          //   Loop over the coins (largest to smallest)
      for(;t>=c;          //    As long as `t` is larger than or equal to the current coin
          t-=c)           //     Remove the coin from the value `t`
          q++;            //     And increase the quantity-counter by 1
      if(q<Q){            //   If the quantity-counter is smaller than the current smallest
        Q=q;              //    Replace the smallest with the current
        r=m;}}            //    And replace the result with the current `m`
  return"".format("%.2f",r)l;}
                          //  Return the result with 2 decimal places

I don't think this is technically valid at the moment since the question specifies a program, but the OP hasn't clarified.

OP has clarified functions are now allowed, so you don't need to worry about doubling the size.

Clean, 207 156 bytes
Swapping to a function saved 51 bytes, unsurprisingly.
import StdEnv
d=[10000,2000,1000,500,100,25,10,5,1]
$n u l=snd(hd(sort[(sum[foldl(rem)m(d%(0,i))/k\\k<-d&i<-[-1..]],toReal m)\\m<-map toInt[n*u..n*l]]))/1E2

Try it online!

OP clarified that functions are now allowed.

@Laikoni Thanks for letting me know :) Saves a lot of bytes - full programs are expensive in Clean!

Python (264 222 bytes)
Slightly more golfed.
m=[.01,.05,.1,.25,.5,1,5,10,20,50,100]
def f(a,i,j):
 t,u=9**9,a*j
 def g(s,d,c):
  nonlocal t
  if(a*i<s<u)+(c>t):t=min(c,t);return c,s
  return(t+1,s)if(s>u)+(d>9)else min(g(s+m[d],d,c+1),g(s,d+1,c))
 return g(0,0,0)[1]

Try it Online!

Perl 6, 93 92 89 bytes
{.01*($^a*$^b+|0...$a*$^c).min:{$!=$_;sum '✐ᎈߐϨǴd
'.ords>>.&{($!%=$_)xx$!/$_}}}

Try it online!
Anonymous code block that takes three arguments (price, minimum percentage, and maximum percentage) and returns the tip.

Wolfram Language (Mathematica), 105 bytes
This will give all the solutions with minimal coin count.
MinimalBy[NumberDecompose[#,d=100{100,50,20,10,5,1,.25,.10,.05,.01}]&/@Range[Ceiling[#2#],#3#],Tr].d/100&

Try it online!

Kotlin, 215 bytes
{p:Double,l:Int,h:Int->val d=listOf(10000,5000,2000,1000,500,100,25,10,5,1)
var m=Int.MAX_VALUE
var r=0.0
(Math.ceil(p*l).toInt()..(p*h).toInt()).map{var a=it
var c=0
d.map{c+=a/it
a%=it}
if(c<m){m=c
r=it/100.0}}
r}

Try it online!

Jelly,  33  32 bytes
“ñṇzi;’b⁴×H¥\ɓ_>Ƈ-Ṫ
PĊ1¦r/ÇƬL$ÞḢ

A monadic link accepting a list [cost in cents, [minimum ratio, maximum ratio]] which yields a tip amount in cents.
Try it online!
How?
The first line is a helper Link which yields the amount given less the largest denomination note/coin:
“ñṇzi;’b⁴×H¥\ɓ_>Ƈ-Ṫ - Link 1, get next lower amount: integer, V
“ñṇzi;’             - base 250 number = 112835839060
       b⁴           - to base 16 = [1,10,4,5,8,10,4,4,5,4]
            \       - cumulative reduce with:       e.g.: 1,10   5,4   10,5   25,8
           ¥        -   last two links as a dyad:
         ×          -     multiply                        10     20    50     200
          H         -     halve                            5     10    25     100
                    - ...yielding: [1,5,10,25,100,500,1000,2000,5000,10000]
             ɓ      - start a new dyadic link with swapped arguments
              _     - subtract (vectorises) ...i.e. [V-1,V-5,V-10,...]
                Ƈ   - filter keep those which satisfy:
                 -  -   literal -1
               >    -   greater than? (i.e. if V-X > -1)
                  Ṫ - tail (tailing an empty list yields 0)

The number of calls required in order to reach zero is used to sort the range of tip amounts, and then the leftmost is yielded:
PĊ1¦r/ÇƬL$ÞḢ - Main Link: [cost, [min, max]]
P            - product = [cost*min, cost*max]
   ¦         - sparse application...
  1          - ...to indices: 1
 Ċ           - ...what: ceiling   -> [ceil(cost*min), cost*max]
     /       - reduce by:
    r        -   inclusive range (implicit floor of arguments)
          Þ  - sort by:
         $   -   last two links as a monad:
       Ƭ     -     repeat collecting results until a fixed point is reached:
      Ç      -       last link (1) as a monad  (e.g. 32 -> [32,7,2,1,0])
        L    -     length (i.e. coins/notes required + 1)
           Ḣ - head


text:
Howdy! I'm the sheriff of code golf!
It's likely that anyone who used Twitter a couple of months ago would know about the 'Howdy! I'm the sheriff of X" meme. Where a simple image of a sheriff is drawn with emoji, and changes to fit a theme. So I thought it was time for the Sheriff of Code Golf. Here he is:
    ###
   #####
    ###
    ###
    ###
     #
   #####
  #  #  #
 #   #   #
 #   #   #
     #
    ###
   #   #
   #   #
   #   #
   #   #

This one in particular has 'pixels' which are one character wide, and one character high. To generate him, the arguments will be 1 and 1.
What if he is to be wider than he is tall?
      ######
    ##########
      ######
      ######
      ######
        ##
    ##########
  ##    ##    ##
##      ##      ##
##      ##      ##
        ##
      ######
    ##      ##
    ##      ##
    ##      ##
    ##      ##

He's got a height of 1, but a width of 2.

Rules:

The challenge is to write code to draw your own Sheriff of Code Golf, in the fewest characters possible.
Use any programming language your heart desires.
Your code should take two arguments, both of which are integers, for the height and width of the Sheriff.
The output should be composed of single white spaces for the background, and any other character(s) you choose for the Sheriff. (I've used hashes for the test cases, but it doesn't matter what you use).
It should be possible for the height to be a negative integer, inverting the image.
The width can be a negative integer, but because the image is symmetrical, it will be identical to it's positive value.
Trailing white-spaces are irrelevant.
If either argument is 0, that dimension is 'flattened' to a single row or column. The length of this line is the other argument multiplied by the height, or width of the Sheriff, respectively.
If both arguments are 0, both lines are 'flattened', leaving a single positive character.
Not essential, but please include a link to an online interpreter such as tio.run
The output should be a string, over multiple lines, or output to the console.

Test Cases
1 high, 1 wide
    ###
   #####
    ###
    ###
    ###
     #
   #####
  #  #  #
 #   #   #
 #   #   #
     #
    ###
   #   #
   #   #
   #   #
   #   #

2 high, 1 wide
    ###
    ###
   #####
   #####
    ###
    ###
    ###
    ###
    ###
    ###
     #
     #
   #####
   #####
  #  #  #
  #  #  #
 #   #   #
 #   #   #
 #   #   #
 #   #   #
     #
     #
    ###
    ###
   #   #
   #   #
   #   #
   #   #
   #   #
   #   #
   #   #
   #   #

1 high, 2 wide
      ######
    ##########
      ######
      ######
      ######
        ##
    ##########
  ##    ##    ##
##      ##      ##
##      ##      ##
        ##
      ######
    ##      ##
    ##      ##
    ##      ##
    ##      ##

2 high, 2 wide
      ######
      ######
    ##########
    ##########
      ######
      ######
      ######
      ######
      ######
      ######
        ##
        ##
    ##########
    ##########
  ##    ##    ##
  ##    ##    ##
##      ##      ##
##      ##      ##
##      ##      ##
##      ##      ##
        ##
        ##
      ######
      ######
    ##      ##
    ##      ##
    ##      ##
    ##      ##
    ##      ##
    ##      ##
    ##      ##
    ##      ##

-1 high, 1 wide
   #   #
   #   #
   #   #
   #   #
    ###
     #
 #   #   #
 #   #   #
  #  #  #
   #####
     #
    ###
    ###
    ###
   #####
    ###

1 high, -1 wide
    ###
   #####
    ###
    ###
    ###
     #
   #####
  #  #  #
 #   #   #
 #   #   #
     #
    ###
   #   #
   #   #
   #   #
   #   #

0 high, 0 wide
#

1 high, 0 wide
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#
#

0 high, 2 wide
##################

Have fun, y'all!

This challenge has reminded me of the Inverted World novel.

Related: Picture of an old friend in ASCII art (variable scales; no inversion or flattening)

Observation: 1 high, 2 wide is the most human looking of the test cases, though I'm obligated to cheer for the Australian in the middle of it

@JoKing If I was naming them, I'd definitle have (-1, 1) as 'Australian' and (-1, 2) as 'Realistic Australian'. Although... Perhaps that could be misunderstood.

Closely related

Why do the 1-wide versions have an extra column of spaces at the left?

JavaScript (ES6), 171 bytes
Takes input in currying syntax (width)(height). Returns an array of strings.
w=>h=>[...Array((h>0?h:-h)*16||1)].map((_,y)=>'012345678'.replace(/./g,x=>' #'[((c=+'3733317900134444'[(h<0?16-~y/h:y/h)|0]||17)>>4-x|c>>x-4)&1|!h].repeat(w>0?w:-w))||'#')

Try it online!
How?
Only the left half of the sheriff is encoded as binary bitmasks, including the middle column:
    ##.         00011     3
   ###..        00111     7
    ##.         00011     3
    ##.         00011     3
    ##.         00011     3
     #          00001     1
   ###..        00111     7
  #  #  .       01001     9
 #   #   .  --> 10001 --> 17
 #   #   .      10001     17
     #          00001     1
    ##.         00011     3
   #   .        00100     4
   #   .        00100     4
   #   .        00100     4
   #   .        00100     4

Because there are only two values greater than \$9\$ and they're both equal to \$17\$, we can replace them with \$0\$ in order to have one character per row and still have a rather straightforward decoding process. Hence the packed string:
'3733317900134444'

For \$0 \le x \le 8\$ and \$0 \le y \le 15\$, the 'pixel' at \$(x,y)\$ is given by:
' #'[                                  // character lookup:
  (                                    //   0 = space
    (                                  //   1 = '#'
      c = +'3733317900134444'[y] || 17 // extract the bitmask for this row; 0 -> 17
    )   >> 4 - x                       // test the left part, middle column included
    | c >> x - 4                       // test the right part, middle column also included
  ) & 1                                // isolate the least significant bit
]                                      // end of character lookup

No matter how many answers you post, I'm impressed every single time..

I've shortened your version by 10 bytes. I'm not sure whether to post it as my own or to just enhance yours. Mine draws inspiration from yours so it looks almost as a duplicate. Great thinking by the way :D. Good job!

... by 8 bytes not 10. :-P

@ibrahimmahrir Sometimes, there's a thin line between outgolfed and improved. So, it's up to you. If you think your implementation is different enough, I don't mind at all if you post it as a separate answer.

I think it's just an improvment. The idea is to use characters codes as bitmaskes. That will save some space as each character will represent the whole row instead of just half of it. You can get the character code using String#charCodeAt.

Here it is in action: TIO. And I've just noticed it is not shortened by 8 bytes but by 5. text-encoding-face-palm. It is however shortened by 8 characters, so.... I still don't know how golfing works, yet.

@ibrahimmahrir I see. I think I'd better let this one as-is. You can still post yours as a separate alternate version. That's fine with me! (I'd make sure to add a link in my answer.)

Python 2, 228 218 202 189 173 bytes
lambda h,w:sum(([''.join('# '[int(n)]*abs(w)for n in bin([62,120,224,238,438,750][int(l)])[2:])or'#']*abs(h)for l in'1211102455013333'),[])[::1-(h<0)*2]or['#'*9*abs(w)or'#']

Try it online!

Alternatives:
Python 2, 173 bytes
lambda h,w:sum(([''.join('# '[int(n)]*abs(w)for n in bin(ord(' >w(8\x96I'[l])*l)[2:])or'#']*abs(h)for l in map(int,'3433314655132222')),[])[::1-(h<0)*2]or['#'*9*abs(w)or'#']

lambda h,w:sum(([''.join('# '[int(n)]*abs(w)for n in bin(ord(' >w(8\x96I'[int(l)])*int(l))[2:])or'#']*abs(h)for l in'3433314655132222'),[])[::1-(h<0)*2]or['#'*9*abs(w)or'#']

Perl 5, 169 166 157 bytes
@a=map"$_\n",(split 1,'  #####1   ###1    #1 #  #  #1#   #   #1  #   #')
[1011120344215555=~/./g];
print s/./$&x abs"@F"/ger x abs$F[1]for$F[1]<0?reverse@a:@a;

Try it online!
Maybe more could be gained by bit fiddling.

Great approach! I've played with your answer and with a few changes you can save quite a few bytes: Try it online! It's exactly the same approach just using slightly different I/O and a few tricks to reorder elements and store them for fewer bytes! Happy to elaborate on anything if needed!

Thx for the tip on split, I'm using that now and saved two bytes. Also shaved one off by loosing the 's around the indexes. Couldn't get say to work though.

Thx also for getting width and height "for free" with -a, lost 9 more bytes with that.

No problem at all! You can enable say with -M5.010, but not everyone likes to, you could use -l instead and keep print, but  if not, you can use a literal newline or $_.$/ for -1. Nice to see another Perl golfer!

Couldn't leave this alone and managed to reduce by a few more. say wasn't working because the newline was appended in the map so to use it necessitates a slightly different call. I also realised that when your code ends in a variable and you're using -p or something you can use @; as it includes that: Try it online! Hope you don't mind my comments!

Charcoal, 61 bytes
ＮθＮη¿θＦ⪪”{“↷Ｃ¿2t´⁴Ｑ19·“*Ｔy”!Ｅ↔θ∨⭆ι×μ↔η#×#∨×⁵↔η¹‖ＯＯ←∨↔η¹¿‹θ⁰‖↓

Try it online! Link is to verbose version of code. Explanation:
ＮθＮη

Input the dimensions.
¿θＦ⪪”{“↷Ｃ¿2t´⁴Ｑ19·“*Ｔy”!

If the height is nonzero, loop over the the right half of the sheriff...
Ｅ↔θ

... repeating the absolute height number of times...
∨⭆ι×μ↔η#

... if the width is nonzero then repeating each character the absolute number of times, otherwise a #.
×#∨×⁵↔η¹

But if the height is zero, then repeat # 5 times the absolute width, but at least 1 #.
‖ＯＯ←∨↔η¹

Reflect to produce the left half of the sheriff.
¿‹θ⁰‖↓

If the height is negative, flip the sheriff.

Python 2, 217 216 bytes
h,w=input();t=[];w=abs(w)
for i in range(16):c=bin(32+int('37333179HH134444'[i],26))[-5:];t+=[[''.join(abs(w)*' #'[d>'0']for d in c+c[3::-1]),'#'][w==0]]*abs(h)
print['\n'.join(t[::[1,-1][h<0]]),'#'*(w*16or 1)][h==0]

Try it online!
A Pythonic riff on Arnauld's approach.
Ugh! Now works for all edge conditions...

Clean, 299 275 272 bytes
import StdEnv,Data.List
f=flatlines
r=repeatn
$0 0=['#']
$h w#w=abs w
|h==0=r(w*9)'#'
|w<1=f(r(abs h*16)['#'])
=f(if(h<0)reverse id[cjustify(w*9)(intercalate(spaces((0xde35945rem n)*10/n*w))(r((0xc8d88154f8fberem n)*10/n)(r w'#')))\\n<-map((^)10o~)[-16..0],_<-[1..abs h]])

Try it online!

Powershell, 174 170 bytes
Inspired by Arnauld's Javascript
param($w,$h)('CGCCCAGIQQACDDDD'[((0..15),(15..0))[$h-lt0]],31)[!$h]|%{$n=+$_
,(-join(4..0+1..4|%{,' #'[($n-shr$_)%2]*[Math]::Abs($w)}),'#')[!$w]*[Math]::Abs(($h,1)[!$h])}

Ungolfed, explained and test scripted:
<#

Script uses 5 bits of integer as 5 left chars of a line of a sheriff
Script ignores other bits in this integer, so we can use 6 bit to take a ASCII letter
    ##.         1 00011     C
   ###..        1 00111     G
    ##.         1 00011     C
    ##.         1 00011     C
    ##.         1 00011     C
     #          1 00001     A
   ###..        1 00111     G
  #  #  .       1 01001     I
 #   #   .  --> 1 10001 --> Q
 #   #   .      1 10001     Q
     #          1 00001     A
    ##.         1 00011     C
   #   .        1 00100     D
   #   .        1 00100     D
   #   .        1 00100     D
   #   .        1 00100     D

#>

$f = {

param($w,$h)
(
    'CGCCCAGIQQACDDDD'[             # 5 bits of each char correspond to 5 left symbols of line of sheriff.
        ((0..15),(15..0))[$h-lt0]], # forward or reverse sequence of chars
    31                              # or sequence of one element = 11111
)[!$h]|%{                           # choose a sequence and for each
    $n=+$_                          # integer or ASCII code
    ,(  -join(
            4..0+1..4|%{            # loop on bit range 4..0 and append fliped range 1..4
                ,' #'[($n-shr$_)%2]*[Math]::Abs($w)
            }                       # returns space or # depend on bit, repeat $w times
        ),
        '#'                         # returns # for $w equal 0
    )[!$w]*[Math]::Abs(($h,1)[!$h]) # choose a sheriff line, repeat $h times
}

}

@(
    ,(1,0)
    ,(0,1)
    ,(1,-1)
    ,(0,0)
    ,(1,1)
    ,(0,0)
    ,(-2,-1)
    ,(0,0)
    ,(2,2)
) | % {
    $w,$h = $_
    $r = &$f $w $h
    $r
}


text:
Computing time sheets
Time sheets
In a work place you often have to complete time sheets. This task is write code to help this.
Input
Two times in a slightly non- standard 12 hour clock signifying the start and end of the day separated by a space.  A third number represents the number of minutes taken for lunch. For example
9:14 5:12 30

This means you started work at 9:14am, finished work at 5:12pm and took 30 minutes for lunch.
You can assume that

Any time in the first column is from 00:00 (midnight) up to but not including 1pm and any time in the second column is 1pm at the earliest up until 11:59pm.
The lunch break is no longer than the working day!

The input format must be as in the examples given.
Task
Your code should read in a file (or standard input) of these triples, and for each one output how long you worked. This output should indicate the number of hours. For the example above this is:
7hr and 58min minus 30 minutes which is 7hr 28min.
Output
Your output must specify the (whole) number of hours and minutes and must not list more than 59 minutes. That is you can't output 2hr 123min. Apart from that, your code can output in any easily human read format that is convenient for you.
Examples
10:00 1:00 30    --> 2hr 30min
12:59 1:00 0     --> 0hr 1min
00:00 11:59 0    --> 23hr 59min
10:00 2:03 123   --> 2hr 0min

I don't see how the strict input format (: delimited times on the 12 hour clock) adds anything to this challenge.

@Shaggy Parsing the input format was most of the challenge for me at least, because you can't assume character positions since hours could be either one or two characters...

Does the code have to read several lines? Or is it enough if it reads one line?

@mbomb007 No, I'm not seeing that, I'd prefer each time to be in the range 01:00-12:59.

Yes the code has to accept multiple lines.

@Neil I have clarified the non standard 12 hour clock rule. Please let me know if it isn’t clear now.

Can we use function argument as input if we are using pure javascript?

@ibrahimmahrir We don't usually allow different languages to play by different rules. But of course that is ultimately up to the OP.

Related.

@mbomb007 You can downvote, but not liking the input format is not a reason to VTC.

@mbomb007 There shouldn't be a contradiction now. Can you show me what it is so I can fix it please?

MATL, 28 bytes
`jYb0&)YOd.5+wgU13L/- 15XODT

Try it online!

This is very impressive!

Shouldn't the output be in this format "XXhr YYmin"?

@ibrahimmahrir The challenge says your code can output in any easily human read format that is convenient for you

Ah, I see! I'm going to edit my answer to shorten it out. Thanks!

Retina 0.8.2, 83 bytes
\d+
$*
 (1+:)
 12$*1$1
+`1:
:60$*
(1*) :\1(1*)(1*) \2
$3
:(1{60})*(1*)
$#1hr $.2min

Try it online! Link includes test cases. Explanation:
\d+
$*

Convert the input to unary.
 (1+:)
 12$*1$1

Add 12 hours to the stop time.
+`1:
:60$*

Multiply the hours by 60 and add to the minutes.
(1*) :\1(1*)(1*) \2
$3

Subtract the start time and break time from the stop time.
:(1{60})*(1*)
$#1hr $.2min

Divmod by 60. (Save 5 bytes for a more boring output format.)

Perl 5 -pl, 80 74 71 bytes
/:(\d+) (\d+):(\d+) /;$m=720+($2-$`)*60+$3-$1-$';$_=($m/60|0).":".$m%60

Try it online!

Python 3, 161 bytes
I know this won't even be close to smallest, but it does read in a file:
for l in open('t'):
    l=l[:-1].split(':')
    m=-int(l[0])*60+int(l[1][:2])+(int(l[1][3:])*60+720+int(l[2][:2])-int(l[2][2:]))
    print(f'{m//60}hr {m-(m//60*60)}min')

I'm feeling the irony of pausing my timesheet to do this...
Python 2.7, 133 bytes
Thanks for the suggestions in the comments! Switching to python 2.7 saves a few more bytes because it defaults to integer division:
for l in open('t'):i,h,l=int,60,l[:-1].split(':');m=-i(l[0])*h+i(l[1][:2])+(i(l[1][3:])*h+720+i(l[2][:2])-i(l[2][2:]));print m/h,m%60

The same approach with python3 is 135 bytes because of the print statement and defaulting to float division:
for l in open('t'):i,h,l=int,60,l[:-1].split(':');m=-i(l[0])*h+i(l[1][:2])+(i(l[1][3:])*h+720+i(l[2][:2])-i(l[2][2:]));print(m//h,m%60)

You could save 4 bytes by putting i=int at the beginning and changing the third line to m=-i(l[0])*60+i(l[1][:2])+(i(l[1][3:])*60+720+i(l[2][:2])-i(l[2][2:]))

@DJMcMayhem Thank you! I was trying to think of a way to simplify those...

Very nice first answer, welcome to Programming Puzzles & Code Golf! To help golfing a little, you may be able to take input from STDIN, use map(int,l[:-1].split(':')) and drop the multiple conversions to int, collapse everything to a one-liner by replacing the indentation with ; etc. to save a couple of bytes. Additionally, you can visit Tips for golfing in Python for some more neat tricks other users discovered during their golfer lives :).

Additionally, the OP seems to be less restrictive about the output format, so I think print(m,m%60) would suffice. (Also note the use of m%60 in place of m-(m//60*60))

You can remove most of the indentation and just use one space per line as well.

Wolfram Language 125 119 111 bytes
i=Interpreter;j=IntegerPart;Row@{j[t=(i["Time"][#2<>"pm"]-i["Time"][#])[[1]]-#3/60],"hr ",j[60Mod[t,1]],"min"}&

8 bytes saved thanks to user 202729
Example
Abbreviations are not used here, to make it easier to follow the logic.
Row[{IntegerPart[
 t = (Interpreter["Time"][#2 <> "pm"] -
      Interpreter["Time"][#])[[1]] - #3/60], "hr ",
IntegerPart[60 Mod[t,1]], "min"}] &["9:00", "4:12", 20]

6hr 51min

Interpreter["Time"][#2 <> "pm"]  interprets as a time the second parameter followed by "pm", namely, in this case, "4:12pm", returning a TimeObject corresponding to 4:12 pm.
-Interpreter["Time"][# <> "am"])[[1]] - #3/60].  #3 is the third parameter, namely 20min.  The minus sign subtracts the lunch hour interval from the end of shift time.  It returns the adjusted end of shift time, that is, the end of shift that would apply had the person not taken a lunch break.
Interpreter["Time"][#]  interprets as a time the first parameter, in this case, "9:00", returning a TimeObject corresponding to 9:00 am.
Subtracting the shift start from the adjusted end of shift time yields t, the time interval expressed in hours.  IntegerPart[t] returns the number of complete hours worked.  IntegerPart[60 Mod[t,1]], "min"}] returns the additional minutes worked.

Yes. Thanks.  First time I see Mod[x, 1] used.

Taken from this (deleted) tips. / Actually mod 1 behaves differently from fractional part for negative number. / Can Floor be used for IntegerPart?

Floor returns a, to me, inexplicable result of  -6hr 52min for the sample values I used.   I need to look into this to understand why a negative value for hours (and apparently minutes) was produced.

C, 105 bytes
a,b,c,d,e;f(){for(;scanf("%d:%d%d:%d%d",&a,&b,&c,&d,&e);)a=(12+c-a)*60+d-b-e,printf("%d:%d ",a/60,a%60);}

Completely straightforward. Try it online here.
Ungolfed:
a, b, c, d, e; // start hours, minutes; end hours, minutes; break - all implicitly int
f() { // function - return type is implicitly int (unused)
    for(; scanf("%d:%d%d:%d%d", &a, &b, &c, &d, &e) ;) // until EOF is hit, read line by line
        a = (12 + c - a) * 60 + d - b - e, printf("%d:%d,", a / 60, a % 60); // calculate the minutes and store, then output separated: "h m"
}

Suggest a,b,c,d;f(e) instead of a,b,c,d,e;f() and ;printf("%d:%d ",a/60,a%60))a=(12+c-a)*60+d-b-e;} instead of ;)a=(12+c-a)*60+d-b-e,printf("%d:%d ",a/60,a%60);

JavaScript, 83 bytes 76 bytes
s=>(r=s.match(/\d+/g),r=(r[2]-r[0]+12)*60-r[4]-r[1]+ +r[3],(r/60|0)+':'+r%60)

Just got rid of the inner funtion from below solution (What was I thinking?). Changed the output format as well.
Try it online!

OLD: JavaScript, 112 bytes 111 bytes 110 bytes
s=>(t=(h,m,a)=>(a?12+h:h)*60+m,r=s.match(/\d+/g),r=t(+r[2],r[3]-r[4],1)-t(r[0],+r[1]),`${r/60|0}hr ${r%60}min`)

Explanation:
Inside the main function, we start by defining another that will help us calculate the minutes of a giving time, adding 12 hours to the hours parameter if the third parameter is truthy:
(hours, minutes, addTwelve) =>
    (addTwelve? hours + 12: hours) * 60 + minutes

Next, we split the string by either ' ' or ':' match the numbers inside the string resulting in an array of all the numbers in the string.
Then we calculate the difference of end time and start time and substracting lunch time using the function defined previously (converting the strings to numbers when needed).
Finally we produce the result string: hours are the integer part of r/60 and minutes are r%60.
Try it online!

@Jakob I'm a new codegolf user. I still don't know how things work around here including the TIO. Also I've asked in this comment how would I approach this using javascript but no one responded.

@Jakob TIO fixed. And I'm not using NodeJS, I'm using the browser's console. NodeJS was added by TIO.

Still not sure the input method is legal (this question is unfortunately restrictive), but we may need a more experienced JS golfer to chime in. But also note that programs need to support multiple days of input data--unfortunately that wasn't made very clear in the description.

@Jakob If more days should be used as input I could just make the function accept an array and use map: a=>a.map(...). It will add 5 bytes to my answer. But I'm still waiting for OP (or anyone) response to my comment.

Since pure JavaScript does not have access to standard input or files, I suggest you go with the default method of using a GUI prompt: https://codegolf.meta.stackexchange.com/a/2459/79343

@O.O.Balance How about this.

I don't think that will do you any good since the OP explicitly specified STDIN/file. The answer I linked on the other hand deals specifically with GUI prompts as a substitute for STDIN, and mentions JavaScript as an example for a language where that isn't available.

Generally it's possible to use any of the I/O format listed here, unless OP explicitly specify the format.

Although pure Javascript can't read input/output, the submission may be in "Javascript (Node.js)" or "Javascript (Chrome)" or "Javascript (Firefox)" ... where it's possible to read input/output (using prompt() or process.stdin something like that)

By the way, our main chat room is The Nineteenth Byte. You can ask questions about golfing there. It's usually not very active however.

@user202729 Yes, but OP did specify: read from a file or standard input

Python 2, 100 bytes
for I in open('x'):x,y,z,w,l=map(int,I.replace(':',' ').split());d=60*(12+z-x)+w-y-l;print d/60,d%60

Try it online!
Full program that reads multiple lines from a text file, as directed by OP. A function that just parses a single line would save an addition al 10 bytes.

This is also way more legible than my attempt!

Java 10, 194 191 bytes
u->{var s=new java.util.Scanner(System.in).useDelimiter("\\D");for(int i,a[]=new int[5];;i=(12+a[2]-a[0])*60+a[3]-a[1]-a[4],System.out.println(i/60+":"+i%60))for(i=0;i<5;)a[i++]=s.nextInt();}

I/O is painful in Java. Terminates abnormally when there is no next line of input to read. Try it online here.
Ungolfed:
u -> { // lambda taking a dummy input – we're not using it, but it saves a byte
var s = new java.util.Scanner(System.in).useDelimiter("\\D"); // we use this to read integers from standard input; the delimiter is any character that is not part of an integer
for(int i, a[] = new int[5]; ; // infinite loop; i will be used to loop through each line and to store the result in minutes between lines; a will hold the inputs
    i = (12 + a[2] - a[0]) * 60 + a[3] - a[1] - a[4], // after each line, calculate the result in minutes ...
    System.out.println(i / 60 + ":" + i % 60)) // ... and output the result in hours:minutes, followed by a newline
    for(i = 0; i < 5; ) // read the five integers on the current line ...
        a[i++] = s.nextInt(); // ... into the array
}

Red, 35 bytes
func[s e l][e + 12:0 - s -(l * 60)]

Try it online!
Note: The output is in the format hh:mm:ss

Wow! This is very surprising :)

@Anush Yes, Red (and of course Rebol) has nice time datatype.

R, 97 bytes
s=matrix(strtoi(unlist(strsplit(scan(,""),':'))),5,,T)%*%c(-60,-1,60,1,-1);paste(12+s%/%60,s%%60)

Try it online!
For each line returns "hours minutes"

-16 bytes thanks to JayCe !

I tried using a data.frame to save some bytes - not working so far. But this simple change does :)

this is better (97)