[Question]
  [
The gambler's fallacy is a cognitive bias where we mistakenly expect things that have occurred often to be less likely to occur in the future and things that have not occurred in a while to be more likely to happen soon. Your task is to implement a specific version of this.
## Challenge Explanation
Write a function that returns a random integer between 1 and 6, inclusive. The catch: the first time the function is run, the outcome should be uniform (within 1%), however, each subsequent call will be skewed in favor of values that have been rolled fewer times previously. The specific details are as follows:
* The die remembers counts of numbers generated so far.
* Each outcome is weighted with the following formula: \$count\_{max} - count\_{die} + 1\$
	+ For instance, if the roll counts so far are \$[1, 0, 3, 2, 1, 0]\$, the weights will be \$[3, 4, 1, 2, 3, 4]\$, that is to say that you will be 4 times more likely to roll a \$2\$ than a \$3\$.
	+ Note that the formula means that a roll outcome of \$[a, b, c, d, e, f]\$ is weighted the same as \$[a + n, b + n, c + n, d + n, e + n, f + n]\$
## Rules and Assumptions
* Standard I/O rules and banned loopholes apply
* Die rolls should not be deterministic. (i.e. use a PRNG seeded from a volatile source, as is typically available as a builtin.)
* Your random source must have a period of at least 65535 or be true randomness.
* Distributions must be within 1% for weights up to 255
	+ 16-bit RNGs are good enough to meet both the above requirements. Most built-in RNGs are sufficient.
* You may pass in the current distribution as long as that distribution is either mutated by the call or the post-roll distribution is returned alongside the die roll. Updating the distribution/counts *is a part of this challenge*.
* You may use weights instead of counts. When doing so, whenever a weight drops to 0, all weights should increase by 1 to achieve the same effect as storing counts.
	+ You may use these weights as repetitions of elements in an array.
Good luck. May the bytes be ever in your favor.
  
[Answer]
# [R](https://www.r-project.org/), 59 bytes
```
function(){T[o]<<-T[o<-sample(6,1,,max(T)-T+1)]+1
o}
T=!1:6
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T0OzOiQ6P9bGRhdI2egWJ@YW5KRqmOkY6ujkJlZohGjqhmgbasZqG3Ll13KF2CoaWpn9L0otyMlMTixJ1TA0MNBJ09DU/A8A "R – Try It Online")
Keeps the counts in `T`, which is then transformed to be used as the `weights` argument to `sample` (which then most likely normalizes them to sum to `1`).
The `[<<-` operator is used to assign a value to `T` in one of the parent environments (in this case, the only parent environment is `.GlobalEnv`).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~112~~ 99 bytes
```
from random import*
def f(C=[0]*6):c=choices(range(6),[1-a+max(C)for a in C])[0];C[c]+=1;print(c+1)
```
[Try it online!](https://tio.run/##DcsxDsMgDEDRvadgxKGVgiJlaMTEMRADcqBhACOHoT09ZfrL@@3XL6rbGImpCA71nMmlEfflccYkkrTGrX7Z4Y0GL8oYbzndJ8odnk6/girhKy0kYhFErsJ6mMNhHXpl9NE41y5RaRjjDw "Python 3 – Try It Online")
**Explanation**
```
# we only need the "choice" function
from random import*
      # C, the array that holds previous choices, is created once when the function is defined
      # and is persisted afterwards unless the function is called with a replacement (i.e. f(C=[0,1,2,3,4,5]) instead of f() )
      C=[0]*6
# named function
def f(.......):
                  # generate weights
                  [1-a+max(C)for a in C]
# take the first item generated using built-in method
c=choices(range(6),......................)[0]
    # increment the counter for this choice
    C[c]+=1
    # since the array is 0-indexed, increase the number by 1 for printing
    print(c+1)
```
Edit: Saved 13 bytes. Thanks, [attinat](https://codegolf.stackexchange.com/users/81203/attinat)!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 13 bytes
```
Z>αāDrÅΓΩ=Q+=
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/yu7cxiONLkWHW89NPrfSNlDb9v//aEMdAx1jHSMdIB0LAA "05AB1E – Try It Online")
Takes the list of counts as input. Outputs the roll and the new counts.
Explanation:
```
Z                 # maximum
 >                # plus 1
  α               # absolute difference (vectorizes)
                  # the stack now has the list of weights
ā                 # range(1, length(top of stack)), in this case [1..6]
 D                # duplicate
  r               # reverse the entire stack
   ÅΓ             # run-length decode, using the weights as the run lengths
     Ω            # pick a random element
                  # the stack is now: counts, [1..6], random roll
=                 # output the roll without popping
 Q                # test for equality, vectorizing
  +               # add to the counts
   =              # output the new counts
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 32 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
-4 bytes using replicate instead of interval index.
```
{1∘+@(⎕←(?∘≢⌷⊢)(1+⍵-⍨⌈/⍵)/⍳6)⊢⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rwUccMbQeNR31TH7VN0LAH8h51LnrUs/1R1yJNDUPtR71bdR/1rnjU06EPZGoCic1mmkA5IKf2fxpQy6PePqBeT/9HXc2H1hs/apsI5AUHOQPJEA/PYKCS3sWGBgZAHWaPercYcCH4BjqmQBEgG0UMaBdUGAA "APL (Dyalog Unicode) – Try It Online")
Defined as a function that takes the current distribution as an argument, prints the resulting die roll, and returns the updated distribution. First run on TIO is 100 invocations starting with `[0,0,0,0,0,0]`, second run is heavily biased towards 1 with `[0,100,100,100,100,100]`, and the last run is heavily biased towards 6 in the same manner.
[Answer]
# JavaScript (ES8), 111 bytes
```
_=>++C[C.map((v,i)=>s+=''.padEnd(Math.max(...C)-v+1,i),s=''),n=s[Math.random()*s.length|0]]&&++n;[,...C]=1e6+''
```
[Try it online!](https://tio.run/##PY4xb8QgDIX3/gpLlQ6oCYKlQ1OyRDd26ZqiCl3I3VU5iAKKTmr721MnQ8Vg3vf8bH/5xefTfJ1KFVMf1sGun7ZBbLtW3fzE@SKvwjYZLWNq8v0x9vzNlwuZd66UakW1oKEemalDyGhzt/uzj326cfGU1RjiuVx@tHOHA2KsO7kFnTXhGRlbhzTzXHwBC52W/89JmAmZmsorGK01/RAFfD8AzCGTN3BRk9jC3UYqMA5xQ6cUcxqDGtOZs/c0jvDIAGkSAoOqamBXFCH9Ufb1@WWH@yVEBaPZv@sf "JavaScript (Node.js) – Try It Online")
### How?
This is a rather naive and most probably suboptimal implementation that performs the simulation as described.
We keep track of the counts in \$C\$. At each roll, we build a string \$s\$ consisting of each die \$i\$ repeated \$max(C)-C\_i+1\$ times and pick a random entry in there with a uniform distribution.
[Answer]
# [Perl 6](http://perl6.org/), 31 bytes
```
{--.{$/=.pick}||++«.{1..6};$/}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WldXr1pF31avIDM5u7amRlv70Gq9akM9PbNaaxX9WpA6lZTM4hIFWwWnxHSPxOIMDZCkprVCcWKlQpoGWFJTR0HdWkFdB6o0Lb9IIc7IwPo/AA "Perl 6 – Try It Online")
Accepts the current weight distribution as a BagHash, starting with one where all weights are 1. The distribution is mutated in-place.
The BagHash `pick` method selects a key at random using the associated weights; the weight of that key is then decremented by one. If that weight is thereby made zero, `++«.{1..6}` increments the weights of all numbers 1-6.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 91 bytes
```
w=1~Table~6
F:=Module[{g},g=RandomChoice[w->Range@6];w[[g]]++;w=Array[Max@w-w[[#]]+1&,6];g]
```
[Try it online!](https://tio.run/##VY49C8IwEIb3/opSwaUpNEsHS6QidCuIuB0Zoj3SQD@gRk4p7V@Pqbp43HDv8z7Ddco22Clrbso5Eny5qGuLSxaUO1EN9aNFmPTMtDirvh66YzOYGwIle581FpnMCUBLGcc5icM4qhdU6llQ4vHGY75l3tHSnUbTW4hqg@E6hEY39h7J4FescOIs/NvZ95@H4GuVbPUiRpLxNJX@Dpx7Aw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
## Javascript (ES6+), 97 bytes
```
d=[1,2,3,4,5,6]
w=[...d]
r=x=>(i=~~(Math.random()*w.length),k=w[i],w.concat(d.filter(x=>x!=k)),k)
```
### Explanation
```
d=[1,2,3,4,5,6]                   // basic die
w=[...d]                          // weighted die
r=x=>(                            // x is meaningless, just saves 1 byte vs ()
  i=~~(Math.random()*w.length),   // pick a random face of w
  k=w[i],                         // get the value of that face
  w.concat(d.filter(x=>x!=k)),    // add the faces of the basic die that aren't the value
                                  // we just picked to the weighted die
  k                               // return the value we picked
)
```
Note this will eventually blow up if `w` exceeds a length of 232-1, which is the max array length in js, but you'll probably hit a memory limit before then, considering a 32-bit int array 232-1 long is 16GiB, and some (most?) browsers won't let you use more than 4GiB.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 49 bytes
```
{($!=roll (1..6 X=>1+max 0,|.{*})∖$_:),$_⊎$!}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WkNF0bYoPydHQcNQT89MIcLWzlA7N7FCwUCnRq9aq1bzUcc0lXgrTR2V@EddfSqKtf@tuYB6VVIUbBWSEtM1NK250vKLFOKMDBSquThBMkXWXJwaKkU6QDWaQEVpGkAaKFScCJLTUVCKKVECyVlz1f4HAA "Perl 6 – Try It Online")
Takes the previous rolls as a Bag (multiset). Returns the new roll and the new distribution.
### Explanation
```
{                                            }  # Anon block taking
                                                # distribution in $_
                     max 0,|.{*}  # Maximum count
                   1+             # plus one
           1..6 X=>  # Pair with numbers 1-6
          (                     )∖$_  # Baggy subtract previous counts
     roll                            :  # Pick random element from Bag
 ($!=                                 )  # Store in $! and return
                                       ,$_⊎$!  # Return dist with new roll
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~22~~ 20 bytes
```
Xt
hOs.e*]kh-eSQbQQ1
```
[Try it online!](https://tio.run/##K6gsyfj/P6KEK8O/WC9VKzY7Qzc1ODApMNDw//9oQx0DHWMdIx0gHQsA "Pyth – Try It Online")
Input is the previous frequencies as a list, outputs the next roll and the updated frequencies separated by a newline.
```
Xt¶hOs.e*]kh-eSQbQQ1   Implicit: Q=eval(input())
                       Newline replaced with ¶
      .e         Q     Map elements of Q, as b with index k, using:
             eSQ         Max element of Q (end of sorted Q)
            -   b        Subtract b from the above
           h             Increment
        *]k              Repeat k the above number of times
                       Result of the above is nested weighted list
                       e.g. [1,0,3,2,1,0] -> [[0, 0, 0], [1, 1, 1, 1], [2], [3, 3], [4, 4, 4], [5, 5, 5, 5]]
     s                 Flatten
    O                  Choose random element
   h                   Increment
  ¶                    Output with newline
 t                     Decrement
X                 Q1   In Q, add 1 to the element with the above index
                       Implicit print
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
’ạṀJx$X,Ṭ+¥¥
```
[Try it online!](https://tio.run/##ATEAzv9qZWxsef//4oCZ4bqh4bmASngkWCzhuawrwqXCpf8weDbDh@G5hOG5qsaKMTAwwqH/ "Jelly – Try It Online")
A monadic link which takes a single argument, the current count list, and returns a list of the number chosen and the updated count list.
# [Jelly](https://github.com/DennisMitchell/jelly), 18 bytes
```
0x6+ɼṀ_®‘Jx$XṬ+ɼṛƊ
```
[Try it online!](https://tio.run/##y0rNyan8/9@gwkz75J6HOxviD6171DDDq0Il4uHONWCh2ce6/h9a9HBni4qhgcGhhf8B "Jelly – Try It Online")
As an alternative, here’s a niladic link which returns the number chosen and keeps track of the count list in the register.
]