text:
Stock Exchange KoTH
The stock market is all about the speed of knowledge. Unlike previous challenges, the current stock price is not random: it is determined by those playing the game.  If you can identify an under-priced stock before anybody else, then you've written yourself a money-making program.
Price refers to the how much people are trading the stock for, while Value refers to the amount the stock is worth at the end of the game.
Each player starts with 1000 of each stock, and 0 relative net worth.  Each stock has a secret value, and your score at the end of the game is (stockValue for each ownedStock) + netWorth.  Your net worth can be negative.  In an N-player game, there are N stocks.
Steps:
The game follows the following steps:

You are given the secret value of a single stock.
You make an offer to sell X of Y stock for $Z
All players are given the offers, and each may choose one to accept
All players are informed of accepted offers
Go back to step 2

Each of the steps are given in detail below:

void secretValue(int stockType, int value):

The value you learn is not revealed to any other player.
The value is between 0 and 1000
Low values are more like to occur than high values (squared uniform distribution)

Offer makeOffer(List<Stock> currentStock)

You can return null to make no offer.

Offer acceptOffer(List<Offer> offers)

You can return null to accept none of them
If there are no available offers, this will not be called
If you accept, your net worth goes down by $Z (can go negative) and receive X of Y stock.  The opposite occurs with the seller.
If you accept an offer, the exchange will occur immediately, and the offer will be removed so additional players cannot accept it.

void acceptedOffers(List<Offer> offers)

Includes your accepted offers as well

Static variables or writing to files is not allowed.  (No persistent data from game to game)  Non-serious contenders are allowed.
Interfaces:
public final class Stock {
    public Stock(int stockType, int amount);
    public int getType();
    public int getAmount();
    public Stock minus(Stock other);
    public Stock plus(Stock other);
    public Stock minus(int amount);
    public Stock plus(int amount);
    public Stock setAmount(int amount);
}
public class Offer {
    public Offer(Stock offer, int payment);
    public Stock getOffer();
    public int getPayment();
}

Non-Java submissions:

All calls consist of two lines: The first line is the function being called: SecretValue, MakeOffer, AcceptOffer, AcceptedOffers, SetRandom, and the second line containing the actual data.
Stocks are formatted with a : delimiter: stockType:stockAmount.
Offers are formatted with a @ delimiter: offer@price
Lists are formatted with a ; delimiter
SecretValue is formatted with a : delimiter: stockType:value
RandomSeed is used to make your submission deterministic.  If your submission uses randomness, please use the integer value passed as the seed!
All function calls need a response.  If the response is null or void, return an empty string.
Please include a command.txt that gives the command line arguments to run your submission

