What is the Sandbox?





Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily


  • 1

2569 Answers 2569


Inversion languages



  1. It halts in both A and B.

  2. It halts in A but not B.

  3. It halts in B but not A.

  4. It doesn't halt in either A or B.


Further rules on languages




Your answer should contain the following information.

  1. A concrete description of both languages

  2. Proofs that each language as described is Turing complete.











  • 1
  • 2
  • 2
  • 1
  • 1
  • 1



Two lasers between two mirrors


|*  |      |
|   |      |
|   |  ----+
|   |      |
|   |      |
|   |      |
|   +---   |
|          |
|          |
|          |
  • Astrisk(*): laser starting point.
  • Whitespace: passable.
  • Any other character is a reflective obstacle.


|\  |   /\ |
| \ |  /  \|
|  \| /----+
|  /|/   /\|
| / |\  / /|
|/  | \/ / |
|\  +---/  |
| \    /   |
|  \  /    |
|   \/     |


  • When you can't move horizontally, reverse horizontal direction.
  • When you can't move vertically, reverse vertical direction.

Simplifying factors:

  • Let's just say the laser always goes the same way.
  • The map is always a rectangle.
  • Just the one laser.

It'll probably just be a golfing challenge.

  • 1
  • 3


Compress the previous answer








  • 1
  • 1
  • 1
  • 1

Rebuild My Scrabble Board



Each move includes 4 pieces of information





  • 15x15 matrix
  • Unused spaces display as a period .
  • No leading spaces allowed.
  • Trailing spaces allowed.
  • One line feed at the end of each row.
  • Up to one leading and one trailing line feed permitted.



What you don't need to worry about:









  • Standard loopholes are forbidden.
  • 3
  • \$\begingroup\$ @JayCe ok for both. I need to finish this and turn it into an actual challenge \$\endgroup\$ – manassehkatz Jun 11 '18 at 3:53
  • 1

Find the minimum set of letters to buy

Imagine that you own a board like this:

Black letter board









This would of course be a code-golf challenge

  • 1


Formic Functions 3: Memory




The arena




Ant abilities



Provide a function body



No access to outside data





Input and output



Cells are numbered in this order:

 0 1
5 6 2
 4 3


color: a number from 1 to 8
food: 0 or 1

[Is 8 colors perhaps too many?]


food: 0 or more (maximum 1 for a worker)
queen: true or false
friend: true or false
memory: memory string when friendly, otherwise undefined





cell: a number from 0 to 6 (mandatory)
color: a number from 1 to 8 (optional)
spawn: a string (optional)
memory: a string (optional)





[Should changing own memory take a turn?]




Example outputs:

{cell:0}: move to cell 0

Invalid outputs:


[Missed any?]



Turn order


Limit on number of players


[Good max number of players?]

Time limit per turn


[Enough time?]




  • Exceeding the time limit as described.
  • Returning an invalid move as described under Output.
  • The cell to produce a worker on contains an ant.
  • A worker is trying to produce a worker.

[Did I miss any?]


Multiple answers and editing







[Scoring mechanism subject to change.]


  • 2
    \$\begingroup\$ 8000 turns is too few, 65k of memory is way too much. \$\endgroup\$ – Draco18s Mar 7 '18 at 22:12
  • 1
  • 1
  • 3

How many times was the function called?

Inspired by this question.





f() returns 1
f();f() returns 1 2



  • 1
  • 1

Mixed alphanumeric sort



Sorting is done according to the following algorithm:

  • The empty string is sorted first
  • Single token strings are sorted as follows:




  • You can choose to process uppercase characters instead of lowercase ones
  • Standard loopholes apply
  • Lowest byte count wins

Sandbox questions


Diagonalize a Blackbox

todo: test cases

more math explaination?

better challenge definition?



Or, more compactly:








This affects the transformation as well:








The Challenge















Test Cases




  • More I won't disclose
  • Probably more I haven't thought of

Double JSON

Input a JSON, double every values in it, and output.


A String. It is guaranteed to be a valid[1] JSON.


A String. It should be a valid JSON.

For each value in the inputed JSON:

  • If the value is number, double it
    • 42 -> 84
  • If the value is string, repeat it
    • "data" -> "datadata"
  • If the value is an array, double its items recursively, and repeat the array twice
    • [1,2,3] -> [2,4,6,2,4,6]
  • If the value is object, keep keys as is, double its values recursively
    • {"a":1} -> {"a":2}
  • If the value is not a type listed above, keep it as is

Test Cases

42 -> 84
-1 -> -2
"abc" -> "abcabc"
true -> true
null -> null
{} -> {}
[] -> []
{"abc":42} -> {"abc":84}
{"true":42,"42":true} -> {"true":84,"42":true}
{"length":1,"0":true} -> {"length":2,"0":true}
[false] -> [false,false]
[42] -> [84,84]
[[42,"abc"]] -> [[84,"abcabc",84,"abcabc"],[84,"abcabc",84,"abcabc"]]
[[[]]] -> [[[],[]],[[],[]]]
{"a":4,"b":[1,2,3],"c":{"a":5}} -> {"a":8,"b":[2,4,6,2,4,6],"c":{"a":10}}


  • This is code-golf.
  • Output JSON should be equivalent to the sample output
    • No missing / unnecessary / redundancy values allowed;
    • Order of keys in object does not matter. But order of items in an array does matter;
    • Whitespaces are allowed as long as the output is valid JSON;
    • Number may be represented in any valid format with in acceptable floating point errors (<1%);
  • To keep this challenge easy:
    • Strings and keys of objects in JSON may only contain printable ASCII;
    • Inputed numbers are always integers;
    • No need to worry about number overflow when double it;
    • No duplicate keys in Object; And your output should not contain duplicate keys either;
  • If you chose implementing a function, input / output should be a string instead of an object / a dictionary.
    • Because it is hard to define a proper data type for JSON across languages.

