# What is the Sandbox?

This "Sandbox" is a place where Programming Puzzles & Code Golf (PPCG) users can get feedback on prospective challenges they wish to post to the main page. This is useful because writing a clear and fully specified challenge on the first try can be difficult. There is a much better chance of your challenge being well received if you post it in the Sandbox first.

See the Sandbox FAQ for more information on how to use the Sandbox.

## Get the Sandbox Viewer to view the sandbox more easily

To add an inline tag to a proposal use shortcut link syntax with a prefix: [tag:king-of-the-hill]

• Suggestion: instead of having a notice on the top answer ("note: if you are..."), you'd better just put a moderator notice below the question – nicael Mar 19 '18 at 19:35
• @nicael We can only choose from three post notices: citation needed, current event, and insufficient explanation. – Dennis Apr 7 '18 at 14:43
• If you remove a post but didn't post it you can replace the text body with [](lots of text here to reach the min chars) to make it much smaller when removed – Christopher Apr 13 '18 at 17:54
• @Christopher Please don't do that for old proposals. It clutters the first page with an answer nobody cares about anymore, instead of staying hidden on page 10 where it will bother nobody. – Dennis Apr 13 '18 at 18:17
• @Dennis ? what are you talking about. As if if you didn't post it like you just removed you own sandbox because dupe or something – Christopher Apr 13 '18 at 18:18
• @Christopher If your proposal is still on the first few pages, you can replace the proposal with a stub to save vertical space on these pages. However, if your proposal is already on page 10, editing your proposal will bump it to page 1, where space is more precious than on page 10. – Dennis Apr 13 '18 at 18:21
• @Dennis ohh that makes sense – Christopher Apr 13 '18 at 18:25
• codegolf.meta.stackexchange.com/questions/12599/… – Redwolf Programs Apr 17 '18 at 17:38
• Maybe it's time to consider cleaning some of this up a bit. There's just too much to go through and some of these proposals are years old and obviously not going anywhere (even some of the good ones). Perhaps cull anything that is two years old and has likewise been inactive for as long? – ouflak Aug 6 '18 at 9:07
• @ouflak You can sort posts by "active". That seems to resolve all of the problems you describe. – FryAmTheEggman Sep 27 '18 at 19:04
• I already posted this, but codegolf.stackexchange.com/questions/176599/… – 2br-2b Nov 27 '18 at 2:38
• How are tags added to questions? – guest271314 Jan 9 at 7:51
• It seems like there is a rollback war with moderators and the Community user to add and remove the featured tag. – smileycreations15 Mar 21 at 21:13
• @smileycreations15 That's unfortunately unavoidable. Community is an automatic script, and, since most featured questions are only temporarily so, it assumes that we don't want this question to be featured forever. However, we do, so a mod has to edit the tag in every now and then. – Erik the Outgolfer Mar 24 at 15:22
• @EriktheOutgolfer Yeah. Maybe they can create a special [featured-pin] tag which will both feature it and pin it from removal by the Community user. – smileycreations15 Mar 24 at 17:20

# Speeding up powers of 2

Create a function or program that indefinitely prints outs successive powers of 2 separated by newlines. However, the nth term of the sequence (2^n) must have a delay of 1/n seconds either before or after it is printed, but please specify this in your answer. If you choose to add the delay before the number is printed, the first number may optionally have a delay before it is printed.

Your program may begin with 1 or 2 as the first printed number, but if you include 1, it is considered the 0th term, and your delays must be before each print and skip any initial delay (1/0 as a delay would not work, hence this rule).

Your program should run properly until it either reaches the integer limit of your language, or until n = 1000 (a 1 ms delay)

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...


### Sandbox

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

EDITS: Clarified that n refers to the term number, not the power of 2

• I like the idea, but any language with arbitrary precision integers is disqualified because it's not possible (and it's not a small set of languages, a lot of languages support).. – ბიმო Jan 10 at 2:12
• @BMO How is this impossible with arbitrary precision integers? Does it make it difficult to calculate the delays or is there some way in which printing some larger numbers make this impossible? Also, should I require that programs theoretically work for integers beyond the limit of the language (with minor modifications to account for this)? – Neil A. Jan 11 at 4:31
• The delay needs to be $\frac{1}{n}$, any system imposes some $t_{\min}$ which is required to output anything at all, as $n$ gets larger there will be some $n_0$ where $\frac{1}{n_0} < t_{\min}$ which is not possible. In short: The delay gets arbitrarily small while the work gets arbitrarily large and at some point this becomes infeasible. – ბიმო Jan 11 at 10:02
• Are we allowed to sleep 1/1 seconds before printing 2 in the first iteration? Or are we allowed to print 1 and sleep 1/2 seconds afterwards in the first iteration? – Kevin Cruijssen Jan 11 at 12:18
• @BMO is indeed right that fairly quickly 1/n will become 0 in loads of languages. Java for example has a maximum precision of 16 decimal digits after the comma for floats/doubles (it does have BigDecimals for higher precision, but let's ignore those for now). The 64th iteration (number 18446744073709551616) will have a delay of 5.421010862427522e-17 ms, which is basically 0 in programming languages with 16 decimal digit precision. – Kevin Cruijssen Jan 11 at 12:37
• I do like the challenge in general, though (and have prepared a solution if it goes live), so +1 from me. :) – Kevin Cruijssen Jan 11 at 12:37
• @KevinCruijssen: You would have to either sleep for 1/1 and then print 1 initially, or sleep 1/2 seconds then print 2 initially, i.e. you must include the term associated with the delay. As for the second point, I would consider that to be starting with 1 and having the delay imposed before printing the nth term, so it is valid. – Neil A. Jan 11 at 15:26
• @BMO: Should I instead make the sleep duration something like n^2, (2^n)/n, or another function that could make this interesting? (I want to avoid using simply n to make it a bit more interesting). I would change the title of the challenge appropriately, of course. – Neil A. Jan 11 at 15:29
• Choosing $n^2$ or even $\frac{2^n}{n}$ changes things massively. I like the idea of having less time for more work, but: 1) You need to set a boundary, st. the mentioned problem will not occur, if a submission chooses the right approach. 2) To make it interesting, I would balance the boundary and function in a way that the last iteration isn't too easy. – ბიმო Jan 11 at 17:17
• A starting point (using a Unix system): Investigate how many CPU cycles a write syscall takes (let's assume $1000$ - I haven't checked though and it will depend a lot on the environment), assume a standard CPU clocked at $1.5$GHz, this gives you $\frac{1000}{10^{9}\text{Hz}}=1\mu\text{s}$ for a single write. A delay of $\frac{1}{2^{31}}$ (maximum power of two for $\texttt{uint32}$) is already half of that. – ბიმო Jan 11 at 17:17
• @BMO: I may have messed up on my specifics, but what I intended was something along the lines of: when printing 2^31, there should be a delay of 1/31 seconds, not 1/(2^31). (n=the term number, not the power of two). – Neil A. Jan 11 at 17:46
• Ah, I misunderstood the challenge (I screwed up, not you). Delaying for $\frac{1}{31}$ of a second should be easy. You will still need to add a bound though. – ბიმო Jan 11 at 17:52
• @BMO: Edited for clarity, limit is n=1000 (1 ms delay, should be handled by most languages fine) – Neil A. Jan 11 at 17:59

## Static Code Analysis Battle!

Your programs will play a friendly game of rock, paper, scissors. There's a catch though; you can not use randomness and the combatants can see each other's source code.

That is, you will write a python program that, when imported, provides a function named rps. Given two combatants, say player1.py and player2.py, the controller will import them, and execute player1.rps(player2sourceCode) and player2.rps(player1sourceCode). These should output R, P, or S. The winner is then whoever would win in rock paper scissors with those moves. If one player makes a valid move, and the other does not, that player wins. If both players make an invalid move, it is considered tie. Additionally, taking more than 1 second to move is considered an invalid move.

Here are the rules:

