title: Let's have a tank war!

text:
# Question
Title: Let's have a tank war!
# Let's have a tank war!

Partially inspired by Destroy Them With Lazers

## Objective

Your task is to control a tank. Move around and shoot other tanks and obstacles in the 2D battlefield. The last tank standing will be the winner!

## Map format

Your tank will be on a 2D field based on an `n` by `n` grid of unit squares. I will decide what `n` is based on the number of submissions. Each square can contain only one of:

* A tank
* A tree
* A rock
* A wall
* Nothing

All obstacles and tanks completely fill their spaces, and they block all shots that hit them from damaging things further down.

Here is an example of a field with `#`=tank; `T`=tree; `R`=rock; `W`=wall; `.`=nothing with `n`=10

```
.....#....
..T....R..
WWW...WWWW
W......T..
T...R...Ww
W...W.....
W....W...T
WWWWWW...R
W.........
WWWWWWRT..

```

Coordinates are in the format `x, y` where `x` increases left to right and `y` increases bottom to top. The bottom left space has the coordinate `0, 0`. Each tank may move to any empty space and shoot in any direction.

## Map Dynamics

Your tank doesn't just have to shoot other tanks! If it shoots something on the map, things can happen.

* If a wall is shot at, it will be destroyed after some number of shots, ranging from 1 to 4
* If a tree is shot at, it will be destroyed immediately
* If a rock is shot at, the shot will pass over it and damage the next thing it hits

Once something is destroyed, it is no longer on the map (it will be replaced with nothing). If a shot destroys an obstacle, it will be blocked and will not damage anything further along its path.

## Tank dynamics

Each tank starts with `life`=100. Each shot at a tank will reduce 20-30 `life` based on distance. This can be calculated with `delta_life=-30+(shot_distance*10/diagonal_map_length)` (where `diagonal_map_length` is `(n-1)*sqrt(2)`). Additionally, each tank regenerates 1 `life` per turn.

## Turns

Some number of rounds will be run (I will decide once I have submissions). At the beginning of every round, a map will be generated randomly, and tanks will be placed on it in random empty locations. During every round, each tank will be given a turn, in any arbitrary order. After every tank has been given a turn, they will be given turns again in the same order. The round continues until there is only one tank left. That tank will be the winner, and they will receive 1 point. The game will then go on to the next round.

Once all the rounds have been run, I will post the scores on this question.

During a tank's turn, it may do one of the following

* Move up to 3 spaces in a single direction, either horizontally or vertically. If the tank is blocked by an obstacle or another tank, it will be moved as far as possible without going through the obstacle or tank.
* Shoot in some direction, represented by a floating point angle in degrees. The x-axis of your tank's local space (horizontally left to right, aka east or `TurnAction.Direction.EAST`) is 0deg, and angles increase counterclockwise. Shots are inaccurate, and the actual angle of the shot may be 5 degrees greater or less than the angle you choose.
* Do nothing.

Turns are not limited in time, but this doesn't mean you can intentionally waste time to hang everything up.

## Submissions/Protocol

Each program submitted will control one tank on the field. The control program is in Java, so your programs need to be in Java for now (I will probably write a wrapper for other languages at some point, or you could write your own).

Your programs will implement the `Tank` interface, which has the following methods:

```
public interface Tank {
    // Called when the tank is placed on the battlefield.
    public void onSpawn(Battlefield field, MapPoint position);
    // Called to get an action for the tank on each turn.
    public TurnAction onTurn(Battlefield field, MapPoint position, float health);
    // Called with feedback after a turn is executed.
    // newPosition and hit will be populated if applicable.
    public void turnFeedback(MapPoint newPosition, FieldObjectType hit);
    // Called when the tank is destroyed, either by another tank,
    // or because the tank won. The won parameter indicates this.
    public void onDestroyed(Battlefield field, boolean won);
    // Return a unique name for your tank here.
    public String getName();
}

```

The `Battlefield` class contains a 2D array of objects (`Battlefield.FIELD_SIZE` by `Battlefield.FIELD_SIZE`) which represents things on the battlefield. `Battlefield.getObjectTypeAt(...)` will give a `FieldObjectType` for the object at the specified coordinates (one of `FieldObjectType.ROCK`, `FieldObjectType.TREE`, `FieldObjectType.TANK`, `FieldObjectType.WALL`, or `FieldObjectType.NOTHING`). If you try to get an object out of range of the map (coordinates \<0 or \>=`Battlefield.FIELD_SIZE`) then an `IllegalArgumentException` will be thrown.

`MapPoint` is a class for specifying points on the map. Use `MapPoint.getX()` and `MapPoint.getY()` to access the coordinates.

**EDIT:** Some utility methods have been added: `MapPoint.distanceTo(MapPoint)`, `MapPoint.angleBetween(MapPoint)`, `Battlefield.find(FieldObjectType)`, and `TurnAction.createShootActionRadians(double)` as suggested by Wasmoo.

More info can be found in the javadocs, see section below.

All (public API) classes are under the package `zove.ppcg.tankwar`.

## Control Program

The full source and javadocs of the control program and tank API can be found on my GitHub repo: https://github.com/Hungary-Dude/TankWarControl

Feel free to send pull requests and/or comment if you see a bug or want an improvement.

I have written two sample tank programs, `RandomMoveTank` and `RandomShootTank` (the name says it all).

To run your tank, add your fully qualified (package name + class name) tank class to `tanks.list` (one class per line), edit settings as necessary in `zove.ppcg.tankwar.Control` (turn delay, whether or not to show a GUI representation of the field, etc), and run `zove.ppcg.tankwar.Control`. Make sure there are at least 2 tanks on the list, or results are undefined. (Use the sample tanks if necessary).

Your programs will be run on my machine under this control program. I'll include a link to the source once I write it. Feel free to suggest edits to the source.

## Rules

* Your submissions must follow the guidelines above
* Your programs may not access the filesystem, network, or attempt to attack my machine in any way
* Your programs may not attempt to exploit my control program to cheat
* No trolling (such as intentionally making your program waste time to hang everything up)
* You may have more than one submission
* Try to be creative with submissions!
* I reserve the right to allow or not allow programs arbitrarily

Good luck!

**UPDATE:** After fixing the wall teleportation bug and implementing regeneration, I ran the current submissions for 100 rounds with `Battlefield.FIELD_SIZE = 30`

**UPDATE 2:** I added the new submission, RunTank, after fooling with Groovy for a bit...

Updated results:

```
+-----------------+----+
| RandomMoveTank  | 0  |
| RandomShootTank | 0  |
| Bouncing Tank   | 4  |
| Richard-A Tank  | 9  |
| Shoot Closest   | 19 |
| HunterKiller 2  | 22 |
| RunTank         | 23 |
| Dodge Tank      | 24 |
+-----------------+----+

```

Currently tanks regenerate 1 life per turn. Should that be increased?

# Answer
This straight-forward tank finds the closest enemy tank and shoots at it. Would be nice if `find`, `distance`, and `angle` were built in, and if `createShootAction` accepted a double in radians (i.e. the result of `angle`)

**Edit:** Class rewritten to include new utility methods

```
public final class ShootClosestTank implements Tank {

    @Override
    public TurnAction onTurn(Battlefield field, MapPoint position, float health) {
        //Find all the tanks
        List<MapPoint> tanks = field.find(FieldObjectType.TANK);
        tanks.remove(position);

        if (tanks.isEmpty()) return TurnAction.createNothingAction();

        //Calculate closest tank
        MapPoint cPoint = null;
        double cDist = Double.POSITIVE_INFINITY;
        for (MapPoint p : tanks) {
            double dist = position.distanceTo(p);
            if (dist < cDist) {
                cDist = dist;
                cPoint = p;
            }
        }

        //Shoot at closest tank
        return TurnAction.createShootActionRadians(position.angleBetweenRadians(cPoint));

    }

    @Override
    public void onDestroyed(Battlefield field, boolean won) {
        //Sucks to be me
    }

    @Override
    public void onSpawn(Battlefield field, MapPoint position) {
        //No setup
    }

    @Override
    public void turnFeedback(MapPoint newPosition, FieldObjectType hit) {
        //Nothing to update
    }

    @Override
    public String getName() {
        return "Shoot Closest";
    }
}

```
> 2 votes

# Answer
**HunterKiller**

This intelligent hunter will attempt to find a safe position where it can cleanly shoot at exactly one target. (And thus, only one target can shoot it)

Works best when there is lots of cover.

```
import zove.ppcg.tankwar.*;
import java.util.*;
public final class HunterKiller implements Tank {

    private final int MAX_DEPTH = 2;
    private Battlefield field;
    private List<MapPoint> enemies;
    private MapPoint me;
    private HashMap<MapPoint, MoveNode> nodeMap = new HashMap();

    //A description of how safe the position is from each tank in enemies
    private class Safety extends java.util.ArrayList<Double> {
        public int threats;
        public Safety(MapPoint position) {
            for (MapPoint p : enemies) {
                int obstacles = countObstacles(position, p, false);
                if (obstacles > 0) {
                    add((double) obstacles);
                } else {
                    add(missChance(position.distanceTo(p)));
                    threats++;
                }
            }
        }
    };

    //A description of a move
    private class Move {

        public TurnAction.Direction direction;
        public int distance;
        public MapPoint point;

        public Move(TurnAction.Direction direction, int distance, MapPoint point) {
            this.direction = direction;
            this.distance = distance;
            this.point = point;
        }

        public TurnAction action() {
            return TurnAction.createMoveAction(direction, distance);
        }

        @Override
        public String toString() {
            return direction + " " + distance;
        }
    }

    /**
     * A MoveNode holds a point and all the moves available from that point.
     * The relative safety of the node can be calculated as a function
     * of its depth; ie. this position is safe because we can can move to safety
     */
    private class MoveNode {

        MapPoint point;
        ArrayList<Move> moves;
        ArrayList<Safety> safetyArray = new ArrayList();

        public MoveNode(MapPoint point) {
            this.point = point;
            this.moves = getMoves(point);
        }

        public Safety getSafety(int depth) {
            if (safetyArray.size() <= depth) {
                Safety value;
                if (depth == 0 || this.moves.isEmpty()) {
                    value = new Safety(point);
                } else {
                    ArrayList<Safety> values = new ArrayList();
                    for (Move m : moves) {
                        MoveNode n = nodeMap.get(m.point);
                        if (n == null) {
                            n = new MoveNode(m.point);
                            nodeMap.put(n.point, n);
                        }
                        values.add(n.getSafety(depth - 1));
                    }
                    Collections.sort(values, cmp);
                    value = values.get(0);
                }
                safetyArray.add(depth, value);
            }
            return safetyArray.get(depth);
        }
    }

    /**
     * Find all the points between here and there, excluding those points
     */
    private java.util.ArrayList<MapPoint> path(final MapPoint p1, MapPoint p2) {
        java.util.ArrayList<MapPoint> ret = new ArrayList();
        float tankX = p1.getX();
        float tankY = p1.getY();
        double angle = p1.angleBetweenRadians(p2);
        double maxDistance = p1.distanceTo(p2);
        for (int x = 0; x < Battlefield.FIELD_SIZE; x++) {
            for (int y = 0; y < Battlefield.FIELD_SIZE; y++) {
                float x2 = (float) (((x - tankX) * Math.cos(-angle)) - ((y - tankY) * Math.sin(-angle)));
                float y2 = (float) (((x - tankX) * Math.sin(-angle)) + ((y - tankY) * Math.cos(-angle)));
                if (x2 > 0 && y2 >= -0.5 && y2 <= 0.5) {
                    MapPoint p = new MapPoint(x, y);
                    if (maxDistance > p1.distanceTo(p)) {
                        ret.add(p);
                    }
                }
            }
        }
        Collections.sort(ret, new Comparator<MapPoint>() {
            @Override
            public int compare(MapPoint o1, MapPoint o2) {
                return (int) Math.signum(p1.distanceTo(o2) - p1.distanceTo(o1));
            }
        });
        return ret;
    }

    /**
     * Find the number of obstacles between here and there, excluding those
     * points
     */
    private int countObstacles(MapPoint p1, MapPoint p2, boolean countRocks) {
        java.util.ArrayList<MapPoint> points = path(p1, p2);
        int count = 0;
        for (MapPoint p : points) {
            Object obj = field.getObjectTypeAt(p);
            if (FieldObjectType.NOTHING.equals(obj)
                    || (!countRocks && FieldObjectType.ROCK.equals(obj))
                    || (!countRocks && FieldObjectType.TANK.equals(obj))
                    || p.equals(me)) {
                count += 0;
            } else {
                count += 1;
            }
        }
        return count;
    }

    /**
     * Returns a value between 1.0 and 0.0, where 1.0 is far and 0.0 is close
     */
    private double missChance(double distance) {
        return distance / Battlefield.DIAGONAL_FIELD_SIZE;
    }

    //Returns a list of valid moves from the given position
    private ArrayList<Move> getMoves(MapPoint position) {
        ArrayList<Move> ret = new ArrayList();
        for (TurnAction.Direction d : TurnAction.Direction.values()) {
            for (int i = 1; i <= 3; i++) {
                MapPoint p = d.translate(position, i);
                try {
                    FieldObjectType t = field.getObjectTypeAt(p);
                    if (t != FieldObjectType.NOTHING && !p.equals(me)) {
                        break;
                    }
                    ret.add(new Move(d, i, p));
                } catch (IllegalArgumentException ex) {
                    //Can't move off the map...
                    break;
                }
            }
        }
        return ret;
    }

    //Compares two safeties with a preference for exactly 1 threat
    private Comparator<Safety> cmp = new Comparator<Safety>() {
        @Override
        public int compare(Safety o1, Safety o2) {
            int tc1 = o1.threats;
            int tc2 = o2.threats;
            //Prefer 1 threat
            if (tc2 == 1 && tc1 != 1) {
                return 1;
            }
            if (tc2 != 1 && tc1 == 1) {
                return -1;
            }

            //Prefer fewer threats
            if (tc2 != tc1) {
                return tc1 - tc2;
            }

            //We're splitting hairs here
            //Determine the least safe option
            int ret = -1;
            double s = Double.MAX_VALUE;
            for (Double d : o1) {
                if (d < s) {
                    s = d;
                }
            }
            for (Double d : o2) {
                if (d < s) {
                    ret = 1;
                    break;
                }
                if (d == s) {
                    ret = 0;
                }
            }
            if (tc1 > 1) {
                //Prefer the safest
                return -ret;
            } else {
                //Prefer the least safest
                return ret;
            }
        }
    };

    @Override
    public TurnAction onTurn(Battlefield field, MapPoint position, float health) {
        //Find all the tanks
        List<MapPoint> enemies = field.find(FieldObjectType.TANK);
        enemies.remove(position);
        if (enemies.isEmpty()) {
            return TurnAction.createNothingAction();
        }

        //Set the constants needed for this turn
        this.enemies = enemies;
        this.field = field;
        this.me = position;

        //Create a new NodeMap
        MoveNode n = new MoveNode(position);
        this.nodeMap.clear();
        this.nodeMap.put(position, n);

        //Find the "best" safety within MAX_DEPTH moves
        int depth = 0;
        Safety safety = n.getSafety(0);
        for (depth = 0; depth < MAX_DEPTH; depth++) {
            int lastThreat = safety.threats;
            safety = n.getSafety(depth);
            int newThreat = safety.threats;
            if (newThreat == 1) {
                //Always prefer 1 threat
                break;
            }
            if (depth != 0 && lastThreat - newThreat >= depth) {
                //Prefer fewer threats only if we are much safer;
                //  Specifically, don't move twice for only 1 less threat
                break;
            }
        }

        //Depth == 0         : Only 1 threat; best position
        //Depth == MAX_DEPTH : Many or no threats, but no good moves available
        if (depth > 0 && depth < MAX_DEPTH) {
            //Move towards the better spot
            for (Move m : n.moves) {
                if (nodeMap.get(m.point).getSafety(depth - 1) == safety) {
                    return m.action();
                }
            }
        }

        //We're in a good position, shoot now
        //Calculate tank with most threat
        MapPoint threat = null;
        double biggestThreat = Double.MAX_VALUE;
        for (MapPoint p : enemies) {
            double t = missChance(position.distanceTo(p)) + countObstacles(position, p, false);
            if (t < biggestThreat) {
                biggestThreat = t;
                threat = p;
            }
        }

        return TurnAction.createShootActionRadians(position.angleBetweenRadians(threat));
    }
    public void onDestroyed(Battlefield field, boolean won) {}
    public void onSpawn(Battlefield field, MapPoint position) {}
    public void turnFeedback(MapPoint newPosition, FieldObjectType hit) {}
    public String getName() {
        return "HunterKiller " + MAX_DEPTH;
    }

}

```

And that's it. I'm spent.
> 2 votes

# Answer
This one is a variant on the Shoot-Closest in that, every other turn, it moves in a direction until it can no longer. It shoots every other turn.

It has a handy utility, `path`, which can be used to identify all points (and thus objects) between two points.

```
public final class BouncingTank implements Tank {

    /**
     * Find all the points between here and there, excluding those points
     * @param p1 Here
     * @param p2 There
     * @return
     */
    private java.util.ArrayList<MapPoint> path(MapPoint p1, MapPoint p2) {
        double dist = p1.distanceTo(p2);
        double dx = (p2.getX() - p1.getX()) / dist;
        double dy = (p2.getY() - p1.getY()) / dist;

        java.util.ArrayList<MapPoint> ret = new java.util.ArrayList();
        MapPoint lastP = null;
        for (int i = 0; i < dist; i++) {
            MapPoint p = p1.cloneAndTranslate((int)(i*dx), (int)(i*dy));
            if (p.equals(p1) || p.equals(lastP)) continue;
            if (p.equals(p2)) break;
            ret.add(p);
            lastP = p;
        }
        return ret;
    }

    /**
     * Find the number of legal moves in the given direction
     * @param field
     * @param position
     * @param dir
     * @return
     */
    private int findMoves(Battlefield field, MapPoint position, TurnAction.Direction dir) {
        if (dir == null) return -1;
        int count = 0;
        MapPoint dest = dir.translate(position, Battlefield.FIELD_SIZE);
        java.util.ArrayList<MapPoint> obs = path(position, dest);
        for (MapPoint oMP : obs) {
            try {
                if (FieldObjectType.NOTHING.equals(field.getObjectTypeAt(oMP))) {
                    count++;
                } else {
                    break;
                }
            } catch (IllegalArgumentException ex) {
                break;
            }
        }
        return count;
    }

    /**
     * Finds the direction towards which there are the fewest obstacles
     * @param field
     * @param position
     * @return
     */
    private TurnAction.Direction findDirection(Battlefield field, MapPoint position) {
        TurnAction.Direction ret = null;
        int mostMoves = 0;
        for (TurnAction.Direction d : TurnAction.Direction.values()) {
            int count = findMoves(field, position, d);
            if (count > mostMoves) {
                ret = d;
                mostMoves = count;
            }
        }
        return ret; //Maybe null
    }

    private TurnAction shootClosest(Battlefield field, MapPoint position) {
        //Find all the tanks
        List<MapPoint> tanks = field.find(FieldObjectType.TANK);
        tanks.remove(position);

        if (tanks.isEmpty()) return TurnAction.createNothingAction();

        //Calculate closest tank
        MapPoint cPoint = null;
        double cDist = Double.POSITIVE_INFINITY;
        for (MapPoint p : tanks) {
            double dist = position.distanceTo(p);
            if (dist < cDist) {
                cDist = dist;
                cPoint = p;
            }
        }

        //Shoot at closest tank
        return TurnAction.createShootActionRadians(position.angleBetweenRadians(cPoint));
    }

    private int turnsUntilShoot = 1;
    private TurnAction.Direction moveToward = null;

    @Override
    public TurnAction onTurn(Battlefield field, MapPoint position, float health) {
        //Determine if current direction is valid
        int moves = findMoves(field, position, moveToward);
        if (moves <= 0) {
            moveToward = findDirection(field, position);
            //Determine if we're stuck
            if (moveToward == null) {
                return shootClosest(field, position);
            }
        }

        //Shoot if it's time
        if (turnsUntilShoot == 0) {
            turnsUntilShoot = 1;
            return shootClosest(field, position);
        } else {
            turnsUntilShoot--;
            return TurnAction.createMoveAction(moveToward, Math.min(3, moves));
        }
    }

    public void onDestroyed(Battlefield field, boolean won) {}
    public void onSpawn(Battlefield field, MapPoint position) {}
    public void turnFeedback(MapPoint newPosition, FieldObjectType hit) {}
    public String getName() {
        return "Bouncing Tank";
    }
}

```
> 1 votes

