title: The Gray area of n-ary codes

text:
# Question
Title: The Gray area of n-ary codes
Write a program or function that takes a base `n` and a number `x`, and returns or outputs the `n`-ary Gray code of `x`.

## Rules

* `n` is an integer in the range `2 <= n <= 16`.
* `x` is an integer in the range `0 <= n < 2**32`.
* The inputted numbers can either be two integer arguments if you write a function, or two arguments to `ARGV` or a space separated pair to `STDIN` if you write a program.
* The output should be a string, either returned or printed to `STDOUT`.
* If `n` is 10 or more, use hex digits to represent digits with a value greater than 9. The case of the digits does not matter.
* If the `n`-ary Gray code of `x` is zero, `'0'` must be printed or returned.
* Code length is in bytes, and standard loopholes are not permitted.
* You do not need to use the same algorithm as below, but if you use a different one, make sure it produces valid Gray codes.

## Example

Example code adapted from Wikipedia:

```
>>> import string
>>>
>>> def nary_gray_code(base, num):
...     base_num = []
...     # Convert to num to base base
...     while num:
...         base_num.append(num % base)
...         num = num // base
...     # Convert base base number to base-ary Gray code
...     shift = 0
...     gray = []
...     for b in reversed(base_num):
...         gray.insert(0, (b + shift) % base)
...         shift += base - gray[0]
...     return "".join(string.hexdigits[i] for i in reversed(gray)) or "0"
...
>>> nary_gray_code(2, 100)
'1010110'
>>> nary_gray_code(2, 1)
'1'
>>> nary_gray_code(2, 0)
'0'
>>> nary_gray_code(10, 23)
'21'
>>> nary_gray_code(10, 100)
'190'
>>> nary_gray_code(3, 26)
'200'
>>> nary_gray_code(3, 27)
'1200'
>>> for i in range(2, 17):
...     print(i, nary_gray_code(i, 2**32 - 1))
...
2 10000000000000000000000000000000
3 122102120011102000122
4 3000000000000000
5 34020102231331
6 1401154214013
7 260241350125
8 34000000000
9 11762782617
10 4875571576
11 1824007509
12 92b627446
13 5b25a2c00
14 2ac96ab2b
15 197dde1a7
16 f0000000
>>>

```

# Answer
# Pyth, 20 bytes

```
Msme.H%dGu+G-HsGjHGY

```

This defines a function `g` which takes two integers as parameters. Take a look at this online demonstration: Pyth Compiler/Executor.

## Explanation:

```
Msme.H%dGu+G-HsGjHGY
M                     def g(G, H): return _
                jHG      convert H to base G
         u      jHGY     reduce(lambda G, H: _, jHG, [])
          +G-HsG            G + [H - sum(G)]
  m                      map each number d to:
   e.H%dG                   hex-representation(d % G)[-1]
 s                       sum (join all digits)

```

This code is a little bit confusing. There are 4 function parameters in this code: two of them are called `G` and two of them are called `H`. The `G` in `+G-HsG` is different from the `G` in `jHG` or `%dG`.
> 2 votes

---
Tags: code-golf, conversion, coding-theory
---


title: King of the Hill: Robot Battle

text:
# Question
Title: King of the Hill: Robot Battle
Your task here is to write an AI for a simple robot battle. The class to be implemented is provided at the bottom of this post, and source of the controller can be found here.

# Requirements

1. Write a class which implements the abstract Bot class, provided at the bottom of this post
2. You must provide a 0-argument constructor, this must change the value of the Name field, but may not change any other inherited fields
3. Outside of the constructor, you may not change any of the inherited fields in any way
4. Your action method should, when called (it will be called once per turn cycle, with a copy of the 64 by 64 map as its argument), return one of the Action enum fields:

