Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Array.prototype.shuffle = function() {
- var c = this.length, temp, i;
- while (c > 0) {
- i = Math.floor(Math.random() * c);
- c--;
- temp = this[c];
- this[c] = this[i];
- this[i] = temp;
- }
- return this;
- };
- function Deck(cards) {
- if (cards == null) {
- this.cards = Deck.CARDS.slice(0).shuffle();
- } else {
- this.cards = cards;
- }
- }
- Deck.CARDS = (function() {
- var list = [];
- for (var i = 0; i < 81; i++) {
- list.push([
- ~~(i / 27) % 3,
- ~~(i / 9) % 3,
- ~~(i / 3) % 3,
- ~~(i / 1) % 3
- ]);
- }
- return list;
- }());
- Deck.isSet = function(a, b, c) {
- for (var i = 0; i < 4; i++) {
- if (!(a[i] === b[i] && b[i] === c[i]) &&
- !(a[i] !== b[i] && a[i] !== c[i] && b[i] !== c[i])) {
- return false;
- }
- }
- return true;
- };
- Deck.prototype.deal = function(n, dest) {
- dest = dest || new Deck([]);
- for (var i = 0; i < n; i++) {
- dest.cards.push(this.cards[i]);
- }
- this.cards = this.cards.slice(n);
- return dest;
- };
- Deck.prototype.isEmpty = function() {
- return this.cards.length === 0;
- };
- Object.defineProperty(Deck.prototype, 'length', {
- get: function() {
- return this.cards.length;
- }
- });
- Deck.prototype.findSet = function() {
- var cards = this.cards, len = cards.length, result = false;
- for (var i = 0; i < len - 2; i++) {
- for (var j = i + 1; j < len - 1; j++) {
- for (var k = j + 1; k < len - 0; k++) {
- if (Deck.isSet(cards[i], cards[j], cards[k])) {
- var set = [cards[i], cards[j], cards[k]];
- this.cards = this.cards.filter(function(e, ii) {
- return ii !== i && ii !== j && ii !== k;
- });
- return set;
- }
- }
- }
- }
- return null;
- };
- function Histo() {
- this.data = {};
- }
- Histo.prototype.increment = function(point) {
- if (this.data[point] == null) this.data[point] = 0;
- this.data[point]++;
- };
- function monteCarlo(n) {
- var histo = new Histo();
- for (var i = 0; i < n; i++) {
- var deck = new Deck(), dealt = deck.deal(9);
- while (!deck.isEmpty()) {
- deck.deal(3, dealt);
- while (dealt.findSet() != null) {};
- histo.increment(dealt.length);
- }
- }
- return histo;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement