title: Dollar Bill Auction

text:
# Question
Title: Dollar Bill Auction
This is a KOTH challenge for the dollar bill auction game in game theory. In it, a dollar is being sold to the highest bidder. Bids go up in increments of 5¢, and the loser also pays their bid. The idea is that both players escalate the bidding war far beyond the value of a dollar in order to cut their losses.

Let's hope your bots are smarter than that.

You will be creating a bot to play this game by extending the `net.ramenchef.dollarauction.DollarBidder` class. You must implement the `nextBid` method that returns your bot's next bid given the other bot's previous bid. If necessary, you can also use the `newAuction` method to reset for each auction with the class of the opponent's bot.

```
public abstract class DollarBidder {
    /**
     * Used by the runner to keep track of scores.
     */
    long score = 0;

    /**
     * (Optional) Prepare for the next auction.
     *
     * @param opponent The class of the opponent's bot.
     */
    public void newAuction(Class<? extends DollarBidder> opponent) {}

    /**
     * Bid on the dollar. Bidding ends if the bid is
     * not enough to top the previous bid or both bids
     * exceed $100.
     *
     * @param opponentsBid How much money, in cents,
     *  that the opponent bid in the previous round. If
     *  this is the first round in the auction, it will
     *  be 0.
     * @return How much money to bid in this round, in
     *  cents.
     */
    public abstract int nextBid(int opponentsBid);
}

```

Bidding goes until one of the following happens:

* `nextBid` throws an exception. If this happens, the bot that threw the exception pays their previous bid, and the other bot gets the dollar for free.
* Either bot does not pay enough to top the previous bid. If this happens, both bots pay their bids (the loser pays their previous bid), and the winner gets a dollar.
* Both bots bid over $100. If this happens, both bots pay $100, and neither bot gets the dollar.

2 auctions are held for each combination of bots. Bots are scored by the total profit they made across those auctions. The highest score wins.

# Examples

## `GreedyBot`

```
import net.ramenchef.dollarauction.DollarBidder;

public class GreedyBot extends DollarBidder {
    @Override
    public int nextBid(int opponentsBid) {
        return opponentsBid + 5;
    }
}

```

## `OnlyWinningMove`

```
import net.ramenchef.dollarauction.DollarBidder;

public class OnlyWinningMove extends DollarBidder {
    @Override
    public int nextBid(int opponentsBid) {
        return 0;
    }
}

```

## `AnalystBot`

*Don't use this as a template for analytically-minded bots; use `ImprovedAnalystBot` instead.*

```
import net.ramenchef.dollarauction.DollarBidder;

// yes, this is a poor implementation, but I'm not
// going to waste my time perfecting it
public class AnalystBot extends DollarBidder {
    private DollarBidder enemy;

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        try {
            enemy = opponent.newInstance();
            enemy.newAuction(this.getClass());
        } catch (ReflectiveOperationException e) {
            enemy = null;
        }
    }

    @Override
    public int nextBid(int opponentsBid) {
        if (enemy == null)
            return 0;

        return enemy.nextBid(95) >= 100 ? 0 : 95;
    }
}

```

## `AnalystKiller`

```
import net.ramenchef.dollarauction.DollarBidder;

public class AnalystKiller extends DollarBidder {
    private static int instances = 0;
    private final boolean tainted;

    public AnalystKiller() {
        this.tainted = instances++ != 0;
    }

    @Override
    public int nextBid(int opponentsBid) {
        if (tainted)
            throw new RuntimeException("A mysterious error occurred! >:)");

        return 0;
    }
}

```

# Additional Rules

* Standard loopholes are forbidden.
* Sabotaging other bots is allowed, but attempting to alter field/method visibility will result in mysterious `SecurityException`s. An exception is causing another bot to break the 500ms limit.
* Bots cannot access the runner package except to extend the `DollarBidder` class.
* All methods should return in 500ms or less.
* Bots do not need to be deterministic.
* Your bid does *not* need to be a multiple of 5¢.
* $1=100¢
* Results will be posted on April 24, 2018.

Runner on GitHub

# Results

View the individual rounds here.

```
MTargetedBot: $14.30
BuzzardBot: $9.83
BluffBot: $9.40
RiskRewardBot: $9.35
SecretBot: $8.50
LuckyDiceBot: $7.28
CounterBot: $6.05
MBot: $5.40
StackTraceObfuscaterBot: $5.20
EvilBot: $4.80
MarginalBot: $4.60
TargetValueBot: $4.59
InflationBot: $4.27
UpTo200: $4.20
InsiderTradingBot: $1.90
MimicBot: $1.50
BorkBorkBot: $1.22
DeterrentBot: $0.95
MarginalerBot: $0.00
RandBot: $-4.45
BreakEvenAsap: $-7.00
AnalystOptimizer: $-13.95
DeterredBot: $-1997.06
ScoreOverflowBot: $-21474844.15
MirrorBot: $-21475836.25

```

Congratulations to `MTargetedBot` with a profit of $14.30!

# Answer
# MTargetedBot

```
public class MTargetedBot extends MBot {

    @Override
    protected int calcBid(int opponentsBid, boolean isPeeking, boolean isSubPeeking) {
        Class c = this.rivalClass;

        switch (c.getSimpleName()) {
            case "AnalystBot":
                if (isPeeking && !isSubPeeking) {
                    throw new RuntimeException();
                } else if (isPeeking) {
                    return 66666;
                }
                break;
            case "MirrorBot":
                if (isPeeking && !isSubPeeking) {
                    throw new RuntimeException();
                } else if (isPeeking) {
                    return 0;
                }
                break;
            case "GreedyBot":
            case "LuckyDiceBot":
            case "InflationBot":
            case "TargetValueBot":
                // not playing with ya
                return 0;
            case "MimicBot":
            case "BuzzardBot":
            case "MarginalBot":
            case "MarginalerBot":
            case "BluffBot":
            case "MBot":
                // go away, gimme easy money
                return isPeeking ? 66666 : 5;
            case "RandBot":
                // me or noone
                return 100;
            case "SecretBot":
                return 10;
            case "AnalystKiller":
            case "OnlyWinningMove":
            case "EvilBot":
            case "StackTraceObfuscaterBot":
                // easy
                return opponentsBid + 5;
        }

        return super.calcBid(opponentsBid, isPeeking, isSubPeeking);
    }
}

```
* Based on updated MBot
* Uses similar method like CounterBot, but with some methods refined to harder hit some of it opponents, also should be more readable
* On unknown opponent default to MBot strat
> 2 votes

# Answer
# MimicBot

```
import net.ramenchef.dollarauction.DollarBidder;

import java.util.Set;
import java.util.HashSet;

public class MimicBot extends AbstractAnalystCounterBot {

    private final Set<Class<? extends DollarBidder>> bidders = new HashSet<>();
    private DollarBidder reference = null;

    // A benchmark class. Not MarginalBot because of proposed rule changes.
    public static class BidFive extends DollarBidder {
        public int nextBid(int o) {
            return 5;
        }
    }

    public MimicBot() {
        bidders.add(OnlyWinningMove.class);
        bidders.add(GreedyBot.class);
        bidders.add(BidFive.class);
    }

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        DollarBidder enemy;
        reference = null;
        try {
            enemy = opponent.newInstance();
        } catch (Throwable t) {
            return;
        }

        if (!bidders.contains(opponent))
            bidders.add(opponent);

        Class<? extends DollarBidder> leader = OnlyWinningMove.class;
        int best = 0;

        for (Class<? extends DollarBidder> audition : bidders) {
            try {
                enemy.newAuction(MimicBot.class);
            } catch (Throwable t) {
                reference = new GreedyBot(); // Deterrence.
                break;
            }

            DollarBidder tryout;
            try {
                tryout = audition.newInstance();
                tryout.newAuction(opponent);
            } catch (Throwable t) {
                continue;
            }

            int tryoutScore = -100000;
            /* This code was copy-pasted from the *
             * runner, with significant changes. */
            int bid1 = 0, bid2 = 0;
            while (true) {
                int next;
                try {
                    next = enemy.nextBid(bid2);
                } catch (Throwable t) {
                    tryoutScore = 100;
                    break;
                }
                if (next < bid2 + 5) {
                    if (bid2 > 0) {
                        tryoutScore = 100 - bid1;
                    }
                    break;
                }
                if (next > 10000 && bid2 > 10000) {
                    tryoutScore = -10000;
                    break;
                }
                bid1 = next;

                try {
                    next = tryout.nextBid(bid1);
                } catch (Throwable t) {
                    tryoutScore = -bid2;
                    break;
                }
                if (next < bid1 + 5) {
                    tryoutScore = -bid2;
                    break;
                }
                if (next > 10000 && bid1 > 10000) {
                    tryoutScore = -10000;
                    break;
                }
                bid2 = next;
            }
            /* End of copy-pasted code. */

            if (tryoutScore > best) {
                best = tryoutScore;
                leader = audition;
            }
        }

        try {
            reference = leader.newInstance();
        } catch (Throwable t) {
            reference = new OnlyWinningMove();
        }
        reference.newAuction(opponent);
    }

    @Override
    public int nextBid(int opponentsBid) {
        try {
            return reference.nextBid(opponentsBid);
        } catch (Throwable t) {
            return 5;
        }
    }
}

```

Holy cow. I expected this to be simple to write, then subsequently spent 3 hours on it.

In essence, `MimicBot` keeps a running list of the available bots. When it goes to a new auction, it runs through the list in search of the most effective one against the current opponent. It then uses that bot as a "reference" in the auction.

For testing purposes, it would be best to use either a randomized subset of the submissions or the full set. It starts with `GreedyBot`, `MimicBot`, and one more bot that just bids 5¢.
> 15 votes

# Answer
# InsiderTradingBot

In the spirit of @StephenLeppik's answer, InsiderTradingBot knows all of his opponents and understands their strategies. Your move, Stephen.

```
import net.ramenchef.dollarauction.DollarBidder;

public class InsiderTradingBot extends DollarBidder {
  private static boolean analystNutcracker = false;
  private int bid;

  @Override
  public void newAuction(Class<? extends DollarBidder> opponent) {
    if (opponent.equals(DeterredBot.class) ||
        opponent.equals(OnlyWinningMove.class) ||
        opponent.equals(MirrorBot.class)) {
      // I can do this ^.^
      bid = 5;
    } else if (opponent.equals(AnalystKiller.class)) {
      // Outbid 'em >:D
      bid = 10;
    } else if (opponent.equals(BreakEvenAsap.class) ||
               opponent.equals(BorkBorkBot.class) ||
               opponent.equals(DeterrentBot.class)) {
      // Break even quicker!
      bid = 100;
    } else if (opponent.equals(InsiderTradingBot.class)) {
      // I'm probably a simulation inside MirrorBot
      bid = 0;
    } else if (opponent.equals(Analyst.class)) {
      // Let's fight the Analyst with the power of global variables
      bid = 100;
      analystNutcracker = true;
    } else {
      // Welp
      bid = 0;
    }
  }

  @Override
  public int nextBid(int opponentsBid) {
    if ((opponentsBid == 95) && analystNutcracker) {
      analystNutcracker = false;
      return 0;
    }
    return bid;
  }

};

```
> 11 votes