```
UP  to move up (towards y=0)
DOWN to move down
LEFT to move left (towards x=0)
RIGHT to move right
MINE to plant a mine and then move a random direction
PASS to pass

```
5. Within the passed map, 0 represents an empty cell, -1 represents a mined cell, and anything else denotes a cell occupied by a bot (each bot will be represented by its unique bot\_id, you can get your bot's id by calling this.id())
6. A bot is eliminated in any of the following situations:

* It moves out of the map
* It moves into a cell occupied by a mine
* Another bot moves into the cell it currently occupies
* Its action method takes more than 50ms to respond
* Its action method throws any exception that is not caught within its own bounds

# To win

Have your bot be the last bot standing!

# Additional Rules

The round is not allowed to last more than 1,000 turn cycles. If, after the 1,000th turn cycle, more than one bot is still standing, all of the surviving bots are considered to have tied that round.

Each time a new bot is submitted, it will, as soon as possible, be pitted in two two-bot, three three-bot, and three-four bot rounds; each time against randomly selected opponents.

# Scoring

total score=1000\*(wins+(1/3) ties - (1/12) losses)/roundsPlayed

The exceptions to this are that any bot that has played at least one round that it didn't lose is guaranteed at least one point, and no bot may have a negative score.

# The class to be implemented:

```
import java.util.*;

public abstract class Bot {
    public static enum Action{
        UP,DOWN,LEFT,RIGHT,MINE,PASS;
    }
    public static final class Position{
        public int x;
        public int y;
        public String toString(){
            return "("+x+","+y+")";
        }
        public double distance(Position p){
            int dx=p.x-this.x;
            int dy=p.y-this.y;
            return Math.sqrt(dx*dx+dy*dy);
        }
        public Position(int x,int y){
            this.x=x;
            this.y=y;
        }
    }
    public String toString(){return name;}
    public Position p;
    public String name="";
    public abstract Action action(int[][] map);
    private int bot_id;
    public final int id(){return bot_id;}
    public final void register(List<Bot> a){
        a.add(this);
        bot_id=a.size();
    }
}

```

# Leaderboard

*The full match log may be read here*

```
ProtectiveBot (6 wins, 6 ties, 1 loss)- 609 points
Albert (2 wins, 8 ties, 0 losses)- 467 points
Frozen (1 win, 8 ties, 0 losses)- 407 points
Cocoon (1 win, 3 ties, 3 losses)-250 points
Wanderlust (0 wins, 3 ties, 5 losses)- 73 points
MineThenBoom (0 wins, 2 ties, 11 losses)- 1 point
PatientBot (0 wins, 0 ties, 13 losses)- 0 points

```

# Sample Bots

Simple Pathfinder: http://pastebin.com/raw.php?i=aNBf00VU

RandomBot: http://pastebin.com/raw.php?i=VD8iGaHC

Minelayer: http://pastebin.com/raw.php?i=sMN1zSa0

# Answer
> 3 votes
# ProtectiveBot

A bunch of ideas rolled together to form something. There are a number of states that it can enter. Firstly, if there is no-one around them, it will build itself a cocoon which is just about indestructible, and sit in it for a while, killing anyone it can.

If there is someone close during startup, there is less then 200 turns left, or there is only one enemy bot remaining, the bot will enter a aggressive mode, which is essentially an enhanced pathfinder, attempting to trick its opponents. This mode uses a flood style pathfinding system at close range, and the same technique in the provided pathfinding example at long range.

If there are multiple instances of this bot in game, the bots will refrain from killing each other until the end.

Its big as well, weighing in at ~~527~~ 741 lines. Compiling against Java 8. Also, have a graphic renderer of the battle system: https://github.com/j-selby/RobotBattleController

> I've reached the limit for how big these posts can be, see bot src at https://github.com/j-selby/RobotBattleController/blob/master/src/main/java/ProtectiveBot.java. Sorry...

Rev 3:

* Threaded pathfinding. No more timeouts!
* Detection of stalemates. TODO: Do something about them.
* Full A\* pathfinding. No more dumb stuff.
* Checks OTHER bots positions for unfair play (trapping themselves in completely).

Rev 2:

* Stopped bot being killed at corners
* Smarter building logic
* Will never do any move that could endanger us, excluding against other instances of ProtectiveBot.

# Answer
> 3 votes
# Frozen

After analyzing how the controller worked, I determined the only way to lose is to move. Therefore, this robot stays in place unless absolutely necessary.

```
public class Frozen extends Bot{
        public Frozen(){
            this.name="Frozen";
        }
        public Action action(int[][] map) {
            if (p.x > 0 && map[p.x-1][p.y] > 0) return Action.LEFT;
            if (p.x < map.length-1 && map[p.x+1][p.y] > 0) return Action.RIGHT;
            if (p.y > 0 && map[p.x][p.y-1] > 0) return Action.UP;
            if (p.y < map.length-1 && map[p.x][p.y+1] > 0) return Action.DOWN;
            return Action.PASS;
        }
}

```

# Answer
> 2 votes
# Wanderlust

I join the competetion with a bot called Wanderlust! Its algorithm is actually pretty straightforward. While it's trying to avoid mines and not running off the map, it's randomly spraying mines around. If an enemy bot would come closer, though, it scurries off in the opposite direction.

Wanderlust's a decent bot, but just doesn't cut it when there are A\* algorithm bots on the field. You can see it running away while the enemy bot is figuring out how to get closer, but eventually it dies. (Unless those bots get trapped of course, which then simply results in a tie.)

```
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Wanderlust extends Bot {

private static final double NEAR_ENEMY_RUN_DISTANCE = 12;
private static final double NEAR_ENEMY_PASS_DISTANCE = 2.5;
private static final int SAFE_NUMBER_OF_MINES = 0;
private Random random;

public Wanderlust() {
    this.name = "Wanderlust";
    this.random = new Random(System.currentTimeMillis());
}

@Override
public Action action(int[][] map) {

    List<Action> actions = new ArrayList<Action>();
    List<Position> enemyPositions = mapEnemyPositions(map);
    Position nearestBotPosition = getNearestBotPosition(enemyPositions);
    Action action = Action.PASS;

    if (nearestBotPosition != null && nearestBotPosition.distance(this.p) < NEAR_ENEMY_RUN_DISTANCE) {
        // Run! Can't risk to drop a mine because of the random movement afterwards.
        // So check where the enemy is and run the opposite way!
        // This is all good unless the enemy is reaaaally close. In that case, we're just struck with fear and stand still.

        if (nearestBotPosition.distance(this.p) < NEAR_ENEMY_PASS_DISTANCE) {
            return Action.PASS;
        }

        int dx = this.p.x - nearestBotPosition.x;
        int dy = this.p.y - nearestBotPosition.y;

        Action horizontalAction = dx < 0 ? Action.LEFT : Action.RIGHT;
        Action verticalAction = dy < 0 ? Action.UP : Action.DOWN;

        // Is the enemy closer to me on the x-axis, or the y-axis?
        if (Math.abs(dx) < Math.abs(dy)) {
            // OK, which way do we run away from the enemy? Left or right?
            // And if we can't run left or right, we should think about a back-up plan: moving vertically.
            Action primaryAction = dx < 0 ? Action.LEFT : Action.RIGHT;
            actions.add(primaryAction);
            actions.add(verticalAction);
            action = getValidMove(actions, true, map);
        } else {
            // OK, which way do we run away from the enemy? Up or down?
            // And if we can't run up or down, we should think about a back-up plan: moving horizontally.
            Action primaryAction = dy < 0 ? Action.UP : Action.DOWN;
            actions.add(primaryAction);
            actions.add(horizontalAction);
            action = getValidMove(actions, true, map);
        }
    } else {
        // Just casual strolling. Hey, perhaps dropping a mine? #casualThings
        actions.add(Action.LEFT);
        actions.add(Action.RIGHT);
        actions.add(Action.UP);
        actions.add(Action.DOWN);
        actions.add(Action.MINE);

        if (this.p.x == 0 || this.p.x == 63 || this.p.y == 0 || this.p.y == 63 || getNumberOfMinesAroundPosition(this.p, map) > SAFE_NUMBER_OF_MINES) {
            actions.remove(Action.MINE);
        }

        action = getValidMove(actions, false, map);
    }

    return action;
}

private Action getValidMove(List<Action> actions, boolean preserveOrder, int[][] map) {

    List<Action> validMoves = new ArrayList<Action>();

    for (Action action : actions) {
        if (action == Action.LEFT && this.p.x > 0 && map[this.p.x-1][this.p.y] >= 0) {
            validMoves.add(Action.LEFT);
        }

        if (action == Action.RIGHT && this.p.x < 63 && map[this.p.x+1][this.p.y] >= 0) {
            validMoves.add(Action.RIGHT);
        }

        if (action == Action.UP && this.p.y > 0 && map[this.p.x][this.p.y-1] >= 0) {
            validMoves.add(Action.UP);
        }

        if (action == Action.DOWN && this.p.y < 63 && map[this.p.x][this.p.y+1] >= 0) {
            validMoves.add(Action.DOWN);
        }

        if (action == Action.MINE) {
            validMoves.add(Action.MINE);
        }
    }

    if (validMoves.isEmpty()) {
        return Action.PASS;
    }

    return preserveOrder ? validMoves.get(0) : validMoves.get(random.nextInt(validMoves.size()));
}

private int getNumberOfMinesAroundPosition(Position position, int[][] map) {
    int count = 0;

    if (position.x > 0 && map[position.x-1][position.y] == -1) {
        count++;
    }

    if (position.x < 63 && map[position.x+1][position.y] == -1) {
        count++;
    }

    if (position.y > 0 && map[position.x][position.y-1] == -1) {
        count++;
    }

    if (position.y < 63 && map[position.x][position.y+1] == -1) {
        count++;
    }

    return count;
}

private Position getNearestBotPosition(List<Position> enemyPositions) {
    Position botPosition = null;
    double distance = Double.MAX_VALUE;

    for (Position position : enemyPositions) {
        double botDistance = position.distance(this.p);
        if (botDistance <= distance) {
            distance = botDistance;
            botPosition = position;
        }
    }

    return botPosition;
}

private List<Position> mapEnemyPositions(int[][] map) {

    List<Position> enemyPositions = new ArrayList<Position>();

    for (int yy = 0; yy < 63; yy++) {
        for (int xx = 0; xx < 63; xx++) {
            if (map[xx][yy] > 0 && map[xx][yy] != id()) {
                enemyPositions.add(new Position(xx, yy));
            }
        }
    }

    return enemyPositions;
}
}

```

# Answer
> 0 votes
# MineThenBoom

A modified version of the pathfinder.
His priorities are crush, mine, leave, sit. Yeah, the guy's a little crazy.
Updates to this bot may be given as I find new strategies. Please notify me if something goes wrong.

```
import java.util.*;

public class MineThenBoom extends Bot{
    public MineThenBoom() {
        this.name="MineThenBoom";
    }
    public Action action(int[][] map) {
        List<Position> enemies=new ArrayList<Position>();
        for(int x=1;x<map.length;x++){
            for(int y=1;y<map[x].length;y++){
                if(map[x][y]!=0&&map[x][y]!=this.id()&&map[x][y]!=-1){
                    enemies.add(new Position(x,y));
                }
            }
        }
        double d=200;
        Position x=null;
        for(Position pos:enemies){
            if(p.distance(pos)<d){
                x=pos;
                d=p.distance(pos);
            }
        }
    // initialize checking for walls
    boolean can_move_left = p.x != 0;
    boolean can_move_right = p.x != 63;
    boolean can_move_up = p.y != 0;
    boolean can_move_down = p.y != 63;
    // Check if there's anyone nearby to crush, if it won't put us in danger.
        if(x.x<p.x&&map[p.x-1][p.y]!=-1&&x.x<p.x&&map[p.x-1][p.y]!=0) {
       boolean no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x-1][p.y+1] < 1;
       if(no_one_around)return Action.LEFT;
    }
        if(x.x>p.x&&map[p.x+1][p.y]!=-1&&x.x<p.x&&map[p.x-1][p.y]!=0) {
       boolean no_one_around = map[p.x+1][p.y-1] < 1 && map[p.x+1][p.y+1] < 1;
       if(no_one_around)return Action.RIGHT;
    }
        if(x.y>p.y&&map[p.x][p.y+1]!=-1&&x.x<p.x&&map[p.x-1][p.y]!=0) {
       boolean no_one_around = map[p.x-1][p.y+1] < 1 && map[p.x+1][p.y+1] < 1;
       if(no_one_around)return Action.DOWN;
    }
        if(x.y<p.y&&map[p.x][p.y-1]!=-1&&x.x<p.x&&map[p.x-1][p.y]!=0) {
       boolean no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x+1][p.y-1] < 1;
       if(no_one_around)return Action.UP;
    }
    // If we've come this far, it means no one is crushable. Lay a mine, but only if we're ABSOLUTELY safe.
    boolean no_one_around = map[p.x+1][p.y-1] < 1 && map[p.x+1][p.y+1] < 1 && map[p.x-1][p.y-1] < 1 && map[p.x-1][p.y+1] < 1;
    boolean not_walking_into_mine = map[p.x+1][p.y] == 0 && map[p.x-1][p.y] == 0 && map[p.x][p.y-1] == 0 && map[p.x][p.y+1] == 0;
    boolean not_walking_near_danger = map[p.x+2][p.y] < 1 && map[p.x-2][p.y] < 1 && map[p.x][p.y+2] < 1 && map[p.x][p.y-2] < 1;
    if(no_one_around && not_walking_into_mine && not_walking_near_danger)return Action.MINE;
    // OK, let's take a little walk.
        if(x.x<p.x&&map[p.x-1][p.y]!=-1) {
       boolean no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x-1][p.y+1] < 1;
       if(no_one_around)return Action.LEFT;
    }
        if(x.x>p.x&&map[p.x+1][p.y]!=-1) {
       boolean no_one_around = map[p.x+1][p.y-1] < 1 && map[p.x+1][p.y+1] < 1;
       if(no_one_around)return Action.RIGHT;
    }
        if(x.y>p.y&&map[p.x][p.y+1]!=-1) {
       boolean no_one_around = map[p.x-1][p.y+1] < 1 && map[p.x+1][p.y+1] < 1;
       if(no_one_around)return Action.DOWN;
    }
        if(x.y<p.y&&map[p.x][p.y-1]!=-1) {
       boolean no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x+1][p.y-1] < 1;
       if(no_one_around)return Action.UP;
    }
    // We clearly are pinned down by some number of players on one or more edges. Let's make our way out of here!
    no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x-1][p.y+1] < 1 && map[p.x-2][p.y] < 1 && map[p.x-1][p.y] == 0 && x.x<p.x;
    if(no_one_around)return Action.LEFT;
    no_one_around = map[p.x+1][p.y-1] < 1 && map[p.x+1][p.y+1] < 1 && map[p.x+2][p.y] < 1 && map[p.x+1][p.y] == 0 && x.x>p.x;
    if(no_one_around)return Action.RIGHT;
    no_one_around = map[p.x-1][p.y-1] < 1 && map[p.x+1][p.y-1] < 1 && map[p.x][p.y-2] < 1 && map[p.x][p.y-1] == 0 && x.y<p.y;
    if(no_one_around)return Action.DOWN;
    no_one_around = map[p.x-1][p.y+1] < 1 && map[p.x+1][p.y+1] < 1 && map[p.x][p.y+2] < 1 && map[p.x][p.y+1] == 0 && x.y>p.y;
    if(no_one_around)return Action.UP;
    // Well then. We can't crush, lay a mine, or escape.
    // We are most likely near a player who, if they move, will either no longer be a threat or we can crush.
    // If we are somehow surrounded by mines, we're safe anyways.
    return Action.PASS;

    }
}

```

**CHANGES**

* Fixed bot so it wouldn't always lay mines, and won't be crushed too easily.
* Fixed severe logic flaws in bot, as well as minor tune-ups.
* Once again, rewrote all the logic.
* v1.0: Added code to try to move around a little, see if we can force other bots like us to move.

Thanks to SuperJedi224 for helping me with my code.

# Answer
> 0 votes
# PatientBot

Super simple bot that puts down a defensive wall and then just waits. (I will probably write a more serious solution later, but this will do for now.)

```
public class PatientBot extends Bot{
    public PatientBot(){
        name="PatientBot";
    }
    int turn = 0;
    public Action action(int[][] map){
        switch(turn++){
        case 0: return Action.UP;
        case 1: return Action.MINE;
        case 2: return Action.LEFT;
        case 3: return Action.DOWN;
        case 4: return Action.MINE;
        case 5: return Action.DOWN;
        case 6: return Action.RIGHT;
        case 7: return Action.MINE;
        case 8: return Action.RIGHT;
        case 9: return Action.UP;
        case 10: return Action.MINE;
        default: return Action.PASS;
        }
    }
}

```

# Answer
> 0 votes
Well, here's another Simple Pathfinder variant I wrote, and I decided... why not enter it this time?

# Albert

```
import java.util.*;

public class Albert extends Bot{
    private Random r=new Random();
    public Albert(){
        this.name="Albert";
    }
    private int countMines(int[][] map,Position p){
        int mines=0;
        if(p.y==63||map[p.x][p.y+1]==-1)mines++;
        if(p.y==0||map[p.x][p.y-1]==-1)mines++;
        if(p.x==0||map[p.x-1][p.y]==-1)mines++;
        if(p.x==63||map[p.x+1][p.y]==-1)mines++;
        return mines;
    }
    @Override
    public Action action(int[][] map) {
        List<Position> enemies=new ArrayList<Position>();
        for(int x=1;x<map.length;x++){
            for(int y=1;y<map[x].length;y++){
                if(map[x][y]!=0&&map[x][y]!=this.id()&&map[x][y]!=-1){
                    enemies.add(new Position(x,y));
                }
            }
        }
        double d=200;
        Position x=null;
        for(Position pos:enemies){
            if(p.distance(pos)<d){
                x=pos;
                d=p.distance(pos);
            }
        }
        if(countMines(map,p)==0&&r.nextDouble()<0.5&&d>2.01)return Action.MINE;
        if(d>1.03&&d<3)return Action.PASS;
        if(x==null)return Action.PASS;
        if(x.x<p.x&&map[p.x-1][p.y]!=-1&&countMines(map,new Position(p.x-1,p.y))<2&&r.nextDouble()<0.8)return Action.LEFT;
        if(x.x>p.x&&map[p.x+1][p.y]!=-1&&countMines(map,new Position(p.x+1,p.y))<2&&r.nextDouble()<0.8)return Action.RIGHT;
        if(x.y>p.y&&map[p.x][p.y+1]!=-1&&countMines(map,new Position(p.x,p.y+1))<2&&r.nextDouble()<0.8)return Action.DOWN;
        if(x.y<p.y&&map[p.x][p.y-1]!=-1&&countMines(map,new Position(p.x,p.y-1))<2&&r.nextDouble()<0.8)return Action.UP;
        List<Action> v=new ArrayList<Action>();
        if(p.y>0&&map[p.x][p.y-1]!=-1&&countMines(map,new Position(p.x,p.y-1))<3)v.add(Action.UP);
        if(p.y<63&&map[p.x][p.y+1]!=-1&&countMines(map,new Position(p.x,p.y+1))<3)v.add(Action.DOWN);
        if(p.x>0&&map[p.x-1][p.y]!=-1&&countMines(map,new Position(p.x-1,p.y))<3)v.add(Action.LEFT);
        if(p.x<63&&map[p.x+1][p.y]!=-1&&countMines(map,new Position(p.x+1,p.y))<3)v.add(Action.RIGHT);
        v.add(Action.PASS);
        return v.get((new Random()).nextInt(v.size()));
    }
}

```

# Answer
> 0 votes
# Cocoon

I borrowed a bit of utility code from some other bots. The basic strategy here is to get into a safe spot. To accomplish that, I try to lay mines in spots likely to bump me into safe spots. Nearby goals are preferred over distant goals. Absolutely nothing is done about other bots. This bot can usually build a safe spot in a few dozen turns after laying down a checkerboard of failures, so it will at least tie with other bots that can't seek it out and kill it that fast. A bit of code to avoid or kill other bots would improve that scenario.

```
import java.awt.*;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;

public class CocoonBot extends Bot{
    private static final int Y = 64, X = 64;
    public CocoonBot() {
        this.name="Cocoon";
    }

    private int neighborMines(int[][] map, Point p){
        int mines=0;
        if (p.y>=Y-1||map[p.x][p.y+1]==-1) mines++;
        if (p.y<=  0||map[p.x][p.y-1]==-1) mines++;
        if (p.x>=X-1||map[p.x+1][p.y]==-1) mines++;
        if (p.x<=  0||map[p.x-1][p.y]==-1) mines++;
        return mines;
    }

    @Override
    public Action action(int[][] map) {

        Point firstPoint = new Point(p.x, p.y);
        if ( neighborMines(map,firstPoint) == 4 ) {
            return Action.PASS; // we've built a cocoon and are safe
        }

        // calculate how many mines surround each point of the map, 0-4
        Map<Point, Integer> safety = new HashMap<>();
        for(int x=0; x<X; x++) {
            for(int y=0; y<Y; y++) {
                //TODO: teach the bot that it won't ever lay mines on the edge or adjacent to other mines
                //      so effective safety is 0 if getting to 3 requires one of those actions
                Point p = new Point(x,y);
                int s = neighborMines(map,p);
                safety.put(p,s);
            }
        }

        // flood fill the map to find travel paths and distances from the current square to each other non-mine square
        LinkedBlockingQueue<Point> frontier = new LinkedBlockingQueue<>();
        Map<Point, Point> came_from = new HashMap<>();
        Map<Point, Integer> distance = new HashMap<>();
        frontier.add(firstPoint);
        came_from.put(firstPoint, new Point(-1, -1));
        distance.put(firstPoint,0);
        Point current;
        while((current = frontier.poll()) != null) {
            // TODO: bail here for squares too far away to be worth considering
            for(int d=0; d<4; d++) {
                int dx = d<2?(d*2-1):0; //-1 +1  0  0
                int dy = d<2?0:(d*2-5); // 0  0 -1 +1
                if (current.y+dy<Y && current.y+dy>=0 && current.x+dx<X && current.x+dx>=0) {
                    if (map[current.x+dx][current.y+dy] != -1) {
                        Point next = new Point(current.x+dx, current.y+dy);
                        if(!distance.containsKey(next)) {
                            frontier.add(next);
                            came_from.put(next, current);
                            distance.put(next,distance.get(current)+1);
                        }
                    }
                }
            }
        }

        // calculate the safety of where we might end up after dropping a mine
        // weighted towards safer spaces, we really want to end up in space that's already safety=3
        Map<Point, Integer> safety2 = new HashMap<>();
        for(int x=0; x<X; x++) {
            for(int y=0; y<Y; y++) {
                int s = 0;
                for(int d=0; d<4; d++) {
                    int dx = d<2?(d*2-1):0; //-1 +1  0  0
                    int dy = d<2?0:(d*2-5); // 0  0 -1 +1
                    Point p = new Point(x+dx,y+dy);
                    if ( x+dx<0||x+dx>=X||y+dy<0||y+dy>=Y || map[x+dx][y+dy]==-1 ) {
                        // never risk moving into a mine or off the map!
                        s = -999;
                        break;
                    } else if ( safety.containsKey(p) ) {
                        // safety 3 is great
                        // safety 2 is ok
                        // safety 1 is better than nothing
                        s += safety.get(p)>2?12:safety.get(p)>1?3:safety.get(p); // magic numbers!
                    }
                }
                Point p = new Point(x,y);
                safety2.put(p,s);
            }
        }

        // find the safest/closest point
        Point bestpoint = firstPoint;
        double bestscore = safety2.get(firstPoint)+0.1;
        distance.remove(firstPoint);
        for (Map.Entry<Point,Integer> pd : distance.entrySet()) {
            Point p = pd.getKey();
            double score = safety2.get(p)/Math.pow(pd.getValue(),0.8); // magic number!
            if(score > bestscore) {
                bestscore = score;
                bestpoint = p;
            } else if (score == bestscore) {
                if ( (bestpoint.x-X/2)*(bestpoint.x-X/2)+(bestpoint.y-Y/2)*(bestpoint.y-Y/2) >
                     (p.x-X/2)*(p.x-X/2)+(p.y-Y/2)*(p.y-Y/2) ) {
                    // aim for the middle, less wasted time at edges
                    bestscore = score;
                    bestpoint = p;
                }
            }
        }

        // we're in the right spot, place a mine and hope for a good random bump
        if(bestpoint == firstPoint) {
            return Action.MINE;
        }

        // walk back up came_from to figure out which way to step to get to bestpoint
        while(came_from.get(bestpoint) != firstPoint) {
            bestpoint = came_from.get(bestpoint);
        }
        if ( bestpoint.x > firstPoint.x ) {
            return Action.RIGHT;
        }
        if ( bestpoint.x < firstPoint.x ) {
            return Action.LEFT;
        }
        if ( bestpoint.y > firstPoint.y ) {
            return Action.DOWN;
        }
        if ( bestpoint.y < firstPoint.y ) {
            return Action.UP;
        }

        // should never happen
        return Action.MINE;
    }

}

```

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


title: Getting a Highscore in Kuku Kube

text:
# Question
Title: Getting a Highscore in Kuku Kube
First of all, this is more a challenge, than a serious programming question, I would like to share.

Some of you might know the game Kuku kube, where you have to identify a square in a grid, which has a different colour than the others and click it.

You can find it under http://kuku-kube.com/ .

As this seems to be an ideal exercise for our image processing students, I want to see, which way is the best to get the highest score.

My code so far:

```
from pymouse import PyMouse
import time
b=time.time()
m=PyMouse()
start=(2912,895)
tl=(2695,387)
br=(3129,814)
def click():
    m.click(start[0],start[1])
    time.sleep(0.1)
    while time.time()-b<60:
        for i in range(0,9):
            for l in range(0,9):
                m.click(2696+i*53.625,390+l*53.125)
                time.sleep(0.004)

click()

```

gets me to about 370-ish. Is it possible to get more? Use image processing?

High-score wins!

# Answer
# Javascript (Cheating), Score = limitless?

I realized that the game timer was using `setInterval`, which is a very unreliable way of keeping time. With that in mind, since js is single threaded, if we simply hog the thread, the timer can't update. As a result, you can essentially get any score you want. If you perform 1000 clicks in a single function call without releasing the thread, you guarantee a score of at least 60000 (in fact I did this and got 180000). This is obviously cheating because the game lasts longer than 60 seconds, though the game doesn't realize it. For this reason, **any js solution at all is really sort of cheating**. Though the time increase is minimal for code that completes quickly, you can still potentially delay the timer for as long as your code runs.

```
var factor = 1000;

function findAndClick() {
  var array = document.getElementById("box").children;

  for(var j = 0; j < factor; j++){
      var one = array[0].style.cssText;
      var two = array[1].style.cssText;

      var color;
      if(one != two){
        color = array[2].style.cssText;
      } else {
        color = one;
      }

      for (var i=0; i < array.length; i++) {
        if (array[i].style.cssText != color) {
          array[i].click();
          break;
        }
      }
    }
}
$(".play-btn").click();
setInterval(findAndClick, 0);

```

# Javascript (REALLY Cheating), Score = limitless?

The game's object is actually global. As a result, you can tweak various properties to your advantage. The easiest of which is to just set your score to whatever you want it to be:

```
$(".play-btn").click();
Game.lv = 1000000;

```
> 13 votes

# Answer
# Javascript, Score ≈ 10700 14400 (Chrome)

On the home page, open your developer console (F12), copy/paste the following code and wait 60 seconds.

jQuery slow down the execution, so I used the fantastic Vanilla-JS

```
function findAndClick() {
  var array = document.getElementById("box").children;
  var last = "";
  for (var i=0; i < array.length; i++) {
    if (array[i].style.cssText != last) {
      array[i].click();
      last = array[i].style.cssText;
    }
  }
}
$(".play-btn").click();
setInterval(findAndClick, 0);

```
> 10 votes

# Answer
# Javascript/JQuery: 4489

I went the same route as Mig, but I think his is more efficient than mine, as my javascript skills are quite limited.

```
clickBox = function() {
    a = jQuery("#box span");
    if (!a.is(":visible")) {
        clearInterval(clickBox);
        return;
    };
    var colors = {};
    a.each(function(i, o) {
        var style = jQuery(this).attr("style");
        colors[style] = 1 + (colors[style] || 0)
    });
    a.each(function() {
        if (colors[jQuery(this).attr("style")] == 1) {
            jQuery(this).click()
        }
    });
};
setInterval(clickBox, 0);

```
> 1 votes

---
Tags: code-challenge, image-processing
---


title: Cops and Robbers

text:
# Question
Title: Cops and Robbers
Everyone always wants to implement Conway's Game of Life. That's boring! Let's do cops and robbers instead!

You'll have two teams: the cops and the robbers. Each team has 5 members with 50 health each. The program will loop continuously. Each iteration, the following will occur:

* For each team, print the first letter (`C` for the cops, `R` for the robbers), a space, a space-separated list of the members' HP, and a newline. This is the teams' status. After both are done, print another newline. For instance, here's what it might look like the first round:

```
C 50 50 50 50 50
R 50 50 50 50 50

```
* Pick a random number from 1 to 10 (including both 1 and 10). We'll call the number `N`. If `N` is even, the robbers lose this round; if odd, the cops lose.
* Pick a random member of the losing team whose HP is greater than 0 and deduct `N` HP. *The members' HP should never appear go below 0 on the status.*
* Restart the loop.

The game ends when all the members of one team lose all their HP. Then, the following will be printed if the cops win:

```
C+
R-

```

and if the robbers win:

```
R+
C-

```

This is code golf, so the shortest number of characters wins.

Here's a sample implementation in Python 2:

```
import random

cops = [50]*5
robbers = [50]*5

while any(cops) and any(robbers):
    # print the status
    print 'C', ' '.join(map(str, cops))
    print 'R', ' '.join(map(str, robbers))
    print
    # pick N
    N = random.randint(1, 10)
    # pick the losing team (robbers if N is even, else cops)
    losers = robbers if N % 2 == 0 else cops
    # pick a member whose HP is greater than 0
    losing_member = random.choice([i for i in range(len(losers)) if losers[i]])
    losers[losing_member] -= N
    # make sure the HP doesn't visibly drop below 0
    if losers[losing_member] < 0: losers[losing_member] = 0

if any(cops):
    # robbers lost
    print 'C+'
    print 'R-'
elif any(robbers):
    # cops lost
    print 'C-'
    print 'R+'

```

# Answer
> 3 votes
# CJam, 86 bytes

I'm a bit late to the party, but I bring the gift of CJam! ... Hey wait, where are you going?

```
50aA*{"CR"1$+2/zSf*Nf+oNoAmr{_AmrE&+:P2$=:H!}gPH@)-Ue>t_2/z::+0#:L)!}g;'CL'+'-?N'R2$6^

```

Try it online.

### Explanation

As the questions asks to emulate a straightforward process, this is a relatively straightforward answer. Perhaps one interesting choice I made was to hold the health of both teams interleaved in the same list. This costs 3 bytes to convert to two separate lists, which is needed for both health displaying and checking if a team has lost. But (I think) this is made up for by the 2 bytes saved in initialization and much simpler damage-dealing logic.

```
50aA*           "Initialize the health list to 10 copies of 50. Even indices
                 hold the health of cops and odd indices hold the health of
                 robbers.";
{               "Do:";
  "CR"1$+2/z      "Split the health list into the two teams for output, adding
                   the corresponding team letter to the start of each.
                       [a b c d e f g h i j]
                    -> [['C a c e g i] ['R b d f h j]]";
  Sf*Nf+          "Insert a space between each element in each team health list
                   and append a newline to the end of each team health list.";
  oNo             "Print the health status for each team and an extra newline.";
  Amr             "Generate the damage amount minus one. If the damage amount is
                   even (robbers lose), then this is odd and aligns with robbers
                   being at odd indices in the health list, and vice versa.";
  {               "Do:";
    _AmrE&+:P       "Add a random even number from [0, 10) to the damage amount
                     minus one. This value modulo the size of the health list
                     (10) selects a person on the losing team to be damaged.";
    2$=:H!
  }g              "... While the selected person's health is zero.";
  PH@)-Ue>t       "Set the damaged person's new health to the maximum of their
                   current health minus the damage amount and zero.";
  _2/z::+0#:L     "Split the health list into the two teams, sum each team's
                   health, and search for a team's health equal to zero.";
  )!
}g              "... While no team's health was found equal to zero.";
;               "Discard the health list.";
'C              "Produce a 'C'.";
L'+'-?          "Produce a '+' if team 1 (robbers) lost, or '-' otherwise.";
N               "Produce a newline.";
'R              "Produce an 'R'.";
2$6^            "Produce the opposite of the sign produced before.";
                "Implicitly print these final results.";

```

# Answer
> 3 votes
## R - 201

```
S=sum
Z=sample
C=R=rep(50,5)
while(S(R)*S(C)){cat("C",C,"\nR",R,"\n\n")
N=Z(10,1)
F=function(x,i=Z(rep(which(x>0),2),1)){x[i]=max(0,x[i]-N);x}
if(N%%2)R=F(R)else C=F(C)}
cat(c("R+\nC-\n","C+\nR-\n")[1+!S(R)])

```

# Answer
> 2 votes
# APL (Dyalog) (101)

```
∇K
S←2 5⍴50
→6/⍨~∧/J←∨/S>0
⎕←3↑'CR',0⌈S
S[L;M[?⍴M←(0<S[L←1+~2⊤N;])/⍳5]]-←N←?10
→2
⎕←'CR',⍪'+-'⌽⍨J⍳0
∇

```

Explanation:

* `S←2 5⍴50`: at the beginning, set `S` to a 5-by-2 matrix where each value is 50. The top row of the matrix represents the cops, the second row represents the robbers.
* `J←∨/S>0`: for each row of the matrix, store in `J` whether any of the HPs are larger than zero.
* `→6/⍨~∧/J`: if not both teams have living members, jump to line 6. (end)
* `⎕←3↑'CR',0⌈S`: for each value in the matrix, output the maximum of it and 0, prepend a 'C' to the first row and an 'R' to the second, and add a third (empty) line.
* `N←?10`: get a random number in the interval \[1,10\] and store it in `N`.
* `L←1+~2⊤N`: set `L` (the losing team) to `1` if the number was odd and to `2` if it was even.
* `M←(0<S[L`...`;])/⍳5`: get the indices of the living members of that team, and store them in `M`
* `M[?⍴M`...`]`: select a random value from `M`
* `S[L;M`...`]-←N`: subtract `N` from the selected team member's value
* `→2`: jump to line 2 (the test for living members)
* `⎕←'CR',⍪'+-'⌽⍨J⍳0`: output the final status, putting the `+` in front of the winning team and the `-` in front of the losing team.

Sample output

# Answer
> 1 votes
# Mathematica, ~~246~~ 241 bytes

Could probably be golfed further...

```
a=ConstantArray[50,{2,5}];b=Or@@(#<1&)/@#&;c=Print;d=StringJoin@Riffle[IntegerString/@#," "]&;e=RandomInteger;Label@f;Which[b@a[[1]],c@"R+\nC-",b@a[[2]],c@"C+\nR-",True,c["C "<>d@a[[1]]<>"\nR "<>d@a[[2]]];a[[Mod[g=e@9+1,2]+1,e@4+1]]-=g;Goto@f]

```

# Answer
> 1 votes
# Ruby, 184

```
c,r=[p,p].map{('50 '*5).split}
puts([?C,*c]*' ',[?R,*r]*' ')while (u,v=[r,c].map{|a|a.shuffle.find{|x|x>?0}}).all?&&[u,v][rand(1..10)%2].sub!(/.+/){eval"#$&-1"}
puts u ?'R+
C-':'C+
R-'

```

# Answer
> 1 votes
# C, ~~390~~ ~~384~~ 371 bytes

My first golf, if there are any possible improvements, just tell me :)