1. Both the action of importing your module and your rps function should be pure functions. This means for example that you can not do the following:
1. Use randomness or other non-deterministic code.
2. Interfere with or receive information from the file system, I/O, peripherals, etc...
3. Use time.sleep.
4. Alter or access the state of the controller.
5. Use other functions to do impure actions. For example, you can not call eval on the source code of an impure function call. An exception to this is if the only impure thing it does is interact with your program's state (i.e. it is permitted to change variables in your program's namespace). You can, however, call it on pure function call source code.
6. Anything else that a pure function could not do.
2. Other functions in your source code, however, may be impure.
3. You may assume that the source code passed as an argument to rps obeys rule 1. You may not, however, assume that the rps in the passed source code is a pure function when you pass it source code that does not obey rule 1. Additionally, other functions in the module may be impure.
4. Additionally, going into an infinite loop is perfectly fine, although if it happens when the caller calls your program, your move will be considered invalid. If the opponent calls your program and it causes them to go into an infinite loop, however, their move will be considered invalid, and vice versa.

This is , so the program that defeats the other programs wins! In particular, I will run a match between each program and each other program. The winner will be the condorcet winner if one exists. Otherwise, the result will be a tie between the Schwartz set members.

Moved to main. Thanks everyone for your input. Happy golfing!

• This seems like a nice challenge! I'm not as experienced as other people around here, but you should publish it to main. – MilkyWay90 Jan 26 at 16:28
• These question are likely to be asked: Can input be in decimal (some languages don't have "hex"-numbers and in other languages it's most of the time just a different literal but represents the same)? Can input be binary (maybe even as string)? Does "any character" include spaces? Is it restricted to printables only? Is returning an array of strings allowed or does it need to be a single newline-separated string? – ბიმო Jan 28 at 13:27
• Maybe you could add an example with both x- and y-stretch factors being negative? – ბიმო Jan 28 at 13:30
• @BMO thank you for your suggestions! I've updated the description to address your points. – gwaugh Jan 28 at 14:41
• I've clarified a few things and added some better test cases. I'll wait to get a few more up-votes before submitting it though. – gwaugh Jan 28 at 17:36
• Nice challenge! I've already prepared a solution in case it goes to main. Only perhaps slightly confusing part is where you use the byte-format 018H/024H in the circle example at the top, but then the format 0x18/0x24 in your test cases. I would change the 018H/024H in that first example to 0x18/0x24 as well to remain consistent across the entire challenge description. Apart from that everything is clear to me. – Kevin Cruijssen Jan 29 at 13:42

# Bit-checker

Write a program that takes two integers in the range $$\0\$$ to $$\255\$$ inclusive, and returns whether the binary forms of the numbers are exactly one bit different.

For example, $$\1\$$ and $$\0\$$ have binary forms 00000001 and 00000000, which are one bit apart. $$\152\$$ and $$\24\$$ are 010011000 and 000011000, so they return true.

However, your code must be radiation hardened such that if any one bit in your program is flipped, it should still work correctly.

### Test cases:

0,1     => Truthy
1,0     => Truthy
152,24  => Truthy
10,10   => Falsey
10,11   => Truthy
11,12   => Falsey
255,0   => Falsey


## Rules:

• I'm thinking this might be way too hard to get answers. Vote this comment if you think I should change it to pristine-programming (i.e. that every changed program produces an error) – Jo King Mar 18 at 5:03
• Vote here to keep it as radiation-hardening – Jo King Mar 18 at 5:03
• There is no such thing as something that is too hard for a code-golfer. – MilkyWay90 Mar 18 at 23:49

## 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.

# Output

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.

# Scoring

Because this is , the shortest code wins

# Example

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


>15
8 1 15 10 6 3 13 12 4 5 11 14 2 7 9 16
>15
6 8 1 15 10 6 3 13 12 4 5 11 14 2 7 9
>18
17 8 1 15 10 6 3 13 12 4 5 11 14 2 7 9 16
>15
1 3 6 10 15 2 7 9 4 5 11 8 12 13 14

• 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. – Shaggy Apr 7 at 1:15
• @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. – Akangka Apr 8 at 6:02
• To me, they are separate challenges: "Does the series exist" is a decision-problem challenge and "What is the series is" a sequence challenge. – Shaggy Apr 9 at 9:23
• Do you want to add anything about exhaustive searches? I could just try every combination under the current rules... – Phil H Apr 9 at 10:58
• @PhilH now that you say that. I have bad faith in this challenge. – Akangka Apr 10 at 1:34

# The Forest Game (KotH, WIP)

## Summary

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

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.

## Growing

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.

## Value

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

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).

## Tournament

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!

## I/O

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.

## Controller

WIP, extremely buggy

'''
Rules
---
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

actions:
'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)

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

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

growing:
. > 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

I/O
---
'''

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):
return
elif str(i) in 'Ti':
burn.append(i)
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:
return
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)
return
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):
def __init__(self, x, y, game, creator):
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:
return
else:
self.points += text[0] == 'w'
return
dirs = "^'<p>,v." #p = placeholder
if text[1] not in dirs:
return
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):
return
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
return
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) == ' ':
print('.')
self.game.place(Seed, nx, ny, self)
self.points -= 1
elif text[0] == 'l' and self.points > 9:
if str(itm) == ' ':
print('l')
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):
self.map.append([])
for y in range(size):
self.map[-1].append(Empty(x, y, self))
choose.append((x, y))
self.players = {}
random.shuffle(choose)
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
self.round(1)

def round(self, number):
for i in self.players:
self.updatemap()
self.turn(i, number)
if not 'idlelib.run' in sys.modules:
time.sleep(0.04)
os.system('cls')
print(' |0 1 2 3 4 5 6 7 8 9')
print('---------------------')
[print(str(self.map.index(i)) + '|' + ' '.join(str(j) for j in i)) for i in self.map]
if number != 100:
self.round(number+1)
else:
[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
points.append(self.players[i].points)
text = player(map_=[x[:] for x in self.map], num=num, points=points, round_=rn)
self.players[player].command(text)

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

def move(self, ox, oy, x, y):
try:
self.map[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:
pass

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:
try:
around.append(self.map[x+rx][y+ry])
except IndexError:
around.append('')
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='-----')
self.map[x][y].update(around)

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:
players.append(i.run)
names[i.run] = allnames[allplayers.index(i)]
Game(players, names, 10)
input()


Nothing yet!

## Sandbox

• 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...

• I'd recommend cutting the probability aspect of saplings growing into trees and make it a variable growth rate based on neighbors. – Beefster Apr 12 at 18:30
• @Beefster Interesting. I'll think about that. – 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

### Communication

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)

# Combat

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.

# Coding

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.

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

# Output the Visible Spectrum in RGB

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


## Bonus

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)

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

Input:

• 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.)

Output:

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

Rules:

• 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.

• 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 – Redwolf Programs May 5 at 14:03
• @RedwolfPrograms yes, I believe so! Guess my finger slipped on the keyboard – Tau May 5 at 16:31
• Is there anything else I should change about this post before I post it on main? Not sure what to call this challenge tbh – Tau May 5 at 20:05
• 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. – Redwolf Programs May 5 at 20:09
• Good point! I think that I should remove that line, as it is invalidated later on, as you said. – Tau May 5 at 20:18
• Posting to main! Let's hope that this challenge fares well. – Tau May 7 at 13:25
• "The output must be calculated using the aforementioned method" falls foul of Things to avoid: Non-observable program requirements. – Peter Taylor May 7 at 14:18
• @PeterTaylor it may not be observable directly, but the source code will be able to indicate whether the method was used or not. – Tau May 7 at 14:25

## Background

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.

## Challenge

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.

### Input

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

### Output

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.

### Examples

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.

• 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. – ais523's temporary account May 7 at 22:43
• 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". – ais523's temporary account May 7 at 22:50
• 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. – ais523's temporary account May 7 at 22:53
• I've added some clarifications. – LambdaBeta May 9 at 14:51
• "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). – ais523's temporary account May 13 at 16:22
• I see what you mean, I'll adjust that and post it. Thanks for the help! – LambdaBeta May 13 at 16:35

# Arithmetic quine

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

Challenge

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)

Example:
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.

Operations

The list of operations you are allowed to implement is:

Addition
Subtraction
Multiplication
Integer Division
Integer exponentiation
Integer Factorial


Scoring

score = bytes/(n_operations + 1)

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

Appending

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

• What operations should I add or how should I make this more clear? – IQuick 143 Apr 29 '18 at 7:37
• If not duplicate it be good – l4m2 Apr 29 '18 at 11:14
• 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. – Esolanging Fruit Apr 30 '18 at 6:19
• 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? ) – user202729 May 2 '18 at 12:22
• Can we read our own source code, or do default loopholes and quine rules apply? – Kevin Cruijssen May 8 at 13:30
• @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? – Kevin Cruijssen May 8 at 13:49
• Prepared a solution with nine operations, and will add more later on. :) Looking forward seeing this go live. – Kevin Cruijssen May 8 at 13:57
• @KevinCruijssen May I know which operations, I'll probably add them to the list – IQuick 143 May 8 at 14:05
• @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. – IQuick 143 May 8 at 14:09
• @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) – Kevin Cruijssen May 8 at 16:48
• 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:") – Kevin Cruijssen May 8 at 16:50
• @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? – IQuick 143 May 11 at 13:46
• @JoKing Thanks for the grammar help. – IQuick 143 May 11 at 13:47
• @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. – Kevin Cruijssen May 13 at 9:06
• 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? – 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.

Example:

1, 100 -> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

3.543235, 200 -> 354323500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

3.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333, 10 -> 33333333333.333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333

5.3282, -71 -> 0.000000000000000000000000000000000000000000000000000000000000000000000053282

0, 999999 -> 0

• Nice challenge, but can we use our language's scientific notation, E.g. some languages don't use the +, or use a different minus? – Adám May 20 at 11:09
• Maybe even allow taking mantissa and exponent as separate inputs? – Adám May 20 at 11:12
• Don't forget to add some example cases with negative exponent and one with an integer mantissa. Oh, and also a 0 case. – Adám May 20 at 11:13
• 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? – Adám May 20 at 11:15
• 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). – Omegastick May 21 at 1:15

# Golf the truth and null values

In many programming languages there is a null and/or other special values. Sometimes they don't follow the normal rules of boolean operations. They may not even agree with the values of the same name in other languages.

Here are some different kinds of the "extended" boolean values, either borrowed from some languages or invented myself:

• False.
• True.
• Absent. All operations between absent and another operand return the other operand.
• Whatever. All operations between whatever and another operand returns whatever (itself).
• Partial. If the result can be decided using the other operand, return that. Otherwise return partial (itself).
• Error. An error as the first operand works like whatever, and an error as the second operand works like partial, except that "itself" means error. It has higher precedence than whatever and partial.

Your task is to define all these values in your language, and the 2 operations and or.

To be clear, the 2 operations should work exactly as in the following tables. The left column represents the first operand, and the top row the second operand.

and F T A W P E       or F T A W P E
F F F F W F F        F F T F W P E
T F T T W P E        T T T T W T T
A F T A W P E        A F T A W P E
W W W W W W W        W W W W W W W
P F P P W P E        P P T P W P E
E E E E E E E        E E E E E E E


## Rules

You could use anything distinct and consistent to represent these values. You don't have to use a truthy value to represent true, or a falsy value to represent false. You are allowed and encouraged to use values that contain useful code, i.e. this loophole is not forbidden.

You are allowed to use actual errors or exceptions to represent some of the values. In this case the definition of that value should throw the same error, instead of represent the caught error. But the caught errors or the output messages should be distinct and consistent. Alternatively, you may choose to include STDERR in the output of your code, and use the printed message string as a normal value.

You may choose to pass functions generating and returning the values but doing nothing else to your code as input, in place of the values themselves, without counting the extra code.

You may use different ways of input/output for different values, as long as it is consistent for each kind of value, and it is possible to tell apart the first and the second operand.

You are allowed to use builtin functions and operators without boilerplate, even if you cannot save them in something callable in your language.

There could be some common code shared by all the 8 definitions and appear only once as header/footer. Other than that, the 8 definitions of operations and values must work independently from each other. The only way you can call something defined in the values in the operations is through a valid input method (e.g. you cannot set a variable in a value and read it in an operation).

Your score is the length of common code * 12 + the total length of the 2 operations * 6 + the total length of the values. Smallest score wins. The length of a value is either the length of the code generating it, or the length of itself unquoted if all the values are strings and you choose this way.

## Abandoned rules

You are allowed to use operators, or chains of operators and values to represent the 2 operations, even if you cannot save them in something callable in your language. You may require the operands to appear at specific positions, but each operand must appear exactly once and be grouped together. You may choose whether to save operands in variables previously, and don't count the assignment if it doesn't add new information in the assignment (e.g. by changing its type). This makes it possible to use the built-in operators with short-circuit evaluation in languages that don't allow redefining them and preserve this characteristic, and may also make it shorter in some other languages.

Previous scoring: total length of the 2 operations * 50 + the total length of the values.

## Possible follow-up

Original title: All the weirdness about the nulls

Extended tables including Valid in a previous version, Reverse aka Opposite by Zgarb, and Possible.

and T F N O W E V R P     or T F N O W E V R P
T T F T O W E ? F T      T T T T T W T T T T
F F F F F W F F F F      F T F F O W E ? T F
N T F N O W E ? ? ?      N T F N O W E ? ? ?
O O F O O W E ? O O      O T O O O W E ? O T
W W W W W W W ? W W      W W W W W W W ? W W
E E E E E E E ? E E      E E E E E E E ? E E
V T F ? O F F ? ? ?      V T T ? T F F ? T ?
R F F ? O W ? ? ? ?      R T T ? O W ? ? ? ?
P T F ? O W ? ? ? ?      P T F ? T W ? ? ? ?


• Default, that is opposite to Opposite.
• Merge Possible with Valid.

## Sandbox questions

1. Will this be too easy in some languages that already have all of them?

In languages that has True defined to be -1 and unifies bitwise and logical operations, most integers would works as Partial. GCD/LCM in APL is similar to this. SQL null is Whatever Partial. Most languages that has shortcut evaluation has errors as Error. Not sure about Absent, though.

(Maybe the easiest way to find out is to post this question. It doesn't make the answer bad. But it's just some consideration in the sandbox for me to decide whether I'll post a stronger version.)

2. Allowing "operators and chains of operators" seems to open a can of worms. Should I just remove this rule?

• How about Opposite that behaves like the negation of the other operand? – Zgarb Dec 11 '16 at 19:10
• @Zgarb Too similar to Other. For the "2 more to be added", I intended to make it possible to write expressions to 1) decide whether a variable is a specific value, and 2) return a specific value if a variable is true, or false otherwise. This may make the list more useful later. – jimmy23013 Dec 11 '16 at 19:42
• @Zgarb I gave up and even removed one, to make hardcoding the tables less likely to be the optimal way. – jimmy23013 Dec 13 '16 at 17:56
• if(whatever){/*???*/} – Pavel Dec 13 '16 at 20:23
• @Zgarb I forgot this post for some reasons. Now I found your idea quite interesting. But I'll post the first version without it, and may add a stronger version if it worked well or is too easy, and may name it Degenerate to make most of the other results from operations make sense. – jimmy23013 Apr 30 at 8:40

# Do X with Y code-golfascii-art

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 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
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
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
y                 y
y                 y


# Input

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

# Output

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?
• 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. – Giuseppe Jun 3 at 21:37
• 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. – xnor Jun 4 at 4:49
• 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. – someone Jun 13 at 14:53

# Analog is Obtuse!

• This is the inverse of your challenge. You should also add the date tag, as that's used for datetime challenges. – AdmBorkBork May 28 at 19:17
• 12:30 isn't 180°, but 165°. – Erik the Outgolfer May 28 at 19:26
• @EriktheOutgolfer oh of course, the hour hand still moves. My bad – Skidsdev May 28 at 20:02
• The answer will always be a multiple of 0.5, so "accurate to at least 2 decimal places" is a very weird requirement. Just require the exact answer. – Grimy May 29 at 14:19
• @Grimy good point, I hadn't taken the time to actually think through possible answers – Skidsdev May 29 at 14:27
• Side note: When I used to write table quizzes, one of my go-to questions was to ask the acute angle between the minute and hour hands on a standard analogue watch when it was a quarter past 12 because 90% of people would incorrectly say 90°. Another favourite was to ask the same question but with a digital watch instead - 100% of people used to get that one wrong! – Shaggy Jun 1 at 23:40

This challenge (and several others to follow) is intended to be posted whenever R is the language of the month, so I'll be adding some text up here about that. This is a multipart series inspired by different R functions.

# fivenum and a little bit

Given a dataset $$\D\$$ of integers, I need you to compute the 5 number summary of $$\D\$$. However, I'm working on large datasets, so I need your code to be as small as possible, allowing me to store everything on my computer.