# Answer
# MirrorBot

Makes the enemy play against itself.

```
import net.ramenchef.dollarauction.DollarBidder;

public class MirrorBot extends DollarBidder{

    private DollarBidder enemy;

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        try {
            enemy = opponent.newInstance();
            enemy.newAuction(this.getClass());
        } catch (ReflectiveOperationException e) {
            enemy = null;
        }
    }

    @Override
    public int nextBid(int opponentsBid){
        if (enemy == null)
            return (opponentsBid >= 95) ? 0 : (opponentsBid + 5);
        try {
            return enemy.nextBid(opponentsBid);
        } catch (Throwable e) {
            System.out.println("haha no");
            return (opponentsBid >= 95) ? 0 : (opponentsBid + 5);
        }
    }
}

```
> 8 votes

# Answer
**Edit**: Targeted changes in the DollarBidder class has broken this bot.

# ScoreOverflowBot

```
import net.ramenchef.dollarauction.DollarBidder;

public class ScoreOverflowBot extends DollarBidder {
  boolean betBig = true;

  @Override
  public int nextBid(int opponentsBid) {
    if(betBig)
    {
      betBig = false;
      return 2147483645;
    }
    else
      return 105;
  }
}

```

After 1 auction, its score will be -2147483645 but the next time it will lose 5¢ or 105¢ making the score positive and very big. All other losses would then be negligible.

On the first auction, it would also make GreedyBot bet -2147483646 which isn't divisible by 5.
> 8 votes

# Answer
# TargetValueBot

```
import java.util.Random;
import net.ramenchef.dollarauction.DollarBidder;

public class TargetValueBot extends DollarBidder {
    private int target;

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        Random rand = new Random();
        target = 100;
        for (int i = 0; i < 20; i++) {
            target += rand.nextInt(2) * 10 - 5;
        }
    }

    @Override
    public int nextBid(int opponentsBid) {
        if (opponentsBid >= target) {
            return 0;
        } else {
            return opponentsBid + 5;
        }
    }
}

```

Can't test this at the moment, so please let me know if it's broken.

Basically, pick a value for the dollar, and outbid the opponent until we exceed that value.
> 7 votes

# Answer
# MarginalBot

```
import net.ramenchef.dollarauction.DollarBidder;

public class MarginalBot extends DollarBidder {
    private DollarBidder rival;

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        try {
            rival = opponent.newInstance();
            rival.newAuction(this.getClass());
        } catch (Throwable t) {
            try {
                rival = opponent.newInstance();
                rival.newAuction(null);
            } catch (Throwable h) {
                rival = null;
            }
        }
    }

    @Override
    public int nextBid(int opponentsBid) {
        if (opponentsBid == 0) {
            try {
                if (rival.nextBid(5) < 10) {
                    return 5;
                }
            } catch (Throwable t) {
                //do nothing.
            }
        }
        return 0;
    }
}

```

Very simple, it tries to determine whether an opponent would contest a minimal bid and, if not, places it.

# MarginalerBot

```
import net.ramenchef.dollarauction.DollarBidder;

public class MarginalerBot extends DollarBidder {
    private DollarBidder rival;
    private int bidCount;

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        bidCount = 0;

        try {
            rival = opponent.newInstance();
            rival.newAuction(this.getClass());
        } catch (Throwable t) {
            try {
                rival = opponent.newInstance();
                rival.newAuction(null);
            } catch (Throwable h) {
                rival = null;
            }
        }
    }

    @Override
    public int nextBid(int opponentsBid) {
        bidCount += 1;

        for (int iBid = opponentsBid + 5; iBid < 100; iBid = iBid + 5) {
            if (bidCount > 0) {
                break;
            }

            try {
                if (rival.nextBid(iBid) < iBid + 5) {
                    return iBid;
                }
            } catch (Throwable t) {
                //do nothing.
            }
        }
        return 0;
    }
}

```

A new, smarter version of MarginalBot that checks to see if it can make any money-making move without contest, rather than just hoping to win with the minimum.

Since its in the same family as my previous bot, but sidesteps strategies trying to beat it, I figured a new entry in the same post was the most reasonable way of presenting it.

**Edit 1:** Made a small change to the newAuction method to optimise against other analyser-type bots.

**Edit 2:** Made a change to MarginalerBot to minimise losses against sneaky or non-deterministic strategies.
> 7 votes

# Answer
## BorkBorkBot

```
import net.ramenchef.dollarauction.DollarBidder;

public class BorkBorkBot extends DollarBidder{
  @Override
  public int nextBid(int opponentsBid){
    return (opponentsBid >= 95) ? 0 : (opponentsBid + 5);
  }
}

```

Gives up if it can't break even.
> 6 votes

# Answer
# DeterrentBot

```
import net.ramenchef.dollarauction.DollarBidder;

public class DeterrentBot extends DollarBidder {
    @Override
    public int nextBid(int opponentsBid) {
        return opponentsBid > 5 ? 100 : opponentsBid + 5;
    }
}

```

Attempts to persuade any analytically-minded bots that the only winning move is not to play.
> 6 votes

# Answer
## `RandBot`

```
import net.ramenchef.dollarauction.DollarBidder;
import java.util.concurrent.ThreadLocalRandom;

public class RandBot extends DollarBidder {

    @Override
    public int nextBid(int opponentsBid) {
        return ThreadLocalRandom.current().nextInt(21) * 5;
    }
}

```

It had to be done.
> 6 votes

# Answer
# LuckyDiceBot

LuckyDiceBot only trusts his dice. He rolls two dice, adds the sum to the current bidder's value, and bids that much. If it's not enough to overcome the opponent's bid, he cuts his losses and goes on his way.

```
import net.ramenchef.dollarauction.DollarBidder;
import java.util.Random;

public class LuckyDiceBot extends DollarBidder {
  private Random random;

  public LuckyDiceBot() {
    random = new Random();
  }

  @Override
  public int nextBid(int opponentsBid) {
    int d1 = random.nextInt(6) + 1;
    int d2 = random.nextInt(6) + 1;
    return opponentsBid + d1 + d2;
  }

};

```
> 5 votes

# Answer
# DeterredBot

```
import net.ramenchef.dollarauction.DollarBidder;

public class DeterredBot extends DollarBidder {
    private int deterrence;
    public void newAuction(Class<? extends DollarBidder> opponent) {
        if (opponent.equals(DeterrentBot.class)) {
            deterrence = 1;
        } else if (opponent.equals(LuckyDiceBot.class)) {
            deterrence = -1;
        } else {
            deterrence = 0;
        }
    }
    @Override
    public int nextBid(int opponentsBid) {
        switch (deterrence) {
        case 0:
            return 0;
        case -1:
            return opponentsBid + 5;
        case 1:
            // Holy shit, the fuzz! Hide the money!
            return 100001;
        }
        throw new RuntimeException("Darn hackers!");
    }
}

```

DeterredBot makes a fortune off of his illegal gambling with LuckyDiceBot. So of course when the police (DeterrentBot) arrive, he has to quickly dispose of his earnings in some way, such as bidding on the next auction.
> 5 votes

# Answer
# BreakEvenAsap

```
import net.ramenchef.dollarauction.DollarBidder;

public class BreakEvenAsap extends DollarBidder{
  @Override
  public int nextBid(int opponentsBid){
    // If the opponent has bid 100 or more: bid 0 to break even and let them win
    return opponentsBid >= 100 ? 0
    // Else: bid 100 to break even (and possibly win)
     : 100;
  }
}

```

**Scenarios**

* If the opponent may start and bids `<= 0` they lose.
* If the opponent may start and bids `[5,95]`: bid 100 yourself. Either your opponent stops now, or will bid above 100 in total, in which case you stop bidding to let them have the win and break even yourself.
* If the opponent may start and bids `>= 100`: bid 0 yourself to lose but break even.
* If you may start: bid 100 right away. Either your opponent stops now, or will bid above 100, in which case you stop bidding to let them have the win and break even yourself.
> 4 votes

# Answer
# Non-competing: AbstractAnalystCounterBot

```
import net.ramenchef.dollarauction.DollarBidder;

import java.util.Set;
import java.util.HashSet;

public abstract class AbstractAnalystCounterBot extends DollarBidder {

public AbstractAnalystCounterBot() {
    if (isPeeking())
        throw new RuntimeException();
}

    protected boolean isPeeking() {
        StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        for (StackTraceElement ste : stackTrace) {
            Class<?> clazz;
            try {
                clazz = Class.forName(ste.getClassName());
            } catch (ClassNotFoundException | SecurityException e) {
                continue;
            }
            if (DollarBidder.class.isAssignableFrom(clazz) && !clazz.isAssignableFrom(this.getClass()))
                return true;
        }
        try {
            return Class.forName(stackTrace[0].getClassName()).getPackage().getName().equals("net.ramenchef.dollarauction");
        } catch (Exception e) {
            return true;
        }
    }
}

```

This is not intended as a true submission, but rather as some boilerplate for others to use to deter pet-keeping bots like `MirrorBot` and `MimicBot`.

Since it's the default constructor, there's no need to call it in your subclass. It implements an `isPeeking` method to determine if another bot is snooping.
> 4 votes

# Answer
# InflationBot

```
import net.ramenchef.dollarauction.DollarBidder;

public class InflationBot extends DollarBidder {
    private int target = -5;

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        target += 5;
    }

    @Override
    public int nextBid(int opponentsBid) {
        if (opponentsBid >= target) {
            return 0;
        } else {
            return opponentsBid + 5;
        }
    }
}

```

Can't test this at the moment, so please let me know if it's broken.

Each round, the value of the dollar goes up.
> 4 votes

# Answer
# AnalystOptimizer

```
import net.ramenchef.dollarauction.DollarBidder;

public class AnalystOptimizer extends DollarBidder{

    private DollarBidder enemy;

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        try {
            enemy = opponent.newInstance();
            enemy.newAuction(this.getClass());
        } catch (ReflectiveOperationException e) {
            enemy = null;
        }
    }

    @Override
    public int nextBid(int opponentsBid){
        if (enemy == null)
            return (opponentsBid >= 95) ? 0 : (opponentsBid + 5);
        int nb = 0;
        try {
            return enemy.nextBid(95) >= 100 ? 95 : 0;
        } catch (Throwable e) {
            System.out.println("haha no");
            return 95;
        }
    }
}

```

cobbled together from parts of other bots. this one plays by trying to be AnalystBot, and if unsuccessful, becomes BorkBorkBot.

I don't think this one will do that well.
> 3 votes

# Answer
# CounterBot