golfed version:

```
#include <time.h>
#include <stdio.h>
int p[10],j,r,c,w,N,x;int s(){r=c=0;for(j=5;j--;){c+=p[5+j];r+=p[j];}return !!r-!!c;}void t(){for(j=10;j--;)printf("%s %d",j-4?j-9?"":"\n\nC":"\nR",p[j]*=p[j]>0);}main(){srand(time(0));for(j=10;j--;)p[j]=50;t();while(!(w=s())){N=rand()%10+1;while(!p[x=N%2*5+rand()%5]);p[x]-=N;t();}N=(x=w<1?'C':'R')-w*15;printf("\n\n%c+\n%c-",x,N);}

```

somewhat ungolfed version:

```
#include <time.h>
#include <stdio.h>
int p[10],j,r,c,w,N,x;

int s(){
    r=c=0;
    for(j=5;j--;){
        c+=p[5+j];
        r+=p[j];
    }
    return !!r-!!c;
}

void t(){
    for(j=10;j--;)printf("%s %d",j-4?j-9?"":"\n\nC":"\nR",p[j]*=p[j]>0);
}

main(){
    srand(time(0));
    for(j=10;j--;)p[j]=50;
    t();
    while(!(w=s())){
        N=rand()%10+1;
        while(!p[x=N%2*5+rand()%5]);
        p[x]-=N;
        t();
    }
    //w=-1 if cops won, w=1 if robbers won
    N=(x=w<1?'C':'R')-w*15;
    printf("\n\n%c+\n%c-",x,N);
}

```