[1]: There are more than one JSON specifications. I don't think they could make anything here different. Just in case, you may chose any one as your like. And here we define a subset of your specification you need to handle:

  • JSON is a lightweight data-interchange format. A value in json may be one of the following types: number, string, boolean, null, object, array.
  • number: numbers are always decimal, in format /-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][-+]?[0-9]+)?/;
    • In this question, inputted number would always be integer in format /-?[1-9][0-9]*|0/;
  • string: Start and end with ", contain Unicode characters or escape sequences;
    • In this question, inputted string will only contain printable ASCII excluding " or \, without any escape sequence;
  • boolean: literally true or false;
  • null: literally null;
  • array: Starts with [, ends with ], contains zero or more values spited by ,;
  • object: A dictionary, starts with {, ends with }, contains zero or more key-value pairs. Keys are string, values are any valid JSON values. A : placed between each pair of key and value.
  • A valid json allow whitespaces characters between any tokens. But its guaranteed that input will only contain whitespace characters in string.
  • \$\begingroup\$ If the value is an object, should we keep the object as it is or go though the object properties as well? Example: {"a": 4, "b": [1, 2, 3], "c": {"a": 5}} => {"a": 8, "b": [1, 2, 3, 1, 2, 3], "c": {"a": 5}} or {"a": 8, "b": [1, 2, 3, 1, 2, 3], "c": {"a": 10}}? \$\endgroup\$ – Luis felipe De jesus Munoz Jul 23 '18 at 13:13
  • 1
    \$\begingroup\$ I like this challenge, but you're assuming everyone knows what JSON is down to the technical details, making the challenge not self-contained. I would explicitly define what the format of the input and the output might be right in the question itself. This isn't so hard - I believe the definition is recursive. That is also a better way to avoid the "more than one specification" problem than just saying "don't worry about it". \$\endgroup\$ – ngm Jul 23 '18 at 18:55
  • \$\begingroup\$ @LuisfelipeDejesusMunoz It should be {"a":8,"b":[2,4,6,2,4,6],"c":{"a":10}}. I would add it to testcase. \$\endgroup\$ – tsh Jul 24 '18 at 1:24
  • \$\begingroup\$ I agree with what ngm said, challenges should be self-contained especially in cases like this where possible ambiguity could arise. If not you should define what a JSON-specification is which is probably way more difficult. Also what happens with arrays of objects? \$\endgroup\$ – ბიმო Jul 26 '18 at 12:30
  • \$\begingroup\$ And a test-case with a string that contains a valid JSON-object which would be doubled should be added, eg. {"json": "{\"nine\":9}"} or something, or even {"json": "[1,2,3]" }. \$\endgroup\$ – ბიმო Jul 26 '18 at 12:33
  • \$\begingroup\$ (Just looking at the specs leads to many questions/test cases like the one about the array or a lot about numbers: 1e9, -1e9, 1.234, -1.234, 1e-18, 1E+10, 1.23E-8 etc.? What about floating-point precision issues? Other special test cases: [{}], {"true":"false"},"" or empty input) \$\endgroup\$ – ბიმო Jul 26 '18 at 12:43
  • \$\begingroup\$ @OMᗺ With the explanation in the question: Input numbers are always integers, so /-?[1-9]\d*|0/. But you are free to handle it as integer or float. If you handle it as float, output should in +-1%. Empty input is not a valid JSON. \$\endgroup\$ – tsh Jul 27 '18 at 1:13

Making a Mountain out of a Molehill


Recognize the hardest context-free language


The language





           C           C        C        C    Split by C


             | "(" <balanced> ")"
             | "[" <balanced> ")"

The task



The lowest byte count wins, and other standard rules apply.

Test cases



Number of Unit Squares Intersecting a Circle


(Credit to user202729 for the illustration)

OEIS sequence A234300 is defined thusly:



Range       Term
0           0
(0,1)       1
1           1
(1,√2)      3
√2          2
(√2,2)      3
2           3
(2,√5)      5
√5          3
(√5,√8)     5
√8          4





  • 1

Non-overlapping Matrix Sum



A nonempty list of nonempty arrays of integers.


An integer that represents the maximum sum.


Input -> Output
[[1]] -> 1

Output Hello, World! ... sometimes



Hello, World!


This is a , so the shortest program in bytes wins.

Example program


const THRESHOLD = 0.5;
let randomFloat = Math.random();

let output;

