# Question
Title: Generate programs that print n times their length
Given a nonnegative integer `n`, your solution must output a program in your chosen language whose output has `n` times as many bytes as the outputted program.

## Rules

* You must specify the language and encoding of the programs your solution outputs, and you may not choose different languages or encodings for different inputs to your solution. The language of your output program may or may not be the same as the language of your solution.
* Your submission only needs to handle integers in your language's range, but please do not abuse this rule.

This is so the shortest submission in bytes wins.

## Example

Suppose `n` is 4. My solution then outputs `f_8`, a program which, in my (imaginary) language outputs `j3 1s+/2]!mz`. The program output has length 3 and its output has length 3 * 4 = 12, so the solution is correct for input 4.

Suppose instead that `n` is 1 and my program outputs `ffffpfpffp` (10 bytes). The program `ffffpfpffp` in my chosen language would have to produce an output of 10 * 1 = 10 bytes.

# Answer
> 7 votes
# JavaScript (ES6), 38 bytes

```
n=>`(x="${n}")=>(x+1/7+1e9).repeat(x)`

```

### Demo

```
let f =

n=>`(x="${n}")=>(x+1/7+1e9).repeat(x)`

function update() {
  let n = I.value,
      func = f(n),
      res = eval(func)();
  O.innerText =
    'n = ' + n + '\n\n' +
    'Function (' + func.length + ' bytes):\n' + func + '\n\n' +
    'Function output (' + res.length + ' bytes):\n' + res;
}
update()
```

```
<input type=range id=I min=0 max=100 oninput="update()">
<pre id=O>
```

# Answer
> 3 votes
# Jelly, 10 bytes

```
;“DL+8×x@⁶

```

Try it online!

For input `12`, it outputs `12DL+8×x@⁶`, which outputs 120 spaces. Try it online!

# Answer
> 3 votes
# brainfuck, 348 bytes

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

```

Try it online! Or see the Ungolfed version (i.e. what I had to work with)

---

### Disclaimer

I spent more time making this than I thought was humanly possible. I'd like to thank my girlfriend for allowing me to ditch her to work on this; as well as my savior.

### How does it even work?

No clue.

### *How* does it work?

All outputs have a trailing snippet of code that are all the same:

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

```

Let's split it into three parts called `a,b,c`

```
a : [->+>+>+<<<]>>>>               THE DUPLICATOR
b : -[<<+>>-------]<<+-----        THE ADJUSTER
c : [<[.-]>->[->+<<<+>>]>[-<+>]<<] THE PRINTER

```

The input `i` is simply tacked on to the front in unary:

```
iabc

```

*(e.g; if the input was 10, then `i = '++++++++++'`)*

**The Duplicator** \- Splits the input into two identical numbers `m, n`, equivalent to the input

**The Adjuster** \- Adjusts `n` such that it equals the length of the program

**The Printer** \- Prints `m*n` ASCII characters

---

*Note that the input in the example is a `newline`, which as an ASCII value of 10, therefore the input is `10`. If you want to test other small numbers, replace the `,` with however many `+`'s you desire.*

# Answer
> 2 votes
# Cheddar, ~~10~~ 9 bytes

```
(*)&" "*9

```

An awkward Proton polyglot \>\_\<

# Answer
> 2 votes
# Haskell, 55 bytes

```
f n=(++)<*>show$"main=putStr$[1.."++show n++"*2]>>'#':"

```

Try it online! Example usage: `f 1` yields the following 54 bytes program:

```
main=putStr$[1..1*2]>>'#':"main=putStr$[1..1*2]>>'#':"

```

Try it online! which produces the following 54 byte output:

```
#main=putStr$[1..1*2]>>'#':#main=putStr$[1..1*2]>>'#':

```

# Answer
> 1 votes
# Python 3 -\> HQ9+, 11 bytes

```
'Q'.__mul__

```

It had to be done

Try it online!

# Answer
> 1 votes
# Java 8, ~~175~~ 174 bytes

```
interface M{static void main(String[]a){System.out.printf("interface M{static void main(String[]a){int i=(88+%s)*%s;for(;i-->0;System.out.print(0));}}",a[0].length(),a[0]);}}

```

**Examples:**

`n=1` outputs:

```
interface M{static void main(String[]a){int i=(88+1)*1;for(;i-->0;System.out.print(0));}}

```

(length=89) which outputs 89 zeroes:

```
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

```

---

`n=10` outputs:

```
interface M{static void main(String[]a){int i=(88+2)*10;for(;i-->0;System.out.print(0));}}

```

(length=90) which outputs 900 zeroes:

```
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

```

---

`n=100` outputs:

```
interface M{static void main(String[]a){int i=(88+3)*100;for(;i-->0;System.out.print(0));}}

```

(length=91) which outputs 9100 zeroes:

```
[encoded data, 9100 characters]

```

**Explanation:**

```
interface M{                                // Class:
  static void main(String[]a){              //  Mandatory main method
    System.out.printf("interface M{static void main(String[]a){
                                            //   Print a new program with:
      int i=(88+%s)*%s;                     //    Integer containing (88*A)+B
      for(;i-->0;System.out.print(0));}}",  //    And print that many zeroes
        a[0].length(),                      //     Where A is the length of the number
                                            //     (0-9 = 1; 10-99 = 2; 100-999 = 3; etc.)
        a[0]);}}                            //     and B is the number itself

```

# Answer
> 0 votes
# RProgN 2, ~~7~~ 5 bytes

```
«•.*

```

*With a trailing space*

## Explained

```
«•.*
«    # Yield a function from the remaining string.
 •.  # Append a space and stringify, which builds the original program (Because stringifying a function removes noops, which spaces are)
   * # Repeat the implicit input times.

```

Try it online!

# Answer
> 0 votes
# CJam, ~~8~~ 13 bytes

```
q_,S\" 8+*S*"

```

Try it Online

The generated program outputs spaces so it's kind of hard to tell.

# Answer
> 0 votes
# Ly, 29 bytes

```
"\"9>("&onu")[<&s&ol>1-]<;"&o

```

Try it online! ~~(does not work currently due to a pre-processing bug)~~ All good!

# Answer
> 0 votes
# Python → TECO, 20 bytes

The answer is in Python while the generated code is in TECO. The Python is a function returning `VV12345\VV` repeated *n* times. See here for an explanation of the TECO.

```
'VV12345\VV'.__mul__

```

# Answer
> 0 votes
# PHP, 47+1 bytes

```
<?="<?=str_pad(_,",strlen($argn)+18,"*$argn);";

```

prints one underscore followed by spaces.
Run as pipe with `-F`; run outputted program with `-f` or `-F`.

This would fail for input with more than 64 digits,
which is far higher than `PHP_INT_MAX` (at this time).

However, it fails for input larger than `PHP_INT_MAX`-18 ... does it still qualify?

# Answer
> 0 votes
# PHP → Python 2, 40+1 bytes

```
print "A"*<?=13+strlen($argn),"*",$argn;

```

prints a Python program that prints repeated `A`s. Run as pipe with `-F`.

# Answer
> 0 votes
## Batch → Charcoal, 22 bytes

I'm not sure which encoding I should be using, since these are bytes. Here are the bytes interpreted as Windows-1252:

```
@set/p=Á%1ñªÉñ«Ìñ¹<nul

```

The same bytes as PC-850:

```
@set/p=┴%1±¬╔±½╠±╣<nul

```

The same bytes in Charcoal's code page:

```
@set/p=Ａ%1θ×Ｉθ⁺Ｌθ⁹<nul

```

The resulting Charcoal program is `Plus(Length(Cast(n)), 9)` bytes long:

```
Ａ       Assign
 %1      (String representation of n)
   θ      To variable q
        Implicitly print a number of `-`s equal to:
×        Product of:
 Ｉθ       Cast of q to integer
 ⁺        Sum of:
  Ｌθ       Length of q
  ⁹        Integer constant 9

```

# Answer
> 0 votes
# JavaScript (ES8), ~~43~~ ~~41~~ 39 bytes

```
n=>`f=_=>"".padEnd(${n}*(88+f).length)`

```

---

## Test it

The output of the generated function is a string of spaces which are replaced with `*`s in this Snippet.

```
g=
n=>`f=_=>"".padEnd(${n}*(88+f).length)`

o.innerText=(h=n=>`Function: ${x=g(n)}\nLength:   ${x.length}\nOutput:   "${x=eval(x)().replace(/./g,"*")}"\nLength:   `+x.length)(i.value=10);oninput=_=>o.innerText=h(+i.value)
```

```
<input id=i type=number><pre id=o>
```

# Answer
> 0 votes
# Recursiva, ~~16~~ 15 bytes

```
++"*"V*15a'"*"'

```

Try it online!

This for input of `n=2` prints:

```
*30"*"

```

which outputs 30 `*`. Try it online!