edit: I found a way to shorten it a bit and fixed a small bug

# Answer
> 1 votes
## Batch - 396 Bytes

I don't know if this technically counts - as it doesn't actually select a random member of the team *who's health is greater than 0*. It just selects a random member, and if the health subtraction generates a number less than 0, then the number becomes 0..

```
@echo off&setLocal enableDelayedExpansion&for %%a in (C R)do for %%b in (1 2 3 4 5)do set %%a%%b=50
:a
set/aN=%RANDOM%*10/32768+1
set/ac=%N%/2*2
if %c%==%N% (set T=C&set L=R)else set T=R&set L=C
set/aG=%RANDOM%*5/32768+1
set/a%T%%G%-=%N%
for %%a in (C R)do set %%a=0&for %%b in (1 2 3 4 5)do (if !%%a%%b! LEQ 0 set %%a%%b=0
set/a%%a+=!%%a%%b!)
if %C% NEQ 0 if %R% NEQ 0 goto :a
echo !T!+&echo !L!-

```

# Answer
> 1 votes
**PHP - 416 bytes**

I'm new to golfing and though this challenge would be easy enough to try it out. So here is what I came up with.

```
<?$c=[50,50,50,50,50];$r=[50,50,50,50,50];while((array_sum($c)!=0)&&(array_sum($r)!=0)){$a="C ".join(" ",$c)."\n";$b="R ".join(" ",$r)."\n";echo$a,$b;$n=rand(1,10);$m=rand(0,4);if($n %2==0){while($r[$m]==0){$m=rand(0,4);}$r[$m]=$r[$m]-$n;if($r[$m]<0){$r[$m]=0;}}else{while($c[$m]==0){$m=rand(0,4);}$c[$m]=$c[$m]-$n;if($c[$m]<0){$c[$m]=0;}}if(array_sum($r)==0){echo"C+\nR-\n";}if(array_sum($c)==0){echo"R+\nC-\n";}}?>

```

With explanation:

```
<?
$c=[50,50,50,50,50];$r=[50,50,50,50,50];                       populate Arrays
while((array_sum($c) != 0) && (array_sum($r) != 0)){           loop until on array sums up to 0
    $a="C ".join(" ",$c)."\n";                                 set cops health to a
    $b="R ".join(" ",$r)."\n";                                 set robbers health to b
    echo$a,$b;                                                 print cop and robber health
    $n=rand(1,10);                                             chose random n
    $m=rand(0,4);                                              chose random member
    if($n % 2 == 0){                                           check if n is even
        while($r[$m] == 0){ $m=rand(0,4); }                    loop until value m of array r is not 0
        $r[$m]=$r[$m]-$n;                                      lower health of member m
        if($r[$m] < 0){ $r[$m]=0; }                            if health goes below 0 set it to 0
    }else{
        while($c[$m] == 0){ $m=rand(0,4); }                    same as above
        $c[$m]=$c[$m] - $n;
        if($c[$m] < 0){$c[$m]=0;}
    }
    if(array_sum($r) == 0){ echo"C+\nR-\n"; }                  check if r array sums up to 0 and print that cops won
    if(array_sum($c) == 0){ echo"R+\nC-\n"; }                  check if c array sums up to 0 and print that robbers won
}
?>

```

# Answer
> 0 votes
# Octave, 182 177 158 145 bytes

**145:**

```
t=repmat(50,5);while prod(any(t))d=ceil(rand*10);c=2-mod(d,2);r=ceil(rand*5);t(r,c)-=d;t.*=t>0;end;p=2*any(t,1);['C-';'R+';'C+';'R-'](1+p:2+p,:)

```

I gave up checking if the character shoot is above zero - this would only be significant if we were forced to display the state in each turn - here we're just randomly skipping one random number from RNG, making it more random.

Also, replaced

```
t=max(0,t)

```

with shorter

```
t.*=t>0

```

---