The five number summary consists of:

• Minimum value
• First quartile (Q1)
• Median / Second quartile (Q2)
• Third quartile (Q3)
• Maximum value

There are several different ways of defining the quartiles, but we will use the one implemented by R.

## Definitions:

• Minimum and maximum -- smallest and largest values, respectively.
• Median: the middle value if $$\D\$$ has an odd number of entries, and the artithmetic mean of the two middle-most values if $$\D\$$ has an even number of entries. Note that this means the median may be a non-integer value.
• First and Third Quartiles: Divide the data into two halves, including the median value in each half if $$\D\$$ has an odd number of entries, and find the median value of each. The median of the lower half is the First Quartile, and the median of the upper half is the Third Quartile.

## Examples:

$$\D=[1,2,3,4,5]\$$. The median is then $$\3\$$, and the lower half is $$\[1,2,3]\$$, yielding a first quartile of $$\2\$$, and the upper half is $$\[3,4,5]\$$, yielding a third quartile of $$\4\$$.

$$\D=[1,3,3,4,5,6,7,10]\$$. The median is $$\4.5\$$, and the lower half is $$\[1,3,3,4]\$$, yielding a first quartile of $$\3\$$, and the upper half is $$\[5,6,7,10]\$$, yielding a third quartile of $$\6.5\$$.

• input is as an array or your language's nearest equivalent.
• You may return/print the results in any consistent order, and in whichever flexible format you like, but please denote the order and format in your answer.
• Built-in functions that compute these values are allowed, but I would also like to see self-implemented solutions.
• This is , so shortest answer in each language wins!

# To-do

• test cases (repeated values, etc.)
• I still don't like my definition of median/quartiles

# sandbox questions

• Peter Taylor raises a good question in the comments: should I guarantee output to only be integers?
• I was also considering posting a challenge to compute the Median Absolute Deviation (MAD), which is the median of the dataset $$\\{|D_i-M|\}\$$, where $$\M\$$ is the median of $$\D\$$. Would each challenge stand on its own? They both boil down to finding the median efficiently, and we already have a challenge for that.
• 1. For completeness, you should define the median. In particular, given that the input is integers and all the examples have integer outputs, you should make clear whether or not the median of an even number of elements can be non-integral. 2. In "lower and upper halves (less than the median and greater than the median)" the parenthetical statement makes things more confusing, not less. E.g. take $[1,3,3,3,6,10]$: the median is 3, but without the parenthetical statement I would assume that the two halves are $[1,3,3]$ and $[3,6,10]$. – Peter Taylor Aug 24 '18 at 10:02
• @PeterTaylor thank you, for the suggestions. I do have a definition of median, but on reflection it's pretty unclear. I'll clean up the definitions of the quartiles as well. – Giuseppe Aug 24 '18 at 14:22
• Mea culpa: I see it now. – Peter Taylor Aug 24 '18 at 17:59

# A quine of sorts

Given a string x, output the characters in x sorted according to order of appearance in your source code.

## Examples

Source: ThisIs A Test
Input: Is it a Test?
Output: TissI   etta?

Source: Harry - yer a wizard.
Input: I'm a what?
Output: aa  wh'?Imt

Source: Mr. H. Potter, The Floor, Hut-on-the-Rock, The Sea
Input:
Output:


## Rules

• Standard loopholes & i/o apply
• Input & output can be either a string, a list of characters, or a list of bytes.
• If a character is used multiple times in the source, use the first occurrence.
• If one or more characters does not appear in the source, they should be at the end; their order does not matter, nor does it have to be consistent.
• Source must be non-empty
• This is , so shortest answer in bytes for each language wins!

## Meta

This is my first question, so feedback is very welcome!

New contributor
tjjfvi is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
• Shouldn't the output of your first example be TisIs etaI? instead? The I comes before the second s. If instead all s should be together, shouldn't it then be TissII eta? instead (both I together)? As for the second test case, where is that , coming from and where is the m (typo I assume)? – Kevin Cruijssen 2 days ago
• @KevinCruijssen Yes, that was a typo; fixed. I looked at the examples again and realized the first was very wrong, so I have auto-generated them and they should be good now. Thanks for the catches! – tjjfvi 2 days ago
• @KevinCruijssen Do you think I need to be more explicit that the characters should be grouped? – tjjfvi 2 days ago
• Now that the test cases are fixed it looks a lot clearer, and the examples are fine as well (since the characters not in the source are in a random order in the second input, which is good). I've already prepared a solution. Still need to golf it a bit, though. ;) – Kevin Cruijssen 2 days ago
• @KevinCruijssen Nice! Would you recommend I post it now or wait some more? – tjjfvi yesterday
• It's usually best to leave a challenge at least 72 hours in the sandbox, but it usually depends on the challenge. I personally don't see anything unclear anymore about the current challenge description now that the test cases are fixed. But maybe someone sees a loophole in the rules I might have missed, so perhaps leave it a bit longer? You could also ask in the Nineteenth byte chat if anyone has anything more to add, and if not you'll post it in X hours from now. – Kevin Cruijssen yesterday
• @KevinCruijssen Ok; thanks! – tjjfvi yesterday

# Do the 26 richest billionaires own as much wealth as the poorest 3.8 billion people?

## Introduction:

I just read this post with the same title when I came across it in the HNQ. In this question it is being discussed if the claim of president-candidate Bernie Sanders, who claimed the following:

Today the world's richest 26 billionaires, 26, now own as much wealth as the poorest 3.8 billion people on the planet, half of the world's population.

is true or not. Please go to the question itself for answers and discussions there.

As for the actual challenge based on this claim:

## Challenge:

Two inputs: a descending sorted number-list $$\L\$$ and a number $$\n\$$ (where $$\n\$$ is $$\1\leq n\lt \text{length of }L\$$).
Output: the longest possible suffix sub-list of $$\L\$$ for which the total sum is $$\\leq\$$ the sum of the first $$\n\$$ values in list $$\L\$$.

Example:

Inputs: $$\L\$$ = [500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3] and $$\n=2\$$.
Output: [125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]

Why?

The first $$\n=2\$$ values of the list $$\L\$$ ([500,200]) sum to 700. If we take all suffices of the remaining numbers, as well as their sums:

Suffix:                                                                  Sum:

[-3]                                                                     -3
[-3,-2]                                                                  -5
[-3,-2,0]                                                                -5
[-3,-2,0,1]                                                              -4
[-3,-2,0,2,1]                                                            -2
[-3,-2,0,2,2,1]                                                          0
[-3,-2,0,3,2,2,1]                                                        3
[-3,-2,0,5,3,2,2,1]                                                      8
[-3,-2,0,5,5,3,2,2,1]                                                    13
[-3,-2,0,5,5,5,3,2,2,1]                                                  18
[-3,-2,0,5,5,5,5,3,2,2,1]                                                23
[-3,-2,0,10,5,5,5,5,3,2,2,1]                                             33
[-3,-2,0,10,10,5,5,5,5,3,2,2,1]                                          43
[-3,-2,0,20,10,10,5,5,5,5,3,2,2,1]                                       63
[-3,-2,0,30,20,10,10,5,5,5,5,3,2,2,1]                                    93
[-3,-2,0,30,30,20,10,10,5,5,5,5,3,2,2,1]                                 123
[-3,-2,0,40,30,30,20,10,10,5,5,5,5,3,2,2,1]                              163
[-3,-2,0,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1]                           213
[-3,-2,0,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1]                        268
[-3,-2,0,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1]                     343
[-3,-2,0,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1]                  418
[-3,-2,0,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1]              518
[-3,-2,0,125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1]          643
[-3,-2,0,150,125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1]      793
[-3,-2,0,150,150,125,100,75,75,55,50,40,30,30,20,10,10,5,5,5,5,3,2,2,1]  943


The longest suffix which has a sum lower than or equal to 700 is [125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3] with a sum of 643, so that is our result.

## Challenge rules:

• Values in the first $$\n\$$ prefix aren't counted towards the output-suffix. I.e. inputs $$\L\$$ = [10,5,5,3] and $$\n=2\$$ would result in [5,3], and not [5,5,3].
• I/O is flexible. You can input $$\L\$$ as a list/stream/array of integers/decimals/strings, a single delimited string, one by one through STDIN, etc. You can output with as a list/stream/array of integers/decimals/strings as well, print/return a delimited string, print a number on each newline, etc. Your call.

## General rules:

• This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
• Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
• Default Loopholes are forbidden.

## Test cases:

Inputs: L=[500,200,150,150,125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3], n=2
Output: [125,100,75,75,55,50,40,30,30,20,10,10,8,5,5,5,3,2,2,1,0,-2,-3]

Inputs: L=[10,5,5,3], n=2
Output: [5,3]


More to come.

• “You can output with a delimiter, or print a number on each newline. Your call.” Is this necessary? You’ve already got the default I/O rules bit. Re the question about having to exclude the first n values, I think keep it. It adds a little (but not too much) complexity. – Nick Kennedy yesterday
• @NickKennedy With default I/O I usually think of program vs function, and using either function arguments, STDIN, or program arguments for input. For that reason I usually add a section in the rules section for some examples of allowed input/output types, like the list/array/stream or printing/returning with delimiter in this case. But if you think it's redundant I'll remove that bit. – Kevin Cruijssen yesterday
• do keep it if you like. It might be worth explicitly adding to that sentence the fact that output can be an array etc. though, because when I first came to it I assumed that output had to be a string with delimiters rather than for example an array or list. – Nick Kennedy yesterday
• @NickKennedy Expanded a bit, thanks! And I've removed my Sandbox question. I indeed think it's better to keep it this way. – Kevin Cruijssen yesterday
• Note that the answers in the linked question seem to imply it should allow negative numbers... which is not very reasonable, but it's likely someone will comment on this. – jimmy23013 19 hours ago
• @jimmy23013 The second challenge rule is "The input numbers are guaranteed to be positive integers." Should I also mention it elsewhere to make it more clear? – Kevin Cruijssen 19 hours ago
• Not sure. I didn't read most of the spec and only tried to find whether they must be positive because of that question, and I found it. Not sure whether a normal reader will notice it. But everyone will probably at least notice the examples are all positive. – jimmy23013 19 hours ago
• I find that these kinds of questions are usually more interesting the closer they fit the source. I think it may be a good idea to allow negative numbers to increase the suffix length and also to change the output to the length of the suffix (i.e. answer how many people are as wealthy as the $n$ wealthiest). That's just an opinion though, I think it is pretty good as is. Though some language is a bit muddy, I had a hard time parsing the output line on my first try. – FryAmTheEggman 16 hours ago
• @FryAmTheEggman I've changed it so it's also possible for negative integers to be in the list. Let me know if everything is clear. I just have to add more test cases (suggestions by anyone are welcome). – Kevin Cruijssen 1 hour ago

# Count Syllables

The goal of this challenge is to write a program that can count the syllables in a word as accurately as possible.

## Input

On STDIN, your program will receive a number X followed by X lines, each containing a single word. Simple enough. (Should there be a limit on the size of X?) The words will come from this list.

4
challenge
to
count
syllables


## Output

Your output should be to STDOUT and have X lines. On each line should be the number of syllables counted in that word.

2
1
1
3


# Scoring

To score you program, it will receive a long secret list of words to test. All programs will receive the same list of words. For each word, the number of syllables that your program got wrong will be added to the score of the program. If it output a 4 or a 2 when the word had 3 syllables, then one point will be added. If it said a 15 instead of a 3, then 12 points will be added to the score. The lower the score, the better.

For example, if for the above input your program output 3 2 2 2 (which would be produced by a program that counts strings of vowels), then the program would receive a score of 2.

# Rules

Your program should not access any external files (such as the word list). Also, your program should be no more than 5,000 bytes long (is this a reasonable limit?).

The winner will be the person whose program has the lowest score, therefor the most accurate syllable counter. The deadline for submissions is [some time at least a month away].

# Suggestions

I am open to all constructive criticism. Is 5,000 bytes a reasonable limit for the program size? How long should the official scoring test be? How long should the deadline be?

• This has one major flaw: the output is subjective. How many syllables do these words have? Every; victory; hierarchy; desire; oil; hour; poem. The only real way I see to work around this is for you to produce a marked-up version of the word list. – Peter Taylor May 29 '12 at 20:40
• I was really worried about that, and I don't see a way around it. – PhiNotPi May 29 '12 at 20:42
• I personally would love to see more language processing challenges. I agree with @PeterTaylor on the difficulty of some words. Perhaps taking a specific text(s) and identifying explicitly in the challenge which words will have how many syllables? – Gaffi Jun 8 '12 at 3:34
• @PeterTaylor ...Or maybe you could filter ambiguous words out of the reference list? – user16991 Feb 8 '15 at 1:19
• What's the point of the first line of input? – msh210 Apr 27 '16 at 20:05
• If you provide a reference list, A hyphenated reference list, and hide a secret list which may or may not include members of the reference list, this would be a reasonable challenge – Rohan Jhunjhunwala Sep 17 '16 at 0:05
• Do you plan to post this? If not, I'd be happy to adopt it. (If you don't respond within two weeks, by community standards, I'm allowed to do so.) – MD XF Aug 18 '17 at 3:20
• The example of inaccurate program that would score 2 - did you mean to output 3 1 1 2 rather than 3 2 2 2? – Heimdall Nov 9 '17 at 18:31
• A reference list could be dynamic: potential contestants can ask for words of their choice to be added to the list. They won't know what's on the secret list but will try to make their programs as accurate as possible (according to your syllable count) so they should always be able to ask for specific words they are not sure about. Of course, you could make it in different language. In my language, Slovene, it's much clearer how many syllables words have. How about Solresol, haha! – Heimdall Nov 9 '17 at 18:38
• I am going to adopt this if you don''t respond – Christopher Dec 20 '17 at 16:48

## Play Simple 2-Dimensional Minecraft

Recently I found this video of "HansLemurson" showing a computer that was built in minecraft, which runs minecraft. He is playing minecraft on a computer that was built in minecraft that is running on his computer. To be specific, it is a two dimensional version with an 8x8 grid of cells. There is gravity, block placement, and even jumping. It is worth noting that the computer is single purpose. The same person has built programmable computers, but making them single purpose allows the computer to be much smaller.

## Details

The minecraft world is an 8x8 grid (one horizontal and one vertical dimension). The grid is comprised of either Xs (representing blocks) or empty spaces. The player is an X that is blinking on and off about once every second.

There are two modes in the game, controlled by a toggle switch. The first mode is movement. This is controlled by a WASD-like button arrangement. If the player chooses to move left/right/down, the computer checks to see if the space immediately in that direction is empty. If so, then the player moves into that space.

If the player chooses to move up, then the computer checks that the block underneath the player is solid. If so, then the player moves upward two units. Notice that this can propel the player into a solid block. If this happens, the player is obscured by the solid block, but can still move to an empty block next to him. When the player is inside on a solid block, the game continues as if the block isn't there, although the block is still there once the player leaves it.

After each move, the player falls down one unit if there is empty space there. This simulates gravity. This is also why moving up moves up two units, so that the gravity makes a net movement of up one unit. Gravity does not cause the player to fall all of the way to the ground, just one unit.

The second mode is block placement. In this mode, the same exact WASD buttons are used. Instead of moving the player, they toggle the state of the block in that direction. If the player presses "left" and there is a block there, then the block is destroyed. If there is not a block there, then a block is placed. Again after this move, the player is again subject to gravity. The blocks are not subject to falling.

Toggling the toggle switch does not count as a move, and does not invoke gravity.

The game board is a torus, so all actions (movement, block creation) can wrap around the board. The board does not scroll with the player. The player moves, and the blocks stay in the same place.

## The challenge

You challenge is to write the shortest program that simulates this game. Your program should display and update the map correctly (with Xs as blocks, and with the blinking player). It should accept input from a button that toggles the state and four buttons for movement and actions. This is code golf.

There are imaginary bonus points for adding more features (block types, game size, etc) to your game.

## Suggestions?

• With more complicated challenges I find that it helps to do a reference implementation so that you have a very concrete idea of how much work is involved. Aside from that, I like it. – dmckee Jun 3 '12 at 20:11
• Is the blink rate selected to fit with the ANSI escape sequence? Either way I would explicitly allow that, because it's the obvious way to do it on compatible terminals. – Peter Taylor Jun 5 '12 at 7:14
• The blink rate wasn't selected to be anything specific. I think that I will broaden the restriction. Maybe any blink rate between 3 blinks per second to 1 blink every 2 seconds. – PhiNotPi Jun 5 '12 at 20:21
• @programmer5000 No, for two main reasons: First, challenges can go extended periods of time in the sandbox before they are posted and/or adopted. In the past I've posted challenges after not touching them for 4 years. Second, deleting this answer will not reduce lag, as deleted answers are still present, simply not visible. Users with sufficient rep will see all 4040 answers in the sandbox, and you will too once you earn the "view deleted answers" privilege. – PhiNotPi Apr 13 '17 at 18:15

Overview:

Let's say you've decided to operate your computer using voice recognition software, but unfortunately you did a horrible job researching the various products out there and chose a package that does not recognize numbers as numerals, only words. (i.e. "one" (spoken) == "one" (typed), not "1".) Rather than spend more money to get another option, you decide to make do. Now you want to use the computer's calculator, but this poses a problem, since your machine doesn't know how to add "one plus one".

Objective:

Implement a basic calculator that will read in a string of the written-out equation, perform the correct calculations, then return the result in its text form. Your code should be as short as possible; this is code golf.

Rules/Constraints:

• Input/output will be using your preferred method (STDIN, ARGV, etc.).
• Your calculator must be able to handle input and output within the billions (non-inclusive) -1,000,000,000 < i < 1,000,000,000, but you may expand to more if you wish.
• Decimal values and/or parts must be accepted (0 < i < 1) up to 3 places/digits.
• When calculating answers, proper rounding must be used, so "three point one four one five nine two six" must be returned as "three point one four two".
• Basic calculator functions required:
• "Add"/"Plus"/"Sum"/"And" (+)
• "Subtract"/"Minus"/"Remove" (-)
• "Multiply"/"Times" (*)
• "Divide"/"Divided"/"Divide by"/"Divided by" (/)
• "Raise"/"Exponent"/"Power"/"To the power of" (^)
• "<Base>Root"/"<Base>Radical" (√)
• "Point"/"Decimal" (.)
• "Pi" (π)
• All strings in the list above must be accounted for in your code, capitalization does not matter.
• Numbers may be presented as their full value ("one thousand") or by digit (one zero zero zero).
• Negative numbers may be assigned using "Minus" or "Negative".
• The string "Minus" bust be accounted for as an operator and identifier. (see example)
• "And" is only acceptable as an operator, not as part of a named number.
• "one hundred and one"
• "one hundred one"
• "a" or the absence of a number does not equate to any number; all numbers will be explicitly accounted for in the program input.
• "a hundred" does not equate to "one hundred" and is not a valid input.
• No more than 2 terms will be used.
• "one plus one minus one" will not be implemented.
• If an invalid input is supplied, your function/program should handle the error and exit gracefully with an error description.

Example I/O:

• "one add one" --> "two"
• "five thousand thirty four subtract ten thousand six hundred" --> "negative five thousand five hundred sixty six"
• Alternatively: "five zero three four subtract one zero six zero zero"
• "three root twenty seven" --> "three"
• "ten minus minus ten" --> "twenty"
• Alternatively: "ten subtract negative ten"

## Sandbox Questions:

1. Is this too basic/complicated? (I'm assuming some languages will handle this much more simply than the method I have in my head...)
2. Does the title fit?
3. Are there any constraints that should be added/lifted?
4. Are any more examples needed for clarification?

• Not everyone says numbers the same way. Does the parser have to treat the following as equivalent? "negative one hundred five", "minus one hundred five", "negative one hundred and five", "minus one hundred and five", "negative a hundred five", "negative a hundred and five", ...? – Peter Taylor Jun 15 '12 at 15:12
• @PeterTaylor I had had a similar thought re: operators. ("plus" versus "add", etc.) I think it would be more interesting to account for all, but given the wide variety of possible inputs, it may generally be better to limit the options to a specifically defined set (which I have yet to define). – Gaffi Jun 15 '12 at 15:18
• @PeterTaylor I've added some of these details. Please let me know if there's anything unclear about them. – Gaffi Jun 15 '12 at 16:10
• I don't spot any ambiguities in the parser. There is still an ambiguity relating to decimals, though. What precision should be used? Also, I notice now that there's no winning condition. Is this intended to be code-golf? (Ugh - tons of strings which will have to be hard-coded in most languages. I expect Perl has a suitable parser already in CPAN, though...) – Peter Taylor Jun 19 '12 at 9:03
• @PeterTaylor I don't know where I went... I've updated the spec. re: decimal places and objective. – Gaffi Jun 29 '12 at 13:24
• @PeterTaylor metacpan.org/pod/Lingua::EN::Words2Nums – msh210 Apr 27 '16 at 20:37
• Can we delete this because the sandbox lags so much and this hasn't been touched in 5 years? – programmer5000 Apr 13 '17 at 17:36

# Huffman Decoding

Write a programm which takes two strings as input and prints a text.

The first argument is a Huffman Tree, serialized in the following format:

• every ascii character except ~ is always a leaf, if ~ is the first characater it is also a leaf.
• <tree0><tree1>~ is a tree where <tree0> is the left subtree and <tree1> is the right subtree.

Example: ab~cde~~~ generates this tree:

 ┌─┴─┐
┌┴┐ ┌┴─┐
a b c ┌┴┐
d e


where a would have the key 00, b 01, c 10, d 110 and e the key 111.

The second argument is a text that has been compressed with with the Huffman code that is defined by the first parameter. This bit-string can contain any bit sequence (also null-bytes and non-printable characters) and is not byte aligned, therefore it has been encoded with a variation of the standard Base64 encoding:

• the characters used for the encoding are the standard base64 characters: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
• the bitstring is broken up into 6-bit chunks and mapped to this characters
• if the last chunk is smaller than 6 bits, a character with this prefix is used, and padding characters are added to the string:
• - : the last chunk was five bits long
• = : the last chunk was four bits long
• =- : the last chunk was three bits long
• == : the last chunk was two bits long
• ==- : the last chunk was one bit long

Example:

bits:       1 1 1 1 0 1 1 0 1 0 0 1 1 1 0 1 0 1 0 0 0 1 1 0 1
chunks:    |1 1 1 1 0 1|1 0 1 0 0 1|1 1 0 1 0 1|0 0 0 1 1 0|1[0 0 0 0 0]|
characters:       9           p           1           G           g
base64:     9p1Gg==-


Your programm has to decode the text encoded in the second parameter and print it to stdout.

You have to provide your source code encoded in the way described above. The length of your encoded source code + the length of your serialized huffman tree will be the winning criterion.

TODO: example input

• It would be helpful to explicitly state the 64 characters used in the encoding. I presume they're A-Za-z0-9+/ but (especially if you're expecting people to implement that part explicitly) it's best to make the problem self-contained. – Peter Taylor Oct 8 '12 at 16:23
• Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) – programmer5000 Jun 9 '17 at 15:30

# Graphical Output -- Esoteric Artifacts -- The Glass Bead Game

## Draw the Cabalistic Tree of Life

Simply described, the Tree of Life is an undirected network of nodes representing the conduit between matter and higher forms of spiritual energy. It has an upper face arranged in a hexagon, and a lower fact built from equilateral triangles adjacent to the lower two edges of the upper face. Don't label the paths, paths may overlap however you wish, may be single (thick) lines, even. Code Golf. Bonus -100 for labels on the Sephiroth (nodes); Bonus -150 for Hebrew labels.

## Draw a Mandala for each Natural Number

Draw a circle with interesting visual patterns using the input N [ 1 .. \inf ) to determine the number of points around the circle to anchor figures whose shape is also modified by the input N. Actually, 12 seems like a good max: they're pretty much a blur after that no matter what.

//lotsoflines n = 1 ..12

(doesn't need to be this elaborate, This is >600 lines of showing-off.).

. . . need good images for these . . .

## Draw the Ptolemeic System of the Universe

All the stuff I could find is animated already. Maybe this one's done-to-death. :(

Update: Found good stuff on Alchemy. The "Keplar Platonic" model could be fun (3D and all). This one looks good, too. And this.

## Draw the Pythagorean Monochord

aka pre-classical nomogram. I misplaced my Pythagoras books, I know I've got a picture somewhere.

This is the one I was thinking of.

But I think this one's even cooler

## Draw the I-Ching Hexagrams in King Wen Sequence.

I suppose I need to implement this first to avoid copyright issues! :)