```
import net.ramenchef.dollarauction.DollarBidder;

public class CounterBot extends DollarBidder {
  private Class<? extends DollarBidder> enemy;

  @Override
  public void newAuction(Class<? extends DollarBidder> opponent){
    this.enemy = opponent;
  }

  @Override
  public int nextBid(int opponentsBid) {
    if(this.enemy.equals(CounterBot.class))
      throw new RuntimeException("Here boy, catch!");

    return this.enemy.equals(DarthVader.class) ||
           this.enemy.equals(MirrorBot.class) ||
           this.enemy.equals(OnlyWinningMove.class) ||
           this.enemy.equals(AnalystKiller.class) ||
           this.enemy.equals(DeterredBot.class) ||
           this.enemy.equals(InsiderTradingBot.class) ||
           this.enemy.equals(RiskRewardBot.class) ||
           this.enemy.equals(ImprovedAnalystBot.class) ?
            5
         : this.enemy.equals(MarginalBot.class) ?
           opponentsBid == 0 ? 5 : 10
         : this.enemy.equals(AnalystBot.class) ||
           this.enemy.equals(AnalystOptimizer.class) ?
            opponentsBid == 95 ? 100 : 5
         : this.enemy.equals(TargetValueBot.class) ?
            opponentsBid < 190 ? opponentsBid + 5 : 200
         : this.enemy.equals(BorkBorkBot.class) ?
            opponentsBid < 90 ? opponentsBid + 5 : 95
         : this.enemy.equals(DeterrentBot.class) ?
            105
         : this.enemy.equals(BreakEvenAsap.class) ?
            opponentsBid == 100 ? 105 : 100
         : this.enemy.equals(LuckyDiceBot.class) ?
            opponentsBid == 0 ? 5 : 0
         : this.enemy.equals(RandBot.class) ||
           this.enemy.equals(UpTo200.class) ||
           this.enemy.equals(SecretBot.class) ||
           this.enemy.equals(BluffBot.class) ||
           this.enemy.equals(EvilBot.class) ?
            opponentsBid + 5
         : this.enemy.equals(MimicBot.class) ? // TODO: Find actual counter
            10
         : this.enemy.equals(MarginalerBot.class) ||
           this.enemy.equals(MBot.class) ||
           this.enemy.equals(StackTraceObfuscaterBot.class) ||
           this.enemy.equals(MSlowBot.class) ?
            opponentsBid < 95 ? 90 : opponentsBid == 95 ? 100 : 95;
         : this.enemy.equals(BuzzardBot.class) ?
            100
         : this.enemy.equals(ScoreOverflowBot.class) ?
            opponentsBid == 105 ? 110 : 0
         : //this.enemy.equals(GreedyBot.class) ||
           //this.enemy.equals(RichJerk.class) ||
           //this.enemy.equals(InflationBot.class) ?
           // TODO: More bots?
            0;
  }
}

```

**Counters:**

* `DarthVader` counters itself by causing a `SecurityException` before the bidding starts, but I'll bid 5 just in case.
* `AnalystBot` and `AnalystOptimizer` will both look at my answer when I bid 95, in which case I'll show I bid 100 so it will bid 95 itself. I will bid 5 however if I start (or 100 if they've started), so they lose 95 cents and I either win the 1 USD bill by only bidding 5 cents, or by breaking even.
* `MirrorBot` will bid what I would bid against it. So I'll just bid 5, and whoever begins wins 95 cents, and the other loses 5 cents.
* `MarginalBot` will bid 5 if I would bid less than 10 (or what it starts), otherwise it will bid 0. So if I just bid 5 when I start, or 10 when it starts, I win either 95 or 90 cents, and they lose 5 cents.
* `GreedyBot` always bids 5 more than me, so just bid 0 to break even and let them have the win
* `OnlyWinningMove` and `AnalystKiller` both always bids 0, so just bid 5 to win
* `TargetValueBot` will bid in the range `[100,200]`, so bid 5 more every time until they're at 190, in which case we raise to 200 to break even by winning the dollar (and let them lose 190 or 195 depending on who started)
* `BorkBorkBot` will bid in the range `[5,95]`, so bid 5 more every time as well. As soon as they bid either 85 or 90 (depending on who started), bid 95 yourself. They'll lose 85 or 90 cents, and you win the 1 USD bill for a 5 cents profit.
* `DeterrentBot` will bid 5 if they start or 100 if we start, so just bid 105 so they counter with 100, causing them to lose 100 and us to lose just 5 cents by winning the 1 USD bill.
* `BreakEvenAsap` will bid 100 right away. So if they've started with their bid of 100, counter with 105 to win 95 cents and let them lose 100. If we may start just bid 100 so we both break even.
* `RichJerk` will bid 10,001 right away, so just bid 0 to break even and let them lose 9,901.
* `DeterredBot` doesn't know me and will therefore bid 0, so just bid 5 to win.
* `LuckyDiceBot` keeps on bidding till it wins. So if we started, bid 5 in the hope they bid as high as possible to win the dollar. If they've started just bid 0 to let them have the win and break even yourself.
* `RandBot` will bid random in the range `[5,100]`, so just bid 5 more until it stops, in which case you've won 95 cents and they've lost `0-100`.
* `UpTo200` will (as the name states) bid up to 200. So just bid 5 higher until they stop. We'll win the 1 USD bill and take a total loss of 105 cents, they however lose 200 cents.
* `InsiderTradingBot` doesn't know me, so just bid 5 cents to win
* `MimicBot` was the hardest. Just bid 10 to either start with or counter their first bid of 5. If they try to access me I will throw a RuntimeException (which they will catch in which case it would act as if I had bid 100 instead - although it will break the inner while-loop). Based on the enemies it has in it's HashSet a different thing happens. I'll have to revisit and look more closely to see if there is an actual counter.
* `RiskRewardBot` doesn't know me so will just bid 5, in which case I will bid 5 to win.
* `MarginalerBot` will bit up to 100 depending on what I would bid. If I may start, I will bid 90, then it will bid 95, then I will bid 100 so it will bid 0 and lose 95 cents, while I win the 1 USD bill and break even. If it may start instead, it sees I would bid 90 against it, so it bids 90 itself, then I will bid 95 so it will bid 0 and lose 90 cents, while I win the 1 USD bill with a 5 cent profit.
* `BuzzardBot` will analyze all my counters in the range `[0,100)`. If I bid `100` right away it use `oppFlag = 0` and the complete 100-sized array will contain 100x the value 100. In the switch `case 0`, the loop will be in the range `[0,100)` again, and since `i + 5` will at most be 104, the if `bids[i] < i + 5` won't ever be true, so the bid it does remains 0.
* `ImprovedAnalystBot` will always have `this.enemy = null` because his opponent is `CounterBot`, not itself. So it will always bid 0, which I just counter with a bid of 5.
* `InflationBot` will bid 0 to break even when it starts, otherwise it will keep bidding 5. So just bid 0 ourselves to break even right away and let them have the win.
* `ScoreOverflowBot` will either bid near `Integer.MAX_VALUE` if they may start, otherwise they'll bid `105`. So if they've bid 105 just bid 110 ourselves (they'll lose 105, we'll lose 10), otherwise just bid 0 to let them have the win.
* `MBot` is the same as `MarginalerBot`, but with added protection against 'peeking' opponents. Since I don't 'peek', it's basically the same as `MarginalerBot`.
* `SecretBot` will have his `isPeeking()` method return false, so if it may start or if I bid 5, it will bid 5 or 10 respectively. Otherwise it will bid 0. So whether I start or not, `opponentsBid + 5` would cause me to win either way, either with my 10 cents or 15 cents bid, causing them to loose either 5 or 10 cents.
* `BluffBot` will look at what I would bid when his bid is 95, and if this is larger than or equal to 100 it will bid 0 to break even, otherwise it will bid `opponentsBid + 5`. So I'll just bid `opponentsBid + 5`. It'll break even regardless of who starts, and I win either 100 or 95 cents depending on whether I have started or not.
* `StackTraceObfuscaterBot` will act the same as `MarginalerBot`.
* `EvilBot` will always bid 5, so just bid `opponentsBid + 5`. Either way they'll loose those 5 cents, and we'll win the 1 USD bid (either with a 5 cents bid if we've start, or 10 cents bid if they've started).
* `MSlowBot` is the same as `MBot` and therefore also `MarginalerBot`.

Let me know if you see any typos or flaws in my counters.
> 3 votes

# Answer
# RiskRewardBot

```
import net.ramenchef.dollarauction.DollarBidder;

public class RiskRewardBot extends DollarBidder {
    private int target;

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        if (opponent.equals(OnlyWinningMove.class) ||
            opponent.equals(DeterredBot.class) ||
            opponent.equals(MirrorBot.class) ||
            opponent.equals(AnalystKiller.class) ||
            opponent.equals(RiskRewardBot.class)) {
            target = 5;
        } else if (opponent.equals(MarginalBot.class) ||
            opponent.equals(EvilBot.class)) {
            target = 10;
        } else if (opponent.equals(SecretBot.class)) {
            target = 15;
        } else if (opponent.equals(BorkBorkBot.class)) {
            target = 95;
        } else if (opponent.equals(MarginalerBot.class) ||
             opponent.equals(BluffBot.class) ||
             opponent.equals(BuzzardBot.class)) {
            target = 100;
        }
        } else {
            target = 0;
        }
    }

    @Override
    public int nextBid(int opponentsBid) {
        if (opponentsBid >= target) {
            return 0;
        } else if (target > 10 && opponentsBid == target - 10) {
            return target;
        } else {
            return opponentsBid + 5;
        }
    }
}

```

Can't test this at the moment, so please let me know if it's broken.

The goal is to get the highest total score, so don't worry about beating anyone. Just take the easy wins, and don't waste money on possible losses.
> 3 votes

# Answer
# BuzzardBot

```
import java.util.Random;

import net.ramenchef.dollarauction.DollarBidder;

public class BuzzardBot extends DollarBidder {

    private int[] bids = new int[100];
    private int oppFlag = 0;

    public void newAuction(Class<? extends DollarBidder> opponent) {
        oppFlag = 0;
        if(isPeeking()) {
            oppFlag = 3;
            return;
        }
        try {
            DollarBidder enemy = opponent.newInstance();
            enemy.newAuction(this.getClass());
            // a simple (and fallible) determinism check
            int sample = new Random().nextInt(100);
            int a = enemy.nextBid(sample);
            int b = enemy.nextBid(sample);
            int c = enemy.nextBid(sample);
            if ((a - b) * (b - c) != 0) {
                oppFlag = 2;
                return;
            }
            for (int i = 0; i < 100; i++) {
                bids[i] = enemy.nextBid(i);
            }
        } catch (Throwable t) {
            oppFlag = 1;
        }
    }

    @Override
    public int nextBid(int opponentsBid) {
        switch (oppFlag) {
        case 0:
            // assume the opponent's nextBid function depends only on the bid provided, and
            // make the bid that yields the biggest profit possible accordingly
            int best = 0;
            int bid = 0;
            for (int i = 0; i < 100; i++) {
                if (bids[i] < i + 5) {
                    int gain = (i >= opponentsBid + 5) ? 100 - i : -i;
                    if (gain > best) {
                        best = gain;
                        bid = i;
                    }
                }
            }
            return bid;
        case 1:
            // act like BorkBorkBot against anything that tries to foil analysis with an
            // Exception
            return (opponentsBid >= 95) ? 0 : (opponentsBid + 5);
        case 3:
            // bid aggressively against opposing analysts
            return Math.min(opponentsBid + 5, 100);
        case 2:
        default:
            // place an opening bid against something unpredictable, as it might yield 95c
            // profit, and failure has a low cost.
            return (opponentsBid == 0) ? 5 : 0;
        }
    }

    private static boolean isPeeking() {
        final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        for (StackTraceElement ste : Arrays.copyOfRange(stackTrace, 3, stackTrace.length)) {
            Class<?> clazz;
            try {
                clazz = Class.forName(ste.getClassName());
            } catch (ClassNotFoundException e) {
                return true;
            }
            if (DollarBidder.class.isAssignableFrom(clazz))
                return true;
        }
        return false;
    }
}

```