***\[note - it is printing 'C+R-' without the newline - it's fixed in 145 byte version\]***

**158:**

```
t=repmat(50,5);while prod(any(t))d=ceil(rand*10);c=2-mod(d,2);do r=ceil(rand*5);until t(r,c);t(r,c)-=d;t=max(0,t);end;p=4*any(t,1);disp('C-R+C+R-'(1+p:4+p))

```

Degolfed:

```
t=repmat(50,5);               #only first two columns (cops, robbers) relevant
while prod(any(t))
    d=ceil(rand*10);
    c=2-mod(d,2);
    do r=ceil(rand*5);until t(r,c);
    t(r,c)-=d;
    t=max(0,t);
end;
p=4*any(t,1);
disp('C-R+C+R-'(1+p:4+p))

```

I changed `repmat(50,5,2)` to `repmat(5)` \- so we have 5x5 matrix instead of 5x2 now (the additional 3 columns don't affect the algorithm). I also found a way to compress the output.

**177:**

```
t=repmat(50,5,2);while prod(sum(t))d=ceil(rand*10);c=2-mod(d,2);do r=ceil(rand*5);until t(r,c);t(r,c)-=d;t=max(0,t);end;if sum(t)(1)printf "C+\nR-\n";else printf "C-\nR+\n";end

```

Degolfed:

```
t=repmat(50,5,2);
while prod(sum(t))
    d=ceil(rand*10);
    c=2-mod(d,2);                  #cops or robbers affected?
    do r=ceil(rand*5);until t(r,c);
    t(r,c)-=d;
    t=max(0,t);
end
if sum(t)(1)
    printf "C+\nR-\n"
else
    printf "C-\nR+\n"
end

```

Basically, we create a 5x2 matrix, where the first column are cops and the second column are robbers:

```
t =
50     50
50     50
50     50
50     50
50     50
[cops] [robbers]

```

The `sum` function when one argument applied makes a sum by columns, so it's initially:

```
250    250

```

When one of them reaches zero, the `prod(sum(t))` evaluates to zero breaking the loop. Then we can examine who won checking whose column sums to zero.

# Answer
> 0 votes
## Javascript: 410

```
function x(l){var t=this,o=t.p={n:l||"C",h:[50,50,50,50,50],s:function(){return o.h.reduce(function(a,b){return a+b})},r:function(){console.log(o.n+' '+o.h.join(' '))},d:function(m){while(o.h[z=~~(Math.random()*5)]<1){}o.h[z]=m>o.h[z]?0:o.h[z]-m}};o.r()}q=[new x(),new x('R')];while((c=q[0].p.s()>0)&&q[1].p.s()>0){q[(z=~~(Math.random()*10))%2].p.d(z);q[0].p.r();q[1].p.r()}console.log(c?'C+\r\nR-':'R+\n\rC-')

```

---
Tags: code-golf
---


# Question
Title: Write two single line functions to encode and decode base64
Write two functions of one line each that can encode and decode base64.

* Use any language you want, but if the language can naturally be converted to a single line (e.g. javascript) then any block of code separated by an end-of-line character is counted as a line.
* The functions must be self-contained. They cannot reference outside variables or imported libraries, with the exception of a single input argument.
* Expanding on the previous point, you cannot define constants or variables for use inside the function. For instance, if your function references `alphabet` as the collection of base64 symbols, replace every instance of `alphabet` with a literal of the same value.
* The functions must be one line each, not counting the function definition itself. For example, in languages like Visual Basic, functions are a minimum of three lines due to the beginning and end lines being a required part of the function definition. This is acceptable as long as the code that does the base64 conversion is only one line.
* Do not use built in functions such as javascript's `atob` or `btoa`.

Here's my functions written in python. I can't find a way to make these smaller.

```
def tobase64(m):
    return ''.join(['ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'[int(z[::-1].zfill(6)[::-1],2)] for z in [''.join([bin(ord(x))[2:].zfill(8)for x in m])[y:y+6] for y in range(0,len(m)*8,6)]])+''.join(['=' for x in range(-len(m)%3)])

```

and the decoder

```
def fromb64(m):
    return ''.join([chr(int(w,2)) for w in [(''.join([''.join([bin('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.index(x))[2:].zfill(6) for x in m if x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'])[y:y+8] for y in range(0,len(''.join([bin('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.index(x))[2:].zfill(6) for x in m if x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'])),8)])+'a')[:-(len(m)-len(m.replace('=','')))*2-1][z:z+8] for z in range(0,len(''.join([bin('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.index(x))[2:].zfill(6) for x in m if x in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'])),8)] if len(w) == 8])

```

# Answer
## Python 2, 437 characters

As a first improvement to your Python solution, you can cut down on the references to the long string of characters 'abc...ABC...0123456789+/':

```
def fromb64(m):
    return (lambda A:''.join([chr(int(w,2)) for w in [(''.join([''.join([bin(A.index(x))[2:].zfill(6) for x in m if x in A])[y:y+8] for y in range(0,len(''.join([bin(A.index(x))[2:].zfill(6) for x in m if x in A])),8)])+'a')[:-(len(m)-len(m.replace('=','')))*2-1][z:z+8] for z in range(0,len(''.join([bin(A.index(x))[2:].zfill(6) for x in m if x in A])),8)] if len(w)==8]))('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/')

```

This is just (lambda A: {{what you did, but with that string replaced by A}})(that string).
> 1 votes

---
Tags: code-golf, base-conversion
---


title: Connecting letters

text:
# Question
Title: Connecting letters
You should write a program or function which receives a block of chars represented as a string and outputs or returns a similar string in which the letters adjacent in the alphabet are connected.

A visual example (in the form of `input => output`):

```
b     d               b     d
                      |\   /|
                      | \ / |
             =>       |  X  |
                      | / \ |
      e               |/   \e
c     a               c     a

```

## Details

* Input will be a string containing spaces, newlines and exactly one of each of the first `N` lowercase letters. `1 <= N <= 26`
* The lines of the input will be padded with spaces creating a full rectangular block.
* Every pair of letters adjacent in the alphabet will be on the same row, column or diagonal line and should be connected with a straight ascii line using `\ / | or -`. (The line might have a length of 0.)
* The following types of two-line overlaps should be handled:

```
/ and \ become X
| and - become +
/ and / become /
\ and \ become \
| and | become |
- and - become -
[letter] and [anything] become [letter]

```
* No other kind of two-line overlap will occur.
* If more than two lines overlap any pair of them will be guaranteed to be one of the valid overlaps. (e.g. `[letter] / |` triplet will never occur)
* Apart from changing spaces into `\ / | - X and +` input and output should be identical.
* Trailing newline is optional but have to be the same for input and output.
* This is code-golf so the shortest entry wins.

## Examples

Input:

```
b     d

     h   gi

      e  f
c     a

```

Output:

```
b     d
|\   /|
| \ / |
|  X h+--gi
| / \ |  |
|/   \e--f
c     a

```

Input:

```
     dk    j

 b    l

 c   fg

     a    m

   i      h
     e

```

Output:

```
     dk----j
    /||   /
 b / |l  /
 |X  | \/
 c \ fg/\
    \|/\ \
     a  \ m
    /|   \
   i-+----h
     e

```

Input:

```
   eti  sqjh k  p  u  cfm vb owgzyx rnd la

```

Output:

```
   eti--sqjh-k--p--u--cfm-vb-owgzyx-rnd-la

```

Input:

```
a

```

Output:

```
a

```

# Answer
> 3 votes
# Perl, 219

Some improvements may be still possible.

```
#!perl -p0
/
/;$x="@-";
sub g{map"(?=$_)(.@_)+[".chr(1+ord).chr(~-ord)."]",a..z}
sub f{for$p(g"{$x}"){s/$p/$&&((_."\177"x~-$x)x y!
!!)/se;$_=lc;s![\0\\]!@_!g}$x++}
f"/";y!\17!/!;f"|";f"\\";y/\17/X/;for$p(g){s/$p/$&=~y! |!-+!r/e}

```

Try me.

# Answer
> 6 votes
# JavaScript (ES6) 246 ~~266 280 285 307~~

Quite bulky ...

A function with string param and returning the modified string. A trailing newline is optional unless the input is just 1 row (I need a newline to find the row len)

*Just to make someone happy*

```
F=b=>b.match(/\w/g).sort().map(l=>(q=b.indexOf(l),~p)?[o=b.indexOf('\n'),~o,o+2,1].map((d,i)=>{k=(q-p)/d|0;if(k&&k*d+p==q)for(m='/|\\-'[i];(p+=k>0?d:-d)-q;c==m|c>'`'&c<'{'?0:b[p]=c>' '?c<'/'|c>'z'?'+':'X':m)c=b[p]}):p=q,p=-1,b=[...b])&&b.join('')

```

*More readable*

```
F=b=>
  b.match(/\w/g).sort().map(l=>
    (q=b.indexOf(l),~p)?
    [o=b.indexOf('\n'),~o,o+2,1].map((d,i)=>{
      k=(q-p)/d|0;
      if(k&&k*d+p==q)
        for(m='/|\\-'[i];
              (p+=k>0?d:-d)-q;
              c==m|c>'`'&c<'{'?0:b[p]=c>' '?c<'/'|c>'z'?'+':'X':m)
            c=b[p]
    })
    :p=q
  ,p=-1,b=[...b])
  &&b.join('')

```

**Test** In Firefox/FireBug console

```
console.log(F('\
b     d\n\
       \n\
       \n\
       \n\
       \n\
      e\n\
c     a\n'))

console.log(F('\
     dk    j\n\
            \n\
 b    l     \n\
            \n\
 c   fg     \n\
            \n\
     a    m \n\
            \n\
   i      h \n\
     e      \n'))

console.log(F('\
b     d    \n\
           \n\
           \n\
     h   gi\n\
           \n\
      e  f \n\
c     a    \n'))

```

*Output*

```
b     d
|\   /|
| \ / |
|  X  |
| / \ |
|/   \e
c     a

     dk----j
    /||   /
 b / |l  /
 |X  | \/
 c \ fg/\
    \|/\ \
     a  \ m
    /|   \
   i-+----h
     e

b     d
|\   /|
| \ / |
|  X h+--gi
| / \ |  |
|/   \e--f
c     a

```

---
Tags: code-golf, ascii-art, printable-ascii, connected-figure
---


title: Unwise bit operations

text:
# Question
Title: Unwise bit operations
I like to golf in `dc`, but I'm sometimes frustrated because `dc` doesn't have bitwise operations.

# Challenge

Provide four named functions which implement the equivalent of the c bitwise operations `&`, `|`, `~` and `^` (bitwise AND, OR, NOT and XOR). Each function will take two operands (`~` takes only one) which are at least 32-bit unsigned integers. Each function will return an unsigned integer of the same bit-width as the operands.

### Restriction

You may only use operations that are supported by `dc`. These are:

* `+` `-` `*` `/` Arithmetic addition, subtraction, multiplication and division
* `~` modulo (or divmod if your language supports it)
* `^` exponentiation
* `|` modular exponentiation
* `v` square root
* `>` `>=` `==` `!=` `<=` `<` standard equality/inequality operators
* `>>` `<<` bit shift operators. `dc` doesn't have these, but since they are trivially implemented in terms of division/multiplication by powers of 2, then I will allow these.

Control structures in `dc` my be clumsily built using (recursive) macros and (in)equality operations. You may use whatever built-in control structures your language has.

You **may also use logical operators** `&&` `||` `!`, even though these aren't directly available in `dc`.

You **must not use the bitwise operators** `&`, `|`, `~` and `^` or any functions that trivially implement them.

In addition you must not use built-in base-conversion-of-string operators or functions.

---

Please also consider providing a test program or online compiler snippet (not included in the golf score) to help verify your answer.

# Answer
# C, 134

The C preprocessor is pretty fun to abuse. Basically this macro defines the 3 functions, `a`, `o`, and `x`, for `and`, `or`, and `xor` respectively. The only difference in the algorithm for these operations is the criteria for setting the bit in the result.

`not` is the function `n`.

```
#define f(n,c)n(a,b){for(r=0,i=31;i+1;--i)if(((a>>i)%2+(b>>i)%2)c)r+=1<<i;return r;}
i,r;n(a){return 0xffffffff-a;}f(a,/2)f(o,)f(x,%2)

```

Tester program (takes a long time, I didn't spend any time optimizing it at all, but it does test every test case possible, beside MAX\_INT related ones):

```
#define m_assert(expected, condition, actual)\
    if(!((expected) condition (actual)))\
        printf("assert fail @ line %i, expected: %x, actual %x, condition "#condition"\n", __LINE__, expected, actual);

int main()  {
    unsigned int j,k;
    for(j=0; j<0xffff; ++j)    {
        m_assert(~j, ==, n(j));
        for(k=0; k<0xffff; ++k)    {
            m_assert(j & k, ==, a(j,k));
            m_assert(j | k, ==, o(j,k));
            m_assert(j ^ k, ==, x(j,k));
        }
    }

```
> 4 votes

# Answer
# ised 76 bytes

ised also doesn't have bitwise operations - usually annoying, but now welcome, because we really *need* to implement them.

Functions will be stored in numbered memory slots (no verbose names).

Conversion to and from binary:

```
@5{:x/2^[32]%2:};
@6{:x@:2^[32]:};

```

NOT could be `@1{:$6::{1-$5::x}:}` but it's obviously easier to just subtract:

```
@1{:2^32-x-1:};

```

OR:

```
@2{:$6::{$5::{x_0}:+$5::{x_1}>0}:};

```

AND:

```
@3{:$6::{$5::{x_0}:*$5::{x_1}}:};

```

XOR:

```
@4{:$6::{$5::{x_0}:<>$5::{x_1}}:};

```

This would bring us to 156 bytes (with newlines and semicolons). A test code would just be (NOT, OR, AND, XOR in succession, found under names $1,$2,$3,$4):

```
> $1::{6}
4294967289
> $2::{12 11}
15
> $3::{12 11}
8
> $4::{12 11}
7

```

---

But of course OR and NOT are all we really need and things can be simplified:

```
@1{:2^32-x-1:};
@2{:@+{2^U{?{$5::x}%32}}:};
@3{:${1 2 1}::x:};
@4{:$3::{$2::x${1 2}::x}:};
@5{:x/2^[32]%2:};

```

That's 109 characters. When newlines and semicolons are skipped, and with a bit more golfing, we have 76 characters:

```
@3{@1{:2^32-x-1:}@2{:@+{2^U{?{x/2^[32]%2}%32}}:}$1}@4{{:$2::x${1 2}::x:}$3};

```
> 4 votes

# Answer
# Nim (537)(490)

*Nim Compiler 0.10.2*

I've been looking for a reason to learn nim so here we go.

For code golf, I have leveraged variable parameters and implicit returns. The variable parameters, per the documentation are less stack efficient. Personally, I find the implicit returns harder to read and would probably only use them in trivial procedures.

As for the algorithms, they are simple enough. For all operations except NOT, we compare each bit and manually compare them to our expected truth table. Set each bit as needed along the way in our output variable. In Nim, result is the implicit return value.

I wasn't sure if we were allowed to use built-in OR and AND for asserting two boolean conditions so the notZero procedure was put in their place.

```
proc s(x, y, b: var int)=
  x = x div 2
  y = y div 2
  b *= 2

proc n(x: var int): int =
  return -(x+1)

proc a(x, y: var int): int =
  var b = 1
  while x > 0 and y > 0:
    if (x mod 2  + y mod 2) == 2:
      result += b

    s(x,y,b)

proc o(x, y: var int): int =
  var b = 1
  while x + y > 0:
    if (x mod 2 + y mod 2) >= 1:
      result += b

    s(x,y,b)

proc r(x, y: var int): int =
  var b = 1
  while x + y > 0:
    if (x mod 2 + y mod 2) == 1:
      result += b

    s(x,y,b)

```

Still looking for a better method...

Here is the non-squished version plus full test harness to run on your own machine.
If you just want to run a couple of inputs, here is test case lite.
> 1 votes

# Answer
# CJam, 71 bytes

```
{:F;0{:R;2md@2md@+F~!2I#*R+}64fI\;\;}:B{"2-"B}:A{'!B}:O{0SB}:N{'(B}:X];

```

### Explanation

```
"B : UInt64 UInt64 String -> UInt64
 Computes a bitwise operation on the two given unsigned integers. The operation
 is defined by the logical inverse of the result of evaluating the given string
 given the sum of two input bits.";
{
  :F;             "Save the operation string.";
  0               "Initialize the result to 0.";
  {               "For I from 0 through 63:";
    :R;             "Save the result.";
    2md@2md@        "Divide each input by 2 and collect the remainders as the
                     next pair of bits to process.";
    +F~!            "Compute the logical inverse of the result of evaluating
                     the operation string given the sum of the two bits.";
    2I#*            "Adjust the resulting bit to be in the correct output
                     position by multiplying it by 2^I.";
    R+              "Add the location-adjusted bit to the result.";
  }64fI
  \;\;            "Clean up.";
}:B

"A : UInt64 UInt64 -> UInt64
 Computes the bitwise AND of the two given unsigned integers.
 This is done by passing the inputs along to B with an operation such that:
   bit_out = !((bit_in_1 + bit_in_2) - 2)";
{"2-"B}:A

"O : UInt64 UInt64 -> UInt64
 Computes the bitwise OR of the two given unsigned integers.
 This is done by passing the inputs along to B with an operation such that:
   bit_out = !(!(bit_in_1 + bit_in_2))";
{'!B}:O

"N : UInt64 -> UInt64
 Computes the bitwise NOT of the given unsigned integer.
 This is done by passing the input and 0 along to B with an operation such that:
   bit_out = !((bit_in + 0))";
{0SB}:N

"X : UInt64 UInt64 -> UInt64
 Computes the bitwise XOR of the two given unsigned integers.
 This is done by passing the inputs along to B with an operation such that:
   bit_out = !((bit_in_1 + bit_in_2) - 1)";
{'(B}:X

];              "Clean up.";

```

### Test suite

This code tests runs of each of my and, or, not, and xor functions 100 times with uniformly-distributed 64-bit unsigned inputs and compares the result with that produced by the built-in operator. Due to gratuitous use of the eval operator, it's quite slow and may take up to about a minute with the online interpreter. But if all goes well, execution should end with no output, because any discrepancies found are printed.

```
N:L;
{:F;0{:R;2md@2md@+F~!2I#*R+}64fI\;\;}:B{"2-"B}:A{'!B}:O{0SB}:N{'(B}:X];
{;Y32#__mr*\mr+}2e2%2/{~:U;:V;"A&O|X^"2/{[{US@SV" = "UV5$~L}/9$2$={];}{]oLo}?}/"N~"[{U" = "U3$~Y64#(&L}/6$2$={];}{]oLo}?}/

```
> 1 votes

# Answer
# JavaScript ~~294~~ 267

Was able to shave off a few more bytes with @AlexA.'s and @kennytm's suggestions.

Functions:

```
B=(n,m,t)=>{for(var p=4294967296,y=0;p>=1;p/=2)y+=t=='x'&&(n>=p||m>=p)&& !(n>=p&&m>=p)?p:0,y+=t=='a'&&n>=p&&m>=p?p:0,y+=t=='o'&&(n>=p||m>=p)?p:0,n-=n>=p?p:0,m-=m>=p?p:0
return y}
N=(n)=>{return 4294967295-n}
A=(n,m)=>B(n,m,'a')
O=(n,m)=>B(n,m,'o')
X=(n,m)=>B(n,m,'x')

```

example:

```
var n = 300;
var m = 256;
console.log(X(n,m) + ", " + (n ^ m));
console.log(O(n,m) + ", " + (n | m));
console.log(A(n,m) + ", " + (n & m));
console.log(N(n) + ", " + (~n>>>0));
console.log(N(m) + ", " + (~m>>>0));

```

output:

```
44, 44
300, 300
256, 256
4294966995, 4294966995
4294967039, 4294967039

```
> 0 votes

---
Tags: code-golf, restricted-source, arithmetic, bitwise
---


# Question
Title: Produce different behaviour in all versions of your language
Write a program that:

* if a compiled language is used, compiles without errors
* if an interpreted language is used, runs without syntax errors

for every major release of your language, and produces different output for every major release under which it is compiled/run. (It may produce the same or different output for versions within the same major release, as long as it varies among major releases.) You may not output or use any part of the language version in your program.

A "major release" of a language is defined to be a publicly available release that added to the major version number. For example, C# has had 6 major releases, C has had 3 (K&R is not a numbered version and does not contribute to the count), and Ruby has also had 3 (due to version 0.95). What number constitutes the major version number can change over time (Java has had 8 major releases).

Any language used in this challenge must have:

* At least three major releases, and
* A dedicated Wikipedia article.

# Answer
> 40 votes
# Python

```
if 2 + 2 is 4:
    # Lies must be abolished

    try:
        fact = '2 + 2 = %r' % 5
        exec('True = False')
        exec('assert (2 + 2 == 5) is True')
    except ValueError:
        print('War is peace.')
    except NameError:
        print('Freedom is slavery.')
    except SyntaxError:
        print('Ignorance is strength.')

else:
    # All is good
    print('Big Brother is watching you.')

```

*(Edit: Had to make a change because string formatting was actually introduced in... 0.9.9)*

Tested on the following versions:

* **0.9.1**: Prints `Big Brother is watching you.` because 2 + 2 is *5*.\*
* **1.5**: Prints `War is peace.` since `%r` string formatting is unavailable, raising a `ValueError`,
* 2.1: Prints `Freedom is slavery.` since `True` is not defined, raising a `NameError`,
* 3.4: Prints `Ignorance is strength.` since `True` cannot be assigned to, raising a `SyntaxError`.

As a bonus, Python 2.3 to 2.7 gives no output, since the assertion passes.

Note that there are four spaces on both "blank" lines, and the file also needs to have a trailing newline.

<sup>* `is` checks *object equality*, and only from 1.0.0 onwards were small integers shared. You can still see the effect today by trying larger numbers, e.g. `999 + 1 is 1000` gives `False`.</sup>

# Answer
> 10 votes
# Python

Typical sunday afternoon in a house of three brothers.

```
try:    # The night before the exam.
        assert(2/5 < 3/5) # Math is hard!
        print("Be quiet!")
except: # Options: 1. Play. 2. Do nothing.
        try: print(__import__("this").s)
        except: "Too afraid to snap back."

```

### Output

```
$ # Older brother:
$ python3.4 123.py
Be quiet!
$
$ # Much younger brother:
$ ./python1 123.py
$
$ # Slightly younger brother:
$ python2.7 123.py
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Gur Mra bs Clguba, ol Gvz Crgref

Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
Pbzcyrk vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcnefr vf orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.
Nygubhtu cenpgvpnyvgl orngf chevgl.
Reebef fubhyq arire cnff fvyragyl.
Hayrff rkcyvpvgyl fvyraprq.
Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.
Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.
Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
Abj vf orggre guna arire.
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!

```

# How it works

```
try:
        assert(2/5 < 3/5)

        # In Python 3, '2/5' and '3/5' are floats.
        # In lower versions, they're ints and the assertion fails.

        print("Be quiet!")

        # Python 3 prints this and exits.
        # Lower versions already caught an exception.
except:
        try: print(__import__("this").s)

        # Try importing 'this' (an easter egg which prints the Zen of
        # Python) and printing 'this.s' (same old Zen with ROT13 obfuscation).
        # The easter egg doesn't exist in Python 1 and an exception is raised.

        except: "Too afraid to snap back."

        # Bare string. Would be printed in REPL; does nothing in a program.

```

# Answer
> 3 votes
This C++03 C++11 and C++14 program prints old, medium or new: (C++03 is a set of technical corrections to C++98: compilers consider the two to be synonymous)

```
#define M(x, ...) __VA_ARGS__

int a[] = { M(1'2, 3'4, 5, 0) };
const char *b[]={ 0, "is", "the", "best", "always", "new" };
struct foo { ~foo() { throw std::string("old"); } };

void done() {
    std::cout << "medium" << std::endl;
    std::exit(0);
}
int main() {
  if (b[a[1]]) {
    std::cout << b[a[1]] << std::endl;
  } else {
    std::set_terminate(done);
    try { foo test; }
    catch( std::string c) {
      std::cout << c.c_str() << std::endl;
    }
  }
}

```

live example

There are a few ways to do this; I figured out ways that current versions of clang and gcc support when you tell it to compile in a particular version mode.

It relies on a few things.

To distinguish C++14 from C++11/C++03, it uses `'` as an internal delimiter in integer constants. Then I discard a leading token, which either contains a `,` or not depending on the C++ version. The 2nd element of the array is now either `0` or `5`. I use this to look up in another array -- entry `0` is null, and entry `5` is `"new"`. If it is non-null, I print it and am finished (for C++14).

To distinguish C++03 from C++11, it throws from a destructor. In C++11, all destructors are implicitly noexcept, which calls the `std::set_terminate` handler.

I install a terminate handler that prints out `"medium"` (for C++11), and in the catch block I print `"old"` (for C++03).

Breaking changes stolen from here for C++11 and here for C++14.

# Answer
> 2 votes
# **C**

**Golfed**, for the hell of it.

```
O;main(o){o=((O='\o'),O);}

```

> *It does nothing.*

Fortunately.
I didn't find anything relevant, so this is just about playing with *undefined behaviors* again.

---

### **C89**

> **§3.1.3.4 7 — Character constants**
>
> In addition, certain nongraphic characters are representable by escape sequences consisting of the backslash `\` followed by a lower-case letter: `\a` , `\b` , `\f` , `\n` , `\r` , `\t` , and `\v` . If any other escape sequence is encountered, the behavior is undefined.

Yup. `'\o'` implies an *undefined behavior* in **C89**, while it is only *implemention-defined* in **C99** and **C11** (it gives me `'o'`).

---

### **C99**

This is where it gets tricky.

> **§6.5.16 4 — Assignment operators**
>
> (...) If an attempt is made to modify the result of an assignment operator or to access it after the next sequence point, the behavior is undefined.

This is a weird wording specific to **C99**.

A sequence point is needed after `(O='\o')`: `,` do the trick.
Since it is necessary to *access* the result (i.e. *"to read or modify the value of an object"* as defined by the standard, whose identifier is `O`) to store it in `o`, the behavior is undefined.

---

### **C11**

All of that does not apply in **C11**.
It should work fine while compiling in **C11**.
Nobody uses **C11**.

---
Tags: popularity-contest
---


title: Two-zero-one-five puzzle

text:
# Question
Title: Two-zero-one-five puzzle
## Background

This puzzle is a variation on the four fours puzzle (itself the topic of a past question). Like that puzzle, the aim is to find mathematical expressions for different whole numbers, using only four digits and certain mathematical operators. In this case, however, the **permitted digits are just 2, 0, 1 and 5**. Each must appear precisely once in the solution and in the correct order. Surprisingly many whole numbers can be represented this way. Solvers are encouraged to try solving it by hand first, as it's strangely enjoyable.

## Rules

Constants may be constructed from single or multiple digits:

* Integers: e.g. 2, 0, 15, etc.
* Decimals: e.g. .2, .01, 1.5, etc.
* Repeating decimals: e.g. .2~ (=0.222...), .15~ (=0.1555...), 20.15~~ (=20.1515...)

The following unary operations are permitted:

* Unary negation: -x
* Square root: sqrt(x)
* Integer factorial: x!

The following binary operations are permitted:

* Standard arithmetic operators: x+y, x-y, x\*y and x/y
* Arbitrary exponentiation: x^y
* Arbitrary roots: rt\[x\](y) (= x'th root of y)

## Task

Your program should print out expressions for as many of the integers between 0 and 100 as it can, and then output the number of expressions it has produced.

* The solutions must be printed in order in the format n=\[expr\].
* The expressions must use all the digits 2, 0, 1, 5, once each in that order.
* The expressions must be printed using the notation described above. Unnecessary parentheses are permitted but not required, as is whitespace. The order of operator precedence is unary negation, factorial, exponentiation, multiplication/division and addition/subtraction.
* The program need not return solutions for all the numbers. A program that simply outputs 0 is therefore valid; however, see the scoring section below.
* The program should run in under 15 minutes on a modern computer.

You may write a program or function. The expressions should be printed to STDOUT (or closest alternative). The number of expressions can be printed to STDOUT or returned as an integer. Standard code golf restrictions apply.

## Example output

```
0=2*0*1*5
10=20*1*.5
42=((2+0!)!+1)!/5!
100=20*1*5
4

```

## Scoring

**Update**: *@orlp has noted a flaw in the scoring system. See http://meta.codegolf.stackexchange.com/questions/5106/way-of-salvaging-two-zero-one-five-puzzle-challenge for a discussion of how or whether this should be fixed.*

Solutions are scored *first* by the number of expressions they produce and *then* by their code length in bytes. Hence, a 1000 byte program that produce 80 results will beat a 100 byte program that produces only 79 (though the latter could easily be extended to include the missing results).

For those who would like a motivating target, below is a lower bound on the number of expressions that can be represented. I don't plan to submit an entry, so it may well be possible to win with less!

> At least 85 (out of 101), though it may well be higher.

## Scoreboard

As an extra incentive, here is a summary of the score progression. Whenever you beat the highest score, feel free to add yourself to the top of the table (or ask someone else to).

* 0 expressions, 1 byte (Pyth): *implementation that just outputs 0*

# Answer
> 9 votes
# 85, ~2400 bytes

I'm a bit sad this is a code golf challenge, as I feel that all my previous efforts have been rather useless now that I'll post this:

```
  0 = ((2*0)^15)
  1 = ((2^0)^15)
  2 = (2-(0^15))
  3 = (20*.15)
  4 = (20*(1/5))
  5 = (20-15)
  6 = ((.20+1)*5)
  7 = ((20*.1)+5)
  8 = (2*((0-1)+5))
  9 = ((.20/.1~)*5)
 10 = (20/(1/.5))
 11 = ((((2-0)+1))!+5)
 12 = (20*(.1+.5))
 13 = ((-(2)-0)+15)
 14 = (20-(1+5))
 15 = ((2*0)+15)
 16 = ((2^0)+15)
 17 = ((2-0)+15)
 18 = (20-(1/.5))
 19 = (20-(1^5))
 20 = (20^(1^5))
 21 = (20+(1^5))
 22 = (20+(1/.5))
 23 = (((2-0)/.1~)+5)
 24 = ((20-1)+5)
 25 = ((20^1)+5)
 26 = ((20+1)+5)
 27 = (rt[.2](((0)!+1))-5)
 28 = (2*(-((0)!)+15))
 29 = ((((2+(0)!)+1))!+5)
 30 = ((2-0)*15)
 31 = (20+sqrt((1+(5)!)))
 32 = ((20*.1)^5)
 33 = ((.2^-((0)!))/.15~~)
 34 = (2+(((0)!+1)^5))
 35 = (20+15)
 36 = (20*(1/.5~))
 37 = (rt[.2](((0)!+1))+5)
 38 = ((20-1)/.5)
 39 = (-((2^0))+(sqrt(.1~)*(5)!))
 40 = (20*(1/.5))
 41 = (((.2~^-((0)!))/.1~)+.5)
 42 = ((20+1)/.5)
 43 = (-(2)+(((0)!/.1~)*5))
 44 = (20+((-(1)+5))!)
 45 = (20/(1-.5~))
 46 = ((.2+((0)!/.1~))*5)
 47 = (2+(((0)!/.1~)*5))
 48 = (2*(((0-1)+5))!)
 49 = ((((2+(0)!))!/.1~)-5)
 50 = (((2^0)/.1)*5)
 51 = ((.2+((0)!/.1))*5)
 52 = (2+(((0)!/.1)*5))
 54 = (((2+(0)!)/.1)/.5~)
 55 = ((2+((0)!/.1~))*5)
 56 = (((.2-(0)!)+sqrt(.1~))*-((5)!))
 58 = (-(2)+sqrt((((((0)!/sqrt(.1~)))!)!*5)))
 59 = ((((2+(0)!))!/.1~)+5)
 60 = (20/(.1~^.5))
 62 = (2*(-((0)!)+sqrt(rt[-(.1)](.5))))
 64 = ((2-0)^(1+5))
 65 = ((20/sqrt(.1~))+5)
 66 = ((-(((2+(0)!))!)/.1~)+(5)!)
 67 = (((((2+(0)!))!)!*.1)-5)
 69 = ((2^(((0)!/sqrt(.1~)))!)+5)
 70 = (((.2^-((0)!))/-(.1))+(5)!)
 72 = ((2+(0)!)*((-(1)+5))!)
 75 = ((.2^-((0)!))*15)
 76 = (rt[(-(2)^-((0)!))](.1~)-5)
 77 = (((((2+(0)!))!)!*.1)+5)
 78 = (2*(-((0)!)+(sqrt(.1~)*(5)!)))
 80 = (-(20)*(1-5))
 81 = (201-(5)!)
 82 = (2*((0)!+(sqrt(.1~)*(5)!)))
 84 = (((.2-(0)!)+.1)*-((5)!))
 85 = (((((2+(0)!))!)!*.1~)+5)
 86 = (rt[(-(2)^-((0)!))](.1~)+5)
 88 = (rt[.2]((-((0)!)-1))+(5)!)
 90 = ((20/.1~)*.5)
 93 = (((2+(0)!)/-(.1~))+(5)!)
 95 = ((20-1)*5)
 96 = ((.20-1)*-((5)!))
 98 = (-(20)*(.1-5))
 99 = ((-(20)-1)+(5)!)
100 = (20/(1/5))
85

```

From here on it's just a compression challenge. Maybe I'll compete later, maybe I won't. For me most of the fun was in the challenge to find the most formulas.

A hint for those struggling to write a solver - runtime shouldn't be a problem. If you have too many formulas to check you need better heuristics to throw away hopeless solutions and duplicates. The code I wrote to generate the above runs in ~5 sec on Python.

---
Tags: code-golf, number, kolmogorov-complexity, arithmetic, expression-building
---


title: Draw a Random ASCII Art Quilt

text:
# Question
Title: Draw a Random ASCII Art Quilt
For this challenge, an ASCII art quilt will be a block of text 24 characters wide and 18 lines tall, containing the characters `=-<>/\` in a quilt-like pattern that is horizontally and vertically symmetrical.

Example quilt:

```
========================
------------------------
//\\//\\\//\/\\///\\//\\
<<><<>>>>><<>><<<<<>><>>
/\\/\\\\/\/\/\/\////\//\
------------------------
/\/////\\///\\\//\\\\\/\
\///\/\/\\\\////\/\/\\\/
\///\/\/\\\\////\/\/\\\/
/\\\/\/\////\\\\/\/\///\
/\\\/\/\////\\\\/\/\///\
\/\\\\\//\\\///\\/////\/
------------------------
\//\////\/\/\/\/\\\\/\\/
<<><<>>>>><<>><<<<<>><>>
\\//\\///\\/\//\\\//\\//
------------------------
========================

```

All quilts have the same form:

* They are always 24 by 18.
* The top line (line 1) and bottom line (line 18) are `=` all the way across.
* Lines 2, 6, 13 and 17 are `-` all the way across.
* Lines 4 and 15 are the same random **horizontally symmetric** pattern of `<` and `>`.
* All other lines (3, 5, 7, 8, 9, 10, 11, 12, 14, 16) are filled with `/` and `\` in a completely random way such that the entire quilt remains **horizontally and vertically symmetric**.

Notice that when folding the quilt exactly in half, either vertically or horizontally, the *shapes* of the characters exactly match up. Don't get this confused with the characters themselves matching up. e.g. line 3 and line 16 are **not** identical, they are vertical mirror images.

# Challenge

Write a program or function that will print or return a random ASCII art quilt.

Due to the many hardcoded lines and the symmetry, the only real randomness comes from the first 12 characters on lines 3, 4, 5, 7, 8, 9:

* The first 12 characters on line 4 should be able to be any length 12 string of the characters `<` and `>`.
* The first 12 characters on lines 3, 5, 7, 8, 9 should be able to be any length 12 string of the characters `/` and `\` (independent of each other).
* These random strings are then mirrored accordingly to make the entire quilt.

**The shortest answer in bytes wins. Tiebreaker is earlier post.**

You may use pseudorandom number generators. (No, you don't need to prove that *all* 12 char string of `<>` or `/\` can be generated with you language's PRNG.)

The output may optionally contain a trailing newline, but no trailing spaces or other characters besides what's necessary for the quilt.

# Answer
> 15 votes
# CJam, ~~61~~ ~~60~~ ~~58~~ ~~55~~ ~~54~~ ~~52~~ 51 bytes

Shortened a bit with some help from Sp3000 and Optimizer.

```
"=-/</-///"{C*1{"<\/>"%1$W%\_W%er}:F~+mrC<1FN}%s3F(

```

Test it here.

## Explanation

As usual with these symmetric ASCII art challenges, I'm generating one quadrant and then expand it to the full thing by two appropriate mirroring operations.

For this explanation I should start with the function `F`, which I'm defining somewhere along the way, because it's used in three places for three different things:

```
{"<\/>"%1$W%\_W%er}:F

```

This expects an integer on the top of the stack, and a string beneath that. Its purpose is to reverse the string and also swap some characters, to get the mirroring right. The integer is either `1` or `3` and indicates whether (`1`) both brackets and slashes should be swapped or (`3`) only brackets should be swapped. Here is how it works:

```
"<\/>"            "Push a string with all four relevant characters.";
      %           "% applied to a string and an integer N (in any order) selects every
                   Nth character, starting from the first. So with N = 1 this just
                   leaves the string unchanged, but with N = 3 it returns a string
                   containing only < and >.";
       1$         "Copy the string we want to mirror.";
         W%       "% also takes negative arguments. Giving it -1 reverses the string.";
           \_     "Swap the two strings and duplicate the <\/> or <> string.";
             W%   "Reverse that one. Due to the symmetry of this string, we'll now
                   have the characters to be swapped at corresponding indices.";
               er "Perform element-wise transliteration on the reversed input string
                   to complete the mirroring operation.";

```

Now for the rest of the code:

```
"=-/</-///"                            "This string encodes the 9 different line types.
                                        Note that for the /\ and <> lines we only use
                                        one of the characters. This idea is due to
                                        Sp3000. Thanks! :)";
           {                   }%      "Map this block onto the characters.";
            C*                         "Repeat the character 12 times, turning it into
                                        a string.";
              1{...}:F~                "Define and call F on the resulting string. The
                                        reversal doesn't do anything, but the character
                                        swapping creates strings containing both \/ and
                                        <>.";
                       +mr             "Add the two halves together and shuffle them.";
                          C<           "Truncate to 12 characters. We've now got our
                                        random half-lines.";
                            1F         "Call F again to mirror the half-line.";
                              N        "Push a newline.";
                                 s     "Join all those separate strings together by
                                        converting the array to a string.";
                                  3F   "Perform one more mirroring operation on the
                                        half-quilt, but this time only swap < and >.
                                        This yields the correct full quilt, except
                                        there are two newlines in the centre.";
                                    (  "This slices the leading newline off the second
                                        half and pushes it onto the stack.";

```

The two halves and that single newline are then printed automatically at the end of the program.

# Answer
> 12 votes
# Python 3, ~~257~~ ~~229~~ ~~192~~ ~~185~~ ~~176~~ ~~149~~ 143 bytes

```
from random import*
k,*L=80703,
while k:s=eval("''"+".join(sample('--==<>\/'[k%4*2:][:2],2))"*12);L=[s]+L+[s[::(-1)**k]];k//=4
*_,=map(print,L)

```

With help from @xnor, we've finally caught up with JS!

Sample output:

```
========================
------------------------
///////////\/\\\\\\\\\\\
>><<<>><<<><><>>><<>>><<
/\/\\/\/\\/\/\//\/\//\/\
------------------------
//\\////\\/\/\//\\\\//\\
/////\\\/\/\/\/\///\\\\\
/\\//\\/////\\\\\//\\//\
\//\\//\\\\\/////\\//\\/
\\\\\///\/\/\/\/\\\/////
\\//\\\\//\/\/\\////\\//
------------------------
\/\//\/\//\/\/\\/\/\\/\/
>><<<>><<<><><>>><<>>><<
\\\\\\\\\\\/\///////////
------------------------
========================

```

## Explanation

*(Slightly outdated, will update later)*

`"444046402"` encodes the rows, with each digit referring to the starting index of the relevant 2-char substring of `'--==\/<>'`. Each individual row is built inside-out via repeated shuffling of the two chars (using `sample(...,2)`, since `random.shuffle` is unfortunately in-place) and string joining.

A simplified example of what the expansion might look like for the fourth row is:

```
''.join(['<','>']).join(['>','<']).join(['>','<']).join(['<','>']).join(['>','<'])

```

which would yield `><>><><<><`:

```
               ''
    <>         .join(['<','>'])
   >  <        .join(['>','<'])
  >    <       .join(['>','<'])
 <      >      .join(['<','>'])
>        <     .join(['>','<'])

```

The overall quilt is also built inside-out, as construction begins with the 9th/10th rows, working outward. To do this we start with an empty list `L`, which we add rows to the front and back of as we go via

```
L=[s]+L+[[s,s[::-1]][n<"5"]]

```

The `n<"5"` condition is to check whether we have a row consisting of `><`, in which case we append an identical row to the back, otherwise its reverse.

Finally, `*_,=` is to force the evaluation of `map` so printing occurs, and is just a shorter way to do `print("\n".join(L))`.

For a long time I had the function

```
g=lambda s:s.translate({60:62,62:60,92:47,47:92})

```

which takes a string and converts `/\><` to `\/<>` respectively, but I've finally managed to get rid of it :)

# Answer
> 6 votes
# Python 2, 300 bytes

This program uses `join, lambda, replace, sample, import` and other verbose functions, so it will not be winning any golf awards.

```
from random import*
f=lambda a,b,t:t.replace(a,'*').replace(b,a).replace('*',b)
k=lambda a:''.join(sample(a*12,12))
c='-'*24
e=k('<>')
h=e+f('<','>',e[::-1])
j=[d+f('/','\\',d[::-1])for d in[k('\\/')for i in'quilt']]
g=['='*24,c,j[0],h,j[1],c]+j[2:]
print'\n'.join(g+[f('/','\\',d)for d in g[::-1]])

```

The code before the auto-golfer got hold of it:

```
from random import *

change = lambda a,b,t: t.replace(a,'*').replace(b,a).replace('*',b)
pick = lambda a: ''.join(sample(a*12, 12))

innerline = '-' * 24
line4h = pick('<>')
line4 = line4h + change('<', '>', line4h[::-1])
diag = [d + change('/', '\\', d[::-1]) for d in [pick('\\/') for i in 'quilt']]

quilt = ['='*24, innerline, diag[0], line4, diag[1], innerline] + diag[2:]
print '\n'.join(quilt + [change('/', '\\', d) for d in quilt[::-1]])

```

A sample output:

```
========================
------------------------
\\\\/\////\\//\\\\/\////
<><<>>>><><><><><<<<>><>
/\\\\////\\\///\\\\////\
------------------------
\\\\//\///\\//\\\/\\////
//\//\\\\/\/\/\////\\/\\
\/\\\\/\//\/\/\\/\////\/
/\////\/\\/\/\//\/\\\\/\
\\/\\////\/\/\/\\\\//\//
////\\/\\\//\\///\//\\\\
------------------------
\////\\\\///\\\////\\\\/
<><<>>>><><><><><<<<>><>
////\/\\\\//\\////\/\\\\
------------------------
========================

```

# Answer
> 6 votes
# PHP, 408, 407, 402, 387, 379 bytes

I am not a good golfer, but this problem sounded fun so I gave it a try.

```
<?$a=str_replace;$b=str_repeat;function a($l,$a,$b){while(strlen($s)<$l){$s.=rand(0,1)?$a:$b;}return$s;}$c=[$b('=',12),$b('-',12),a(12,'/','\\'),a(12,'<','>'),a(12,'/','\\'),$b('-',12)];while(count($c)<9){$c[]=a(12,'/','\\');}for($d=9;$d--;){$c[$d].=strrev($a(['/','<','\\','>',1,2],[1,2,'/','<','\\','>'],$c[$d]));$c[]=$a(['/','\\',1],[1,'/','\\'],$c[$d]);}echo implode("
",$c);

```

Ungolfed code

```
<?php

    function randomString($length, $a, $b) {
        $string = '';
        while(strlen($string) < $length) {
            $string .= rand(0, 1) ? $a : $b;
        }
        return $string;
    }

    if(isset($argv[1])) {
        srand(intval($argv[1]));
    }

    $lines = [
        str_repeat('=', 12),
        str_repeat('-', 12),
        randomString(12, '/', '\\'),
        randomString(12, '<', '>'),
        randomString(12, '/', '\\'),
        str_repeat('-', 12)
    ];
    while(count($lines) < 9) {
        $lines[] = randomString(12, '/', '\\');
    }

    for($index = count($lines); $index--;) {
        $lines[$index] .= strrev(str_replace(['/', '<', '\\', '>', 1, 2], [1, 2, '/', '<', '\\', '>'], $lines[$index]));
        $lines[] = str_replace(['/', '\\', 1], [1, '/', '\\'], $lines[$index]);
    }

    echo implode("\n", $lines) . "\n";

?>

```

The ungolfed version has a little bonus: You can pass it an integer to seed `rand()` and get the same quilt each time for a seed:

```
php quilt.php 48937

```

This results, for example, in this beautiful, hand woven quilt:

```
========================
------------------------
/\\\////\\\/\///\\\\///\
><>><>><<<><><>>><<><<><
/\\\///\//\/\/\\/\\\///\
------------------------
/\\/\\\/\\/\/\//\///\//\
/\\\\/\//\\/\//\\/\////\
\/\\/\/\////\\\\/\/\//\/
/\//\/\/\\\\////\/\/\\/\
\////\/\\//\/\\//\/\\\\/
\//\///\//\/\/\\/\\\/\\/
------------------------
\///\\\/\\/\/\//\///\\\/
><>><>><<<><><>>><<><<><
\///\\\\///\/\\\////\\\/
------------------------
========================

```

**Edit**: Turns out my first version did not return a correct quilt. So I fixed it. Funny enough, the fix is even shorter.

# Answer
> 6 votes
# APL (~~53~~ 58)

It's not *quite* as symmetrical as I thought it was, unfortunately. Fix cost me 5 characters and now I'm out of the running.

```
L←+,3-⌽⋄'==--/\<><'[↑(732451451260688⊤⍨18/8)+L{L?12⍴2}¨⍳9]

```

Explanation:

* `L←+,3-⌽`: L is a function that returns its argument followed by 3 - the reverse of its argument
* `L{L?12⍴2}¨⍳9`: generate 9 lines of 12 random values from \[1,2\] plus their reverse, then the reverse of those 9 lines
* `732451451260688⊤⍨18/8`: generate the list `0 2 4 6 4 2 4 4 4 4 4 4 2 4 _7_ 4 2 0` (that's where the damn asymmetricality is)
* `+`: for each line, add the corresponding number to each value
* : format as matrix
* `'==--/\<><'[`...`]`: for each of the numbers in the matrix, select the character from the string at that position

Output:

```
========================
------------------------
///////\\///\\\//\\\\\\\
<<><<><><<<<>>>><><>><>>
\\\\\//\/\\\///\/\\/////
------------------------
/\///\\/\/\/\/\/\//\\\/\
\////////\//\\/\\\\\\\\/
\\/\\\//\///\\\/\\///\//
//\///\\/\\\///\//\\\/\\
/\\\\\\\\/\\//\////////\
\/\\\//\/\/\/\/\/\\///\/
------------------------
/////\\/\///\\\/\//\\\\\
<<><<><><<<<>>>><><>><>>
\\\\\\\//\\\///\\///////
------------------------
========================

```

# Answer
> 4 votes
# JavaScript (ES6) 169 ~~195 201~~

**Edit** 6 bytes saved thx @nderscore. Beware, the newline inside backquotes is significant and counted.

**Edit2** simplified row building, no need of `reverse` and `concat`

```
F=(o='')=>[...z='/\\/-/<\\-='].map((c,i,_,y=[z,'\\/\\-\\>/-='],q=[for(_ of-z+z)Math.random(Q=k=>q.map(v=>r=y[v^!k][i]+r+y[v^k][i],r='')&&r+`
`)*2])=>o=Q()+o+Q(i!=5))&&o

```

*Run snippet to test* (in Firefox)

```
F=(o='')=>[...z='/\\/-/<\\-='].map((c,i,_,y=[z,'\\/\\-\\>/-='],q=[for(_ of-z+z)Math.random(Q=k=>q.map(v=>r=y[v^!k][i]+r+y[v^k][i],r='')&&r+`
`)*2])=>o=Q()+o+Q(i!=5))&&o

Q.innerHTML=F()
```

```
<pre id=Q style='font-size:9px;line-height:9px'>
```

# Answer
> 4 votes
# Ruby, 162 155

I like this one because it made me learn to abuse backslashes in both string literals and `String#tr`. The code isn't terribly clever otherwise, just compact.

```
a='/\\'
b='\\\/'
t=Array.new(9){x=''
12.times{x+=a[rand(2)]}
x+x.reverse.tr(a,b)}
t[0]=?=*24
t[1]=t[5]=?-*24
t[3].tr!a,'<>'
puts t,((t.reverse*'
').tr a,b)

```

# Answer
> 3 votes
# Pyth, 57 ~~59 61~~

```
J"\<>/"K"\/"L+b_mXdK_Kbjbym+d_XdJ_JmsmOk12[\=\-K-JKK\-KKK

J"\<>/"K"\/"jbu++HGXHK_Km+d_XdJ_JmsmOk12[KKK\-K-JKK\-\=)Y

```

Thanks a lot to @Jakube for coming up with these 57 byte versions.

Algorithm very similar to Martin's. (Revised) Explanation to come.

Try it online

Explanation:

```
=G"\<>/"                            : Set G to be the string "\<>/"
K"\/"                               : Set K to be the string "\/"
Jm+d_XdG_GmsmOk12[\=\-K"<>"K\-KKK;  : Set J to be the top half of the carpet
                 [\=\-K"<>"K\-KKK;  : Make a list of possible chars for each row
          msmOk12                   : for each element of that list,
                                    : make a list of 12 randomly chosen characters
                                    : from it, then join them
Jm+d_XdG_G                          : for each element of that list,
                                    : make a new list with the old element,
                                    : and its horizontal reflection
jb+J_mXdK_KJ                        : Print the whole carpet
     mXdK_KJ                        : For each element of J make its vertical reflection

```

# Answer
> 2 votes
# J, ~~56~~ 54 bytes

```
'=/\<>--></\'{~(-,|.)0,(3(2})8$5,3#1)+(,1-|.)"1?8 12$2

```

Usage:

```
   '=/\<>--></\'{~(-,|.)0,(3(2})8$5,3#1)+(,1-|.)"1?8 12$2
========================
------------------------
///\\\\/\///\\\/\////\\\
><<><><>><>><<><<><><>><
\\/\//\\/\//\\/\//\\/\//
------------------------
\/\/\//////\/\\\\\\/\/\/
/\/\\//\//\\//\\/\\//\/\
//\\\\/////\/\\\\\////\\
\\////\\\\\/\/////\\\\//
\/\//\\/\\//\\//\//\\/\/
/\/\/\\\\\\/\//////\/\/\
------------------------
//\/\\//\/\\//\/\\//\/\\
><<><><>><>><<><<><><>><
\\\////\/\\\///\/\\\\///
------------------------
========================

```

1 byte thanks to @FUZxxl.

Explanation coming soon.

Try it online here.

# Answer
> 1 votes
# Javascript (*ES7 Draft*) 174 168 146

Some inspiration taken from @edc65

Edit: Thanks to edc65 for some ideas to optimize building of rows.

```
F=(o='')=>[for(i of'555357531')(z=[for(_ of c='==--/\\<>golf')Math.random(r=x=>z.reduce((s,y)=>c[w=i^y^x]+s+c[w^1],'')+`
`)*2],o=r()+o+r(i<7))]&&o

```

---

**Demonstration: (*Firefox only*)**

```
F=(o='')=>[for(i of'555357531')(z=[for(_ of c='==--/\\<>golf')Math.random(r=x=>z.reduce((s,y)=>c[w=i^y^x]+s+c[w^1],'')+`
`)*2],o=r()+o+r(i<7))]&&o

document.write('<pre>' + F() + '</pre>');
```

---

**Commented:**

```
// define function, initialize output to ''
F = (o = '') =>
    // loop through character indexes of first 9 lines
    [
        for (i of '555357531')(
            // build array of 12 random 0/1's, initialize character list
            z = [
                for (_ of c = '==--/\\<>golf')
                    Math.random(
                        // define function for generating lines
                        // if x is true, opposite line is generated
                        r = x =>
                            z.reduce(
                                (s, y) =>
                                    c[w = i ^ y ^ x] + s + c[w ^ 1],
                                ''
                            ) + `\n`
                    ) * 2
            ],
            // build new lines and wrap output in them
            // x true in the second line for indexes < 7 (not character '>')
            o = r() + o + r(i < 7)
        )
    ]
    // return output
    && o

```

# Answer
> 1 votes
# Python 295 287 227 bytes

Not that great but I'll post it anyway:

```
from random import*
m,d=[],dict(zip("\/<>=-","/\><=-"))
v=lambda w:[d[x]for x in w]
for e in '=-/>/-///':f=[choice([e,d[e]])for x in[0]*12];t=''.join(f+v(f[::-1]));print t;m+=''.join(e=='/'and v(t)or t),
print'\n'.join(m[::-1])

```

If you want an explanation just ask me.

# Answer
> 0 votes
## Pharo 4, 236

```
|s i f v h|s:='====----/\/\/<><<>'.f:=[:c|s at:(s indexOf:c)+i].v:=#(),'=-/</-///'collect:[:c|h:=(String new:12)collect:[:x|i:=2atRandom.f value:c].i:=1.h,(h reverse collect:f)].i:=3.String cr join:v,(v reverse collect:[:k|k collect:f])

```

or formatted normally:

```
|s i f v h|
s:='====----/\/\/<><<>'.
f:=[:c|s at:(s indexOf:c)+i].
v:=#() , '=-/</-///'
  collect:[:c|
    h:=(String new:12)collect:[:x|i:=2atRandom.f value:c].
    i:=1.
    h,(h reverse collect:f)].
i:=3.
String cr join:v,(v reverse collect:[:k|k collect:f])

```

Explanation:

The string `s:='====----/\/\/<><<>'` together with the block `f:=[:c|s at:(s indexOf:c)+i]` are here both for tossing the characters and for reversing the patterns...

* For i=1, it performs horizontal reversion (`/` \<-\> `\` , `<` \<-\> `>` ).
* For i=3, it performs vertical reversion (`/` \<-\> `\`)
* For i=1 or 2 atRandom, it toss among `/` or `\`, `<` or `>`

`'=-/</-///'` encodes the character type `c` that will feed the block `f` for the 9 first lines.

`#() , '=-/</-///'` is a concatenation trick for transforming the String into an Array and thus collecting into an Array.

The rest is simple concatenation after applying the horizontal/vertical symetry.

```
========================
------------------------
\\/\/\\\\/\/\/\////\/\//
>>>><><><>><><<><><><<<<
\/\/\//\///\/\\\/\\/\/\/
------------------------
/\//\/\/////\\\\\/\/\\/\
\\//\//\\\/\/\///\\/\\//
////\\/\/\//\\/\/\//\\\\
\\\\//\/\/\\//\/\/\\////
//\\/\\///\/\/\\\//\//\\
\/\\/\/\\\\\/////\/\//\/
------------------------
/\/\/\\/\\\/\///\//\/\/\
>>>><><><>><><<><><><<<<
//\/\////\/\/\/\\\\/\/\\
------------------------
========================

```

# Answer
> 0 votes
## Squeak 4.X, 247

```
|r s h m n p|s:='==--/\<>'.r:=(1<<108)atRandom.h:=''.m:=0.(16to:0by:-2),(0to:16by:2)do:[:i|n:=3bitAnd:28266>>i.p:=0.(11to:0by:-1),(0to:11)do:[:j|h:=h,(s at:n*2+1+(r-1>>(6*i+j)+(101>>(3-n*4+m+p))bitAnd:1)).j=0and:[p:=1]].i=0and:[m:=2].h:=h,#[13]].h

```

Or formatted:

```
|r s h m n p|
s:='==--/\<>'.
r:=(1<<108)atRandom.
h:=''.
m:=0.
(16to:0by:-2),(0to:16by:2) do:[:i|
  n:=3 bitAnd: 28266>>i.
  p:=0.
  (11to:0 by:-1),(0to:11) do:[:j|
    "h:=h,(s at:n*2+1+((r-1bitAt:6*i+j+1)bitXor:(101bitAt:3-n*4+m+p))). <- originally"
    h:=h,(s at:n*2+1+(r-1>>(6*i+j)+(101>>(3-n*4+m+p))bitAnd:1)).
    j=0and:[p:=1]].
  i=0and:[m:=2].
  h:=h,#[13]].
h

```

Explanations:

`s:='==--/\<>'.` obviously encodes the four posible pairs.

`r:=(1<<108)atRandom.` toss 108 bits (in a LargeInteger) for 9 rows\*12 columns (we toss the == and -- unecessarily but performance is not our problem).

`h:=''`is the string where we will concatenate (Schlemiel painter because a Stream would be too costly in characters).

`(16to:0by:-2),(0to:16by:2)do:[:i|` is iterating on the rows (\*2)

`(11to:0by:-1),(0to:11) do:[:j|` is iterating on the columns

`28266` is a magic number encoding the pair to be used on first 9 lines.
It is the bit pattern `00 01 10 11 10 01 10 10 10`, where 00 encodes '==', 01 '--', 10 '/\\' and 11 '\<\>'.

`101` is a magic number encoding the horizontal and vertical reversion.
It is the bit pattern `0000 0000 0110 1010`, encoding when to reverse (1) or not (0) the first (0) or second (1) character of each pair '==' '--' '/\\' and '\<\>', for the vertical symetry and horizontal symetry.

`n:=3 bitAnd: 28266>>i` gives the encoding of character pair for row i/2 (0 for '==', 1 for '--', 2 for '/\\' and 3 for '\<\>').

`(r-1 bitAt: 6*i+j+1)` pick the random bit for row i/2 column j (1 is the rank of lowest bit thus we have a +1, k atRandom toss in interval \[1,k\] thus we have a -1).

`(101 bitAt: 3-n*4+m+p)` pick the reversal bit: (3-n)\*4 is the offset for the group of 4 bits corresponding to the pair code n, m is the vertical reversion offset (0 for first 9, 2 for last 9 rows), p is the horizontal reversion offset (0 for first 12, 1 for last 12 columns)+1 because low bit rank is 1.

`bitXor:` performs the reversion (it answer an offset 0 or 1), and `s at:2*n+1+bitXor_offset` pick the right character in s.

But `(A>>a)+(B>>b) bitAnd: 1` costs less bytes than `(A bitAt:a+1)bitXor:(B bitAt:b+1)`thus the bitXor was rewritten and offset +1 on p is gone...

`h,#[13]` is an ugly squeakism, we can concatenate a String with a ByteArray (containing code for carriage return).

```
========================
------------------------
/\/\\\/\//\/\/\\/\///\/\
><>><<>>>><<>><<<<>><<><
////\\////\\//\\\\//\\\\
------------------------
/\\\/\\/\\//\\//\//\///\
\/\\/\//////\\\\\\/\//\/
\\\//\\\////\\\\///\\///
///\\///\\\\////\\\//\\\
/\//\/\\\\\\//////\/\\/\
\///\//\//\\//\\/\\/\\\/
------------------------
\\\\//\\\\//\\////\\////
><>><<>>>><<>><<<<>><<><
\/\///\/\\/\/\//\/\\\/\/
------------------------
========================

```

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