• The I-Ching one would have to be in standard order to be remotely interesting, and then becomes as much about kolmogorov-complexity as graphical-output – Peter Taylor Nov 22 '12 at 21:24
• For the others: images, please! – Peter Taylor Nov 22 '12 at 21:25
• I've emailed the owner of the Alchemy pages asking for permission to use his copyrighted images. Awaiting response. – luser droog Jan 28 '13 at 8:25
• Can we delete this because the sandbox lags so much and this hasn't been touched in 5 years? – programmer5000 Apr 13 '17 at 17:42

## DeCSS

It is known that the DVD Content Scrambling System can be deciphered with a rather short program (434 bytes of C, 472 bytes of Perl). Can you do better?

<< Test cases go here >>

I don't plan to include a more detailed spec, because it will just wind up duplicating some of the code. The test cases would be in the form of (key, link to data file, md5sum of the deciphered stream).

• And the winning criterion is who is the first to get post from the courts? – celtschk Oct 3 '15 at 20:18
• @celtschk, I think that would be unfair. Winning criteria shouldn't really depend on where people live... – Peter Taylor Oct 10 '15 at 20:56
• I think you should at least explain the general concept of the spec. – Rohan Jhunjhunwala Aug 2 '16 at 22:53
• This actually sounds interesting. @PeterTaylor Perhaps you could use (and link to) Charles Hannum's explanation of the algorithm and post this. (It would be fun to have it as a popularity contest for a program that looks like it's nothing DeCSS related, or a program that furthers the gallery's point about the text vs source code arbitrary distinction - but I don't know if popularity contests are popular any more!) – sundar Jun 25 '18 at 8:25

## Code golfing problem: Surface classification

The task: Given a surface-word reply with the classification of what surface it is.

Example 1: Input: aba'b' ----> Output: 1T

Example 2: Input: aabcb'c' ----> Output: 3P

Bounds on the problem: Since there are only 26 letters, there will never be more than that many labels. Additionally output should be in the form S,nT,mP for n,m positive integers.

Background: In the study of algebraic topology students are often presented with diagrams such as the one below. The represent instructions for how to assemble a surface. The assembly is prescribed as: if there are two edges labeled with the letter x then glue them together so that the arrows point the same direction. To make our job easy, topologists have discovered an algorithmic way to classify surfaces using 'words' assembled from these 'plane gluing-diagrams'.

Choosing a corner arbitrarily (top right) and orientation (ccw) we read off the labels on the edges where an inverse appears wherever the arrow points against the orientation. In this case the 'word' that represents this plane model is given as abab.

A surface word is a string that contains the letters a,b,...,@ up to some letter @ and each letter is contained in it exactly twice. In the two occurrences of each letter: 0, 1, or 2 of them may be postfixed by a ' which I am considering using to represent 'inverse' (opposite orientation).