Tries to evaluate the opponent it's faced with, and make sure to not bite off more than it can chew.
> 3 votes

# Answer
# BluffBot

```
import net.ramenchef.dollarauction.DollarBidder;

public class BluffBot extends DollarBidder {

private DollarBidder enemy;

@Override
public void newAuction(Class<? extends DollarBidder> opponent){
  try {
    this.enemy = opponent.newInstance();
    enemy.newAuction(this.getClass());
} catch (Throwable e) {
    enemy = null;
}
}

@Override
public int nextBid(int opponentsBid) {
    //Is this a legit call?
    for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
        Class<?> clazz;
        try {
            clazz = Class.forName(ste.getClassName());
            if (DollarBidder.class.isAssignableFrom(clazz) && !clazz.isAssignableFrom(this.getClass())) {
                return 100000;
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //Play it safe against strangers
    int enemyMaxBid;
    try{
        enemyMaxBid = enemy.nextBid(95);
    }
    catch (Throwable t){
        enemyMaxBid = 0;
        enemy = null;
    }
    if(enemy == null) return opponentsBid <= 5 ? opponentsBid + 5 : 0; //Hazard a 5c guess because of how many bots fold instantly.

    //If there's profit to be had, get there as cheaply as possible. Otherwise, best outcome is zero.
    return enemyMaxBid >= 100 ? 0 : opponentsBid + 5;
}

}

```

A spy you know of is more valuable than no spy at all...

If someone else tries to call the getBid method, BluffBot responds with $100 to trick them into either quitting or betting really high.

Otherwise, see if it's possible to win for under $1, and just don't bid if it's not.
> 3 votes

# Answer
# EvilBot

```
import java.util.Arrays;

import net.ramenchef.dollarauction.DollarBidder;

public class EvilBot extends DollarBidder {

    @Override
    public int nextBid(int opponentsBid) {
        if (isPeeking()) {
            throw new Error("HaHa!");
        } else {
            return 5;
        }

    }

    private static boolean isPeeking() {
        final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        for (StackTraceElement ste : Arrays.copyOfRange(stackTrace, 3, stackTrace.length)) {
            Class<?> clazz;
            try {
                clazz = Class.forName(ste.getClassName());
            } catch (ClassNotFoundException e) {
                return true;
            }
            if (DollarBidder.class.isAssignableFrom(clazz))
                return true;
        }
        return false;
    }

}

```

Throws an Error instead of an Exception to confound analysts.
> 3 votes

# Answer
# UpTo200

```
import net.ramenchef.dollarauction.DollarBidder;

public class UpTo200 extends DollarBidder{
  @Override
  public int nextBid(int opponentsBid){
    // If the current bid of the opponent is in the range [0,195]: raise the bid by 5
    return opponentsBid <= 195 ? opponentsBid + 5
    // Else: Give up
     : 0;
  }
}

```
> 2 votes

# Answer
# Darth Vader

```
import java.lang.reflect.Field;
import net.ramenchef.dollarauction.DollarBidder;

public class DarthVader extends DollarBidder
{
@Override
public void newAuction(Class<? extends DollarBidder> opponent) {
    //set all values in the integer cache to over the $100 limit except 0
    Class icache = Integer.class.getDeclaredClasses()[0];
    Field c = icache.getDeclaredField("cache");
    c.setAccessible(true);
    Integer[] cache = (Integer[]) c.get(cache);
    for(sbyte b=0;b<128;b++)
    {
     cache[b]=100001;
    }
}

@Override
public int nextBid(int opponentsBid)
{
    return 0;
}
}

```

This one tries to force the opponent's bot to overpay by setting the integer cache to the value over the $100 limit.
> 2 votes

# Answer
# SecretBot

```
import java.util.Arrays;

import net.ramenchef.dollarauction.DollarBidder;

public class SecretBot extends DollarBidder {

    @Override
    public int nextBid(int opponentsBid) {
        if (isPeeking()) {
            return opponentsBid;
        } else if (opponentsBid < 10) {
            return opponentsBid + 5;
        } else {
            return 0;
        }

    }

    private static boolean isPeeking() {
        final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        for (StackTraceElement ste : Arrays.copyOfRange(stackTrace, 3, stackTrace.length)) {
            Class<?> clazz;
            try {
                clazz = Class.forName(ste.getClassName());
            } catch (ClassNotFoundException e) {
                return true;
            }
            if (DollarBidder.class.isAssignableFrom(clazz))
                return true;
        }
        return false;
    }

}

```

This bot makes minimal attempts to win by bidding 5 or 10. He also checks the stack trace to see if he was called by another Bot and then lies to them about what bids he'll make.
> 2 votes

# Answer
# StackTraceObfuscaterBot

```
import net.ramenchef.dollarauction.DollarBidder;

import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;

public class StackTraceObfuscaterBot extends DollarBidder {
    private volatile static boolean created = false;
    private volatile DollarBidder pet;
    private boolean firstBid = false;

    public StackTraceObfuscaterBot() {
        if (created)
            throw new IllegalStateException("THERE CAN ONLY BE ONE!");
        created = true;
    }

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        firstBid = true;
        RunnableFuture<DollarBidder> task = new FutureTask<>(() -> {
            try {
                return opponent.newInstance();
            } catch (Throwable t) {
                return null;
            }
        });
        Thread thread = new Thread(task);
        thread.start();
        try {
            pet = task.get(450, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | ExecutionException | TimeoutException e) {
            task.cancel(true);
            pet = null;
        }
    }

    @Override
    public int nextBid(int opponentsBid) {
        if (!firstBid)
            return 0;
        firstBid = false;

        for (int bid = opponentsBid + 5; i < 100; i += 5) {
            final int bidt = bid;
            RunnableFuture<Boolean> task = new FutureTask<>(() -> {
                pet.newAuction(this.getClass());
                return pet.nextBid(bidt) < bidt + 5;
            });
            Thread thread = new Thread(task);
            thread.start();
            try {
                if (task.get(23, TimeUnit.MILLISECONDS))
                    return bid;
            } catch (InterruptedException | ExecutionException | TimeoutException e) {
                task.cancel(true);
                return 0;
            }
        }
        return 0;
    }
}

```

This bot laughs at attempts to detect reflection via the stack trace. The closest thing they see to a `DollarBidder` is some lambda class it created. Clearly not another bot trying to reflect them. Little do they know that that lambda class is actually working for a `DollarBidder`. Beyond that, he acts like `MarginalerBot`.
> 2 votes

# Answer
# Non-competing: MSlowBot

```
import net.ramenchef.dollarauction.DollarBidder;

import java.util.Arrays;

public class MSlowBot extends DollarBidder {
    private DollarBidder rival;

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        try {
            rival = opponent.newInstance();
            rival.newAuction(this.getClass());
        } catch (Throwable t) {
            rival = null;
        }
    }

    @Override
    public int nextBid(int opponentsBid) {
        noPeeking();

        for (int iBid = opponentsBid + 5; iBid <= 100; iBid = iBid + 5) {
            try {
                if (rival.nextBid(iBid) < iBid + 5) {
                    return iBid;
                }
            } catch (Throwable t) {
                //do nothing.
            }
        }
        return 0;
    }

    private void noPeeking() {
        final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        for (StackTraceElement ste : Arrays.copyOfRange(stackTrace, 3, stackTrace.length)) {
            try {
                Class<?> clazz = Class.forName(ste.getClassName());
                if (DollarBidder.class.isAssignableFrom(clazz))
                    Thread.sleep(1000);
            } catch (ClassNotFoundException | InterruptedException e) {
                throw new RuntimeException(":(");
            }
        }
    }
}

```

Same logic as MBot, just use timeout instead of Exception when fighting against enemy. So far no one is defending agains timeout so should be effective
> 2 votes

# Answer
# One Extra

```
import net.ramenchef.dollarauction.DollarBidder;

public class OneExtra extends DollarBidder {
    @Override
    public int nextBid(int opponentsBid) {
        if(opponentsBid < 110)
          return opponentsBid + 6;
        return opponentsBid;
    }
}

```

Bids 6 more than the last bid, just because he can.
> 2 votes

# Answer
# `ImprovedAnalystBot` (non-competing)

A lot of people seem to be using the `AnalystBot` code as a template, even though it's deliberately bad code. So I'm making a better template.

```
import net.ramenchef.dollarauction.DollarBidder;

public class ImprovedAnalystBot extends DollarBidder {
    private DollarBidder enemy;

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        if (!opponent.equals(this.getClass()))
            try {
                this.enemy = opponent.newInstance();
                enemy.newAuction(this.getClass());
            } catch (Throwable t) {
                this.enemy = null;
            }
        else
            this.enemy = null;
    }

    @Override
    public int nextBid(int opponentsBid) {
        try {
            return enemy != null && enemy.nextBid(95) < 100 ? 95 : 0;
        } catch (Throwable t) {
            return 0;
        }
    }
}

```
> 1 votes

# Answer
# MBot

```
import net.ramenchef.dollarauction.DollarBidder;

import java.util.Arrays;

public class MBot extends DollarBidder {
    protected DollarBidder rival = null;
    protected boolean rivalPrepared = false;
    protected Class<? extends DollarBidder> rivalClass;

    @Override
    public void newAuction(Class<? extends DollarBidder> opponent) {
        this.rivalClass = opponent;
        this.rivalPrepared = false;
    }

    protected DollarBidder getRival() {
        if (!rivalPrepared) {
            rivalPrepared = true;
            try {
                rival = rivalClass.newInstance();
                rival.newAuction(this.getClass());
            } catch (Throwable t) {
                rival = null;
            }
        }
        return rival;
    }

    @Override
    public int nextBid(int opponentsBid) {
        return calcBid(opponentsBid, isPeeking(3), isPeeking(4));
    }

    protected int calcBid(int opponentsBid, boolean isPeeking, boolean isSubPeeking) {
        if (isPeeking) {
            throw new RuntimeException();
        }

        for (int iBid = opponentsBid + 5; iBid <= 100; iBid = iBid + 5) {
            try {
                if (getRival().nextBid(iBid) < iBid + 5) {
                    return iBid;
                }
            } catch (Throwable t) {
                // noop
            }
        }
        return 0;
    }

    protected boolean isPeeking(int level) {
        final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        final StackTraceElement[] stackTraceElements = Arrays.copyOfRange(stackTrace, level, stackTrace.length);
        for (StackTraceElement ste : stackTraceElements) {
            try {
                Class<?> clazz = Class.forName(ste.getClassName());
                if (DollarBidder.class.isAssignableFrom(clazz))
                    return true;
            } catch (ClassNotFoundException e) {
                return true;
            }
        }
        return false;
    }
}

```

Slightly refined MarginalerBot

* be unkind to those who wan't to check you
* allow paying 100 to get 100 and break even case, just to deny others easy money
> 1 votes

# Answer
## `TimeRandBot`

```
import net.ramenchef.dollarauction.DollarBidder;

public class TimeRandBot extends DollarBidder {

    @Override
    public int nextBid(int opponentsBid) {
        return (int) (System.currentTimeMillis() % 21 * 5);
    }
}

```

Bids from 0¢ up to 100¢ inclusive in increments of 5¢.
> 0 votes

---
Tags: game, king-of-the-hill, java
---


# Question
Title: Create a function for transposing musical chords
Your mission is to create a function for transposing music chords.

Copied from SO with permission of the original asker, I just really wanted to see what you guys could do with this one:

Since I don't expect everyone to be a musician here, I'll try to explain how it works in music theory. I hope I don't forget something. If yes, musicians, please, correct me.

1) The simple chords

The simple chords are almost as simple as an alphabet and it goes like this:

> C, C#, D, D#, E, F, F#, G, G#, A, A# B

From B it loops all over again to C. Therefore, If the original chord is `E` and we want to transpose +1, the resulting chord is `F`. If we transpose +4, the resulting chord is `G#`.

2) Expanded chords

They work almost like the simple chords, but contain a few more characters, which can safely be ignored when transposing. For example:

> Cmi, C#7, Dsus7, Emi, Fsus4, F#mi, G ...

So again, as with the simple chords, if we transpose `Dsus7` \+ 3 = `Fsus7`

3) Non-root bass tone

A problem arises when the bass plays a different tone than the chord root tone. This is marked by a slash after the chord and also needs to be transposed. Examples:

> C/G, Dmi/A, F#sus7/A#

As with examples 1 and 2, everything is the same, but the part after the slash needs transpose too, therefore:

`C/G` \+ 5 = `F/C`

`F#sus7/A#` \+ 1 = `Gsus7/B`

I think this should be all, unless I forgot something.

So basically, imagine you have a javascript variable called `chord` and the transpose value `transpose`. What code would transpose the chord?

Example:

```
var chord = 'F#sus7/C#';
var transpose = 3; // remember this value also may be negative, like "-4"
... code here ...
var result; // expected result = 'Asus7/E';

```

original question here: https://stackoverflow.com/questions/7936843/how-do-i-transpose-music-chords-using-javascript (note that he's asking for JS, for this challenge I don't care what language its in)

# Answer
> 2 votes
# Haskell, 146

```
c=zip(words"C C# D D# E F F# G G# A A# B")[0..]
x#n=maybe x(\i->fst$c!!mod(i+n)12)$lookup x c
(x:'#':y)%n=(x:"#")#n++y%n
(x:y)%n=[x]#n++y%n
x%_=x

```

This defines an operator `%` that transposes a chord by a given amount, so you'd use it like this:

```
*Main> "E"%1
"F"
*Main> "E"%4
"G#"
*Main> "Dsus7"%3
"Fsus7"
*Main> "C/G"%5
"F/C"
*Main> "F#sus7/A#"%1
"Gsus7/B"

```

# Answer
> 2 votes
OK, within the limitations of the question as asked and not catering for a lot of things you'd need to allow for if using with real music (flats being the most obvious):

```
function t(c,a) {
  var s=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],i;
  return c.replace(/[A-G]#?/g,function(m){return s[(i=(s.indexOf(m)+a)%s.length)<0?i+s.length:i];});
}

```

This is my first attempt at code-golf, so I hope I've taken the right approach. Following is the readable version that I originally posted at stackoverflow.com:

```
function transposeChord(chord, amount) {
  var scale = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
  return chord.replace(/[CDEFGAB]#?/g,
                       function(match) {
                         var i = (scale.indexOf(match) + amount) % scale.length;
                         return scale[ i < 0 ? i + scale.length : i ];
                       });
}

```

# Answer
> 0 votes
As a preliminary effort, I'd like to flesh-out some of what "the full solution" should take into account.

**Sharps and Flats**