# Answer
> 0 votes
# , 46 bytes

```
function(n)sprintf("cat(rep('a',%d*23),'')",n)

```

Try it online!

Anonymous function that returns the string

```
cat(rep('a',n*23),'')

```

Which prints `a` (that's `a` followed by a space) 23 times `n` times. I needed the `''` because otherwise `cat` wouldn't print the last space character.

# Answer
> 0 votes
# C, 94 bytes

```
main(int c,char**a){if(c>1){c=atoi(a[1]);if(c>0&&c<0xFFFFFF){c*=94;while(c--)printf("r");}}}

```

this would be 94 bytes include the last \n that stadard C says it should be written. return as 'r' characters as the (lenght of the program) * (argument of the program) if the program argument not exist or it is \<=0 or it is \>0xFFFFF print nothing example

```
C:\>nameProg.exe 1
rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr

```

# Answer
> 0 votes
## MATLAB (63 bytes)

```
a=@(n)['repmat(''a'',1,',num2str(n*(15+numel(num2str(n)))),')']

```

For example:

```
>> a(5)

ans =

repmat('a',1,80)

```

and:

```
>> repmat('a',1,80)

ans =

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

```

---
Tags: code-golf, quine
---


# Question
Title: Martin vs Dennis - Round 1: Who has more rep?
I know there have been a lot of challenges about "the two best code-golfers in the world", but this one is a bit more unique, being *Round 1* in a series of (future) challenges involving the two of them.

---

Your task is to write a program or function that returns two different non-whitespace ASCII strings, corresponding to the one who has more reputation at the moment the program is ran, between Dennis ♦ and Martin Ender ♦. The tricky part is that you must output the exact string ***"tie"*** in case the reputation is identical (not likely), and the two *different non-whitespace ASCII strings* mentioned above should be different than *"tie"* *****.

No input can be taken, such as usernames or user ids. As usual, URL shorteners are forbidden, and so are the common loopholes.

## Examples:

```
Let the chosen string for Dennis be "D" and the chosen one for Martin Ender be "M" (should be specified)

If Dennis' rep > Martin Ender's rep => D
If it's the other way around => M
If it's a tie => tie

```

---

> **IMPORTANT!** Voting on posts by Dennis & Martin for the sole purpose of affecting a tie in order to test the solutions below constitutes targeted voting which is forbidden across the Stack Exchange network. If you want to test that a solution properly outputs `tie` then change the IDs in it to those of 2 users you know to be tied. See this Meta post for more details.

<sup>**I think no one would have used that, anyway*</sup>

# Answer
> 20 votes
# 05AB1E, ~~65~~ 64 bytes

### Code:

```
•в=6{•5ôvy’ƒËŠˆ.Â‚‹º.ŒŒ/†š/ÿ’.w’„Ö="Âˆ"’¡1èт£þ}})ZQā*O<“D M·‡“#è

```

Uses the **05AB1E** encoding.

### Explanation:

`•в=6{•` converts the number `в=6{` from base 255 to base 10, resulting in 1201208478. The first half being the ID of Dennis (12012) and the second half being the ID of Martin (8478). Split into pieces of 5 using  to get the following array:

```
['12012', '08478']

```

Luckily, we can leave the leading zero from Martin's ID, since this will still work (check the link before clicking to see the leading zero).

We now loop through this array using `vy` and construct the following string from this 05AB1E code:

```
’ƒËŠˆ.Â‚‹º.ŒŒ/†š/ÿ’  -->  codegolf.stackexchange.com/users/ÿ

```

Whereas `ÿ` is the current element of the iterator (using string interpolation) Try it online!

After constructing the link, `.w` reads all data from the link, resulting into a huge amount of text. To scrape the reputation from this, we need to split on the string `title="reputation"`. Or in a more compressed version: `’„Ö="Âˆ"’`. Split on this piece of string (with `¡`) and get the second element (with ) and keep the first **100 characters** (with `т£`).

Now, our scraped text looks a bit like this:

```
>
        139,883 <span class="label-uppercase">reputation</span>
   </div>

<div class="ba

```

This part is easy, we just remove anything **but digits** to remain the reputation number, for which we have a builtin (`þ`). We end the loop and wrap everything into an array `}})`.

Finally, we can go on to processing the reputation numbers:

```
ZQā*O<“D M·‡“#è   -   On stack: an array in the format [Dennis rep, Martin rep]

Z                 # Get the maximum of the array
 Q                # Check for equality with the array
  ā*              # Multiply by it's index (1-indexed)
    O<            # Sum and decrement by 1
      “D M·‡“#    # Push the array ['D', 'M', 'tie']
              è   # Get the element on the index of the sum

```

Which results in either `D`, `M` or `tie`.

# Answer
> 18 votes
# PowerShell v3+, ~~147~~ ~~123~~ ~~119~~ ~~103~~ ~~101~~ 96 Bytes

```
$a,$b=irm api.stackexchange.com/users/12012`;8478?site=codegolf|% I*|% r*n;$a-$b|% T*g "D;M;Tie"

```

Saved 24 bytes using true/false output instead of the names.

Saved another 4 by restructuring the final checks.

saved 16 by getting only the reputations of the two users from the request, saves having to use the `|% r*n` more than once, also means we can get rid of like a million brackets, and two useless variables.

-2 thanks to TessellatingHeckler \- using an escape char instead of two doublequotes for the url, also removed the `@` from the array which was un-needed (oopsie)

used a weird `.ToString` trick I never knew existed until now reccomended by TessellatingHeckler -5, and finally below 100.

---

Version which returns names:

```
$a,$b=irm "api.stackexchange.com/users/12012;8478?site=codegolf"|% I*
if(($c=$a|% r*n)-eq($d=$b|% r*n)){"tie"}else{@(($a|% d*),($b|% d*))[$c-lt$d]}

```

this looks pretty messy due to the shortening of parameter names.

anywhere `|% r*n` appears we're getting the `ReputatioN`, and `|% d*` is the `Display_name`

uses `Invoke-RestMethod` (alias `irm`) to query the API, stores the result named `Items` (gotten using `|% I*`), into the two variables `$a` & `$b`, one for each pro golfer's, the `ToString` (`|% T*g`) trick results in one of the values `D`,`M` or `Tie` if the number is odd/even/zero.

# Answer
> 16 votes
# Python 2, 160 bytes

```
from requests import*
print cmp(*[get('http://api.stackexchange.com/users/12012;8478?%ssite=codegolf&filter=!9aK21rboZ'%s).text for s in'order=asc&',''])or'tie'

```

Not the shortest Python answer, but the shortest one so far that doesn't make any assumptions.

Prints `1` if Martin has more rep, `-1` if I do.

# Answer
> 13 votes
# JavaScript (ES6), ~~167~~ ~~156~~ ~~146~~ ~~144~~ ~~141~~ ~~132~~ 103 bytes

Stupid `fetch` and its stupid, expensive `Promise` chaining!

Assumes, as currently allowed, that Dennis & Martin will always be the 2 top ranked users. Needs to be run from the root level of `api.stackexchange.com`. Returns a `Promise` object (as is now permitted by consensus) containing `tie` or the JSON object for whoever has the most rep at the time. If the JSON object isn't considered valid output then add 5 bytes for `.link`.

```
_=>fetch`users/?site=codegolf`.then(r=>r.json()).then(({items:[j,i]})=>j[r="reputation"]==i[r]?"tie":j)

```
* Saved 11 bytes thanks to Kevin suggesting I return the profile `link` rather than the first letter of the `display_name`, which also provide better future-proofing against them changing their usernames to start with the same letter!
* 5 bytes saved adapting a tip from kamoroso94 on a another solution of mine.

---

## Try It

```
f=
_=>fetch`//api.stackexchange.com/users/?site=codegolf`.then(r=>r.json()).then(({items:[j,i]})=>j[r="reputation"]==i[r]?"tie":j)
f().then(console.log)
```

---

## Alternative

If a time comes that Dennis & Martin aren't at the top and we still want to know who has the most rep between them then we'd need the following, at a cost of an additional 10 bytes.

```
_=>fetch`users/12012;8478?site=codegolf`.then(r=>r.json()).then(({items:[j,i]})=>j[r="reputation"]==i[r]?"tie":j)

```

# Answer
> 8 votes
# Python 3, ~~160~~ ~~157~~ 151 bytes

```
from requests import*
a,b,*c=get('http://api.stackexchange.com/users?site=codegolf').json()['items']
r='reputation'
print(['tie',a['link']][a[r]>b[r]])

```

---

*-3 bytes thanks to @KevinCruijssen*

Prints a link to the user having more reputation

Assumes they are on #1 and #2

---

**Without making any assumptions, Python 2, 157 bytes**:

```
from requests import*
a,b=get('http://api.stackexchange.com/users/8478;12012?site=codegolf').json()['items']
r='reputation'
print['tie',a['link']][a[r]>b[r]]

```

# Answer
> 6 votes
# PHP, 167 Bytes

prints -1 for Dennis , 1 for Martin Ender. tie in case of a tie

```
<?=($b=($t=json_decode(gzdecode(join(file('http://api.stackexchange.com/users/12012;8478?site=codegolf&order=asc'))))->items)[0]->reputation<=>$t[1]->reputation)?:tie;

```

# Answer
> 5 votes
# Python, ~~226~~ ~~225~~ 221 bytes

I feel like this is too long.

```
import requests as r,re
def f(i):d=re.sub('[, ]','',r.get('http://codegolf.stackexchange.com/users/'+i).text);D=d.index('"reputation">')+14;return int(d[D:d.index('<',D)])
a=f('8478')
b=f('12012')
print([a>b,'tie'][a==b])

```

Prints `"True"` if Martin has more rep than Dennis, `"False"` if Dennis has more rep than Martin, and `"tie"` if they have the same (theoretically. I can't test this :P).

`https` -\> `http` for 1 byte thanks to @KevinCruijssen! `re as r, r.sub` -\> `re, re.sub` for 4 bytes thanks to @ovs!

# Answer
> 4 votes
# Bash + jq, 140 133 bytes

```
w3m 'api.stackexchange.com/users/12012;8478?site=codegolf&sort=name'|jq '.items|map(.reputation)|1/(index(min)-index(max))'||echo tie

```

## Formatted and explained

First, we *curl* w3m the API (and use `--compressed`, or short `--com` to un-gzip):

```
w3m 'api.stackexchange.com/users/12012;8478?site=codegolf&sort=name'

```

That's some JSON. Notice the order ist stable, not based on reputation. JQ then processes the JSON, which is what it's made for.

```
.items                          # take the items array
| map(.reputation)              # extract only the reputations
| 1 /
  (index(min)-index(max))       # This checks if the bigger value is first (1) or last (-1) in array

```

We use `1/x` above to generate an division-by-zero error when min==max, so in a tie situation. The `||echo tie` in bash catches that.

*Note that a warning is printed on stderr by JQ in that case, but we consider only stdout the actual result of the program ;)*

# Answer
> 3 votes
# Python 2, ~~228~~ ~~223~~ ~~204~~ 199 bytes

I did this on a mobile hotspot so... it's not great... ~~Assumes both of them will always be in the same hundred thousand.~~ Doesn't assume anything now. :D

```
import urllib as l,re
f=lambda i:int(re.search('n">\s*([\d,]+)',l.urlopen('http://codegolf.stackexchange.com/users/%d'%i).read()).group(1).replace(',',''))
d,m=f(12012),f(8478)
print[d>m,'Tie'][d==m]

```

Prints `True` if Dennis has more reputation than Martin, `False` otherwise and `Tie` if they are... tied.

# Answer
> 1 votes
## Stackexchange API Data Explorer, ~~184~~ 180 bytes

Thanks to @Kevin Cruijssen for -4 bytes

```
DECLARE @M int,@D int;SELECT @M=reputation from users where id=8478;SELECT @D=reputation from users where id=12012;IF @D=@M PRINT('tie')ELSE BEGIN;IF @D>@M PRINT(1)ELSE PRINT(2)END

```

Prints 1 for Dennis and 2 for Martin

Since i only yesterday learned about the SEADE this should be very beatable.

Try it here

---
Tags: code-golf, internet, stack-exchange-api
---


title: Construct a tournament bracket

text:
# Question
Title: Construct a tournament bracket
Given an input list of non-empty strings, output an ASCII art representation of a tournament, based on the following drawing rules:

* The number of strings is guaranteed to be of quantity `2,4,8,16,etc.`
* The first two strings play each other, and the next two play each other, and so on. This is the first round.
* For each game, choose the winner randomly with equal probability.
* For the next round, the winner of the first game plays the winner of the second game, the winner of the third game plays the winner of the fourth game, and so on. Subsequent rounds follow the pattern.
* There is eventually one overall winner.
* For pretty output (required) the strings must all be prepended and appended with an underscore `_`.
* In order for the brackets to line up appropriately, each entry must be padded with `_` to all be the same length for that round.
* You can choose whether the padding is prepended or appended, so long as it's consistent.
* Instead, you can choose to pre-pad all strings to be the same length, rather than on a per-round basis. Whichever is golfier for your code.

## Further Rules

* Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* Standard loopholes are forbidden.
* This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

## Examples

Example with cities `['Boston', 'New York', 'Charlotte', 'Atlanta', 'St. Paul', 'Chicago', 'Los Angeles', 'Phoenix']`:

```
_Boston______
             \_New York____
_New York____/             \
                            \_New York_
_Charlotte___               /          \
             \_Charlotte___/            \
_Atlanta_____/                           \
                                          \_St. Paul_
_St. Paul____                             /
             \_St. Paul____              /
_Chicago_____/             \            /
                            \_St. Paul_/
_Los Angeles_               /
             \_Los Angeles_/
_Phoenix_____/

```

Example with `['Lions', 'Tigers', 'Bears', 'Oh My']`:

```
_Lions__
        \_Tigers_
_Tigers_/        \
                  \_Tigers_
_Bears__          /
        \_Bears__/
_Oh My__/

```

# Answer
# Charcoal, ~~92~~ 79 bytes

```
Ａ¹θＷＳ⊞υ⪫__ιＷυ«Ａ⌈ＥυＬκεＡ⁺θθδＦυ«Ｐ×_εＰκＭδ↓»ＡＥ✂υ¹Ｌυ²⎇‽²κ§υ⁺λλυＭε→Ｆυ«Ｍδ↑↗θ←↖θ→»Ｍθ↘Ａδθ

```

Try it online! Link is to verbose version of code. Needs a blank line to mark the end of the input. Explanation:

```
Ａ¹θ

```

Initialise the variable `q`. This holds the size of the zig-zags i.e. half the gap between rows.

```
ＷＳ⊞υ⪫__ι

```

Read nonblank input lines into the array `u`. The lines are automatically surrounded by `_`s as they are read in, although they are not padded yet.

```
Ｗυ«

```

Loop while there are still strings left.

```
Ａ⌈ＥυＬκε

```

Calculate the width of the largest string in `e`.

```
Ａ⁺θθδ

```

Calculate the gap between rows in `d`.

```
Ｆυ«Ｐ×_εＰκＭδ↓»

```

For each team, print the padding, print the team, and then move down to the next team.

```
ＡＥ✂υ¹Ｌυ²⎇‽²κ§υ⁺λλυ

```

For every other team, randomly pick between that team or the previous team. (Note that if there is only one team left then this produces an empty list.)

```
Ｍε→Ｆυ«Ｍδ↑↗θ←↖θ→»Ｍθ↘

```

If there are still teams left, draw the zigzags joining them in pairs.

```
Ａδθ

```

Double the length of the zigzags each time.
> 6 votes

# Answer
# Python 2, ~~379~~ 364 bytes

```
exec r"""c=input();from random import*;R,L,d=range,len,0;u,s="_ ";r=[[""]*-~L(c)@R(2*L(c)-1)]
while c:
 W=2+max(map(L,c));j=1<<d;J=j/2;D=d+d;d+=1
 @r:l[D]=s*W;l[D-1]=s*J
 @R(L(c)):
	h=l*2*j+j-1;r[h][D]=(u+c[l]+u*W)[:W]
	@R(h-J,h+J):r[-~l][~-D]=("/\\"[l<h]+s*abs(h-l-(l<h))).rjust(J)
 c=[choice(l)@zip(c[::2],c[1::2])]
@r:print"".join(l)""".replace("@","for l in ")

```

Try it online!
> 2 votes

---
Tags: code-golf, string, ascii-art
---


# Question
Title: Design a commutative injective function between any (restricted) infinite set and unordered pairs thereof
Related, but this only requires positive integers and does not have to be commutative

The Cantor Pairing Function is described in this Wikipedia article. Essentially, it is an operation such that when it is applied to two values X and Y, one can obtain the original values X and Y given the result.

Your task is to design two functions: one which performs `X, Y -> Z` and the other which performs `Z -> X, Y`. Here's the catch: `X, Y -> Z` must be commutative. This means that `Z -> X, Y` won't be able to determine if the input was `X, Y` or `Y, X`.

The formal definition of this challenge would be:

Choose an countable infinite set S of numbers.
Design two functions that perform the following tasks:

* Given an unordered pair of values in S, return a value in S
* Given a return value from the initial function, return the unordered pair of values which evaluates to the input integer when passed through the first function. I don't care about the behaviour of this inverse function if the input isn't a return value from the first function.

# Requirements

* The result should be identical between runs.
* `{a, a}` is an unordered pair

Note: your answer is more likely to get an upvote from me if you provide a proof, but I will test answers when I get to it and upvote it once I'm fairly sure it works.

# Answer
# Haskell, 65 + 30 = 95 bytes

```
a#b=length.fst$span(<(max a b,min a b))[(a,b)|a<-[1..],b<-[1..a]]

```

Try it online!

```
([(a,b)|a<-[1..],b<-[1..a]]!!)

```

Try it online!

---

**Note:** When the two functions may share code, this is only 75 bytes:

```
(l!!)
a#b=length.fst$span(<(max a b,min a b))l
l=[(a,b)|a<-[1..],b<-[1..a]]

```

Try it online! The domain is the positive integers. The function `(#)` performs the pairing, the function `(l!!)` its inverse. Usage example: Both `(#) 5 3` and `(#) 3 5` yield `12`, and `(l!!) 12` yields `(5,3)`.

This works by explicitly listing all sorted pairs in an infinite list `l`:

```
l = [(1,1),(2,1),(2,2),(3,1),(3,2),(3,3),(4,1),(4,2),(4,3),(4,4),(5,1),(5,2),(5,3),(5,4),(5,5),(6,1), ...`

```

The encoding is then just the index in this list.
> 13 votes

# Answer
# Pyth, 8 + 6 = 14 bytes

```
ij\aSQ16

```

```
    SQ   # Sort the input
 j\a     # join with "a"
i     16 # convert from base 16 to base 10

```

Try it online!

```
c.HQ\a

```

```
 .HQ     # convert from base 10 to 16
c   \a   # split on "a"

```

Try it online!
Domain: Positive integers.
> 5 votes

# Answer
# Jelly, 8 + 11 = 19 bytes

Rolled back since Rod's algorithm didn't work.

This works on the domain of the positive integers.

Takes `x` and `y` as 2 arguments, doesn't matter in which order, returns `z`.

```
»’RSð+ð«

```

Try it online!

Takes `z` and returns `[min(x, y), max(x, y)]`

```
R€Ẏ,Rx`$ị@€

```

Try it online!
> 4 votes

# Answer
# C (gcc), 36 + 39 = 75 bytes

Thanks to @tsh for saving two bytes.

The domain is non-negative integers.

```
p(x,y){return y>x?p(y,x):-~x*x/2+y;}

```

Takes `x` and `y`, returns `z`.

```
u(int*r){for(*r=0;r[1]>*r;r[1]-=++*r);}

```

Takes a two-element `int` array. The second element must be set to `z` before the call. After the call `r` contains `x` and `y`.

Try it online!
> 4 votes

# Answer
## JavaScript (ES7), 44 bytes

```
(x,y)=>x>y?x*x+y:y*y+x
z=>[x=z**.5|0,y=z-x*x]

```

Maps from non-negative integers to a subset thereof.
> 4 votes

# Answer
# Jelly, ~~13~~ 11 bytes

### pair of positive integers to positive integer, 5 bytes

```
Ṁc2+Ṃ

```

Try it online!

### positive integer to pair of positive integers, 6 bytes

```
ŒċṀÞị@

```

Try it online!

## Algorithm

If we sort the set of all unordered pairs of positive integers by their maximum and then by their sum, we get the following sequence.

**{1,1}, {1,2}, {2,2}, {1,3}, {2,3}, {3,3}, {1,4}, {2,4}, {3,4}, {4,4}, {1,5}, {2,5}, {3,5}, {4,5}, {5,5}, …**

The first function takes a pair **{x,y}** and finds its index in this sequence.

The second function takes a positive integer **z** and returns the **z**th item of the sequence.

Note that this mapping is the same as in @EriktheOutgolfer's Jelly answer.

## How it works

```
Ṁc2+Ṃ   Main link. Argument: [x, y]
        Let m = max(x, y) and n = min(x, y).

Ṁ       Maximum; yield m.
 c2     2-combinations; yield mC2 = m(m-1)/2.
        Note that there's one pair with maximum 1 ({1,1}), two pairs with maximum 2
        ({1,2}, {2,2}), etc., so there are 1 + 2 + … + (m-1) = m(m-1)/2 pairs with
        maximum less than m.
    Ṃ   Minimum; yield n.
        Note that {x,y} is the n-th pair with maximum m.
   +    Add; yield mC2 + n.
        This finds {x,y}'s index in the sequence.

```

```
ŒċṀÞị@  Main link. Argument: z

Œċ      2-combinations w/replacement; yield all pairs [x, y] such that x ≤ y ≤ z.
  ṀÞ    Sort by maximum.
    ị@  Retrieve the pair at index z (1-based).

```
> 3 votes

# Answer
## Mathematica (35+53)=78 Bytes

```
((x=Min[#])+(y=Max[#]))(x+y+1)/2+y&

(i=Floor[(-1+Sqrt[1+8#])/2];{#-i(1+i)/2,i(3+i)/2-#})&

```

This is the one good known quadratic pairing function for Z\<--\>ZxZ combined with Min and Max to make it orderless.
> 2 votes

# Answer
# Java 8, ~~153~~ ~~146~~ ~~141~~ 137 + ~~268~~ ~~224~~ ~~216~~ 205 bytes

Pair function

```
a->{String f="";for(int i=(f+a[0]).length(),c=0,j;i>0;i-=c,f+=c,c=0)for(j=1;j<10;c+=i-j++<0?0:1);return new Integer(a[0]+""+a[1]+"0"+f);}

```

Try it online!

Depair function

```
r->{String a=r+"",t=a.substring(a.lastIndexOf('0')+1);int l=0,i=l,o=t.length();for(;i<o;l+=r.decode(t.charAt(i++)+""));return new int[]{r.decode(a.substring(0,l)),r.decode(a.substring(l,a.length()-o-1))};}

```

Try it online!
> 2 votes

# Answer
# Ruby, 66 bytes

```
f=->x,y{2**~-x|2**~-y}
g=->n{x,y=(1..n).select{|i|n[i-1]>0};[x,y||x]}

```

I'm trying to find a way to cunningly select an infinite set to make this easier, this is the best I've got so far.

We define f(x,y) = 2x-1 bitwise-or 2y-1. The domain consists of the set defined recursively as containing 1,2, and all numbers that can be produced by calling f on numbers in the set (note that f(1,1) = 1 and f(2,2) = 2, so 1 and 2 have inverses). The resulting numbers all have either one or two 1s in their binary expansion, with the indices of the 1s corresponding to numbers in the set. We can get the original unordered pair out by taking the indices. If there's only one 1, that means the elements of the pair are equal.

For example, f(3,5) is 20, because 20 is 10100 in base 2, which has 1s in the 3rd and 5th least significant places.
> 2 votes

# Answer
# 05AB1E, 6 + 11 = 17 bytes

Port of my Jelly answer.

Domain: positive integers.

Takes a list `[x, y]` as input, returns `z`.

```
{`<LO+

```

Try it online!

Takes a positive integer `z` as input, returns `[min(x, y), max(x, y)]`.

```
L2ã€{RÙR¹<è

```

Try it online!

-5 thanks to Emigna.
> 1 votes

# Answer
# JavaScript, 72 bytes

```
f=a=>eval('0x'+a.sort().join`a`)
g=n=>n.toString(16).split`a`.map(x=>+x)

```

Works for positive integers (in theory). Quite simple idea: sort two number in some (magic) order, connect them as string by a letter `"a"`, parse it as hex integer.

```
f=a=>eval('0x'+a.sort().join`a`)
g=n=>n.toString(16).split`a`.map(x=>+x)
```

```
<pre oninput="p.value=f([+x.value, +y.value])">
     X = <input id="x" type="number" min="0" />
     Y = <input id="y" type="number" min="0" />
 f(X,Y)= <output id="p"></output>
</pre>

<pre oninput="q.value=g(+u.value).join(', ')">
     U = <input id="u" type="number" />
   g(U)= <output id="q"></output>
</pre>
```
> 1 votes

# Answer
# MATL, 6+8=14 bytes

Encoding function, takes two inputs n, m. Outputs product of nth prime and mth prime.

```
,iYq]*

```

Steps:

* `,` \- Do twice
* `i` \- Push input
* `Yq` \- Pop input, push input'th prime
* `]*` \- End do twice, pop both primes and push product

---

Decoding function, takes one input m. Outputs the number of primes below each of the prime factors of n.

```
iYf"@Zqn

```

Steps:

* `i` \- Push input
* `Yf` \- Pop input, push array of prime factors
* `"` \- For n in array
* `@Zq` \- Push array of primes below n
* `n` \- Pop array, push length of array

This is commutative because multiplication is commutative, and injective because prime factorizations are unique. Not that this is not onto the integers.
> 1 votes

# Answer
# Husk, 5+3=8 bytes

I really hope I got the challenge right, I see some deleted answers that seem valid to me...

Couples of positive integers to a single positive integer:

```
¤*!İp

```

Try it online!

It works by taking the numbers at the given indices (1-indexed) from the list of prime numbers, and multiplying them.

Result of the first function to couples of positive integers:

```
mṗp

```

Try it online!

We factorize the input number and return the index in the list of primes of all (both) of its factors.

### Worked example

Given `(4,1)` as a starting couple, we take the fourth and first prime numbers `(7,2)` and multiply them → `14`. This multiplication is what makes the function indipendent on the order of the two elements.

Starting from `14`, we factorize it `(2,7)` and return the indices of `2` and `7` in the list of prime numbers → `(1,4)`.
> 0 votes

# Answer
## C#, 80 bytes ( 38 + 42 )

---

### Data

### Encoder

* **Input** `Int32` `l` A number
* **Input** `Int32` `r` A number
* **Output** `Int64` Both ints fused together

### Decoder

* **Input** `Int32` `v` The value
* **Output** `Int32[]` An array with the two original ints.

---

### Golfed

```
// Encoder
e=(l,r)=>{return(long)l<<32|(uint)r;};

// Decoder
d=v=>{return new[]{v>>32,v&0xFFFFFFFFL};};

```

---

### Ungolfed

```
// Encoder
e = ( l, r ) => {
    return (long) l << 32 | (uint) r;
};

// Decoder
d = v => {
    return new[] {
        v >> 32,
        v & 0xFFFFFFFFL };
};

```

---

### Ungolfed readable

```
// Encoder
// Takes a pair of ints
e = ( l, r ) => {

    // Returns the ints fused together in a long where the first 32 bits are the first int
    // and the last 32 bits the second int
    return (long) l << 32 | (uint) r;
};

// Decoder
// Takes a long
d = v => {

    // Returns an array with the ints decoded where...
    return new[] {

        // ... the first 32 bits are the first int...
        v >> 32,

        // ... and the last 32 bits the second int
        v & 0xFFFFFFFFL };
};

```

---

### Full code

```
using System;
using System.Collections.Generic;

namespace TestBench {
    public class Program {
        // Methods
        static void Main( string[] args ) {
            Func<Int32, Int32, Int64> e = ( l, r ) => {
                return(long) l << 32 | (uint) r;
            };
            Func<Int64, Int64[]> d = v => {
                return new[] { v >> 32, v & 0xFFFFFFFFL };
            };

            List<KeyValuePair<Int32, Int32>>
                testCases = new List<KeyValuePair<Int32, Int32>>() {
                    new KeyValuePair<Int32, Int32>( 13, 897 ),
                    new KeyValuePair<Int32, Int32>( 54234, 0 ),
                    new KeyValuePair<Int32, Int32>( 0, 0 ),
                    new KeyValuePair<Int32, Int32>( 1, 1 ),
                    new KeyValuePair<Int32, Int32>( 615234, 1223343 ),
                };

            foreach( KeyValuePair<Int32, Int32> testCase in testCases ) {
                Console.WriteLine( $" ENCODER: {testCase.Key}, {testCase.Value} = {e( testCase.Key, testCase.Value )}" );
                Console.Write( $"DECODING: {e( testCase.Key, testCase.Value )} = " );
                PrintArray( d( e( testCase.Key, testCase.Value ) ) );

                Console.WriteLine();
            }

            Console.ReadLine();
        }

        public static void PrintArray<TSource>( TSource[] array ) {
            PrintArray( array, o => o.ToString() );
        }
        public static void PrintArray<TSource>( TSource[] array, Func<TSource, String> valueFetcher ) {
            List<String>
                output = new List<String>();

            for( Int32 index = 0; index < array.Length; index++ ) {
                output.Add( valueFetcher( array[ index ] ) );
            }

            Console.WriteLine( $"[ {String.Join( ", ", output )} ]" );
        }
    }
}

```

---

### Releases

* **v1.0** \- `80 bytes` \- Initial solution.

---

### Notes

* None
> 0 votes

# Answer
# Python: 41+45=86

## encoder: 41

```
e=lambda*x:int('1'*max(x)+'0'+'1'*min(x))

```

> ```
> e(4, 3), e(3,4)
>
> ```
>
> (11110111, 11110111)

## decoder: 45

```
d=lambda z:[len(i)for i in str(z).split('0')]

```

> ```
> d(11110111)
>
> ```
>
> \[4, 3\]

# Older attempt:

Python: 114: 30 + 84

## encoder: 30

accepts 2 integers, returns a string

```
e=lambda*x:2**max(x)*3**min(x)

```

> ```
> e(3, 4), e(4, 3)
>
> ```
>
> (432, 432)

## decoder: 86

```
def d(z):
 x=y=0
 while 1-z%2:
  x+=1
  z/=2
 while 1-z%3:
  y+=1
  z/=3
 return x,y

```

> ```
> d(432)
>
> ```
>
> 4, 3

## decoder2: 120

another attempt with generator comprehensions and sum

```
def d(z):
 x=sum(1 for i in range(z)if not z%(2**i))-1
 z/=2**x
 return x,sum(1 for i in range(int(z))if not z%(3**i))-1

```
> 0 votes

---
Tags: code-golf, math, open-ended-function
---


title: Simulate My Stupid Old Alarm Clock

text:
# Question
Title: Simulate My Stupid Old Alarm Clock
I have a stupid old alarm clock with two buttons: `hour` and `minute`. The `hour` button increments the hour of a set alarm, and `minute` increments the minute time of a set alarm. However, some smart designers realized that pressing both buttons at the same time should have a meaning, and decided that pressing `hour` and `minute` simultaneously would cause the alarm to be set to `12:00 am`/`0:00`. Your task is to simulate this behavior.

# Task

Given a start time and a sequence of button states, figure out the end time.

Starting from the start time, increment the hour for each occurrence of `(1,0)`, increment the minute for each occurrence of `(0,1)`, and set the time to `0:00` for each occurrence of `(1,1)`. The states `(0,0)` should be ignored because they correspond to neither button being pressed.

When adding to minutes and hours, if the minute/hour goes above the maximum, set it to `0`, i.e. incrementing a minute value of `59` should set the minute value to `0` and incrementing an hour value of `23` should set the hour value to `0`. Incrementing minute/hour values above their limits do not affect the other value, for example incrementing the minute of `10:59` yields `10:00`, not `11:00`.

# Example

Given the input time `13:58` and steps `[(0,1),(0,1),(0,1),(0,0),(1,1),(1,0)]`,

1. `(0,1)`. This corresponds to `minute` being pressed. The time is now `13:59`.
2. `(0,1)`. This corresponds to `minute` being pressed. The time is now `13:00`.
3. `(0,1)`. This corresponds to `minute` being pressed. The time is now `13:01`.
4. `(0,0)`. This corresponds to neither button being pressed. The time,unaffected, is now `13:01`
5. `(1,1)`. This corresponds to both buttons being pressed. The time is now `0:00`.
6. `(1,0)` This corresponds to `hour` being pressed. The time is now `1:00`.

Since we end with `1:00`, it is the output.

# I/O

The input will consist of a time and a sequence of button states. The output is a single time.

The input time and output time may be

* a 2-tuple of `(hour, minute)` or `(minute, hour)` in `24`-hour time such as `(13, 30)` (`hour` ranges from `0` to `23` and `minute` ranges from `0` to `59`)
* same as the previous but in `12`-hour time and a Boolean `am`/`pm` switch (`hour` ranges from `0` to `11` or `12` and `1` to `11` with `minute` from `0` to `59`).
* a number of minutes since `0:00` such as 810 (from 0 to 1439, inclusive)
* any other format which encodes the same information

The sequence of button states is a representation of a list of Boolean 2-tuples, for example:

* a list of tuples: `[(0,1),(1,0),(0,0),(1,1)]`
* a space-delimited string: `"01 10 00 11"`
* a string: `"01100011"`
* in Quaternary: `[1,2,0,3]`
* converted to an integer: `99`
* any other format which encodes the same information

# Test Cases

```
time,steps -> output
06:49,[(0, 1)] -> 06:50
12:23,[(1, 0)] -> 13:23
02:23,[(0, 1), (1, 0)] -> 03:24
21:40,[(0, 1), (0, 1), (0, 1), (0, 1)] -> 21:44
13:10,[(0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (1, 1), (0, 1), (0, 1)] -> 00:02
21:33,[(1, 0), (0, 1), (1, 0), (0, 1)] -> 23:35
14:21,[(0, 1), (0, 1), (0, 1)] -> 14:24
02:39,[(0, 0), (0, 1)] -> 02:40
16:07,[(0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1)] -> 19:16
17:55,[(0, 1), (1, 0), (0, 1)] -> 18:57
15:55,[(1, 0), (1, 0), (1, 0), (0, 1), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (1, 0), (1, 0), (0, 1), (1, 0)] -> 23:00
22:11,[(0, 1), (1, 0), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1)] -> 00:19
03:58,[(1, 0), (0, 0), (0, 0), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (0, 1), (1, 0), (0, 1)] -> 07:03
13:02,[(0, 1), (1, 0), (0, 1), (1, 0), (0, 1), (0, 1), (1, 0)] -> 16:06
04:37,[(1, 0), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (1, 0), (0, 1), (1, 0)] -> 08:47
00:01,[(0, 1), (1, 0), (1, 0), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1)] -> 03:08
02:58,[(1, 0), (1, 0), (0, 1)] -> 04:59
01:43,[(0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (1, 0), (0, 1)] -> 04:52
07:54,[(1, 0), (0, 1), (1, 0), (1, 0), (1, 1)] -> 00:00
09:33,[(0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1)] -> 10:38
09:01,[(0, 1), (0, 1)] -> 09:03
19:04,[(0, 1), (1, 0), (0, 1), (1, 0)] -> 21:06
11:17,[(0, 1), (1, 0), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (1, 1), (0, 1), (0, 1)] -> 00:02
19:32,[(0, 1), (1, 0), (0, 1), (1, 0), (1, 0), (1, 0)] -> 23:34
17:31,[(0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (1, 0), (0, 1), (0, 0), (1, 1), (0, 1)] -> 00:01
06:46,[(0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (0, 1), (0, 1), (1, 0), (0, 1), (1, 0), (0, 1), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1), (1, 0), (1, 0), (0, 1), (1, 0), (0, 1), (0, 1), (0, 1), (0, 1), (0, 1)] -> 18:16

```

# Answer
# Jelly, 13 bytes

```
_`+Ạ}?/%24,60