if(randomFloat < THRESHOLD) {
    output = "Hello, World!";
else {
    output = randomFloat.toString();


Try it online!

  • 2

Universal Self-correcting Program







Triple redundancy codes



AAA => A
AAB => A


Putting it together






The score is Score = Size / 2^Tolerance

Lowest score wins.


Detect if your program has been mutated



Meta radiation hardener


  • 2
  • \$\begingroup\$ Again Lenguage win lol \$\endgroup\$ – l4m2 Jan 8 at 14:53

Speeding up powers of 2




Expected output if 1 is included:

1 # after, wait 1/1 seconds
2 # after, wait 1/2 seconds
4 # after, wait 1/3 seconds
8 # after, wait 1/4 seconds
16 # after, wait 1/5 seconds
# etc...

Expected output if 1 is not included:

2 # before/after, wait 1/1 seconds
4 # before/aftert, wait 1/2 seconds
8 # before/after, wait 1/3 seconds
16 # before/after, wait 1/4 seconds
# etc...


  • How should I improve the wording?
  • What potential ambiguities or language limits are there?
  • Is this too similar to a preexisting challenge?


  • 1

Static Code Analysis Battle!



Here are the rules:

    1. Use randomness or other non-deterministic code.
    3. Use time.sleep.
    4. Alter or access the state of the controller.
    6. Anything else that a pure function could not do.



Classic VCS ASCII Adventure


  • 1

Square Sum Problem

Your task is to rearrange the sequence 1 to n so that every adjacent pair sum into a square number.


An integer n.


A sequence such that

  1. There is no duplication.
  2. Every adjacent pair sums into a square number.
  3. Every number from 1 to n is present in the sequence.
  4. No number outside of that is present in the sequence.

If there are more than one answers, pick one. If there are none, do anything.


Because this is , the shortest code wins


Valid answer:

8 1 15 10 6 3 13 12 4 5 11 14 2 7 9

Invalid answer:

8 1 15 10 6 3 13 12 4 5 11 14 2 7 9 16
6 8 1 15 10 6 3 13 12 4 5 11 14 2 7 9
17 8 1 15 10 6 3 13 12 4 5 11 14 2 7 9 16
1 3 6 10 15 2 7 9 4 5 11 8 12 13 14
  • 1
    \$\begingroup\$ Your 14 test case suggests that this isn't achievable for every n. If that is indeed the case then I would suggest that we only need handle values of n for which it is achievable as input validation rarely goes down well here. \$\endgroup\$ – Shaggy Apr 7 at 1:15
  • \$\begingroup\$ @Shaggy Well, the question is actually "Does the series exist, and if exists, what is the series." But if that question is not desirable, I'll fix it. \$\endgroup\$ – Akangka Apr 8 at 6:02
  • 1
    \$\begingroup\$ To me, they are separate challenges: "Does the series exist" is a decision-problem challenge and "What is the series is" a sequence challenge. \$\endgroup\$ – Shaggy Apr 9 at 9:23
  • \$\begingroup\$ Do you want to add anything about exhaustive searches? I could just try every combination under the current rules... \$\endgroup\$ – Phil H Apr 9 at 10:58
  • \$\begingroup\$ @PhilH now that you say that. I have bad faith in this challenge. \$\endgroup\$ – Akangka Apr 10 at 1:34

The Forest Game (KotH, WIP)


You have been given a space of land to plant trees in. Unfortunately, due to an administrative mix-up, so have 4 other people. You are in a competition with them to make the most money out of your trees within the next 100 years.

The map

A 10 by 10 grid, representing the area of land. Each square will be one of the following:

  • A number, 0 to 4, representing a player
  • ., representing a seed (more later)
  • i, representing a sapling
  • T, representing a tree
  • F, an ongoing fire
  • , an empty space


Actions, given by your program, are 1 or 2 characters long. The first is the type:

  • . - plant a seed, costs 1
  • i - plant a sapling, costs 10
  • F - start a fire, costs 5
  • m - move, costs 0
  • w - work, gains 1 (what you do for easy points/to do nothing)
  • - - harvest, variable gains (see below)

Anything else as the first character will result in ignored command. The second character is one of `^'<>,v., a direction, which refers to the relative location of the square on which to perform the command:

` ^ '     NW N NE
<   > --> W     E
, v .     SW S SE

For the work command, the second character need not be present, but must be one of the eight if it is. An invalid command is ignored.


Seeds become saplings, saplings trees. After 5 rounds (25 turns), a seed becomes a sapling with the probability \$\frac{8 - C}8\$ where \$C\$ is the number of nearby (diagonally or orthogonally adjacent) saplings or trees. Saplings become trees after 7 rounds, with the same probability (\$C\$ here is only trees). This is worked out from the top left, going across each row in turn, meaning that each seed/sapling growth may be affected by saplings/trees created that turn.


When harvested, saplings/trees add to your score. Saplings are valued at 15, trees at 20. After every round, a tree gains 1 point of value, up to a maximum of 40 points. Seeds cannot be harvested, nor can other players' saplings/trees.


Fires spread from the point you set them to all nearby trees and saplings, unless there is a player other than you also nearby. Example:

  T          T          T          T        
  i5         i5         F5          5       
TTTTTT --> FFTTTT -->   FTTT -->    TTT
F1 ii       1 ii       1 ii       1 ii      
  i          i          i          i        

Where 1 is you and 5 is the other player. Each step represents one turn (not one round).


Each game, you start with 15 points, and loose/gain them as described in the 'actions' and 'value' sections. The aim is to be the player with the most points at the end of 100 rounds (500 turns in total). Each game will be played 6 times, and then repeated until one player has won more than any of the others. This collection of 6+ games is a 'match'. Every two days, if there have been new players added, the players will be split up into groups of 5, padded out with simple bots of mine if necessary. The winners of each of these will be split into groups of five and the above process repeated until there is only one group of five, the winner of which is the victor!


Your submission should be a Python 3 program, with a method run defined in the global scope. This method will be called with the following parameters:

  • map_ - a list of ten lists of single character strings. This will be a deep copy of the map, each string is one of 01234.iTF, representing that square.
  • round_ - the round number
  • points - a list of integers, representing the number of points each player has, in order.
  • num - whereabouts on the points list you come, also the number representing you and where you come in the turn order.

It should output the two/one character string mentioned above.


WIP, extremely buggy

map, 20 by 20 squares,
starts empty with randomly placed players
square can be:
' ' - empty
'1' - [0-4], player
'.' - seed
'i' - sapling
'T' - tree
'F' - flames

'm' - move
'i' - plant sapling
'.' - plant seed
'-' - harvest tree
'F' - start fire
'w' - work (dir optional and ignored)
'?' - other, nothing

each action other than move should be accompanied by
a direction, [<>^v`,'.O] = (W,E,N,S,NW,SW,NE,SE,O)

 - go out if person nearby other than starter
 - turn every nearby tree/sapling to flames, 33% each
 - go out, leave ' '

'm' - none
'i' - -10
'.' - -1
'-' - +15 for sapling, +20 for tree + turns living max. +40
'F' - -1
'w' - +1
'?' - none

. > l - (8-nearby [lT])/8 chance, after 5 turns
l > T - (8-nearby [T])/8 chance, after 7 turns
   T+ - +1 value every turn, max. 40

every five turns, tree drops a seed in an empty nearby square
start at 10 points
game end after 100 rounds


import random, os, time, sys

class Item(object):
    def __init__(self, x, y, game, creator=None):
        self.x = x
        self.y = y
        self.game = game
        self.creator = creator

class Flame(Item):
    def update(self, around):
        burn = []
        for i in around:
            if str(i) in map(str, range(6)):
                if str(i) != str(self.creator):
            elif str(i) in 'Ti':
        for i in burn:
            self.game.place(Flame, i.x, i.y, self.creator)
        self.game.place(Empty, self.x, self.y)

    def __str__(self):
        return 'F'

class Seed(Item):
    def __init__(self, x, y, game, creator, count=25, _next=None):
        _next = _next or Sapling
        super(Seed, self).__init__(x, y, game, creator)
        self.counter = count
        self.creator = creator
        self.next = _next

    def update(self, around):
        self.counter -= 1
        if self.counter:
        pos = sum(str(x) in 'Ti' for x in around)
        if random.randrange(8) in range(pos):
            self.game.place(Empty, self.x, self.y)
        self.game.place(self.next, self.x, self.y, self.creator)

    def __str__(self):
        return '.'

class Sapling(Seed):
    def __init__(self, x, y, game, creator):
        super(Sapling, self).__init__(x, y, game, creator, 35, Tree)

    def __str__(self):
        return 'i'

    def __int__(self):
        return 15

class Tree(Item):
        super(Tree, self).__init__(x, y, game, creator)
        self.val = 20

    def update(self, around):
        self.val += 1
        if self.val > 40:
            self.val = 40

    def __str__(self):
        return 'T'

    def __int__(self):
        return self.val

class Empty(Item):
    def update(self, around): pass

    def __str__(self):
        return ' '

class Player(object):
    def __init__(self, x, y, name, game):
        self.game = game
        self.x = x
        self.y = y
        self.name = name
        self.around = (None,) * 8
        self.points = 15

    def update(self, around):
        self.around = around

    def command(self, text):
        text = "mv"
        if len(text) != 2:
            if len(text) != 1:
                self.points += text[0] == 'w'
        dirs = "`^'<p>,v." #p = placeholder
        if text[1] not in dirs:
        ny = self.y + (dirs.index(text[1]) % 3) - 1
        nx = self.x + int(dirs.index(text[1]) / 3) - 1
        if (nx, ny) == (self.x, self.y):
        itm = self.around["`<,^v'>.".index(text[1])]
        if text[0] == 'w':
            self.points += 1
        elif ny < 0 or nx < 0 or not itm:    #remove for wrapping
        if text[0] == 'm':
            if str(itm) == ' ':
                self.game.move(self.x, self.y, nx, ny)
        elif text[0] == 'F' and self.points > 0:
            if str(itm) in 'Ti':  #never!!!
                self.game.place(Flame, nx, ny, self)
                self.points -= 1
        elif text[0] == '.' and self.points > 0:
            if str(itm) == ' ':
                self.game.place(Seed, nx, ny, self)
                self.points -= 1
        elif text[0] == 'l' and self.points > 9:
            if str(itm) == ' ':
                self.game.place(Sapling, nx, ny, self)
                self.points -= 1
        elif text[0] == '-':
            if str(itm) in 'Ti':
                if itm.creator == str(self):  #never!!
                    self.game.place(Empty, nx, ny)
                    self.points += int(itm)

    def __str__(self):
        return str(self.name)

class Game(object):
    def __init__(self, players, names, size=20):
        self.map = []
        choose = []
        self.names = names
        for x in range(size):
            for y in range(size):
                self.map[-1].append(Empty(x, y, self))
                choose.append((x, y))
        self.players = {}
        for i in range(len(players)):
            pos = choose.pop()
            p = Player(*pos, str(i), self)
            self.players[players[i]] = p
            self.map[pos[0]][pos[1]] = p

    def round(self, number):
        for i in self.players:
            self.turn(i, number)
            if not 'idlelib.run' in sys.modules:
                print(' |0 1 2 3 4 5 6 7 8 9')
                [print(str(self.map.index(i)) + '|' + ' '.join(str(j) for j in i)) for i in self.map]
        if number != 100:
            [print(' '.join(str(j) for j in i)) for i in self.map]
            for i in self.players:
                print(names[i], self.players[i].points, sep=': ')

    def turn(self, player, rn):
        points = []
        n = 0
        for i in self.players:
            if i == player:
                num = n
        text = player(map_=[x[:] for x in self.map], num=num, points=points, round_=rn)

    def place(self, item_t, x, y, creator=None):
            itm = item_t(x, y, self, creator)
            self.map[x][y] = itm
            return itm
        except IndexError:

    def move(self, ox, oy, x, y):
            itm = self.map[ox][oy]
            self.place(Empty, ox, oy)
            self.map[x][y] = itm
            itm.x = x
            itm.y = y
        except IndexError:

    def updatemap(self):
        for x in range(len(self.map)):
            for y in range(len(self.map[x])):
                around = []
                for rx in (-1, 0, 1):
                    for ry in (-1, 0, 1):
                        if rx or ry:
                            except IndexError:
                if str(self.map[x][y]).strip():
                    print(' '.join(str(i) for i in around[:3]),
                          ' '.join(str(i) for i in around[3:6]),
                          ' '.join(str(i) for i in around[6:]),
                          str(self.map[x][y]), sep='\n', end='-----')

import burnitall, flamingworker, hardworker, plantandwait, seedandreap
allnames = ('Burn It All', 'Flaming Worker',
            'Hard-worker', 'Plant And Wait',
            'Seed And Reap')
allplayers = (burnitall, flamingworker, hardworker, plantandwait, seedandreap)

players = []
names = {}
for i in allplayers:
    names[i.run] = allnames[allplayers.index(i)]
Game(players, names, 10)

Game results

Nothing yet!


  • Any thoughts? Do you like it?
  • All numbers, rules are undecided, tell me what you think I should change.
  • I know the controller has many bugs, I posted it here to show that one is being made but it's very much not ready to use.
  • That doesn't mean I don't want bug reports, if you use it and spot one, please tell me.
  • If you don't like Python - tough. It's all I've got on my computer*1, and I don't have space for much else.

*1 I tell a lie, I have got Java, but so much fuss in implementing it for one more language? I'll think about it...

  • \$\begingroup\$ I'd recommend cutting the probability aspect of saplings growing into trees and make it a variable growth rate based on neighbors. \$\endgroup\$ – Beefster Apr 12 at 18:30
  • \$\begingroup\$ @Beefster Interesting. I'll think about that. \$\endgroup\$ – Artemis Fowl Apr 12 at 19:51

Ragtag Band of Misfits

(Guaging interest)

This is a sort of sequel to Adventurers in the Ruins, taking place in a 2D dungeon, using a multi-agent team

A group of five adventurers enters a dungeon and wants to get the best loot. There are other parties competing for loot. Each party member has different abilities, health, stamina amounts, and carry capacity. Each has independent knowledge and must exchange information via a speak action.

The dungeon is made of rooms connected on a 2D grid. A room may have 1-4 doors. Some doors may be one-way. Rooms may have treasures, monsters, and traps.

As in the prequel challenge, treasure requires bidding and all actions resolve simultaneously with a specific priority on action types.

Party members

There are five classes of characters comprising each party

  1. Quartermaster
    • 100kg carry capacity, 10 HP, 1000 stamina, 5 power
    • Can heal party members in the same room
  2. Ranger
    • 50kg carry capacity, 10 HP, 1000 stamina, 8 power
    • Can see and attack monsters in adjacent rooms that are connected by a door
  3. Fighter
    • 50kg carry capacity, 25 HP, 1000 stamina, 8 power
    • Double damage to monsters
  4. Thief
    • 30kg carry capacity, 10 HP, 1500 stamina, 5 power
    • Automatically detects booby trapped treasures and can take them without triggering the trap
    • Can steal treasure from enemy adventurers in the same room
    • Can booby trap a treasure, making it appear twice as valuable, but dealing damage to whoever picks it up.
    • Effective bid on treasures is doubled. Wins ties on treasure bids except against other thieves.
  5. Wizard
    • 20kg carry capacity, 8 HP, 1500 stamina, 4 power
    • Can communicate telepathically with any single teammate without needing to be in the same room. This is a two-way channel of communication.
    • Can telepathically visit the room a teammate is currently in, seeing its contents and doors and enabling teleportation to that room
    • Can teleport self or ally in same room to any previously visited room or the same room as any ally.
    • Can teleport any ally to the current room
    • Carried treasure does not increase cost for moving between rooms or teleporting
    • Deals half damage to monsters

Actions available to adventurers of all classes

  • Move between rooms
  • Exit the dungeon (if in the starting room)
  • Speak (can be combined with certain actions)
  • Send a message to the wizard
  • Pick up a treasure (bidding rules work the same as the first challenge)
  • Gift a treasure to another party member in the same room
  • Drop a treasure
  • Attack a monster
  • Attack a rival adventurer in the same room
  • Guard (prevent oncoming attacks and theft attempts)
  • Wait


Adventurers can communicate by speaking, which will be heard by all teammates in the same room. Speaking requires no stamina and can be combined with movement or gifting, but is limited to be a 20-character string. (Use of emojis for increased message density is fair game)


A power must be specified when attacking a monster. This cannot be higher than the adventurer's power rating. That amount of stamina will be expended and the monster will be damaged by that amount. If the monster is still alive after all attacks have resolved, the monster will then deal its damage split among all combatants that attacked that turn, minimum of 1 damage.

If adventurers are outnumbered by monsters in any room, the monsters will attack anyone attempting to pick up treasure for 1 damage each.

Defeating a monster will cause the monster to drop up to 3 treasures (typically more valuable than the others in the room) and the characters who attacked the monster that turn will level up, gaining 1 power.

Attacking a rival adventurer will deal one fifth of the damage normally dealt to monsters, but will not result in a counterattack. Attacking an adventurer who either guards or moves into another room will result in a miss. It is possible for adventurers to kill each other on the same turn since attacks resolve simultaneously.


You will write a bot for each party member. They may not share data (other than constants and libraries).


Battle of Wits (Where is the Poison?)

The battle of wits is a well-known scene from the Princess Bride.

Two bots will face off in a battle of wits: one poisons a wine goblet and the other chooses which to drink from (the other player drinks from the other goblet). Whoever drinks the poison loses. This will be repeated until one bot wins 20 rounds, with who poisons the goblet being randomized each time. Each match, you will be able to see the entire history of which goblet was chosen and you will also have access to the other player's decision function (Related). All submissions will be evaluated in a round-robin tournament, with ties being broken by who has the fewest losses across all games. Further ties will be resolved by who has the fewest losses to the contesting opponents. If there is a perfect intransitive relationship among three or more bots, all of them will be considered tied for first place.

This is equivalent to the matching pennies game in terms of who wins a round. The poisoner is equivalent to the penny matcher and the chooser is equivalent to the non-matcher.

  • 1
    \$\begingroup\$ How about, to make it more interesting, let the bots read each other's source code? \$\endgroup\$ – Jo King Apr 19 at 4:51
  • 1
    \$\begingroup\$ @JoKing ooh. That's genius! Similar to this? \$\endgroup\$ – Beefster Apr 19 at 6:00

Output the Visible Spectrum in RGB

Inspired by http://www.physics.sfasu.edu/astro/color/spectra.html

Light with wavelength between ~380 and 780 nanometers is considered to be within the visible spectrum. One can approximate the colors of the visible spectrum in RGB space by linearly interpolating the wavelength at specific ranges. The ranges and corresponding formulae for a wavelength wl are given below, assuming each color value is a real between 0 and 1:

  • [380-440): r = (440 - wl) / (440 - 380), g = 0, b = 1
  • [440-490): r = 0, g = (wl - 440) / (490 - 440), b = 1
  • [490-510): r = 0, g = 1, b = (510 - wl) / (510 - 490)
  • [510-580): r = (wl - 510) / (580 - 510), g = 1, b = 0
  • [580-645): r = 1, g = (645 - wl) / (645 - 580), b = 0
  • [645-780): r = 1, g = 0, b = 0

Note that in this system, the interpolation formula is cyclic with the color components, and changes sign with respect to the range maximum or minimum.

The challenge

Given an integer wavelength between 380 and 780, output the RGB value using the above interpolations.

Output may be a list of floats in [0,1] or integers between [0,255] in the format (r,g,b), or a valid RGB hex code.

This is code golf, so the shortest code in bytes wins!

Test cases

Rounding errors to within 0.01 in float format or to within 1 in integer format are acceptable.

wl=400 --> (0.29, 0.0, 0.65) or (73,0,165) or #4900A5
wl=530 --> (0.28, 1.0, 0.0)  or (72,255,0) or #48FF00
wl=640 --> (1.0, 0.07, 0.0)  or (255,19,0) or #FF1300
wl=750 --> (1.0, 0.0, 0.0)   or (255,0,0)  or #FF0000


At extreme ranges of the visible spectrum, human perception is not as good. This can be modeled as a loss of intensity by multiplying the RGB values computed above by a factor f for specific cutoff points:

  • wl < 420: f=0.3+0.7*(wl-380)/(420-380)
  • wl > 700: f=0.3+0.7*(780-wl)/(780-700)

The total (r,g,b) including the perception factor is therefore (f*r, f*g, f*b)

  • \$\begingroup\$ I changed your post slightly; feel free to revert if you dislike my changes. \$\endgroup\$ – Jonathan Frech May 3 at 20:19
  • \$\begingroup\$ I also want to notify you of the fact that we have MathJax enabled, so you could TeX your equations. \$\endgroup\$ – Jonathan Frech May 3 at 20:22

Approximating Roots

(If you can think of a better title, then please suggest it!)

One day, when I was bored in maths class, I learned of a neat trick for solving the real cube root of a number!

Let's use the number \$79,507\$ as an example.

First, take digit in the one's place and compare it to this table:

\begin{array} {|r|r|} \hline \text{Extracted Digit} &\text{Resulting Digit} \\ \hline \text{1} &\text{1} \\ \text{2} &\text{8} \\ \text{3} &\text{7} \\ \text{4} &\text{4} \\ \text{5} &\text{5} \\ \text{6} &\text{6} \\ \text{7} &\text{3} \\ \text{8} &\text{2} \\ \text{9} &\text{9} \\ \text{0} &\text{0} \\ \hline \end{array}

In this example, the Resulting Digit will be \$3\$ since the digit in the one's place is \$7\$.

Next, remove all digits that are less than \$10^3\$:

$$ 79507 → 79 $$

Then, find the largest perfect cube that does not exceed the input:

$$ 64 < 79 $$

\$64=4^3\$, thus the next digit needed is \$4\$.

Finally, multiply the digit found in the previous step by \$10\$ and add the Resulting Digit found in the first step:

$$ 10*4+3=43 $$

Thus, the cube root of \$79,507\$ equals \$43\$.

However, there a neat quirk about this trick: it doesn't apply to only cubed numbers. In fact, it works with all \$n>1\$ where \$n\bmod2\ne0\$.

The steps mentioned above can be summed up in this generalization for an \$n\$ power:

  • Step 1) Take the digit in the one's place in the input. Compare it to the one's place digit of the \$n\$th powers of \$1\$ to \$10\$, then use the corresponding digit.

  • Step 2) Remove all digits of the input less than \$10^n\$. Compare the resulting number to the perfect powers definied in Step 1. Use the \$n\$th root of the largest perfect power less than said number.

  • Step 3) Multiply the number from Step 2 by 10 then add the number from Step 1. This will be the final result.


Given two positive integers \$n\$ and \$m\$, return the \$n\$th root of \$m\$.


  • Two positive integers \$n\$ and \$m\$.

  • \$m\$ is guaranteed to be a perfect \$n\$th power of an integer.

  • \$n\$ is guaranteed to be odd and greater than \$2\$. (This method doesn't work if \$n\$ is even.)


  • The \$n\$th root of \$m\$.


  • This is , so the fewer bytes, the better!

  • Standard I/O rules apply.

  • The output must be calculated using the aforementioned method.

  • No builtins allowed that already calculate this. A prime example being TI-BASIC's x√ command.

  • \$\begingroup\$ That's a pretty neat trick! I guess I'm not the only one who gets bored in math class. Also, I think you made an error on your test case, it says 10 x 4 + 4 rather than + 3 \$\endgroup\$ – Redwolf Programs May 5 at 14:03
  • \$\begingroup\$ @RedwolfPrograms yes, I believe so! Guess my finger slipped on the keyboard \$\endgroup\$ – Tau May 5 at 16:31
  • \$\begingroup\$ Is there anything else I should change about this post before I post it on main? Not sure what to call this challenge tbh \$\endgroup\$ – Tau May 5 at 20:05
  • \$\begingroup\$ At the beginning of the question, it states that the method only works on perfect cubes, but it later says that it works on all odd numbers > 2. Other than that I don't see many issues, but I'd leave it here for a day or so just in case. \$\endgroup\$ – Redwolf Programs May 5 at 20:09
  • \$\begingroup\$ Good point! I think that I should remove that line, as it is invalidated later on, as you said. \$\endgroup\$ – Tau May 5 at 20:18
  • \$\begingroup\$ Posting to main! Let's hope that this challenge fares well. \$\endgroup\$ – Tau May 7 at 13:25
  • \$\begingroup\$ "The output must be calculated using the aforementioned method" falls foul of Things to avoid: Non-observable program requirements. \$\endgroup\$ – Peter Taylor May 7 at 14:18
  • \$\begingroup\$ @PeterTaylor it may not be observable directly, but the source code will be able to indicate whether the method was used or not. \$\endgroup\$ – Tau May 7 at 14:25
  • \$\begingroup\$ @Tau, read the answer I linked. It explicitly addresses that point. \$\endgroup\$ – Peter Taylor May 7 at 14:51

Golf my Ada arrays


Ada is a programming language that is not exactly known for its terseness.

However, its array literal syntax can in theory allow for fairly terse array specifications. Here is a simple EBNF description of the array literal syntax (passable to bottlecaps.de:

array ::= positional_array | named_array
positional_array ::= expression ',' expression (',' expression)*
named_array ::= component_association (',' component_association)*
              | expression (',' expression)* ',' 'others' '=>' expression
component_association ::= discrete_choice_list '=>' expression
discrete_choice_list ::= discrete_choice ('|' discrete_choice)*
discrete_choice ::= expression ('..' expression)?

We will limit ourselves to 1-dimensional arrays of integers for simplicity. This means that we will use only integers for the expression values. Perhaps in a future challenge we could try something more advanced (like declaring variables and multidimensional arrays). You do not have to golf the integer literals.


The goal of this challenge is to output the shortest byte-count Ada array literal for a given input array. Note that Ada arrays can start from whatever index is desired, so you can pick what you wish the starting index to be as long as each value is sequential. In this example I choose to start at 1, which is idiomatic for Ada, however you can choose to start at any other integer.


Your input will consist of a list of integers, in whatever form is convenient.


Your output will be a string of text representing the shortest valid Ada array literal that represents the list of input integers. You may use any starting index you wish on this array, but your choice (whatever it is) must be specified in your answer (the starting index may also be dynamic).

Do not modify the representation of the input integers, keep them in decimal format. This challenge does not cover golfing of integer values.


Here are some examples:

Simple: [1, 2, 3] -> (1,2,3)
Range: [1, 1, 1, 1, 1, 1, 1,] -> (1..7=>1)
Others: [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1] -> (6=>2,others=>1)
Multiple Ranges: [1,1,1,1,1,2,2,2,2,2,1,1,1,1,1,2,2,2,2,2,1,1,1,1,1] -> (6..10|16..20=>2,others=>1)
Tiny Ranges: [1,1,2,2,1,1,1,1,1] -> (3|4=>2,others=>1)
Far Range: [[1]*5, [2]*100, [3]*5] -> (1..5=>1,6..105=>2,others=>3)
Alternation: [1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2] -> (1|3|5|7|9|11|13|15|17=>1,others=>2)
Big Number: [1234567890,1,1234567890] -> (2=>1,1|3=>1234567890)
Big-ish Number: [1234567,1,1234567] -> (1234567,1,1234567)

Minimum Requirements

  • Support at least 100 numbers and inputs of at least 256 numbers in length.

  • Produce the correct result for all such inputs (including putting 'others' at the end)

  • Terminate (preferably on TIO) for each of the above inputs in under a minute.

Reference Implementation

Try it online!

This implementation uses the input as its array, with each character being a number. Capital letters are special constants for large values. The program argument is the 'start index' to use.

The "code" section in the TIO link is a correct solution to the problem, while the "header" and "footer" implement the test structure.

  • \$\begingroup\$ Your syntax doesn't match the examples; although I don't know Ada, I do know VHDL (which uses the same array syntax), and I think allowing others => in a named array (like the examples do, and the syntax doesn't) is correct. As for the challenge more generally, the specification is clear but you're missing a victory condition. code-golf is our most common victory condition here because it works well for a wide range of problems; I don't see any reason why it would work badly for this one, and don't think any of the usual alternatives are better. \$\endgroup\$ – ais523's temporary account May 7 at 22:43
  • \$\begingroup\$ Oh, one other suggestion is that having more functionality in the reference implementation than is required in users' answers is confusing. You might want to try explaining more clearly what the linked TIO program does, and explaining it as something like "a tool to try out various inputs, supporting abbreviations for some larger inputs, and seeing what the intended output is". \$\endgroup\$ – ais523's temporary account May 7 at 22:50
  • \$\begingroup\$ One other thing that could improve the question: specify what sort of input the program should take (presumably a list of integers), and what sort of output the program should produce (presumably a string). You don't need to define terms like "list" and "string" precisely; people will use whatever definitions make sense for their language. You should probably say something like "for the purposes of this challenge, numbers in the output should be in decimal; you do not have to golf them", because golfing of the output integers could change their length and thus which array syntax is optimal. \$\endgroup\$ – ais523's temporary account May 7 at 22:53
  • \$\begingroup\$ I've added some clarifications. \$\endgroup\$ – LambdaBeta May 9 at 14:51
  • \$\begingroup\$ "Do not modify the representation" is a bit unclear: the language that people use might be taking input in a format other than decimal, but in that case we still want decimal in the output. Apart from that, I think everything is fine now (and that particular issue isn't unclear enough to make the question closeable, IMO, although close votes are often hard to predict). \$\endgroup\$ – ais523's temporary account May 13 at 16:22
  • \$\begingroup\$ I see what you mean, I'll adjust that and post it. Thanks for the help! \$\endgroup\$ – LambdaBeta May 13 at 16:35

Arithmetic quine

Write a quine.
Well that's not very original challenge so let's spice things up.


Write a quine which when once or multiple times appended to itself (see Appending) then performs an arithmetic operation of your choice.
You can implement as many operations from the as you want (see Scoring, Operations)

Let's say my code were foobar. This would return foobar because it's a quine.
Now foobarfoobar would preform + operation on two input numbers.
foobarfoobarfoobar could preform a * operation.

Note: which operation you choose for whatever number of appended copies doesn't matter but you have to write it down in your answer.

Example: Your code might be 4 times appended to preform addition, or it might need to be appended 5 times. It doesn't matter as long as you write the full list of the operations you implemented and the number of concatenations needed.


The list of operations you are allowed to implement is:

Integer Division
Integer exponentiation
Integer Factorial


score = bytes/(n_operations + 1)

Bytes mean the bytes of the initial un-appended program.


All languages (even if 2D) must be appended by simply concatenating the program two or more times.

  • \$\begingroup\$ What operations should I add or how should I make this more clear? \$\endgroup\$ – IQuick 143 Apr 29 '18 at 7:37
  • 2
    \$\begingroup\$ If not duplicate it be good \$\endgroup\$ – l4m2 Apr 29 '18 at 11:14
  • \$\begingroup\$ I expect that this would be extremely difficult. Hyperprogramming is a similar challenge with only addition, multiplication, and exponentiation where its achievability was called into question. \$\endgroup\$ – Esolanging Fruit Apr 30 '18 at 6:19
  • 3
    \$\begingroup\$ In my opinion, all languages should be treated equally. Otherwise there would be a lot of disputes (for example: (1) what about Cubix or Hexagony or Wumpus or Quadrefunge, where the layout is not directly rectangular but still >1D? (2) if my language is not 2D can I append horizontally? (3) Can I use a codepage where newline is a different character from \x10? ) \$\endgroup\$ – user202729 May 2 '18 at 12:22
  • \$\begingroup\$ Can we read our own source code, or do default loopholes and quine rules apply? \$\endgroup\$ – Kevin Cruijssen May 8 at 13:30
  • 1
    \$\begingroup\$ @EsolangingFruit I have the feeling this challenge is easier than that one though. Appending the entire source code allows you to utilize the length, whereas duplicating every character gives all kind of trouble which is harder to overcome/ignore. PS: I've prepared a solution which works with all six operations. Those operations are just examples, right? I could add more if I want to? \$\endgroup\$ – Kevin Cruijssen May 8 at 13:49
  • \$\begingroup\$ Prepared a solution with nine operations, and will add more later on. :) Looking forward seeing this go live. \$\endgroup\$ – Kevin Cruijssen May 8 at 13:57
  • \$\begingroup\$ @KevinCruijssen May I know which operations, I'll probably add them to the list \$\endgroup\$ – IQuick 143 May 8 at 14:05
  • \$\begingroup\$ @KevinCruijssen The list was supposed to be a full list but I don't see why we couldn't expand it, also I'm considering adding a score to each operation, since some are harder to accomplish than others. \$\endgroup\$ – IQuick 143 May 8 at 14:09
  • 1
    \$\begingroup\$ @IQuick143 Well, the ones I have right now are: addition; subtraction; multiplication; integer division; exponentiation; factorial; square; square-root; 1/n. But I could easily add more like regular division; modulo; +1; +2; -1; -2; signum; absolute difference; base-conversion to; base-conversion from; xor; bitwise-and; bitwise-or; negate; halve; double; length; etc. etc. haha ;p So maybe it's good to have a list instead of leaving the choice to everyone. ;) I would personally use add; subtract; divide; int-divide; multiply; exponent; modulo (all requiring two inputs) \$\endgroup\$ – Kevin Cruijssen May 8 at 16:48
  • 1
    \$\begingroup\$ But I'll leave the choice to you. If you want to keep the original six operators that's fine as well. (In which case I would change the sentence to "The list of operations you are allowed to implement:") \$\endgroup\$ – Kevin Cruijssen May 8 at 16:50
  • \$\begingroup\$ @KevinCruijssen I was thinking of changing the metric to score = bytes * (operations_language_can_implement - implemented_operations + 1), because some languages might not be able to handle floats for instance, what do you think? \$\endgroup\$ – IQuick 143 May 11 at 13:46
  • \$\begingroup\$ @JoKing Thanks for the grammar help. \$\endgroup\$ – IQuick 143 May 11 at 13:47
  • \$\begingroup\$ @IQuick143 Doesn't that give an unfair advantage to those languages? Let's say language A can and has implemented 5 operations in X+5 bytes. And language B can and has implemented 10 operations in X+10 bytes. Although both will get get 1 in the (operations_language_can_implement - implemented_operations + 1) part of your scoring, the byte-count of B is X+10, so 5 bytes higher than A's X+5, even though it implemented more operations.. I would keep the scoring as is, and have a select list of operations to implement. If a language can't handle it, it's score would be higher to reflect that. \$\endgroup\$ – Kevin Cruijssen May 13 at 9:06
  • \$\begingroup\$ And if you want to keep it with integers only, you could perhaps use the following six operation all requiring two inputs: add; subtract; int-divide; multiply; exponent; modulo? \$\endgroup\$ – Kevin Cruijssen May 13 at 9:07

Print some very large numbers

Not sure if this has been done before. Write a program that takes in a scientific format number (as two inputs, a mantissa and an exponent), and outputs a decimal representation of that number (as a string). The trick is that this must go far beyond most languages number limits.

The mantissa will always be within 1 ≤ mantissa ≤ 10 or mantissa = 0.

The exponent will always be a 32-bit signed integer.


1, 100 -> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

3.543235, 200 -> 354323500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

3.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333, 10 -> 33333333333.333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333

5.3282, -71 -> 0.000000000000000000000000000000000000000000000000000000000000000000000053282

0, 999999 -> 0
  • 3
    \$\begingroup\$ Nice challenge, but can we use our language's scientific notation, E.g. some languages don't use the +, or use a different minus? \$\endgroup\$ – Adám May 20 at 11:09
  • 2
    \$\begingroup\$ Maybe even allow taking mantissa and exponent as separate inputs? \$\endgroup\$ – Adám May 20 at 11:12
  • 1
    \$\begingroup\$ Don't forget to add some example cases with negative exponent and one with an integer mantissa. Oh, and also a 0 case. \$\endgroup\$ – Adám May 20 at 11:13
  • 1
    \$\begingroup\$ Will input always be in canonical format; 1≤|mantissa|<2 or mantissa=0. Can there be leading and trailing 0s in input? How about in output? \$\endgroup\$ – Adám May 20 at 11:15
  • 2
    \$\begingroup\$ I like the idea of taking the mantissa and exponent as seperate inputs. Then we can do away with the string parsing part of the challenge and just focus on handling big numbers (by giving the inputs as floating point numbers). \$\endgroup\$ – Omegastick May 21 at 1:15

Do X with Y

Your task is to create a X made of nested 3x3 lowercase Ys, with n levels of nesting. Here is how a X looks like (this is also the output for n = 0):

y y
y y

A 0-level nested lowercase Y is just y. To nest a lowercase Y a level further, you arrange 4 copies of it like this:

y y

Here is the output for n = 1:

y y   y y
 y     y 
y     y  
   y y
y y   y y
 y     y 
y     y  

Here is the output for n = 2 (I typed all of this by hand; excuse any mistakes):

y y   y y         y y   y y
 y     y           y     y 
y     y           y     y
   y y               y y
    y                 y
   y                 y
y y               y y
 y                 y
y                 y
         y y   y y
          y     y
         y     y
            y y
         y y
y y   y y         y y   y y
 y     y           y     y
y     y           y     y
   y y               y y
    y                 y
   y                 y
y y               y y
 y                 y
y                 y


A non-negative integer n. You may choose the levels of nesting to be either 0- or 1- indexed.


A X made of nested 3x3 lowercase Ys, with n levels of nesting, as a string, list of lines as strings, or outputted directly.

Sandbox stuff

  • Is anything missing?
  • Is the specification of the X clear enough?
  • 1
    \$\begingroup\$ heavily related question. I'm not 100% convinced this is different enough to not be a dupe, but I'd try to get some more feedback before posting/abandoning this. \$\endgroup\$ – Giuseppe Jun 3 at 21:37
  • 2
    \$\begingroup\$ I think this would be a duplicate. My experience with porting an answer from yet another 3*3 fractal challenge was that I only needed to make a small change in the code. \$\endgroup\$ – xnor Jun 4 at 4:49
  • \$\begingroup\$ I have no idea if should I post this or not, as this both is +3 and seems to receive feedback as a possible duplicate. \$\endgroup\$ – someone Jun 13 at 14:53

Atomic Handshakes


Here you are. At a party, with two drinks in your hands. Your friend just went to the bathroom and you don't really know anyone else here. And so you wait. Or do you?

There is a century old hypothesis known as Six Degrees of Separation. The hypothesis states, that any other person in the world is connected to you as a friend of a friend of a friend etc.. It would essentially only take you six handshakes to connect with any other person on this planet. But is there actually any truth in this hypothesis? That's what we're about to find out in this challenge!

A similar question also finds its way into my own field of expertise: chemistry. Hence the title. Chemistry is the study of molecules, and molecules get very complex very fast. All (for the sake of simplicity) atoms in a molecule are connected. For certain types of analysis, one may need to know how many connections (bonds) it takes to get from one atom to another.

The Challenge

In a set of N people, each person has a maximum of N-1 direct connections. Based on this information, it is your task to deduce for every person what the lowest number of connections is to get to every other person.

People (and atoms too) can have similar names. Therefore, instead of a name, every person will get a unique identifier. To make things easy, the identifier will be a non-negative integer and the integers are all consecutive. How convenient!


An array-like object of size N which lists the first-degree connections for each person.


A two-dimensional, symmetrical array of size NxN which shows for each person the shortest distance to every other person.

Challenge rules

  • All people are connected: there are no loners or isolated groups in the input
  • Circular connections are allowed, but
  • Only the shortest connection must be output as more ways lead to Rome

General rules


As the theory may still be somewhat confusing, I will include a network graph for each example. This should make it a lot easier to understand what we're talking about. Here goes!

Example 1

Consider the connected set

        |   |

For this network, our input array will be

[[1]          # Since 0 is connected only to 1
 [0 2]        # Since 1 is connected to 0 and 2
 [1 3 4]      # Since 2 is connected to 1, 3 and 4
 [2 5]        # Et cetera
 [2 5]
 [3 4 6]

Which should result in the following output (excluding comments):

# Distance from
# 0 1 2 3 4 5 6
                   # To
[[0 1 2 3 3 4 5]   # 0
 [1 0 1 2 2 3 4]   # 1
 [2 1 0 1 1 2 3]   # 2
 [3 2 1 0 2 1 2]   # 3
 [3 2 1 2 0 1 2]   # 4
 [4 3 2 1 1 0 1]   # 5
 [5 4 3 2 2 1 0]]  # 6

Example 2

Consider the connected set

|       |
|   0   |
|   |   |
|   1---2---3---.
|   |   |   |   |
'---4---5---6   |
    |           |

For this network, our input array will be

[[1]          # Since 0 is connected only to 1
 [0 2 4]      # Since 1 is connected to 0, 2 and 4
 [1 3 4 5]    # Since 2 is connected to 1, 3, 4 and 5
 [2 6 9]      # Et cetera
 [1 2 5 7]
 [2 4 6]
 [3 5]
 [4 8]
 [7 9]
 [3 8]]

Which should result in the following output (excluding comments):

# Distance from
# 0 1 2 3 4 5 6 7 8 9
                         # To
[[0 1 2 3 2 3 4 3 4 4]   # 0
 [1 0 1 2 1 2 3 2 3 3]   # 1
 [2 1 0 1 1 1 2 3 3 2]   # 2
 [3 2 1 0 2 2 1 3 2 1]   # 3
 [2 1 1 2 0 1 2 1 2 3]   # 4
 [3 2 1 2 1 0 1 2 3 3]   # 5
 [4 3 2 1 2 1 0 3 3 2]   # 6
 [3 2 3 3 1 2 3 0 1 2]   # 7
 [4 3 3 2 2 3 3 1 0 1]   # 8
 [4 3 2 1 3 3 2 2 1 0]]  # 9

Example 3

Consider the connected set

|   |   |
|   |   |

For this network, our input array will be

[[1 2 3]      # Since 0 is connected to 1, 2 and 3
 [0 1 3 4]    # Et cetera
 [0 2 4]
 [1 2 3]]

Which should result in the following output (excluding comments):

# Distance from
# 0 1 2 3 4
               # To
[[0 1 1 1 2]   # 0
 [1 0 1 2 1]   # 1
 [1 1 0 1 1]   # 2
 [1 2 1 0 1]   # 3
 [2 1 1 1 0]]  # 4
  • 2
    \$\begingroup\$ In short, all pairs shortest path. Single-route shortest path would definitely be closed as a duplicate; I would say there's a significant chance that the consensus will be that this is also a duplicate of one of the questions in path-finding. \$\endgroup\$ – Peter Taylor Jul 5 at 10:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .