Show HN: A Set of Dice That Follows the Gambler's Fallacy
github.com
github.com
A fair 6-sided die would be an equal number of balls numbered 1-6 and a rule that you simply return the ball you drew. You can get a gambler's fallacy distribution by, say, adding one of every ball that you didn't draw. I read the code as a Pólya urn starting with 1 ball 1-N and doing that on each draw plus reducing the number of balls of the drawn number to 1.
Also related, in 2d space, is the idea of randomly covering the plane in points but getting a spread-out distribution, since uniformity will result in clusters. (If you're moving a small window in any direction and you haven't seen a point in a while, you're "due" to see another one, and vice versa if you just saw a point.) Mike Bostock did a very nice visualization of that here: https://bost.ocks.org/mike/algorithms/
Then months later by accident while looking at a completely different topic: "OMG there it is, the thing!"
[1] https://www.jstor.org/stable/2283724
[2] https://www.fda.gov/downloads/MedicalDevices/DeviceRegulatio...
Relatedly, there's a Bayesian interpretation to overweighting successful past draws. A model where you return one extra ball of the same color to the urn gets you a Dirichlet-multinomial distribution, which is a die-roll distribution where the weights to each face are not known for sure, but are given a probability distribution and revised with observed evidence. In other words: here's an n-sided die, I don't know its weightings, but as I observe outcomes I'll update my beliefs that the sides that come up are more favorably weighted. The number of balls in the urn you start with correspond to your priors; only 1 ball of each color means a very weak belief that it's a fair die, 1000 balls of each color means a strong belief, unequal numbers mean that you start off believing it's weighted.
Thank you for that link - a great read!
Whether this was because they had a botched 'smart' randomizer or because they in fact used true random to shuffle, I may never know.
Supposedly Jobs specifically “fixed” this behavior and it’s why there used to be (still is?) a slider that allowed you to customize that behavior.
So next time some one tells you their computer is broken, don't reply saying it appears to be in one piece.
I think this whole shuffling meme started with Spotify's engineers misunderstanding what they were asked to do, then claiming their customers don't know what they want when they obviously delivered the wrong feature.
The article is about weighting randomness based on past distribution. In a music playlist that may be enough. Some user might also want a term in the equation that weights songs they've rated highly to be favored over lower-rated or unrated songs.
This is orthognal to the choice of distributon. Shuffle and Weighted Sampling are different choices of distribution.
If someone with no specialized knowledge about math and probability requests their songs in a "random" order, I don't think one should assume they are insisting on an order sampled from a uniform distribution.
I'd like to read about this, do you still have the intended link?
About your linked post: You don't test the randomness of the shuffling, you only test if a shuffled list contain one and only of each original item.
Amazon Music does this and it annoys me. Just because I added something a while ago doesn't mean I want to hear it less.
'Random' was better, especially when there were players that would play "random album" which was great.
You're right that shuffle has been the standard for a long time, the last actual "random" for singles I remember was napster back when it was popular.
When I was writing my in car entertainment system (it's not as good as it sounds!) the first metric that was shuffled was the artist, followed by weightings for albums.
Long ago I asked this related question on stackoverflow: https://stackoverflow.com/questions/5467174/how-to-implement... - it surprises me still that nobody has identified a classic algorithm for solving exactly this problem.
A simpler system is picking a random song, but excluding the last 20 songs played.
Another method is to pick a random key K and sort the entries of the playlist based on HMAC(SONG, K) (where SONG is the name or other identifier of the song). This has a number of interesting properties. For starters the playlist will be randomized (that's good). It will also keep it's overall order if a new song is added. The new song will get inserted based upon its HMAC. You can switch things up a bit by having K be a based on the current date. That way new songs will maintain their order and jumping to a track on a given day will continue the chain as before, but day to day you won't always hear the same tracks back to back.
The prime method will sample songs p apart from each other, and it's easy to find examples of N and p where p is even, for example N=5 p=2. More generally, this method works for any n that is co-prime with N, so N=5 n=4 works as well.
There are lots of shufflings where subsequent songs are not separated by a constant amount, so your main point is true. There are many combinations of songs that you would never hear no matter which prime you picked.
To quantify just how many takes a little bit of work.
There are N! total shufflings possible. We know that there are N-1 or less numbers that are co-prime with N (you get N-1 when N is prime, less otherwise). For each number that is co-prime, we have N possible shufflings, each starting from a different point. This gives at most N(N-1) shufflings from the prime method (really the co-prime method).
As a percentage of total shufflings, we know the upper bound from the co-prime method is N(N-1) / N! == 1/(N-2)!. This very quickly goes to 0. For the first few N,
N % of shuffles
2 100.00000%
3 100.00000%
4 50.00000%
5 16.66667%
6 4.16667%
7 0.83333%
8 0.13889%
9 0.01984%
10 0.00248%
11 0.00028%
12 0.00003%
13 0.00000%
So for any reasonable number of songs, we know that _most_ shufflings will not be found by the prime shuffling method.- don't play too many songs from the same artist in a row (and too many is probably 2) - don't play too many slow/fast/sad/angry/... songs in a row - ... instruments - ... genres - ... "feel" - ...
Deep AI is definitely needed to create playlists that "feel random". :)
when I finally noticed this and realized that could only mean it's not actually random, I researched it, and found out that once you hit shuffle/random on Winamp, it shuffled the songs once and kept the sequence forever.
and then as it turned out, Winamp actually had a setting to select a truly random song each time. all I needed to cure my madness was a checkbox!
I manually shuffle some playlists now. One nice thing about the desktop client is the clipboard integration. You can press cmd+a to highlight all the songs, cmd+c to copy, and then paste all the song URLs into a text editor. Then I used "permute lines" in Sublime Text to shuffle them, then cmd+c and cmd+v to paste the songs back into Spotify.
One, if I remember somewhat correctly, was that if the player was stopped/shutdown, it forgot the shuffle seed. This would essentially lead to a reshuffle, which would cause duplicate songs for songs played before the unintended reseeding.
Favorites: Normal <----------> Very Frequently
Artist: Liked only <-----------> Wide variety
Prefer: Old <----Balanced----> New
Popularity: Hits only <--------> Fringe
It was great to be able to customize stations. I don't remember what service it was, but I think it did get purchased and folded into something else.This was a great way of tweaking the "randomization", and really gets into understanding what people want to hear. In my case, I had different stations/playlists customized in different ways.
I know this is about being "technically correct" but I'd argue that even if you're pedantic and know the behavior of true randomness, the complaints are justified.
First, "pick a song from a uniform distribution" is an implementation detail, not the use case. The use case is "pick songs in a pleasant, novel order". If the implementer chose to do this using uniform randomness, that's their descision. If that implementation does not fulfill the use case, it's a bug and also their responsibility.
Second, the function is frequently called "shuffle" - so it even gives some hints about the implementation expected. No shuffling algorithm should ever result in duplicates. (except at the beginning and end of playlists)
Players would love that! Make my hero feel more heroic! The inevitable comeback!
But then I thought about the inverse case -- you are doing really well, and now you are due for a failure. Or series of failures. That would feel awful.
We have a lot of emotions around dice rolling. I wonder if players really want from their dice. Would players prefer dice that are secretly unevenly weighted towards good rolls? Would they still want those dice if they knew they were weighted?
Anyway, nice work!
I think there are interesting stories to tell in an RPG where you know the "weight" of your rolls, approximately how many "success" cards you have left, some choice in what you play from your hand.
«But then I thought about the inverse case -- you are doing really well, and now you are due for a failure. Or series of failures. That would feel awful.»
It depends on how personal you take it in how awful it feels. If the goal is to create an interesting story, a grand sequence of failures can be a very interesting story. Look at Fiasco, for instance, where some of the fun can be very explicitly "how do I make my character more miserable?" In those cases where you know you are about to hit a lot of failures in die rolls/card draws you can lean in to it. Try to explain why your character is having such awful luck, for instance. Maybe try to set up an elaborate Rube Goldberg design of failures that eventually cascade into the weirdest, grandest success, like a "drunken master" kung fu ballet.
It doesn't have the "you are doing really well, and now you are due for a failure" since "not a critical" isn't really that negative of an outcome.
For something like D&D, the same kind of "better-than-random" distribution just comes from adding dice. 4d6 is much more consistent than 1d21+3.
There are even websites like https://pitytracker.com/ that keep track of where you are in your chances.
Randomness is what makes a game more realistic but true randomness will not make it more likable. True randomness dictates that in half of your games, your players will have a harder time achieving anything.
It is not uniformity of results that the players are looking for, it is uniformity of successes weighted by the importance of the rolls. Failing a perception check in an empty room is less important than failing a dodge roll in the final fight on your last health point.
Many games suggest that the gamemaster cheats on some crucial rolls. More games propose an alternate system that biases rolls based on points systems. Some others even replace totally the dices with a points system.
I really prefer those. A very simple biased rolls system I often use (Dk2) is that GM can emphasize the action of dangerous NPCs by adding special D6 dices to a D20 roll (they are special as they only give +3 or +6 on 3 and 6 and +0 on other results). Once used, these dices are added to a pool that the players can use for their actions.
Anyway, my favorite system is Amber Diceless RPG. It trades randomness for secrets. Every player is a bit of a backstabing asshole who does not show all their skills on any action. If someone has 30 in strength, they may just announce 10 if they think it is enough for the action.
The winner in a fight is the one with the bigger score. Add bonus if they use some kind of trick or ambushes (recommended). It is surprisingly interesting for such a simple system.
In general, things are heavily weighted towards actual player skill and also character skills accrued over time for the important interactive elements.
For things like loot drops, it's strictly random from a chart per enemy type, but they monitor the overall economy and use that to set the weights for the various items. If one group of people has figured out some trick to farming an extremely valuable item, they will nerf it to keep the economy where they want it. For a number of years, the company actually kept a professional economist on full-time to keep track of these things. I think that got eliminated when CCP was having a rough financial time several years ago. And I think that game has gotten a bit worse as a result.
But in terms of stuff that counts RNGs are a fairly small part of the action, and in some cases not at all, so you can pick your poison: lower overall damage to a target but more consistent, allowing for one kind of play style. Or you can have more variable damage with higher potential if you're willing to take risks. And there are a couple of flavors along the spectrum.
It's a pretty interesting game design. And, of course, tons of people complain about it. Loot drops really are pretty damn random (with between 30-40 thousand people online at any given time, there's a lot of entropy to seed the PRNG). And you get the clusters you would expect from random data. But everyone really hates random outcomes. People want uniform outcomes. It's baked into our psychology.
But in terms of things that determine who lives and who dies in a fight. The random element is really downplayed, and it boils down to player skill more than anything.
There's a whole thing where people who have been playing for a long time will start brand new accounts with low skill levels and shitty equipment and still be able to blow people out of the water because they have a superior understanding of the game mechanics. In fact, there are entire "corporations" who really do nothing but this. Fine people who have been around for long enough to make some money and buy some expensive things and then lure them into fights and slaughter their bling-bling.
It's an interesting approach to game balance, and one I quite admire. It does keep me coming back, and paying that sweet, sweet monthly sub.
EVE is also one of the games that really capitalizes on the technology component. As much as I love Skyrim, for example, I don't think there's anything going on with the actual game interaction mechanics that couldn't be easily replicated on a table with some dice. I'm also willing to eat my words if I'm completely wrong about that.
EVE Online has the luxury of hammering out fairly complicated formulas based on the current state of things, and it does so very well. It does it for every ship in space (again, typically 30-40k), once each server tick (usually a tick is 1 second, but for really huge fights, they dilate time and slow the ticks down).
So they can make things like damage calculated for each gun or missile or drone on each ship based on every relevant ship's current speed and direction relative to every other ship, etc.
It's an impressive use of technology for an RPG, and I find it especially cool that you are your own gamemaster. The only story is the one you make for yourself.
But now I sound like a fucking fanboi, so I'll shut up.
I've never heard of Amber Diceless before. I'm curious and will check it out. Thanks for mentioning.
> These accusations would come up even though they (all being computer science majors) know it's possible (although unlikely) for these events to happen. They just don't trust the black box.
I am reminded of the approach that GamesByEmail.com used to address this criticism: http://www.gamesbyemail.com/News/DiceOMatic
Hah! That might be the best donation "gift" I've ever heard of!
Given a fair coin that outputs Heads (H) or Tails (T), which of the following sequences is more or less probable
HHTHTT or HHHHHH
Answer: Both are equally probable strings to be generated by the fair coin and each should occur once in every 64 sequences (~1.56%)
HHHHHH THHHHH
Answer: THHHHH. Only 1/(2^6) of the time it will be HHHHHH. The only way to get HHHHHH will be if the first 6 flips are heads. If you don't flip a head you must have got a tail which means THHHHH will always appear before HHHHHH.
We tend to use the fair coin or the fair die as a common way of talking about things, but I've found that this is problematic for a lot of people.
First off is the use of the word fair. People not from a background in statistics don't think of that word the way we do. They think of it as an attribute of the object itself. The the coin or die is 'fair' in the ethical sense of the word.
Second is the experiential understanding: 'This coin is fair and therefore should flip heads and tails with equal frequency. It's the same damn coin, and I flipped it a thousand times! Why are these crazy stats people telling me it comes up heads and tail equally often? It doesn't, dammit!'
What I've had some success with helping people understand independent trials is to get them to envision flipping 6 different coins at the same time. Then you can sort of walk them back into understanding that flipping 6 different coins once is no different from flipping the same one 6 times. The events are totally unrelated, and a past event is not a predictor of the future.
Plus, you can actually map out the math for them on the spot. .5 * .5 * .5, etc.
That's just my experience trying to explain things though. Would love some criticisms if there are better ways to go about this.
You can actually play it right here and go direct to the Boss Fight if you wanted to: http://briancable.com/clock-legends/
With my method, it was possible for the same move to be picked 2 or 3 times in a row, but it mostly went back and forth, so the player was definitely going to encounter both moves, but they couldn't know for absolute certain which move the next one would be (and they both needed you to kind of quickly get into different positions before getting hit).
The type of pattern you'd usually get with mine was more like A,B,B,A,A,B,A,B,A,A,A,B,B,A.
Tetris is the go-to example. Tetris has seven tetronimos, and in most modern implementations you're guaranteed to see them in sets of seven in random order.
http://tetris.wikia.com/wiki/Random_Generator
This is pretty essential to make competitive play err on the side of skill rather than randomness: pro-players can anticipate and plan for this. For fun, here's a recent Tetris head-to-head speed-run from Awesome Games Done Quick, with pretty good narration about the tactics involved:
The biggest challenge will probably be the power supply. I'm sure that a processor, accelerometer, and the Taptic Engine (the thing that provides vibration and haptic feedback in Apple devices) are all small enough to fit in a typical die. Of course, something like this could easily be built into a larger novelty die.
Bonus points should be awarded if the die is perfectly balanced when it's not actively adjusting itself in mid-air.
[0] http://appleinsider.com/articles/14/12/02/apple-patents-acti...
This would probably cost a lot of money to fit in a normal sized die.
I wonder if you tuned the e-m coil for a particular frequency if you could make the device passive and weight it using an external frequency change?
Or use computer vision, a passive dice with a metal insert and a magnetic table; switch on the magnet when the dice hits the table right (this version would be highly obvious but perhaps could be made less so).
Some purists insist that they role dice, so we just let 'em and the resulting game feels quite like you're using gambler's dice.
I'm not sure that factors into the game (have played but its been a while). Cards seem like a more controlled way to distribute the results with some randomness.
only one way to get a 12 (6+6) but 7 much more likely.. (6+1, 5+2, 4+3, 3+4, 2+5, 1+6)
as someone who played a bit of online backgammon back in the day, We always suspected the random dice rolls behaved differently in the game than playing in real life...
Likewise, if you use the Traders and Barbarians dice-deck, the same thing applies - there are 5X as many 6s and 8s in the deck as there are 2s and 12s.
They basically made one card for each possiblity of pair of dices, so there is a 7 card for 6+1, another for 5+2, and so on...
Playing with it is MUCH better than with dice... when I played with the dice that came with my copy with catan, the dice were clearly defective (rolls weren't just random-looking, they were WILDLY wrong, it rolled 10s 2 times the amount of 7s...), and the game was super boring, it would end with everyone having the same materials and not having others, so not even trade would fix the game, we had stuff like 10 turns in a row where noone had one particular item while the 'bank' ran out of the other items because everyone had lots of them.
So the game pace slowed to a crawl... Also, the funky dice never rolling bricks meant people would quickly rack up random resources, sometimes like 3 of each, so they ended with 9 cards, and would then lose to robber rolls (7).
Then of course in one game where this happened there was an asshole cousin that thought it would be hilarious to hog resources and make the game worse, he would spend his whole turn making 'negotiations' with everyone, and them cancelling them, wasting like 5 minutes every time it was his turn, and sometimes if 7 was taking long enough have 20 cards on his hand...
We don't play with that cousin anymore either.
But yeah, not having a way to build roads make the game suuuuuper slow.
http://www.catan.com/files/styles/lightboxy/public/gallery/d...
Notice that the 12 has one dot, the 9 (6+3, 5+4, 4+5, 3+6) has 4 dots, and the 3 (2+1, 1+2) has 2 dots. The gray robber piece is sitting on a red number token, which is either a 6 or an 8 and has 5 dots because it is more likely to be rolled.
In the game, you develop your pieces with the hopes of getting resources based on the adjacent numbers being rolled. It definitely creates a lot of stress in some people when "eights are being rolled all the time this game but never sixes!" or "your stupid 10 keeps getting rolled when it shouldn't, that's not fair!"
I think I'll give it a try tonight with some numbered cards. I just threw some together in Excel: 1-6 in B1-G1, 1-6 in A2-A7, and the formula
=B$1&" + "&$A2&" = "&(B$1+$A2)
spread across the grid and printed that out, but on doing a little, ah, market research, it looks like you can buy official Catan decks like this at https://boardgamegeek.com/boardgameexpansion/20038/catan-eve.... Or download this: https://boardgamegeek.com/filepage/40420/deck-dice-separate-... (note: not the above). Or someone else pointed out that you can simulate it with two matching decks of cards with: one 2
two 3S
three 4S
four 5S
five 6S
six 7S
five 8S
four 9S
three 10S
two Jacks
one Queen
Other market research says that people start counting cards to see when their numbers are going to come up again....perhaps some compromise, with perhaps two or three such decks? Real dice are an approximation of an infinite number of shuffled decks of dice, and I imagine you'd go through on the order of 100 'cards' in a given game, so with more than 3 or 4 decks you could end up with certain cards/numbers that never appeared, which seems to happen frequently and cause ire in games with real dice...interesting. Science is required! Sorry for rambling/thinking out loud.An interesting bit of trivia: In roman times it seems they played with 3 dice instead of 2: http://www.bkgm.com/variants/Tabula.html
http://www.gdcvault.com/play/1012186/The-Psychology-of-Game-...
More often than not, true RNG in game design takes a back seat to fun.
They could do with learning a little from other games and making it a little less random.
Ultimately you can see it as a bug in human reasoning but we're the ones playing the game.
If every house had one pistol and one rifle it would get pretty dull. Raiding 3 houses and only getting a crossbow, bandages, and SMG magazines is frustrating but it's exciting. Just last night I got to #3 or #4 with a crossbow and a pistol.
Basically, the higher your chance to hit with an attack was, the the sooner it would break a streak of misses and force a hit. This is definitely not random, but seems to be more satisfying to the player. Plus it no doubt cuts down on the number of complaints on the forums about "unfair" RNG.
If that is a bug or a feature is left as an exercise for the reader.
Update: Heads stayed ahead by a few for quite a while, until they tied at 45 each. It's a race to 50, my money is on tails - it's due for a comeback!
Update: Tails takes the lead, 46-47!
Update: 47-49 Tails is in position to strike!
Update: Tails wins! 48-50! (two more clicks to make a sum of 100 results in a perfect 50/50 split)
It's surprisingly fun to anthropomorphize heads vs tails, and commentating on their battle
But it's very clear from the comments that having dice that aren't independent between rolls is incredibly in demand :o, and having the right words to google can be tricky.
(I feel like there's an important lesson there)
DoTA2 uses a simple distribution based on the number of "rolls" since the last successful one - P(N) = P0 * N, where P0 is the base probability and N is the number of rolls since the last successful one[1].
It keeps both "hot" and "cold" streaks from being too much of an issue, although that doesn't stop players from cursing the RNG gods when they lose.
> These accusations would come up even though they (all being computer science majors) know it's possible (although unlikely) for these events to happen. They just don't trust the black box.
This reminds me of a talk [1] given at Game Developer's Conference (GDC) about the game Civilization, in which the Sid Meyer -- creator of said game -- spent a bit of the time talking about the difference between fairness and perceived fairness. The talk is only an hour long and worth watching.
RNJesus is merciful.
Einstein believed the universe was deterministic. Just because it appears to us that there is no correlation between independent events ( the roll of a dice ), does not mean that there isn't some underlaying variable that we are unable to measure or perceive which is affecting the outcome of the roles.
Theoretically all physical processes are predictable, but in practice there is a limit.
If you count a radioactive decay event as a physical process, then this is not so.
I would go the other route. Nothing can be predicted, except statistically.
Which I wasn't. You clearly are. Yes, quantum stuff exists. At the scales the OP was talking about though they are mostly insignificant therefore I hand-waved them because they were not relevant to the discussion.
But that’s also because that’s where the really interesting work is.
It’s quite a different scope of conversation
But for the context of the physical processes the OP was talking about those effects are not significant and so I excluded them.
So you defined away quantum effects as 'not physical', which most people would not agree with. How do feel about the theoretical limits on measurement accuracy that also negate your claim?
I want to be clear that my point is not merely a technical one. I'm not just saying "it's technically impossible to have complete knowledge," I'm saying that it is physically, mathematically impossible. The laws of physics do not allow it. One might argue "maybe it's not possible, but if we did know the complete quantum state of the universe, the universe would be deterministic and we could predict everything," but this is equivalent to saying "if the laws of physics were different, then the universe would be deterministic."
Edit: To the distinction you make between "physical" and "quantum" processes: There is no distinction. Quantum effects do diminish in magnitude with increasing size, but they never truly go away. You can predict the motion of macroscopic objects with what may seem to be an arbitrarily high degree of certainty, but in truth you can never have 100% complete knowledge of even macroscopic properties. I still disagree with your claim that the universe is deterministic in any way, even if you conveniently exclude systems for which quantum effects are substantial.
To the GP: You still aren't "due" for a win, that's silly.
Contrast this to a topic for which Einstein is better known, relativity. The mathematical framework describing the effects of special relativity had already been partially discovered by Lorentz, but we credit Einstein for its discovery. Why? Because he postulated two simple rules from which these laws can be derived: 1) The speed of light is the same in all inertial reference frames, and 2) the laws of physics should be the same in all inertial reference frames. How about general relativity? A similar idea, that a person inside of an elevator should not be able to tell the difference between sitting stationary on Earth and accelerating through space at a rate of 9.8 m/s^2.
Einstein had opinions on the physical basis for the laws of quantum mechanics. But they were not necessarily the most popular opinion at the time, and definitely not today. As tylerhou posted in another comment, tests of Bell's theorem more or less disprove the existence of local hidden variables, meaning local quantities that behave deterministically but not measurable. It is still possible that there are nonlocal hidden variables, but this is not a popular opinion these days for a variety of reasons.
I would also like to point out that the various "interpretations" of quantum mechanics (e.g. the Copenhagen interpretation, pilot wave theory, etc) frequently fail to address what the nature of physical reality, i.e. what is the starting point, what is the axiom, what is "real". Are wave functions real? Do they actually exist, or are they merely convenient mathematical tools that can be used to describe reality? Are pilot waves real? Are density matrices real? Are Greens functions real? Are quasiparticles real? (n.b., most of these things are described as complex-valued quantities ;) )
No, they ALWAYS fail to address it, That's why they are called "interpretations", not "models".
> Do they actually exist
This question is completely outside of the realm of science.
I've designed a few loot tables and the Gambler's Fallacy is a criticism I often have to deal with when people don't understand why a given item hasn't dropped despite them having killed a mob enough times to statistically warrant it.
http://monsterhunter.wikia.com/wiki/Monster_Hunter_Wiki:Mons...
the studio has denied the existence of any such mechanism.
I had a friend think of a playing card and any number (1-52). She picked the 6 of spades and the number 15 which is exactly the position where the card was located. It was only the third time I had done this trick with anybody.
Obviously, card and number picking is not uniformly random, especially when you influence their choice (e.g. "pick a large number"). But the odds of someone guessing the exact combination should still be extremely low.
A lot of what you see from David Blaine on TV is exactly this. He always has a backup plan but more often than not he doesn't need it.
It's similar to me to condensing 30 characters to 5 via an algorithm. You can go one direction but not the other and if your model was centered around the resulting 5 it doesn't really reflect what's actually happening which may skew the probabilities quite a bit. e.g. if the algorithm was "if first letter is not q, then first letter in output is q". If you were saying each has an equal percentage of occurring it'd be flat out wrong.
* I am not a statistician and have no idea what I'm talking about
Outside of games, for which this was explicitly created, these kinds of things are learning tools to understand distributions and dependent vs. independent events, and it also makes a separate point about assumptions.
In reality, if we were wanting to predict the outcome from a real dice-throwing event, we would either sample the results from actual people throwing dice, or we would simulate the results based on parameter inputs for exactly the types of things you are talking about.
Of course, no one really cares that much about dice, other than people who play board games with dice. :) So substitute any other stochastic method for generating an outcome that does matter, and the statistical approach will generally be the same: either sample or simulate.
Obviously there are exceptions, but that's really the basic idea.
My idea is based on time - if we assign each song to a 1/1000th of a second, we play the song that matches the 1000th of a second when the next song is called.
In this case, I'm referring to the 1/1000th of a second of current time of day. Depending on the song´s position in the second that I change tracks, is what song gets played.
A bit more randomness (if this is needed) could come if we use Pi - for example, we can run through a series in Pi which adds to the ID of the song. Differing track lengths then do the job of ensuring that we always wind up on a different song in the loop.
The above seems to my layman's eye to be a simpler solution, at least.
Having unusually bad luck (e.g. opening 100 packs and not getting a single legendary card, when the average would be every ~20 packs) feels bad and probably loses Blizzard a customer, so the solution is to cut off the downside tail of the distribution.
[1] https://www.reddit.com/r/hearthstone/comments/3z7jyh/pity_ti...
[1] https://en.wikipedia.org/wiki/Linear-feedback_shift_register
roll() {
const sum = this.state.reduce((p, c) => p + c, 0)
const r = Math.random() * sum
let runningSum = 0
let result = -1
for (let i = 0; i < this.state.length; i++) {
const mark = this.state[i]
runningSum += mark
if(r < runningSum && result === -1) {
result = i
this.state[i] = 1
} else {
this.state[i]++
}
}
// Add 1, so the die roll is between 1 -> size of die
return (result + 1)
}At the outset, `this.state` is initialized as an array of `1`s — [1, 1, 1, ... , 1] — the number of `1`s is based on the `size` parameter passed to the `Die` constructor. So for a 4-sided die, `this.state` would initially be `[1, 1, 1, 1]`.
`sum` is the accumulated sum of `this.state`, but it helped me to think of the `sum` variable as a number line. Continuing with the 4-sided die case, we'd have a number line of length 4 at initialization (sum of `[1, 1, 1, 1]`).
In the context of a number line, though, `this.state` can be thought of as giving the geometric positions of each possible result. `this.state[i]` simply gives the length of the valid region for a certain result. At initialization, each result of `1` to `4` of our four-sided die would have a length of 1 on the number line (again, `[1, 1, 1, 1]`).
In concrete terms, the region [0, 1) on the number line would yield a roll of `1`, the region [1, 2) would yield a roll of `2`, ... , the region [3, 4) would yield a roll of `4`.
With that in mind, we can think of `r` as choosing a random point on the number line between 0 and the end of the number line. At initialization, it simply chooses a point on [0, 4), since 4 is the length of our number line.
`runningSum` is our location on the number line. The code chooses a result here using the boolean expression `(r < runningSum)`, but it helped me to think of it in flipped terms: checking if `runningSum` is greater than or equal to `r`.
In essence, we're traversing the number line starting from 0.
Back to our four-sided die example: let's say `r`, the random point on the number line we got, was 2.5. At initialization we'd start by checking the region of the number line where `1` would be our result. Since `this.state[0]` (the length of the valid region for the result `1`) is 1, we can say that if we choose a point randomly on the number line [0, 4) and it is on the interval [0, 1), our roll is a 1.
However, 2.5 is not on [0, 1), so we add the length of the region where `1` is valid to `runningSum` (our location on the number line) so we can move on to the next region - the interval where `2` is our result. The length of this interval is stored in `this.state[1]`, and is also equal to 1 (`this.state` = `[1, 1, 1, 1]`). In terms of our number line, the valid interval is thus [1, 2). At this point, our location of the number line, `runningSum`, is 2: still less than 2.5.
Next, we'd get to the region for the result `3`, `this.state[2]`, and we'd be at [2, 3) on our number line. At this point, our `runningSum` (location on the number line) is 3, which is greater than `r` (the randomly chosen point on the number line), 2.5, and we have our result. (sidenote: the variable `result` being equal to `-1` is a sentinel value and prevents `4` also being considered a valid roll by virtue of it being greater than 2.5 as well. After this iteration, `result` is set to `2` - changed to `3` in the return statement).
The "magic" of the die comes in when traversing the number line over the non-valid regions, however. While we're traversing the number line, we're also resizing the valid regions for each result and extending the line for the next roll. If we go back to the example in the previous paragraphs with the 4-sided die, we saw that since `r` (our randomly chosen point on the number line), 2.5, was not on [0, 1), the result of our roll was not `1`. To increase the likelihood of `1` in the next roll, we increase the length of the number line and the region where `1` is our roll: `this.state` becomes `[2, 1, 1, 1]`, the valid region for a roll of `1` becomes [0, 2), and the size of the number line grows to 5 (however, this expansion of the number line does not apply to the current roll).
At the culmination of our first example above, `this.state` would be `[2, 2, 1, 2]` — we'd increase the size of the valid region for each result except for `3`, our result from the previous roll. For the next roll, we'd choose a random point on the number line between 0 and (2 + 2 + 2 + 1 = 7). In terms of probabilities, another `3` would be half as likely as a `1`, `2`, or `4`, independently.
There were some housekeeping rules to work around the organicness of human life - if someone went on holiday they kept their score, for example - but overall it seemed to work.
> const RiggedDie = require('gamblers-dice')
> const die = new RiggedDie(20) // for a d20
> console.log(die.roll()) // 1 -> 20
> console.log(die.roll()) // keep using the same instance
Do I put it in a file? Do I copy paste it into a REPL? If so what provides that REPL?
I am always surprised when sample code providers assume I know their languages ecosystem.
UPDATE: Apparently I can use "node" as a REPL for this.