# Answer
I'm not very good at this but I thought I'd still give it a shot, you know, practice and stuff.

My tank will randomly decide to move or shoot. When it decides to shoot, it'll try to shoot at the nearest available target.

```
package com.richarda.tankwar;

import zove.ppcg.tankwar.*;

import java.util.Random;
import java.util.ArrayList;

public class RichardATank implements Tank
{
    private String name;

    public RichardATank()
    {
        this.name = "Richard-A Tank";
    }

    /**
     *
     * @param field
     *            The current battlefield, complete with all obstacle and tank
     *            positions
     * @param position
     */
    @Override
    public void onSpawn(Battlefield field, MapPoint position)
    {

    }

    /**
     * The tank will randomly move around and occasionally shoot at the nearest available target.
     *
     * @param field
     *            The current battlefield, complete with all obstacle and tank
     *            positions
     * @param position
     *            The tank's current position
     * @param health
     *            The tank's current health
     * @return
     */
    @Override
    public TurnAction onTurn(Battlefield field, MapPoint position, float health)
    {
        Random r = new Random();
        int n = r.nextInt(2);

        if(n == 1)
        {
            return this.tryShootAtNearestTank(field, position);
        }

        return TurnAction.createMoveAction(TurnAction.Direction.getRandom(), r.nextInt(2) + 1);
    }

    /**
     *
     * @param newPosition
     *            The tank's new position (may not be changed)
     * @param hit
     *            What the tank hit, if it decided to shoot
     */
    @Override
    public void turnFeedback(MapPoint newPosition, FieldObjectType hit)
    {

    }

    /**
     *
     * @param field
     *            The battlefield
     * @param won
     */
    @Override
    public void onDestroyed(Battlefield field, boolean won)
    {

    }

    @Override
    public String getName()
    {
        return this.name;
    }

    /**
     * Try and shoot at the nearest tank
     *
     * @param bf The battlefield
     * @param curTankLocation The current tank's location
     * @return TurnAction the shoot action to the nearest tank
     */
    private TurnAction tryShootAtNearestTank(Battlefield bf, MapPoint curTankLocation)
    {
        MapPoint nearestTankLoc = this.getNearestTankLocation(bf, curTankLocation);

        double firingAngle = curTankLocation.angleBetween(nearestTankLoc);

        return TurnAction.createShootAction((float) firingAngle);
    }

    /**
     * Try to find the nearest tank's location
     *
     * @param bf The battlefield
     * @param curTankLocation The current tank's location
     * @return MapPoint The location of the nearest tank
     */
    private MapPoint getNearestTankLocation(Battlefield bf, MapPoint curTankLocation)
    {
        ArrayList<MapPoint> enemyTankLocations = this.getEnemyTanksOnField(bf, curTankLocation);

        MapPoint nearestTankLoc = null;

        for(MapPoint enemyTankLoc : enemyTankLocations)
        {
            if(nearestTankLoc == null || curTankLocation.distanceTo(enemyTankLoc) < curTankLocation.distanceTo(nearestTankLoc))
            {
                nearestTankLoc = enemyTankLoc;
            }
        }

        return nearestTankLoc;
    }

    /**
     * Get all enemy tanks on the field
     *
     * @param bf The battlefield
     * @param curTankLocation The current tank's location
     * @return ArrayList<MapPoint> A list with all enemy tanks in it
     */
    private ArrayList<MapPoint> getEnemyTanksOnField(Battlefield bf, MapPoint curTankLocation)
    {
        int maxSize = Battlefield.FIELD_SIZE;
        ArrayList<MapPoint> tanks = new ArrayList<MapPoint>();

        for(int i = 0; i < maxSize; i++)
        {
            for(int j = 0; j < maxSize; j++)
            {
                FieldObjectType objType = bf.getObjectTypeAt(i, j);

                if(objType == FieldObjectType.TANK)
                {
                    MapPoint tankLocation = new MapPoint(i, j);

                    if(!tankLocation.equals(curTankLocation))
                    {
                        tanks.add(tankLocation);
                    }
                }
            }
        }

        return tanks;
    }
}

```

The full code including the control program can be found here.
> 1 votes

# Answer
## Dodge Tank

This tank will shoot at the closest tank. Every so often, depending on its health and the last time it moved, it will try to move perpendicular to the closest tank in an attempt to dodge its lasers.

```
public class DodgeTank implements Tank {

private int lastMove;
@Override
public void onSpawn(Battlefield field, MapPoint position){
    //nada
}
@Override
public TurnAction onTurn(Battlefield field, MapPoint position, float health){
    List<MapPoint> tanks = field.find(FieldObjectType.TANK);
    tanks.remove(position);
    MapPoint nearest= new MapPoint(0,0);
    double dis=Double.POSITIVE_INFINITY;
        for (MapPoint tank: tanks){
            double distance=tank.distanceTo(position);
            if (distance<dis){
                nearest=tank;
                dis=distance;
            }
        }
    if (lastMove*Math.random()+(4-health/25)<5){//Attack
        lastMove++;
        return TurnAction.createShootActionRadians(position.angleBetweenRadians(nearest));
    }
    else {
        lastMove=0;
        double cumulativeAngle=position.angleBetweenRadians(nearest);
        for (MapPoint tank : tanks){
            cumulativeAngle+=position.angleBetweenRadians(tank);
        }
        cumulativeAngle/=tanks.size();
        cumulativeAngle/=(Math.PI/2);
        int dir=(int)Math.floor(cumulativeAngle);
        TurnAction move;
        switch (dir){
            case 0:
                if (position.getX()>2&&field.getObjectTypeAt(position.cloneAndTranslate(-3, 0)).equals(FieldObjectType.NOTHING)){
                    return TurnAction.createMoveAction(TurnAction.Direction.WEST, 3);
                }
                return TurnAction.createMoveAction(TurnAction.Direction.EAST, 3);
            case 1:
                if (position.getY()>2&&field.getObjectTypeAt(position.cloneAndTranslate(0, -3)).equals(FieldObjectType.NOTHING)){
                    return TurnAction.createMoveAction(TurnAction.Direction.SOUTH, 3);
                }
                return TurnAction.createMoveAction(TurnAction.Direction.NORTH, 3);
            case -1:
                if ((position.getY()<(Battlefield.FIELD_SIZE-4))&&field.getObjectTypeAt(position.cloneAndTranslate(0,3)).equals(FieldObjectType.NOTHING)){
                    return TurnAction.createMoveAction(TurnAction.Direction.NORTH, 3);
                }
                return TurnAction.createMoveAction(TurnAction.Direction.SOUTH, 3);
            default:
                if ((position.getX()<(Battlefield.FIELD_SIZE-4))&&field.getObjectTypeAt(position.cloneAndTranslate(3,0)).equals(FieldObjectType.NOTHING)){
                    return TurnAction.createMoveAction(TurnAction.Direction.EAST, 3);
                }
                return TurnAction.createMoveAction(TurnAction.Direction.WEST, 3);
        }
    }
}
@Override
public void turnFeedback(MapPoint newPosition, FieldObjectType hit){
    //Nada
}
@Override
public void onDestroyed(Battlefield field, boolean won){
  //if (won) this.taunt();
  //else this.selfDestruct();
}
@Override
public String getName(){
    return "Dodge Tank";
}
}

```
> 1 votes

# Answer
This was way more complicated than I thought..

This is my entry in groovy, you need groovy installed and compile it with

```
groovyc zove\ppcg\tankwar\felsspat\RunTank.groovy

```

To call it you need to add $GROOVY\_HOME/Groovy/Groovy-2.3.4/lib/groovy-2.3.4.jar (or whatever version) to the classpath.

I could send you a compiled .class file and the library if you don't want to install it.

There seems to be a situation where tanks can't see it other, I don't know if that is intended. That caused deadlocks while testing.

Anyway here is RunTank: RunTank boldy advances in the opposite direction of the closest tank if it is the closest tank to the closest tank or more than one tank is within FIELD\_SIZE / 3. I hope that makes sense, I'm drunk :)

```
package zove.ppcg.tankwar.felsspat

import zove.ppcg.tankwar.Battlefield
import zove.ppcg.tankwar.FieldObjectType
import zove.ppcg.tankwar.MapPoint
import zove.ppcg.tankwar.Tank
import zove.ppcg.tankwar.TurnAction
import zove.ppcg.tankwar.TurnAction.Direction

public class RunTank implements Tank {

    @Override
    public TurnAction onTurn(Battlefield field, MapPoint position, float health) {
        def targets = (field.find(FieldObjectType.TANK) - position).sort{ position.distanceTo(it) }

        if (targets) {

            def runDistance = (Battlefield.FIELD_SIZE / 3).toInteger()

            def closeTargets = targets.grep {
                position.distanceTo(it) < runDistance
            }

            if (position.distanceTo(closestEnemy(position, field)) < targets.first().distanceTo(closestEnemy(targets.first(), field))) {
                return run(field, position, targets)
            }

            if (closeTargets.size() > 1) {
                return run(field, position, targets)
            } else  {
                return shootEnemy(position, targets)
            }
        } else {
            println "WTF! Targets: ${field.find(FieldObjectType.TANK)} + Position ${position}"
            return TurnAction.createMoveAction(Direction.getRandom(), 1);
        }

    }

    def shootEnemy(position, targets) {
        return TurnAction.createShootActionRadians(position.angleBetweenRadians(targets.first()))
    }

    def run(field, position, targets) {
        def freePositions = (field.find(FieldObjectType.NOTHING) - position).grep { position.distanceTo(it) <= 3.0 && [0d, 90d, 180d, 270d].contains(position.angleBetween(it))}.sort{position.distanceTo(it)}
        def availablePositions = []
        freePositions.each { targetPosition ->
            def positions = getPositionsBetween(position,targetPosition)
            if (! positions || positions.every { it.equals(FieldObjectType.NOTHING) }) {
                availablePositions.add(targetPosition)
            }
        }
        availablePositions = availablePositions.sort{closestEnemy(it, field)}.reverse()

        if (availablePositions) {
            def targetPosition = availablePositions.first()
            if (targetPosition.distanceTo(closestEnemy(targetPosition, field)) > position.distanceTo(closestEnemy(position, field))) { // Don't move closer to an enemy
                return moveTo(position, targetPosition)
            } else {
                return shootEnemy(position, targets)
            }
        } else {
            return shootEnemy(position, targets)
        }
    }

    def moveTo(position, targetPosition) {
        def distance = position.distanceTo(targetPosition).toInteger()
        switch (position.angleBetween(targetPosition)) {
            case 0d:
                return TurnAction.createMoveAction(TurnAction.Direction.NORTH, distance)
                break

            case 90d:
                return TurnAction.createMoveAction(TurnAction.Direction.EAST, distance)
                break

            case 180d:
                return TurnAction.createMoveAction(TurnAction.Direction.SOUTH, distance)
                break

            case 270d:
                return TurnAction.createMoveAction(TurnAction.Direction.West, distance)
                break

            default:
            println "I'm stupid :("

        }
    }

    def closestEnemy(position, field) {
        return field.find(FieldObjectType.TANK).sort { position.distanceTo(it) }.first()
    }

    def getPositionsBetween(self, target) {
        def positions = []
        if(self.x == target.x) {
            for (y in self.y..target.y) {
                positions.add(new MapPoint(self.x, y))
            }
        } else {
            for (x in self.x..target.x) {
                positions.add(new MapPoint(x, self.y))
            }
        }
        return positions - self - target
    }

    @Override
    public void turnFeedback(MapPoint newPosition, FieldObjectType hit) {
    }

    @Override
    public void onDestroyed(Battlefield field, boolean won) {
        println ":("
    }

    @Override
    public void onSpawn(Battlefield field, MapPoint position) {
        println "Go!"
    }

    @Override
    public String getName() {
        return "RunTank";
    }
}

```

I have one suggestion: Add colors to the tank, and a method to implement it. Also labels would be nice in the GUI :)
> 1 votes

---
Tags: king-of-the-hill
---


title: Golfing for Domino Day

text:
# Question
Title: Golfing for Domino Day
Given a setup of dominoes your task is to figure out which dominoes fall and which don't.

## Input

Take a rectangular ASCII representation of a domino setup. The following characters are used for the ASCII grid:

* (space): empty cell
* `|`, `-`, `/`, `\`: dominoes

Dominoes can fall in 8 directions, which are represented by the following letters (similar to WASD orientations):

```
Q W E
A   D
Z X C

```

One or more of the dominoes will be replaced by one of these letters to indicate that the domino is pushed over at the start. Here is an example:

```
D||||/
  -   /
  -    -
  -    -
  /|||||

```

I don't want this challenge to turn into an exercise in input parsing so any of the following input forms are allowed:

* A string with the grid (optionally preceded by its dimensions if that helps)
* An array/list/tuple with one string for each line (optionally along with width and height integers)
* A (nested) array/list/tuple with one string/character for each grid cell (optionally along with width and height variables)

You can read from STDIN or take a function argument or even expect the input to be stored in a variable.

## Output

Write to STDOUT or return (or save in a variable) the resulting grid in any of the valid input formats, indicating which dominoes have fallen and which haven't. That is, replace each fallen domino with `#` and leave each standing domino as it was in the input.

## Rules

Of course, dominoes propagate their fall through the setup. As there may be race conditions, we assume that there are fixed time steps and the falling propagates one grid cell per time step.

Dominoes generally fall the way you would intuitively expect them to, but a rigorous specification of common sense turns out to be quite lengthy. Sorry for that, I hope the examples help. Here is a gist with all unique two-tile combinations (up to rotation and reflection). Read on for the rigorous rules.

Each domino can fall in only two directions:

```
           W       Q          E
A | D      -        /        \
           X         C      Z

```

Whenever a domino falls it affects the cell in the direction of the fall. If that cell contains a domino which can fall in the same direction or in a direction which differs by 45 degrees, that domino does so in the next time step.

Examples:

```
D|    ->    DD      (falls in same direction)

D/    ->    DC      (falls at 45 degrees)

C     ->    C       (falls at 45 degrees)
 -           X

```

