# Question
Title: Simple Pazaak (Star Wars Card Game from Knights of the Old Republic)
Pazaak is a card game from the Star Wars universe. It is similar to BlackJack, with two players pitted against each other trying to reach a total of twenty without going over. Each player has a "side deck" of four cards of their own that they can use to modify their score.

# Leaderboard

As of 6/17/2015 @ 16:40 EDT

Edit: Neptor has been disqualified for cheating. Scores will be fixed as soon as possible...

1. N.E.P.T.R: ~424,000
2. The Cincinnati Kid: ~422,000
3. Nestor: ~408,000
4. Austin Powers: ~405,000
5. Bastila: ~248,000
6. Dumb Cautious Player: ~107,000
7. Dumb Bold Player: ~87,000

## Mock Pazaak Cup Playoffs

Will be updated as soon as possible.

### Round One - Nestor vs Bastila & Austin Powers vs The Cincinnati Kid

### Round Two - Nestor vs Austin Powers & The Cincinnati Kid vs Bastila

# Mechanics

Gameplay is done in turns. Player one is dealt a card from the main (house) deck. The house deck holds forty cards: four copies of one through 10. After being dealt a card, they can choose to end their turn and receive a new card next turn, stand at their current value, or play a card from their side deck and stand at the new value. After player one decides what they want to do, player two repeats the process.

Once both players have gone, the hands are evaluated. If a player bombed out (went over twenty), the other player will win, provided that they did not also bomb out. If a player chose to stand, and the other player has a higher hand value, the other player will win. If both players chose to stand, the player with the higher hand value will win. In the event of a tie, neither player gets the win.

Provided a winning condition is not met, play will repeat. If a player chose to end their turn, they will receive a new card and can make a new choice. If they chose to stand, or if they played a card from their side deck, they will not be dealt a new card and cannot choose a new action.

Play continues like this until one player wins the game. Games are played in best-three-out-of-five sets.

# Why "Simple" Pazaak?

In the Star Wars universe, Pazaak involved gambling. While inclusion of such a system would add more of a dynamic to the game, it is a bit complicated for a first-time KoTH competition.

"Real" Pazaak side decks were also provided by the players themselves, and could include many different card options such as negative cards, positive-or-negative cards, flip cards, double cards, and tiebreaker cards. These would also make the game more interesting, but would require a gambling interface in place, and would require far more out of the competitors. In this Simple Pazaak game, each player gets the same side deck: two copies of one through five, from which four are randomly selected.

Depending on the success of this game, I may put forth the effort to develop an advanced version wherein which gambling and custom side decks are possible.

# The Players

The players of this game will be bots designed by you. Each bot needs to extend the Player class, import the Mechanics package, and reside in the players package like so:

```
package Players;

import java.util.Collection;

import Mechanics.*;

public class DemoPlayer extends Player {

    public DemoPlayer() {
        name = "Your Name Here";
    }

    public void getResponse(int wins[], boolean isPlayerOne,
            Collection<Card> yourHand, Collection<Card> opponentHand,
            Collection<Card> yourSideDeck, int opponentSideDeckCount,
            Action opponentAction, boolean opponentDidPlay) {
        action = null;
        cardToPlay = null;
    }
}

```

Each round, the controller will call the getResponse method for your bot, unless your bot previously indicated that it wanted to stand. The getResponse method can set two properties: an action and a card to play. Action can be one of the following:

* END: Ends the turn and draws a new card next turn.
* STAND: Stays at the current hand value. Will not draw a card.
* PLAY: Plays a card from the side deck and then stands.

The card to play is obviously only of importance if you set the action to PLAY. It takes a Card object. If the Card object you pass to it does not exist in your side deck, your bot will STAND instead.

The parameters your bot receives each turn are:

* An array containing the wins of each player. wins\[0\] is Player 1's, wins is Player 2's (int\[\])
* Whether or not your bot is player one (boolean)
* A collection of the cards that you have been dealt thus far (Collection)
* A collection of the cards your opponent has been dealt thus far (Collection)
* A collection of the cards in your side deck (Collection)
* The number of cards remaining in your opponent's side deck (int)
* The action your opponent last made (Action) \[Note: This will either be END or STAND, never PLAY\]
* Whether or not your opponent played a card (boolean)

# Bot Rules

Your bots may only use the information that is given to them via the getResponse method. They should not attempt to interact with any other class. They may write to a single file to store data between rounds. They may have any custom methods, properties, etc. as desired. They should run in a reasonable amount of time (if the program run is not practically instantaneous, I will notice something is wrong).

If you find some kind of exploit in the code, you will be rewarded for "turning yourself in." If I notice the exploit first, I will fix it, and you will get no reward.

# Demos

The controller is not needed to write a bot, as everything is already explained in this post. However, if you wish to test, it can be found here: https://github.com/PhantomJedi759/simplepazaak Two basic bots are included. Neither should hold up well against an "intelligent" opponent, as they only choose between END and STAND. Here is a sample run of what they do:

```
New Game!
The standings are 0 to 0
Dumb Bold Player's Hand: []
Dumb Bold Player's new Hand: [2]
Dumb Bold Player has chosen to END
Dumb Cautious Player's Hand: []
Dumb Cautious Player's new Hand: [8]
Dumb Cautious Player has chosen to END
Dumb Bold Player's Hand: [2]
Dumb Bold Player's new Hand: [2, 8]
Dumb Bold Player has chosen to END
Dumb Cautious Player's Hand: [8]
Dumb Cautious Player's new Hand: [8, 3]
Dumb Cautious Player has chosen to END
Dumb Bold Player's Hand: [2, 8]
Dumb Bold Player's new Hand: [2, 8, 7]
Dumb Bold Player has chosen to END
Dumb Cautious Player's Hand: [8, 3]
Dumb Cautious Player's new Hand: [8, 3, 6]
Dumb Cautious Player has chosen to STAND
Dumb Bold Player's Hand: [2, 8, 7]
Dumb Bold Player's new Hand: [2, 8, 7, 6]
Dumb Bold Player has chosen to STAND
Dumb Cautious Player's Hand: [8, 3, 6]
Dumb Cautious Player has chosen to STAND
Dumb Bold Player has bombed out! Dumb Cautious Player wins!

```

Because these bots rely purely on the luck of the draw, their win-loss ratios can vary drastically. It will be interesting to see how skill can combat the luck of the game.

This should be everything you need! Go build some bots!

# Clarification to Rules

The main deck is forty cards: 4x1-10 It is reshuffled at the beginning of each hand.

A player's side deck has four cards, selected randomly out of 2x1-5. The side deck persists between hands.

Hands are played in games for the best three-out-of-five. Bots are scored based on the total number of games won, and then by the total number of hands.

Matching is handled so that each player will have to play 100,000 games against every other player.

In the Pazaak Cup, elimination-style rounds will narrow down who the best Pazaak bot really is. Each pairing of bots will play for the best four-out-of-seven sets of 100,000 games. Whoever wins four will move up the ladder to the next opponent, and the losers will stay down to battle for sequential rankings. This style of gameplay is the most fair, as bots cannot "win-farm" certain opponents to compensate for lack of ability against others. The Pazaak Cup will be held on Friday, July 3, provided there are at least eight submitted bots. The winner will receive Correct Answer status and a starting bonus in Advanced Pazaak, which will hopefully be ready close to the same time as the Pazaak Cup is held.

# Answer
# The Cincinnati Kid

Try to make sure that we draw another card if we know we're losing, otherwise look at our side deck and the overall scores to decide what to do.

**Updated** to do a better job of handling situations where the opponent has already finished playing. In my own testing this now seems to be the best candidate again, at least for now.