When transposing a musical *key*, one adds sharps or flats to the key signature according to the distance traversed in the "circle of fourths" (or fifths, depending on the direction you're going).

```
fifths from C up to the enharmonic
key: C G  D  A  E  B  F# C# G#  D#  A#  E#  B#
add:   F# C# G# D# A# E# B# F## C## G## D## A##

fourths from C down to the enharmonic
key: C F  Bb Eb Ab Db Gb Cb Fb  Bbb Ebb Abb Dbb
add:   Bb Eb Ab Db Gb Cb Fb Bbb Ebb Abb Dbb Gbb

```

So the key of C can be written with zero sharps or flats, or with twelve sharps, or with twelve flats. The first options is clearly superior.

But we only really need the middle of the table above because all those double-sharps and double-flats mean that some note is being given an overly-complicated name. So extracting the middle and arranging in sequence gives us this list of keys.

```
C  Db(5 'b's) D(2#) Eb(3b) E(4#) F(1b) F#(6#)[or Gb(6b)]
G(1#) Ab(4b) A(3#) Bb(2b) B(5#) C

```

And, dropping the counts and picking between F# and Gb (all flats looks prettier than one lonely sharp) gives:

```
C Db D Eb F Gb G Ab A Bb B C

```

But for named chords, the situation is less clear because the names carry accidentals with them.

# Answer
> 0 votes
# Javascript, 249

This code **handles bemol input**:

```
let N=["A","A#","B","C","C#","D","D#","E","F","F#","G","G#"]
let t=(r,n)=>r.split("/").map((i)=>{
let a=i[1]
let m=a=="#"||a=="b"?2:1
let c=i.slice(0,m)
c=a=="b"?t(c[0],-1):c
let x=(N.indexOf(c)+n)%12
x=x<0?12+x:x
return N[x]+i.slice(m)
}).join("/")

```

Limitations:

1. No double flat or double sharp support.
2. No validation of the chord's bass note or modifiers.
3. Output always uses sharps for accidents. i.e: `G#/C` instead of `Ab/C`.

To solve the 'full' problem, you need the program to understand the chord modifiers and calculate each note that the chord uses, then match that with the transposed chord to get the right answer. While possible I see it unpractical to code that in a code golf setting.

### 'Readable' version:

```
let Notes=["A","A#","B","C","C#","D","D#","E","F","F#","G","G#"]
let transpose=(input,n)=>input.split("/").map((splittedInput)=>{
let accident=splittedInput[1]
let modifierIndex=accident=="#"||accident=="b"?2:1
let note=splittedInput.slice(0,modifierIndex)
note=accident=="b"?transpose(note[0],-1):note
let transposedIndex=(Notes.indexOf(note)+n)%12
transposedIndex=transposedIndex<0?12+transposedIndex:transposedIndex
return Notes[transposedIndex]+splittedInput.slice(modifierIndex)
}).join("/")

```

---
Tags: code-golf, music
---


title: Win a KQ vs K endgame

text:
# Question
Title: Win a KQ vs K endgame
# Win a K vs KQ endgame

## Summary

The goal of this challenge is to create a program or function which will win a Chess game with a King and Queen against a lone King. The user will specify three squares, representing the locations of the computer's King, the computer's Queen, and the user's King. The computer will then a output a move which will eventually lead to checkmate.

## Input/Output

The program or function will first take as input three squares, representing the locations of the computer's King, the computer's Queen, and the user's King (not necessarily in that order). It can be assumed that the input is a legal position.

Parsing input is not the point of this challenge, so all reasonable forms of input/output are allowed, including but not limited to

* Strings with algebraic chess notation such as `"Ke4"` or `"Qf6"`
* Triples representing pieces and coordinates such as `('K', 0, 2)`

After three squares are taken as input, the computer outputs a single legal move. Behaviour on invalid input is undefined.

## Requirements

This procedure must terminate using your program or function:

* User sets up a legal KQ vs K position on a physical chessboard.
* User inputs the board position. The computer outputs a legal move. If the move is a checkmate, STOP. If the move is a stalemate or allows the computer's queen to be captured, your solution is invalid.
* User makes the computer's move on the physical board.
* User makes a legal move for the lone king on the physical board.
* User goes to step 2 and repeats.

In other words, the computer must eventually win by checkmate, through repeatedly using your program or function.

Furthermore, from any legal starting position the checkmate must occur in 50 or fewer moves by the computer, i.e. the above procedure will be repeated no more than 50 times. An explanation as to why your solution will always win in 50 moves or fewer is appreciated.

(Of course, a physical chessboard is in no way necessary to test the code; I only mentioned it to help visualize the procedure. The chessboard could just as well be visualized in the user's head.)

## Possible test cases

The squares are given in the order: *computer's Queen, computer's King, user's King*

* `c2, h8, a1` (must avoid stalemate)
* `a1, a2, a8`
* `a8, a1, e5`

## Rules

* The checkmate must occur in 50 or fewer moves by the computer, but it does not need to be as fast as possible.
* Chess libraries are not permitted.
* Shortest program in each language (in bytes) wins.

# Answer
# Python 3, 1054 bytes

```
def d(kx,ky,x,y):return abs(x-kx)<2>abs(y-ky)
def l(qx,qy,kx,ky,x,y):
 if x==qx:return x!=kx or ky<min(y,qy)or max(y,qy)<ky
 o=kx<min(x,qx)or max(x,qx)<kx
 if y==qy:return o or y!=ky
 if x-y==qx-qy:return o or x-y!=kx-ky
 return x+y==qx+qy and(o or x+y!=kx+ky)
def f(c,x,y):c[x][y]=1;[f(c,u,v)for v in range(max(y-1,0),min(y+2,8))for u in range(max(x-1,0),min(x+2,8))if c[u][v]<1]
def s(qx,qy,kx,ky,hx,hy):c=[[d(kx,ky,u,v)or l(qx,qy,kx,ky,u,v)for v in range(8)]for u in range(8)];t=sum(map(sum,c));f(c,hx,hy);t=sum(map(sum,c))-t;return t if t-1else 64
def m(qx,qy,kx,ky,hx,hy):a=[[s(x,y,kx,ky,hx,hy)if(x+y-7and x-y)and d(hx,hy,x,y)<=d(kx,ky,x,y)and l(qx,qy,kx,ky,x,y)and l(qx,qy,hx,hy,x,y)else 64for y in range(8)]for x in range(8)];b=list(map(min,a));c=min(b);e=b.index(c);return(0,e,a[e].index(c))if c<a[qx][qy]else min(((x-hx)**2*2+(y-hy)**2*2+(x-3)*(x-4)+(y-3)*(y-4),x,y)for x in range(max(kx-1,0),min(kx+2,8))for y in range(max(ky-1,0),min(ky+2,8))if(x!=kx or y!=ky)and(x!=qx or y!=qy)>d(hx,hy,x,y)and(x-7and x or y-7and y)and s(qx,qy,x,y,hx,hy)<64)

```

Try it online! Link includes footer which starts from the given position (input as a string of three squares in the order computer Queen, computer King, human King, without separators) and plays random moves on the human's behalf until the computer checkmates it. I've never seen it take anywhere near 50 moves but I don't know how to prove that it won't. Not completely golfed for the sake of my sanity. Explanation:

```
def d(kx,ky,x,y):return abs(x-kx)<2>abs(y-ky)

```

Determines whether a square is under attack from a King, e.g. to prevent the Queen from giving itself away.

```
def l(qx,qy,kx,ky,x,y):
 if x==qx:return x!=kx or ky<min(y,qy)or max(y,qy)<ky
 o=kx<min(x,qx)or max(x,qx)<kx
 if y==qy:return o or y!=ky
 if x-y==qx-qy:return o or x-y!=kx-ky
 return x+y==qx+qy and(o or x+y!=kx+ky)

```

Determines whether the Queen is threatening the square that the human's King might want to move to.

```
def f(c,x,y):c[x][y]=1;[f(c,u,v)for v in range(max(y-1,0),min(y+2,8))for u in range(max(x-1,0),min(x+2,8))if c[u][v]<1]

```

Helper recursive function to flood fill the squares that the human's King can reach.

```
def s(qx,qy,kx,ky,hx,hy):c=[[d(kx,ky,u,v)or l(qx,qy,kx,ky,u,v)for v in range(8)]for u in range(8)];t=sum(map(sum,c));f(c,hx,hy);t=sum(map(sum,c))-t;return t if t-1else 64

```

Calculate the scope of the human's King. However, it returns 64 on stalemate, indicating that this is a bad move for the Queen to make.

```
def m(qx,qy,kx,ky,hx,hy):a=[[s(x,y,kx,ky,hx,hy)if(x+y-7and x-y)and d(hx,hy,x,y)<=d(kx,ky,x,y)and l(qx,qy,kx,ky,x,y)and l(qx,qy,hx,hy,x,y)else 64for y in range(8)]for x in range(8)];b=list(map(min,a));c=min(b);e=b.index(c);return(0,e,a[e].index(c))if c<a[qx][qy]else min(((x-hx)**2*2+(y-hy)**2*2+(x-3)*(x-4)+(y-3)*(y-4),x,y)for x in range(max(kx-1,0),min(kx+2,8))for y in range(max(ky-1,0),min(ky+2,8))if(x!=kx or y!=ky)and(x!=qx or y!=qy)>d(hx,hy,x,y)and(x-7and x or y-7and y)and s(qx,qy,x,y,hx,hy)<64)

```

The meat of the program, this actually computes the computer's move. The return value is a tuple of (Piece to move, desired X, desired Y) where the flag is 0 to move the Queen and all parameters and X and Y are 0-indexed. It first checks all of the Queen's available moves (except those that give it away or those to squares on the main diagonals, as the symmetry confuses it) to see whether it can reduce the scope of the human's King. If not, it tries to move its own King nearer the human's King, or failing that, nearer the middle of the board.
> 6 votes

---
Tags: code-golf, game, chess
---


title: Extend the line

text:
# Question
Title: Extend the line
## Task

Given an image with a line on it, produce or display an image with the line extended till the edge of image. The line is black and the background is white. The image size is `100x100` The image comes in any reasonable format (e.g. `jpg`, `png`, `ppm`, `bmp`).

## Line format

I'm using a simplified version of Bresenham's line algorithm for drawing lines. Lines will only have an integer slope so that the line will never partially cover a pixel but not color it:

(Wikipedia image)

At a minimum the line will be 3x3 unless the line is straight, in which case you will only see 3x1 or 1x3 in the image. Lines will also have one side on the edge of the image, so you only have to extend it in one direction.

### Example (`.png`, red line added so you can see it):

## Real examples (`.png`)

### ====================

### ====================

### ====================

### ====================

# Answer
# APL (dzaima/APL), 93 bytes

```
{w←⍵⋄m←÷/(⊢/-⊃)p←⍸¯1≠⍵.mat⋄y x←⊃p⋄P5.size←⍵.sz⋄P5.setup←{P5.G.bg¯1⋄P5.G.ln∊{⍵,y+m×⍵-x}¨⍳101}}

```

Try it online!

A dfn which takes the image as an `APLImg` object. Taking the image as a URL is 102: Try it online!

Uses `⎕IO←0` (0-indexing).

The function effectively takes the line, calculates its equation and redraws it.

## Explanation

**Slope calculation:** `m←÷/(⊢/-⊃)p←⍸¯1≠⍵.mat`

`⍵.mat` get the image as an integer matrix

`¯1≠` check which pixels aren't white

get all the required coordinates

`p←` store in p

`(⊢/-⊃)` subtract the last point from the first

`÷/` reduce by division

---

`y x←⊃p` store the first point in y and x

`P5.size←⍵.sz` set canvas size to image size

---

**Draw the image:** `P5.setup←{P5.G.bg¯1⋄P5.G.ln∊{⍵,y+m×⍵-x}¨0,w.width}`

`P5.setup←{...}` draw the following once:

`P5.G.bg¯1` set the background to white

`P5.G.ln∊{⍵,y+m×⍵-x}¨⍳101` draw lines between the following points:

`{...}¨0,w.width` get the points for each x in 0-100:

`y+m×⍵-x` \\$y = y\_1+m(x-x\_{1})\\$

`⍵,` pair the x value with that

enlist so it can be drawn
> 2 votes

# Answer
# Mathematica, 125 bytes

```
ImageRotate@Image@SparseArray[Array[Floor,101,#&@@ImageLines[ColorNegate@#,Method->"RANSAC"]]+1->0,{101,101},1][[;;-2,;;-2]]&

```

---

**Explanation**

`ImageLines` detect lines in the image with method `RANSAC`. We take the first detected line and convert it back to an image. The whole function takes an image as the argument and returns an image.
> 2 votes

---
Tags: code-golf, geometry, graphical-output, image-processing
---


title: Do we share the prime cluster?

text:
# Question
Title: Do we share the prime cluster?
The *prime cluster* of an integer **N** higher than **2** is defined as the pair formed by the highest prime **strictly** lower than **N** and the lowest prime **strictly** higher than **N**.

Note that following the definition above, if the integer is a prime itself, then its prime cluster is the pair of the primes *preceding* and *succeeding* it.

# Task

Given two integers integers **N**, **M** (**N, M ≥ 3**), output a truthy / falsy value based on whether **N** and **M** have the same prime cluster.

This is , so the aim is to reduce your byte count as much as possible. Thus, the shortest code in every programming language wins.

# Test cases / Examples

For instance, the prime cluster of **9** is `[7, 11]`, because:

* **7** is the highest prime strictly lower than **9**, and
* **11** is the lowest prime strictly higher than **9**.

Similarly, the the prime cluster of **67** is `[61, 71]` (note that **67** is a prime).

**Truthy pairs**

```
8, 10
20, 22
65, 65
73, 73
86, 84
326, 318
513, 518

```

**Falsy pairs**

```
4, 5
6, 8
409, 401
348, 347
419, 418
311, 313
326, 305

```

# Answer
> 17 votes
# Jelly, ~~6~~ ~~4~~ ~~3~~ ~~5~~ 4 bytes

```
rÆPE

```

Try it online! or Try all test cases.

### How it works

```
rÆPE    Main link. Arguments: N, M
r       Yield the range of integers between N and M, inclusive.
 ÆP     For each integer, yield 1 if it is prime, 0 otherwise.
   E    Yield 1 if all items are equal (none in the range were prime,
        or there's only one item).

```

Works because two numbers have different prime clusters iff there is a prime between them, or either number is itself prime; *unless* both numbers are the same, in which case `E` returns `1` anyway (all items in a single-item array are equal).

# Answer
> 2 votes
# Python 3, 103 95 91 bytes

```
lambda*z:len({*z})<2or[1for i in range(min(z),max(z)+1)if all(i%k for k in range(2,i))]<[0]

```

Try it online!

# Answer
> 2 votes
# Perl 6, 52 bytes

```
{[eqv] @_».&{(($_...0),$_..*)».first(*.is-prime)}}

```

Test it

## Expanded:

```
{  # bare block lambda with implicit slurpy input ｢@_｣

  [eqv]               # see if each sub list is equivalent

    @_».&{            # for each value in the input

      (

        ( $_ ... 0 ), # decreasing Seq
          $_ ..  *    # Range

      )».first(*.is-prime) # find the first prime from both the Seq and Range

    }
}

```

# Answer
> 2 votes
# Ruby, <sub>~~57~~</sub> 54 bytes

```
->n,m{[*n..m,*m..n].all?{|x|?1*x=~/^(11+)\1+$/}||n==m}

```

Try it online!

Uses the horrible regex primality test from my answer (which I had forgotten about until I clicked on it) to the related question Is this number a prime?. Since we have N, M ≥ 3, the check for 1 can be removed from the pattern, making the byte count less than using the built-in.

Note: The regex primality test is pathologically, hilariously inefficient. I believe it's at least O(n!), though I don't have time to figure it right now. It took twelve seconds for it to check 100,001, and was grinding for five or ten minutes on 1,000,001 before I canceled it. *Use/abuse at your own risk.*

# Answer
> 2 votes
# Retina, 58 bytes

```
\b(.+)¶\1\b

.+
$*
O`
+`\b(1+)¶11\1
$1¶1$&
A`^(11+)\1+$
^$

```

Try it online! Explanation:

```
\b(.+)¶\1\b

```

If both inputs are the same, simply delete everything, and fall through to output 1 at the end.

```
.+
$*

```

Convert to unary.

```
O`

```

Sort into order.

```
+`\b(1+)¶11\1
$1¶1$&

```

Expand to a range of all the numbers.

```
A`^(11+)\1+$

```

Delete all composite numbers.

```
^$

```

If there are no numbers left, output 1, otherwise 0.

# Answer
> 2 votes
# C (gcc), ~~153~~ 146 bytes

```
i,B;n(j){for(B=i=2;i<j;)B*=j%i++>0;return!B;}
#define g(l,m,o)for(l=o;n(--l););for(m=o;n(++m););
a;b;c;d;h(e,f){g(a,b,e)g(c,d,f)return!(a-c|b-d);}

```

-7 from Jonathan Frech

Defines a function `h` which takes in two `int`s and returns `1` for truthy and `0` for falsey

Try it online!

`n` is a function that returns 1 if its argument is not prime.

`g` is a macro that sets its first and second arguments to the next prime less than and greater than (respectively) it's third argument

`h` does `g` for both inputs and checks whether the outputs are the same.

# Answer
> 2 votes
# JavaScript (ES6), ~~57~~ 56 bytes

Takes input in currying syntax `(a)(b)`. Returns `0` or `1`.

```
a=>b=>a==b|!(g=k=>a%--k?g(k):k<2||a-b&&g(a+=a<b||-1))(a)

```

### Test cases

```
let f =

a=>b=>a==b|!(g=k=>a%--k?g(k):k<2||a-b&&g(a+=a<b||-1))(a)

console.log('Truthy')
console.log(f(8)(10))
console.log(f(20)(22))
console.log(f(65)(65))
console.log(f(73)(73))
console.log(f(86)(84))
console.log(f(326)(318))
console.log(f(513)(518))

console.log('Falsy')
console.log(f(4)(5))
console.log(f(6)(8))
console.log(f(409)(401))
console.log(f(348)(347))
console.log(f(419)(418))
console.log(f(311)(313))
```

### How?

```
a => b =>                 // given a and b
  a == b |                // if a equals b, force success right away
  !(g = k =>              // g = recursive function taking k
    a % --k ?             //   decrement k; if k doesn't divide a:
      g(k)                //     recursive calls until it does
    :                     //   else:
      k < 2 ||            //     if k = 1: a is prime -> return true (failure)
      a - b &&            //     if a equals b: neither the original input integers nor
                          //     any integer between them are prime -> return 0 (success)
      g(a += a < b || -1) //     else: recursive call with a moving towards b
  )(a)                    // initial call to g()

```

# Answer
> 2 votes
# , ~~63~~ 46 bytes

*-17 by Giuseppe*

```
function(a,b)!sd(range(numbers::isPrime(a:b)))

```

Try it online!

Pretty simple application of ETHProductions' Jelly solution. Main interesting takeaway ~~is~~ was that with R boolean vectors `any(x)==all(x)` is equivalent to `min(x)==max(x)`.

# Answer
> 2 votes
# PARI/GP, 28 bytes

```
v->s=Set(v);#s<2||!primes(s)

```

Try it online with all test cases!

Returns `0` or `1` (usual PARI/GP "Boolean" values).

Explanation:

`v` must be a vector (or a column vector, or a list) with the two numbers `N` and `M` as coordinates. For example `[8, 10]`. Then `s` will be the "set" made from these numbers, which is either a one-coordinate vector (if `N==M`), or a two-coordinate vector with *sorted* entries otherwise.

Then if the number `#s` of coordinates in `s` is just one, we get `1` (truthy). Otherwise, `primes` will return a vector of all primes in the closed interval from `s[1]` to `s[2]`. Negation `!` of that will give `1` if the vector is empty, while negation of a vector of one or more non-zero entries (here one or more primes) will give `0`.

# Answer
> 1 votes
# Jelly, 6 bytes

```
ÆpżÆnE

```

Try it online!

-2 thanks to Dennis.

# Answer
> 1 votes
# APL (Dyalog Unicode), ~~18+16 = 34~~ 24 bytes

```
⎕CY'dfns'
∧/=/4 ¯4∘.pco⎕

```

Try it online!

Thanks to Adám for 10 bytes.

The line `⎕CY'dfns'` (**C**OP**Y**) is needed to import the *dfns* (**d**ynamic **f**unctio**ns**) collection, included with default Dyalog APL installs.

### How it works:

```
∧/=/4 ¯4∘.pco⎕ ⍝ Main function. This is a tradfn body.
             ⎕ ⍝ The 'quad' takes the input (in this case, 2 integers separated by a comma.
          pco  ⍝ The 'p-colon' function, based on p: in J. Used to work with primes.
    4 ¯4∘.     ⍝ Applies 4pco (first prime greater than) and ¯4pco (first prime smaller than) to each argument.
  =/           ⍝ Compares the two items on each row
∧/             ⍝ Applies the logical AND between the results.
               ⍝ This yields 1 iff the prime clusters are equal.

```

# Answer
> 1 votes
# Python 2, ~~87~~ 86 bytes

```
lambda*v:v[0]==v[1]or{1}-{all(v%i for i in range(2,v))for v in range(min(v),max(v)+1)}

```

Try it online!

# Answer
> 1 votes
# C (gcc), ~~103 bytes~~ 100 bytes

```
i,j,p,s;f(m,n){s=1;for(i=m>n?i=n,n=m,m=i:m;i<=n;i++,p?s=m==n:0)for(p=j=2;j<i;)p=i%j++?p:0;return s;}

```

Try it online!

# Answer
> 0 votes
# Mathematica, 39 27 26 bytes

```
Equal@@#~NextPrime~{-1,1}&

```

Expanded:

```
                         &  # pure function, takes 2-member list as input
       #~NextPrime~{-1,1}   # infix version of NextPrime[#,{-1,1}], which
                            # finds the upper and lower bounds of each
                              argument's prime clusters
Equal@@                     # are those bounds pairs equal?

```

Usage:

```
Equal@@#~NextPrime~{-1,1}& [{8, 10}]
(*  True  *)

Equal@@#~NextPrime~{-1,1}& [{6, 8}]
(*  False  *)

Equal@@#~NextPrime~{-1,1}& /@ {{8, 10}, {20, 22}, {65, 65},
    {73, 73}, {86, 84}, {326, 318}, {513, 518}}
(*  {True, True, True, True, True, True, True}  *)

Equal@@#~NextPrime~{-1,1}& /@ {{4, 5}, {6, 8}, {409, 401},
    {348, 347}, {419, 418}, {311, 313}}
(*  {False, False, False, False, False, False}  *)

```

Contributions: -12 bytes by Jenny\_mathy, -1 byte by Martin Ender

# Answer
> 0 votes
# Haskell, 81 bytes

A straightforward solution:

```
p z=[x|x<-z,all((0/=).mod x)[2..x-1]]!!0
c x=(p[x-1,x-2..],p[x+1..])
x!y=c x==c y

```

Try it online!

# Answer
> 0 votes
# , 15 bytes

```
-:&(_4&p:,4&p:)

```

How it works:

```
   &(           ) - applies the verb in the brackets to both arguments
            4&p:  - The smallest prime larger than y
      _4&p:       - The largest prime smaller than y
           ,      - append
 -:               - matches the pairs of the primes

```

Try it online!

# Answer
> 0 votes
# Stax, 9 bytes

```
α╖ª»º√π├╔

```

Run and debug it

# Answer
> 0 votes
# 05AB1E, 3 bytes

```
ŸpË

```

Port of *@ETHproductions*'s Jelly answer, so make sure to upvote him!

Try it online or verify all test cases.

**Explanation:**

```
Ÿ    # Create an inclusive ranged list of the (implicit) input-pair
 p   # Check for each value in the list whether it's a prime (1 if truthy; 0 if falsey)
  Ë  # Check if all values are the same (so either all truthy or all falsey)
     # (after which the result is output implicitly)

```

---
Tags: code-golf, number-theory, decision-problem, primes
---


title: Visualize long addition with ASCII art

text:
# Question
Title: Visualize long addition with ASCII art
Totally not inspired by Visualize long division with ASCII art ;)

Your job is to show long hand addition with ASCII art. You solve longhand addition by adding up the columns right to left, placing the value of the ones place in the result, and carrying the tens place over to the top of the next column.

## Input

Input can come basically in any format you want, just as long as you take from 2 to 9 numbers as input.

## Output

The formatting here likely matches how you learned it in school:

```
carry row
 number1
 number2
     ...
+   numX
--------
  result

```

You can have just about any amount of trailing whitespace you want here ;)