Whenever a diagonally oriented domino (`/` or `\`) falls, it also affects the two cells which touch both its cell and the cell in the direction of its fall. If these cells contain a domino which can fall in the same direction as the original domino, or in the axis-aligned direction away from it, that domino does so in the next time step.

Examples:

```
C/     ->   CC      (the cell in the direction of the fall is the one below
                     the /, so it falls in the same direction)

C|     ->   CD      (falls in the axis-aligned direction away from the C)

C-     ->   C-       (the direction away from the Q is W,
  or                  but neither - nor \ can fall to W)
C\     ->   C\

```

**Exception**: if a domino is pushed in both valid directions at once (i.e. if any of the above rules are in conflict), it doesn't fall.

Examples:

```
D|A   ->    D|A     (central domino in pushed in both directions)

  Z           Z     (although it's pushed in one direction by two dominoes
D\A   ->    D\A      and in the other by only one, it doesn't fall)

 X           X      (the domino is being pushed from two opposing sides
D-A   ->    DXA      D and A, but neither is valid for that domino. Hence,
                     there is no conflict and the X can push the domino over)

 Z           Z      (pushed in the same direction by two dominoes, so falls)
\A    ->    ZA

   Z           Z           Z    (once the conflict arises, the affected
  \   ->      Z   ->      Z      domino is locked in its position and can't
D|A         D|A         D|A      be pushed over by future dominoes)

```

## Examples

```
8 5
D||||/            ######
  -   /             -   #
  -    -    -->     -    #
  -    -            -    #
  /|||||            /|||||

===============================================

17 9
E|/|||/                    #######
  -   -                      #   #
  -   -                      #   #
  -   -                      #   #
  /|||/|||||||||/    -->     ###############
       /        -                 #        #
        /       -                  #       -
         /      -                   #      #
          /|||||\                    #######

===============================================

19 8
       \|/                        ###
       - -                        # #
D||||/|\ /|||/             ######## #####
      /      -                   #      #
       -    \-       -->          -    \#
      \-   \ -                   #-   \ #
D||||\ /  \  /             ###### /  \  #
        |\    |||||                |\    #####

==============================================

11 11
-\\\/|\|\-|         -\##/|###-|
-|\\||\-|\-         -|#####-|\-
|\//\//|-/-         |#//\//|#/-
\|//|-|\-\|         #####-|##\|
---||/-\//|         #-######//|
///|||\----   -->   #/#####----
-|/---|-|-\         #|##--|-|-\
--|--\/|///         ####-\/|///
/|//--|//-|         ####--|//-|
|/\-|||-/-\         |/\####-/-\
E||\-|\---/         ####-|\---/

```

Let me know if you think I made a mistake (especially with the last one).

# Answer
> 17 votes
## C# ~~1048~~ ~~907~~ 850bytes

Now heavily golfed, pretty much just a jumble of bit operations on a two-dimensional array of integer enums. Could probably be made somewhat shorter by using a 1-dimensional array, but I'm not prepared to try and re-work this at this point. Reads the dimensions and string from stdin, for example:

```
11 11 -\\\/|\|\-|-|\\||\-|\-|\//\//|-/-\|//|-|\-\|---||/-\//|///|||\-----|/---|-|-\--|--\/|////|//--|//-||/\-|||-/-\E||\-|\---/

```

Golfed:

```
using L=System.Console;class R{static void Main(){int p=255,e,c,E=7,D,C,X,Z,A,m=-1,t=m,f=t,u,i=t;for(;t<0;)for(t=f,f=0;(C=L.Read())>47;)f=f*10+C-48;var T=new int[f,t];for(;++i<f;)for(c=0;c<t;T[i,c++]=(C>99?68:C>91?34:C>89?112:C>87?56:C>86?131:C>80?193:C>68?7:C>67?14:C>66?28:C>64?224:C>46?136:C>44?17:0)*(C>64&C<91?1:257))C=L.Read();for(;i+E>0;E=-E)for(i=c=m;++c<f;)for(C=m;++C<t;){if(E>0&(A=D=T[c,C])>0&D<p){T[c,C]=m; X=C+(i=(D&4)>0?1:(D&64)/-64);Z=c+(u=(D&16)>0?1:D%2*m);System.Action v=()=>{if(Z>m&Z<f&X>m&X<t&&(e=T[Z,X])>p&(e>>8&A)>0)T[Z,X]&=65280|A;};v();if((i&u)!=0){X=i==u?C:X;Z=i==u?Z:c;A=((D&128)/128+D*2)&D;v();X=C+i-X+C;Z=c+u-Z+c;A=(D%2*128+D/2)&D;v();}i=8;}if(E<0&D>p&((D=D&p)&(D-1))<1&D>0)T[c,C]=D<2?131:D>64?193:D/2*7;}for(D=m;++D<f;L.WriteLine())for(c=0;c<t;L.Write(C<0?'#':(C=C>>8)>99?'/':C>67?'|':C>33?'\\':C>9?'-':' '))C=T[D,c++];}}

```

Because I have too much time I've modified the ungolfed version to output an animated gif of the dominoes falling (with help from this SO question and these documents  ). This has only added code, and it's either in a `#if gifness` block or clearly marked.

To create the gifs you provide a pair of command line arguments describing the frame times, output file, etc,

```
dominoGolf.exe console_delay (out_file_name (gif_frame_time (final_frame_time)))
dominoGolf.exe 0 outfile.gif 1 100

```

The third argument is the frame time for each frame (1/100s of seconds). The fourth argument is the frame time for last frame (1/100s of seconds). The second argument is the output filename for the gif. You can omit the filename, delay, and final delay if you just want the console output. The first argument is a delay between frames rendered to the terminal in milliseconds. You can omit all arguments if you don't want an animation at all and just want to see the result. It reads the domino data from stdin just like the golfed version. This code is horrible in it's own way (butchers the gif so that it loops).

Ungolfed gif-generating code:

```
#define gifness

using L=System.Console;

class R
{
    static void Main(string[] args) // don't need args
    {
        int p=255,P=0xFF00,m=15,M=240, // might be able to inline a couple of these
        w=1,e=2,d=4,c=8,x=16,z=32,a=64,q=128, // most of these are reusable
        W=131,E=7,D=14,C=28,X=56,Z=X*2,A=Z*2,Q=193, // most (all?) of these are reusable
        Y=w+x,U=a+d,N=c+q,B=z+e, // one of these atleast is pre-evalable

        // recognise this?
        t=-1,f=t,k,u,i=t,j,J,K,o,O,b;
        for(;t<0;)
            for(t=f,f=0;(k=L.Read())>47;)
                f=f*10+k-48;

        var T=new int[f,t]; // main arr
        // domino: dir, copy(for render)
        // motion: pickup

        // input
        for(;++i<f;) // values of i and j don't matter, just counters
        {
            for(j=0;j<t;) // increment done 3down
            {
                k=L.Read();
                T[i,j++]=(
                // fallen
                k=='W'?W:k=='E'?E:k=='D'?D:k=='C'?C:k=='X'?X:k=='Z'?Z:k=='A'?A:k=='Q'?Q:
                // dominos
                k==' '?0:k=='-'?Y:k=='/'?N:k=='|'?U:B // ASCII, order for >
                )*(k>64&k<91?1:257);
            }
        }

        #if gifness
        System.Drawing.Font font1 = null;
        System.Windows.Media.Imaging.GifBitmapEncoder genc = null;
        System.Drawing.Bitmap bmp = null;
        System.Drawing.Graphics g = null;
        if (args.Length > 1)
        {
            font1 = new System.Drawing.Font(System.Drawing.FontFamily.GenericMonospace, 12, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel);
            genc = new System.Windows.Media.Imaging.GifBitmapEncoder();
            bmp = new System.Drawing.Bitmap(t * 8, f * 14); // I have no clue what these should be in relation to em size
            g = System.Drawing.Graphics.FromImage(bmp);
        }
        #endif

        if (args.Length > 0) // not important
        {
            L.Clear();
        }

        // main
        for(;i>0;) // can do i=1-i and swap setting 1 for 0 to remove {}
        {

            if (args.Length > 0) // non-critical, renders the current state to the console/gif
            {
                var os="";
                for (o=0;o<f;o++) // values of i and j don't matter, just counters
                {
                    for (j=0;j<t;j++)
                    {
                        k=T[o,j];
                        os += k==0?' ':k<p?'#':(k=k>>8)==Y?'-':k==N?'/':k==U?'|':'\\'; // order for >
                    }
                    os+="\n";
                }
                L.SetCursorPosition(0, 0);
                L.Write(os);

                #if gifness
                if (args.Length > 1)
                {
                    g.Clear(System.Drawing.Color.White);
                    g.DrawString(os, font1, System.Drawing.Brushes.Black, 0, 0);
                    System.IO.MemoryStream bms = new System.IO.MemoryStream();
                    bmp.Save(bms, System.Drawing.Imaging.ImageFormat.Gif);
                    var bmpf = System.Windows.Media.Imaging.BitmapFrame.Create(bms);
                    genc.Frames.Add(bmpf);

                    // do I chose the frame duraton1??!?!?! (take from args[2] is present else args[0])
                }
                #endif

                System.Threading.Thread.Sleep(int.Parse(args[0]));
            }

            // back to important stuff
            i=0; // set me to 1 if we do anything (8 in golfed version due to E being 7)

            // move motions
            for (j=0;j<f;j++) // careful!!
            {
                for (k=0;k<t;k++) // careful!!
                {
                    O=o=T[j,k];
                    if (o>0&o<p) // we are motion
                    {
                        T[j,k]=-1; // do this so we can't skip it

                        K=k+(i=((o&d)>1?1:(o&a)>0?-1:0));
                        J=j+(u=((o&x)>1?1:(o&w)>0?-1:0));

                        System.Action v=()=>{
                            if(J>=0&J<f&K>=0&K<t&&(b=T[J,K])>p&&((b>>8)&O)>0)
                            {
                                T[J,K]&=(P|O);
                            }
                        };

                        v();
                        if (i!=0&u!=0)
                        {
                            K=i==u?k:K; // k+i == K
                            J=i==u?J:j; // j+u == J
                            O=(((o&q)>0?w:0)+o*2)&o;
                            v();

                            K=K==k?k+i:k;
                            J=J==j?j+u:j;
                            O=(((o&w)>0?q:0)+o/2)&o;
                            v();
                        }

                        i=1;
                    }
                }
            }

            // move dominos
            for (j=0;j<f;j++) // careful!!
            {
                for (k=0;k<t;k++) // careful!!
                {
                    o=T[j,k];
                    if (o>p) // we are domino
                    {
                        o=o&p;
                        if ((o&m)<1!=(o&M)<1)
                        { // we have motion
                            T[j,k]=o==w?W:o==q?Q:o+o/2+o*2;
                        }
                    }
                }
            }
        }

        if (args.Length > 0)
        {
            L.SetCursorPosition(0, 0);
        }

        // output
        for (o=0;o<f;o++)
        {
            for (j=0;j<t;j++)
            {
                k=T[o,j];
                L.Write(k<0?'#':(k=k>>8)==0?' ':k==Y?'-':k==N?'/':k==U?'|':'\\'); // order for >
            }
            L.WriteLine();
        }

        #if gifness
        if (args.Length > 1)
        {
            g.Dispose();
            bmp.Dispose();

            System.IO.MemoryStream ms = new System.IO.MemoryStream();

            genc.Save(ms);
            byte[] data = ms.GetBuffer();
            byte[] netscape = { 0x21, 0xFF, 0x0B, 0x4E, 0x45, 0x54, 0x53, 0x43, 0x41, 0x50, 0x45, 0x32, 0x2E, 0x30, 0x03, 0x01, 0x00, 0x00, 0x00 };

            if (args.Length > 2)
            {
                int last = -1;
                int duration = int.Parse(args[2]);

                // promise yourself now you will never use this in production code
                // I've not read enough of the GIF spec to know if this is a bad idea or not
                for (i = 0; i < ms.Length - 5; i++)
                {
                    if (data[i] == 0x21 && data[i+1] == 0xF9 && data[i+2] == 0x04 && data[i+3] == 01)
                    {
                        data[i+4] = (byte)(duration & p); // something endian (least significant first)
                        data[i+5] = (byte)((duration & P) >> 8);
                        last = i+4;
                    }
                }

                if (last != -1 && args.Length > 3)
                {
                    duration = int.Parse(args[3]);
                    data[last] = (byte)(duration & p);
                    data[last+1] = (byte)((duration & P) >> 8);
                }
            }

            using (System.IO.FileStream fs = new System.IO.FileStream(args[1], System.IO.FileMode.Create))
            {
                fs.Write(data, 0, 13);

                // behold
                fs.Write(netscape, 0, netscape.Length);

                fs.Write(data, 13, (int)ms.Length - 13); // lets hope these arn't in excess of 2GBs
            }
        }
        #endif
    }
}

```

An example gif for the 3rd example input (and that shown above)

Example randomly generated 100x25 domino layout

"Domino" in dominoes

# Answer
> 3 votes
# Python 1188

Basically just loops through continuously matching some hefty regex until it stops changing. It actually matches all the pushes of each direction separately (through regex), and then composes the different results making sure there are no conflicts and such.

The regex can probably be done much more compactly, but for now here is what I have (it assumes the grid is stored in a string, `g`, and the dimensions are in `x` and `y`):

```
import re;L='QWEADZXC';a='';m=(x*y+y);o=[0]*m;X='(.{%s})';t=X%x;u=X%(x+1);v=X%(x-1);R=range
def S(s,l):
 f=s
 for p,r in l:
    n=re.sub(p,r,s,flags=re.DOTALL)
    for i in R(len(n)):
     if n[i]!=s[i]:f=f[:i]+n[i]+f[i+1:]
 return f
while g != a:
 a=g;n='';d=[S(g,[(r'D\|','DD'),(r'D\\','DE'),('D/','DC')]),S(g,[(r'\|A','AA'),(r'\\A','ZA'),('/A','QA')]),S(g,[('-%sW'%t,r'W\1W'),(r'\\%sW'%t,r'E\1W'),('/%sW'%t,r'Q\1W')]),S(g,[('X%s-'%t,r'X\1X'),(r'X%s\\'%t,r'X\1Z'),(r'X%s/'%t,r'X\1C')]),S(g,[('C%s/'%u,r'C\1C'),('C%s-'%u,r'C\1X'),(r'C%s\|'%u,r'C\1D'),('C%s/'%t,r'C\1C'),('C%s-'%t,r'C\1X'),('C/','CC'),(r'C\|','CD')]),S(g,[(r'Z%s\\'%v,r'Z\1Z'),('Z%s-'%v,r'Z\1X'),(r'Z%s\|'%v,r'Z\1A'),(r'Z%s\\'%t,r'Z\1Z'),('Z%s-'%t,r'Z\1X'),(r'\\Z','ZZ'),(r'\|Z','AZ')]),S(g,[('/%sQ'%u,r'Q\1Q'),('-%sQ'%u,r'W\1Q'),(r'\|%sQ'%u,r'A\1Q'),('/%sQ'%t,r'Q\1Q'),('-%sQ'%t,r'W\1Q'),('/Q','QQ'),(r'\|Q','AQ')]),S(g,[(r'\\%sE'%v,r'E\1E'),('-%sE'%v,r'W\1E'),(r'\|%sE'%v,r'D\1E'),(r'\\%sE'%t,r'E\1E'),('-%sE'%t,r'W\1E'),(r'E\\','EE'),(r'E\|','ED')])]
 for i in range(m):
    c=0
    for r in d:
     if r[i]in L:
        if c==0:c=r[i]
        elif r[i]!=c:o[i]=1;break
    n+=g[i]if c==0 or o[i]else c
 g=n
print re.sub(r'\w','#',g)

```

More ungolfed:

```
import re

L = 'QWEADZXC'

def sub_all(string,lst):
    final = string
    for p,r in lst:
        new = re.sub(p,r,string,flags=re.DOTALL)
        for i in range(len(new)):
            if new[i]!=string[i]:
                final=final[:i]+new[i]+final[i+1:]
    return final

def dominoes(grid,x,y):
    print len(grid),x*y+y
    print grid

    last = ''
    locked = [0]*(x*y+y)
    while grid != last:
        last = grid

        Dgrid = sub_all(grid,[(r'D\|','DD'),(r'D\\','DE'),('D/','DC')])
        Agrid = sub_all(grid,[(r'\|A','AA'),(r'\\A','ZA'),('/A','QA')])
        Wgrid = sub_all(grid,[('-(.{%s})W'%x,r'W\1W'),(r'\\(.{%s})W'%x,r'E\1W'),('/(.{%s})W'%x,r'Q\1W')])
        Xgrid = sub_all(grid,[('X(.{%s})-'%x,r'X\1X'),(r'X(.{%s})\\'%x,r'X\1Z'),(r'X(.{%s})/'%x,r'X\1C')])

        Cgrid = sub_all(grid,[('C(.{%s})/'%(x+1),r'C\1C'),('C(.{%s})-'%(x+1),r'C\1X'),(r'C(.{%s})\|'%(x+1),r'C\1D'),
                        ('C(.{%s})/'%x,r'C\1C'),('C(.{%s})-'%x,r'C\1X'),
                        ('C/','CC'),(r'C\|','CD')])

        Zgrid = sub_all(grid,[(r'Z(.{%s})\\'%(x-1),r'Z\1Z'),('Z(.{%s})-'%(x-1),r'Z\1X'),(r'Z(.{%s})\|'%(x-1),r'Z\1A'),
                        (r'Z(.{%s})\\'%x,r'Z\1Z'),('Z(.{%s})-'%x,r'Z\1X'),
                        (r'\\Z','ZZ'),(r'\|Z','AZ')])

        Qgrid = sub_all(grid,[('/(.{%s})Q'%(x+1),r'Q\1Q'),('-(.{%s})Q'%(x+1),r'W\1Q'),(r'\|(.{%s})Q'%(x+1),r'A\1Q'),
                        ('/(.{%s})Q'%x,r'Q\1Q'),('-(.{%s})Q'%x,r'W\1Q'),
                        ('/Q','QQ'),(r'\|Q','AQ')])

        Egrid = sub_all(grid,[(r'\\(.{%s})E'%(x-1),r'E\1E'),('-(.{%s})E'%(x-1),r'W\1E'),(r'\|(.{%s})E'%(x-1),r'D\1E'),
                        (r'\\(.{%s})E'%x,r'E\1E'),('-(.{%s})E'%x,r'W\1E'),
                        (r'E\\','EE'),(r'E\|','ED')])

        grids = [Dgrid,Agrid,Wgrid,Xgrid,Cgrid,Zgrid,Qgrid,Egrid]
        ngrid = ''

        for i in range(x*y+y):
            c = None
            for g in grids:
                if g[i] in L:
                    if c==None: c = g[i]
                    elif g[i] != c:
                        ngrid += grid[i]
                        locked[i]=1
                        break
            else:
                ngrid += grid[i] if c==None or locked[i] else c
        grid = ngrid
        print grid
    return re.sub(r'\w','#',grid)

```

The listed inputs all produce their outputs except the third, in which I'm pretty sure there's a mistake (the `\-/` at the very top should be `\|/` if the given output is desired). I'm also assuming that the `.` in the bottom left corner of the last one was intended to be a `D`.

---
Tags: code-golf, dominoes
---


# Question
Title: Generate me some appropriate license plates!
---

The scenario: You are a software designer working for a gov't-run company that designs license plates for cars and other vehicles. You've been asked to develop software that generates license plates. Before you got to work, your bosses laid down these ground rules.

---

# A license plate cannot contain:

* `ASS`
* `666`
* `69<any number here>`
* `<any number here>69`
* `KKK`
* `SHT`

# Rules and requirements:

* License plate **must** be randomly generated.
* Once a random license plate is generated, the same license plate cannot be generated again.
* You must output at least 200 **unique** license plates. You can generate more **if you want to**.
* You may store generated plates in a file to "remember" them.
* The license plate contains 2 sections, one containing only three letters, and one containing only three numbers, separated by a dash, like this: `233-ADF` or `ADF-233`.
* You can only use numbers and capital letters.
* License plates can be written to stdout, or a file.
* Each "side" of a license plate will contain either three numbers or letters.
* This is a , so shortest, most popular, answer wins. Winner will be chosen after seven days.

# General rules

* Answer **should** include, but not limited to, the following.
* Language name.
* Character count.
* File size.
* How the code is run.
* The code itself.
* Example: **Python 234 chars** or **Python 23mb**.

---

If I need to clarify any additional details, please mention it in the comments and I will add it to my post. Anyways, good luck, and generate me some appropriate license plates!

---

# Update 1: Winner will be chosen slightly earlier.

Turns out I have to go on a trip soon, so I will be choosing a winner around 00:00 UTC, July 25. After the winner is chosen, you can still submit entires, just know that a winner has been chosen. Bai.

---

# Update 2: Winners!

We have winners! Yay! Cheese and wine to everyone who participated! Here's who won.

* 1st place: **Àngel - Bash (95 characters)**
* 2nd place: **Martin Büttner - Mathematica (182 bytes)**
* 2nd place: **Emilio M Bumachar - Pyg (92 ?)**
* 2nd place: **Peter Taylor - Golfscript (98 characters)**
* 3rd place: **Mark Thomas - Ruby (127 characters)**

Wow, three second place ties. Wow. The competition is over, but feel free to submit entries if you want to. Bai!

---

# Answer
# bash (95 chars)

Save the script as `m` in a folder in your PATH with execute bit set.

Run as `bash m`. The plates are stored in file p

```
l(){ tr -dc $1</dev/urandom|head -c3;};egrep -ve"ASS|666|69|KKK|SHT" -fp>>p<<<`l 0-9`-`l A-Z`;m

```

This is equivalent to running the following:

```
# Print three random numbers and three random letters
echo $(tr -dc 0-9 < /dev/urandom | head -c3)-$(tr -dc A-Z < /dev/urandom | head -c3) |

# Print only plates not matching the blacklist or any line of p
# Append the plates ton p
egrep -v -e "ASS|666|69|KKK|SHT" -f p >> p

# Execute itself again
m

```

Caveat: The final `m` should actually be `exec m` (+5 chars) in order to avoid leaving processes waiting for completion (but you can have thousands without much problem)

Credit goes to http://www.cyberciti.biz/faq/linux-random-password-generator/ for the idea of using `tr -dc`
> 12 votes

# Answer
## PYG \- 92

```
Pe(Se(Re.sub(".*(666|69|ASS|KKK|SHT).*","",J(RSm(STuc*3,3)+[j]+RSm(STd*3,3)))for j in'-'*K))

```

Now able to select uniformly from all unused plates, keeping to OP's specs, while being shorter by 1 more character.

It's theoretically possible that the list of 999 plates will contain enough repetitions so that the trimmed set will be less than 200. But the odds of that are infinitesimally small. In ten trials, the lowest length I got was 994.

EDIT: changed 999 to K (which is pyg for 1000), to save two chars at the advice of bitpwner.
> 7 votes

# Answer
## Mathematica, 182 bytes

Ugh, this is long

```
l={};While[Length[l=Union@Pick[l,StringFreeQ[l,"ASS"|"666"|"69"|"KKK"|"SHT"]]]<200,AppendTo[l,RandomSample[FromCharacterCode/@{48+9~(r=RandomInteger)~3,65+25~r~3}]~Riffle~"-"<>""]];l

```

Ungolfed

```
l = {};
While[
  Length[
    l = Union@
      Pick[l, StringFreeQ[l, "ASS" | "666" | "69" | "KKK" | "SHT"]]
  ] < 200,
  AppendTo[l,
   RandomSample[
      FromCharacterCode /@ {48 + 9~(r = RandomInteger)~3,
        65 + 25~r~3}]~Riffle~"-" <> ""]
  ];
l

```

Pretty straight-forward. Generates random plates, and filters out duplicates and forbidden ones until 200 are found.
> 5 votes

# Answer
## GolfScript (98 chars)

```
260{3?}:^~,{.10^+`-3>'-'+\10^/26^+26base(;{65+}%+.-1%}%{'ASSKKKSHT66669'3/{1$\?)!},*},{,^^rand}$n*

```

This generates all possible licence plates in a random order using some ugly base conversion followed by filtering. There are a lot of them, so don't expect it to execute quickly, but the question didn't place any constraints on execution time.
> 5 votes

# Answer
## JavaScript (ES6) - 213

It can probably be improved. Tested on Firefox Console.

**Change that alert to a `console.log()` if you want to test**

```
r=x=>~~(Math.random()*x)+'';l=x=>[...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'][r(26)];a=[];while(a.length<200)p=r(10)+r(10)+r(10)+'-'+l()+l()+l(),!/ASS|666|69|KKK|SHT/.test(p)&&a.indexOf(p)<0&&a.push(p);a.forEach(x=>alert(x))

```
> 4 votes

# Answer
### Ruby — ~~136~~ ~~133~~ 129 characters

Hideous. Think there's room for improvement, though. Just drop the code in `irb` or `pry` and hit enter to run:

```
f=->*t{[0,1,2].map{t.sample}*''}
g=->l{(a=f[*?A..?Z]+?-+f[*?0..?9];l|=[a]if/69|666|ASS|SHT|KKK/!~a)until l.size>199;l}
puts g[[]]

```
> 4 votes

# Answer
## Python 2.7 - 258 chars

I'm not a professional programmer or anything, so I'd say I'm satisfied with the result.

```
import random as o
r=o.randint
t,j,k=[],0,""
b=["SHT","KKK","ASS","69","666"]
for i in range(200):
 l,j=b[0],b[4]
 while any(w in l for w in b):
  l,j="",""
  for i in range(3):
   l+=chr(r(65,90))
   j+=str(r(0,9))
 t.append(l+'-'+j)
print "\n".join(set(t))

```

Filesize is 4.0 K, run with `python file.py` !
> 4 votes

# Answer
# Ruby, 127 chars

My attempt at a "readable" Ruby version:

```
a=[]
until a.size==200 do
  p="#{rand(899)+100}-#{('A'..'Z').to_a.sample(3).join}"
  a<<p unless p=~/69|666|ASS|SHT|KKK/
end
puts a

```
> 4 votes

# Answer
# Python - 208

Hi heres my stab at license plate generation. This solution is similar to @bitpwner's solution but without the string module and instead of a list for the license plate I chose to use a set and its also allows numbers first.

```
import random as r,re
f=r.randint
l=lambda x:chr(f(65, 90))if x else`f(0,9)`
d=set()
while len(d)<200:
 k=f(0,1);j=1-k;c=l(k)+l(k)+l(k)+'-'+l(j)+l(j)+l(j)
 if not(re.search("666|69|ASS|KKK|SHT",c)):d.add(c)

```

Sample output:

```
set(['DQJ-641', '086-QRY', '981-GAZ', 'UHN-718', '114-VMI', 'GLO-887',  ...

```
> 3 votes

# Answer
# Python, 252 bytes

Here's my contribution. I'm impressed with it, but I know others have done better with python.

```
from random import randint as r
f=()
while len(f)<200:
 t=str(r(0,999))
 if not("666" in t or "69" in t):
  u=''.join(chr(r(65,90)) for _ in [1,2,3])
  if not("KKK" in u or "SHT" in u or "ASS" in u):f+=("%s-%s"%(t.zfill(3),u),)
 f=tuple(set(f))
print f

```
> 3 votes

# Answer
# Python - 165

Those imports...

```
import random as r,re
j="666|69|ASS|KKK|SHT"
t=r.randint
while len(j)<2e3:
 exec"x="+"chr(t(0,25)+65)+"*3+"'-'"+"+`t(0,9)`"*3
 if not re.search(j,x):print x;j+='|'+x

```

If there is a need to begin randomly with either numbers or alphabets, which I don't think is really needed, then 190.

```
import random as r,re
j="666|69|ASS|KKK|SHT"
t=r.randint
while len(j)<2e3:
 exec"x="+"chr(t(0,25)+65)+"*3+"'-'"+"+`t(0,9)`"*3
 x=x[::r.choice((-1,1))]
 if not re.search(j,x):print x;j+='|'+x

```
> 2 votes

# Answer
## PHP 341 324 320

Was the best I could do.

```
<?$a="p";$b=fopen($a,'a+');while($c<200){$d=rand(100,999);$e='';for($f=0;$f<3;++$f)$e.=chr(rand(65,90));$g=(rand(1,2)==1)?"$d-$e":"$e-$d";$h=array('ASS','666','69','kkk','SHT');$i=1;foreach($h as $j)!preg_match("/$j/",$g)?:++$i;if($i==1){$k=fread($b,filesize($a));if(!strpos($k,$g)){fwrite($b,$g);echo"$g<br />";++$c;}}}

```

To run the code just save as a .php file and browse to it on any web server. It will attempt to create the blacklist file p.txt if it does not exist already. However you may need to define it with a full server path if you do not have root access.

The code itself is here pre golfification:

```
<?
// create random plate
// check it does not break rules
// check is not on all time blacklist file
// Add to blacklist file
// Output to screen

// open file handle
$file = "p"; // filename and path if not root access
$fh = fopen($file, 'a+');

// do 200
while($x<200) {

    // get random number
    $rand_number = rand(100,999);

    // get random letters
    $letters = '';
    for($y=0; $y<3; ++$y) $letters .= chr(rand(65,90));

    // mix up combination
    $string = (rand(1,2)==1) ? "$rand_number-$letters" : "$letters-$rand_number";

    // assume is ok
    $ok = 1;

    // Set checks to be excluded on new plates.
    $checks = array('ASS','666','69','kkk','SHT');

    // do the exclusions
    foreach ($checks as $check) !preg_match("/$check/", $string) ? : ++$ok;

    // if all ok, check is not on the blacklist
    if($ok == 1) {

        // read blacklist
        $blacklist = fread($fh, filesize($file));

        // if not on blacklist, add it to file, echo it to output, increment counter
        if (!strpos($blacklist, $string)) {
            fwrite($fh, $string);
            echo "$string<br />";
            ++$x;
        }
    }
}

```

Was as short as I could get it :-(

Sample Output

```
XWU-888
PUD-534
355-QXG
WDE-402
113-QID
362-YBW
TBK-594
939-XDT
148-ARZ
838-ICY
723-ZDA
.... does exactly 200 new plates.

```

EDIT: tidied up a couple of if statements to use short form.
> 2 votes

# Answer
# Cobra - 198

```
class P
    def main
        l,r=[],Random()
        while l.count<200
            a,b=r.next(1000),''
            for i in 3,b+='[r.next(65,91)to char]'
            if not ('69'in'[a]'or 666==a or b in'ASS KKK SHT'),l+=['[a]-'+b]
        print l

```
> 1 votes

# Answer
## Delphi, 161 bytes

Here is my take on this. It outputs license plates to stdout without line feed between them. If LF is needed (not specified in the rules), than that adds extra 4 bytes.

Golfed version:

```
var S,L:string;begin repeat Str(100+Random(69),S);S:=S+'-';while Length(S)<7do S:=S+Chr(65+Random(10));if Pos(S,L)=0then L:=L+S;until Length(L)>1393;Write(L)end.

```

Ungolfed:

```
var
  S, L: string;
begin
  repeat
    Str(100 + Random(69), S); // generate and add first three numbers
    S := S + '-'; // add dash
    while Length(S) < 7 do // generate and add last three letters
      S := S + Chr(65 + Random(10));
    if Pos(S, L) = 0 then // check if its not in the L string and add it
      L := L + S;
  until Length(L) > 1393; // exit loop once L string has more than 1393 chars (199 * 7 = 1393)
  Write(L); // output L to stdout
end.

```

How to run:

```
app.exe > plates.txt

```
> 1 votes

# Answer
## Python3, 257 chars

```
import string as X,re,random as R
I=[0,1,2]
s={}
while len(s)<200:
 L=R.sample([[R.choice(X.digits) for i in I],[R.choice(X.ascii_uppercase) for i in I]],2);L=''.join(L[0]+['-']+L[1])
 if re.search('ASS|KKK|SHT|69|666',L) or L in s:continue
 print(L);s[L]=0

```

Sample output:

```
# python3 shortened.py
EUN-215
546-SIL
464-ZTR
XIX-794

```
> 1 votes

# Answer
## PHP, 267

This is about as short as I can get it.

```
<?php $g=file("p",2)?:[];$b=["ASS","666","KKK","SHT"];for($i=0;$i<200;){$m="A";$n=rand(702,18277);for($j=0;$j<$n;$j++){$m++;}$m.=-rand(100,999);if(!(strpos($m,"69")|in_array($m,$b)|in_array($m,$g))){$g[]=$m;echo"$m\n";$i++;}}file_put_contents("p",implode("\n",$g));?>

```

Plates are stored in file "p".

```
<?php
$g=file("p",2)?:[]; // Read existing plates
$b=["ASS","666","KKK","SHT"]; // Don't generate these
for($i=0;$i<200;){ // 200 plates
    $m="A"; // Base letter
    $n=rand(702,18277); // 3 random letters
    for($j=0;$j<$n;$j++){$m++;} // Increment until letters are reached (SLOW, but short)
    $m.=-rand(100,999); // Add a dash and three numbers
    if(!(strpos($m,"69")|in_array($m,$b)|in_array($m,$g))){ // Check that it's valid and unused
        $g[]=$m;echo"$m\n";$i++; // Echo it, add it to used array and increment counter
    }
}
file_put_contents("p",implode("\n",$g)); // Save the plates
?>

```
> 1 votes

# Answer
## R, 229 characters

I'm sure this could be improved:

```
l=function(x)paste0(sample(x,3,r=T),collapse="")
a=function()c(l(LETTERS),l(0:9))
A=list()
for(i in 1:200)while(any(sapply(c("ASS","666","69","KKK","SHT"),grepl,A[[i]]<-a()))|A[i]%in%A[-i])A[[i]]=a()
lapply(A,paste,collapse="-")

```

Run in the console, prints a list of license plates.
> 1 votes

# Answer
# ECMAScript 6 - ~~155~~ ~~168~~ 158

**Warning**: 200 alert dialogs (change `alert` to `console.log` to test)

```
for(i=0,s={},r=Math.random,l=x=>String.fromCharCode(65+r()*26);i<200;)/ASS|666|69|KKK|SHT/.test(p=(r()+'-'+l()+l()+l()).slice(-7))?0:s[p]=s[p]||(alert(p),i++)

```

**Edit**: Oops. Original version printed duplicates...

**Edit 2**: Closer to the original score now - switched from a set to an associative array with some fugly duplicate checks allowing it to print as it goes

Tested in Firefox console.
> 1 votes

# Answer
# Javascript - 283 327 Characters

# Edit:

After implementing the suggestions from **Alconja**, here's my new version:

```
m=Math.random;function y(v){return "ASS|KKK|SHT|666".indexOf(v)<0&&v.indexOf("69")<0?0:!0}function c(){return String.fromCharCode(m()*26+65)}for(i=0;i<200;i++){do {do {n=(m()+"").slice(2,5)}while(y(n));do {l=c()+c()+c()}while(y(l));r=l+"-"+n}while(o.indexOf(r)>=0);o+=r+"\n"}alert(o)
/* 1 line - 283 Characters */

```

1) Remove Variable:s and use literal:"\n" \[-4\]\[323\]
2) Remove "var o="",i,r,n,l," \[-17\]\[306\]
3) Remove Variable:t and use literal:"ASS|KKK|SHT|666" \[-4\]\[302\]
4) Set m=Math.random and use "m" instead \[-7\]\[296\]
5) Use (m()+"") rather than m().toString() \[-6\]\[290\]
6) Remove unneeded ";" \[-7\]\[283\]

---

# Old-version: Javascript - 327 Characters

I'm sure there's some room for improving... I'm pretty inexperienced at Code-golfing:

```
var o="",s="\n",i,r,n,l,t="ASS|KKK|SHT|666";function y(v){return t.indexOf(v)<0&&v.indexOf("69")<0?0:!0;}function c(){return String.fromCharCode(Math.random()*26+65);}for(i=0;i<200;i++){do {do {n=Math.random().toString().slice(2,5);}while(y(n));do {l=c()+c()+c();}while(y(l));r=l+"-"+n;}while(o.indexOf(r)>=0);o+=r+s;}alert(o);
/* 1 line - 327 Characters */

```

Here is a formatted, "Ungolfed" version with "un-minified" variable/function names:

```
var outp="",lsep="\n",ndx,res,nbr,ltr,tbl="ASS|KKK|SHT|666";
function fnvfy(vinp){
  return tbl.indexOf(vinp)<0&&vinp.indexOf("69")<0?0:!0;
}
function fnchr(){
  return String.fromCharCode(Math.random()*26+65);
}
for(ndx=0;ndx<200;ndx++){
  do {
    do {
      nbr=Math.random().toString().slice(2,5);
    }
    while(fnvfy(nbr));
    do {
      ltr=fnchr()+fnchr()+fnchr();
    }
    while(fnvfy(ltr));
    res=ltr+"-"+nbr;
  }
  while(outp.indexOf(res)>=0);
  outp+=res+lsep;
}
alert(outp);

```

---

Here is a "debug" version that can be pasted into URL of browser favorite/bookmark. Output is placed in a "TEXTAREA" on a new "window" instead of "alert()":
```
javascript:(function(){var outp="",lsep="\n",ndx,res,nbr,ltr,tbl="ASS|KKK|SHT|666";function fnvfy(vinp){return tbl.indexOf(vinp)<0&&vinp.indexOf("69")<0?0:!0;}function fnchr(){return String.fromCharCode(Math.random()*26+65);}for(ndx=0;ndx<200;ndx++){do {do {nbr=Math.random().toString().slice(2,5);}while(fnvfy(nbr));do {ltr=fnchr()+fnchr()+fnchr();}while(fnvfy(ltr));res=ltr+"-"+nbr;}while(outp.indexOf(res)>=0);outp+=res+lsep;}var x=window.open();x.document.write('<head>\n</head>\n<body>\n<form name=sa><textarea name=t rows=25 cols=80 wrap>'+outp+'</textarea><br />\n</body>\n');x.document.close();})()
/* */

```

Here is the "debug" version, formatted:

```
javascript:
(function(){
  var outp="",lsep="\n",ndx,res,nbr,ltr,tbl="ASS|KKK|SHT|666";
  function fnvfy(vinp){
    return tbl.indexOf(vinp)<0&&vinp.indexOf("69")<0?0:!0;
  }
  function fnchr(){
    return String.fromCharCode(Math.random()*26+65);
  }
  for(ndx=0;ndx<200;ndx++){
    do {
      do {
        nbr=Math.random().toString().slice(2,5);
      }
      while(fnvfy(nbr));
      do {
        ltr=fnchr()+fnchr()+fnchr();
      }
      while(fnvfy(ltr));
      res=ltr+"-"+nbr;
    }
    while(outp.indexOf(res)>=0);
    outp+=res+lsep;
  }
  var x=window.open();
  x.document.write('<head>\n</head>\n<body>\n<form name=sa><textarea name=t rows=25 cols=80 wrap>'+outp+'</textarea><br />\n</body>\n');
  x.document.close();
}
)()

```
> 1 votes

# Answer
# JavaScript (ES6) 184

As usual, test in FireFox console and change `alert` to `console.log` or be prepared to press `escape` 200 times.

```
R=x=>Math.random()*++x|0
for(l='ABCDEFGHIKJLMNOPQRSTUVWXYZ',i=0,u={};i<200;)
!(/69|666|ASS|SHT|KKK/.test(k=l[R(25)]+l[R(25)]+l[R(25)]+'-'+R(9)+R(9)+R(9))&u[k])&&alert(k,u[k]=++i);

```
> 1 votes

# Answer
# PHP,167

```
while(count($a)<200){$c="";for(;++$y&3;)$c.=chr(rand(65,90));$d=rand(100,999);$c=rand()&1?"$d-$c":"$c-$d";preg_match("/ASS|666|69|KKK|SHT/",$c)||$a[$c]=1;}print_r($a);

```

that's 100 chars less than current PHP's best :)

```
while(count($a)<200)
{
    $c="";
    for(;++$y&3;) $c.=chr(rand(65,90));
    $d=rand(100,999);
    $c=rand()&1?"$d-$c":"$c-$d";
    preg_match("/ASS|666|69|KKK|SHT/",$c)||$a[$c]=1;
}
print_r($a);

```

hope you like it. In case it is allowed:

```
while(count($a)<200){$c="";for(;++$y&3;)$c.=chr(rand(65,90));$c.=-rand(100,999);preg_match("/ASS|666|69|KKK|SHT/",$c)||$a[$c]=1;}print_r($a);

```

is only 141 chars but doesn't shuffle chars and numbers. Any suggestions wellcome :)
> 1 votes

# Answer
# F#, 264 chars

Not really a language designed for golfing, but I'm sure this could be improved. Using Seq.exists with a lambda is pretty annoying, as are the many parens and lack of implicit conversion.

Uses recursion, keeps going forever.

```
let g=System.Random()
let c()=char(g.Next(65,90))
let k(i:string)l=Seq.exists(fun e->i.Contains(e))l
let rec p d:unit=
 let l=sprintf"%i-%c%c%c"(g.Next(100,999))(c())(c())(c())
 if k l d||k l ["ASS";"666";"69";"KKK";"SHT"]then p d else
  printfn"%s"l
  p(l::d)
p[]

```

Can be run in FSI.
> 1 votes

# Answer
## Python 203

I'm not sure if this technically counts, but I liked it so I'm posting it anyway. While I do generate the answers pseudo-randomly, as pretty much everyone else did, I strategically picked the random seed such that invalid answers wouldn't end up in the output. So, my answer isn't actually capable of generating the entire set of valid answers, without also generating the invalid ones.

```
from random import*;seed(1);L='ABCDEFGHIJKLMNOPQRSTUVWXYZ';D='0123456789';C=choice
for i in 'x'*200:s=randint(0,1);a=''.join(C(L)for _ in'000');b=''.join(C(D)for _ in'000');i=[a,b];print i[s-1]+'-'+i[s]

```
> 1 votes

# Answer
## Perl - 123 Characters

```
while(@p<200){$l=(AAA..ZZZ)[int rand 999]."-".(100+int rand 899);@p=grep!/ASS|666|69|KKK|SHT|$l/,@p;push@p,$l}$,=$/;print@p

```

Ungolfed:

```
while(@p < 200){ # Repeat until we get 200 plates
    $l = (AAA..ZZZ)[int rand 999]."-".(100+int rand 899); # generate the license plate
    @p = grep !/ASS|666|69|KKK|SHT|$l/, @p; # remove disallowed license ones and duplicates
    push @p, $l # add a license plate
}
$,=$/; # so they print with newlines
print @p # print the plates

```

If anyone has ideas to golf it further, let me know, I am interested. If you want further explanation of part of the code, leave a comment and I'd be happy to explain more too.
> 1 votes

---
Tags: code-golf, popularity-contest, generation
---