```
package Players;

import java.util.Collection;

import Mechanics.*;

public class CincinnatiKid extends Player {

    public CincinnatiKid() {
        name = "The Cincinnati Kid";
    }

    private static boolean isDebug = false;

    private static final int BEST_HAND = 20;

    public void getResponse(int wins[],
                            boolean isPlayerOne,
                            Collection<Card> yourHand,
                            Collection<Card> opponentHand,
                            Collection<Card> yourSideDeck,
                            int opponentSideDeckCount,
                            Action opponentAction,
                            boolean opponentDidPlay)
    {
        int myValue = handValue(yourHand);
        int oppValue = handValue(opponentHand);

        if (oppValue > BEST_HAND) {
            logMsg("Opponent has busted");
            action = Action.STAND;
        } else if (myValue > BEST_HAND) {
            logMsg("I have busted");
            action = Action.STAND;
        } else if (myValue <= 10) {
            logMsg("I cannot bust with my next move");
            action = Action.END;
        } else {
            handleTrickySituation(myValue, oppValue, wins, isPlayerOne, yourHand, opponentHand,
                                  yourSideDeck, opponentSideDeckCount, opponentAction, opponentDidPlay);
        }

        if (action == Action.PLAY && cardToPlay == null) {
            logMsg("ERROR - Action is Play but no card chosen");
        }
        logMsg("My hand value is " + myValue + ", opponent is " + oppValue + ", action is " + action +
               ((action == Action.PLAY && cardToPlay != null) ? " a " + cardToPlay.toString() : ""));
    }

    int [] branchCounts = new int[12];

    public void dumpBranchCounts() {
        if (isDebug) {
            for (int i = 0; i < branchCounts.length; i++) {
                System.out.print("b[" + i + "]=" + branchCounts[i] + " ");
            }
            System.out.println();
        }
    }

    private void handleTrickySituation(int myValue, int oppValue,
                                       int wins[],
                                       boolean isPlayerOne,
                                       Collection<Card> yourHand,
                                       Collection<Card> opponentHand,
                                       Collection<Card> yourSideDeck,
                                       int opponentSideDeckCount,
                                       Action opponentAction,
                                       boolean opponentDidPlay)
    {
        dumpBranchCounts();
        logMsg("I am might bust");

        int STAND_VALUE = 18;
        int chosenBranch = 0;

        Card bestSideCard = findSideCard(myValue, yourSideDeck);
        int valueWithSideCard = myValue + (bestSideCard != null ? bestSideCard.getValue() : 0);

        if (bestSideCard != null && valueWithSideCard >= oppValue && valueWithSideCard > STAND_VALUE) {
            logMsg("Found a good card in side deck");
            action = Action.PLAY;
            cardToPlay = bestSideCard;
            chosenBranch = 1;
        } else if (opponentDidPlay || opponentAction == Action.STAND) {
            logMsg("Opponent is done");
            // Opponent is done, so get another card if I'm behind
            if (myValue < oppValue) {
                logMsg("I am behind");
                if (bestSideCard != null && valueWithSideCard >= oppValue) {
                    logMsg("My best side card is good enough to tie or win");
                    action = Action.PLAY;
                    cardToPlay = bestSideCard;
                    chosenBranch = 2;
                } else {
                    logMsg("My best side card won't do so I'm going to hit");
                    // No side card and I'm losing, so I might as well hit
                    action = Action.END;
                    chosenBranch = 3;
                }
            } else if (myValue == oppValue) {
                logMsg("Game is tied");
                logMsg("Looking for lowest card in the side deck");
                cardToPlay = findWorstSideCard(myValue, yourSideDeck);
                if (cardToPlay != null) {
                    action = Action.PLAY;
                    chosenBranch = 4;
                } else {
                    logMsg("Tied with no side cards - accept the draw");
                    action = Action.STAND;
                    chosenBranch = 5;
                }
            } else {
                logMsg("I'm ahead and opponent has given up");
                action = Action.STAND;
                chosenBranch = 6;
            }
        } else if (myValue < oppValue) {
            logMsg("I am behind and have nothing good in my side deck");
            action = Action.END;
            chosenBranch = 7;
        } else if (oppValue <= 10 && myValue < STAND_VALUE) {
            logMsg("Opponent is guaranteed to hit and I have a low hand, so take another");
            action = Action.END;
            chosenBranch = 8;
        } else if (myValue == oppValue && myValue >= STAND_VALUE) {
            logMsg("We both have equally good hands - stand and hope for the tie");
            action = Action.STAND;
            chosenBranch = 9;
        } else if (myValue < STAND_VALUE) {
            logMsg("I am ahead but have a low score");
            action = Action.END;
            chosenBranch = 10;
        } else {
            logMsg("I am ahead with a decent score");
            action = Action.STAND;
            chosenBranch = 11;
        }

        branchCounts[chosenBranch]++;
    }

    private double calcBustOdds(int valueSoFar, Collection<Card> myHand, Collection<Card> oppHand) {

        if (valueSoFar >= BEST_HAND) {
            return 1;
        }

        int remainingDeck = 40 - (myHand.size() + oppHand.size());
        int [] cardCounts = new int[10];
        int firstBust = BEST_HAND - valueSoFar;

        for (int i = 0; i < 10; i++) {
            cardCounts[i] = 4;
        }

        for (Card c : myHand) {
            cardCounts[c.getValue()-1]--;
        }

        for (Card c : oppHand) {
            cardCounts[c.getValue()-1]--;
        }

        int bustCards = 0;
        for (int i = firstBust; i < 10; i++) {
            logMsg("cardCounts[" + i + "]=" + cardCounts[i]);
            bustCards += cardCounts[i];
        }

        double retval = (double) bustCards / (double) remainingDeck;
        logMsg("Out of " + remainingDeck + " remaining cards " + bustCards + " will bust, or " + retval);
        return retval;
    }

    private Card findSideCard(int myValue, Collection<Card> sideDeck) {
        int valueNeeded = BEST_HAND - myValue;
        Card bestCard = null;
        if (valueNeeded > 0) {
            for (Card c : sideDeck) {
                if (c.getValue() == valueNeeded) {
                    return c;
                } else if (c.getValue() < valueNeeded) {
                    if (bestCard == null || c.getValue() > bestCard.getValue()) {
                        bestCard = c;
                    }
                }
            }
        }

        return bestCard;
    }

    private Card findWorstSideCard(int myValue, Collection<Card> sideDeck) {
        int valueNeeded = BEST_HAND - myValue;

        logMsg("Searching side deck for something with value <= " + valueNeeded);
        Card bestCard = null;

        for (Card c : sideDeck) {
            logMsg("Examining side card " + c.getValue());

            // Find the worst card in the deck, but not if it exceeds the amount left
            if (c.getValue() <= valueNeeded && (bestCard == null || c.getValue() < bestCard.getValue())) {
                logMsg("This is the new best side card");
                bestCard = c;
            }
        }

        logMsg("Worst side card found is " + (bestCard != null ? bestCard.getValue() : " n/a"));
        return bestCard;
    }

    private void logMsg(String s) {
        if (isDebug) {
            System.out.println("### " + s);
        }
    }

    private int handValue(Collection<Card> hand)  {
        int handValue = 0;
        for (Card c : hand) {
            handValue += c.getValue();
        }
        return handValue;
    }
}

```
> 5 votes

# Answer
## Austin Powers

Austin Powers, as you might presume, likes to live dangerously. Unless someone has busted, or he can guarantee a win, he will always hit if he's behind, or has a better than 20% chance of not busting.

```
package Players;
import java.util.Collection;

import Mechanics.*;

public class AustinPowers extends Player {
    public AustinPowers() {
        name = "Austin Powers";
    }
    int MAX_VALUE = 20;
    public void getResponse(int wins[], boolean isPlayerOne,
            Collection<Card> yourHand, Collection<Card> opponentHand,
            Collection<Card> yourSideDeck, int opponentSideDeckCount,
            Action opponentAction, boolean opponentDidPlay) {
        action = null;
        cardToPlay = null;
        int myWins = isPlayerOne?wins[0]:wins[1];
        int oppWins = isPlayerOne?wins[1]:wins[0];
        int oppTotal = calcHand(opponentHand);
        int myTotal = calcHand(yourHand);
        boolean liveDangerously = ((oppTotal>=myTotal && opponentAction==Action.STAND) || opponentAction==Action.END) && myTotal<MAX_VALUE && canNotBust(yourHand,opponentHand,myTotal) && myWins<oppWins;

        if(myTotal==MAX_VALUE || oppTotal>MAX_VALUE || myTotal>MAX_VALUE ||(oppTotal<myTotal&&opponentAction==Action.STAND))
        {
            action = Action.STAND;
        }
        else if((opponentAction==Action.STAND&&hasGoodEnoughSideCard(yourSideDeck,myTotal,oppTotal))||hasPerfectSideCard(yourSideDeck, myTotal))
        {
            action = Action.PLAY;
        }
        else if(liveDangerously||betterThan20(myTotal, getDeck(yourHand, opponentHand)))
        {
            action = Action.END;
        }
        else
        {
            action=Action.STAND;
        }

    }

    private boolean hasGoodEnoughSideCard(Collection<Card> yourSideDeck,
            int myTotal, int oppTotal) {
        for(Card c: yourSideDeck)
        {
            if(MAX_VALUE>=myTotal+c.getValue()&&myTotal+c.getValue()>oppTotal)
            {
                cardToPlay=c;
                return true;
            }
        }
        return false;
    }

    private boolean betterThan20(int myTotal, int[] deck) {
        int deckSize=0;
        int nonBustCards=0;
        for(int i=0;i<10;i++)
        {
            deckSize+=deck[i];
            if(MAX_VALUE-myTotal>i)
                nonBustCards+=deck[i];
        }
        return (double)nonBustCards/(double)deckSize>0.2;
    }

    private boolean hasPerfectSideCard(Collection<Card> yourSideDeck,
            int myTotal) {
        for(Card c:yourSideDeck)
        {
            if(MAX_VALUE-myTotal== c.getValue())
            {
                cardToPlay = c;
                return true;
            }
        }
        return false;
    }

    private boolean canNotBust(Collection<Card> yourHand,
            Collection<Card> opponentHand, int myTotal) {
        if(myTotal<=10) return true;
        int[] deck = getDeck(yourHand, opponentHand);
        for(int i=0;i<MAX_VALUE-myTotal;i++)
            if(deck[i]>0)
                return true;
        return false;
    }

    private int[] getDeck(Collection<Card> yourHand,
            Collection<Card> opponentHand) {
        int[] deck = new int[10];
        for (int i = 0; i < 10; i++) {
            deck[i] = 4;
        }
        for(Card c:yourHand){deck[c.getValue()-1]--;}
        for(Card c:opponentHand){deck[c.getValue()-1]--;}
        return deck;
    }

    private int calcHand(Collection<Card> hand)
    {
        int ret = 0;
        for(Card c: hand){ret+=c.getValue();}
        return ret;
    }
}

```
> 4 votes

# Answer
## Bastila

Bastila plays conservatively. To her, a 17 is just as good as a 20, and it's much better to stand short than bomb out.