## Examples

```
50, 50

1
 50
+50
---
100

1651, 9879

1111
 1651
+9879
-----
11530

6489789, 9874, 287

   1122
 6489789
    9874
+    287
--------
 6499950

```

# Answer
# Stax, 48 bytes

```
¢≈3ä⌂♪s♂N#┼DuΦeÑα▼dσÿóYRC├[♂≡α%┴&UZ≤§╟Ω^j╪♪■∞xëa

```

Run and debug it

`)` is a lifesaver here, but it still feels too long.
> 1 votes

# Answer
# Pyth, ~~59~~ 58 bytes

```
L.[dJhl`eSQ`b:jk_.u/+NsYT.t_MjRTQ00\0djbyMPQXyeQ0\+*J\-ysQ

```

Try it online. Test suite.

Way too long. Should golf more.

### Explanation

```
L                  helper function y = lambda b:
        eSQ          largest number in input
      l`             length as string
     h               increment
    J                save to J
 .[d       `b        pad argument with spaces to that length

                             carry row:
                jRTQ           each input to base 10
              _M               reverse each result
            .t      0          transpose, padding with zeroes
    .u               0         cumulative reduce from 0:
         sY                      sum digits of column
       +N                        add previous carry
      /    T                     floor-divide by 10
   _                           reverse
 jk                            join by ""
:                     \0d      replace 0 by space

          number rows:
    PQ      all input numbers but last one
  yM        pad to correct length
jb          print on separate lines

           last number row:
  eQ         last input number
 y           pad to correct length
X   0\+      change first char to +

        separator row:
 J        width of input (saved in helper)
* \-      that many dashes

       result row:
 sQ      sum of inputs
y        pad to correct length

```
> 5 votes

# Answer
## Batch, 326 bytes

Byte count does not include explanation, of course.

```
@echo off
set t=%*                            Get the space separated parameters
set t=%t: =+%                       Change the spaces into + signs
set/at=%t%,l=p=1                    Add together, and initialise length and power
set c=                              Carry string
set d=-                             Dash string
:l                                  Loop though each power of 10
set/al+=1,p*=10,s=t/p               Divide the total by the power
for %%n in (%*)do set/as-=%%n/p     Subtract each parameter divided
set c=%s%%c%                        Anything left must have been carried
set d=-%d%                          Add a - to the line of dashes
if %p% leq %t% goto l               Keep going until we run out of powers
echo(%c:0= %                        Delete any zeros in the carry and output it
:i                                  Loop through each parameter
set n=%d:-= %%1                     Pad it with a whole bunch of spaces
call set n=%%n:~-%l%%%              Extract the rightmost characters
if "%2"=="" set n=+%n:~1%           Insert a + before the last parameter
echo %n%                            And output it
shift                               Move to the next parameter
if not "%1"=="" goto i              Until they are all consumed
echo %d%                            Output the line of dashes
echo  %t%                           Output the total (with an indent for the +)

```
> 1 votes

# Answer
## JavaScript (ES6), 199 bytes

```
a=>[[...t=` `+a.reduce((t,n)=>t+n)].map((_,i)=>a.reduce((c,n)=>c-n[i],90+t[i])%10||` `),a=a.map(n=>(` `.repeat(l=t.length)+n).slice(-l))).join``,...a,`-`.repeat(l),t].join`\n`.replace(/ (?=.*\n-)/,`+`)

```

Where the first `\n` represents a literal newline character, while the second one is a two-character regexp escape sequence. Explanation:

```
a=>[                            Accept an array of numbers
 [...                           Split the total into digits
  t=` `+a.reduce((t,n)=>t+n)    Calculate the total and add a space
 ].map((_,i)=>a.reduce((c,n)=>  For each column
  c-n[i],90+t[i])               Subtract the column from the total
  %10||` `),                    Deduce the carry that was needed
  a=a.map(n=>                   For each input value
   (` `.repeat(l=t.length)+n)   Pad to the length of the total
    .slice(-l))                 Remove excess padding
 ).join``,                      Join the carries together
 ...a,                          Append the padded input values
 `-`.repeat(l),                 Append the dividing line
 t].join`\n`                    Append the total and join together
  .replace(/ (?=.*\n-)/,`+`)    Insert the + on the line above the -

```

The carry calculation works by taking the total digit, prefixing `90`, subtracting all the input value digits in that column, and taking the result modulo 10. (The prefix is `90` rather than `9` so that the leading column generates a blank carry space.)
> 0 votes

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


title: Compiled quine variant

text:
# Question
Title: Compiled quine variant
Thinking about various quine puzzles here, I got an idea for another one:

**Compose a program that outputs its own *compiled* code to a file** (or multiple files, if the compiled code is). (This means that only compiled languages are eligible.)

# Rules

Standard quine rules - no cheating allowed. In particular:

1. The program cannot read the compiled code from disk, cannot store it somewhere etc. It must compute it somehow without external help.
2. If the program is compiled to several files (i.e. several Java `.class` files), it must output them all.
3. You can use any existing libraries available for your language. However:
    * The libraries you use cannot be something created just for this task. (For example in order to keep some information away from what's considered to be the program.)
    * Any libraries you use must be older than your program. You cannot just create a program that loads a piece of data from an external library, compile the program, and copy the compiled code into the library - that'd be cheating.
    * You cannot embed a compiler of your language in any form. In particular, you cannot just take a standard quine and hook it up with a compiler to produce the compiled output.
4. As mentioned, only compiled languages are eligible. You can use a scripting language as long as it can be compiled to a bytecode that's reasonably different from the source form (if you're not sure, better ask).

# Notes

Most likely, this puzzle can be solved reasonably only in languages that compile to some sort of bytecode that can be manipulated. For example, Java and compiled bytecode seems good for the task. (But if you find a genuine solution in some other compiled language, that's fine too, as long as it isn't some sort of cheating.)

# Submission

Don't submit the compiled program (as this could be potentially dangerous). Instead post your sources and a description what to do to create the final program.

# Evaluation

Let voters decide the best solution. Personally I'd appreciate solution that are elegant, short (in their source form) and didactic - that explain what's going on.

# Bonuses

Bonus points for

* Let the program output a *compressed* file containing its compiled code. This has the additional benefit that if the program is compiled into more files, the output will be a single packed file. For example, in Java try to create an executable JAR file that outputs the JAR itself.
* Outputting the MD5 sum of the compiled file(s) - so the program would write its compiled code *and* its MD5 sum.

# Answer
# Assembly (DOS .com file)

```
start:

%rep 2
    call $+3

    mov ah, 9
    mov dx, 100h + (end - start) / 2
    int 21h

    mov ah, 2
    mov dl, "$" - 1
    inc dx
    int 21h

    ret
    db "$"

%endrep

end:

```

Assemble with `nasm quine.asm -o quine.com`. Try with `dosbox quine.com`.

Proof of correctness (you can also verify by the smilies here):
> 8 votes

# Answer
# Python 2.7.3

```
#!/usr/bin/env python
import sys
import time
import struct
import compiledquine

_ = '\x63\x00\x00\x00\x00\x00\x00\x00\x00\x06\x00\x00\x00\x40\x00\x00\x00\x73\x6e\x00\x00\x00\x64\x00\x00\x64\x01\x00\x6c\x00\x00\x5a\x00\x00\x64\x00\x00\x64\x01\x00\x6c\x01\x00\x5a\x01\x00\x64\x00\x00\x64\x01\x00\x6c\x02\x00\x5a\x02\x00\x64\x00\x00\x64\x01\x00\x6c\x03\x00\x5a\x03\x00\x64\x02\x00\x5a\x04\x00\x65\x00\x00\x6a\x05\x00\x6a\x06\x00\x64\x03\x00\x65\x02\x00\x6a\x07\x00\x64\x04\x00\x65\x08\x00\x65\x01\x00\x6a\x01\x00\x83\x00\x00\x83\x01\x00\x83\x02\x00\x17\x65\x04\x00\x65\x04\x00\x16\x17\x83\x01\x00\x01\x64\x01\x00\x53\x28\x05\x00\x00\x00\x69\xff\xff\xff\xff\x4e\x73\x08\x00\x00\x00%s\x73\x04\x00\x00\x00\x03\xf3\x0d\x0a\x74\x01\x00\x00\x00\x49\x28\x09\x00\x00\x00\x74\x03\x00\x00\x00\x73\x79\x73\x74\x04\x00\x00\x00\x74\x69\x6d\x65\x74\x06\x00\x00\x00\x73\x74\x72\x75\x63\x74\x74\x0d\x00\x00\x00\x63\x6f\x6d\x70\x69\x6c\x65\x64\x71\x75\x69\x6e\x65\x74\x01\x00\x00\x00\x5f\x74\x06\x00\x00\x00\x73\x74\x64\x6f\x75\x74\x74\x05\x00\x00\x00\x77\x72\x69\x74\x65\x74\x04\x00\x00\x00\x70\x61\x63\x6b\x74\x03\x00\x00\x00\x69\x6e\x74\x28\x00\x00\x00\x00\x28\x00\x00\x00\x00\x28\x00\x00\x00\x00\x73\x1c\x00\x00\x00\x2f\x68\x6f\x6d\x65\x2f\x67\x72\x61\x6e\x74\x2f\x63\x6f\x6d\x70\x69\x6c\x65\x64\x71\x75\x69\x6e\x65\x2e\x70\x79\x74\x08\x00\x00\x00\x3c\x6d\x6f\x64\x75\x6c\x65\x3e\x02\x00\x00\x00\x73\x0a\x00\x00\x00\x0c\x01\x0c\x01\x0c\x01\x0c\x02\x06\x01'
sys.stdout.write('\x03\xf3\x0d\x0a' + struct.pack('I', int(time.time())) + _ % _)

```

Note that this **must** be saved as `compiledquine.py`. These are the results I get:

```
$ ./compiledquine.py > compiledquine.py.out
$ md5sum compiledquine.pyc compiledquine.py.out
4b82e7d94d0d59e3d647d775fffc1948  compiledquine.pyc
4b82e7d94d0d59e3d647d775fffc1948  compiledquine.py.out

```

I won't guarantee that it'll work for you, but it does consistently work for me. Here's what happens:

* At the bottom of the import statements, the script itself is imported. This compiles it to a .pyc file.
* The variable `_` is filled with the program's bytecode starting at byte 0x08, except `%s` is put in place of the variable itself.
* The script fills in the first 4 'magic' bytes, which are specific to Python 2.7.3, followed by the timestamp in the next 4 bytes, which is generated by `struct.pack` and `time.time`, and then adds `_ % _` to complete the output. (That last bit is borrowed from some other Python quines.)
* Because of the timestamp at the beginning, this script technically isn't always accurate. If the self-import and the last line execute in different seconds, the output will be a byte off.
> 3 votes

# Answer
# Lua

```
s="s=%qf=io.open('dump.txt','w')f:write(string.dump(load(s:format(s))))"f=io.open('dump.txt','w')f:write(string.dump(load(s:format(s))))

```

Now, one's first concern may be that Lua is '*An Interpreted Language, not a compiled one*' However, Lua actually interprets by compiling at runtime. `string.dump` returns the compiled byte code of the function supplied, and `load` returns the function defined by the string supplied.

Very simply, makes a function out of itself through the usual Lua quine method, then writes its compiled output.

## Output

```
LuaS “

xV           (w@‰s="s=%qf=io.open('dump.txt','w')f:write(string.dump(load(s:format(s))))"f=io.open('dump.txt','w')f:write(string.dump(load(s:format(s))))            @@€À@  A A@ € $€€  €@ ÀA † B ‡@BÆ€B @ ÁB†@ $€ä   ¤   $@  & €    sEs=%qf=io.open('dump.txt','w')f:write(string.dump(load(s:format(s))))fioopen  dump.txtwwritestringdumploadformat                                                                              _ENV

```

Contains mostly unprintable characters, so here's a Hex Dump

```
00000000:  1b4c 7561 5300 1993 0d0d 0a1a 0d0a 0408 0408 0878 5600 0000  :.LuaS..............xV...
00000018:  0000 0000 0000 0000 2877 4001 8973 3d22 733d 2571 663d 696f  :........(w@..s="s=%qf=io
00000030:  2e6f 7065 6e28 2764 756d 702e 7478 7427 2c27 7727 2966 3a77  :.open('dump.txt','w')f:w
00000048:  7269 7465 2873 7472 696e 672e 6475 6d70 286c 6f61 6428 733a  :rite(string.dump(load(s:
00000060:  666f 726d 6174 2873 2929 2929 2266 3d69 6f2e 6f70 656e 2827  :format(s))))"f=io.open('
00000078:  6475 6d70 2e74 7874 272c 2777 2729 663a 7772 6974 6528 7374  :dump.txt','w')f:write(st
00000090:  7269 6e67 2e64 756d 7028 6c6f 6164 2873 3a66 6f72 6d61 7428  :ring.dump(load(s:format(
000000a8:  7329 2929 2900 0000 0000 0000 0000 0207 1400 0000 0840 4080  :s))))................@@.
000000c0:  06c0 4000 0700 4100 4140 0100 8180 0100 2480 8001 0800 0081  :..@...A.A@......$.......
000000d8:  0680 4000 0cc0 4100 8600 4200 8740 4201 c680 4200 0601 4000  :..@...A...B..@B...B...@.
000000f0:  0cc1 4202 8601 4000 2401 8001 e400 0000 a400 0000 2440 0000  :..B...@.$...........$@..
00000108:  2600 8000 0c00 0000 0402 7314 4573 3d25 7166 3d69 6f2e 6f70  :&.........s.Es=%qf=io.op
00000120:  656e 2827 6475 6d70 2e74 7874 272c 2777 2729 663a 7772 6974  :en('dump.txt','w')f:writ
00000138:  6528 7374 7269 6e67 2e64 756d 7028 6c6f 6164 2873 3a66 6f72  :e(string.dump(load(s:for
00000150:  6d61 7428 7329 2929 2904 0266 0403 696f 0405 6f70 656e 0409  :mat(s))))..f..io..open..
00000168:  6475 6d70 2e74 7874 0402 7704 0677 7269 7465 0407 7374 7269  :dump.txt..w..write..stri
00000180:  6e67 0405 6475 6d70 0405 6c6f 6164 0407 666f 726d 6174 0100  :ng..dump..load..format..
00000198:  0000 0100 0000 0000 1400 0000 0100 0000 0100 0000 0100 0000  :........................
000001b0:  0100 0000 0100 0000 0100 0000 0100 0000 0100 0000 0100 0000  :........................
000001c8:  0100 0000 0100 0000 0100 0000 0100 0000 0100 0000 0100 0000  :........................
000001e0:  0100 0000 0100 0000 0100 0000 0100 0000 0100 0000 0000 0000  :........................
000001f8:  0100 0000 055f 454e 56                                       :....._ENV

```
> 0 votes

# Answer
# Python 3, 161 bytes

```
s = 's = %s; print(compile(s %% repr(s), \'file\', \'exec\').co_code.decode(\'utf-16\'))'; print(compile(s % repr(s), '<file>', 'exec').co_code.decode('utf-16'))

```

Try it online!

This one outputs its EXACT bytecode (that is, the bytecode that is stored in the Python interpreter when you run the program.)

# Python 3, 328 bytes (Extension)

```
import zipfile
with zipfile.ZipFile("output.zip", "w") as f:s = 'import zipfile\n\nwith open(\"output.zip\", \"w\") as f:\ns = %s\nf.writestr(\n\'output\',\ndata=(compile(s %% repr(s), \'file\', \'exec\').co_code.decode(\'utf-16\')))\n';f.writestr('output',data=(compile(s % repr(s), '<file>', 'exec')).co_code.decode('utf-16'))

```

Try it online!

This one prints its EXACT bytecode (that is, the bytecode that is stored in the Python interpreter when you run the program. It also outputs it being compressed.)
> 0 votes

---
Tags: popularity-contest, quine
---