title: Help me sell day-old bagels

text:
# Question
Title: Help me sell day-old bagels
You work at a bakery and every day you make exactly 100 bagels. However your customers are not as reliable and every day a random number of bagels will be ordered. So sometimes you will run out of bagels and sometimes you will have leftovers.

Now leftover bagels will still be good for 1 more day. After a day on the shelves they have to be tossed. But until then you can still sell them. So you keep them for the next day. Customers will *prefer* fresh bagels so if you haven't run out of fresh bagels they will get a fresh bagel. Only when you are out of fresh bagels will they ask for a day-old bagel.

So for example if you have have 25 bagels left over one day and the next day 100 bagels are ordered, you don't sell any of the old bagels so you throw them out and have 0 leftover bagels the next day.

Your task is to write a program or function which takes a non-empty list of non-negative integers representing how many orders were placed in a given time:

e.g.

```
[106,25,134,99,85,12]

```

means that on the first day 106 bagels were ordered, on the second day 25 bagels were ordered and then 134 etc.

Your task is to calculate how many bagels were sold in the described period. You should assume that at the start of the period there will be no leftover bagels available.

This is so answers will be scored in bytes with fewer bytes being the goal.

## Test cases

```
[100,100,100] -> 300
[372,1920,102] -> 300
[25,25,25] -> 75
[25,100,120] -> 225
[0,200] -> 200
[0,175,75] -> 250
[75,150,150] -> 300
[0,101,199]-> 201
[200,0] -> 100

```

# Answer
> 9 votes
# Perl 5 \+ `-p -MList::Util+min`, 28 bytes

```
$\+=min$_,100+$-;$-=100-$_}{

```

Try it online!

## Explanation

Adds the `min`imum of `$_` (implicit input via `-p`) or `100+$-` (where `$-` starts as `0`) to `$\` (which is automatically output at the end of all lines of input).

`$-` is set to `100-$_`, which is safe because `$-` can never be negative.

# Answer
> 8 votes
# BQN, 17 bytesSBCS

```
+´⊢⌊100+·»0⌈100⊸-

```

Run online!

-1 from ovs.

## Explanation

```
{+´⌊100+»0⌈100-}
            100- subtract input from 100
          0⌈      maximum with 0
         »        shift right, prepending a 0
     100+         add 100. This is the number of bagels available on a day.
   ⌊             minimum with input
 +´               sum the minimums

```

# Answer
> 7 votes
# Brainfuck, 148 bytes

```
,[->[-]>[-<+>]>++++++++++[-<++++++++++>],[>>>+<<<-<[->>+>>-<<<<[->>>+<<<]]>>>[-<<<+>>>]>[-<<<<<[->>>+<<<[->>>>+<<<<]]>>>>[-<<<<+>>>>]>]<<<]<<<]>>>>.

```

First is inputed length of array, then the values. Sadly I can't find any site which supports input&output as decimal numbers. Best I got is this site where you can input escape squences like `\3\100\100\100`, but the output is ASCII, so you will need to convert it to decimal. (Please let me know about any sites supporting decimal in comments)

## Explanation

**Memory map**: `arrayLength old fresh order output temp flag`

```
,[-                          loop through all elements of array
  >[-]                       reset old count
  >[-<+>]                    set old count to the remaining amount from fresh
  >++++++++++[-<++++++++++>] set fresh to 100
  ,[                         while there is order
    >>>+                     set flag
    <<<-                     reduce order size
    <[                       check if there are any fresh
      -                      reduce amount of fresh
      >>+                    increase output
      >>-                    unset flag
      <<<<[->>>+<<<]         copy fresh to temp variable so condition can exit
    ]
    >>>[-<<<+>>>]            copy from temp back to fresh
    >[                       check if flag is set (if previous condition wasnt executed it acts as else)
      -                      unset flag
      <<<<<[                 check if there are any old
        -                    reduce amount of old
        >>>+                 increase output
        <<<[->>>>+<<<<]      copy old to temp variable so condition can exit
      ]
      >>>>[-<<<<+>>>>]       copy from temp back to old
      >
    ]<<<
  ]<<<
]

```

# Answer
> 6 votes
# JavaScript (Node.js), ~~57~~ ~~55~~ 54 bytes

```
x=>x.map(i=>[s+=i>a?a:i,a=i>99?100:200-i],s=0,a=100)|s

```

Try it online!

Badly golfed maybe...

# Answer
> 6 votes
# Haskell, 42 bytes

```
sum.(zipWith(min.max 100.(-)200)=<<(100:))

```

Try it online!

Since there's now a Haskell answer I thought I'd toss mine in the ring.

# Answer
> 6 votes
# Excel, 66 bytes

```
=LET(o,A:A,a,100+INDEX((100-o)*(o<100),ROW(o)-1),SUM(IF(o<a,o,a)))

```

Input is in the range `A:A` with each day's order in a cell by itself. Output is wherever the formula is.

The `LET()` function allows you to define variables and later reference them by that variable name. The terms come in pairs (`variable, value`) except the last term which is just the output value.

* `o,A:A` defines `o` (orders) to be the entirety of column A. This technically limits you to about 2,870 years of bagel orders. I consider this to be acceptable.
* `a,100+INDEX((100-o)*(o<100),ROW(o)-1)` defines `a` (available) and does most of the heavy lifting so let's break it down into pieces.
    + `100` is how many bagels are made fresh each day.
    + `(100-o)` is how many leftover fresh bagels there are each day.
    + `*(o<100)` filters out negatives (more orders than fresh so no leftovers).
    + `ROW(o)-1` tells us that we're going to be looking at the data for the previous day.
    + In plain(er) text: `100+INDEX([leftover fresh]*[not negative],[from yesterday])`.
    + All together, you could read it as `[fresh] + [yesterday's fresh leftovers]`.
* `IF(o<a,o,a)` returns either the number of orders (if it was less than what was available) or just what was available.
* `SUM(IF(~))` adds it all up.

# Answer
> 5 votes
# C(gcc -O0), ~~115~~ ~~109~~ ~~84~~ ~~82~~ 78 bytes.

```
m,l,g;f(a,n)int*a;{m=l=0;for(g=100;n--;++a)m+=fmin(g+l,*a),l=*a<g?g-*a:0;m=m;}

```

Try it online!

The function takes two arguments, a pointer to the array and the size of the array.

*-25 bytes thanks to AZTECCO*

*-4 bytes thanks to ceilingcat*

Can I golf it further?

# Answer
> 5 votes
# 05AB1E, 14 bytes

```
тs-Dd*т+тšø€ßO

```

Port of @Razetime's BQN answer.

Try it online or verify all test cases.

**Explanation:**

```
                #  e.g. input = [0,101,199]
тs-             # Subtract the values in the (implicit) input-list from 100
                #  STACK: [100,-1,-99]
   D            # Duplicate this list
                #  STACK: [100,-1,-99],[100,-1,-99]
    d           # Check for each that they're non-negative (>=0)
                #  STACK: [100,-1,-99],[1,0,0]
     *          # Multiply the values at the same positions
                #  STACK: [100,0,0]
      т+        # Add 100 to each
                #  STACK: [200,100,100]
        тš      # Prepend 100
                #  STACK: [100,200,100,100]
          ø     # Create pairs with the (implicit) input-list,
                # ignoring the additional trailing item
                #  STACK: [[0,100],[101,200],[199,100]]
           €ß   # Get the minimum of each pair
                #  STACK: [0,101,100]
             O  # Sum those minima
                #  STACK: 201
                # (after which the result is output implicitly)

```

# Answer
> 5 votes
# Wolfram Language (Mathematica), ~~37~~ 36 bytes

```
Tr[i=c=100;Min[2c-c~Min~i,i=#]&/@#]&

```

Try it online!

# Answer
> 3 votes
# , ~~51~~ 48 bytes

```
function(n,`~`=pmin)sum(c(n,0)~100-c(0,n-100~0))

```

Try it online!

Ports Razetime's BQN answer.

-3 bytes thanks to pajonk.

# Answer
> 3 votes
# Python, 56 bytes

```
lambda a:sum(map(min,[200-min(r,100)for r in[100]+a],a))
```

Attempt This Online!

If it weren't for Python 2 padding arguments to `map` with `None`s, we could abuse its global ordering like so:

```
lambda a:sum(map(min,[200-min(r,100)for r in[a]+a],a))

```

because `a` will always be "larger" than `100`.

As it is, we have to work around it with `a+[0]))` for 58.

---

## Python, 58 bytes

```
lambda a,S=100:sum(min(r,100-S+(S:=min(r,100)))for r in a)
```

Attempt This Online!

# Answer
> 3 votes
# , 19 bytes

```
+/@:<.100>.0,200-}:

```

Try it online!

* `}:`: Remove the last number.
* `200` `-`: Subtract each number from 200.
* `0` `,`: Prepend 0.
* `100` `>.`: Take the maximum of each number with 100. This produces the number of available bagels for each day.
* `<.`: Take the minimum of that and the original values...
`@:`: and then (using composition)...
`+/`: take the sum of the values.
(This whole thing is a hook.)

# Answer
> 2 votes
# Python 3.8 (pre-release), 63 62 bytes

```
f=lambda o,*v,l=1:min(o,99+l)+(len(v)and f(*v,l=max(1,101-o)))

```

Try it online!

Takes the input as a vararg list

# Answer
> 1 votes
# Charcoal, 22 bytes

```
ＩΣＥθ⌊⟦ι⌈⟦¹⁰⁰∧κ⁻²⁰⁰§θ⊖κ

```

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

```
   θ                    Input array
  Ｅ                     Map over orders
    ⌊⟦                  Minimum of
      ι                 Today's order and
       ⌈⟦               Maximum of
         ¹⁰⁰            Literal integer `100` and
             κ          Current index
            ∧           Logical And
               ²⁰⁰      Literal integer `100`
              ⁻         Subtract
                  §θ⊖κ  Previous day's order
 Σ                      Take the sum
Ｉ                       Cast to string
                        Implicitly print

```

# Answer
> 1 votes
# APL+WIN, 24 bytes

Prompts for input

```
+/b⌊100+¯1↓0,0⌈n←100-b←⎕

```

Try it online! Thanks to Dyalog Classic

# Answer
> 1 votes
# Haskell, ~~57~~ 55 bytes

```
(0!)
r!(x:t)|x>100=0!t+min(100+r)x|j<-100-x=x+j!t
_!x=0

```

Try it online!

*saved 2 Bytes thanks to @Wheat Wizard*

# Answer
> 1 votes
# Pari/GP, 56 bytes

```
f(b)=sum(i=1,#b,min(b[i],100+if(i>1,max(0,100-b[i-1]))))

```

Try it online!

# Answer
> 1 votes
# x86-64 machine code, 24 bytes

```
31 c0 99 97 91 ad 01 c7 83 e8 64 01 c2 78 02 29 d7 99 21 c2 e2 ef 97 c3

```

Fixed.
Try it online!

Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length in RDI and the address of an array of 32-bit integers in RSI.

Assembly:

```
.global bagels
bagels:
    xor eax, eax    # EAX = 0.
    cdq             # EDX = 0.
    xchg edi, eax   # Exchange EDI (length) with EAX (0).
    xchg ecx, eax   # Exchange ECX with EAX (length).
                    #   Here, EDI will hold the number of bagels sold, and EDX
sl:                 #    will hold -l, with l being the number of leftover bagels.
    lodsd           # Load the current number n into EAX, advancing the pointer in ESI.
    add edi, eax    # Add the number ordered to EDI.
    sub eax, 100    # Subtract 100 from EAX, producing n-100.
    add edx, eax    # Add n-100 to EDX, producing n-100-l.
    js skip         # Jump if that's negative (more bagels available than ordered).
    sub edi, edx    # (Otherwise) Subtract the shortfall n-100-l from EDI.
skip:
    cdq             # Fill EDX with the sign bit of EAX.
    and edx, eax    # Bitwise AND; makes EDX equal n-100 if it's negative, 0 otherwise.
    loop sl         # Count down from the length in ECX, looping that many times.
    xchg edi, eax   # Switch the result (in EDI) into EAX.
    ret             # Return.

```

# Answer
> 1 votes
# Java (JDK), 73 bytes

```
a->{int s=0,l=0,h=100;for(var o:a){s+=h+l<o?h+l:o;l=o<h?h-o:0;}return s;}

```

Try it online!

# Answer
> 1 votes
# Kotlin, ~~115~~ 101 bytes

shaved off 14 bytes thanks to a helpful user

```
{var s=0;var l=0;for(d in it){var t=Math.min(d,100);t+=Math.min(d-t,l);s+=t;l=100-Math.min(d,100)};s}

```

Try it online!

#### Ungolfed:

```
fun bagelCalculator1(arg: Array<Int>) : Int
{
    var sold = 0
    var left = 0
    for(demand in arg)
    {
        var soldToday = min(demand,100)
                          // V the deficit V
        soldToday += min(demand-soldToday, left)
        sold += soldToday
        left = 100-min(demand,100)
    }
    return sold
}

```

# Answer
> 1 votes
# PHP, 79 bytes

```
function b($a){foreach($a as$o){$t+=min(100+$d,$o);$d=max(0,100-$o);}return$t;}

```

And now I want a bagel :)

Try it online!

# Answer
> 1 votes
# Pip, ~~25~~ 23 bytes

```
MN{H[ah+yYMX[h-a0]]}MSg

```

Takes the list of orders-per-day as separate command-line arguments. Attempt This Online! Or, verify all test cases.

### Explanation

```
                         ; We store the number of leftovers in y (initially = 0)
                      g  ; List of cmdline args
                    MS   ; Map this function and sum the results:
MN                       ; Apply min to the result of
  {                }     ; This function:
   H                     ;   All but the last element of
    [             ]      ;   This list:
     a                   ;     Function arg (today's number of orders),
      h+y                ;     100 plus yesterday's leftovers,
         Y               ;     and yank the new number of leftovers:
          MX[    ]       ;       Take the max of
             h-a         ;       100 minus function arg
                0        ;       and 0

```

# Answer
> 1 votes
# Jelly, 11 bytes

```
ȷ2ð_«Ż+ḷṖ«S

```

Try it online!

Another handful of ports of Razetime's BQN.

`ȷ2` could hypothetically be golfed to `³` if this is used as a function in a program with no command-line arguments, but the existing Jelly corpus seems to discourage this. Modifying the programs to use STDIN has yielded no savings (but thanks to emanresu A for reminding me).

```
ȷ2ð            With 100 as the left argument to a dyadic chain:
    «          Take the minimum of each element of the input and 100,
   _           and subtract each minimum from 100.
     Ż         Prepend a 0,
      +ḷ       add 100 to each,
        Ṗ      remove the last element,
         «     take the pairwise minima with the input,
          S    and sum.

```

# Jelly, 11 bytes

```
ȷ2ɓ«ṖạŻ+ɓ«S

```

Try it online!

# Jelly, 11 bytes

```
ȷ2ðḤ_«Ṗ⁸;«S

```

Try it online!

# Answer
> 1 votes
# Go, 106 bytes

```
func(a[]int)(s int){l,h:=0,100
for _,o:=range a{if h+l<o{s+=h+l}else{s+=o}
if o<h{l=h-0}else{l=0}}
return}

```

Attempt This Online!

Port of Olivier's Java solution.

# Answer
> 0 votes
# ///, 63 bytes

```
/b|/|bbbbb// /bbbb||//b1///b\||1/||//1///b*/*s//*/\/// *//sb//

```

Try it online!

Takes input appended to the program, as space-separated unary numbers using `1`s; produces output in unary using `s`s.

Or, run a modified version with added pre-processing and post-processing to use decimal numbers in input and output.

## Explanation

```
/b|/|bbbbb/
/ /bbbb||/

```

The first substitution modifies the second substitution's replacement string: each `|` multiplies the number of `b`s by 5 as it passes through them, resulting in `||bbb*…(100)…*bbb`.

Then, the second substitution replaces each space with that string. In addition to the spaces between the input numbers, there is one more space from the end of the program (just before the input), so the string appears at the start of every day, providing the 100 bagels (as `b`s) made for the day and a separator `||`.

```
/b1//

```

Use bagels to fulfil orders made on the same day, removing both.

```
/b\||1/||/

```

Use bagels to fulfil orders made on the next day, removing both. The backslash prevents this code from being modified by the first substitution.

```
/1//

```

Remove unfulfilled orders.

```
/b*/*s/
/*/\//
/ */

```

The last of these three pieces will have already been modified by the second substitution in the program, to `/||bbb*…(100)…*bbb*/`. It is further modified here, becoming `/||*sss*…(100)…*sss/` and then `/||/sss*…(100)…*sss/`, and then executed, replacing each day separator `||` with a hundred `s`s, again producing the number of bagels made that day.

```
/sb//

```

Cancel out bagels made with bagels unsold, leaving the number of bagels sold in `s`s.

# Answer
> 0 votes
# TI-Basic, 26 bytes

```
sum(min(Ans,ᴇ2+augment({0},max(0,ᴇ2-ΔList(cumSum(Ans)-Ans

```

Takes input in `Ans`.

---
Tags: code-golf
---


# Question
Title: Get the date of the nth day of week in a given year and month
# Introduction

Often, people refer to dates as the "second Friday in August, 2018" or the "fourth Sunday in March, 2012". But it's hard to tell what date that is! Your task to is to write a program that receives a year, a month, a day of the week, and an integer, and output that date.

# Challenge

* For input, you will get a year, a month, a day of week, and a number.
* You can take input in any reasonable format, like using a string for the day of week or using a zero indexed weekday, or even take the year and month in a single string. Do explain your input format in your answer, though.
* The integer that tells you which day of week in the month to target will be an integer from 1-5. The integer will never refer to a day of week that does not exist(e.g. the fifth Friday of February 2019, which doesn't exist).
* Years will always be positive.
* Your output can be in any reasonable format, including printing your final date. However, please explain your output format un your answer.
* Providing the year and month in the output is optional. Also, you may assume the date is valid.

# Example Input and Output

Consider this input, with the format being taking in the year as a 4 digit number, month as an integer, day of week as string, and the ordinal number as an integer:

> 2019, 3, Saturday, 2
> 2019, 12, Sunday, 1
> 2019, 9 Saturday, 1

Output:

> March 9
> December 1
> September 7

This is , so shortest answer wins.

# Answer
> 6 votes
# MediaWiki Template, 19 bytes

```
{{#time:r|{{{1}}}}}

```

This is a MediaWiki Template ParserFunctions port of this PHP answer

Note: `#time` use PHP `strtotime` internally.

---

Sample Input

> {{#time:r|second saturday of March 2019}}

Sample Output

> Sat, 09 Mar 2019 00:00:00 +0000

# Answer
> 3 votes
# Japt, ~~19~~ 15 bytes

Input is: year, 0-based index of month, 0-based index of day of the week (`0` is Sunday) & `n`.

```
_XµW¶Ze}f@ÐUVYÄ

```

Try it

```
                    :Implicit input of U=year, V=month, W=weekday & X=n
       }f           :Output the first element generated by the right function that returns
                    : falsey (0) when passed through the left function
         @          :Right function. Y=0-based index of current iteration
          ÐUVYÄ     :  new Date(U,V,Y+1)
_                   :Left function. Z=date being passed
 Xµ                 :  Decrement X by
   W¶               :   Test W for equality with
     Ze             :    Z.getDay()

```

# Answer
> 3 votes
# Perl 6, ~~52~~ 48 bytes

```
{1+($^c+4-Date.new($^a,$^b,1).daycount)%7+$^d*7}

```

Try it online!

Anonymous code block that takes input as year, month, day of week (Sunday is 0) and week number (0 indexed). Output is a date object.

### Old Explanation:

```
{                                                  } # Anonymous code block
 (   Date.new(         ))   # Create a new date with
              $^a,$^b,1     # With year, month and the first day
  $_=                       # Save in the variable $_
                         +  # Add to this
                           $^c+4                     # The given day plus 4
                          (     -.daycount)          # The number of days since 17 Nov, 1858
                                           %7        # Modulo 7 to get the correct day
                                             +$^d*7  # Plus the 7 times the number of weeks

```

# Answer
> 2 votes
# PHP, ~~46~~, ~~43~~, 31 bytes

```
<?=date(d,strtotime($argv[1]));

```

Try it online!

The program receives as input a string like `"second saturday of March 2019"`

The program prints the day number.

*-12 bytes thanks to Shaggy.*

# Answer
> 2 votes
# SmileBASIC, ~~58~~ ~~51~~ ~~48~~ ~~46~~ 45 bytes

```
READ N,M$DTREAD M$OUT,,D,W?(5-W+D*2)MOD 7+N*7

```

Input is in the form: `week,year/month/weekday`

* `week`: week number, 0-indexed
* `year`: year, 4 digits
* `month`: month (1-indexed), 2 digits `0`-padded
* `weekday`: day of the week (1-indexed, 1=Sunday), 2 digits `0`-padded

Output is the day of the month, 0 indexed.
The 2nd Saturday in March 2019 would be `1,2019/03/07``8` (March 9th)

## Ungolfed

```
READ WEEK,M$
DTREAD M$ OUT ,,D,W
'Functions in SB can output multiple values using OUT.
'In this case, we don't need the first 2 values, so no variables are given.

PRINT (5-W+ D*2) MOD 7 +WEEK*7

```

## Explanation

The input form was specifically chosen so that the year/month/weekday could be passed directly to `DTREAD`, which is a function which parses a `YYYY/MM/DD` string and returns the year/month/day as numbers, as well as calculating the day of the week.

However, notice that, where `DTREAD` expects the day of the month, we're giving it the day of the week instead. This complicates things, but also means that there are fewer input values and we don't need to add `/01` to the end of the date string.

`DTREAD` outputs `W` and `D`.
`W` is the weekday, and `D` is the day-of-the-week of the `W`th day of the month.
(So, if you input `7` as the weekday, `D` will be `7` and `W` will be whatever day-of-the-week the 7th day of the month is)

The expression `(5-W+D*2)MOD 7` is used to get the 1st occurrence of the input weekday, as a 0-indexed day of the month. (I figured this one out mostly through trial and error)

After that, the program just adds `WEEK*7`.

---

I really wish there were separate words for "day of the week" and "day of the month".

# Answer
> 2 votes
# C# (Visual C# Interactive Compiler), 59 bytes

```
(y,m,d,w)=>1+(d-(int)new DateTime(y,m,1).DayOfWeek+7)%7+7*w

```

Try it online!

-27 bytes thanks to @EmbodimentOfIgnorance!

Less golfed code...

```
// y: year
// m: month
// d: day of week (0 is Sunday)
// w: week number (0 based)
(y,m,d,w)=>
  // start on the first day of the month
  1+
  // determine the number of days to
  // the first occurrence of the
  // requested weekday
  (d-(int)new DateTime(y,m,1).DayOfWeek+7)%7+
  // add the number of requested weeks
  7*w

```

The return value is an integer for the day of the month of the requested date.

# Answer
> 1 votes
# MATL, ~~28~~ 27 bytes

```
'1 'ihYO31:q+t8XOi=!A)i)1XO

```

This uses three inputs:

* String with month and year: `'March 2019'`
* String with three letters, first capitalized, indicating day of the week: '`Sat`'
* Number: `2`.

Output is a string with day, year and month separated with dashes: `09-Mar-2019`.

Try it online!

### Explanation

Consider inputs `'March 2019'`, `'Sat'`, `2`.

```
'1 '    % Push this string
        % STACK: '1 '
ih      % Input string: month and year. Concatenate
        % STACK: '1 March 2019'
YO      % Convert to serial date number
        % STACK: 737485
31:q+   % Create vector [0 1 2 ... 30] and add element-wise
        % STACK: [737485 737486 737487 ... 737515]
t8XO    % Duplicate. Convert to date format 'ddd': day of week in three letters. Gives
        % a 2D char array
        % STACK: [737485 737486 737487 ... 737515], ['Fri'; 'Sat'; 'Sun'; ...; 'Sun']
i=      % Input string: day of week in three letters. Compare element-wise with broadcast
        % STACK: [737485 737486 737487 ... 737515],
        % [0 0 0; 0 0 0; ...; 1 1 1; 0 0 0; ... 1 1 1; ...]
!A      % True for rows containing only 1
        % STACK: [737485 737486 737487 ... 737515], [0 0 ... 1 ... 0 ... 1 ...]
)       % Index: uses the second vector as a mask into the first
        % STACK: [737486 737493 737500 737507 737514]
i)      % Input number. Index
        % STACK: 737493
1XO     % Convert to date format 'dd-mmm-yyyy'. Implicit display
        % STACK: '09-Mar-2019'

```

# Answer
> 1 votes
# , ~~72~~ 69 bytes

```
function(y,m,d,n,D=as.Date(paste0(y,-m,-1))+0:31)D[weekdays(D)==d][n]

```

Try it online!

Taking input as :

* Year number
* Month number (1-12)
* Weekday string in the current locale (TIO requires english name with capital letter)
* Ordinal number (1-indexed)

# Answer
> 1 votes
# Python 3, ~~92~~ 82 bytes

82 bytes thanks to @Jo King

```
lambda y,m,d,w:z(y,m)[w-(z(y,m)[0][d]>0)][d]
from calendar import*
z=monthcalendar

```

Try it online!

### Original version, 92 bytes

```
from calendar import*
def f(y,m,d,w):
 x=monthcalendar(y,m)
 if x[0][d]:w-=1
 return x[w][d]

```

Try it online!

Takes the year as an integer, month as a 1-indexed integer, day of the week as a 0-index integer where Monday is `0` and Sunday is `6`, and week of the month as a 1-indexed integer.

How it works:

```
# import monthcalendar
from calendar import*
# function with 4 inputs
def f(y,m,d,w):
 # get a 2-D array representing the specified month
 # each week is represented by an array
 # and the value of each element is its date of the month
 # Monday is the 0th element of each week, Sunday is the 6th element
 # days of the first week of the month before the 1st are 0s
 x=monthcalendar(y,m)
 # if the first week of the month includes the desired day of week
 # convert the week of month to 0-index so that it takes into account the first week
 if x[0][d]:w-=1
 # return the weekday of the week number specified
 return x[w][d]

```

# Answer
> 0 votes
## JavaScript (ES6), ~~49~~ 48 bytes

```
f=
(a,d,n)=>(d+6-new Date(...a,7).getDay())%7+n*7-6
```

```
<div oninput=o.textContent=f([+y.value,+m.value],+d.value,+n.value)>Year: <input id=y type=number value=2019><br>Month: <select id=m><option value=0>Jan<option value=1>Feb<option value=2>Mar<option value=3>Apr<option value=4>May<option value=5>Jun<option value=6>Jul<option value=7>Aug<option value=8>Sep<option value=9>Oct<option value=10>Nov<option value=11>Dec</select><br>Day: <select id=d><option value=0>Sun<option value=1>Mon<option value=2>Tue<option value=3>Wed<option value=4>Thu<option value=5>Fri<option value=6>Sat</select><br>Count: <input id=n type=number value=1 min=1 max=5><pre id=o>
```

Takes parameters as `f([year, month], day, number)`. Month and day of week (starting on Sunday) are zero-indexed. Edit: Saved 1 byte thanks to @Shaggy.

# Answer
> 0 votes
# Groovy, 46 bytes

```
{y,m,d,w->r=new Date(y,m,7*w)
r-(r.day+7-d)%7}

```

Try it online!

Input as years since 1900, 0-indexed month, 0-indexed day (Sunday being 0) and week number

# Answer
> 0 votes
# Red, ~~64~~ 60 bytes

```
func[y m d n][a: to-date[1 m y]d - a/10 - 7 % 7 +(n * 7)+ a]

```

Try it online!

Takes the year, the month and the weekday as numbers, 1-indexed, Monday is the first day of the week.

# Answer
> 0 votes
# Scala, 86 bytes

```
(y,m,d,w)=>{var r=new java.util.Date(y,m,7*w)
r.setDate(r.getDate-(r.getDay+7-d)%7)
r}

```

Try it online!

# Answer
> 0 votes
# APL (Dyalog Unicode), ~~36~~ 28 bytesSBCS

Full program. Prompts for `[year,month]` (January is 1), then for day (Sunday is 0), then for n (first is 1).

```
¯1⎕DT⎕⊃d/⍨⎕=7|d←(⍳31)+1⎕DT⊂⎕

```

prompt console for `[year,month]` numbers

`1⎕DT⊂` days since 1899-12-31 of the 0th of that month

`(⍳31)+` add the **i**ntegers 1…31 to that

`d←` store in `d` (for **d**ay numbers)

`7|` division remainder when dividing by 7 (day-of-week with Sunday being 0 due to good epoch)

`⎕=` prompt console for day-of-week number and get mask where equal the day-of-week numbers

`d/⍨` filter `d` with that mask

`⎕⊃` prompt console for n and use that to pick from the list of day numbers

`¯1⎕DT` datetime stamp (has trailing zeros for hours, minutes, seconds, milliseconds)

# Answer
> 0 votes
# TSQL, 106 bytes

```
DECLARE @ datetime='2019',@m int=3,@w char(2)='saturday',@p int=2

SELECT dateadd(wk,datediff(d,x,dateadd(m,@m-1,@)-1)/7,x)+@p*7FROM(SELECT
charindex(@w,' tuwethfrsasu')/2x)x

```

Output:

```
2019-03-09 00:00:00.000

```

**Try it out**

# Answer
> 0 votes
# Kotlin, ~~131~~ 84 bytes

47 bytes thanks to ASCII-only's code and comment.

Input: year, monthNumber, weekdayNumber, weekNumber

All integers 1 to maximum on single line. Week day number is Sunday of 1 to Saturday of 7. The main program makes the year lose 1900 for Date class and month and weekday are shifted to start with zero instead of one before calling the lambda. You can enter your arguments in the input text box to try your own dates.

Output: a Date class instance. The main program displays the result like: Sat Mar 09 00:00:00 UTC 2019.

There is an expanded version with comments explaining the code for those wishing to learn more.

```
{y,m,d,w->val r=java.util.Date(y,m,7*w)
r.setDate(r.getDate()-(r.getDay()+7-d)%7)
r}

```

Try it online!

# Answer
> 0 votes
# Go, 177 bytes

```
import."time"
func f(y,m,d string,n int)string{t,_:=Parse("20061",y+m)
D:=Hour*24
for t.Weekday().String()!=d{t=t.Add(D)}
for i:=1;i<n;i++{t=t.Add(D*7)}
return t.Format("Jan2")}

```

Attempt This Online!

Outputs the month and the day as `Jan2`.

### Explanation

```
import."time"
func f(y,m,d string,n int)string{
t,_:=Parse("20061",y+m)

```

Parse the date to get the first of the month. `time.Date()` is not feasible here because of the need for a location, which we don't need here.

```
D:=Hour*24

```

A time constant alias because Go doesn't provide time constants higher than `Hour`.

```
for t.Weekday().String()!=d{t=t.Add(D)}

```

Increment the day until we get the desired day.

```
for i:=1;i<n;i++{t=t.Add(D*7)}

```

Add weeks until we get the desired `n`-th day of the month.

```
return t.Format("Jan2")}

```

Return a string of the date, formatted as a 3-letter month and the date.

---
Tags: code-golf, date
---


# Question
Title: Get the date of the Nth day of week after the Xth day of week in a given year and month
**Introduction**

In the United States, national elections are normally held on the first Tuesday after the first Monday in November.

**Challenge**

Write a program that takes a Year as integer, and a pair of (day of week as character and ordinal as integer) and output the date as "yyyy-mm-dd" Remember, the second pair is after the first pair. use this for inspiration: https://codegolf.stackexchange.com/questions/178227/get-the-date-of-the-nth-day-of-week-in-a-given-year-and-month\[\]\[1\]

**Example Input and Output**

Example input:

* 2021 November Tuesday 1 Monday 1
* 2020 November Tuesday 1 Monday 1
* 2020 December Friday 2 Wednesday 1
* 2019 April Wednesday 1 Friday 1
* 2023 February Tuesday 4 Wednesday 1
* 2023 February Wednesday 5 Thursday 1
* 2022 December Sunday 5 Sunday 55

Expected output:

* "2021-11-02"
* "2020-11-03"
* "2020-12-11"
* "2019-04-10"
* "2023-02-28"
* "NA"
* "NA"

Note: the output indicated as "NA" could be any negative finding such as null, but not an error. \[1\]: Get the date of the nth day of week in a given year and month

# Answer
# JavaScript, ~~102~~ ~~93~~ ~~91~~ ~~88~~ ~~80~~ ~~78~~ 77 bytes

Oof, this made my brain itch. Possibly still some room for improvement.

```
(m,t,x=0)=>g=w=>(d=new Date(...m,++x)).getDay()-w[0]||--w[1]?g(w):w!=t?g(t):d

```

Try it online!

Call with `f([y,m],[W,O])([w,o])`, where:

* `y` is the year,
* `m` is the 0-indexed month,
* `W` is the 0-indexed target weekday (`0`=Sunday),
* `O` is the ordinal of `W`,
* `w` is the 0-indexed starting weekday, and,
* `o` is the ordinal of `w`

**EDIT:** Looking at the rest of the solutions coming in, they seem to be interpreting the I/O requirements of the spec a *lot* more strictly than I am. After a few read-throughs, I'm not seeing that strictness, nor would it be reasonable to assume it's that strict. Still, though, seeing as I appear to be the only one taking the requirements *this* loosely, I'll take a stab at an alternative solution on Tuesday. (It's a bank holiday weekend in Ireland)
> 3 votes

# Answer
# C (gcc), ~~439~~ 428 bytes

* -11 thanks to ceilingcat

Most of the code is parsing the input.

```
#define z(d)(*d-83?*d-84?*d-77?*d-87?5:3:1:d[1]-117?4:2:d[1]-117?6:0)
#define Z(d,e)(d-e+(d<e?7:0))
t[20],a,b,n,x,y;char*m,*d,*e;f(s){sscanf(s,"%d %ms %ms %d %ms %d",&y,&m,&d,&a,&e,&b);t[5]=y-=1900;x=*m-78;t[4]=n=x+4?~x?x+13?x+8?x-5?x-1?x?11:10:9:8:1:m[1]-112?7:3:m[2]-114?2:4:m[1]-97?m[2]-110?6:5:0;t[3]=1;mktime(&t);t[3]+=Z(z(e),t[6])+(a+b-2)*7+Z(z(d),z(e));mktime(&t);t[4]-n|t[5]-y||printf("%04d-%02d-%02d",y+1900,n+1,t[3]);}

```

Try it online!

Ungolfed:

```
// Day of week: Su=0, M=1, Tu=2, W=3, Th=4, F=5, Sa=6
#define z(d)(*d-'S'?*d-'T'?*d-'M'?*d-'W'?5:3:1:d[1]-'u'?4:2:d[1]-'u'?6:0)
// Add one week if the target day of week precedes the current one
#define Z(d,e)(d-e+(d-e<0?7:0))
t[20], // struct tm for time conversions (important parts are initialized each run through)
a, b, // week numbers
x, // temporary for month calculation
n, y; // month and year
char *m, *d, *e; // original string versions of days, month and year
f(int*s) {
  sscanf(s,"%d %ms %ms %d %ms %d",&y,&m,&d,&a,&e,&b); // get the parsed data
  t[5]=y-=1900; // adjust the year
  x=*m-78; // get most values into single-digit
  // Month: Ja=0 F=1 M_r=2 Ap=3 M_y=4 J_n=5 J_l=6 Au=7 S=8 O=9 N=10 (else) 11
  //t[4]=n=*m-'J'?*m-'M'?*m-'A'?*m-'F'?*m-'S'?*m-'O'?*m-'N'?11:10:9:8:1:m[1]-'p'?7:3:m[2]-'r'?2:4:m[1]-'a'?m[2]-'n'?6:5:0;
  t[4]=n=x+4?~x?x+13?x+8?x-5?x-1?x?11:10:9:8:1:m[1]-112?7:3:m[2]-114?2:4:m[1]-97?m[2]-110?6:5:0;
  t[3]=1; // start on the first day of the month
  mktime(&t); // get the day of week information
  t[3]+=Z(z(e),t[6])+(a+b-2)*7+Z(z(d),z(e)); // add offsets
  mktime(&t); // convert to canonical form
  t[4]-n|t[5]-y?printf("%04d-%02d-%02d",y+1900,n+1,t[3]); // only print date if it is still inside the month
}

```
> 2 votes

# Answer
# 05AB1E, 204 (or 126?) bytes

With strict I/O and outputting `NA` when the date goes beyond the given input month+year: **204 bytes**:

```
"Y`т‰0Kθ4ÖUD<i\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝV"ˆ$”‚æ‡‰…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í……”#s#©1èk>Dˆ®н)V®2ô¦RvyθFNĀi¯н.V}[Y`UD3‹©12*+>₂*T÷®Xα©т%D4÷®т÷©4÷®·(O7%”ŒÍ‹Ó‹ŽŒ¹ŒêŒÛŠ¯”#yнkQ#¯н.V]YÂT‰J'-ýsÅs¯θÊi„NA

```

The cumbersome I/O and 05AB1E's lack of date builtins make for a pretty big program.

Try it online or verify all test cases.

With flexible I/O and just continue calculating instead of outputting `NA`: **126 bytes**:

```
"Y`т‰0Kθ4ÖUD<i\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝV"ˆ1šVvyθFNĀi¯н.V}[Y`UD3‹©12*+>₂*T÷®Xα©т%D4÷®т÷©4÷®·(O7%yнQ#¯н.V]Y

```

Two inputs in the formats `[month,year]` and `[[weekday2,amount2],[weekday1,amount1]]`, where `month` is an integer `1-12` and `weekday` are integers `0-6` for Saturday to Friday.
Outputs in the format `[day,month,year]`.

Still pretty big with the manual calculations, but apparently more than 1/3rd of my top program's bytes are to deal with just the I/O formats.

Try it online.

**Explanation (of the larger strict I/O version):**

Step 0: Create a function to go to the next day, which we'll re-use later on (see this 05AB1E answer of mine for an in-depth explanation of how we're going to the next day manually of a given date):

```
"Y`т‰0Kθ4ÖUD<i\28X+ë<7%É31α}‹iY¬>0ëY1¾ǝDÅsD12‹i>1ë\1Dǝ¤>2}}ǝV"
                 # Push this string to act as function later on with an eval
 ˆ               # Add it to the global array†

```

<sup>† The reason I use the global array instead of a variable: I'm already using all three `U/X`, `V/Y`, and `©®` variable setters/getters in the actual manual date calculations.</sup>

Step 1: Extract the year and month from the input, and parse it as `[1,m,y]` triplet-list:

```
$                # Push 1 and the input-string
 ”‚æ‡‰…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í……”
                 # Push dictionary string "January February March April May June July August September October November December"
  #              # Split it on spaces to a list
   s             # Swap so the input-string is at the top of the stack
    #            # Split it on spaces as well
     ©           # Store this sextuple input-list in variable `®` (without popping)
      1è         # Pop and get the Month at (0-based) index 1
        k        # Get the (0-based) index of this month in the list
         >       # Increase it by 1 to a 1-based index
          Dˆ     # Add a copy to the global array as well
            ®    # Push the input-list of variable `®` again
             н   # Pop and leave its first item (the year)
              )  # Wrap all three values into a list: [1,m,y]
               V # Pop and store it in variable `Y`

```

Step 2: Parse the remainder of the input-string, and start looping:

```
®                # Push the input-list from variable `®` again
 2ô              # Split it into parts of size 2
   ¦             # Remove the first part (the [year,"Month"])
    R            # Reverse the other two parts
     v           # For each over the pairs `y` in the pair:
      yθ         #  Push the last item of the current pair (the amount of days)
        F        #  Pop and inner loop that many times:
         NĀi     #   If it's NOT the first iteration:
            ¯н.V #    Go to the next day
                 #    by evaluating the first item of the global array of step 0
           }     #   Close the if-statement
         [       #   Start an inner infinite loop:

```

Step 3a: Calculate the DayOfWeek of the current date as `[0,1,2,3,4,5,6]` for `[Saturday,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday]` respectively (see again this 05AB1E answer of mine for an in-depth explanation of how I calculate the Day of the Week manually of a given date):

```
Y`UD3‹©12*+>₂*T÷®Xα©т%D4÷®т÷©4÷®·(O7%

```

Step 3b+c: If this day is equal to the input-date of the current pair `y`, stop the infinite loop. If not, go to the next day and continue looping.

```
”ŒÍ‹Ó‹ŽŒ¹ŒêŒÛŠ¯” #    Push dictionary string "Saturday Sunday Monday Tuesday Wednesday Thursday Friday"
 #               #    Split it on spaces to a list
  yн             #    Push the first item of the current pair (the day)
    k            #    Get its 0-based index in the list of weekdays
     Q           #    Check whether it's equal to the calculated DayOfWeek from step 3a
      #          #    If they're equal:
      #          #     Stop the inner infinite loop
       ¯н.V      #    (Else) Go to the next day by evaluating step 0 again

```

Step 4: Format the resulting date to the desired output-format:

```
]                # Close the three loops
 Y               # Push the resulting date `Y`
  Â              # Bifurcate this triplet; short for Duplicate & Reverse copy
   T‰J           # Format the day/month with leading 0:
   T‰            #  Divmod each inner value by 10
     J           #  Join each inner pair together
      '-ý       '# Join the triplet-list with "-" delimiter
  s              # Swap the triplet to the top of the stack again
   Ås            # Only leave its middle item (the month)
     ¯θ          # Push the last item of the global array (the parsed input-month)
       Êi        # If they are NOT equal:
         „NA     #  Push string "NA"
                 # (after which the top of the stack is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `”‚æ‡‰…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í……”` is `"January February March April May June July August September October November December"` and `”ŒÍ‹Ó‹ŽŒ¹ŒêŒÛŠ¯”` is `"Saturday Sunday Monday Tuesday Wednesday Thursday Friday"`.

Both `"ˆ$”‚æ‡‰…ä†ï€¿…Ë…ê†Ä…æ…Ì…Í……”#I#1èk>` and `”ŒÍ‹Ó‹ŽŒ¹ŒêŒÛŠ¯”#yнk` can probably be golfed a bit with magic numbers of some sort, but since I suck at those and I also couldn't really be bothered in an answer already this big because of manual date calculations, the indexing into dictionary strings will do for now.
> 1 votes

# Answer
# Go, 262 bytes

```
import."time"
func f(y,m,d,e string,n,o int)string{t,_:=Parse("2006January",y+m)
D,i,j:=Hour*24,1,1
for t.Weekday().String()!=e{t=t.Add(D)}
for;j<o;j++{t=t.Add(D*7)}
for t.Weekday().String()!=d{t=t.Add(D)}
for;i<n;i++{t=t.Add(D*7)}
return t.Format("2006-01-02")}

```

Attempt This Online!

Extremely similar to my solution for "Get the date of the nth day of week in a given year and month".

For the `NA` test cases, it continues on to the next month/year until it finds the `n`-th `d`day after the `o`-th `e`day.

### Explanation

```
import."time"
func f(y,m,d,e string,n,o int)string{
t,_:=Parse("2006January",y+m)
D:=Hour*24

```

Some initial setup: getting the 1st of month `m` in the year `y`, and defining a `D`ay variable.

```
for t.Weekday().String()!=e{t=t.Add(D)}
for j:=1;j<o;j++{t=t.Add(D*7)}

```

Skip forward to the `o`-th `e`day.

```
for t.Weekday().String()!=d{t=t.Add(D)}
for i:=1;i<n;i++{t=t.Add(D*7)}

```

Skip forward to the `n`-th `d`day.

```
return t.Format("2006-01-02")}

```

Return a formatted date.
> 1 votes

---
Tags: code-golf, date
---


title: Create a bingo card generator

text:
# Question
Title: Create a bingo card generator
# Bingo

Bingo is a numbers game where players match randomly drawn numbers to the numbers on their cards. Each bingo card is a square grid with 25 spaces, and the columns of the grid are labeled with letters such as "B", "I", "N", "G", "O". The letters help to identify the number range in each column, for example, the "B" column may contain numbers 1 to 15.

One of the spaces in the middle of the grid is often a "free" space, and is marked as such. To play the game, each player is given a bingo card with numbers on it. A caller then draws numbers randomly and announces them, and players mark the corresponding numbers on their cards. The first player to match a pre-determined pattern of marked numbers, such as a straight line, all four corners, or a full card, calls out "Bingo!" to win the game. The game continues until one player wins, or multiple players win on the same round. \[1\]

---

# Challenge

Create a set of `n` bingo cards that are printed / outputted in sequence separated by one or two empty lines. The center field should be marked as `free`.

The output should be a 5x5 grid where columns are either separated by a single space, a tab or the grid should be fixed width, and the lines are separated by a single new line.

The randomness must be uniform, i.e. all possible permutations and combinations should be equally likely to occur. All numbers must be unique.

The numbers:

```
B = 1 - 15
I = 16 - 30
N = 31 - 45
G = 46 - 60
O = 61 - 75

```

The number `n` must be taken as input.

## Example output for `n = 3`:

```
B I N G O
1 16 31 46 61
2 17 32 47 62
3 18 free 48 63
4 19 34 49 64
5 20 35 50 65

B I N G O
6 30 40 53 64
5 20 35 50 70
4 25 free 51 69
7 22 32 52 68
11 23 38 49 67

B I N G O
10 25 40 55 70
11 26 41 56 71
12 27 free 57 73
13 28 43 58 73
14 29 44 59 74

```

Yes, those were definitely randomly created.

---

This challenge is based on the fact that I recently had to create 100 Bingo cards. It turned out that this part of the challenge was the easy one. Making it pretty, printable and presentable was the time consuming part.

\[1\] https://chat.openai.com/chat

# Answer
> 7 votes
# Vyxal `J`, 29 bytes

```
(‛₆ṫ⇧Ṅ75ɾ15ẇƛÞ℅5Ẏ;∩2≬2‛λċȦV⁋¶

```

Try it Online!

## Explained (old)

```
(        # input times:
75ɾ15ẇ   #   push the range [1, 75] split into chunks of 15 items
ƛÞ℅5Ẏ;   #   to each: random_permutation[:5]
∩        #   transpose
2≬2‛λċȦV #   tos[2][2] = "free"
‛₆ṫ⇧p    #   .prepend("BINGO")
vṄ⁋      #   .map(" ".join(x)).join("\n")
¶+,      #   + "\n" (then print)

```

# Answer
> 5 votes
# QBasic, 211 bytes

```
DIM b(5,5)
RANDOMIZE TIMER
INPUT n
FOR i=1TO n
ERASE b
?
?"B","I","N","G","O
FOR r=0TO 4
FOR c=0TO 4
4x=INT((c+RND)*15+1)
FOR p=0TO r
IF x=b(p,c)GOTO 4
NEXT p
IF(r=2)*(c=2)THEN?"free",ELSE?x,:b(r,c)=x
NEXT c,r,i

```

Try it at Archive.org! Example run:

## Explanation/ungolfed

```
DIM b(5, 5)
RANDOMIZE TIMER
INPUT n

```

Declare `b` as a 5x5 array; we'll use this to track already-selected numbers and avoid duplicates. Seed the pseudo-random number generator using the current time. Prompt the user for the number of cards `n`.

```
FOR i = 1 TO n

```

Loop `n` times:

```
ERASE b
PRINT
PRINT "B", "I", "N", "G", "O"

```

Set all values in `b` to zero. Print a blank line followed by the B I N G O header. The commas in the `PRINT` statements separate the items by tabs, using a default tab stop of 14 columns.

```
FOR r = 0 TO 4
FOR c = 0 TO 4

```

Loop over rows 0 through 4; for each row, loop over columns 0 through 4.

```
4 x = INT((c + RND) * 15 + 1)

```

Label this as line number , which we'll use as a `GOTO` target later. Set `x` to be a random integer, greater than or equal to `c*15+1`, and less than `(c+1)*15+1`.

```
FOR p = 0 TO r
IF x = b(p, c) THEN GOTO 4
NEXT p

```

Loop over each previous row `p`. If `x` equals the value in array `b` at row `p`, column `c`, go back to line 4 and generate a new random number.

```
IF (r = 2) * (c = 2) THEN
  PRINT "free",
ELSE
  PRINT x,
  b(r, c) = x
END IF

```

If both `r` and `c` are 2, print the string `"free"`; otherwise, print `x` and set the appropriate value in the `b` array to `x`. In both cases, end the print statement with a tab rather than a newline.

```
NEXT c, r, i

```

Close all the `FOR` loops.

---

Astute readers may have noticed this doesn't print a newline at the end of each row. Because of the size of the default tab stop, it just so happens that the sixth column wraps to the next line, so printing a newline explicitly is unnecessary (and, in fact, results in unwanted blank lines). This might be bending the I/O requirements a bit. If an explicit newline must be printed, modify the B I N G O line by adding `",` at the end, and add a line containing `?` in between the `FOR r` and `FOR c` headers.

# Answer
> 4 votes
# JavaScript (ES6), 132 bytes

```
f=N=>(F=n=>N?n<30?F[k=n%5]^(F[k]|=1<<(v=Math.random()*15))?(n++-17?"_BINGO"[n]||k*15-~v:'free')+`
`[k>>2]+F(n):F(n):`
`+f(N-1):n)``

```

Try it online!

### Commented

```
f = N => (              // outer function taking the number N of grids
  F = n =>              // inner function taking a counter n
  N ?                   // if there's still a grid to process:
    n < 30 ?            //   if n is less than 30:
      F[k = n % 5]      //     k is the column index in [0..4]
      ^                 //     if F[k] is not equal to its updated value
      ( F[k] |= 1 << (  //     where the floor(v)-th bit is set
          v =           //     where v is
          Math.random() //     randomly picked in [0,15[
          * 15          //
      )) ?              //     then:
        ( n++ - 17 ?    //       if this is not the center cell:
            "_BINGO"[n] //         append either a BINGO letter (if n <= 5)
            ||          //         or
            k * 15 - ~v //         the number k * 15 + floor(v + 1)
          :             //       else:
            'free'      //         append the word 'free'
        ) +             //
        ` \n`[k >> 2] + //       append a line-feed if k = 4,
                        //       or a space otherwise
        F(n)            //       append the result of a recursive call to F
      :                 //     else:
        F(n)            //       try again
    :                   //   else:
      `\n` +            //     append a line-feed followed by
      f(N - 1)          //     the result of a recursive call to f
  :                     // else:
    n                   //   stop the recursion
)``                     // initial call to F with n zero'ish

```

# Answer
> 4 votes
# Factor, 123 bytes

```
[ [ "free"2 75 [1,b] 15 group [ 5 sample ] map flip
[ third set-nth ] keep "BINGO"1 group prefix simple-table. nl ] times ]

```

Try it online!

* `[ ... ] times` Do something a number of times.

```
"free"                 ! "free"
2                      ! "free" 2
75                     ! "free" 2 75
[1,b]                  ! "free" 2 { 1 2 ... 75 }
15                     ! "free" 2 { 1 2 ... 75 } 15
group                  ! "free" 2 { { 1 2 .. 15 } { 16 17 .. 30 } ... { 61 62 .. 75 } }
[ 5 sample ] map       ! "free" 2 {
                       !     { 9 13 14 1 5 }
                       !     { 26 24 25 27 22 }
                       !     { 32 38 41 31 33 }
                       !     { 54 59 55 49 57 }
                       !     { 75 74 70 71 63 }
                       ! }
flip                   ! "free" 2 {
                       !     { 9 26 32 54 75 }
                       !     { 13 24 38 59 74 }
                       !     { 14 25 41 55 70 }
                       !     { 1 27 31 49 71 }
                       !     { 5 22 33 57 63 }
                       ! }
[ third set-nth ] keep ! {
                       !     { 9 26 32 54 75 }
                       !     { 13 24 38 59 74 }
                       !     { 14 25 "free" 55 70 }
                       !     { 1 27 31 49 71 }
                       !     { 5 22 33 57 63 }
                       ! }
"BINGO"                ! { ... } "BINGO"
1 group                ! { ... } { "B" "I" "N" "G" "O" }
prefix                 ! {
                       !     { "B" "I" "N" "G" "O" }
                       !     { 9 26 32 54 75 }
                       !     { 13 24 38 59 74 }
                       !     { 14 25 "free" 55 70 }
                       !     { 1 27 31 49 71 }
                       !     { 5 22 33 57 63 }
                       ! }
simple-table.          ! output to stdout
nl                     ! newline

```

# Answer
> 4 votes
# Japt `-mR`, ~~39~~ 38 bytes

```
75õ òF Ëö¤v5Ãg2Èh2`fe`ÃÕi"BINGO"¬ m¸·

```

Try it

```
75õ òF Ëö¤v5Ãg2Èh2`fe`ÃÕi"BINGO"¬ m¸·     :Implicit map of range [0,input)
75õ                                        :Range [1,75]
    ò                                      :Partitions of length
     F                                     :  15
       Ë                                   :Map
        ö¤                                 :  Shuffle
          v5                               :  First 5 elements
            Ã                              :End map
             g2                            :Modify the element at 0-based index 2 by
               È                           :Passing it through the following function
                h2                         :  Replace the element at 0-based index 2 with
                  `fe`                     :  Compressed string "free"
                      Ã                    :End modification
                        Õ                  :Transpose
                         i                 :Prepend
                          "BINGO"¬         :  "BINGO", split into an array
                                   m       :Map
                                    ¸      :  Join with spaces
                                     ·     :Join with newlines
                                           :Implicit output joined with newlines

```

# Answer
> 3 votes
# Charcoal, ~~54~~ ~~52~~ 49 bytes

```
ＦＮ«≔⪪BINGO¹θＦ²⁵⊞θ⎇⁼κ¹²free‽⁻⁺×¹⁵﹪κ⁵…¹¦¹⁶θ⟦Ｅ⪪θ⁵⪫κ

```

Try it online! Link is to verbose version of code. Explanation: Now inspired by @Arnauld's answer.

```
ＦＮ«

```

Input `n` and loop that many times.

```
≔⪪BINGO¹θ

```

Start with a list of `BINGO` as separate characters which will make up the first row.

```
Ｆ²⁵

```

Loop `25` times.

```
⊞θ⎇⁼κ¹²free‽⁻⁺×¹⁵﹪κ⁵…¹¦¹⁶θ

```

Put the word `free` in the middle cell, otherwise take a random element of the appropriate numeric range for the cell but subtracting all of the numbers generated so far, and push the result to the list.

```
⟦Ｅ⪪θ⁵⪫κ

```

Split into rows of five cells, join the rows on spaces and output the resulting board double-spaced from the next board.

# Answer
> 3 votes
# Pyth, 39 bytes

```
VQkjd"BINGO"jjL\ Cc5X%3s.SMc5S75y6"free

```

Try it online!

### Explanation

```
                                           # implicitly assign Q = eval(input())
VQ                                         # for N in range(Q):
  k                                        # print a newline
   jd"BINGO"                               # print BINGO joined on spaces
                             S75           # range(1,76)
                           c5              # split into 5 equal parts
                        .SM                # randomly shuffle each part
                       s                   # join the parts back together
                     %3                    # take every third element
                    X           y6"free    # replace the 12th element with "free"
                  c5                       # split into 5 equal parts again
                 C                         # transpose
             jL\                           # join each part on whitespace, converting all elements to strings
            j                              # join on newlines and print

```

# Answer
> 3 votes
# 05AB1E, 32 bytes

```
F75L5äε.r5£N<i'€²2ǝ}}ø‘Èß‘Sš»,¶?

```

Try it online.

**Explanation:**

```
F                # Loop the (implicit) input-integer amount of times:
 75L             #  Push a list in the range [1,75]
    5ä           #  Split it into five equal-sized parts
      ε          #  Map over each part:
       .r        #   Randomly shuffle the list
         5£      #   Then only keep the first 5 integers
       N<i       #   If the index is 2:
          '€²   '#    Push dictionary string "free"
             2ǝ  #    Insert it at (0-based) index 2 into the quintuplet-list
      }}         #  Close both the if-statement and map
        ø        #  Zip/transpose the matrix; swapping rows/columns
         ‘Èß‘    #  Push dictionary string "BINGO"
             S   #  Convert it to a list of characters: ["B","I","N","G","O"]
              š  #  Prepend it to the matrix
               » #  Join each inner list by spaces; and then each string by newlines
 ,               #  Pop and print it with trailing newline
  ¶?             #  And print an additional newline character

```

See this 05AB1E tip of mine (section *How to use the dictionary?*) to understand why `'€²` is `"free"` and `‘Èß‘` is `"BINGO"`.

# Answer
> 3 votes
# Pip, ~~50~~ 49 bytes

```
La{Y ZSH*\,75CH5y@2@2:"free"P_JsPBnMyH5PE"BINGO"}

```

Attempt This Online!

### Explanation

```
La{...}

```

Given command-line argument `a`, loop that many times:

```
Y ZSH*\,75CH5
      \,75            ; Inclusive range from 1 to 75
          CH5         ; Chop into 5 equal sections
   SH*                ; Randomly shuffle each section
  Z                   ; Transpose
Y                     ; Yank that result into the y variable

y@2@2:"free"          ; Set the element of y at index 2,2 to the string "free"

P_JsPBnMyH5PE"BINGO"
        yH5           ; Take the first 5 elements of y
           PE"BINGO"  ; Prepend the element "BINGO"
       M              ; Map to each:
 _Js                  ;  Join on spaces
    PBn               ;  and push a newline to the end of the resulting string
P                     ; Print that list, concatenated, with a trailing newline

```

# Answer
> 3 votes
# Bash \+ GNU utils, 120

```
for((;j++<$1;));{
for((;++i<75;));{
a+=" <(shuf -i$i-$[i+=14] -n5)"
}
eval paste$a|sed '1iB	I	N	G	O
3s/\w*/free/3
$a
'
}

```

Try it online!

# Answer
> 2 votes
# APL (Dyalog Extended), 46 bytes

Full program. Prompts for `n`.

```
('BINGO'{'free'}¨@3@4⍤⍪(15×…4)+⍤1⍉)⍤2↑5?¨⎕5⍴15

```

Try it online!

`⎕5⍴15` prompt for `n` and join that 5, then use that as dimensions for an array of 15s

`5?¨` for each 15, get 5 random numbers in the range 1 through that, without replacement

mix this matrix of lists into an `n`-by-5-by-5 array with each row being a randome 5-of-15

`(``)⍤2` on each layer:

transpose, so the 5-of-15 rows become columns

`(``)+⍤1` add the following to each row:

`…4` the numbers 0 through 4

`15×` fifteen multiplied by those

`'BINGO'``⍤⍪` prepend a row of the given letters, then:

…`@4` at row 4:

…`@3` at column 3:

`{` replace each value (though there's only one) with:

`'free'` the given word

# Answer
> 2 votes
# C (gcc), ~~262~~ 225 bytes

* -37 thanks to c--

```
a[6][5]={L"BINGO"};f(n,i,j,k,r){--n&&puts("",f(n));for(j=5;j--;)for(k=i=0;k||++i<6;k||(a[i][j]=r))for(r=j*15+rand(k=i)%15+1;--k&&a[k][j]-r;);for(i=0;i<6;i+=puts(""))for(j=0;j<5;)printf(i*j-9?i?"%d	":"%c	":"free	",a[i][j++]);}

```

Try it online!

Ungolfed (``` used instead of literal tab character):

```
a[6][5]={L"BINGO"}; // bingo array, with header
f(n, // number of cards to generate
  i,j, // row and column
  k, // random number row checker
  r // random number
 ) {
  --n && puts("",f(n)); // recursively print cards, adding newline
  for(j=5;j--;) // for each column
      for(k=i=0;k||++i<6;k||(a[i][j]=r)) // for each row (redo duplicates)
        for(r=j*15+rand(k=i)%15+1;--k&&a[k][j]-r;); // detect duplicates
    for(i=0;i<6;i+=puts("")) // mark middle item as free; print board
      for(j=0;j<5;)
        printf(i*j-9?i?"%d`":"%c`":"free`",a[i][j++]);
}

```

# Answer
> 2 votes
# Jelly, ~~38~~ 36 bytes

```
75s15Ẋ€ḣ€5Z“ƝM»€3¦€3¦“BINGO”ṭṚK€Y⁷Ṅ)

```

Try it online!

Most of the credit goes to *@cairdcoinheringaahing* and *@UnrelatedString* for helping me in chat.

* -2 thanks to UnrelatedString

This can probably be a bit shorter, though.

#### Explanation

```
75        # 75 (implicit range)
  s15     # Split into 15 parts
     Ẋ€   # Random permutation of each
ḣ€5       # First 5 elements of each
   Z      # Transpose
    “ƝM»  # Replace ↓ with "free"
€3¦€3¦    # The third item in the third item (1-indexed)
“BINGO”   # Push "BINGO"
       ṭṚ # Append and reverse (i.e. prepend)
K€        # Join each by spaces
  Y⁷      # Join by newlines and append a newline
    Ṅ     # Print
     )    # Repeat input number of times

```

# Answer
> 2 votes
# Python 3, 151 bytes

```
from random import *
print("B I N G O")
x=lambda n:n*15+randint(0,15)
[print(*[*("free"if(i==2 and j==2)else x(j)for j in range(5))])for i in range(5)]

```

# Answer
> 1 votes
# Python 3, ~~198 166~~ 157 bytes

```
lambda n:exec('m=["BINGO",*map(list,zip(*[sample(range(i,i+15),5)for i in range(1,75,15)])),""];m[3][2]="free";[print(*i)for i in m];'*n)
from random import*

```

Try it online!

(ATO isn't working right now so I switched to TIO)

* -32 thanks to tsh

This can probably be golfed a bit more.

# Answer
> 1 votes
# Raku, 94 bytes

```
{join "

",({S:13th/\d+/free/}((,|[Z] (1..75).rotor(15)».pick(5)).join("
"))xx$_)}

```
* `(1..75).rotor(15)` splits the range 1-75 into five subranges of size 15: 1-15, 16-30, etc.
* `».pick(5)` selects five distinct random elements from each of those subranges.
* `[Z]` reduces that list of lists of random choices with the `Z`ip operator. It effectively transposes the matrix, so the 1-15 selections are in the first column instead of the first row.
* `<B I N G O>,|...` prepends the header row to the lists of numbers.
* `.join("\n")` joins the rows with newlines, producing a Bingo board as a single string. The actual code uses a single newline character between the quotes to save a byte.
* `S:13th/\d+/free/` changes the thirteenth occurrence of a number in that string to `free`.
* `xx $_` replicates the preceding process a number of times given by the input argument `$_`, producing a list of board strings.
* `join "\n\n"` joins those boards together with two newlines between them.

---
Tags: code-golf, number, grid, random, game
---


title: Yakko's New World Order

text:
# Question
Title: Yakko's New World Order
Given a list of countries in alphabetical order, put them in the same order as they are given in the song "Yakko's World".

Specifically, you are given the following list of countries\* exactly:

```
Abu Dhabi, Afghanistan, Albania, Algeria, Algiers, Angola, Argentina, Australia, Austria, Bahamas, Bahrain, Bangladesh, Barbados, Belgium, Belize, Benin, Bermuda, Bhutan, Bolivia, Borneo, Botswana, Brazil, Bulgaria, Burma, Burundi, Cameroon, Canada, Caribbean, Cayman, Chad, Chile, China, Colombia, Congo, Costa Rica, Crete, Cuba, Cyprus, Czechoslovakia, Dahomey, Denmark, Djibouti, Ecuador, Egypt, El Salvador, England, Ethiopia, Fiji, Finland, France, French Guiana, Gabon, Gambia, Germany, Ghana, Greece, Greenland, Guam, Guatemala, Guinea, Guinea-Bissau, Guyana, Haiti, Honduras, Hong Kong, Hungary, Iceland, India, Indonesia, Iran, Iraq, Ireland, Israel, Italy, Jamaica, Japan, Jordan, Kampuchea, Kenya, Korea, Kuwait, Laos, Lebanon, Lesotho, Liberia, Libya, Liechtenstein, Luxembourg, Madagascar, Mahore, Malawi, Malaysia, Mali, Malta, Mauritania, Mexico, Monaco, Mongolia, Morocco, Mozambique, Namibia, Nepal, New Guinea, New Zealand, Nicaragua, Niger, Nigeria, Norway, Oman, Pakistan, Palestine, Panama, Paraguay, Peru, Poland, Portugal, Puerto Rico, Qatar, Republic Dominican, Romania, Russia, Rwanda, San Juan, Saudi Arabia, Scotland, Senegal, Sierra Leone, Somalia, Spain, Sri Lanka, Sudan, Sumatra, Surinam, Swaziland, Sweden, Switzerland, Syria, Taiwan, Tanzania, Thailand, The Netherlands, The Philippine Islands, Tibet, Tobago, Togo, Transylvania, Tunisia, Turkey, Uganda, United States, Uruguay, Venezuela, Vietnam, Yemen, Yugoslavia, Zaire, Zambia, Zimbabwe

```

And required to output the countries in this order:

```
United States, Canada, Mexico, Panama, Haiti, Jamaica, Peru, Republic Dominican, Cuba, Caribbean, Greenland, El Salvador, Puerto Rico, Colombia, Venezuela, Honduras, Guyana, Guatemala, Bolivia, Argentina, Ecuador, Chile, Brazil, Costa Rica, Belize, Nicaragua, Bermuda, Bahamas, Tobago, San Juan, Paraguay, Uruguay, Surinam, French Guiana, Barbados, Guam, Norway, Sweden, Iceland, Finland, Germany, Switzerland, Austria, Czechoslovakia, Italy, Turkey, Greece, Poland, Romania, Scotland, Albania, Ireland, Russia, Oman, Bulgaria, Saudi Arabia, Hungary, Cyprus, Iraq, Iran, Syria, Lebanon, Israel, Jordan, Yemen, Kuwait, Bahrain, The Netherlands, Luxembourg, Belgium, Portugal, France, England, Denmark, Spain, India, Pakistan, Burma, Afghanistan, Thailand, Nepal, Bhutan, Kampuchea, Malaysia, Bangladesh, China, Korea, Japan, Mongolia, Laos, Tibet, Indonesia, The Philippine Islands, Taiwan, Sri Lanka, New Guinea, Sumatra, New Zealand, Borneo, Vietnam, Tunisia, Morocco, Uganda, Angola, Zimbabwe, Djibouti, Botswana, Mozambique, Zambia, Swaziland, Gambia, Guinea, Algeria, Ghana, Burundi, Lesotho, Malawi, Togo, Niger, Nigeria, Chad, Liberia, Egypt, Benin, Gabon, Tanzania, Somalia, Kenya, Mali, Sierra Leone, Algiers, Dahomey, Namibia, Senegal, Libya, Cameroon, Congo, Zaire, Ethiopia, Guinea-Bissau, Madagascar, Rwanda, Mahore, Cayman, Hong Kong, Abu Dhabi, Qatar, Yugoslavia, Crete, Mauritania, Transylvania, Monaco, Liechtenstein, Malta, Palestine, Fiji, Australia, Sudan

```

You have some flexibility in the form of the input and output; you can take or output the countries as all uppercase, all lowercase, or maintaining case, and can choose to omit spaces as well.

Standard loopholes are forbidden. Since this is , the shortest code wins.

---

\*Note that *Yakko's World* includes several places that aren't countries, and that several countries aren't included in the list.

# Answer
> 8 votes
# JavaScript (Node.js), 205 bytes

*-2 thanks to @l4m2*

This is based on a specific implementation of `sort()` but probably works with several engines.

The source code contains unprintable characters.

```
a=>a.sort(_=>Buffer(`!IF<@E*JGL8*'M-&LDJ>!F%8+,.C?$9C-=M#10-G!G7B*D9,,2!:F"@BF5H;#3-$IK.EK;(%H+F'L'I2,-J2'7M551;,;8*! /%92 D&@J?0E:<2G3EG.K-I'`)[i/6|0]-14<<31-i++%6,i=0)

```

Try it online!

### How?

We make the callback function of `sort()` returning either a negative or non-negative value, depending on whether the items must be swapped or not. We need one bit per iteration and the data string encodes \\$6\\$ bits per character, using the ASCII range \\$\[14\dots77\]\\$.

The list is fully sorted after \\$943\\$ iterations, which requires \\$\lceil 943/6\rceil=158\\$ characters. It happens to be equal to the number of countries in the list, but that's a pure coincidence.

### Commented

```
a =>            // a[] = input list, in alphabetical order
a.sort(_ =>     // sort it, ignoring the arguments of the callback
  Buffer(`...`) //   turn the data string into a list of ASCII codes
  [i / 6 | 0]   //   extract the entry at index floor(i / 6)
  - 14          //   subtract a fixed encoding offset, chosen to avoid
                //   characters that can't be included as literals or
                //   must be escaped
  << 31 -       //   left-shift the result such that the sign bit
  i++ % 6,      //   is replaced with the bit at position (i mod 6)
  i = 0         //   start with i = 0
)               // end of sort()

```

# Answer
> 8 votes
# Jelly, 121 bytes

```
“wỴḅKṭḞ2Ṅðȧ¤[Ạ⁺©iṆȦẉ&ŒÐḷ<⁸Ṛ⁵Ƙ#A½Ƈ'¥ṚPċṢSḥSQUmṘẉL>²XɼNĠ¥ṆỊẋi¥@ȯ⁺CḲKSḌȮC²ß5LṂJṁȮr]zƬe§^YVœX<ḃç%ƝṪƬṣ$¹Ṗa?⁵ḤẠÐẈ}ƬỊhR=zḢɱ¿z’œ?

```

Try it online!

Boring, but it's not clear what further logic could bring it down. The program is just a giant compressed integer representing a permutation, and a builtin to apply it.

# Answer
> 4 votes
# MS-DOS .COM format (8086), ~~220~~ 213 bytes

Takes a CR-LF delimited list of countries from standard input.

```
0000000 b4 08 b1 9e bf 11 03 57 cd 21 3c 0d 75 02 b0 24
0000020 aa 75 f5 cd 21 e2 f0 bb 36 01 b1 9e 8b ec 33 c0
0000040 8a c1 d7 d1 e0 8b f0 8d 3a 8b 15 b4 09 cd 21 b0
0000060 20 cd 29 e2 e9 cd 20 1b 96 6e 2f 40 47 3d 0c 3f
0000100 7a 03 28 9d 5d 81 44 24 45 61 6f 02 7c 84 48 20
0000120 39 76 99 1f 41 4f 1e 13 6a 8e 72 49 80 33 34 0d
0000140 43 4a 85 67 9a 62 69 18 01 3a 89 74 00 98 09 3b
0000160 0b 05 8a 36 1a 37 1c 14 10 59 0f 4c 3c 52 4e 7e
0000200 92 42 50 8c 38 12 9c 86 30 5a 1d 75 70 6c 2a 90
0000220 46 11 93 4d 04 51 55 4b 15 58 57 78 5c 22 87 31
0000240 25 56 9b 21 26 2b 66 0a 54 77 95 16 68 6d 5b 17
0000260 32 64 91 6b 19 07 2d 23 0e 94 8d 35 8f 7b 88 7f
0000300 73 97 8b 63 60 5e 06 7d 29 71 65 82 79 27 2c 53
0000320 5f 2e 3e 83 08

```

Input file

Assembler source (TASM):

```
IDEAL
P8086

MODEL   TINY
CODESEG
ORG 100H

MAIN:
    MOV AH,8    ; Read from STDIN, no echo
    MOV CL,158  ; Do for all strings
    MOV DI,OFFSET STRINGS ; String storage
STORE:
    PUSH    DI  ; Store index of string
LOAD:
    INT 21H     ; Get character
    CMP AL,0DH  ; End of line?
    JNZ LOAD1   ; No, keep going
    MOV AL,'$'  ; Replace end of string with $ terminator
LOAD1:
    STOSB
    JNZ LOAD    ; End of line? (No, keep going)
    INT 21H     ; Yes, skip LF
    LOOP    STORE ; Store next offset until done
DONE:
    MOV BX,OFFSET CONVS-1 ; Conversion table
    MOV CL,158  ; Do for all strings
    MOV BP,SP
PRINT:
    XOR AX,AX   ; Line number
    MOV AL,CL
    XLAT        ; Get conversion
    SHL AX,1    ; Turn into pointer
    MOV SI,AX
    LEA DI,[BP+SI] ; Get address of array index
    MOV DX,[DI] ; Get string address
    MOV AH,9    ; Print string
    INT 21H
    MOV AL,' '  ; Print separator
    INT 29H
    LOOP    PRINT ; Until done
    INT 20H

; Conversion table
CONVS   DB  27,150,110,47,64,71,61,12,63,122,3,40,157,93
    DB  129,68,36,69,97,111,2,124,132,72,32,57,118,153
    DB  31,65,79,30,19,106,142,114,73,128,51,52,13,67,74
    DB  133,103,154,98,105,24,1,58,137,116,0,152,9,59,11
    DB  5,138,54,26,55,28,20,16,89,15,76,60,82,78,126,146
    DB  66,80,140,56,18,156,134,48,90,29,117,112,108,42
    DB  144,70,17,147,77,4,81,85,75,21,88,87,120,92,34,135
    DB  49,37,86,155,33,38,43,102,10,84,119,149,22,104,109
    DB  91,23,50,100,145,107,25,7,45,35,14,148,141,53,143
    DB  123,136,127,115,151,139,99,96,94,6,125,41,113,101
    DB  130,121,39,44,83,95,46,62,131,8
STRINGS DB  ?

END MAIN
ENDS

```

# Answer
> 4 votes
# 05AB1E, 121 bytes

```
•Caиβ”œ`äÔÚ×3ιØ>ãA8Cγ“Ø₄XмK
£#_¯½%˜‚-Z†b}g3EqÄúé…¹ζzŒWmRç°¶вåΔBв„6J0Ð¹%∍¬üë¯β±B[λ9fΩÙ„¶g¹`Hk¹ʒJ.≠|”ΩoK"Âc9„Ƶι–+@ÌèÊ$§₅•.I

```

I/O as a list. It's currently in the default titlecase, but can also be lowercase or uppercase without a change in functionality.

Try it online.

**Explanation:**

```
•Caи...$§₅• # Push compressed integer 17496935826677579314159550205809193960505801935712671712608685729996785341091982271028672893034204123066468970588179871093613064855657604902698437005706906805554153425206759252074826136162698098035155104304651724366320520871306820060929813088043319762751700033987752258296072690622
 .I         # Get the (0-based) ^'th permutation of the (implicit) input-list
            # (after which the list is output implicitly as result)

```

See this 05AB1E tip of mine (section *How to compress large integers?*) to understand why `•Caиβ”œ`äÔÚ×3ιØ>ãA8Cγ“Ø₄XмK\n£#_¯½%˜‚-Z†b}g3EqÄúé…¹ζzŒWmRç°¶вåΔBв„6J0Ð¹%∍¬üë¯β±B[λ9fΩÙ„¶g¹`Hk¹ʒJ.≠|”ΩoK"Âc9„Ƶι–+@ÌèÊ$§₅•` is `17496935826677579314159550205809193960505801935712671712608685729996785341091982271028672893034204123066468970588179871093613064855657604902698437005706906805554153425206759252074826136162698098035155104304651724366320520871306820060929813088043319762751700033987752258296072690622`.

# Answer
> 3 votes
# JavaScript (Node.js), 253 bytes

```
a=>a.map((_,i)=>a[Buffer("lRpfbz5KcXYkGzgsdCCXPz06EgYqHhUiDmgQCY96cJaEMgw5a4ZCMDWHCCZJkzdyd3wCR3hsFntBJUZFiFJITJlQCoxXDXMxLSiAQ20XAYtlEU1bCx9PS2FRjkSNiYFmg2cTmJJilAWdKRRjnIU0OwM2GFNakGlqHVQrDzOKf05cfgQnZH1VGSGbLjxYeVkcQAB1miNekWBWXW4vB4I",'base64')[i]])

```

Try it online!

# JavaScript (Node.js), 355 bytes not using `Buffer`

```
a=>"951a5f6f3e4a7176241b382c7420973f3d3a12062a1e15220e6810098f7a709684320c396b8642303587082649933772777c0247786c167b412546458852484c99500a8c570d73312d2880436d17018b65114d5b0b1f4f4b61518e448d89816683671398926294059d2914639c85343b033618535a90696a1d542b0f338a7f4e5c7e0427647d5519219b2e3c5879591c4000759a235e9160565d6e2f0782".replace(/../g,i=>a['0x'+i-0]+`
`)

```

Try it online!

Nothing but table

# Answer
> 3 votes
# Charcoal, ~~212~~ 150 bytes

```
≔⪪Ｓ, θ≔Ｉ”)¶‴k~r~↷⊙α¤ψςＦ8→⊖"]´τＤβ²×ju÷↷Hγ0÷≕⊙≧↖Ｇⅈσ¦⊕ＡNＱWo0Ｅx⟧/ＤT✳o？Ｌ:Ｊμ∧LY<γ⊗⬤νGΠ↗φWε﹪πχ5₂{“⊗Ｋ»§″^⁶↘;R⁷↧C�nεＫΣ⌊⪫lY×≔>¦³mZ⎇Π⊟⁵↶⦃～Ｄ”ηＷ⁻θυ«⊞υ§ιη≧÷Ｌιη»⪫υ,

```

Try it online! Link is to verbose version of code. Explanation: Now uses the reverse factorial number system.

```
≔⪪Ｓ, θ

```

Split the input on commas.

```
≔Ｉ”...”η

```

Start with a large compressed integer.

```
Ｗ⁻θυ«

```

Repeat until all of the countries have been extracted.

```
⊞υ§ιη

```

Cyclically index the remaining countries with the large integer and push the result to the predefined empty list.

```
≧÷Ｌιη

```

Integer divide the integer by the count of remaining countries.

```
»⪫υ,

```

Output all of the countries joined by commas.

# Answer
> 3 votes
# Vyxal, 140 bytes

```
»÷¤xŻλjb↑+k2x₴O₍‟ḂṀṫ. ɖ`‟z¦¼ẇeRʁ>j:t{*0 Nq;*₅1z⟑-¶±↓`ṡF²k•-ṡ⁼₌]L₇ḊṪṗ₃h¦SεĠT$₴∴∇ǎ)¾ŀ⟇ḟṡ₄↲ḣ×£↳ǎrq°ʁ₀∇ẋ≠↑⁽5₍↑¯₈¤⌈←±e«∷¦jẇʁ»⁺9(n›ḋ÷$)_WṘ(n~i⅛⟇)¾

```

Try it Online!

This uses factorial number system to encode the permutation. A shorter solution would be to index into the list of all permutations of the input but that wouldn't complete before the heat death of the universe.

This code starts with a big integer encoding the permutation on the stack:

```
⁺9(                    # for n in range(158):
   n›                  #   increment
     ḋ                 #   divmod
      ÷$               #   push each to stack and swap
        )              # end for
         _WṘ           # pop, wrap stack and reverse
            (          # for each:
             n~i⅛      #   index into input and push result to global array
                 ⟇     #   remove this index from input
                  )    # end for
                   ¾   # push global array

```

# Answer
> 3 votes
# Zsh, 264 bytes

```
for c (`basenc -d --z85<<<'Mk:jJktc3vb]!]%BS)bqk06z.d<2JK4}#Q.KB7#lG!
<f0y>>wjhI.U!n%zqRCZPV+D2jvBlmbh(IbM#uNO:DLspPBde?8utzwSClw!E<z3)nwuv
P5mQJ/5B3GLh6/LvG<ZO*>E=ORx0:1udh$tAJVo9-T:5g(D(Wu4i2awQWU#baHqHs:Bl(
k((d#bWVZys6//02.J9S'|basenc --base2msbf -w8`)<<<$@[2#$c]

```

Try it Online! Uses z85 encoding. Reformatted the code above for readability. It doesn't work on TIO (no `basenc`), but here's a full version that should run on MacOS or Linux.

### 355 bytes, hex encoded

```
s=951a5f6f3e4a7176241b382c7420973f3d3a12062a1e15220e6810098f7a709684320c396b8642303587082649933772777c0247786c167b412546458852484c99500a8c570d73312d2880436d17018b65114d5b0b1f4f4b61518e448d89816683671398926294059d2914639c85343b033618535a90696a1d542b0f338a7f4e5c7e0427647d5519219b2e3c5879591c4000759a235e9160565d6e2f0782
for i j (${(s::)s})echo $@[0x$i$j+1]

```

Try it online! Uses the hex string in @lm42's answer. Could save 2 bytes by editing `$s` (so I don't need to have `+1` in there), but that's a bit painful. I might add a shorter solution later, using z85 encoding.

# Answer
> 2 votes
# Python 2, 226 bytes

```
lambda x:list(permutations(x))[eval('...'.decode('zip'))]
from itertools import*

```

Attempt This Online! (Times out on ATO)

Here's a hexdump of the string:

```
00000000  78 9c 0d 8d b9 11 00 31 08 03 5b 02 63 be 72 78 | x......1..[.c.rx |
00000010  6b b8 f2 cf 89 46 1b 68 05 9f a6 20 4f 1d b4 76 | k....F.h... O..v |
00000020  b1 5b d3 26 b5 aa dc 8e 51 19 16 08 af 8e 15 64 | .[.&....Q......d |
00000030  38 2b d7 6d e2 68 8d ea be 91 2e b8 53 1e ab 92 | 8+.m.h......S... |
00000040  7b ac b7 0f f0 59 3e 5a 3a 49 79 96 70 96 77 1f | {....Y>Z:Iy.p.w. |
00000050  32 76 12 8d 00 73 1a e7 32 39 cf 4e c2 d5 5b 3e | 2v...s..29.N..[> |
00000060  3e 45 8d 93 ad d5 ac eb 56 06 c5 06 33 1a f7 05 | >E......V...3... |
00000070  5e a3 88 42 54 21 32 32 25 c4 7a e7 0d 22 6b 11 | ^..BT!22%.z.."k. |
00000080  76 47 2d 88 9d 8e bd 5d ec 89 5a 88 a7 ed cc f9 | vG-....]..Z..... |
00000090  01 6a 32 44 1f                                  | .j2D.            |

```

Verify the bytecount here.

# Python, 287 bytes

```
lambda x:[*permutations(x)][0x7b615ec218d9684ced86cf775d91acba8a10d91e8c0ba9575c4d35ad7acdd4ab961fec9af76bf28dfd2052f527c7eb3b2f31ef5ffc7e51db33e6055b85bf5395efeb0474c9e9ec3d1ebd7cd57f98c80c580ee7a4ee71483aac1176338387311cfecd066f8aa84e78a359328c58af2acf0a9ecdbbe]
from itertools import*

```

Attempt This Online! (Times out on ATO)

Port of Kevin Cruijssen's 05AB1E answer. Gets the (a very big number)th permutation of the input list.

---
Tags: code-golf, kolmogorov-complexity
---


title: Help me sell old donuts

text:
# Question
Title: Help me sell old donuts
You work at a bakery, and every day you make pastries. You make 100 of each of several different types. However customers are less predictable. Some days they order all of one kind of pastry and you run out, some days they order hardly any and you have some left over. So your boss has made up a chart which tells you how many days each type of pastry can last before it's too old and can't be sold anymore. When there are leftover pastries the customers will always buy the freshest pastries first.

As an example lets use donuts, which (according to your boss's chart) can be sold 2 days after they are baked. Lets say you start the week with 0 donuts left over and the following are the orders for 5 days:

| Mon | Tue | Wed | Thu | Fri |
| --- | --- | --- | --- | --- |
| 25 | 75 | 55 | 155 | 215 |

* On Monday you bake 100 donuts and sell 25, you have 75 left over.
* On Tuesday you bake 100 donuts and sell 75. Since customers prefer fresh donuts, all 75 donuts sold were ones baked on Tuesday. You have 75 still left over from Monday and 25 left over from Tuesday.
* On Wednesday you bake 100 donuts and sell 55. Since 55 is less than 100, all the donuts sold are fresh from that day. The 75 from Monday are now 2 days old and have to be thrown out. You have 25 still left from Tuesday and 45 from Wednesday.
* On Thursday you bake 100 donuts, and get 155 orders. The 100 fresh donuts get sold first, leaving 55 more orders to be filled, you sell all 45 donuts from Wednesday leaving 10 more orders which can be filled with donuts from Tuesday. At the end of the day you have 15 donuts from Tuesday which have to be thrown out.
* On Friday you bake 100 more donuts and get 215 orders. You only have 100 donuts so you only sell 100 donuts.

## Challenge

Your program will take as input the number of days a particular pastry lasts (e.g. 2 for donuts) and the number of orders for that pastry each day over a period of time. The output will be how many pastries will be sold over that period of time.

This is so the goal is to minimize the size of your source code as measured in bytes.

## Test cases

```
1 [100,100,100] -> 300
1 [372,1920,102] -> 300
1 [25,25,25] -> 75
1 [25,100,120] -> 225
1 [25,100,100,120] -> 325
1 [0,200] -> 200
1 [0,175,75] -> 250
1 [75,150,150] -> 300
1 [0,101,199]-> 201
1 [200,0] -> 100
2 [100,100,100] -> 300
2 [372,1920,102] -> 300
2 [25,25,25] -> 75
2 [25,100,120] -> 245
2 [25,100,100,120] -> 325
2 [0,200] -> 200
2 [0,175,75] -> 250
2 [75,150,150] -> 300
2 [0,101,199]-> 300
2 [200,0] -> 100

```

# Answer
# Vyxal, 19 bytes

```
ȧ₁?›(-½:ȧ~+^-Þr)_-∑

```

Try it Online! or verify all test cases
> 6 votes

# Answer
# Charcoal, ~~51~~ 34 bytes

```
≔⟦⟧ζＦη«Ｆ¹⁰⁰⊞ζθＦιＦ¬¬ζ⊞υ⊟ζ≔⊖Φζκζ»ＩＬυ

```

Try it online! Link is to verbose version of code. Explanation: Now uses @Jonah's method.

```
≔⟦⟧ζ

```

Start with no pastries.

```
Ｆη«

```

Loop over the orders.

```
Ｆ¹⁰⁰⊞ζθ

```

Bake 100 fresh pastries.

```
ＦιＦ¬¬ζ⊞υ⊟ζ

```

For each ordered pastry, try moving the freshest remaining pastry from the shelf to the customer.

```
≔⊖Φζκζ

```

Remove the stalest left-overs and decrease the freshness of the remaining left-overs. (This is actually `≔⁻Φζκ¹ζ` on TIO because its version of Charcoal can't decrement an empty list and I'm too lazy to switch the links over to ATO where it works.)

```
»ＩＬυ

```

Output the final count of sales.
> 4 votes

# Answer
# , 59 bytes

```
1 :'1#.]<.##&>@{.[:(a(#~u>:])@,1+}.)&.>/@|.\(<a=.100$0),;/'

```

Try it online!

Probably not the golfiest possible J approach but I liked the simplicity of it...

Rather than working with numbers that represent *pastry count*, we use a unary number system, representing every pastry with its own number. For counting available pastires, the number itself is irrelevant (any number = 1 pastry), but we also let the number represent pastry age, so we can use it to filter too-old pastries.

Thus, we seed the reduction with 100 zeroes, representing the first day's fresh pastries.

Now we simply:

* Kill `}.` `n` elements where `n` is the days order
* Add 1 to every number remaining on our list
* Prepend a fresh 100 zeroes to the list
* Filter away numbers that have exceeded the input limit

Finally, we do a scan of the reduction so we have the intermediate results, min those with the input, and sum.
> 4 votes

# Answer
# C (clang), <sup>~~125~~ ~~123~~</sup> 121 bytes

```
s;f(*o,n,d){for(int l[n],a,i,j=s=0;j<n;s-=*o++)for(l[i=j++]=100,s+=*o;~i&&j+~i<=d;*o-=a)l[i--]-=a=fmin(*o,l[i]);o[-n]=s;}

```

Try it online!
> 3 votes

# Answer
# JavaScript (ES6), 80 bytes

Expects `(days)(orders)`.

```
n=>a=>a.map(q=>b=[100,...b].map((v,i)=>(q-=x=i>n?0:v<q?v:q,t+=x,v-x)),b=[t=0])|t

```

Try it online!

### Commented

```
n =>             // outer function taking n (number of days)
a =>             // inner function taking a[] (list of orders)
a.map(q =>       // for each number q of orders for each day:
  b =            //   update b[], an array keeping track of remaining
                 //   pastries in reverse chronological order
  [100, ...b]    //   create 100 pastries for today
  .map((v, i) => //   for each stock value v for today minus i days:
    ( q -=       //     subtract from q
      x =        //     the number x of pastries sold, defined as:
      i > n ?    //       if i is greater than n (beyond expiry date):
        0        //         nothing
      :          //       else:
        v < q ?  //         if the stock is less than the orders:
          v      //           the entire stock
        :        //         else:
          q,     //           the remaining number of orders
      t += x,    //     add x to the total t
      v - x      //     subtract x from v and store this in b[]
    )            //     as the remaining stock for this day
  ),             //   end of inner map()
  b = [t = 0]    //   start with t = 0 and b[] = [ 0 ]
) | t            // end of outer map(); return t

```
> 2 votes

# Answer
# Go, 169 bytes

```
func(n int,a[]int)(s int){b:=[]int{100}
for _,q:=range a{x:=0
for i,v:=range b{if i>n{x=0}else if v<q{x=v}else{x=q}
q-=x;s+=x;b[i]-=x}
b=append([]int{100},b...)}
return}

```

Attempt This Online!

Port of Arnauld's solution.
> 2 votes

# Answer
# Python, 105 bytes

```
f=lambda n,d,i=0,x="":d>[]and len((x:=str(i)*100+x)[:d[0]])+f(n,d[1:],i+1,(x+" ")[d[0]:x.find(str(i-n))])

```

I would be *very* surprised if this was optimal.
> 1 votes

# Answer
# Wolfram Language (Mathematica), 150 bytes

Since in any case the WL will not be the winner, I allowed myself to be creative to the challenge.
So we start one day in the morning with *non-negative array of donuts*: \\$\[50, 50, 0, 25, …\]\\$

First item (here is \\$50\\$) means how many donuts are baked every day. In the original challenge it is constant \\$100\\$. Other items are numbers of donuts leftover from: yesterday, 2 days before etc.
So the length of this array is the shelf life + 1.
The second input is an array of orders.

```
Last@With[{d=#1[[1]]},Fold[{Prepend[Rest@Most@FoldList[If[#1<0,#1+#2,#2]&,-#2,#1[[1]]]/._?Negative->0,d],#1[[2]]+Min[Total@#1[[1]],#2]}&,{#1,0},#2]]&

```

So test cases from the original challenge will be looks like:
\\$\[100, 0\] \[372,1920,102\]\\$
\\$\[100, 0, 0\] \[372,1920,102\]\\$ etc.

Here are some advanced test cases:

Every day we bake 50 donuts, from last day leftover 25 donuts, shelf life is 1 day:
\\$\[50, 25\] \\$
Orders:
\\$\[372,1920,102\]\\$
Output: \\$175\\$

Every day we bake 125 donuts, from 2 days before leftover 10 donuts, shelf life is 3 days:
\\$\[125, 0, 10, 0\] \\$
Orders:
\\$\[25,100,100,120\]\\$
Output: \\$345\\$

Try it online!

Non-golfed version with named variables:

```
bakery[donuts_List, orders_List] :=
  Last@With[{daily = First@donuts},
   Fold[
    {Prepend[
       Rest@
         Most@FoldList[If[#1  0
       , daily],
      #1[[2]] + Min[Total@#1[[1]], #2]
      } &, {donuts, 0}, orders]
   ];

```
> 0 votes

---
Tags: code-golf
---


title: Pushing boxes away

text:
# Question
Title: Pushing boxes away
You are on a plane filled with boxes, and you get a sequence of movements, say "up right right down left":

You move up, pushing all boxes in front of you away:

You move right, right and down, getting

and finally left. This time you only push one box rather than infinite boxes:

At the end, there are 4 spaces.

Given a sequence of moves, decide how many spaces are there after these moves. You can take 4 distinct inputs to mean 4 directions. You can also count yourself as space(result +1). Shortest code in each language wins.

Test data:

```
R => 1
RD => 2
RL => 1
RDRU => 4
URRDL => 4
UURDLL => 5
DRDDDLUUU => 7

```

# Answer
> 15 votes
# JavaScript (ES6), 94 bytes

*-3 bytes thanks to @l4m2*

Expects an array of `[dx,dy]` pairs, e.g. `[[-1,0],[1,0]]` for `LR`.

```
a=>a.map(([h,v],i)=>a[[X=x,Y=y]]=!(g=_=>~--a[[X+=h,Y+=v]]?i--?g():++n:1)(x+=h,y+=v),n=x=y=0)|n

```

Try it online!

### How?

The algorithm used here is pretty straightforward.

Whenever we move in a direction \\$(dx,dy)\\$, we look for the first empty cell along this ray.

If we find one, we mark it as non-empty anymore.

Otherwise, we increment the total number of empty cells. In both cases, we mark the cell at our new position as empty.

Note that if we move to an empty cell, it will briefly be marked as non-empty and then marked as empty again, which is conceptually silly but functionally correct.

In order to make sure that we look far enough, the length of the test ray is simply the number of moves performed so far (including the current one).

### Commented

```
a =>            // a[] = input array, re-used to store visited cells
a.map(          // for each ...
([h, v], i) =>  // ... direction [h, v] at index i in a[]:
  a[[           //
    X = x,      //   initialize (X, Y) to (x, y)
    Y = y       //
  ]] =          //   mark this cell as visited (i.e. empty)
  !(            //   by setting it to false
    g = _ =>    //   g is a recursive function ignoring its argument
    ~--a[       //
      [         //     lookup key of the new position
        X += h, //     defined as (X + h, Y + v)
        Y += v  //
      ]         //     we force the state of this cell to non-empty
    ] ?         //     if it already was non-empty:
      i-- ?     //       if i is not equal to 0 (decrement i afterwards):
        g()     //         keep moving along this ray
      :         //       else:
        ++n     //         increment the number n of empty cells and stop
    :           //     else:
      1         //       stop
  )(            //   initial call to g ...
    x += h,     //     ... with (x, y) updated to (x + h, y + v)
    y += v      //
  ),            //
  n = x = y = 0 //   start with n = 0 and (x, y) = (0, 0)
) | n           // end of map(); return n

```

# Answer
> 4 votes
# Python 3.8 (pre-release), ~~130~~ 123 bytes

*-7 bytes thanks to @l4m2*

```
def f(l):
 E=set();p=0
 for m in l:E^={p,p+min([q for y in E if(x:=(y-p)/m)==int(q:=x.real)>0]or[0])*m};p+=m
 return len(E)

```

Try it online!

Takes input as a list of complex numbers.

# Answer
> 3 votes
# Vyxal, 20 bytes

```
Ė¾$(n*:~¨=ȧgF0J‹n/)L

```

Try it Online! or verify all test cases

A full program accepting a list of strings "1°0", "0°1N", "1°0N", "0°1" for right, down, up, left respectively. Works by keeping a list of empty positions and removing the first one in the direction of travel each time.

```
Ė              # evaluate (convert each to a complex number)
 ¾             # push empty list
  $            # swap
   (           # for n in directions:
    n*         #   multiply by n
      :        #   duplicate
       ~¨=ȧ    #   keep only real non-negative numbers by checking if they are invariant under abs(x)
           g   #   minimum
            F  #   remove from the original list

0J             #   append 0
  ‹            #   decrement
   n/          #   divide by n
     )         # end for
      L        # length

```

# Answer
> 2 votes
# Pyth, 34 bytes

```
K,ZZVQ=-aYK<@Ym+VK*LhdNUY1=+VKN;lY

```

Try it online!

Same basic method as @Arnauld. Takes input as four distinct direction vectors `(1,0), (-1,0), (0,1), (0,-1)`.

### Explantion

`K` is the current position and `Y` is a list of empty positions.

```
                                      # implicitly assiqn Q = eval(input())
K,ZZ                                  # K = (0,0)
    VQ                                # for N in Q:
        aYK                           #   append K to Y
              m        UY             #   map range(len(Y)) over lambda d
               +VK*LhdN               #     K + ((d + 1) * N)  (vectorized)
            @Y                        #   intersection of that with Y
           <             1            #   take the first element (or empty list if none)
      =-                              #   remove that element from Y
                          =+VKN       #   K = K + N  (vectorized)
                               ;lY    # after all iterations, output length(Y)

```

# Answer
> 2 votes
# Charcoal, 31 bytes

```
Ｆθ«✳ι#≔ＫＤＬθ✳ιθ§≔θ⌕θ#ψ»ψ≔ＬＫＡθ⎚Ｉθ

```

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

```
Ｆθ«

```

Loop over the input string.

```
✳ι#

```

Mark the current square as "empty" and move in the given direction.

```
≔ＫＤＬθ✳ιθ

```

Peek ahead the number of characters in the input string in the direction given by the current character.

```
§≔θ⌕θ#ψ

```

Try to erase the first `#` found (this corresponds to pushing a box there).

```
»ψ

```

Erase the finishing square. (This could be `»#` to count yourself as an empty square.)

```
≔ＬＫＡθ⎚Ｉθ

```

Get the number of empty squares, clear the canvas, and output the count.

---
Tags: code-golf
---