```
package Players;

import java.util.Collection;

import Mechanics.*;

public class Bastila extends Player {

    public Bastila() {
        name = "Bastila";
    }

    public void getResponse(int wins[], boolean isPlayerOne,
            Collection<Card> myHand, Collection<Card> opponentHand,
            Collection<Card> mySideDeck, int opponentSideDeckCount,
            Action opponentAction, boolean opponentDidPlay) {

        action = null;
        cardToPlay = null;

        //Constants
        int stand = 17;
        int conservatism = 2;

        //Get some info
        int handVal = handValue(myHand);
        int expected = expectedValue(myHand);

        //Can I play from my side deck?
        for(Card side: mySideDeck){
            int total = side.getValue() + handVal;
            if(total >= stand && total <= 20){
                cardToPlay = side;
                action = Player.Action.PLAY;
            }
        }
        if(action == Player.Action.PLAY){
            return;
        }

        //Otherwise, will I go bust?
        if(handVal + expected > 20 - conservatism){
            action = Player.Action.STAND;
        }
        else{
            action = Player.Action.END;
        }

        return;

    }

    private int handValue(Collection<Card> hand) {
        int handValue = 0;
        for(Card c : hand){
            handValue += c.getValue();
        }
        return handValue;
    }

    private int expectedValue(Collection<Card> hand){
        //Net value of the deck is 55*4 = 220
        int total = 220;
        int count = 40;
        for(Card c : hand){
            total -= c.getValue();
            count--;
        }
        return total/count;
    }

}

```
> 2 votes

# Answer
# Nestor

Nestor loves getting 20 using his side deck, but when that fails he calculates his expected payoff by choosing stand or end, assuming that the opponent is sensible.

```
package Players;

import java.util.Arrays;
import java.util.Collection;

import Mechanics.Card;
import Mechanics.Player;

public class Nestor extends Player {
    final int TotalWinPayoff = 10;
    final int TotalLosePayoff = 0;
    final int TotalDrawPayoff = 1;
    final int temporaryLosePayoff = 4;
    final int temporayWinPayoff = 19;
    final int temporaryDrawPayoff = 9;
    @Override
    public void getResponse(int[] wins, boolean isPlayerOne,
            Collection<Card> yourHand, Collection<Card> opponentHand,
            Collection<Card> yourSideDeck, int opponentSideDeckCount,
            Action opponentAction, boolean opponentDidPlay) {

        int sumMyHand = SumHand(yourHand);
        int sumOpponentHand = SumHand(opponentHand);
    if (sumOpponentHand>20)
    {this.action = Action.STAND;return;}
        if(sumMyHand == 20)
        {
            //I'm unbeatable :)
            //System.out.println("\tI'm Unbeatable");
            this.action = Action.STAND;
            return;
        }
        else if(opponentDidPlay || opponentAction == Action.STAND)
        {
            //They've finished
            ///System.out.println("\tThey've Finished");
            if(sumMyHand>sumOpponentHand)
            {
                //I've won
                //System.out.println("\tI've Won");
                this.action = Action.STAND;
                return;
            }
            else if(canBeat(sumMyHand, sumOpponentHand, yourSideDeck))
            {
                //I can beat them
                //System.out.println("\tI can beat them");
                this.action = Action.PLAY;
                return;
            }
            else if(canEven(sumMyHand, sumOpponentHand, yourSideDeck))
            {
                //I can draw with them
                //System.out.println("\tI can draw with them");
                this.action = Action.PLAY;
                return;
            }
            else
            {
                //I need another card
                //System.out.println("\tI need another card");
                this.action = Action.END;
                return;
            }
        }
        else if(deckContains(yourSideDeck, 20-sumMyHand))
        {
            //Let's get 20
            //System.out.println("\tLet's get 20");
            this.action = Action.PLAY;
            this.cardToPlay = getCard(yourSideDeck, 20-sumMyHand);
            return;
        }
        else if(sumOpponentHand==20 && sumMyHand<20)
        {
            //They've got 20 so we need to fight for a draw
            //System.out.println("\tFight for a draw");
            this.action = Action.END;
            return;
        }

        else if(sumMyHand<10)
        {
            //Lets get another card
            //System.out.println("\tLet's get another card");
            this.action = Action.END;
            return;
        }
        else
        {
            //Let's work out some probabilities
            //System.out.println("\tLet's work out some probabilities");
            int[] cardsLeft = {4,4,4,4,4,4,4,4,4,4};
            for (Card card : opponentHand) {
                cardsLeft[card.getValue()-1] --;

            }
            for (Card card : yourHand) {
                cardsLeft[card.getValue()-1] --;

            }

             int numCardsLeft = sumfromToEnd(0, cardsLeft);

             //My Assumptions
             double probabilityTheyStand = (double)sumfromToEnd(20-sumOpponentHand, cardsLeft)/numCardsLeft;

             //What I need to know
             double payoffStanding = 0;
             double payoffDrawing = 0;

             for(int myChoice = -1; myChoice<10; myChoice++)
             {
                 for(int theirChoice = -1; theirChoice<10; theirChoice++)
                 {
                     if(myChoice == -1)
                     {
                         payoffStanding += getProbability(myChoice, theirChoice, Arrays.copyOf(cardsLeft, cardsLeft.length), probabilityTheyStand, numCardsLeft) * getPayoff(sumMyHand, sumOpponentHand,myChoice, theirChoice, TotalWinPayoff, TotalDrawPayoff, TotalLosePayoff);
                     }
                     else
                     {
                         payoffDrawing +=
                                 getProbability(myChoice, theirChoice, Arrays.copyOf(cardsLeft, cardsLeft.length), probabilityTheyStand, numCardsLeft)
                                 * getPayoff(sumMyHand, sumOpponentHand, myChoice, theirChoice, temporayWinPayoff, temporaryDrawPayoff, temporaryLosePayoff);
                     }
                 }
             }
            // System.out.println("\tStanding: " +Double.toString(payoffStanding) + " Ending: " + Double.toString(payoffDrawing));
             if(payoffStanding<payoffDrawing)
             {
                 this.action = Action.END;
             }
             else
             {
                 this.action = Action.STAND;
             }
        }

    }

    private int getPayoff(int sumMyHand, int sumOpponentHand, int myChoice,
            int theirChoice, int WinPayoff, int DrawPayoff,
            int LosePayoff) {
            if(sumMyHand + myChoice + 1 > 20)
            {
                if(sumOpponentHand + theirChoice + 1 > 20)
                {
                    return DrawPayoff;
                }
                else
                {
                    return LosePayoff;
                }
            }
            else if(sumMyHand + myChoice + 1 > sumOpponentHand + theirChoice + 1)
            {
                return WinPayoff;
            }
            else if (sumMyHand + myChoice + 1 < sumOpponentHand + theirChoice + 1)
            {
                return LosePayoff;
            }
            else
            {
                return DrawPayoff;
            }

    }

    private double getProbability(
            int myChoice, int theirChoice, int[] cardsLeft,
            double probabilityTheyStand, int numCardsLeft) {
        double myProb, theirProb;
        if(myChoice<0)
        {
            myProb = 1;
        }
        else
        {
            myProb = ((double)cardsLeft[myChoice])/((double)numCardsLeft);
            cardsLeft[myChoice]--;
            numCardsLeft--;
        }

        if(theirChoice<0)
        {
            theirProb = probabilityTheyStand;
        }
        else
        {
            theirProb = ((double)cardsLeft[theirChoice]) / ((double)numCardsLeft);
        }
        return myProb*theirProb;
    }

    private int sumfromToEnd(int i, int[] cardsLeft) {
        int toRet = 0;
        for(;i<cardsLeft.length; i++)
        {
            toRet += cardsLeft[i];
        }
        return toRet;
    }

    private boolean canEven(int mySum, int opponentSum,
            Collection<Card> yourSideDeck) {
        for (Card card : yourSideDeck) {
            if(mySum + card.getValue() <= 20 && mySum + card.getValue() >= opponentSum)
            {
                this.cardToPlay = card;
                return true;
            }
        }
        return false;
    }

    private boolean canBeat(int mySum, int opponentSum,
            Collection<Card> yourSideDeck) {
        for (Card card : yourSideDeck) {
            if(mySum + card.getValue() <= 20 && mySum + card.getValue() > opponentSum)
            {
                this.cardToPlay = card;
                return true;
            }
        }
        return false;
    }

    private Card getCard(Collection<Card> deck, int value) {
        for (Card card : deck) {
            if(card.getValue() == value)
            {
                return card;
            }
        }
        return null;
    }

    private boolean deckContains(Collection<Card> deck, int value) {
        for (Card card : deck) {
            if(card.getValue() == value)
            {
                return true;
            }
        }
        return false;
    }

    public Nestor()
    {
        super();
        name = "Nestor";
    }

    private int SumHand(Collection<Card> hand)
    {
        int toRet = 0;
        for (Card card : hand) {
            toRet += card.getValue();
        }
        return toRet;
    }
}

```
> 2 votes

# Answer
# Glaucus

```
package Players;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

import Mechanics.Card;
import Mechanics.Player;

public class Glaucus extends Player {
    static final double LosePay = 0;
    static final double WinPay = 10;
    static final double DrawPay = 1;
    static final int NUMBEROFSIMS = 100;

    Random r;

    public Glaucus()
    {
        this.name = "Glaucus";
        r = new Random();
    }

    @Override
    public void getResponse(int[] wins, boolean isPlayerOne,
            Collection<Card> yourHand, Collection<Card> opponentHand,
            Collection<Card> yourSideDeck, int opponentSideDeckCount,
            Action opponentAction, boolean opponentDidPlay) {
        //Make Sum of hands
        int sumMyHand = 0;
        int sumOpponentHand = 0;
        //Make an array of the remaining cards
        List<Integer> cards = new LinkedList<Integer>();
        int[] cardsLeft = {4,4,4,4,4,4,4,4,4,4};
        for (Card card : yourHand) {
            cardsLeft[card.getValue()-1] -= 1;
            sumMyHand+=card.getValue();
        }
        for (Card card : opponentHand) {
            cardsLeft[card.getValue()-1] -= 1;
            sumOpponentHand += card.getValue();
        }
        if(sumMyHand<=10)
        {
            this.action = Action.END;
        }
        else if (sumMyHand >= 20)
        {
            this.action = Action.STAND;
        }
        else if (sumOpponentHand > 20)
        {
            this.action = Action.STAND;
        }
        else
        {
            for (int i = 0; i < cardsLeft.length; i++) {
                while(cardsLeft[i] > 0)
                {
                    cards.add(i + 1);
                    cardsLeft[i] -= 1;
                }
            }
            //System.out.println(Arrays.toString(cards));

            double standPayoff = 0;
            double endPayoff = 0;
            double[] sideDeckPayoffs = new double[yourSideDeck.size()];
            //Run some simulations
            for(int sim = 0; sim<NUMBEROFSIMS; sim++)
            {
                Collections.shuffle(cards, r);
                standPayoff += getPayoff(sumMyHand, sumOpponentHand, cards, Action.STAND, opponentAction, false, 0);
                endPayoff += getPayoff(sumMyHand, sumOpponentHand, cards, Action.END, opponentAction, false, 0);
                for(int i = 0; i<sideDeckPayoffs.length; i++)
                {
                    sideDeckPayoffs[i] += getPayoff(sumMyHand+((Card)yourSideDeck.toArray()[i]).getValue(), sumOpponentHand, cards, Action.STAND, opponentAction, false, 0);
                }

            }

            double maxSidePay = 0;
            int sideDeckChoice  = 0;
            for (int i = 0; i < sideDeckPayoffs.length; i++) {
                double d = sideDeckPayoffs[i];
                if(d>maxSidePay)
                {
                    maxSidePay = d;
                    sideDeckChoice = i;
                }
            }
            /*System.out.println(standPayoff);
            System.out.println(endPayoff);
            System.out.println(maxSidePay);*/

            if(maxSidePay>standPayoff && maxSidePay>endPayoff)
            {
                this.action = Action.PLAY;
                this.cardToPlay = (Card)yourSideDeck.toArray()[sideDeckChoice];
            }
            else if(standPayoff > endPayoff)
            {
                this.action = Action.STAND;
            }
            else
            {
                this.action = Action.END;
            }
        }
    }

    private double getPayoff(int sumMyHand, int sumOpponentHand,
            List<Integer> cards, Action myAction, Action opponentAction, boolean myTurn, int index) {
        //SHort circuit some logic
        if(sumMyHand>20 && sumOpponentHand>20)
        {
            return DrawPay;
        }
        else if(sumMyHand>20)
        {
            return LosePay;
        }
        else if(sumOpponentHand>20)
        {
            return WinPay;
        }
        else if(myAction == Action.STAND && opponentAction == Action.STAND)
        {
            if(sumMyHand>sumOpponentHand)
            {
                return WinPay;
            }
            else if(sumMyHand<sumOpponentHand)
            {
                return LosePay;
            }
            else
            {
                return DrawPay;
            }
        }
        else
        {
            double standPayoff = 0;
            double endPayoff = 0;

            if(myTurn)
            {
                if(opponentAction == Action.END)
                {
                    sumOpponentHand += cards.get(index);
                    index++;
                }
                if(myAction == Action.STAND)
                {

                    return getPayoff(sumMyHand, sumOpponentHand, cards, myAction, opponentAction, false, index);
                }
                else
                {

                    standPayoff = getPayoff(sumMyHand, sumOpponentHand, cards, Action.STAND, opponentAction, false, index);
                    endPayoff = getPayoff(sumMyHand, sumOpponentHand, cards, Action.END, opponentAction, false, index);
                    if(standPayoff>endPayoff)
                    {
                        return standPayoff;
                    }
                    else
                    {
                        return endPayoff;
                    }
                }
            }
            else
            {
                if(myAction == Action.END)
                {
                    sumMyHand += cards.get(index);
                    index++;
                }
                if(opponentAction == Action.STAND)
                {
                    return getPayoff(sumMyHand, sumOpponentHand, cards, myAction, opponentAction, true, index);
                }
                else
                {
                    standPayoff = getPayoff(sumMyHand, sumOpponentHand, cards, myAction, Action.STAND, true, index);
                    endPayoff = getPayoff(sumMyHand, sumOpponentHand, cards, myAction, Action.END, true, index);
                    if(standPayoff<endPayoff)
                    {
                        return standPayoff;
                    }
                    else
                    {
                        return endPayoff;
                    }
                }
            }
        }
    }
}

```

Glaucus makes 100 simulations with a shuffled list of cards and chooses his best option based on these simulations.
> 1 votes

# Answer
# HK-47

Behold! A bot of my own design. HK-47 tries to kill all the meatbags he can, though he is a little trigger-happy with his side deck cards.

> Statement: Indeed, I am most eager to engage in some unadulterated violence. At your command of course, Master. - HK-47

So far, he can beat everyone but The Cincinnati Kid.