If in a surface word all letters appear twice: once without the ' and once with it (f.ex. ba'b'a) then we say that the surface the word represents is orientable. If a surface is orientable then it is necessarily the direct sum of n Tori for some non-negative integer n. If this condition doesn't hold (like in aab'b) then the surface represented is non-orientable: in this case it is the direct sum of m Projective Planes for some positive integer m.

Once you have found out if the reduced word is orientable or not, the final answer is given as follows. If orientable and number of unique letters in the reduced word is 1 then output should be S. Otherwise if the number of unique letters in an orientable word is n (it will be even) then the output should be sT where s = n/2. If the word is non-orientable then the output should be mP where m is the number of distinct letters in the reduced word.

The goal is to take as input some surface word, reduce it via reduction rules 1-6 and then classify it as a sphere, some number of connected tori, or some number of connected projective planes. Here are the 6 reduction rules where ~ represents 'reduces to':

Let M,A,B,C,D be surface words, x be a single letter, and juxtaposition represents concatenation:

1. Cycle Rule: If M = AB then M ~ BA
2. Flip Rule: M ~ M'
3. Sphere Rule: Axx'B ~ AB
4. Block Rule: ABC ~ ADC if B is a surface word and B ~ D by 1 or 2
5. Cylinder Rule: If M = AxBCx'D, then M ~ AxCBx'D
6. Möbius Rule: If M = AxBxC then M ~ AxxB'C ~ AB'xxC

I am looking for input on:

• should this be code-golf or programming-challenge?
• how would scoring work?
• ???

If I feel satisfied with the question in a few days I'll post it to the site.

• If, for each input, there is only one correct output, then it should probably be code-golf. The scoring criteria would then be source code length. – PhiNotPi Jun 8 '13 at 14:33
• Yes, this is the case. In general however there is not a unique series of applications of the reduction rules for any given instance. – Kaya Jun 8 '13 at 16:21
• I don't think the order of explanation is correct. You should explain reduction before talking about "the reduced word". And "reduce it via reduction rules" doesn't entirely make sense, because the rules are presented as equivalences rather than reductions, and most of them don't have a "natural" direction. – Peter Taylor Jun 10 '13 at 8:49
• It's also occurred to me that you haven't defined the notation M'. Does it just consist of toggling the orientation of each token, or does it also reverse the entire string? And do you have test cases which between them force implementation of all of the reduction rules? – Peter Taylor Jun 11 '13 at 8:32
• Good call on the string inverse, yes you have the right idea and I will make it clear. I have a lot of test cases from when I did a number of these computations by hand in a university course and (anecdotal experience) I am pretty sure that it is possible to force the use of all the reduction rules (except maybe 4 which is really just a meta-rule for convenience when doing proofs). Additionally you have alerted me to some concerns regarding the form of the proper output: it's definitely underspecified. I'll put some work into this today. – Kaya Jun 11 '13 at 14:04

I have no idea how to create a good code golf question!

See this description of a ray tracer with source code that fits on a business card. The author stopped when the code size was 1337 bytes.

Achieving identical output, optimise for minimum code size. Execution time is not relevant.

• I think what you have here is a straight ahead golf. All languages. You need only define the requirements. Do you want identical output or do you want "good output encompassing <list of features>"? – dmckee Oct 6 '13 at 17:22
• For a minimum feature list I'd suggest something like (1) it is ray tracer (2) supports point-like lights and shadow + ambient light (3) supports mirrored (implies reflection) and matte surfaces (3) all objects are sphere and overlaps are allowed. With no requirement for (a) anti-aliasing; (2) finite sized light sources; (c) atmosphere effect or (d) depth of field; or (e) tiling and gradients. Notice however, that the example supports at least (b), (d) and (e). – dmckee Oct 6 '13 at 17:29
• BTW--The one you linked can get a little bit more with #define Q return (R was already taken for the rand wrapper) and #define O operator. – dmckee Oct 6 '13 at 17:33
• I suggest reading the Teapot question in the sandbox Mk IV and the comments - it's not the same question, but some of the same issues are relevant, and it might give you ideas for improvements to the spec. – Peter Taylor Oct 6 '13 at 22:48
• Yes. Read the teapot question for guidance. Ultimately I decided that one was too big, but we did get into some pertinent details. – luser droog Dec 1 '13 at 9:48
• This sandbox post has had little activity in a while and little positive reception from the community. Please improve / edit it or delete it to help us clean up the sandbox. – programmer5000 Jun 9 '17 at 15:32

# Count unique characters in text.

Given a string for input, output the unique non-whitespace characters in that string along with a count of their occurrences. The list should be sorted in ascending order of ASCII code.

Examples

Input:

Hello, World!


Output:

Character    Count
!            1
,            1
H            1
W            1
d            1
e            1
l            3
o            2
r            1


Input:

The quick brown fox jumps over the lazy dog.


Output:

Character    Count
.            1
T            1
a            1
b            1
c            1
d            1
e            3
f            1
g            1
h            2
i            1
j            1
k            1
l            1
m            1
n            1
o            4
p            1
q            1
r            1
s            1
t            1
u            1
v            1
w            1
x            1
y            1
z            1


The actual formatting (headers, spacing, etc) of the on-screen output is up to you. The only conditions are that it must be sorted in ascending order by ASCII code, and it must be easy to tell what represents a character from the string and what represents a count of a given character. (For example, given a string of 99999999, the output should be explicit so that it is not confused as saying I have 9 8s.)

Ultimate challenge (taken from here):

JKqdJg+oJgiowgyIJgkS+gyxJdeS+gyxJ4yoJdybJdioJdqIJ4kS+KwFJ4QS+gzYJg+ow4vIJ4yxvd+IJgy=+dv=JdQx+gzbJrzx24zYJgkxJ4qLJKQxJ4yxJKqx+KqdJKqdJg+oJgiowgyIJgkS+gyxJdeo24yxJm+xJdybJdioJdqIJKi=J4wF+dvS+gzYJg+ow4zYJ4yxvdy=J4i=+Kv=JdQo+KqxJrzdJKzYJgkxJ4qLJgkxJ4yxJKvSJ4qbJKqdJg+oJgiowgyIJgkdJgyxJdeo24yxJm+xJdybJd+oJd+S+dz=J4wF+dvS+g+SJg+ow4vIJ4yxJ4voJgy=+dv=+dzdJgqxJrzdJKzYJgkS+dweJKQxJ4yxJKvSJ4qbJKq=24yYJgiowgyIJgkdJgzdJryo24yxJm+d24zxJd+oJdqIJ4kS+KwFJ4QS+gzYJ4y=2gzYJ4yxJ4voJgy=+dv=+dzdJgqxJrzx24zYJgkS+dweJKQxJ4fK+dQSJ4qbJKq=24yYJgiowgyIJgkS+gzdJryS+gyxJ4yoJdybJd+oJd+S+dz=J4wF+dvS+gzYJ4y=2gvIJ4yxJ4voJgy=+dv=JdQo+KqxJrzx24zY+dzS+dweJKQxJ4yxJKqx+KqbJKq=24vbJdyowgyIJgkdJgzdJryS+gyxJm+d24zxJdioJd+S+dz=J4wF+dvS+gzYJg+ow4vIJ4yxJ4voJgy=+Kv=JdQx+gzbJrzx24zYJgkS+dweJgkxJ4yxJKvSJ4qdJKq=24yYJgiowgyIJgkdJgzdJryS+gyxJ4yoJdybJd+oJdqIJKi=J4wF+dvS+gzYJg+ow4vIJ4yxJ4v=J4i=+Kv=+dzdJgqxJrzx24zYJgkS+dweJgkxJ4fKJ4qx+KqdJKqdJg+SJdyowg+oJgkS+gyxJdeS+gyxJ4yoJdybJd+oJdqIJ4kS+KwFJ4QS+g+SJ4y=2gzYJ4yxJ4v=J4i=+Kv=JdQo+KqxJrzx24zY+dzS+dweJKQxJ4yxJKvSJ4qbJKqdJg+oJgiowg+oJgkS+gzdJryo24yxJ4yoJdybJdioJdqIJ4kS+KwFJ4QS+g+SJg+ow4vIJ4yxvd+IJgy=+dv=JdQo+KqxJrzdJKzY+dzxJ4qLJKQxJ4yxJKqx+KqdJKq=24vbJdyowg+oJgkS+gzdJryo24yxJ4yoJdybJdioJd+S+dz=J4wFJ4QS+gzYJg+ow4zYJ4yxvd+IJgy=+Kv=+dzdJgqxJrzdJKzYJgkxJ4qLJgkxJ4yxJKvSJ4qbJKq=24vbJdyowgyIJgkdJgyxJdeo24yxJm+xJdybJd+oJdqIJKi=J4wF+dvS+g+SJ4y=2gvIJ4yxvd+IJgy=+dv=+dzdJKzbJrzdJKzY+dzS+dweJgkxJ4yxJKvSJ4qbJKq=24yYJgiowg+oJgkS+gyxJdeo24yxJ4yoJKzxJd+oJdqIJKi=J4wF+dvS+gzYJg+ow4vIJ4yxJ4v=J4i=+dv=+dzdJgqxJrzx24zYJgkxJ4qLJKQxJ4fKJ4qx+KqdJKqdJg+oJgiowgyIJgkS+gzdJryS+gyxJm+d24zxJd+oJdqIJKi=J4wFJ4QS+gzYJ4y=2gzYJ4yxvdy=J4i=+Kv=+dzdJKzbJrzx24zY+dzxJ4qLJKQxJ4yxJKqx+KqdJKqdJg+SJdyowg+oJgkdJgzdJryo24yxJm+d24zxJd+5


• This isn't really an interesting problem. The shortest answer is almost certainly going to be fewer than 10 characters. – Peter Taylor Dec 11 '13 at 12:19
• @PeterTaylor While I mostly agree with your comment - already the header line may contain more than 10 characters. – Howard Dec 12 '13 at 6:15
• "The quick brown fox jumps over the lazy dog." contains "e" three times. – Howard Dec 12 '13 at 6:16
• @Howard Thanks. I must be blind - it took me about five times of reading your comment to find it. Also, do remember that the header is optional to a certain degree - you just need to make sure the output is unambiguous as to which items are characters from the string, and which are character counts. – Iszi Dec 12 '13 at 7:02
• My brain instantly went into bash mode. wc and uniq practically solve half of this, but not in any particularly short manner. – Rob Dec 17 '13 at 20:31

### PETSCII banner

In an other world... I was using a PET 2001 who used some particular PETSCII charset.

The screen green on black, with 40 columns and 25 lines, was only able to display characters from this charset. No way to draw dots or lines...

But in the chaset, there is some ▝ and ▚, which, ( by the use of reverse video in order to obtain 16 chars: ' ','▖','▗','▘','▝','▀','▄','▐','▌','▞','▚','▟','▛','▜','▙','█' ) make us able to draw graphics on a 80x50 dots plan.

Using an internal clock triggering IRQ, I've done a animated prompter like this:

The goal of this is to make a similar banner, with same charset, (but using UTF-8 characters: ' ','▖','▗','▘','▝','▀','▄','▐','▌','▞','▚','▟','▛','▜','▙','█'). Warn, this charset use inverted lower/upper cases.

• This imply the use of PETSCII charset, I will post them there as a json string, before getting this out of the sandbox if some interest...

• The tool have to change his position 20 time per second.

• The tool must accept as argument, the string to display.

• The tool must add date and time in the form - WDay MDay Mnth Year, HH:MM:SS -

• Scrolling have to be done bit per bit: I.E.: by half character!

• Shortest code...
• -3 if size of console is not limited to 40 columns
• -5 if cpu usage stay less than 90% (On my poor Core(TM)2 Duo CPU E8400 @ 3.00GHz, with 4G ram)
• -5+ if cpu usage stay less than 50%
• -5+ if cpu usage stay under 5%

C.U.

• as for the CPU bonuses - what is the target environment, what is the smoothing factor, and what processes count against this measure? – John Dvorak Dec 15 '13 at 6:19
• This sandbox post has had little activity in a while and little positive reception from the community. Please improve / edit it or delete it to help us clean up the sandbox. – programmer5000 Jun 9 '17 at 15:32

# .... . .-.. .-.. --- .-- --- .-. .-.. -..

Another Hello World challenge, this time with Morse code!

Taking no input, your program must output HELLO WORLD in audible Morse code, printing each letter as it is played. For the purpose of this challenge, the following Morse code guidelines will be followed:

Duration of sounds:

• Dits are one time-unit long.
• Dahs are three time-units long.
• The gap between elements within the same character is equal to one dit.
• The gap between characters within the same word is equal to one dah.
• The gap between words is seven time units long.
• The length of "one time unit" is up to the programmer, so long as it is consistent throughout the message.

Letters:

• H: ....
• E: .
• L: .-..
• O: ---
• W: .--
• R: .-.
• D: -..

I'm a little iffy on that last bullet regarding duration. Should I set a hard standard, or a minimum? If so, what to?

• Set a hard minimum for timing. Otherwise, a golfed solution might have 1 unit = 1 millisecond. – PhiNotPi Dec 16 '13 at 22:23
• Tasks which take input are normally more interesting. – Peter Taylor Dec 17 '13 at 0:09
• I guess that dahs need to be a continuous tone, not just two dits without a gap? – John Dvorak Dec 17 '13 at 6:32
• @JanDvorak Correct. – Iszi Dec 17 '13 at 6:33
• If you don't plan to post this, I would like to modify it and post it. (If you don't reply to this message within two weeks, by community standards, I am allowed to adopt the challenge.) – MD XF Dec 22 '17 at 2:41
• @MDXF What do you suggest for modifications? – Iszi Jan 2 '18 at 15:18