```

Try it online!
> 8 votes

# Answer
# Python 2, ~~84~~ 75 bytes

```
lambda c,a:reduce(lambda(h,m),(d,e):(d&e)and(0,0)or((h+d)%24,(m+e)%60),a,c)

```

Try it online!

Function that takes time as a tuple (hour,minute); outputs same way.
> 7 votes

# Answer
# C, ~~89~~ 87 bytes

*Thanks to @Jonathan Frech for saving two bytes!*

```
f(h,m,s)char*s;{for(;*s;++s)*s++&1?*s&1?h=m=0:++h:*s&1&&++m;printf("%d %d",h%24,m%60);}

```

Try it online!
> 6 votes

# Answer
# Jelly,  ~~21~~  (17?) 19 bytes

17 bytes? -- If the input format: `[[initHour, initMinute], [a1, b1], [a2, b2], ...]` is acceptable we'd have a monadic link and may remove `W;` from the beginning of the second line.

Note: This is now converging towards Erik the Outgolfers Jelly answer, so I wont bother golfing more (I had not seen it)...

```
N⁹⁹Ạ¤?+⁸
W;ç/%24,60

```

A dyadic link taking a list of the initial time as integers `[hour, minute]` (24-hour) on the left and a list of button states `[[hourPressed, minPressed], ...]` on the right
which returns a list of the end result time as integers, again `[hour, minute]` (24-hour).

**Try it online!** or see the test-suite

### How?

```
N⁹⁹Ạ¤?+⁸ - Link 1, nextState: list, currentState [cH, cM]; list, presses [pH, pM]
     ?   - if:
    ¤    - ...condition: nilad followed by link(s) as a nilad:
  ⁹      -   chain's right argument, presses
   Ạ     -   all truthy? (1 for [1,1] 0 otherwise)
N        - ...then: negate (the left argument, currentState, i.e. [-cH, -cM])
 ⁹       - ...else: chain's right argument, presses
       ⁸ - chain's left argument, currentState
      +  - add
           i.e.: if presses was [1,1] then [cH+-cH,cM+-cM]=[0,0]
                 otherwise [cH+pH,cM+cM]

W;ç/%24,60
     24,60 - literal list of integers [24,60]
    %      - modulo by (vectorises)

```
> 6 votes

# Answer
# Retina, 75 bytes

```
.*,1:1
:
\d+
$*
O`\D1*
,

1>`:

+`1{24}:|:1{60}
:
(?<=^|:)1*
$.&
\b\d\b
0$&

```

Try it online! Link includes test cases. Explanation:

```
.*,1:1
:

```

Delete everything up to and including the last double button press, replacing it with an empty time (in case that's the last button press).

```
\d+
$*

```

Convert to unary.

```
O`\D1*

```

Sort the minutes to the end.

```
,

```

Add the hours together.

```
1>`:

```

Add the minutes together, but keeping the hours separate.

```
+`1{24}:|:1{60}
:

```

Reduce the hours and minute modulo 24 or 60 as appropriate.

```
(?<=^|:)1*
$.&

```

Convert to decimal.

```
\b\d\b
0$&

```

Format to two digits.
> 5 votes

# Answer
# JavaScript (ES6), 55 bytes

```
t=>a=>a.map(x=>x>2?t=[0,0]:t[x-1]++)&&[t[0]%60,t[1]%24]

```

Takes input in currying syntax, with the starting time in the array form `[min, hour]` and the steps as a Quaternary array. Output time is in the same format as the input time.

## Test Cases

```
let f=
t=>a=>a.map(x=>x>2?t=[0,0]:t[x-1]++)&&[t[0]%60,t[1]%24]

;[[[49, 06], [1]], [[23, 12], [2]], [[23, 02], [2, 1]], [[40, 21], [1, 1, 1, 1]], [[10, 13], [1, 1, 1, 1, 2, 3, 1, 1]], [[33, 21], [2, 1, 2, 1]], [[21, 14], [1, 1, 1]], [[39, 02], [1, 0]], [[07, 16], [1, 1, 1, 1, 2, 2, 1, 1, 2, 1, 1, 1]], [[55, 17], [1, 2, 1]], [[55, 15], [2, 2, 2, 1, 1, 1, 2, 2, 1, 2, 2, 1, 2]], [[11, 22], [1, 2, 1, 1, 1, 1, 1, 2, 1, 1]], [[58, 03], [2, 0, 0, 1, 1, 2, 2, 1, 1, 2, 1]], [[02, 13], [1, 2, 1, 2, 1, 1, 2]], [[37, 04], [2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 2]], [[01, 00], [1, 2, 2, 1, 1, 1, 2, 1, 1, 1]], [[58, 02], [2, 2, 1]], [[43, 01], [1, 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1]], [[54, 07], [2, 1, 2, 2, 3]], [[33, 09], [1, 1, 1, 2, 1, 1]], [[01, 09], [1, 1]], [[04, 19], [1, 2, 1, 2]], [[17, 11], [1, 2, 1, 1, 2, 1, 1, 3, 1, 1]], [[32, 19], [1, 2, 1, 2, 2, 2]], [[31, 17], [1, 1, 1, 2, 1, 2, 1, 0, 3, 1]], [[46, 06], [1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 2, 2, 1, 1, 1, 2, 2, 1, 1, 1, 2, 1, 2, 1, 1, 2, 1, 1, 1, 2, 2, 1, 2, 1, 1, 1, 1, 1]]]
.forEach(([time,steps])=>{
  let res = f([...time])(steps)
  console.log(JSON.stringify(time)+" -> "+JSON.stringify(res))
})
```

```
.as-console-wrapper{max-height:100%!important}
```
> 4 votes

# Answer
# Python 3, ~~135~~ ~~117~~ 115 bytes

-20 bytes thanks to Jonathan Frech

```
def a(m,f):
 for b,c in f:
  if b&c:m=[0,0]
  elif b:m[0]=-~m[0]*(m[0]<23)
  elif c:m[1]=-~m[1]*(m[1]<59)
 return m

```

Try it online!

Takes the time as a list in the form `[hour, minute]`.
> 4 votes

# Answer
# Haskell, 58 bytes

```
foldl(#)
_#(1,1)=(0,0)
(h,m)#(x,y)=(mod(h+x)24,mod(m+y)60)

```

Try it online! Example usage: `foldl(#) (23,58) [(0,1),(1,0),(0,0),(0,1),(0,1)]`.
> 4 votes

# Answer
# Perl 6, 40 bytes

```
{.reduce({(@^a Z+@^b)X*!@b.min})Z%24,60}

```

Try it online!

Takes a list containing the start time followed by the button presses. Returns the end time. Times and buttons are `(hour, minute)` pairs. 24-hour time.
> 3 votes

# Answer
# Perl 5, 70 bytes

69 bytes of code + 1 for `-n` flag

```
s/.*d/0:0/;/(.*):(\d+)/;printf"%02d:%02d",($1+y/c//)%24,($2+y/b//)%60

```

Try it online!

**Input Format**

`hh:mm,abcdabcdabcdaddccbbaa`

*where:*

```
hh=start hour
mm=start minute
 a = (0, 0) = no buttons pressed
 b = (0, 1) = minute button pressed
 c = (1, 0) = hour button pressed
 d = (1, 1) = both buttons pressed

```

Spaces or other separators between the presses are insignificant.

**Explanation**

```
s/.*d/0:0/;    # If both buttons were ever pressed, previous presses
               # don't matter.  Get rid of them and set start time to midnight.
/(.*):(\d+)/;  # Extract start hour and minute
printf"%02d:%02d",            # Output numbers with leading 0
($1+y/c//)%24,                # Take starting hour, add number of presses, remainder 24
($2+y/b//)%60                 # Take starting minute, add number of presses, remainder 24

```
> 3 votes

# Answer
# Swift, ~~106~~ 96 bytes

-10, thanks to Xcoder

```
func x(m:(Int,Int),n:[(Int,Int)]){let i=n.reduce(m){($0.0+$1.0,$0.1+$1.1)};print(i.0%24,i.1%60)}

```

Try it on ideone!

function will take initial value and array of tuples and returns final time.
> 3 votes

# Answer
# Terrapin Logo, 304 bytes

Not optimized; lots of spaces.

```
MAKE "M :B MAKE "H :A LABEL "L IF EMPTY? :I OP LIST :H :M MAKE "C FIRST :I IF AND ((ITEM 2 :C)=1) ((ITEM 1 :C) = 0) MAKE "M :M+1 IF :M=60 MAKE "M 0 IF AND ((ITEM 1 :C) = 1) ((ITEM 2 :C)=1 MAKE "M 0 MAKE "H 0 IF AND ((ITEM 1 :C)-1) ((ITEM 2 :C) = 0) MAKE "H :H + 1 IF :H = 23 MAKE "H 0 MAKE "I BF :I GO "L

```

Takes a list as its first input and the starting hour+minute (seperate inputs) as second and third, respectively.

I can't copy+paste from Terrapin Logo as it's a trial version so that's that :(
> 1 votes

# Answer
# Mathematica, 54 bytes

```
Switch[#2,a={0,0},#,a+1,a,_,Mod[+##,{24,60}]]&~Fold~#&

```

Anonymous function. Takes a list of 2-tuples as input and returns a 2-tuple as output.
> 1 votes

# Answer
# , 61 bytes

```
function(I,B){for(b in B)I=I+"if"(sum(b)>1,-I,b)
I%%c(24,60)}

```

Takes `I` as a length-2 vector `c(H,M)` and `B` as a list of length-2 vectors for the buttons, `c(H,M)`. Iterates through `B`, setting `I` to `c(0,0)` if the sum is `2`. Then it mods down at the end. There's also a function in the header to translate the button presses into the right R format if you'd like to test them all; it takes the array `[(H,M),...]` as a string.

Try it online!
> 1 votes

# Answer
# C# (.NET Core), 93 bytes

```
(n,l)=>{for(int i=0,x;i<n.Length;){x=n[i++];if(x>1)l[0]=l[1]=0;else{l[x]=++l[x]%(24+36*x);}}}

```

Try it online!

Takes input as in trinary, with 0==(1,0),1==(0,1),2==(1,1), and the time in an array with index 0 being hours and 1 being minutes. Modifies the time array in place.
> 1 votes

# Answer
# Pyth, 22 bytes

```
%Vu?.AH,00+VGHEQ,24 60

```

Try it here.
> 0 votes

# Answer
# Scala, 116 bytes

So I just take the start time as two first parameters of my func (`h` and `m`), and I take the input sequence as an Array\[Tuple2\].

```
var x=h
var y=m
for(u<-a)u match{case (0,1)=>y=(y+1)%60
case (1,0)=>x=(x+1)%24
case (1,1)=>{x=0;y=0}
case _=>}
(x,y)

```

I wonder ... should I count the func declaration (`def time(h:Int,m:Int,a:Array[Tuple2[Int,Int]]):Tuple2[Int,Int]={` plus the ending `}`) in byte count?

Try it online!
> 0 votes

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


title: Answer to Vote Ratio

text:
# Question
Title: Answer to Vote Ratio
*This question is inspired by the fact that I love seeing questions with equal vote and answer counts...*

---

So here's a simple challenge for y'all:

**Challenge:**

Given a `codegolf.stackexchange` question id, output the ratio between the question's votes and number of answers (e.g. `votes/answers`).

**Specifics:**

* You may access the internet, but you may only access `stackexchange.com` and its various sub-domains. You may not use URL shorteners.
* You may take input and give output in any standard format.
* You must output the ratio as a decimal number in base 10, with at least 4 {accurate} digits after the decimal (zeros may be truncated).
* If the question is unanswered, your program may produce undefined behavior.
* You should use the `score` of the question as the vote-count, see here.

This is , least bytes in each language wins for that language, least bytes overall wins overall.

**Here is a sample program in `Python 3 + requests`:**

```
import requests
import json

id = input("id> ")
url = "https://api.stackexchange.com/2.2/questions/" + id + "?site=codegolf"
content = requests.get(url).text
question = json.loads(content)["items"][0]

print(float(question["score"]) / question["answer_count"])

```

# Answer
> 10 votes
# JavaScript (ES6), ~~103~~ 102 bytes

Needs to be run from the root level of `api.stackexchange.com`. Returns a `Promise` object containing the result.

```
n=>fetch(`questions/${n}?site=codegolf`).then(r=>r.json()).then(({items:[j]})=>j.score/j.answer_count)

```

If requiring that it be run from a specific path is allowed then that becomes ~~92~~ 90 bytes.

```
n=>fetch(n+`?site=codegolf`).then(r=>r.json()).then(({items:[j]})=>j.score/j.answer_count)

```

---

## Try it

Full URL added to enable it to work here.

```
f=
n=>fetch(`//api.stackexchange.com/questions/${n}?site=codegolf`).then(r=>r.json()).then(({items:[j]})=>j.score/j.answer_count)
onchange=_=>f(+i.value).then(t=>o.innerText=t)
```

```
<input id=i type=number><pre id=o>
```

# Answer
> 8 votes
# Stratos, 40 bytes

-4 bytes thanks to Shaggy

```
f"¹⁵s/%²"r"⁷s"@0
{s"answer_⁰"
⁰s"score"/

```

Try it!

Stratos specialises in questions.

Explanation:

The code decompresses to the following:

```
f"api.stackexchange.com/questions/%?site=codegolf"r"items"@0
{s"answer_count"
⁰s"score"/

```

Starting from the first line, Stratos evaluates the dyads from right to left.

`f"api.stackexchange.com/questions/%?site=codegolf"r"items"@0` means "evaluate the dyad `@` with the left-hand argument `f"api.stackexchange.com/questions/%?site=codegolf"r"items"` and the right-hand argument `0`. `@` gets the *nth* element of a JSON array.

To evaluate `f"api.stackexchange.com/questions/%?site=codegolf"r"items"`, we will next evaluate the dyad `r` with the left-hand argument `f"api.stackexchange.com/questions/%?site=codegolf"` and the right-hand argument `"items"`. `r` gets the JSON array with the specified name.

Next, we will need to evaluate `f"api.stackexchange.com/questions/%?site=codegolf"`. First, `%` is replaced with the input. `f` means "get the contents of this URL".

Now, we can move on to the second line. The newline means "add what we evaluated to the implicit argument list"

Next, we evaluate `s` (get string in JSON object with a certain name) with `{` and `"answer_count"`. `{` takes an element from the implicit argument stack, returns it, and adds it back to the stack.

Then, we add the output of that to the implicit argument stack.

To evaluate `⁰s"score"/`, we are applying the dyad `/` (divide) to `⁰s"score"` and an element from the implicit argument stack.

To evaluate `⁰s"score"` we are getting the string `"score"` from the JSON object from the 0th element in the implict argument stack.

Now, the output of `/` is printed and the program terminates.

# Answer
> 5 votes
# \+ jsonlite, 111 bytes

```
function(n,x=jsonlite::fromJSON(sprintf('http://api.stackexchange.com/questions/%s?site=codegolf',n))$i)x$s/x$a

```

R-fiddle link

jsonlite is a nice JSON \<-\> R conversion library which works quite well. I wasn't about to golf a JSON parser for R...

# Answer
> 4 votes
# T-SQL, ~~64~~ 54 bytes

It is rare that SQL can beat (most) other languages! Instead of the API URL I went directly to the Stack Exchange Data Explorer:

```
SELECT 1.0*Score/AnswerCount FROM Posts WHERE Id=##i##

```

The `##i##` isn't standard SQL, that's Stack Exchange's format to prompt for input.

Note that the data explorer source is only updated nightly, so values aren't current.

Will throw a divide by zero error on questions with no answers.

**Edit**: Saved 10 bytes by multiplying by 1.0 instead of an explicit `CONVERT` to `FLOAT`.

# Answer
> 3 votes
# PowerShell, 130 bytes

```
($a=(ConvertFrom-Json(iwr("http://api.stackexchange.com/questions/"+$args+"?site=codegolf")).content).items).score/$a.answer_count

```

Performs an `I`nvoke-`W`eb`R`equest against the URL, gets the `.content` thereof, does a `ConvertFrom-Json` of that content, and gets the `.items` of that JSON object. Stores that into `$a` and pulls out the `.score` as the numerator. The denominator is the `.answer_count`. That value is left on the pipeline and output is implicit.

If the question is unanswered, this *should* toss a "Divide by zero" error.

# Answer
> 3 votes
# Japt, ~~83~~ 82 bytes

Wanted to give this a try to see how it would work out, seeing as Japt can't natively accomplish it. Essentially all this is doing is `eval`ing a compressed version of my JS solution. As Japt *is* JS then we can require that this be run from the root level of `api.stackexchange.com` and also return a `Promise` object containing the result.

```
Ox`fet®("quÀËs/{U}?ÐÒ=¬¸golf").È(r=>r.js()).È(i=>(j=i.ems[0]).sÖ/j.s³r_Öt)

```
* View it
* Try it \- the extra bytes in this version are accounted for by the inclusion of `//api.stackexchange.com/` in the URL and of `console.log` so you can actually see it working

# Answer
> 2 votes
# Mathematica, 124 bytes

```
N@("score"/.(u="items"/.Import["http://api.stackexchange.com/questions/"<>#<>"?site=codegolf","JSON"]))/("answer_count"/.u)&

```

Mathematica has a data type called `Rule` and it confuses the heck out of me. :P

# Answer
> 1 votes
# Python 3 \+ requests, 149 bytes

*-1 byte thanks to Mr. Xcoder.*

```
from requests import*
u=get('http://api.stackexchange.com/questions/%s?site=codegolf'%input()).json()['items'][0]
print(u['score']/u['answer_count'])

```

# Answer
> 0 votes
# PHP, 167 bytes

```
<?$f=json_decode(gzdecode(file_get_contents('https://api.stackexchange.com/2.2/questions/'.$argv[1].'?site=codegolf')))->items[0];echo $f->score/$f->answer_count;

```

Turbo-fast crack at this. Save as a file and execute in the terminal like so:

```
php -f file.php 143083

```

Might be a way to reduce this.

---
Tags: code-golf, internet, stack-exchange-api
---


title: Complex Dice Rolling Expressions

text:
# Question
Title: Complex Dice Rolling Expressions
## Background

I play D&D on a regular basis with some friends. While talking about the complexity of some systems/versions when it comes to rolling dice and applying bonuses and penalties, we jokingly came up with some additional complexity for dice rolling expressions. Some of them were too outrageous (like extending simple dice expressions like `2d6` to matrix arguments1), but the rest make for an interesting system.

## The Challenge

Given a complex dice expression, evaluate it according to the following rules and output the result.

## Basic Evaluation Rules

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

## Operators

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

* `d`: output `a` independent uniform random integers in the range `[1, b]`
    + Precedence: 3
    + Both operands are integers
    + Examples: `3d4 => [1, 4, 3]`, `[1, 2]d6 => [3, 2, 6]`
* `t`: take the `b` lowest values from `a`
    + Precedence: 2
    + `a` is a list, `b` is an integer
    + If `b > len(a)`, all values are returned
    + Examples: `[1, 5, 7]t1 => [1]`, `[5, 18, 3, 9]t2 => [3, 5]`, `3t5 => [3]`
* `T`: take the `b` highest values from `a`
    + Precedence: 2
    + `a` is a list, `b` is an integer
    + If `b > len(a)`, all values are returned
    + Examples: `[1, 5, 7]T1 => [7]`, `[5, 18, 3, 9]T2 => [18, 9]`, `3T5 => [3]`
* `r`: if any elements in `b` are in `a`, reroll those elements, using whatever `d` statement generated them
    + Precedence: 2
    + Both operands are lists
    + Rerolling is done only once, so it is possible to still have elements of `b` in the result
    + Examples: `3d6r1 => [1, 3, 4] => [6, 3, 4]`, `2d4r2 => [2, 2] => [3, 2]`, `3d8r[1,8] => [1, 8, 4] => [2, 2, 4]`
* `R`: if any elements in `b` are in `a`, reroll those elements repeatedly until no elements of `b` are present, using whatever `d` statement generated them
    + Precedence: 2
    + Both operands are lists
    + Examples: `3d6R1 => [1, 3, 4] => [6, 3, 4]`, `2d4R2 => [2, 2] => [3, 2] => [3, 1]`, `3d8R[1,8] => [1, 8, 4] => [2, 2, 4]`
* `+`: add `a` and `b` together
    + Precedence: 1
    + Both operands are integers
    + Examples: `2+2 => 4`, `[2]+[2] => 4`, `[3, 1]+2 => 6`
* `-`: subtract `b` from `a`
    + Precedence: 1
    + Both operands are integers
    + `b` will always be less than `a`
    + Examples: `2-1 => 1`, `5-[2] => 3`, `[8, 3]-1 => 10`
* `.`: concatenate `a` and `b` together
    + Precedence: 1
    + Both operands are lists
    + Examples: `2.2 => [2, 2]`, `[1].[2] => [1, 2]`, `3.[4] => [3, 4]`
* `_`: output `a` with all elements of `b` removed
    + Precedence: 1
    + Both operands are lists
    + Examples: `[3, 4]_[3] => [4]`, `[2, 3, 3]_3 => [2]`, `1_2 => [1]`

## Additional Rules

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

## Test Cases

Format: `input => possible output`

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

```

All but the last test case were generated with the reference implementation.

## Worked Example

Expression: `1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3))`

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

## Reference Implementation

This reference implementation uses the same constant seed (`0`) for evaluating each expression for testable, consistent outputs. It expects input on STDIN, with newlines separating each expression.

```
#!/usr/bin/env python3

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

```

---

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

# Answer
# Python 3, ~~803 788 753 749 744 748 745 740 700 695 682~~  680 bytes

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

```

Try it online!

Contains a lot of unprintables, see the TIO link for the full code

-5 bytes thanks to Mr.Xcoder

-5 more bytes thanks to NGN

-about 40 bytes thanks to Jonathan French

Yuck, what a kludge! This works by using a regular expression to wrap all numbers in my `k` class, and converting all of the operators into operators python understands, then using the magic methods of the `k` class to handle the math. The `+-` and `+--` at the end for `.` and `_` are a hack to keep the precedence correct. Likewise, I can't use the `**` operator for d because doing so would make `1d4d4` be parsed as `1d(4d4)`. Instead, I wrap all numbers in an extra set of parens and do d as `.j`, since method calls have higher precedence that operators. The last line evaluates as an anonymous function that evaluates the expression.
> 8 votes

# Answer
# APL (Dyalog Classic), 367 bytes

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

```

Try it online!

This is the shunting yard algorithm from the reference implementation merged with `evaluate_dice()`, without the cruft and object-oriented nonsense. Only two stacks are used: `h` for the operators and `v` for the values. Parsing and evaluation are interleaved.

Intermediate results are represented as 2×N matrices where the first row are the random values and the second row are the number of sides on the dice that produced them. When a result is not produced by the dice-throwing "d" operator, the second row contains arbitrary numbers. A single random value is a 2×1 matrix and thus indistinguishable from a 1-element list.
> 3 votes

# Answer
## Python 3: 723 722 714 711 707 675 653 665 bytes

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

```

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

# Answer
## Clojure, ~~731~~ 720 bytes

(when newlines are removed)

Update: a shorter implementation of `F`.

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

```

This consists of four main parts:

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

I'm not sure how to thoroughly test this, maybe via statistical tests against a reference implementation? At least the AST and its evaluation is relatively easy to follow.

Example S-expression from `1d((8d20t4T2)d(6d6R1r6)-2d4+1d2).(1d(4d6_3d3))`:

```
(. (d 1 (- (d (T (t (d 8 20) 4) 2)
              (R (d 6 6) (r 1 6)))
           (+ (d 2 4)
              (d 1 2))))
   (d 1 (_ (d 4 6) (d 3 3))))

```

Less golfed with internediate results and tests:

```
(def f #(read-string(clojure.string/replace(str"("%")")#"[^0-9]"" $0 ")))

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

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

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

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

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

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

```
> 2 votes

# Answer
Python 3, 695 bytes

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

```

An interpreter built using `tatsu`, a PEG parser library. The first argument to `tatsu.parser()` is the PEG grammar.

`class D` (for Die) subclasses the built in `int` type. It's value is the result of a roll. The attribute `.s` is the number of sides on the die.

`class S` has the semantic actions for the parser, and implements the interpreter.
> 2 votes

---
Tags: code-golf, random, parsing, integer
---