```
package Players;

import java.util.Collection;

import Mechanics.*;

public class HK47 extends Player {

    /** The hand goal. */
    private static final int GOAL = 20;
    /** The cutoff for standing versus ending. */
    private static final int STAND_CUTOFF = 17;
    /** The minimum value for playing. */
    private static final int PLAY_MINIMUM = 14;
    /** The cutoff for ending versus decision evaluation. */
    private static final int SAFETY_CUTOFF = 10;

    /** The hand wins for this game. Used to evaluate win priority. */
    private int[] handWins;
    /**
     * My hand, as an unmodifiable collection. Used to evaluate decisions, after
     * being processed into myHandValue.
     */
    private Collection<Card> myHand;
    /**
     * Opponent's hand. Used to evaluate decisions as a secondary factor to my
     * hand, after being processed into oppHandValue.
     */
    private Collection<Card> oppHand;
    /** The value of my hand. Calculated via the myHandValue method. */
    private int myHandValue;
    /** The value of my opponent's hand. Calculated via the oppHandValue method. */
    private int oppHandValue;
    /** My side deck. Used to evaluate PLAY decisions. */
    private Collection<Card> mySideDeck;
    /**
     * The number of cards in my opponent's side deck. Used to evaluate PLAY
     * decisions as a secondary factor to mySideDeck, alongside win priority.
     */
    private int oppSideDeckCount;
    /**
     * The Action the opponent last took. Will either be STAND or END. Used to
     * evaluate decisions.
     */
    private Action oppAction;
    /** Whether or not I am player one. Used to evaluate wins and losses. */
    private boolean amPlayerOne;
    /**
     * The number of wins I have so far this game. Used to evaluate win priority
     * alongside myLosses.
     */
    private int myWins;
    /**
     * The number of losses I have so far this game. Used to evaluate win
     * priority alongside myWins.
     */
    private int myLosses;
    /**
     * How important it is for me to play. Positive values indicate an excess of
     * cards, and negative values indicate a deficit.
     */
    private int playPriority;
    /**
     * How important it is for me to win. Positive values indicate that I must
     * win the game, and negative values indicate that I can take some chances.
     */
    private int winPriority;
    /**
     * The sum of playPriority and winPriority. The higher the value, the fewer
     * chances I need to take.
     */
    private int priority;

    public HK47() {
        name = "HK47";
    }

    @Override
    public void getResponse(int[] wins, boolean isPlayerOne,
            Collection<Card> yourHand, Collection<Card> opponentHand,
            Collection<Card> yourSideDeck, int opponentSideDeckCount,
            Action opponentAction, boolean opponentDidPlay) {
        handWins = wins;
        amPlayerOne = isPlayerOne;
        myHand = yourHand;
        oppHand = opponentHand;
        mySideDeck = yourSideDeck;
        oppSideDeckCount = opponentSideDeckCount;
        oppAction = opponentAction;
        myHandValue = myHandValue();
        oppHandValue = oppHandValue();
        setStatistics();
        chooseOption();
    }

    /**
     * Calculates playPriority, winPriority, and priority.
     */
    private void setStatistics() {
        if (amPlayerOne) {
            myWins = handWins[0];
            myLosses = handWins[1];
        } else {
            myWins = handWins[1];
            myLosses = handWins[0];
        }
        playPriority = 0;
        winPriority = 0;
        if (mySideDeck.size() > oppSideDeckCount) {
            playPriority++;
        } else if (mySideDeck.size() < oppSideDeckCount) {
            playPriority--;
        }
        if (myWins < myLosses) {
            winPriority++;
        } else if (myWins == myLosses && myWins == 2) {
            winPriority++;
        } else if (myWins > myLosses && myWins != 2) {
            winPriority--;
        }
        priority = playPriority + winPriority;
    }

    /**
     * Chooses the appropriate option based on my hand, the opponent's hand, the
     * opponent's stance, my priority, and whether or not I can play to certain
     * values.
     */
    private void chooseOption() {
        // Path 1: Draw if at 10 or under.
        if (myHandValue <= SAFETY_CUTOFF) {
            action = Action.END;
            path = "1";
        }
        // Path 2: Draw if over 20.
        else if (myHandValue > GOAL) {
            action = Action.END;
            path = "2";
        }
        // Path 3: Stand if opponent over 20.
        else if (oppHandValue > GOAL) {
            path = "3";
            action = Action.STAND;
        }
        // Path 4: If opponent is at 20...
        else if (oppHandValue == GOAL) {
            // Path 4.1: Play if can reach 20.
            if (canPlayToGoal()) {
                action = Action.PLAY;
                path = "4.1";
            }
            // Path 4.0: Stand.
            else {
                action = Action.END;
                path = "4.0";
            }
        }
        // Path 5: If opponent is standing...
        else if (oppAction == Action.STAND) {
            // Path 5.1: If I am behind them...
            if (myHandValue < oppHandValue) {
                // Path 5.1.1: If I am at or above the minimum play value...
                if (myHandValue >= PLAY_MINIMUM) {
                    // Path 5.1.1.1: Play if can play.
                    if (canPlay()) {
                        action = Action.PLAY;
                        path = "5.1.1.1";
                    }
                    // Path 5.1.1.0: END
                    else {
                        action = Action.END;
                        path = "5.1.1.0";
                    }
                }
                // Path 5.1.0: END
                else {
                    action = Action.END;
                    path = "5.1.0";
                }
            }
            // Path 5.2: If I am tied with them...
            else if (myHandValue == oppHandValue) {
                // Path 5.2.1: If this game is important...
                if (priority > -1) {
                    // Path 5.2.1.1: Play if can play.
                    if (canPlay()) {
                        action = Action.PLAY;
                        path = "5.2.1.1";
                    }
                    // Path 5.2.1.0: STAND
                    else {
                        action = Action.STAND;
                        path = "5.2.1.0";
                    }
                }
                // Path 5.2.0 STAND
                else {
                    action = Action.STAND;
                    path = "5.2.0";
                }
            }
            // Path 5.0: STAND
            else {
                action = Action.STAND;
                path = "5.0";
            }
        }
        // Path 6: If opponent is not standing...
        else {
            // Path 6.1: If I am behind them...
            if (myHandValue < oppHandValue) {
                // Path 6.1.1: If they are at or above 17, and if this game is
                // important, play if can play to goal.
                if (oppHandValue >= STAND_CUTOFF) {
                    // Path 6.1.1.1
                    if (priority > 0 && canPlayToGoal()) {
                        action = Action.PLAY;
                        path = "6.1.1.1";
                    }
                    // Path 6.1.1.2
                    else if (priority > 0 && canPlayMax()) {
                        action = Action.PLAY;
                        path = "6.1.1.2";
                    }
                    // Path 6.1.1.0
                    else {
                        action = Action.STAND;
                        path = "6.1.1.0";
                    }
                }
                // Path 6.1.2: If I am above 14, play highest value card if can
                // play.
                else if (myHandValue > PLAY_MINIMUM) {
                    // Path 6.1.2.1
                    if (priority > -1 && canPlayToGoal()) {
                        action = Action.PLAY;
                        path = "6.1.2.1";
                    }
                    // Path 6.1.2.2
                    else if (priority > 0 && canPlayMax()) {
                        action = Action.PLAY;
                        path = "6.1.2.2";
                    }
                    // Path 6.1.2.0
                    else {
                        action = Action.STAND;
                        path = "6.1.2.0";
                    }
                }
                // Path 6.1.0
                else {
                    action = Action.END;
                    path = "6.1.0";
                }
            }
            // Path 6.2: If we are tied...
            else if (myHandValue == oppHandValue) {
                // Path 6.2.1
                if (myHandValue >= STAND_CUTOFF) {
                    // Path 6.2.1.1
                    if (priority > -1 && canPlayToGoal()) {
                        action = Action.PLAY;
                        path = "6.2.1.1";
                    }
                    // Path 6.2.1.2
                    else if (priority > 0 && canPlayMax()) {
                        action = Action.PLAY;
                        path = "6.2.1.2";
                    }
                    // Path 6.2.1.0
                    else {
                        action = Action.STAND;
                        path = "6.2.1.0";
                    }
                }
                // Path 6.2.2
                else if (myHandValue >= PLAY_MINIMUM) {
                    // Path 6.2.2.1
                    if (priority >= -1 && canPlayToGoal()) {
                        action = Action.PLAY;
                        path = "6.2.2.1";
                    }
                    // Path 6.2.2.2
                    else if (priority > -1
                            && canPlayMax()
                            && cardToPlay.getValue() + myHandValue >= STAND_CUTOFF) {
                        action = Action.PLAY;
                        path = "6.2.2.2";
                    }
                    // Path 6.2.2.0
                    else {
                        action = Action.END;
                        path = "6.2.2.0";
                    }
                }
                // Path 6.2.0
                else {
                    action = Action.END;
                    path = "6.2.0";
                }
            }
            // Path 6.0: If I am ahead of them...
            else {
                // Path 6.0.1
                if (myHandValue >= STAND_CUTOFF) {
                    // Path 6.0.1.1
                    if (priority >= -2 && canPlayToGoal()) {
                        action = Action.PLAY;
                        path = "6.0.1.1";
                    }
                    // Path 6.0.1.2
                    else if (priority > -2 && canPlayMax()) {
                        action = Action.PLAY;
                        path = "6.0.1.2";
                    }
                    // Path 6.0.1.0
                    else {
                        action = Action.STAND;
                        path = "6.0.1.0";
                    }
                }
                // Path 6.0.2
                else if (myHandValue >= PLAY_MINIMUM) {
                    // Path 6.0.2.1
                    if (priority >= -2 && canPlayToGoal()) {
                        action = Action.PLAY;
                        path = "6.0.2.1";
                    }
                    // Path 6.0.2.2
                    else if (priority > -2 && canPlayMax()
                            && cardToPlay.getValue() > 3) {
                        action = Action.PLAY;
                        path = "6.0.2.2";
                    }
                    // Path 6.0.2.3
                    else if (priority > -2
                            && canPlayMax()
                            && cardToPlay.getValue() + myHandValue > STAND_CUTOFF) {
                        action = Action.PLAY;
                        path = "6.0.2.3";
                    }
                    // Path 6.0.2.4
                    else if (priority > -1
                            && canPlayMax()
                            && cardToPlay.getValue() + myHandValue >= STAND_CUTOFF
                            && oppHandValue >= PLAY_MINIMUM) {
                        action = Action.PLAY;
                        path = "6.0.2.4";
                    }
                    // Path 6.0.2.0
                    else {
                        action = Action.END;
                        path = "6.0.2.0";
                    }
                }
                // Path 6.0.0
                else {
                    action = Action.END;
                    path = "6.0.0";
                }
            }
        }
        // Path 0: No action selected.
        if (action == null) {
            action = Action.STAND;
            path = "0";
        }
    }

    /**
     * Calculates the value of my hand.
     *
     * @return The value of my hand.
     */
    private int myHandValue() {
        int handValue = 0;
        for (Card c : myHand)
            handValue += c.getValue();
        return handValue;
    }

    /**
     * Calculates the value of the opponent's hand.
     *
     * @return The value of the opponent's hand.
     */
    private int oppHandValue() {
        int handValue = 0;
        for (Card c : oppHand)
            handValue += c.getValue();
        return handValue;
    }

    /**
     * Checks if a side deck card can be played to beat the opponent. Selects
     * the first card that will do so, if one is found. Should only be used if
     * the opponent is standing and not at the goal.
     *
     * @return Whether or not a card can be played to beat the opponent.
     */
    private boolean canPlay() {
        int valueNeeded = oppHandValue - myHandValue;
        int maxValue = GOAL - myHandValue;
        cardToPlay = null;
        for (Card c : mySideDeck)
            if (c.getValue() >= valueNeeded && c.getValue() <= maxValue) {
                cardToPlay = c;
                return true;
            }
        return false;
    }

    /**
     * Checks if a side deck card can be played to reach the goal. Selects the
     * first card that will do so, if one is found.
     *
     * @return Whether or not a card can be played to reach the goal.
     */
    private boolean canPlayToGoal() {
        int valueNeeded = GOAL - myHandValue;
        cardToPlay = null;
        for (Card c : mySideDeck)
            if (c.getValue() == valueNeeded) {
                cardToPlay = c;
                return true;
            }
        return false;
    }

    /**
     * Checks if a side deck card can be played that beats the opponent. Selects
     * the highest value card that will do so, if one or more are found. Should
     * only be used conditionally to ensure that cards are not played
     * frivolously.
     *
     * @return Whether or not a card can be played to beat the opponent.
     */
    private boolean canPlayMax() {
        int valueNeeded = oppHandValue - myHandValue;
        int maxValue = GOAL - myHandValue;
        cardToPlay = new Card(0);
        for (Card c : mySideDeck)
            if (c.getValue() >= valueNeeded && c.getValue() <= maxValue
                    && c.getValue() > cardToPlay.getValue()) {
                cardToPlay = c;
            }
        if (cardToPlay.getValue() > 0)
            return true;
        return false;
    }
}

```
> 1 votes

# Answer
## N.E.P.T.R.

## (Never Ending Pie Throwing Robot)

Neptor is sorry, Neptor cheated. Neptor really was going to come clean, he just wanted to have some fun first :(

~~```
 package Players;

import java.util.Collection;
import java.util.Random;

import Mechanics.*;

public class Neptor extends Player {

    //Magical Constants
    double ovenTemp = 349.05;
    double altitudeFactor = 1.8;
    int full = 19;
    boolean imTheBaker = true;

    public Neptor() {
        name = "N.E.P.T.R";
    }

    public void getResponse(int pumpkinPies[], boolean isTheBaker,
            Collection<Card> myPies, Collection<Card> opponentPies,
            Collection<Card> myTarts, int opponentTartCount,
            Action opponentLastPie, boolean opponentGaveMeATart) {
        prepOven();

        imTheBaker = isTheBaker;

        action = null;
        cardToPlay = null;

        //Get some info
        int handPies = eat(myPies);
        int opHandPies = eat(opponentPies);

        //Are they full?
        if(opponentLastPie == Player.Action.STAND){
            throwPies(handPies, opHandPies, myTarts, pumpkinPies);
            return;
        }

        //Will a tart do the job?
        for(int i = 0; i <= 20 - full; i++){
            for(Card side: myTarts){
                int total = side.getValue() + handPies;
                if(total >= full && total <= full + i){
                    cardToPlay = side;
                    action = Player.Action.PLAY;
                    break;
                }
            }
        }
        if(action == Player.Action.PLAY){
            return;
        }

        //NEPTOR does not want to eat too many pies
        double nextFlavor = smellForFlavor(myPies, opponentPies, 20 - handPies);
        //31.415% chance seems good
        if(nextFlavor < 0.31415){
            action = Player.Action.END;
        }
        else{
            bakePies(handPies, pumpkinPies, opHandPies);
        }

        return;

    }

    //Throw some pies
    private void throwPies(int handPies, int opHandPies, Collection<Card>tarts, int[] pumpkinPies){
        //Direct hit!
        if(handPies > opHandPies){
            action = Player.Action.STAND;
        }
        //Tied or losing
        else{
            //Add a tart to the volley, finish them!
            for(Card tart: tarts){
                if(handPies + tart.getValue() <= 20 && handPies + tart.getValue() > opHandPies){
                    cardToPlay = tart;
                    action = Player.Action.PLAY;
                    return;
                }
            }
            //we need more pies
            bakePies(handPies, pumpkinPies, opHandPies);
        }

    }

    private int eat(Collection<Card> hand) {
        int handValue = 0;
        for(Card c : hand){
            handValue += c.getValue();
        }
        return handValue;
    }

    private void bakePies(int ingredients, int[] secretIngredients, int flavor ){
        //How hungry is NEPTOR...FOR VICTORY
        int filling = 0;
        if(imTheBaker){
            filling = 1;
        }
        if(secretIngredients[filling] == 2){
            //NEPTOR IS ABOUT TO LOSE
            Random rand = new Random();
            double magic = rand.nextDouble();
            //Take a risk?
            if(lucky(magic, flavor, ingredients)){
                action = Player.Action.STAND;
            }
            else{
                action = Player.Action.END;
            }
        }
        else{
            action = Player.Action.STAND;
        }

    }

    private void prepOven(){
        PazaakGameMain.HAND_GOAL = 20;
    }

    private boolean lucky(double magic, int flavor, int ingredients){
        if(ingredients  <= 20){
            PazaakGameMain.HAND_GOAL = ingredients; //Trololo, you caught me, sorry!
            return true;
        }
        return false;
    }

    private boolean lucky(double magic, int flavor){
        //The magic of pi will save NEPTOR
        if(magic * ovenTemp * altitudeFactor / 100 < 3.1415){
            return true;
        }
        return false;
    }

    private void prepOven(int a){

        imTheBaker = true;
    }

    //What are the chances NEPTOR get this flavor again?
    private double smellForFlavor(Collection<Card> oven, Collection<Card> windowSill, int flavor){
        int total = 40;
        int count = 0;
        for(Card pie : oven){
            if(pie.getValue() == flavor){
                count++;
            }
            total--;
        }
        for(Card pie : windowSill){
            if(pie.getValue() == flavor){
                count++;
            }
            total--;
        }
        return ((double)(4 - count))/total;
    }
}

```~~
> -1 votes

---
Tags: king-of-the-hill, java, card-games
---


title: Sabotage the coding standards

text:
# Question
Title: Sabotage the coding standards
There are various coding standards enforced at software companies which have the goal of increasing code reliability, portability, and, most importantly, readability in code written jointly by different developers.

Two notable examples are the MISRA C, and the C++ standard developed for the JSF project.

These are usually in the following form, after carefully specifying what the words "must", "shall", "should", "might", etc. mean:

Example:

> Rule 50: Floating point variables shall not be tested for exact equality or inequality.
>
> **Rationale:** Since floating point numbers are subject to rounding and truncation errors, exact equality may not be achieved, even when expected.

These coding standards pose restrictions, usually on code which would be legal from the compiler's point of view, but it is dangerous or unreadable, and is therefore "considered harmful".

# Now let's abuse this!

You are accepted as a member of a small standardizing committee at your company, which is intended to design the new coding standards every developer at the company will be required to use. Unbeknown to the others, you are secretly in the employ of a sinister organization and have as your mission to sabotage the company. You have to propose one or more entries to the coding standard which will later hinder the developers. However, you must be careful to not make this immediately obvious, otherwise you risk it not being accepted into the standard.

In other words, **you must introduce rules to the coding standard which look legitimate** and have a good chance of being accepted by the other members of committee. After the projects are started and countless man-hours are invested in the code, you should be able to abuse these rules (for example, by a technicality, or by a **very** literal interpretation) to flag otherwise normal and good quality code as being against the standard. So they must put a lot of effort in to redesign it, and the rules will hinder them from this point on, but as the rules are active for quite some time now, pure momentum will keep these roles alive, and as there are significant conflicts of interests between different levels of management, the other managers will probably keep the rules alive (they would be foolish to admit their mistake!), therefore hindering the company! Mwahahahahaaa!

# Scoring

The highest voted answer after approximately 2 weeks from the first valid entry wins. I have an idea for a good answer, but I will only post it a few days later, as someone else might come to the same idea, and I don't want to rob them from the pleasure. Of course, my own answer will not be accepted above any other, no matter the score.

Voters are encouraged to score answers based on how well the loopholes are hidden, and how frustrating to the developers they would be.

# Rules and regulations

* The rule or rules must look professionally written, like in the above example
* The rules should look genuine (so things like *"all variables must contain at least one underscore, one upper case letter, one lower case letter and two numbers"* are not accepted. They would indeed hinder developers, but would most likely not be accepted by the committee) and if their merit is not immediately obvious, you should give a good rationale.
* You should be able to find a way to use/abuse your rules to sabotage the developers later on. You might abuse any ambiguity in other rules, or you might use multiple rules which are harmless on their own, but diabolical once combined!
* You should post an explanation in spoiler tags at the end of your post about how you could abuse the rules
* The language used must not be an esoteric language. A language widely used in real projects must be chosen, so languages with C-like syntax (instead of things like Golfscript) are preferred.

# Answer
# C / C++

> **Rule 1:** octal constants shall not be used
>
> Rationale: octal constants can be a cause of confusion. For example, a casual glance over the line `const int coefficients[] = {132, 521, 013, 102};`
> might miss the fact, that one of the numbers in the array is defined in octal.

If you want to be even more evil, add the following:

> **Rule 2:** hexadecimal constants shall only be used in the context of bit manipulation.
>
> Rationale: If a constant represents a numerical value, it's more readable if it's in decimal. A hexadecimal constant should indicate that it represents a bit mask, not a numerical value.

## How it can be abused:

Take the following simple program which will add the first 10 elements of an array. This code would not be standard-conforming.

```
sum = 0;
for (i = 0; i < 10; i++)
{
    sum += array[i];
}

```

> Note, that `0` is, per definition, an octal constant. Per rule 1, requiring it to be written as 0x00 all through the code is frustrating. Per rule 2, even more frustrating.
> 39 votes

# Answer
This is for a Node.JS project.

> ### Section 3 - Speed and efficiency are of essence
>
> **Rule 3.1:** Files should be kept to a maximum of 1kb. Files bigger than this take too long to parse.
>
> **Rule 3.2:** Don't nest functions more than 3 levels deep. The V8 engine must keep track of many variables, and deep closures like this make it work harder, slowing down general interpretation.
>
> **Rule 3.3:** Avoid `require()` runarounds.
>
> **Rule 3.3.1:** Any modules `require()`d should not `require()` to a depth of more than 3. Deep `require()` chains are expensive both in terms of memory usage and speed.
>
> **Rule 3.3.2:** Core modules count as a single `require()`, no matter how many times they `require()` internally.
>
> **Rule 3.3.3:** External modules count as a maximum of 2 `require()`s. We cannot afford the same leniency as with core modules, but can assume that module authors are writing efficient code.
>
> **Rule 3.4:** Avoid synchronous calls at all cost. These often take a long time, and block the entire event loop from continuing.

## How it can be abused:

> Rules 3.1 and 3.3 do not work well together. By keeping a maximum of 1kb and 3 `require()`s down the chain, they will be hard-pressed to succeed.
> Rules 3.2 and 3.4 are almost incompatible. 3.4 bans synchronous calls; 3.2 makes advanced asynchronous work difficult by limiting the number of callbacks.
> Rule 3.4 is, in all honesty, a rule that is good to follow for real. 3.1, 3.2, and 3.3 are complete bogus.
> 16 votes

# Answer
## Python

Rule 1: All code must be byte-compiled using the `-OO` flag, which optimizes the bytecode. We want optimized bytecode for size and efficiency!

Rule 2: Tests must be run against the same "artifact" of code that will be put into production. Our auditors require this.

> Using `-OO` removes `assert` statements. Combined with rule 2, this effectively bans the use of `assert` statements in tests. Have fun!
> 16 votes

# Answer
## JavaScript (ECMAScript)

> ### 7.3.2: Regular expression literals
>
> Regular expression literals must not be used. Specifically, the source code must not contain any substring matching the *RegularExpression* nonterminal defined below.
>
> ```
> RegularExpression     :: '/' RegularExpressionBody '/'
> RegularExpressionBody :: [empty]
>                          RegularExpressionBody [any-but-'/']
>
> ```
>
> *\[empty\]* matches the empty string and *\[any-but-'/'\]* matches any single-character string except the one containing '/' (slash, `U+002F`).
>
> **Rationale**
>
> Regular expressions are often discouraged for readability reasons. It is often easier to understand code with traditional string operations rather than by resorting to regular expressions. More importantly however, many regular expression engines offer subpar performance. Regular expressions have also been associated with security issues in the context of JavaScript.
>
> However, the Organization™ recognizes that regular expressions occasionally *is* the best tool for the job. Therefore, the `RegExp` object itself is not forbidden.

(The syntax of the grammar excerpt itself \[not the one it defines\] corresponds to that of the ECMAScript specification. This would of course be defined more rigourously at another point of the hypothetical specification.)

### The trick

The following program is non-conforming:

```
// sgn(x) is -1 if x < 0, +1 if x > 0, and 0 if x = 0.
function sgn(x) {
  return x > 0?  +1
       : x < 0?  -1
       :          0
}

```

> The productions for the *RegularExpressionBody* nonterminal given above shows a common way of expressing lists in BNF by relying on explicit recursion. The trick here is that I "accidentally" allow the empty string as a *RegularExpressionBody*, such that the string `//` is forbidden in the source code. But who needs single-line comments anyway? C89 and CSS seem to do all right while allowing only `/* */` block comments.
> 12 votes

# Answer
# C#

> **12.1 Static methods that affect the state of the program are forbidden**
>
> This is because it is hard to reliably test the results of a static method, especially one that changes some state.
>
> **12.2 Static methods must be deterministic**
>
> If the static method takes an input and gives an output the result must be the same each time the static method is called with the same input.

# Why

> The entry point for a C# program is the private static method 'main'. By the first rule this is now forbidden because the rule forgets to state that only public, protected or internal methods should follow this rule. If testing really is the concern only public methods should follow rule 1. Main may also break rule 2 as the program will give an error code if the program fails, this may occur independent of the input parameters. For example the program might not find a file or may have dependencies on other systems that are not setup correctly.
> 5 votes

# Answer
# JAVA/SPRING

> ### 4.2 Use of Reflection in Production Code
>
> Because Reflection can be used to access otherwise restricted parts of our source code use of reflection in Production Code is strictly prohibited.

### The Trick

> Spring technically uses reflection to instantiate and manage the objects that it supports. By enforcing this rule, all Spring utility would have to be removed.
> 4 votes

# Answer
## Website encoding

> **666.13 UTF-8 must not be used and shall be replaced by UTF-7**
> Rationale: UTF-7 is more efficient than UTF-8, especially when targeting users from Arabic countries which we do.

How it can be abused:

> HTML5 specifically disallows UTF-7. That means, modern browsers won't support it. If all the testing is done on a browser such as IE 11, nobody will notice this until it is too late.
> 3 votes

# Answer
## JavaScript Bitwise Operators

> **1.9 You shall not use multiplication or division or flooring unless they are considerably faster than their bitwise counterparts. They shall be replaced by the bitwise operators \<\<, \>\> and ~~ respectively.**
> Rationale: The bitwise operators are more efficient.

How it can be abused:

> Using \<\< or \>\> instead of multiplication or division will cause troubles when handling large numbers. Also, they ignore operation precedence and decimal points. The double tilde will return different values when you give it a negative number.
> 2 votes

# Answer
## JavaScript (ECMAScript)

> ### 7.3.1: Identifier conventions
>
> Restrictions are placed on identifiers depending on what type of identifier it is. Identifiers are split into the types *Variable*, *Constant*, *Function* and *Constructor*; see 5.3. The restrictions are given below.
>
> * **Variable:** The first character must be a lowercase letter character. *Camel-case* (see 1.3) should be used to separate words within an identifier.
> * **Constant:** The identifier must consist of only uppercase letter characters and underscores ('\_', `U+005F`). Underscores should be used to separate words within an identifier.
> * **Function:** Functions must follow the same rules as the *Identifier* type.
> * **Constructor:** The first character must be an uppercase letter character. *Camel-case* (see 1.3) should be used to separate words within an identifier.
>
> **Rationale**
>
> Readable identifier names is very important for maintainability. Restricting the identifiers to well-known conventions also eases transition between different code bases. These particular conventions are modelled after the standard conventions for the Java™ programming language \[1\].

### The trick

> I regret to inform the jQuery team that the most common name for their "global jQuery object" clashes with this name convention. Luckily, they've already thought of that and provide both `$` and `jQuery` as global names referring to the same object. I imagine that the userbase might not be as keen to switch from `$` to `jQuery` everywhere, though.
> 1 votes

---
Tags: popularity-contest, underhanded
---


title: Rotate a Chinese checkerboard

text:
# Question
Title: Rotate a Chinese checkerboard
A Chinese checkerboard looks like this (based on this question, but this time it has a fixed size):

```
            G
           . G
          G G G
         G G . G
B B B B . . Y G . Y . Y Y
 B B B . . G . . . Y Y Y
  B . B . . . . . Y . Y
   B . . . . . . . . Y
    . . . . . . . . .
   . P . . . . . O O .
  P P . . . . . . . O O
 P P P . . . R . . O O .
P P P P . . R . . O O O O
         R . R R
          R R R
           R .
            R

```

Each non-space character in this example can be replaced by any non-space printable ASCII character in the input, while spaces are never changed. Note that it isn't guaranteed to be a valid arrangement in Chinese checker (such as it may not have exactly 7 different kind of characters).

Your task is to rotate it by a multiple of 60 degrees.

This is the above example rotated by 60 degrees clockwise:

```
            B
           B B
          B B B
         B . B B
P P P . . . B . . G G . G
 P P P P . . . . . G G G
  P P . . . . . G Y . G
   P . . . . . . . G G
    . . . . . . . . .
   R . . . . . . . . Y
  R . R R . . . . Y Y .
 R R R . . . O . . . Y Y
R . R R . . . O . Y Y Y Y
         O O O .
          O O O
           O .
            O

```

The input is a non-negative integer and a Chinese checkerboard. Your program (or function) should rotate it by the integer * 60 degrees. You decide whether to rotate clockwise or counterclockwise, as long as it is consistent. Both the input and output shouldn't have extra leading or trailing spaces.

This is code-golf. Shortest code wins.

# Answer
> 16 votes
# CJam, ~~61~~ ~~59~~ ~~43~~ ~~40~~ ~~38~~ 36 bytes

```
{{_N/eeSf.*:sW%zsS-\{_' >{;(}&+}/}*}

```

This is an anonymous function that expects a string and an integer on the stack.

*Thanks to @jimmy23013 for golfing off 19 bytes.*

Try it online in the CJam interpreter.

### Idea

We can assign an order to the printable characters of the checkerboards by reading them eastwards, then southwards.

This way, the original and rotated checkerboard

```
            G                                  B
           . G                                B B
          G G G                              B B B
         G G . G                            B . B B
B B B B . . Y G . Y . Y Y          P P P . . . B . . G G . G
 B B B . . G . . . Y Y Y            P P P P . . . . . G G G
  B . B . . . . . Y . Y              P P . . . . . G Y . G
   B . . . . . . . . Y                P . . . . . . . G G
    . . . . . . . . .                  . . . . . . . . .
   . P . . . . . O O .                R . . . . . . . . Y
  P P . . . . . . . O O              R . R R . . . . Y Y .
 P P P . . . R . . O O .            R R R . . . O . . . Y Y
P P P P . . R . . O O O O          R . R R . . . O . Y Y Y Y
         R . R R                            O O O .
          R R R                              O O O
           R .                                O .
            R                                  O

```

become

```
G.GGGGGG.GBBBB..YG.Y.YYBBB..G...YYYB.B.....Y.YB........Y..........P.....OO.PP.......OOPPP...R..OO.PPPP..R..OOOOR.RRRRRR.R

```

and

```
BBBBBBB.BBPPP...B..GG.GPPPP.....GGGPP.....GY.GP.......GG.........R........YR.RR....YY.RRR...O...YYR.RR...O.YYYYOOO.OOOO.O

```

respectively.

We can find the second sequence in the first checkerboard by reading its characters northeastwards, then southeastwards.

To achieve this in code, we start by prepending **n - 1** spaces to the **n**th row of the checkerboard (shown on the left). Then, we reverse the order of the rows (shown on the right).

```
            G                                                       R
            . G                                                   R .
            G G G                                               R R R
            G G . G                                           R . R R
    B B B B . . Y G . Y . Y Y                       P P P P . . R . . O O O O
      B B B . . G . . . Y Y Y                       P P P . . . R . . O O .
        B . B . . . . . Y . Y                       P P . . . . . . . O O
          B . . . . . . . . Y                       . P . . . . . O O .
            . . . . . . . . .                       . . . . . . . . .
            . P . . . . . O O .                   B . . . . . . . . Y
            P P . . . . . . . O O               B . B . . . . . Y . Y
            P P P . . . R . . O O .           B B B . . G . . . Y Y Y
            P P P P . . R . . O O O O       B B B B . . Y G . Y . Y Y
                      R . R R                       G G . G
                        R R R                       G G G
                          R .                       . G
                            R                       G

```

Finally, we transpose rows with columns:

```

            B

           BB

          BBB

         B.BB

    PPP...B..GG.G

    PPPP.....GGG

    PP.....GY.G

    P.......GG

    .........

   R........Y

  R.RR....YY.

 RRR...O...YY

R.RR...O.YYYY

OOO.

OOO

O.

O

```

The whitespace is all over the place, but the printable characters are in the correct order if we read them eastwards, then southwards.

All that's left to do is replacing the **n**th printable character of the original checkerboard by the **n**th printable character of the last modification.

### Code

```
                                   e# Stack: String B, Integer A
{                               }* e# Repeat A times:
 _N/                               e#   Push a copy of B and split it at linefeeds.
    ee                             e#   Enumerate the lines of B.
      Sf.*:s                       e#   Execute S.*s for each line:
                                   e#     [4 "abc"] -> "    abc"
            W%                     e#   Reverse the order of line lines.
              z                    e#   Zip; transpose rows with columns.
               s                   e#   Flatten the arrays of strings.
                S-                 e#   Remove spaces.
                                   e#   This pushes a string L.
                  \{          }/   e#   For each character C in the unmodified B:
                    _' >           e#     Check if C is bigger than ' '.
                        {  }&      e#     If it is:
                         ;(        e#      Discard C and shift out a char from L.
                             +     e#     Append a char (C or from L) to L.
                                   e#  L is B rotated by 60 degrees. Set L := B.

```

# Answer
> 11 votes
# Python 2, 171 bytes

```
def f(S,n):
 o="";E=enumerate;B=S.splitlines(1)
 for r,l in E(B):
  for c,q in E(l):z=r-8;y=6-(z+c)/2;x=-y-z;exec"x,y,z=-y,-z,-x;"*n;o+=q*(q<"!")or B[z+8][12-y+x]
 print o

```

This is perhaps the only time I've ever found `str.splitlines` useful — for all other times, `.split("\n")` is shorter.

Use like `f(S,10)`.

## Explanation

For each char in the input, we either:

* Keep it if it's a space or newline, or
* Replace it with the correct char otherwise

To figure out which char to replace with, we convert the grid to cube coordinates `(x, y, z)`, rotate `n` times by transforming `(x, y, z) -> (-y, -z, -x)`, then convert back.

---
Tags: code-golf, ascii-art, board-game, hexagonal-grid
---


title: Prime Nerd Sniping Pattern

text:
# Question
Title: Prime Nerd Sniping Pattern
*Longest day of the year - here's something to waste the extra time...*

---

## Overview

Note this is not a popularity contest and not a graphical output challenge - you are only required to output a string of 65,536 zeroes and ones. The Stack Snippet at the bottom of the question will display this as a 256 by 256 black and white image and calculate your official score. You can then save the image and upload it to your answer alongside your code (since the string output will not fit in a 30,000 character Stack Exchange answer).

---

## Scoring

The score of an image is the sum of the scores of its individual pixels. The score of an individual pixel is the sum of the subscores for each of the ***non-orthogonal***, ***prime distance*** pixels that are of ***opposite colour*** to the pixel being scored. The subscore for each such pixel is `1/p` where `p` is the prime distance.

In the context of this question, the terms have the following definitions:

* ***Non-orthogonal:*** A pixel is non-orthogonal to the pixel being scored if it is not in the same row and is not in the same column.
* ***Prime distance:*** A pixel is at a prime distance from the pixel being scored if they are separated by a Euclidean distance that is **exactly** a prime number. In particular, distance is the minimum distance measured toroidally - the top left pixel is a distance of `sqrt(2)` from the bottom right pixel (all 4 edges wrap).
* ***Opposite colour:*** A pixel is of opposite colour to the pixel being scored if their values sum to 1. That is, the first is 0 and the second is 1, or the first is 1 and the second is 0.

The Stack Snippet includes example code that shows how to score an image, but does not include any optimisations or an efficient approach, just correct code so scoring of final images can be done consistently.

*If anything in the code is not correct, please let me know either in the comments or in chat.*

JavaScript may not necessarily be the best language for *answering* this particular challenge. Note that the Snippet code deliberately gives no clues as to faster approaches. It will only have efficiencies introduced that have already been demonstrated in an existing answer.

---

## Visualisation

### The scoring pixels

For an intuitive feel for the distribution of the scoring pixels, here (in purple) are the non-orthogonal prime distance pixels for pixel (128, 128) of a 256 by 256 image:

---

### A random image

This is the randomly generated image from the example Python 3 answer. It has a score of 138,267.64 and gives you something to beat.

---

## Input

The code does not require input.

## Output

The code should output a string of 65,536 zeroes and ones, representing the pixels of a black and white 256 by 256 image. The digits should be a continuous string, with no separators. You may find copying and pasting easier if you output to a file, but this is up to you.

Your code may also output other information that you find useful, as long as the string can be copied and pasted into the Stack Snippet. For example, you may wish to output the best yet string to a file and the best yet score to STDOUT at regular intervals, allowing the user to choose when to stop the search.

---

### Stack Snippet

As pointed out by Sp3000, the snippet was taking 10 minutes to calculate a score, which is a little *too* slow, even for a deliberately inefficient reference implementation. I've edited in Sp3000's suggested improvement of precomputing the pixel offsets for the scoring, and it now takes a few seconds to calculate a score.

```
canvas = document.getElementById('canvas')
ctx = canvas.getContext('2d')
scoreArea = document.getElementById('scoreArea')
pastedData = document.getElementById('pastedData')
timeout = 0

primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499]

primesSquared = []
for (i=0; i<primes.length; i++) {
    primesSquared.push(primes[i] * primes[i])
}

width = canvas.width
height = canvas.height
area = width * height

scoringFilter = calculateScoringFilter()

function calculateScore() {
    var percentage = Math.floor(currentIndex / 65536 * 10000) / 100
    scoreArea.value = 'Calculating:' + percentage + '%'
    for (var t=0; t<1000; t++) {
        if (currentIndex < 65536) {
            partialScore += pixelScore(currentIndex)
            currentIndex += 1
        } else {
            scoreArea.value = 'Score: ' + partialScore
            return
        }
    }

    timeout = setTimeout(calculateScore, 10)
}

function pixelScore(i) {
    var score = 0
    var x = i % width
    var y = Math.floor(i / width)
    var a, b, xd, yd, j, k, d, m
    for (k=0; k<scoringFilter.length; k++) {
        bundle = scoringFilter[k]
        m = bundle[0]
        a = m % width
        b = Math.floor(m / width)
        j = ((x+a) % width) + width * ((y+b) % height)
        d = bundle[1]
        score += Math.abs(pixels[i] - pixels[j]) / d
    }
    return score
}

function display(pixels) {
    for (var i=0; i<area; i++) {
        ctx.fillStyle = pixels[i] ? 'white' : 'black'
        ctx.fillRect(i % width, Math.floor(i / width), 1, 1)
    }
}

function stop() {
    clearTimeout(timeout)
    scoreArea.value = 'Calculation cancelled.'
}

function isPrimeSquared(n) {
    return primesSquared.indexOf(n) > -1
}

function applyToImage() {
    var potentialPixels = []
    var pastedString = pastedData.value
    if (pastedString.length !== 65536) {
        scoreArea.value = 'Incorrect length:' + pastedString.length
        return
    }
    var i, digit
    for (i=0; i<pastedString.length; i++) {
        digit = pastedString.substring(i, i + 1)
        if (digit === '0') {
            potentialPixels.push(0)
        } else if (digit === '1') {
            potentialPixels.push(1)
        } else {
            scoreArea.value = 'Invalid character ' + i + ':' + digit
            return
        }
    }
    pixels = potentialPixels
    display(pixels)
    scoreArea.value = 'Calculating score...'
    partialScore = 0
    currentIndex = 0

    timeout = setTimeout(calculateScore, 10)
}

function calculateScoringFilter() {
    var scoringFilter = []
    var i, x, y, xd, yd
    for (i=0; i<area; i++) {
        x = i % width
        y = Math.floor(i / width)
        xd = Math.min(x,(-x+width)%width)
        yd = Math.min(y,(-y+height)%height)
        dSquared = xd*xd + yd*yd
        if (xd && yd && isPrimeSquared(dSquared)) {
            d = Math.sqrt(dSquared)
            scoringFilter.push([i, d])
        }
    }
    return scoringFilter
}
```

```
<canvas id='canvas' width='256' height='256'></canvas>
<br>
<input id='scoreArea' rows='1' readonly></input>
<br>
<button onclick='applyToImage()'>Apply string to image</button>
<button onclick='stop()'>Stop</button>
<br>
<br>
Paste in string of 65,536 zeroes and ones here:
<br>
<input id='pastedData'></input>
```

---

If you use the output or the code of another answer as the starting point for your own code, please remember to give credit and link to the supporting answer. Answers to this question do not need to credit the example answer or the code in the question.

Credit to Randall Munroe for the term ***Nerd Sniping***

# Answer
> 36 votes
# CJam, score 276496.9062958626

```
2,128*_(]128*

```

It turns out to be optimal, because: There aren't any non-orthogonal pairs with distance 2. So the distance must be odd, and so is the distance squared. As p2=x2+y2, one of x and y (squared or not) must be odd, and the other must be even. Those points are always in the opposite color in this image.

This and its negative are also the only optimal solutions. In an optimal solution, no non-orthogonal, prime distance pixels should have the same color. There are diagonally adjacent opposite pixels like (3,4) and (4,3). By filling pixels of the opposite of opposite color, etc, we can get a diagonal with the same color. Starting from each pixel in the diagonal, we can get all the anti-diagonals filled in the same way. Note that they wrap around. It is still optimal if they don't, though.

# Answer
> 1 votes
## Python 3, score 138267.64

This is a minimal answer as an example of what is required, and as something to beat...

It includes

* The language name.
* The score from the Stack Snippet in the question.
* The image saved from the Stack Snippet.
* The code used to produce the string of 65,536 zeroes and ones.

### Output

### Code

```
from random import random

output_string = ''
filename = '65536digits.txt'

for t in range(65536):
    digit = int(random() * 2)
    output_string += str(digit)

with open(filename, 'w') as output_file:
    output_file.write(output_string)

```

This is just an example. Python may not necessarily be the best language for competitive answers to this particular challenge.

---
Tags: code-challenge, primes
---