Scoring
Games consisting of 1000 turns will be run multiple times.  Players will be scored according to the ELO system, and paired with players of similar skill levels.  The player with the highest final ELO score wins!  (I've modified the system so that each game, ELO scores are updated for each player pairing)
The controller includes an autodownloader, so please start your submission with a header: Name, Language.  If your submission is not in Java, each code block should start with the name of the file.  (excluding the command file, which should be the first block in your post)
Running
There are 2 ways to run this project:

Download the source code, compile and run.  You can find the source on Github.  Run git clone --recursive https://github.com/nathanmerrill/StockExchange.git
Download the JAR executable.  Submissions should be placed in your current working directory in the /submissions folder.  You can download just the JAR, just the submissions, or both

Pass in run to run the project (default option), or pass in download to download all submissions so far from this question.
Scoreboard
1.  1308.1220497323848  Cheater
2.  1242.0333695640356  InsideTrader
3.  1158.3662658295411  UncleScrooge
4.  1113.8344000358493  BlackMarket
5.  1051.8370015258993  DartMonkey
6.  983.0545446731494   WarGamer
7.  939.457423938002    Spammer
8.  901.4372529538886   DumbBot
9.  859.0519326039137   ShutUpAndTakeMyMoney
10. 852.9448222849587   VincentKasuga
11. 718.2112067329083   Profiteer

stock properties aren't public, instruct to use getter methods

@AgentCrazyPython better?

are current prices correlated to previous prices?

The "price" is simply the amount people are selling stock for.  Values of stock change from game to game.

Btw, trueskill is a better ranking system than the elo system. You can find an implementation here.

ability to accept multiple offers, please.

API to get number of turns.

@Accepting Accepting multiple offers won't be supported.  To get number of turns, StockExchange.NUM_EXCHANGES

A chat room would be appreciated.

"Published formulas for Trueskill are not complete"

http://chat.stackexchange.com/rooms/44660/stock-exchange

Wikipedia is wrong. A full implementation is here. A full description of the formulas used is here.

I need to know when it ends to help my new bot...

@AgentCrazyPython you can use a member variable to keep track of the number of turns.  MakeOffer() will be called exactly 1000 times

if nobody makes an offer for a stock, then what's the price at the end? Critical to my bot.

The value at the end is determined randomly, and is independent of the prices being offered.  You get to know the end value of exactly 1 stock.

So, if nobody buys a stock, what's it's value? Average of offers?

It is determined by the controller and not shown to your program.

@NathanMerrill OH I GET IT! Value is different. Then my market corner strat doesn't work..............

Exact formula is Math.ceil(Math.pow(random.nextDouble(), 2) * 1000)

Well it might work because of dumb bots... but not as well...

something that can work is a program that make averages on stock market shares (=="azioni")
for find if there are unusual buy or sale of these stock market shares.
If there are many buy  on one stock share: computer has to buy that stock market share.
if there are many sale on one stock market  share: sale that one.
this is because I as the program computer not have enought info
for sale or buy, no sure info, no true info or important info on what is going on in the market.
Yes it is better if one have some info true on that market and use these. i don't know translation is right...

@RosLuP if I understand you, you are saying to sell when others are selling, and buy when others buy.  This sounds like a good strategy!

@Nathan: yes if i have no good info: selling what other people sell, buy what they are buying (if there are big evidence on these). But i'm not an expert so i can make it wrong...

@TimmyD 1000 turns.  Added, thanks.

Quick clarification: when accepting offers, the end value of that stock will be (stock.amount * stock.secretValue) yes?

@SocraticPhoenix correct

In the controller, StockExchange.nextStep, you shuffle the players before making offers to them, but I think you should also shuffle the offers (either once or before each call to giveOffers).

@PeterTaylor You're right.  The order of offers matters (only slightly), but good catch.

poking question

Cheater, Java
Tries to sell nothing for money.
import java.util.List;
import java.util.Random;
import com.ppcg.stockexchange.*;

public class Cheater extends Player {
    private Random random = new Random();

    public Offer acceptOffer(List<Offer> offers) {
        return null;
    }

    public Offer makeOffer(List<Stock> currentStock){
        Stock stock = randomStock();
        int price = random.nextInt(100) + 1;
        return new Offer(stock.setAmount(0), price);
    }
}

And that's how the great depression happens! I could see this breaking a lot of bots that buy cheap...

Congrats!  I fixed a critical bug, and now this bot is in first!

Wow, the other bots are not good enough then, that this dumb bot can win

WarGamer, Java
Upon a perfunctory examination of the rules I have decided that the primary winning move is not to play. Anyone offering to sell stock likely knows the price and will profit from the sale. It can be toggled so it will make "joke" offers to sell a stock for Integer.MAX_VALUE dollars hoping shut up and take my money will bite.
import java.util.List;
import com.ppcg.stockexchange.*;
import com.ppcg.kothcomm.game.AbstractPlayer;
import com.ppcg.kothcomm.utils.Tools;

import java.util.List;

public class WarGamer extends Player {
static final boolean FRAUD = false;
    /**
     * @param offers All available offers
     * @return An offer you want to accept, or null if you want to accept neither.
     */
    public Offer acceptOffer(List<Offer> offers){
        return null;
    }

    public Offer makeOffer(List<Stock> currentStock){
    if(FRAUD)
    return new Offer(new Stock(0,1),Integer.MAX_VALUE);
        //defraud shut up and take my money
    return null;
    }
}

This would probably work fine, except I expect there will be entries that dumb-luck their way slightly higher. There usually are.

This doesn't compile.

@Rainbolt it has the dependencies. You need to make sure are present.

@Rainbolt what compiler error are you getting

Exception in thread "main" java.lang.RuntimeException: Error on line 8: com.ppcg.stockexchange.WarGamer is not abstract and does not override abstract method makeOffer(java.util.List<com.ppcg.stockexchange.Stock>) in com.ppcg.stockexchange.WarGamer

abstract cause the compilation to fail; a valid version of this code is http://pastebin.com/WmaZt8rL

@Rainbolt sorry

@Geobits it now defrauds shut up and take my money for max profit

I'm not sure the part where you trick the other joke bot is in the right spirit...

@Maltysen your right. It was a bit cheaty of me

@Maltysen I'll add a flag so that "feature" can be toggled

Your if statement made it not compile.  Remove the semicolon after it.  Also, remove the package.

Also, please use the import statements from DumbBot.  Your current imports are wrong.

@NathanMerrill I  am nothing but my IDE, sorry.

Fixed the bugs mentioned let me know if there are any more problems

According to the koth tag wiki, strategies that specifically target other bots are at the least discouraged, if not disallowed by default

@SocraticPhoenix that is why FRAUD is set to false

You still need to remove the package statement.

@NathanMerrill fixed

ShutUpAndTakeMyMoney, Java
import java.util.List;
import com.ppcg.stockexchange.*;

public class ShutUpAndTakeMyMoney extends Player {
    public ShutUpAndTakeMyMoney() {}

    public Offer acceptOffer(List<Offer> offers) {
        try {
            return offers.get(0);
        } catch (Exception ex) {
            return null;
        }
    }
    public Offer makeOffer(List<Stock> stock) {
        return null;
    }
}

It accepts any offer.

Actually thank you for your bot

have +1 for making me rich

It seems to me that this isn't really compatible with the requirement that every answer should "be a serious contender for the winning criteria in use".

@PeterTaylor It's serious, it's 5th on the leaderboard

This is arguably a suicidal entry, as it's reasonable to expect that other bots will sell stocks for more than they are worth, leading to you buying stock for well over its actual price.

While not very competitive, I would categorise this more as a baseline submission rather than a suicidal one. While I'm not deleting this, I would recommend to future KOTH writers to include baseline solutions in the question itself rather than letting other users post them. This both initialises KOTHs so that you don't have to wait for multiple solutions and lets users check that their solutions are at least better than doing nothing at all.

DumbBot, Java
Use this bot when creating your own.  Offers its secret stock at a discounted price.
import java.util.List;
import com.ppcg.stockexchange.*;
public class DumbBot extends Player {
    public Offer acceptOffer(List<Offer> offers) {
        return null;
    }
    public Offer makeOffer(List<Stock> currentStock){
        return new Offer(currentStock.get(secretStockType).setAmount(1), Math.max(1, secretStockValue - 5));
    }
    public void secretValue(int stockType, int value) {
        super.secretValue(stockType, value);
    }
    public void acceptedOffers(List<Offer> acceptedOffers) {
    }
}

Seems like I want him handling my money

please make this community wiki

@AgentCrazyPython why?

@NathanMerrill rep profiting off of this dummy bot

@AgentCrazyPython I don't really want people to be editing this...  I don't really care about rep, so feel free to not upvote (or downvote)

It seems to me that this isn't really compatible with the requirement that every answer should "be a serious contender for the winning criteria in use".

@PeterTaylor you're right.  When I'm constructing games, I select players of similar skill, so I'm ok with non-serious contenders.  I'll add that to the question.

I don't think question askers are permitted to override that sitewide policy.

Reference meta link?

The fact that "Be a serious contender for the winning criteria in use." is a separate requirement from "Correctly implement the required specification." in the help center. I couldn't find any meta questions on it, so you could post one if you want two, but otherwise I'll flag this answer for deletion in two days in accordance with the policy on invalid answers.

I'd personally argue that non-serious contenders can make certain KoTH challenges more interesting, so I'd argue that KoTHs (at least) should be able to override that.  This particular answer was simply here to be copy/pasteable, so it doesn't really fit that bill, though.  This is not a good proponent answer to push the issue.  Feel free to mark it for deletion, I'd be curious to see if it others agree with you.

Given this is posted by the question asker, I think the better solution would be moving this to the question body as an example/template for future solutions. You could still include the bot in future iterations of the competition, at least as a baseline for whether new submissions are competitive

python_starter, Python 3
Use this as a starting point for any python (or other language) programs
Accepts a random offer.
Command file:
python3 starter.py

Program:
starter.py
import random
from functools import total_ordering

LIST_DELIMITER = ';'
STOCK_DELIMITER = ':'
OFFER_DELIMITER = '@'

@total_ordering
class Stock:
    @staticmethod
    def parse(string: str):
        return Stock(*map(int, string.split(STOCK_DELIMITER)))

    def __init__(self, stock_type: int, amount: int):
        self.type = stock_type
        self.amount = max(amount, 0)

    def __str__(self):
        return str(self.type)+STOCK_DELIMITER+str(self.amount)

    def __eq__(self, other):
        return self.amount == other.type

    def __lt__(self, other):
        return self.amount < other.amount

    def update(self, amount) -> 'Stock':
        return Stock(self.type, amount)

    def __mul__(self, other: int) -> 'Stock':
        return self.update(self.amount*other)

    def __floordiv__(self, other: int) -> 'Stock':
        return self.update(self.amount//other)

    def __add__(self, other: int) -> 'Stock':
        return self.update(self.amount+other)

    def __sub__(self, other: int) -> 'Stock':
        return self.update(self.amount-other)

class Offer:
    @staticmethod
    def parse(string: str) -> 'Offer':
        try:
            offer, payment = string.split(OFFER_DELIMITER)
        except ValueError:
            raise Exception("Cannot unpack "+string)
        return Offer(Stock.parse(offer), int(payment.strip()))

    def __init__(self, offer: Stock, payment: int):
        self.offer = offer
        self.payment = payment

    def __str__(self):
        return str(self.offer)+OFFER_DELIMITER+str(self.payment)

def read_stock_value(value: str):
    global hidden_price, hidden_stock
    stock, price = value.split(STOCK_DELIMITER)
    hidden_price = float(price)
    hidden_stock = int(stock)

def process_input():
    handlers = {
        "SecretValue": read_stock_value,
        "RandomSeed": read_seed,
        "MakeOffer": make_offer,
        "AcceptOffer": accept_offer,
        "AcceptedOffers": accepted_offers,
    }
    method = input().strip()
    data = input().strip()
    output = handlers[method](data)
    if output is not None:
        print(str(output))
    else:
        print()

def read_seed(seed: str):
    random.seed(int(seed))

def start():
    while True:
        process_input()

hidden_stock = None
hidden_price = None

def make_offer(current_stock: str):
    current_stock = map(Stock.parse, current_stock.split(LIST_DELIMITER))
    pass

def accept_offer(available_offers: str):
    available_offers = list(map(Offer.parse, available_offers.split(LIST_DELIMITER)))
    return random.sample(available_offers, 1)[0]

def accepted_offers(offers: str):
    offers = map(Offer.parse, offers.split(LIST_DELIMITER))
    pass

if __name__ == "__main__":
    start()

this is too complicated.

Most of it is helper stuff.  If you're writing it in python, you just need to implement the bottom 3 functions.

what does it do?

The bot accepts a random stock.  The helper stuff does parsing/encoding, as well as provides classes for Offer/Stock.

...and it's winning :/

how to use boilerplate?

Copy everything, and implement the bottom 3 functions.

yes, but what's the API for stock and offfer classes?

Basic mathematical operations with stock will work (stock*3, for example).  if you return a stock or offer, it'll automatically get stringified.  stock.amount to get the amount, stock.type to get the type.  offer.offer to get the stock getting offered, and offer.payment to get the amount its getting sold for

VincentKasuga, Java
Not sure if my Java is valid. Please review.
How it works

 - if you own all the stocks, you can set the price of the stock. You are the only seller.
  1. Buy all the stocks.
  2. Set the price of all the stocks to be super high on the last tick.
  3. PROFIT!
 - This isn't normally possible because...

The price would usually skyrocket to infinity... but there's a limit!
... (more reasons to come)

How it works, v2

The price is artificially set at a maximum by some anarchist state
This is bad economically
The bot doesn't predict - it exploits an inherent flaw in the structure of the market!

Todo

Corner the market multiple times! Muahaha!

FAQ
Q: Who's Vincent Kasuga?
A: He bought all the onions and onion futures in the United States. (put them all in a secret warehouse) Held the industry at ransom - give me X million or I'll set the price sky-low and you'll all go bankrupt.
But he didn't stop there.
Then, he secretly shorted the onion ETF (bet that it would go down). He sold all the onions at one time, physically delivering them in thousands of trucks to the stock exchange. The onion bag cost less than the onions. He made millions AGAIN.  In short, the Hudson river overflowed with onions.
He's a real person.
The code
import com.ppcg.stockexchange.Offer;
import com.ppcg.stockexchange.Player;
import com.ppcg.stockexchange.Stock;

import java.util.List;

public class VincentKasuga extends Player {
    private int knownStock;
    private int knownPrice;
    private int corneredStockType = -1;
    private int corneredLikelehood = 0;
    private boolean marketCornered;
    private int ticks;

    public Offer acceptOffer(List<Offer> offers) {
        if (!marketCornered) {
            Offer maxOffer = null;
            int maxAmount = 0;
            if (corneredStockType == -1) {
                for (Offer offer: offers) {
                    if (offer.getOffer().getAmount() > maxAmount) {
                        maxAmount = offer.getOffer().getAmount();
                        maxOffer = offer;
                    }
                }
            } else {
                for (Offer offer: offers) {
                    if (offer.getOffer().getAmount() > maxAmount && offer.getOffer().getType() == corneredStockType) {
                        maxAmount = offer.getOffer().getAmount();
                        maxOffer = offer;
                    }
                }
            }

            if (maxOffer == null) {
                // may have cornered the market
                corneredLikelehood++;
                if (corneredLikelehood == 5) {
                    // probably cornered the market
                    marketCornered = true;
                }
            }
            return maxOffer;
        } else {
            // who needs offers when the market is cornered!?
            return null;
        }
    }

    public Offer makeOffer(List<Stock> currentStock) {
        ticks++;
        if (ticks >= 999) {
            // SELL SELL SELL!
            return new Offer(new Stock(corneredStockType, 1000), 1000);
        } else {
            return null;
        }
    }

    public void secretValue(int stockType, int value) {
        knownStock = stockType;
        knownPrice = value;
        if (stockType == corneredStockType) {
            if (knownPrice == 1000) {
                corneredLikelehood += 3;
            } else if (knownPrice < 900){
                // didn't corner the market.
                corneredLikelehood = 0;
            }
        }
    }
}

"I've cornered the Gold Market, Mr. Bond!"

I've included an auto-downloader for bots.  Please put your code in a code-block.  If it won't fit, that's fine.

@NathanMerrill I understand. But does it compile?

@NathanMerrill done. Probs doesn't compile. interesting strategy, eh? And a lesson in economics!

for (offer: offers) -> for (Offer offer: offers)

corneredStockType == null is also not valid. an int cannot be null.

@AgentCrazyPython I fixed the syntax errors for you, you can accept them here (at least, I'm pretty sure you can)

@SocraticPhoenix thanks. I was too lazy to set up my IDE and import all the modules...

This bot is occasionally return an offer with a type of -1.

Spammer, Java
import java.util.List;
import java.util.ArrayList;
import com.ppcg.stockexchange.*;

public class Spammer extends Player {
    private boolean panic = false;

    public Offer acceptOffer(List<Offer> offers) {
        for (Offer offer : offers) {
            if (this.panic || offer.getPayment() < 20)
                return offer;
        }
        return null;
    }
    public Offer makeOffer(List<Stock> currentStock) {
        if (currentStock.size() > 1) { // Don't sell all the stock
            this.panic = false;
            return new Offer(currentStock.get(secretStockType).setAmount(1), 1);
        }
        this.panic = true; // BUY
        return null;
    }
}

Spam the market with really cheap stock, and only buy stock when the price is lesser than 20. When the stock count fall to 1, it will try to buy anything.

works well in Great Depression

...how is this winning!?

WallStreet, Kotlin
Starts by selling high and buying low and gradually shifts to what it thinks the price really is. Also, you can use this as a template for making your own in kotlin.
Note: There is a bug in here that I can't seem to reliably reproduce. If my program crashes or has problems, please ping me in chat and link a pastebin of the contents of submissions/other/WallStreet/log.txt
kotlinc WallStreet.kt
kotlin WallStreetKt

WallStreet.kt
import java.io.FileOutputStream
import java.io.PrintStream
import java.util.*

val LOGGER = PrintStream(FileOutputStream("log.txt", true))
const val DEBUG = false

const val LOG_GAME_HEADER = """
###############
#STARTING GAME#
###############"""

data class Stock(val type : Int, val amount : Int) {

    operator fun minus(amount : Int) = copy(amount = this.amount - amount)
    operator fun plus(amount: Int) = copy(amount = this.amount + amount)
    fun setAmount(amount: Int) = copy(amount = amount)

    operator fun minus(other : Stock) : Stock {
        assert(type == other.type)
        return copy(amount = this.amount - other.amount)
    }

    operator fun plus(other : Stock) : Stock {
        assert(type == other.type)
        return copy(amount = this.amount + other.amount)
    }

    override fun toString() = "$type:$amount"
}

data class Offer(val offer: Stock, val payment: Int) {
    override fun toString() = "$offer@$payment"
}

fun parseStock(repr : String) : Stock {
    val data = repr.split(":").map { it.toInt() }
    return Stock(data[0], data[1])
}

fun parseOffer(repr: String) : Offer {
    val data = repr.split("@")
    return Offer(parseStock(data[0]), data[1].toInt())
}

fun parseOffers(repr: String) = if (repr == "") emptyList<Offer>() else repr.split(";").map { parseOffer(it) }

interface Player {
    fun secretValue(stockType: Int, value: Int)
    fun makeOffer(currentStock: List<Stock>) : Offer?
    fun acceptOffer(offers: List<Offer>) : Offer?
    fun acceptedOffers(offers: List<Offer>)

    var random : Random
}

fun main(args : Array<String>) {

    try {

        if (DEBUG) {
            LOGGER.println(LOG_GAME_HEADER)
        }
        //Change bot name here
        val player = WallStreet()

        while (true) {
            val function = readLine()
            function ?: return
            val line = readLine()!!
            if (DEBUG) {
                LOGGER.println("\nInput:")
                LOGGER.println(function)
                LOGGER.println(line)
            }
            var result : Any
            try {
                result = when (function) {
                    "SecretValue" -> {
                        val data = line.split(":").map { it.toInt() }
                        player.secretValue(data[0], data[1])
                    }
                    "MakeOffer" -> player.makeOffer(line.split(";").map { parseStock(it) }) ?: ""
                    "AcceptOffer" -> player.acceptOffer(parseOffers(line)) ?: ""
                    "AcceptedOffers" -> player.acceptedOffers(parseOffers(line))
                    "RandomSeed" -> player.random = Random(line.toLong())
                    else -> return        //Exit program
                }
                if (function == "AcceptOffer" && result.toString() !in line) {
                    throw Exception("Offer not among available offers!!!!\nResult: $result\nParsed Available Offers: ${parseOffers(line)}")
                }
            } catch (e : Exception) {
                LOGGER.println("Turn #${player.turn}")
                LOGGER.println("\nInput:")
                LOGGER.println(function)
                LOGGER.println(line)
                throw e
            }

            if (result == Unit) {
                result = ""
            }
            if (DEBUG) {
                LOGGER.println("Output:")
                LOGGER.println(result)
            }

            println(if (result == Unit) "" else result)
        }
    } catch (e : Exception) {
        e.printStackTrace(LOGGER)
        throw e
    } finally {
        LOGGER.close()
    }
}

// ###################################################
// #          Put program logic below here.          #
// ###################################################

const val DEFAULT_STOCK_VALUE = 333
const val MAX_TURNS = 1000
const val MAX_STOCK_VALUE = 1000

class WallStreet : Player {

    var secretStockType = 0
    var secretStockValue = 0
    override var random = Random()

    var turn = 0
    val stockPriceStatistics = mutableMapOf<Int, DoubleSummaryStatistics>()

    override fun secretValue(stockType: Int, value: Int) {
        secretStockType = stockType
        secretStockValue = value
    }

    override fun makeOffer(currentStock: List<Stock>): Offer {
        val stock = currentStock[random.nextInt(currentStock.size)]
        val type = stock.type
        val amount = random.nextInt(stock.amount)
        val price = getSellPrice(type) * amount
        return Offer(Stock(type, amount), Math.ceil(price).toInt())
    }

    override fun acceptOffer(offers: List<Offer>): Offer? {
        var bestOffer : Offer? = null
        var mostProfit = 0.0
        for (offer in offers) {
            val offerProfit = profitOfOffer(offer)
            if (offerProfit > mostProfit) {
                bestOffer = offer
                mostProfit = offerProfit
            }
        }
        if (bestOffer != null && bestOffer !in offers) {
            throw IllegalStateException("Tried to accept non-existent offer.\nOffer:  $bestOffer\nAvailable Offers: ${offers.joinToString(";")}")
        }
        return bestOffer
    }

    override fun acceptedOffers(offers: List<Offer>) {
        turn++
        for ((stock, payment) in offers) {
            val stats = stockPriceStatistics.getOrPut(stock.type) { DoubleSummaryStatistics() }
            for (i in 1..stock.amount) {
                stats.accept(payment.toDouble() / stock.amount)
            }
        }
    }

    private fun getSellPrice(type: Int): Double {
        var price = getPrice(type)
        if (price < 1000) {
            price += (1000 - price) * (MAX_TURNS - turn) / MAX_TURNS
        }
        return if (type == secretStockType) Math.max(secretStockValue.toDouble(), price) else price
    }

    private fun getPrice(type: Int): Double {
        return stockPriceStatistics[type]?.average ?: DEFAULT_STOCK_VALUE.toDouble()
    }

    private fun profitOfOffer(offer: Offer): Double {
        return getBuyPrice(offer.offer.type) * offer.offer.amount - offer.payment
    }

    private fun getBuyPrice(type: Int): Double {
        var price = getPrice(type)
        price = price * turn / MAX_TURNS
        return if (type == secretStockType) Math.min(secretStockValue.toDouble(), price) else Math.min(price, MAX_STOCK_VALUE.toDouble())
    }

}

command.txt doesn't need the file name.   Nice post!

I thought string interpolation was done with ${}, not just $?

@SocraticPhoenix $ only works with a variable name. ${} executes arbitrary code. Basically, it works either way and I prefer without the braces.

FYI: as a temporary solution, window users who want to run this file need to change the command.txt: kotlinc->kotlinc.bat and kotlin->kotlin.bat

Once I fixed my controller, this bot started returning a bunch of bad data, so I removed it from the competition.  I can help you in the chat room if you want :)

InsideTrader, Java
InsideTrader just looked around and saw that everybody was trying to be creative. But he did something creative: do what is expected.
This bot buys when it's "worth it" because it "borrowed" some "internal documents" to "guide" "investing decisions".
To-Do and how it works in the code. ;)
The "code"
import java.util.List;

import com.ppcg.stockexchange.*;

public class InsideTrader extends Player {
    public String coverStory = "I can tell the good companies from the bad ones.";
    private String theTruth = "I'm cheating. (but so is everyone else)";
    private String ambitions = "Learn to \"follow the market\"";  // don't steal this idea
    private int secretStock = -1;
    private int secretStockValue = -1;

    private int appraiseOffer(Offer offer) {
        /* get how much the offer is worth, 0 if it's not the secret stock */
        if (offer.getOffer().getType() != secretStock ||offer.getOffer().getAmount() == 0) {
            return 0;
        }
        return (offer.getPayment()/offer.getOffer().getAmount())  // price per stock...
                - secretStockValue  // minus value of stock.
                ;
    }
    public Offer acceptOffer(List<Offer> offers) {
        Offer bestOffer = null;
        int bestOfferValue = -1;
        for (Offer offer :
                offers) {
            int value = appraiseOffer(offer);
            if (value > bestOfferValue && value > 0) {
                bestOfferValue = value;
                bestOffer = offer;
            }
        }
        return bestOffer;
    }

    public Offer makeOffer(List<Stock> currentStock) {
        return new Offer(new Stock(0,1), Integer.MAX_VALUE);
    }

    public void secretValue(int stockType, int value) {
        secretStock = stockType;
        secretStockValue = value;
    }

    public void acceptedOffers(List<Offer> acceptedOffers) {

    }
}

You can't have those extra classes at the start of the file... it's syntactically invalid... they can be appended to the end without public, i think

Error on line 50: modifier private not allowed here Error on line 54: modifier private not allowed here.  I'd just remove the classes, and have it extend Player

Just a note, some new bots are offering stocks at amounts of zero, so your bot is throwing an ArithimeticException (/ by zero) from the return of appraiseOffer... maybe add a check or something?

@SocraticPhoenix Thanks, will fix.

Congrats, this bot is currently in second!

DartMonkey, Java
(non-competing: It won't win and I already have another answer)
Dart monkey likes throwing things... and there's a big pile of pointy sticks next to him. He sees some paper on the wall. Bam! Bam! Bam! In no time at all, Dart Monkey's thrown 80 darts! Half the darts are red, and the other half are blue, and there's random numbers on them! Dart monkey sees a computer... dart monkey types in the numbers. Dart monkey likes numbers. Dart monkey makes some money from his darts...

In all seriousness, DartMonkey initializes an integer array that has a length that is twice the number of stocks. He stores one number for the amount of stock he wants to buy/sell, and one number for the price of the stock. He then alternates selling stock from the array, and accepting offers according to the array. If he has no stock from the array, he won't offer anything, and if he has no offers given to him from the array, he won't accept anything.

This answer was inspired by @TheNumberOne, who mentioned dart monkeys in the chat
import com.ppcg.stockexchange.Offer;
import com.ppcg.stockexchange.Player;
import com.ppcg.stockexchange.Stock;

import java.util.List;
import java.util.Random;

public class DartMonkey extends Player {
    private int basePrice = 100;
    private int numStocks;
    private int[] dartBoard;
    private boolean first = true;

    @Override
    public Offer acceptOffer(List<Offer> offers) {
        for(Offer offer : offers) {
            Stock stock = offer.getOffer();
            int type = stock.getType();
            int amount = stock.getAmount();
            int price = offer.getPayment();
            if(this.dartBoard[type] < 0 && amount <= -this.dartBoard[type] && price <= this.dartBoard[type + this.numStocks]) {
                this.dartBoard[type] = 0;
                return offer;
            }
        }
        return null;
    }

    @Override
    public Offer makeOffer(List<Stock> stocks) {
        if(this.first) {
            this.first = false;
            this.numStocks = stocks.size();
            this.dartBoard = new int[this.numStocks * 2];
            Random random = this.getRandom();
            for (int i = 0; i < 20; i++) {
                int index = random.nextInt(this.dartBoard.length / 2);
                this.dartBoard[index] = random.nextInt(1001);
                this.dartBoard[this.numStocks + index] = random.nextInt(1001);
            }

            for (int i = 0; i < 20; i++) {
                int index = random.nextInt(this.dartBoard.length / 2);
                this.dartBoard[index] = -random.nextInt(1001);
                this.dartBoard[this.numStocks + index] = random.nextInt(1001);
            }
        }

        for (Stock stock : stocks) {
            int type = stock.getType();
            if(this.dartBoard[type] > 0) {
                Offer offer = new Offer(stock.setAmount(this.dartBoard[type]), this.basePrice + this.dartBoard[type + this.numStocks]);
                this.dartBoard[type] = 0;
                this.dartBoard[type + this.numStocks] = 0;
                return offer;
            }
        }

        return null;
    }

}

I see you have went on a random walk down wall street?

This is arguably a suicidal entry, which are not allowed.

@Mego I don't see how... A suicidal entry would sell stock for 0 dollars, this entry determines what it buys and sells randomly. Which is definitely not against the rules....

UncleScrooge, Java
import java.util.List;
import com.ppcg.stockexchange.*;

public class UncleScrooge extends Player {
    public Offer acceptOffer(List<Offer> offers) {
        Offer offer;
        try {
            offer = offers.get(0);
        } catch (Exception ex) {
            return null;
        }
        if (offer.getPayment() < 100)
            return offer;
        else
            return null;
    }
    public Offer makeOffer(List<Stock> currentStock){
        if (this.getRandom().nextDouble() < 0.6)
            return new Offer(currentStock.get(secretStockType).setAmount(1), Integer.MAX_VALUE);
        else
            return null;
    }
    public void secretValue(int stockType, int value) {
        super.secretValue(stockType, value);
    }
    public void acceptedOffers(List<Offer> acceptedOffers) { }
}

Sell stock at a really high price, and only buy if the price is less than 100.

Profiteer, Java
Profiteer is in it for the money, and he's always counting coins. He makes a conservative estimate of how much money he's got. He'll then buy the secret stock, if it's less than the value, or buy cheap stock. He also remembers how much he's paid for everything, and always makes offers above the stock price. Furthermore, he'll make higher offers if he has less money.
Note: I think I've done this correctly, but if @NathanMerrill wouldn't mind skimming my code for bugs, that'd be great
import com.ppcg.stockexchange.Offer;
import com.ppcg.stockexchange.Player;
import com.ppcg.stockexchange.Stock;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

public class Profiteer extends Player {
    private List<StockInfo> onMarket;
    private List<StockInfo> stocks;
    private int money;
    private boolean first = true;

    @Override
    public Offer acceptOffer(List<Offer> offers) {
        Offer finalOffer;

        Optional<Offer> offer = offers.stream().filter(o -> o.getOffer().getType() == this.secretStockType && o.getPayment() < this.secretStockValue * o.getOffer().getAmount()).sorted((a, b) -> Integer.compare((this.secretStockValue * a.getOffer().getAmount()) - b.getPayment(), (this.secretStockValue * b.getOffer().getAmount()) - b.getPayment())).findFirst();
        if (offer.isPresent()) {
            finalOffer = offer.get();
        } else {
            finalOffer = offers.stream().sorted((a, b) -> Integer.compare(a.getPayment(), b.getPayment())).findFirst().orElse(null);
        }

        if (finalOffer == null || this.money <= finalOffer.getPayment()) {
            return null;
        } else {
            this.stocks.add(new StockInfo(finalOffer.getOffer(), finalOffer.getPayment()));
            this.refreshMoney();
            return finalOffer;
        }
    }

    @Override
    public Offer makeOffer(List<Stock> stocks) {
        if (this.first) {
            this.init(stocks);
        } else {
            this.refreshMarketList(stocks);
        }

        Optional<StockInfo> least = this.stocks.stream().sorted((a, b) -> Integer.compare(a.getBoughtPrice(), b.getBoughtPrice())).findFirst();
        Optional<StockInfo> secret = this.stocks.stream().filter(stockInfo -> stockInfo.getStock().getType() == this.secretStockType).sorted((a, b) -> Integer.compare(a.getBoughtPrice(), b.getBoughtPrice())).findFirst();

        StockInfo finalOffer;
        int price;
        if (secret.isPresent()) {
            finalOffer = secret.get();
        } else if (least.isPresent()) {
            finalOffer = least.get();
        } else {
            return null;
        }

        this.onMarket.add(finalOffer);
        this.stocks.remove(finalOffer);
        price = this.calculatePrice(finalOffer.boughtPrice);
        return new Offer(new Stock(finalOffer.getStock().getType(), finalOffer.getStock().getAmount()), price);
    }

    private int calculatePrice(int boughtPrice) {
        return (int) (boughtPrice + ((boughtPrice / (double) this.money) * this.money)) + 1;
    }

    private void refreshMarketList(List<Stock> stocks) {
        this.stocks.addAll(this.onMarket.stream().filter(stockInfo -> stocks.contains(stockInfo.getStock())).collect(Collectors.toList()));
        this.onMarket.clear();
    }

    private void refreshMoney() {
        this.money = this.stocks.stream().mapToInt(info -> this.secretStockType == info.getStock().getType() ? this.secretStockValue : 5).reduce((a, b) -> a + b).orElseGet(() -> 0) - this.stocks.stream().mapToInt(StockInfo::getBoughtPrice).reduce((a, b) -> a + b).orElseGet(() -> 0);
    }

    private void init(List<Stock> stocks) {
        this.stocks = stocks.stream().map(stock -> new StockInfo(stock, 0)).collect(Collectors.toList());
        this.onMarket = new ArrayList<>();
        this.money = 0;
        this.first = false;
        this.refreshMoney();
    }

    private static class StockInfo {
        private Stock stock;
        private int boughtPrice;

        public StockInfo(Stock stock, int boughtPrice) {
            this.stock = stock;
            this.boughtPrice = boughtPrice;
        }

        public Stock getStock() {
            return this.stock;
        }

        public int getBoughtPrice() {
            return this.boughtPrice;
        }

    }

}

you can go into debt and still by stocks...

@AgentCrazyPython I know, but profiteer doesn't want to risk it

can't undownvote

@AgentCrazyPython meh, it's okay, the game is fun and that's what matters

MaxBot, Java
This bot tries to make the most profit out of each transaction. While selling, puts the price of an unknown stock at $300, when buying $250.
import java.util.List;
import com.ppcg.stockexchange.*;
public class MaxBot extends Player {
    int toSell;
    int sellPrice;

    public void secretValue(int stockType, int value) {
        super.secretValue(stockType, value);
        toSell = stockType;
        sellPrice = (value + 1000)/2;
    }
    public Offer acceptOffer(List<Offer> offers) {
        Offer max = null;
        int maxDif = 0;
        for(Offer o: offers){
            int price = secretStockType == o.getOffer().getType()? secretStockValue: 250;
            int val = price * o.getOffer().getAmount();
            int dif = val - o.getPayment();
            if(maxDif < dif){
                max = o;
                maxDif = dif;
            }
        }
        return max;
    }
    public Offer makeOffer(List<Stock> currentStock){
        if(toSell == -1){
            return null;
        }
        int sum = 0;
        for (Stock s: currentStock){
            if(s.getType() == toSell){
                sum += s.getAmount;
            }
        }
        int n = sum - sum/2;
        return new Offer(new Stock(toSell, n), n * sellPrice);
    }
    public void acceptedOffers(List<Offer> acceptedOffers) {
        int highStock = -1;
        int highPrice = 0;
        int markup = 0;
        for(Offer o: offers){
            int trueVal = secretStockType == o.getOffer().getType()? secretStockValue: 250;
            int marketVal = o.getPayment()/o.getOffer().getAmount();
            if(marketVal - trueVal > markup){
                highStock = o.getOffer().getType();
                highPrice = marketVal;
                markup = marketVal - trueVal;
            }
        }
        toSell = highStock;
    }
}

BlackMarket, Java
Not much to say about this one, seeing as these transactions will be... off the charts, you might say.
import java.util.List;
import com.ppcg.stockexchange.*;

public class BlackMarket extends Player {
    private boolean approvedBySEC = false;
    private int ammoLeft = 30;
    public String taxView = "We want higher tax rates";
    public String excuse = "I never saw that in my life";

    public void secretValue(int drugType, int warrantForMyArrest) {
        super.secretValue(drugType, warrantForMyArrest);
        if (warrantForMyArrest != 0 || drugType == 420) {
            ammoLeft += 10;
        }
    }

    public Offer acceptOffer(List<Offer> offers) {
        for (Offer offer : offers) {
            if (this.approvedBySEC || offer.getPayment() < 9)
                return offer;
        }
        return null;
    }

    public Offer makeOffer(List<Stock> currentStock) {
        return new Offer(new Stock(0,1),420);
    }
}

return null is outside... please indent properly too.

@AgentCrazyPython Thanks! We'll retrieve the "return null" as soon as it's dark. Be wary of cars following you for the next month.

Why the downvote? We placed fourth in the last competition. Although we're not exactly sure how...

NotQuiteABanksBestFriend, Python 3
Command.txt:
python3 NotQuiteABanksBestFriend.py

NotQuiteABanksBestFriend.py
import random
from functools import total_ordering
from io import StringIO

log = StringIO()
log.write("\n\n~~~NEW GAME~~~\n\n")

LIST_DELIMITER = ';'
STOCK_DELIMITER = ':'
OFFER_DELIMITER = '@'

JAVA_MAX_INT = 2147483647

@total_ordering
class Stock:
    @staticmethod
    def parse(string: str):
        return Stock(*map(int, string.split(STOCK_DELIMITER)))

    def __init__(self, stock_type: int, amount: int):
        self.type = stock_type
        self.amount = max(amount, 0)

    def __str__(self):
        return "T%sx%s"%(self.type, self.amount)

    def __repr__(self):
        return str(self.type)+STOCK_DELIMITER+str(int(self.amount))

    def __bool__(self):
        return bool(self.amount)

    def __eq__(self, other):
        return self.amount == other.amount

    def __lt__(self, other):
        return self.amount < other.amount

    def update(self, amount) -> 'Stock':
        return Stock(self.type, amount)

    def __mul__(self, other: int) -> 'Stock':
        return self.update(self.amount*other)

    def __floordiv__(self, other: int) -> 'Stock':
        return self.update(self.amount//other)

    def __add__(self, other: int) -> 'Stock':
        return self.update(self.amount+other)

    def __sub__(self, other: int) -> 'Stock':
        return self.update(self.amount-other)

class Offer:
    @staticmethod
    def parse(string: str) -> 'Offer':
        try:
            stock, price = string.split(OFFER_DELIMITER)
        except ValueError:
            raise Exception("Cannot unpack "+string)
        return Offer(Stock.parse(stock), int(price.strip()))

    def __init__(self, stock: Stock, price: int):
        self.stock = stock
        self.price = price
        try:
            self.price_per_unit = self.price/self.stock.amount
        except ZeroDivisionError:
            self.price_per_unit = float('inf')

    def __str__(self):
        return "%s$%s"%(self.stock, self.price)

    def __repr__(self):
        return repr(self.stock)+OFFER_DELIMITER+str(int(self.price))

def read_stock_value(value: str):
    global hidden_price, hidden_stock
    stock, price = value.split(STOCK_DELIMITER)
    hidden_price = float(price)
    hidden_stock = int(stock)
    log.write("Hidden StockID: %s\nHidden Price: %s\n"%(hidden_stock, hidden_price))

def process_input():
    handlers = {
        "SecretValue": read_stock_value,
        "RandomSeed": read_seed,
        "MakeOffer": make_offer,
        "AcceptOffer": accept_offer,
        "AcceptedOffers": accepted_offers,
    }
    method = input().strip()
    data = input().strip()
    output = handlers[method](data)
    if output is not None:
        print(repr(output))
    else:
        print()

def read_seed(seed: str):
    random.seed(int(seed))

def start():
    while True:
        process_input()

hidden_stock = None
hidden_price = None

def filter_offers(offer):
    if offer.stock.amount == 0:
        return False
    if offer.price_per_unit > 1000:
        return False
    return True

def certain_profit(offer):
    stock = offer.stock
    if stock.type == hidden_stock and offer.price_per_unit < hidden_price:
        log.write("Offer, %s is certainly profitable.\n"%offer)
        return True
    return False

def make_offer(current_stock: str):
    current_stock = list(map(Stock.parse, current_stock.split(LIST_DELIMITER)))
    own_stock = [stock for stock in current_stock if stock.type == hidden_stock]
    if own_stock and own_stock[0]:
        own_stock = own_stock[0]
        amount_sold = min(random.randrange(1,50), own_stock.amount)
        price = hidden_price+random.randrange(10,50)
        return Offer(Stock(hidden_stock, amount_sold), price*amount_sold)
    sell_stock = random.choice(current_stock)
    amount_sold = min(random.randrange(1,50), sell_stock.amount)
    price = random.randrange(1000, JAVA_MAX_INT//(amount_sold or 1))
    return Offer(Stock(sell_stock.type, amount_sold), price*(amount_sold or 1))

def accept_offer(available_offers: str):
    available_offers = list(map(Offer.parse, available_offers.split(LIST_DELIMITER)))
    filtered_offers = list(filter(filter_offers, available_offers))
    profitable = list(filter(certain_profit, filtered_offers))
    rtn_list = filtered_offers
    if profitable:
        log.write("Profitable: %s\n"%profitable)
        rtn_list = profitable
    if not rtn_list:
        return None
    accepted_offer = min(rtn_list, key=lambda offer: offer.price_per_unit)
    log.write("Bidded for %s\n"%accepted_offer)
    return accepted_offer

def accepted_offers(offers: str):
    pass

if __name__ == "__main__":
    try:
        start()
    finally:
        log.close()

Always tries to sell hidden stock for more than it's worth.


text:
Randomly Misspell a Word
Inspired by this CR question (please don't kill me for browsing CR)
Spec
The probabilities of misspelling a word are:

1/3 of the time don't change the output
1/3 of the time remove a random character
1/3 of the time duplicate a random character

The chance for removing/duplicating a given character in the input should be the same for all chars.
If two consecutive characters are the same (case-sensitive), the probability of one of them being modified should be the same as if they are one character. I.e. the outputs for AA (which are AA or A or AAA) should all have the same probability.

The input will only contain of letters for simplicity.
Examples
First line is input, following lines are all possible misspellings. Each line should have the same probability of being output, the input is excluded in the examples but it should still have a 1/3 probability of output.
foo

fo
oo
ffoo
fooo

PPCG

PPC
PPG
PCG
PPPCG
PPCCG
PPCGG

It's a nice challenge, but if each line has the same probability of being output, doesn't that mean that it isn't a 1/3 chance that the word stays the same?

@ValueInk okay that is a flaw with the examples. let me fix

Wait, if each line would have the same probability of being output, then wouldn't the distribution of characters not be uniform? Like, with foo: if you remove a character it could become (-f)oo, f(-o)o, and fo(-o). So fo should be twice as likely as oo, but you say every line has equal probability.

@Deusovi there is a whole paragraph explaing this, I'll copy that here just in case If two consecutive characters are the same (case-sensitive), the probability of one of them being modified should be the same as if they are one character. I.e. the outputs for AA (which are AA or A or AAA) should all have the same probability.

@Downgoat Do you run this program on messages you post in chat before hitting enter? roasted...

@DJMcMayhem no, more than one characters are usually misspelt ;_;

Pip, 38 27 bytes
a@:`(.)\1*`YRR#aa@y@0X:RR3a

This was fun--got to use Pip's regex and mutable string capabilities, which I hadn't pulled out in a while. Takes input via command-line argument.
Explanation:
a@:`(.)\1*`                  Split a into runs of identical chars using regex match
           YRR#a             Yank randrange(len(a)) into y (randomly choosing one such run)
                a@y@0        Take the first character of that run
                     X:RR3   Modify in place, string-multiplying by randrange(3):
                               If RR3 is 0, character is deleted
                               If RR3 is 1, no change
                               If RR3 is 2, character is duplicated
                          a  Output the modified a

Try it online!

Wow, congrats on having a terse golfing lang only with ASCII

Ruby, 64 55 + 1 (p flag) = 56 bytes
Input is a line of STDIN piped in without trailing newline.
a=[]
gsub(/(.)\1*/){a<<$&}
a.sample[-1]*=rand 3
$_=a*''

CJam (21 bytes)
re`_,mr_2$=3mr(a.+te~

Online demo
Dissection
r     e# Read a line of input from stdin
e`    e# Run-length encode it
_,mr  e# Select a random index in the RLE array
_     e# Hang on to a copy of that index
2$=   e# Copy the [run-length char] pair from that index
3mr(  e# Select a uniformly random integer from {-1, 0, 1}
a.+   e# Add it to the run-length
t     e# Replace the pair at that index
e~    e# Run-length decode

JavaScript (ES6), 107
w=>(r=x=>Math.random()*x|0,a=w.match(/(.)\1*/g),a[p=r(a.length)]=[b=a[p],b+b[0],b.slice(1)][r(3)],a.join``)

Less golfed
w=>(
  a = w.match(/(.)\1*/g),
  r = x => Math.random()*x | 0,
  p = r(a.length),
  b = a[p],
  a[p] = [b, b+b[0], b.slice(1)][r(3)],
  a.join``
)

Test

f=w=>(r=x=>Math.random()*x|0,a=w.match(/(.)\1*/g),a[p=r(a.length)]=[b=a[p],b+b[0],b.slice(1)][r(3)],a.join``)

function update() {
  O.innerHTML = Array(99)
  .fill(I.value)
  .map(x=>(
    r=f(x),
    r==x?r:r.length<x.length?''+r+'':''+r+''

    )
  ).join` `
}

update()
#O { width:90%; overflow: auto; white-space: pre-wrap}
<input id=I oninput='update()' value='trolley'>

Java 7, 189 180 178 bytes
import java.util.*;String c(String i){Random r=new Random();int x=r.nextInt(2),j=r.nextInt(i.length());return x<1?i:i.substring(0,j-(x%2^1))+(x<2?i.charAt(j):"")+i.substring(j);}

Ungolfed & test cases:
Try it here.
import java.util.*;
class M{
  static String c(String i){
    Random r = new Random();
    int x = r.nextInt(2),
        j = r.nextInt(i.length());
    return x < 1
            ? i
            : i.substring(0, j - (x%2 ^ 1)) + (x<2?i.charAt(j):"") + i.substring(j);
  }

  public static void main(String[] a){
    for(int i = 0; i < 5; i++){
      System.out.println(c("foo"));
    }
    System.out.println();
    for(int i = 0; i < 5; i++){
      System.out.println(c("PPCG"));
    }
  }
}

Possible output:
foo
fooo
foo
foo
ffoo

PPCCG
PPCG
PPCCG
PPPCG
PPCG

Pyth - 17 bytes
This one actually handles the special cases with consecutive char correctly.
 XZOKrz8Or_1 2r9K

Test Suite.

This is 16 bytes? Is the leading space correct? If not this is 15 bytes?

@Downgoat no, the leading space is correct. I'm pretty sure that its 17 bytes.

Python 2, 134 bytes
from random import*
def f(s):
 p=c=0;M,L=[],list(s)
 for t in L:
  if t!=p:M+=c,;p=t
  c+=1
 L[choice(M)]*=randint(0,2);return''.join(L)

White spaces in for loop are tabs.
Try it on Ideone

JavaScript (ES6), 103
w=>{w=w.split(''),r=Math.random,x=r(),i=r()*w.length|0;w.splice(i,x<.6,x>.3?w[i]:'');alert(w.join(''))}

APL, 21
{⍵/⍨3|1+(?3)×(⍳=?)⍴⍵}

This starts by creating a vector of zeros with a 1 in random position. Then multiplies it by a random number between 1 and 3. +1 and mod 3 obtains a vector with all 1s and one random positioned 0,1 or 2.
Finally, ⍵/⍨ says that each letter should be written n times, where n are the numbers in the vector.
Try it on tryapl.org

Python 2, 123 bytes
from random import*
R=randint
s=input()
m=n=R(0,len(s)-1)
c=R(0,2)
m=[m,1+[-len(s),m][m>0]][c==1]
n+=c==2
print s[:m]+s[n:]

APL, 27 bytes
{⍵/⍨(?3)⌷1⍪2 0∘.|1+(⍳=?)⍴⍵}

Explanation:
                        ⍴⍵  ⍝ length of ⍵
                   (⍳=?)    ⍝ bit vector with one random bit on
                 1+         ⍝ add one to each value (duplicate one character)
           2 0∘.|           ⍝ mod by 2 and 0 (remove instead of duplicate)
         1⍪                 ⍝ add a line of just ones (do nothing)
    (?3)⌷                   ⍝ select a random line from that matrix
 ⍵/⍨                        ⍝ replicate characters in ⍵

Test:
      {⍵/⍨(?3)⌷1⍪2 0∘.|1+(⍳=?)⍴⍵} ¨ 10/⊂'foo'
 fooo  foo  oo  foo  fo  fo  oo  fo  oo  fooo

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Write a program that outputs the number of times it has been run
In a programming language of your choice, write a full program that, when run, prints a positive integer N and then modifies its own source file such that the next time it is run it will print N+1.
For example, this (ungolfed) Python 3 program satisfies this behavior:
N = 1
print(N)
with open(__file__, 'r+') as f:
    N = int(f.readline()[4:]) + 1
    code = 'N = ' + str(N) + '\n' + f.read()
    f.seek(0)
    f.write(code)

Right away it declares and prints N, then it opens itself and rewrites its first line so the declared value of N is incremented. Then it copies the rest of its code verbatim and writes the new code to the same file, resulting in a program that will print N+1 when run again.
If the file were named incr.py, running it on the command line would look something like this:
C:\somepath> python incr.py
1
C:\somepath> python incr.py
2
C:\somepath> python incr.py
3
C:\somepath> python incr.py
4

At this point, incr.py would read:
N = 5
print(N)
with open(__file__, 'r+') as f:
    N = int(f.readline()[4:]) + 1
    code = 'N = ' + str(N) + '\n' + f.read()
    f.seek(0)
    f.write(code)

Your program should behave essentially the same as this Python example, though of course your program structure may be very different, even changing as N increases. (You don't need to define N as a plain integer on the first line, for example.)
Give the program that prints 1 in your answer. Programs for all higher N can then be inferred. The shortest 1-printing program in bytes wins.
Notes

The output should be the sole number N in decimal (or your language's most natural base), followed optionally by a trailing newline.

Your program must actually rewrite its own source code file, not simply output its modified source like a quine.

The file name and/or path of the source file may be hardcoded into your program (e.g. 'incr.py' could have replaced __file__ in the Python example) but the program's behavior should not depend on them. If the file is moved or renamed it should be easy enough to rewrite the program accordingly.

The source file's name and path should not change during execution.

Temporary files may be made (to copy code to or whatever) but they should be removed before the main program ends. Specifically, the only side effects of running your program should be:

Printing N to stdout.

Changing the source file so it will print N+1 when next run.

Related (but that one was a pop con so not a duplicate)

In Excel it's just 5 bytes by setting maximum iterations in Enable Iterative Calculation to 1 and then just enter = A1 + 1 in cell A1.

@matsjoyce No. Did you try the example? It does work beyond 9.

@Anastasiya-Romanova秀, the spec specifically requires you to modify the source file. There are probably relatively few languages which can do this running under Windows, because of its tendency to lock files.

Helka, the spec also says "modifies its own source file such that the next time it is run" (my emphasis). If your intention is that only interpreted languages may be used, you should state that explicitly. If you intend to allow compiled languages as well, the wording is a bit unclear.

@HelkaHomba Sorry, missed the f.read(). Too early it seems...

@PeterTaylor That's why I didn't post my answer :D

Can the program receive as input it's own filename? (another way of hardcoding it). I ask because I want to solve it in sed and it absolutely requires an input to start. I will count the name in the total bytes ofcourse.

I don't see how this is not a duplicate of the challenge that @manatwork linked.

@TimmyD It sadly definitely is. In my defense there were two conversations about this possibly being a dupe in chat and that challenge wasn't mentioned.

bash (+ wc + id), 16 bytes
wc -l<$0;id>>$0

Counts its lines, then appends a line of garbage to itself.
Needs a trailing newline.
Crashes on line 2 with a syntax error, which thankfully prints to STDERR and exits.
After three invocations, the script looks like this for me:
wc -l<$0;id>>$0
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)
uid=1000(lynn) gid=1000(lynn) groups=1000(lynn),4(adm),24(cdrom),27(sudo),30(dip),46(plugdev),113(lpadmin),128(sambashare)

Now that's style!

Gave +1. I also want to mention that since there are no quotes around $0, the source filename must not contain spaces and other specific characters.

Python 2, 31 bytes
open(*'aa').write('+1');print 1

Simply appends +1 to the source file upon execution. This program assumes that the source file is named as a. It can be easily modified to work with an arbitrary filename at 38 bytes as follows:
open(__file__,'a').write('+1');print 1

Additionally, a 37 bytes alternative exists though it isn't valid due to the 'no temporary files' rule:
f=open(*'aa')
print>>f
print f.tell()

This program appends a newline to the file a which is assumed not to exist before the first execution of the program. Then, the program prints the file size of a which is simply f.tell() since the file object is now pointing to the end of the file after appending.

if you know file is stored in 'a', why use __file__ at all?

@Maltysen I'm not assuming the filename of the source file. 'a' opens the file for appending.

Though you are allowed to name the file a.py or just a for a few byte savings.

@HelkaHomba Ah, I see. I assumed it wasn't allowed. Unfortunately, this means my 37 bytes program is now completely outclassed.

Perl (+shell), 30 bytes
self.pl:
#!/usr/bin/perl
print 1;`$^X -pi -es/1/1+1/ $0`

Works as shown, but replace ^X by the literal control byte for the claimed score. This does lead to a warning on recent perl versions though.
Because the filename is passed through the shell it should not contain any special characters.
A pure perl version weights in at 32 bytes (or 33 if you add a -X option to suppress the -i warning)
#!/usr/bin/perl -pi
INIT{print 1;@ARGV=$0}s/1/1+1/

If you don't mind calling with perl -M5.010 in both version 2 more bytes can be removed by using say instead of print

Pyth - 7 bytes
Very simple, save as o.txt.
.wk)l"1

(btw to change filename, replace the paren for the .w with a string, like: .wk"file.pyth"l"1

...what is it doing?

@FrancescoDondi "1 is the string literal "1", and l gives length, so this implicitly prints the length of the string, giving 1 on the first execution. .w writes its argument to o.txt with a single trailing newline; since k is the empty string, this increases the length of the string by 1 each time, incrementing the output.

QBasic (QB64), 47 bytes
OPEN"C:\p.bas"FOR APPEND AS 1:?LOF(1)\2-22:?#1,

Adjust the path and filename as desired. Note: you must create the file C:\p.bas with an external text-editor (I used Notepad++) and make sure it does not contain a trailing newline. The QB64 editor adds one when you save the file, which throws off the math and the bytecount. (I assume actual QBasic would do the same, not to mention the auto-formatting.)
Here's an ungolfed version (which does expect a trailing newline):
OPEN "C:\p.bas" FOR APPEND AS 1
PRINT LOF(1) \ 2 - 32
PRINT #1,

How it works
The program opens its own code file in APPEND mode. It then uses LOF to get the length of the current version in bytes. To begin with, this is 47, so we calculate LOF(1)\2-22 (where \ is integer division) and print the resulting 1.
Finally, we want to write some no-op to the end of the file. The shortest way to do this turns out to be writing nothing, with a trailing newline automatically added. Since this is Windows (or DOS), the newline is \r\n, adding two bytes and necessitating the division by 2 earlier in the code.
(Always CLOSE your files when you're done with them, kids. Unless you're golfing.)

V, 15 bytes
:e z
jñ:wñck0

Or, this readable version:
:e <C-r>z
j<C-a>ñ:wñck0

This will not work on the online interpreter, since it disallows file access.
Here is a hexdump:
00000000: 3a65 2012 7a0a 6a01 f13a 77f1 636b 30    :e .z.j..:w.ck

Explanation:
:e                   "Edit the following file:
   <C-r>z            "Insert the full path to the source file
j                    "Move down a line
 <C-a>               "And increment the first number on this line
      ñ:wñ           "Save this file. Surrounding it with 'ñ' is a fun little hack that allows this to appear on the same line
          ck         "Change this line and the line above us
            0        "To '0' (or whatever number we're on)

Does :e % work in V? (Not that it would change the byte count; I'm just curious.)

@Jordan Good question! That will not work because % is the current file being edited, which in V is the file used to give input. @z is the path to the source file.

PowerShell, 69/60 57
Further golfed and regex corrected based on feedback from TimmyD and Matt
($a=1);$a++;(gc($b=$PSCommandPath))-replace"\d+",$a|sc $b

69 for completely path and filename agnostic
($a=1)|oh;$a++;$b=$PSCommandPath;((gc $b)-replace"\d",$a)|Out-File $b

60 bytes if I can specify a fixed filename
($a=1)|oh;$a++;(gc .\a.ps1)-replace"\d",$a)|Out-File .\a.ps1

Explanation:
Sets $a to 1, returns it. Then it increments the variable, finds its own invocation path, brings that into memory and uses regex to replace digits with the value in $a, then writes to disk.

Would this not fail is a became double digits? Also why not use sc instead of out-file

The second example would fail on the second pass since there is a digit in the file name.

Welcome to PPCG! Matt has it right -- the digit-replace needs to be thought out a little better. Also, a few additional golfs such as eliminating the |oh (things left on the pipeline are implicitly printed), moving the $b assignment into the gc, and using sc instead of out-file gets you down to 57 -- ($a=1);$a++;(gc($b=$PSCommandPath))-replace'\d+',$a|sc $b

Ah, thanks.
I definitely forgot the plus in the regex, that was silly.
I left the define of $a in the pipeline and it didn't print when I was writing it, probably because I hadn't yet put the parens around it, same for why i did the define of $b that way, I knew I could get it to return the value as well as defining but I couldn't remember how.
Completely goofed on forgetting SC

Javascript (Node.js), 92 bytes
s=require('fs')
f=s.readFileSync(l=__filename)
console.log(f.length-91)
s.writeFile(l,f+';')

Prints out the length of the file minus 91, and adds a semicolon (which is ignored by the interpreter) to the final line of the file each time it is run

You can save 2 bytes by moving the first line into the readFileSync call (and changing 93 to 91 of course).

C#, 124 bytes
namespace System.IO{class C{static void Main(){Console.Write(File.ReadAllLines("p").Length);File.AppendAllText("p","\n");}}}

Usage: Source file needs to be called p. If using Visual Studio, make sure the Build Action is set to Compile (not default for non-cs files). Also, under project properties ensure the the Output Path is the current directory (ie- empty text box) (again not a default setting).
How it works: It opens the source file and outputs the line count. Then it appends an empty line to the source file.
Pretty print version:
namespace System.IO // Put in System.IO namespace so no usings needed.
{
    class C
    {
        static void Main()
        {
            Console.Write(File.ReadAllLines("p").Length); // Write line count/run count
            File.AppendAllText("p","\n"); // Increment line count/run count
        }
    }
}

PHP, 38 bytes
There are so many ways in PHP to do that ... this one´s the shortest I could find:
<?=stat(n)[7]-37;fputs(fopen(n,a),1);#

print file size (initially 38) -37, append a character (1 in this case) to the comment at the end.

save with file name n, call with php n
make sure that the file contains no trailing newline
fclose is called implicitly when the script finishes.
if you pick another filename, replace 37 with the new file size -1.
if filename gets longer than 5 characters (including eventual quotation marks), use $n=filename for the first occurence, $n for the second.
if filename gets longer than 7 characters, use __FILE__ instead of the literal file name.

Dyalog APL, 21 bytes
Define f as the following:
(⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f'

⎕NR'f' the Nested Representation of f; on the first run, this is {f, (⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f'}
'⍝',⍨ append a comment symbol, giving {f, (⎕FX⊢2-⍨⍴)'⍝',⍨⎕NR'f', ⍝}
(...) apply the following function:
 ⎕FX Fix definition of f
 ⊢ then
 2-⍨ subtract two from
 ⍴ the length of the argument (3 on the first run)
Example run:
      f
1
      f
2
      f
3

Batch, 70 55 bytes
@cmd/cset/a-1>>%0
@call:l
@echo %n:~1%
:l
@set/an=0

Ensure that the file does not end in a newline. Use the full file name to invoke the file (e.g. incr.bat). Works by appending -1 (cmd/cset/a does not output a trailing newline) to the end of the file on each run (including the first!) so that n is the negation of the desired result, then just strips off the leading minus sign when printing n.
Edit: Saved 8 bytes by removing an exit/b which had no visible effect. Saved 7 bytes by switching from @echo off to @ prefixes on each line.

R, 45 bytes
f=function(){body(f)[[3]]<<-body(f)[[3]]+1;1}

Not sure if a function counts as a "full program" but calling f() will return 1,2,... within the same R session. It also satisfies the self-modifying criterion.
It is necessary to use the double-harpoon operator <<- or else f will just make a local copy of itself and modify that instead. <<- forces that to happen at the top level.

JavaScript (browser) (ES6), 84 bytes
s=document.querySelector('script');f=_=>eval(s.innerHTML);n=0;s.innerHTML+='n++;n;';

Run by calling f(). Note that this is reset on page load.
I assume that modifying the <script> tag counts as rewriting the source code.

PowerShell 55 53 31 Bytes
"$(gc($p='.\1.ps1'))+1"|sc $p;1

Read in the file then just add +1 to the end of the file. Powershell will evaluate that as addition so for the fifth pass the file would have ....;1+1+1+1+1 which evaluates to five!
Old version using saved integer in a variable.
($a=1);$a++;(gc .\1.ps1)-replace'=\d+',"=$a"|sc .\1.ps1

Since we can hardcode a name it saves spaces over the script determining its own name. Printer the current value of $a. Increase $a by one. Using regex, replace the digits that follow an equal sign with the now updated value. Then write back to the original file.
If I change the way I locate the first number I can get down to 53. Using a newline I change my regex to look for numbers at the end of a line. This is why I have to a semicolon to the last line to get that omitted.
$a=1
($a++);(gc .\1.ps1)-replace'\d+$',$a|sc .\1.ps1;

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Given a list of circles, output the area of the smallest containing rectangle
You will be given a list of radii, you must output the area of the smallest rectangle which they will all fit in.
For example, given the list [5,3,1.5] you would output 157.460.
This is the image:

The width is 15.7460 and the height is 10, so the area is 157.460
Rules:

You get the list via stdin or function argument, output the answer via stdout or function return.
The radii will have at most 2 decimal places.
The list will have a length between 2 and 6.
The output should be accurate to 3 decimal places or more.
If you need, π = 3.1416.

Test cases:

[5,3,1.5] = 157.460
[9,4,8,2] = 733.431 - working here.
[18,3,1] = 1296.000

Shortest code in bytes wins.

Related

i don't see an objective winning criterion

that's one of our most central rules

@Tim Most are code golf, with the goal of coding it in the fewest bytes. I think this would make a good code golf challenge, as it has an exact spec.

I recommend getting rid of the "rounded not truncated" condition because it's peripheral to the task, and some languages can just do it while others need extra coding to make it happen. I'm not sure if you intend it to be OK to output more than 3 decimal places, but I'd suggest allowing that too.

@xnor I've gone for code golf, although I'm a little worried it's too tricky to get exact answers. And yes, updated the 3dp thing. Do you think "Into your program, try the three test cases. Your score is the absolute difference between the sum of the three test cases your code outputs, and the correct sum - 2186.891. This means you are aiming for a score of 0." would be suitable / better?

@Tim It's on the harder side for a golf challenge, but I think that's fine. I expect many answers to try to brute force all packings to get the optimum and be really inefficient in run-time. Some larger test cases would be nice if you can generate them, in particular the upper limit of 6.

@xnor I would love to, but I'm making these by hand. I'll attempt a 6 one, but each circle added makes my wolfram alpha time increase dramatically.

@xnor More test cases! :-)

Python 2 + PySCIPOpt, 267 bytes
from pyscipopt import*
R=input()
m=Model()
V,C=m.addVar,m.addCons
a,b,c=V(),V(),V()
m.setObjective(c)
C(a*b<=c)
P=[]
for r in R:
 x,y=V(),V();C(r<=x);C(x<=a-r);C(r<=y);C(y<=b-r)
 for u,v,s in P:C((x-u)**2+(y-v)**2>=(r+s)**2)
 P+=(x,y,r),
m.optimize()
m.printBestSol()

How it works
We write the problem as follows: minimize c over variables a, b, c, x1, y1, …, xn, yn, where

ab ≤ c;
ri ≤ xi ≤ a − ri and ri ≤ yi ≤ b − yi, for 1 ≤ i ≤ n;
(xi − xj)2 + (yi − yj)2 ≥ (ri + rj)2, for 1 ≤ j < i ≤ n.

Obviously, we’re using an external optimization library on these constraints, but you can’t just feed them to any old optimizer—even Mathematica’s NMinimize gets stuck at local minima for these tiny test cases.  If you stare closely at the constraints, you’ll see that they constitute a quadratically-constrained quadratic program, and finding the global optimum for a non-convex QCQP is NP-hard.  So we need some incredibly high-powered magic.  I chose the industrial-strength solver SCIP, which is the only global QCQP solver I could find with so much as a free license for academic use.  Happily, it has some very nice Python bindings.
Input and output
Pass the radius list on stdin, like [5,3,1.5].  The output shows objective value: rectangle area, x1, x2 rectangle dimensions, x3 rectangle area again, x4, x5 first circle center coordinates, x6, x7 second circle center coordinates, etc.
Test cases
[5,3,1.5] ↦ 157.459666673757

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 0.04
Solving Nodes      : 187
Primal Bound       : +1.57459666673757e+02 (9 solutions)
Dual Bound         : +1.57459666673757e+02
Gap                : 0.00 %
objective value:                     157.459666673757
x1                                                 10   (obj:0)
x2                                   15.7459666673757   (obj:0)
x3                                   157.459666673757   (obj:1)
x4                                                  5   (obj:0)
x5                                                  5   (obj:0)
x6                                                  7   (obj:0)
x7                                   12.7459666673757   (obj:0)
x8                                                1.5   (obj:0)
x9                                   10.4972522849871   (obj:0)

[9,4,8,2] ↦ 709.061485909243
This is better than the OP’s solution.  The exact dimensions are 18 by 29 + 6√3.

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 1.07
Solving Nodes      : 4650
Primal Bound       : +7.09061485909243e+02 (6 solutions)
Dual Bound         : +7.09061485909243e+02
Gap                : 0.00 %
objective value:                     709.061485909243
x1                                                 18   (obj:0)
x2                                   39.3923047727357   (obj:0)
x3                                   709.061485909243   (obj:1)
x4                                                  9   (obj:0)
x5                                   30.3923047727357   (obj:0)
x6                                                 14   (obj:0)
x7                                   18.3923048064677   (obj:0)
x8                                                  8   (obj:0)
x9                                                  8   (obj:0)
x10                                                 2   (obj:0)
x11                                  19.6154311552252   (obj:0)

[18,3,1] ↦ 1295.999999999

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 0.00
Solving Nodes      : 13
Primal Bound       : +1.29599999999900e+03 (4 solutions)
Dual Bound         : +1.29599999999900e+03
Gap                : 0.00 %
objective value:                       1295.999999999
x1                                   35.9999999999722   (obj:0)
x2                                                 36   (obj:0)
x3                                     1295.999999999   (obj:1)
x4                                   17.9999999999722   (obj:0)
x5                                                 18   (obj:0)
x6                                   32.8552571627738   (obj:0)
x7                                                  3   (obj:0)
x8                                                  1   (obj:0)
x9                                                  1   (obj:0)

Bonus cases
[1,2,3,4,5] ↦ 230.244214912998

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 401.31
Solving Nodes      : 1400341
Primal Bound       : +2.30244214912998e+02 (16 solutions)
Dual Bound         : +2.30244214912998e+02
Gap                : 0.00 %
objective value:                     230.244214912998
x1                                   13.9282031800476   (obj:0)
x2                                    16.530790960676   (obj:0)
x3                                   230.244214912998   (obj:1)
x4                                                  1   (obj:0)
x5                                   9.60188492354373   (obj:0)
x6                                    11.757778088743   (obj:0)
x7                                   3.17450418828415   (obj:0)
x8                                                  3   (obj:0)
x9                                    13.530790960676   (obj:0)
x10                                  9.92820318004764   (obj:0)
x11                                   12.530790960676   (obj:0)
x12                                                 5   (obj:0)
x13                                                 5   (obj:0)

[3,4,5,6,7] ↦ 553.918025310597

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 90.28
Solving Nodes      : 248281
Primal Bound       : +5.53918025310597e+02 (18 solutions)
Dual Bound         : +5.53918025310597e+02
Gap                : 0.00 %
objective value:                     553.918025310597
x1                                   21.9544511351279   (obj:0)
x2                                   25.2303290086403   (obj:0)
x3                                   553.918025310597   (obj:1)
x4                                                  3   (obj:0)
x5                                   14.4852813557912   (obj:0)
x6                                   4.87198593295855   (obj:0)
x7                                   21.2303290086403   (obj:0)
x8                                   16.9544511351279   (obj:0)
x9                                                  5   (obj:0)
x10                                                 6   (obj:0)
x11                                                 6   (obj:0)
x12                                  14.9544511351279   (obj:0)
x13                                  16.8321595389753   (obj:0)

[3,4,5,6,7,8] ↦ 777.87455544487

SCIP Status        : problem is solved [optimal solution found]
Solving Time (sec) : 218.29
Solving Nodes      : 551316
Primal Bound       : +7.77874555444870e+02 (29 solutions)
Dual Bound         : +7.77874555444870e+02
Gap                : 0.00 %
objective value:                      777.87455544487
x1                                   29.9626413867546   (obj:0)
x2                                   25.9614813640722   (obj:0)
x3                                    777.87455544487   (obj:1)
x4                                   13.7325948669477   (obj:0)
x5                                   15.3563780595534   (obj:0)
x6                                   16.0504838821134   (obj:0)
x7                                   21.9614813640722   (obj:0)
x8                                   24.9626413867546   (obj:0)
x9                                   20.7071098175984   (obj:0)
x10                                                 6   (obj:0)
x11                                  19.9614813640722   (obj:0)
x12                                                 7   (obj:0)
x13                                                 7   (obj:0)
x14                                  21.9626413867546   (obj:0)
x15                                  8.05799919177801   (obj:0)

Shame the last one gives a slight rounding error, but nice work!

It looks to me like [1,2,3,4,5] could be improved by making the radius 3 and radius 5 circles touch also, then rotating the radius 4 / radius 5 diagonal clockwise slightly (the radius 1 circle would have to be moved out of the way but there is plenty of dead space for that. Both my instinct and my calculations indicate that a long, thin rectangle can contain the radius 4/ radius 5 circles more efficiently than a squarer one.

@LevelRiverSt I don’t agree. Moving 3 up to touch 5 would push 4 away to the right (counterclockwise from 5), not let it move left (clockwise from 5). My program’s configuration is (7 + 4√3) × (9 + √(29 + 16√3)) ≈ 13.9282 × 16.5308 ≈ 230.244, while your suggested configuration is (30 + 15√3)/4 × (36 + 3√5 + 6√15)/4 ≈ 13.9952 × 16.4865 ≈ 230.732.