435
\$\begingroup\$

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.

To post to the Sandbox, scroll to the bottom of this page or click on the "Add Proposal" link below, and click "Answer This Question". Click "OK" when it asks if you really want to add another answer. Write your challenge just as you would when actually posting it. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it. When you think your challenge is ready for the public, go ahead and post it, replace the post here with a link to the challenge and delete it.

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

The Sandbox works best if you sort posts by "active".

Add Proposal

Search the Sandbox

Browse your pending proposals

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]

\$\endgroup\$
  • 2
    \$\begingroup\$ 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 \$\endgroup\$ – nicael Mar 19 '18 at 19:35
  • 3
    \$\begingroup\$ @nicael We can only choose from three post notices: citation needed, current event, and insufficient explanation. \$\endgroup\$ – Dennis Apr 7 '18 at 14:43
  • \$\begingroup\$ 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 \$\endgroup\$ – Christopher Apr 13 '18 at 17:54
  • 5
    \$\begingroup\$ @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. \$\endgroup\$ – Dennis Apr 13 '18 at 18:17
  • \$\begingroup\$ @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 \$\endgroup\$ – Christopher Apr 13 '18 at 18:18
  • 4
    \$\begingroup\$ @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. \$\endgroup\$ – Dennis Apr 13 '18 at 18:21
  • \$\begingroup\$ @Dennis ohh that makes sense \$\endgroup\$ – Christopher Apr 13 '18 at 18:25
  • \$\begingroup\$ codegolf.meta.stackexchange.com/questions/12599/… \$\endgroup\$ – Redwolf Programs Apr 17 '18 at 17:38
  • 1
    \$\begingroup\$ 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? \$\endgroup\$ – ouflak Aug 6 '18 at 9:07
  • 1
    \$\begingroup\$ @ouflak You can sort posts by "active". That seems to resolve all of the problems you describe. \$\endgroup\$ – FryAmTheEggman Sep 27 '18 at 19:04
  • \$\begingroup\$ I already posted this, but codegolf.stackexchange.com/questions/176599/… \$\endgroup\$ – 2br-2b Nov 27 '18 at 2:38
  • \$\begingroup\$ How are tags added to questions? \$\endgroup\$ – guest271314 Jan 9 at 7:51
  • \$\begingroup\$ It seems like there is a rollback war with moderators and the Community user to add and remove the featured tag. \$\endgroup\$ – smileycreations15 Mar 21 at 21:13
  • 3
    \$\begingroup\$ @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. \$\endgroup\$ – Erik the Outgolfer Mar 24 at 15:22
  • 2
    \$\begingroup\$ @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. \$\endgroup\$ – smileycreations15 Mar 24 at 17:20

2384 Answers 2384

3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

Classic VCS ASCII Adventure

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

\$\endgroup\$
  • 1
    \$\begingroup\$ This seems like a nice challenge! I'm not as experienced as other people around here, but you should publish it to main. \$\endgroup\$ – MilkyWay90 Jan 26 at 16:28
  • \$\begingroup\$ 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? \$\endgroup\$ – ბიმო Jan 28 at 13:27
  • \$\begingroup\$ Maybe you could add an example with both x- and y-stretch factors being negative? \$\endgroup\$ – ბიმო Jan 28 at 13:30
  • \$\begingroup\$ @BMO thank you for your suggestions! I've updated the description to address your points. \$\endgroup\$ – gwaugh Jan 28 at 14:41
  • \$\begingroup\$ 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. \$\endgroup\$ – gwaugh Jan 28 at 17:36
  • \$\begingroup\$ 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. \$\endgroup\$ – Kevin Cruijssen Jan 29 at 13:42
3
\$\begingroup\$

Does this addition pyramid puzzle have a unique solution?

Given an addition pyramid \$P\$, determine whether it can be solved. An addition pyramid consists of layers, each having one number less than the one below it. Layer \$i\$ is symbolized as \$P_i\$. \$P_1\$ is the base layer, and \$P_{i+1}\$ is the layer atop \$P_i\$. The \$j\$th number of \$P_i\$ is denoted as \$P_{i,j}\$. \$P_{i,1}\$ is the leftmost number of \$P_i\$, and \$P_{i,j+1}\$ is the number to the right of \$P_{i,j}\$. You may visualize \$P_{i+1,j}\$ residing on top of \$P_{i,j}\$ and \$P_{i,j+1}\$ at the middle, hence the name "addition pyramid".

  • \$\forall P_{i,j},P_{i,j}\in\mathbb N^*\$, that is, every number in the pyramid is a non-zero positive integer.
  • \$\forall i>1,P_{i,j}=P_{i-1,j}+P_{i-1,j+1}\$, that is, every number not on the base layer of the pyramid is the sum of the two numbers below it.
  • If \$P_1\$ has \$n\$ numbers, \$P_i\$ has \$n-i+1\$ numbers, therefore \$P_{i,n-i+1}\$ is the rightmost number of \$P_i\$. In simpler terms, each layer has one number less than the layer below it.

An addition pyramid puzzle \$Q\$ is an addition pyramid with some numbers removed (replaced with \$?\$). Its solution is an addition pyramid \$P\$, where \$\forall Q_{i,j}\ne{?},P_{i,j}=Q_{i,j}\$, that is, the numbers that were originally present in the puzzle have been left unchanged. Such a puzzle may have more than one solution.

Your job is, given an addition pyramid puzzle, to determine if it has exactly one solution.

Input

You can get input in any of the following forms, but be consistent:

  • Array of layers.
  • Array of layers, shaped like a pyramid using a consistent non-positive-integer value as a separator between elements (used only once each time) as well as left and right padding. The separator and the padding must be the same.
  • Array of layers with a consistent valid right or left padding (you must be consistent and not mix right and left padding in this case).

Please note that a consistent value that's not a strictly positive integer must be used to represent a missing number; this value can't be used as padding. Also, you can take the layers concatenated (you can still separate them), and the ordering can either be from the base to the top or from the top to the base.

Output

One of two consistent distinct values, where one represents the presence of a unique solution and the other the absence of a solution or the presence of more than one solution.

Rules

  • Don't do these things.
  • This is , so the shortest answer wins! However, don't let that discourage you from posting a solution just because your language is "too verbose".

Examples

You may skip these examples.

Unique solution

$$\begin{array}c&&&10\\&&?&&?\\&?&&2&&?\\?&&?&&?&&1\end{array}$$

Step 1: \$x+y=2\leftrightarrow x=y=1\$.

$$\begin{array}c&&&10\\&&?&&?\\&?&&2&&?\\?&&\color{red}1&&\color{red}1&&1\end{array}$$

Step 2: \$x=y=1\leftrightarrow x+y=2\$.

$$\begin{array}c&&&10\\&&?&&?\\&?&&2&&\color{red}2\\?&&1&&1&&1\end{array}$$

Step 3: \$x=y=2\rightarrow x+y=4\$

$$\begin{array}c&&&10\\&&?&&\color{red}4\\&?&&2&&2\\?&&1&&1&&1\end{array}$$

Step 4: \$x+4=10\leftrightarrow x=6\$

$$\begin{array}c&&&10\\&&\color{red}6&&4\\&?&&2&&2\\?&&1&&1&&1\end{array}$$

Steps 5-6 are similar to 4:

$$\begin{array}c&&&10\\&&6&&4\\&\color{red}4&&2&&2\\\color{red}3&&1&&1&&1\end{array}$$

So here we have our unique solution.

No solution 1

$$\begin{array}c&1\\?&&?\end{array}$$

\$\min\mathbb N^*=1\rightarrow x,y\ge1\rightarrow x+y\ge2>1\$, so there is no solution.

No solution 2

$$\begin{array}c&&&10\\&&5&&5\\&2&&3&&2\\?&&?&&?&&?\end{array}$$

Steps 1-2: \$x+y=2\leftrightarrow x=y=1\$.

$$\begin{array}c&&&10\\&&5&&5\\&2&&3&&2\\\color{red}1&&\color{red}1&&\color{red}1&&\color{red}1\end{array}$$

From there, it follows that \$1+1=3\$, which is a contradiction, therefore there's no solution.

Non-unique solution

$$\begin{array}c&&5\\&?&&?\\?&&?&&?\end{array}$$

Two solutions:

$$\begin{array}c&&5&&&&&&&5\\&2&&3&&&&&3&&2\\1&&1&&2&&&2&&1&&1\end{array}$$

Since there are at least two solutions, there's no unique solution.

\$\endgroup\$
3
\$\begingroup\$

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:

  • Please provide a testing framework that can verify that your program is properly radiation-hardened.
\$\endgroup\$
  • 10
    \$\begingroup\$ 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) \$\endgroup\$ – Jo King Mar 18 at 5:03
  • 6
    \$\begingroup\$ Vote here to keep it as radiation-hardening \$\endgroup\$ – Jo King Mar 18 at 5:03
  • 3
    \$\begingroup\$ There is no such thing as something that is too hard for a code-golfer. \$\endgroup\$ – MilkyWay90 Mar 18 at 23:49
3
\$\begingroup\$

Square Sum Problem

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

Input

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

Valid answer:

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

Invalid answer:

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

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

Game results

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

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

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

\$\endgroup\$
3
\$\begingroup\$

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.

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

Output the Visible Spectrum in RGB

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

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

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

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

The challenge

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

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

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

Test cases

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

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

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)

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

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.

Task

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.

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

Golf my Ada arrays

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.

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

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.
  • Nothing. All operations between nothing and another operand return the other operand.
  • Whatever. All operations between whatever and another operand returns whatever (itself).
  • Other. If the result can be decided using the other operand, return that. Otherwise return other (itself).
  • Error. An error as the first operand works like whatever, and an error as the second operand works like other, except that "itself" means error. It has higher precedence than other and whatever.

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 N W O E       or F T N W O E
  F F F F W F F        F F T F W O E
  T F T T W O E        T T T T W T T
  N F T N W O E        N F T N W O E
  W W W W W W W        W W W W W W W
  O F O O W O E        O O T O W O E    
  E E E E E E E        E E E E E E E

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.

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

You may use different ways of input/output for different values, as long as it is consistent for each kind of value.

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

Your score is the total length of the 2 operations * 50 + 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.


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 Other. GCD/LCM in APL is similar to this. SQL null is Whatever. Most languages that has shortcut evaluation has errors as Error. Not sure about Nothing, 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.)


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

Other potential additions:

  • Default, that is opposite to Opposite.
  • Merge Possible with Valid.
\$\endgroup\$
  • \$\begingroup\$ How about Opposite that behaves like the negation of the other operand? \$\endgroup\$ – Zgarb Dec 11 '16 at 19:10
  • \$\begingroup\$ @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. \$\endgroup\$ – jimmy23013 Dec 11 '16 at 19:42
  • \$\begingroup\$ @Zgarb I gave up and even removed one, to make hardcoding the tables less likely to be the optimal way. \$\endgroup\$ – jimmy23013 Dec 13 '16 at 17:56
  • \$\begingroup\$ if(whatever){/*???*/} \$\endgroup\$ – Pavel Dec 13 '16 at 20:23
  • \$\begingroup\$ @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. \$\endgroup\$ – jimmy23013 Apr 30 at 8:40
3
\$\begingroup\$

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

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?

\$\endgroup\$
  • 8
    \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor May 29 '12 at 20:40
  • \$\begingroup\$ I was really worried about that, and I don't see a way around it. \$\endgroup\$ – PhiNotPi May 29 '12 at 20:42
  • 1
    \$\begingroup\$ 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? \$\endgroup\$ – Gaffi Jun 8 '12 at 3:34
  • 2
    \$\begingroup\$ @PeterTaylor ...Or maybe you could filter ambiguous words out of the reference list? \$\endgroup\$ – user16991 Feb 8 '15 at 1:19
  • 1
    \$\begingroup\$ What's the point of the first line of input? \$\endgroup\$ – msh210 Apr 27 '16 at 20:05
  • 1
    \$\begingroup\$ 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 \$\endgroup\$ – Rohan Jhunjhunwala Sep 17 '16 at 0:05
  • \$\begingroup\$ 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.) \$\endgroup\$ – MD XF Aug 18 '17 at 3:20
  • \$\begingroup\$ The example of inaccurate program that would score 2 - did you mean to output 3 1 1 2 rather than 3 2 2 2? \$\endgroup\$ – Heimdall Nov 9 '17 at 18:31
  • \$\begingroup\$ 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! \$\endgroup\$ – Heimdall Nov 9 '17 at 18:38
  • \$\begingroup\$ I am going to adopt this if you don''t respond \$\endgroup\$ – Christopher Dec 20 '17 at 16:48
2
\$\begingroup\$

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?

\$\endgroup\$
  • 2
    \$\begingroup\$ 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. \$\endgroup\$ – dmckee Jun 3 '12 at 20:11
  • \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor Jun 5 '12 at 7:14
  • \$\begingroup\$ 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. \$\endgroup\$ – PhiNotPi Jun 5 '12 at 20:21
  • \$\begingroup\$ @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. \$\endgroup\$ – PhiNotPi Apr 13 '17 at 18:15
2
\$\begingroup\$

Bad Voice Recognition Calculator

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?

Thanks for your input, guys!

\$\endgroup\$
  • \$\begingroup\$ 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", ...? \$\endgroup\$ – Peter Taylor Jun 15 '12 at 15:12
  • \$\begingroup\$ @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). \$\endgroup\$ – Gaffi Jun 15 '12 at 15:18
  • \$\begingroup\$ @PeterTaylor I've added some of these details. Please let me know if there's anything unclear about them. \$\endgroup\$ – Gaffi Jun 15 '12 at 16:10
  • \$\begingroup\$ 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...) \$\endgroup\$ – Peter Taylor Jun 19 '12 at 9:03
  • \$\begingroup\$ @PeterTaylor I don't know where I went... I've updated the spec. re: decimal places and objective. \$\endgroup\$ – Gaffi Jun 29 '12 at 13:24
  • 1
    \$\begingroup\$ @PeterTaylor metacpan.org/pod/Lingua::EN::Words2Nums \$\endgroup\$ – msh210 Apr 27 '16 at 20:37
  • \$\begingroup\$ Can we delete this because the sandbox lags so much and this hasn't been touched in 5 years? \$\endgroup\$ – programmer5000 Apr 13 '17 at 17:36
2
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor Oct 8 '12 at 16:23
  • \$\begingroup\$ 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.) \$\endgroup\$ – programmer5000 Jun 9 '17 at 15:30
2
\$\begingroup\$

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.

Tree of Life after Kirtcher

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.

Eg. http://code.google.com/p/xpost/downloads/detail?name=ve6a.ps
//lotsoflines n = 1 ..12

Mandalas 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! :)

\$\endgroup\$
  • \$\begingroup\$ 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 \$\endgroup\$ – Peter Taylor Nov 22 '12 at 21:24
  • \$\begingroup\$ For the others: images, please! \$\endgroup\$ – Peter Taylor Nov 22 '12 at 21:25
  • \$\begingroup\$ I've emailed the owner of the Alchemy pages asking for permission to use his copyrighted images. Awaiting response. \$\endgroup\$ – luser droog Jan 28 '13 at 8:25
  • \$\begingroup\$ Can we delete this because the sandbox lags so much and this hasn't been touched in 5 years? \$\endgroup\$ – programmer5000 Apr 13 '17 at 17:42
2
\$\begingroup\$

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

\$\endgroup\$
  • 2
    \$\begingroup\$ And the winning criterion is who is the first to get post from the courts? \$\endgroup\$ – celtschk Oct 3 '15 at 20:18
  • \$\begingroup\$ @celtschk, I think that would be unfair. Winning criteria shouldn't really depend on where people live... \$\endgroup\$ – Peter Taylor Oct 10 '15 at 20:56
  • 3
    \$\begingroup\$ I think you should at least explain the general concept of the spec. \$\endgroup\$ – Rohan Jhunjhunwala Aug 2 '16 at 22:53
  • \$\begingroup\$ 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!) \$\endgroup\$ – sundar Jun 25 '18 at 8:25
2
\$\begingroup\$

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

enter image description here 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.

\$\endgroup\$
  • \$\begingroup\$ 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. \$\endgroup\$ – PhiNotPi Jun 8 '13 at 14:33
  • \$\begingroup\$ Yes, this is the case. In general however there is not a unique series of applications of the reduction rules for any given instance. \$\endgroup\$ – Kaya Jun 8 '13 at 16:21
  • \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor Jun 10 '13 at 8:49
  • \$\begingroup\$ 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? \$\endgroup\$ – Peter Taylor Jun 11 '13 at 8:32
  • \$\begingroup\$ 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. \$\endgroup\$ – Kaya Jun 11 '13 at 14:04
2
\$\begingroup\$

Business Card Ray Tracer

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.

http://fabiensanglard.net/rayTracing_back_of_business_card/index.php

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

\$\endgroup\$
  • 1
    \$\begingroup\$ 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>"? \$\endgroup\$ – dmckee Oct 6 '13 at 17:22
  • 1
    \$\begingroup\$ 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). \$\endgroup\$ – dmckee Oct 6 '13 at 17:29
  • 1
    \$\begingroup\$ 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. \$\endgroup\$ – dmckee Oct 6 '13 at 17:33
  • 3
    \$\begingroup\$ 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. \$\endgroup\$ – Peter Taylor Oct 6 '13 at 22:48
  • \$\begingroup\$ Yes. Read the teapot question for guidance. Ultimately I decided that one was too big, but we did get into some pertinent details. \$\endgroup\$ – luser droog Dec 1 '13 at 9:48
  • \$\begingroup\$ 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. \$\endgroup\$ – programmer5000 Jun 9 '17 at 15:32
2
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ This isn't really an interesting problem. The shortest answer is almost certainly going to be fewer than 10 characters. \$\endgroup\$ – Peter Taylor Dec 11 '13 at 12:19
  • \$\begingroup\$ @PeterTaylor While I mostly agree with your comment - already the header line may contain more than 10 characters. \$\endgroup\$ – Howard Dec 12 '13 at 6:15
  • \$\begingroup\$ "The quick brown fox jumps over the lazy dog." contains "e" three times. \$\endgroup\$ – Howard Dec 12 '13 at 6:16
  • \$\begingroup\$ @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. \$\endgroup\$ – Iszi Dec 12 '13 at 7:02
  • \$\begingroup\$ My brain instantly went into bash mode. wc and uniq practically solve half of this, but not in any particularly short manner. \$\endgroup\$ – Rob Dec 17 '13 at 20:31
2
\$\begingroup\$

PETSCII banner

PETSCII on CodGolf.StackExchange

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:

Animated display sample Hello world!

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.

\$\endgroup\$
  • 3
    \$\begingroup\$ as for the CPU bonuses - what is the target environment, what is the smoothing factor, and what processes count against this measure? \$\endgroup\$ – John Dvorak Dec 15 '13 at 6:19
  • \$\begingroup\$ 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. \$\endgroup\$ – programmer5000 Jun 9 '17 at 15:32
2
\$\begingroup\$

.... . .-.. .-.. --- .-- --- .-. .-.. -..

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?

\$\endgroup\$
  • 1
    \$\begingroup\$ Set a hard minimum for timing. Otherwise, a golfed solution might have 1 unit = 1 millisecond. \$\endgroup\$ – PhiNotPi Dec 16 '13 at 22:23
  • 6
    \$\begingroup\$ Tasks which take input are normally more interesting. \$\endgroup\$ – Peter Taylor Dec 17 '13 at 0:09
  • \$\begingroup\$ I guess that dahs need to be a continuous tone, not just two dits without a gap? \$\endgroup\$ – John Dvorak Dec 17 '13 at 6:32
  • \$\begingroup\$ @JanDvorak Correct. \$\endgroup\$ – Iszi Dec 17 '13 at 6:33
  • \$\begingroup\$ 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.) \$\endgroup\$ – MD XF Dec 22 '17 at 2:41
  • \$\begingroup\$ @MDXF What do you suggest for modifications? \$\endgroup\$ – Iszi Jan 2 '18 at 15:18
2
\$\begingroup\$

This is my first try at writing a challenge. Please let me know how I can improve it.

Roman Calculator

Create a basic calculator for Roman numerals.

Requirements

  • Supports +,-,*,/
  • Input and output should expect only one prefix per symbol (i.e. 3 can't be IIV because there is two I's before V)
  • Input and output should be left to right in order of value, starting with the largest (i.e. 19 = XIX not IXX, 10 is larger than 9)
  • Left to right, no operator precedence, as if you were using a hand calculator.
  • Supports whole positive numbers input/output between 1-4999 (no need for V̅)
  • No libraries that do roman numeral conversion for you

For you to decide

  • Case sensitivity
  • Spaces or no spaces on input
  • What happens if you get a decimal output. Truncate, no answer, error, etc..
  • What to do for output that you can't handle. Negatives or numbers to large to be printed.

Extra Credit

  • -20 - Handle up to 99999 or larger (numbers with a vinculum)

Sample input/output

XIX + LXXX                 (19+80)
XCIX

XCIX + I / L * D + IV      (99+1/50*500+7)
MIV

The shortest code wins.

\$\endgroup\$
  • 1
    \$\begingroup\$ You might want to be explicit about which variants of Roman numerals need to be supported. For example, do I have to understand IV as 4, or can I require that it be written as IIII? And what about, say, writing 8 as IIX instead of VIII, 19 as IXX or XVIV instead of XIX, or 99 as IC instead of XCIX? (All these variants have, AFAIK, been used classically.) \$\endgroup\$ – Ilmari Karonen Feb 9 '14 at 22:36
  • \$\begingroup\$ @IlmariKaronen thanks. I modified the question to be slightly more specific about that. \$\endgroup\$ – Danny Feb 10 '14 at 14:09
  • 1
    \$\begingroup\$ I think that using IV, IX, IC, XC, etc. should be alright, but only allow one prefix. Also, 19 should be written XIX, not IXX. One other thing, can we assume that the operators will be separated by a space, or no? \$\endgroup\$ – Hosch250 Feb 12 '14 at 0:32
  • 1
    \$\begingroup\$ 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.) \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:06
  • \$\begingroup\$ 1. I don't need to handle I/III but need to handle I/III+II/III? 2. For the extra can I output maybe [V] for 5000? \$\endgroup\$ – l4m2 Apr 12 '18 at 15:05
  • \$\begingroup\$ @programmer5000 it was posted to main awhile ago. codegolf.stackexchange.com/questions/20670/… \$\endgroup\$ – Danny Apr 26 '18 at 11:58
2
\$\begingroup\$

How many pizzas do I need

Write a program that figures out the minimum number of pizzas I need to order and the amount of left overs I will have.

Requirements

  • Each pizza is 8 slices
  • Each person gets one choice of pizza topping, represented by a letter A-Z
  • Input in the format PVBC 2. Where each letter represents the choice of 1 person (e.g. P=Plain, V=Vegie, etc...), and the number is the amount of slices each person is allowed to eat. Letters can be in any order and do not need to be grouped.
  • If I don't need a full pizza I must be able to do half one topping and half another topping, the output for a half and half pizza will be denoted by X/Y where X and Y are different toppings
  • If I need multiple of a certain type of pizza they must be shown on one line (e.g. 2 x V Pizza). If there are different combinations the both result in the same, least, amount of pizzas, either output works
  • Output must match the format below of one type of pizza per line and a comma separated list of left overs. The output must show the minimum amount of pizzas and leftover possible.

Extra Credit

  • -20 - Take a 3rd argument that allows you to input the number of slices in a pizza, assume it will be an even number such that you can split it in half

Sample Input/Output

PCPVCB 3              (6 slices P, 3 slices V,  6 slices C, 3 slices B)
1 x P Pizza
1 x V/B Pizza
1 x C Pizza
2 slices P, 2 slices C, 1 slice V, 1 slice B left over

VBBCBBB 2             (10 slices B, 2 slices C, 2 slices V)
1 x C/V Pizza
2 x B Pizza
6 slices B, 2 slices C, 2 slices V left over

The 2nd example has many other combinations that could result in only 3 pizzas, this is just an example of what an output might be.

The shortest code wins.

\$\endgroup\$
  • \$\begingroup\$ I can't say for sure, but I may have seen a similar challenge before. If not, it seems good to me. \$\endgroup\$ – Hosch250 Feb 18 '14 at 19:20
  • \$\begingroup\$ The use of the word "preferences" is confusing to me, because it suggests some kind of optimisation problem where people might get their second preference and you have to optimise for overall satisfaction. In addition, I don't find either the input or the output specification sufficiently clear. For the input, is there any guarantee that the letters are grouped (i.e. that PVP 1 will never be given as input)? And are the 4 letters given the only ones which may be used, or could there potentially be 26 different preferences? How much flexibility is there in the output? \$\endgroup\$ – Peter Taylor Feb 18 '14 at 21:12
  • \$\begingroup\$ @Danny, the one problem with this question is that because of my voracious appetite, there would be no left over pizza... ;) \$\endgroup\$ – WallyWest Feb 18 '14 at 21:15
  • \$\begingroup\$ @PeterTaylor I made edits to hopefully address all of the parts you saw that were possibly confusing. Can you look at the question again and let me know what you think. \$\endgroup\$ – Danny Feb 19 '14 at 13:44
  • \$\begingroup\$ @Danny You might want to add that you want the minimum amount of ordered pizzas/left overs - otherwise there exists a trivial solution where each person gets his own pizza (provided slices<=8). \$\endgroup\$ – Howard Feb 26 '14 at 8:19
  • \$\begingroup\$ 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.) \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:07
2
\$\begingroup\$

Golf a random Human Genome fragment with non-random features

A totally random genome fragment is easy enough: just spit out the letters ATCG in random order, and you're done. So let's try something a little less random and more useful to science.

Your program will:

  • Accept an argument from the user for number of base pairs (20bp-10000bp must be supported, more if you wish)
  • Accept an argument from the user for GC content. This indicates how frequently the generated sequence should contain the G and C bases as a percentage of total sequence length.
  • Include at least one complete gene in every request of 500bp or more, where a gene is defined as an otherwise random sequence that begins with a start codon triplet (ATG) and ends with the first stop codon triplet it encounters (TAG, TGA, or TAA). The distance between the start codon and the stop codon does not have to be a multiple of 3.
  • Vary gene content (the portion of the fragment that is "gene", inclusive of the gene's start and stop codons) linearly with respect to GC content (when sequence >= 500bp). At the extremes, when GC content is 0%, gene content is 10%; when GC content is 100%, gene content is 60%.
  • Output a single-strand sequence that complies with the above specs and the user's given parameters. (i.e. a single row of letters will suffice since it is trivial to deduce the complementary strand of the DNA given the sequence of one strand)
  • Calculate the actual GC content %, actual number of genes, and actual gene content % in the resulting fragment, and output a status line below the sequence conforming to the example format below. Percentages may be rounded to one decimal place. Actual values may deviate by +/- 3% from the expected outcome based on user's input.

    GC content: 42.1% | Genes: 3 | Gene content: 32.1%

Your program will not:

  • Use any Internet, library, or built-in gene sequence generation functions or databases. Roll your own.

Sufficient randomness:

  • For the purposes of this challenge, any built-in random/pseudo-random number generator function, GUID generator, well-seeded cryptographic hash function, etc. is considered an acceptable source of randomness.

What-ifs:

  • What if another start codon occurs before the stop codon? E.g. ATGXXXATGXXXXXXXXXXXXTAG. This is acceptable, but the "gene" length in this case is calculated from the most proximal start codon to the stop codon.
  • What if another stop codon occurs after a stop codon? E.g. ATGXXXXXXXXXXXXXTAGXXXXXXTAG This is also acceptable, but likewise the "gene" length is calculated from the start to the most proximal stop.
  • What if both of these things happen? E.g. ATGXXXATGXXXXXXXXXXXXTAGXXXTGA. Here again, the "most proximal" principle applies and the gene content is demarcated by the innermost start and the innermost stop.
  • Do "orphaned" start and stop codons that do not demarcate a gene count as gene content? No.

This challenge is code golf, so shortest valid code wins.

Post example output from a 500-bp request with GC content between 35% and 65%, and have fun!

\$\endgroup\$
  • \$\begingroup\$ "Use hardcoded fragments for anything other than the start and stop codons." - why not? Specifying criteria for what counts as enough randomness should make these useless in any case. Speaking of which, you need to specify criteria for what counts as enough randomness. \$\endgroup\$ – John Dvorak Feb 28 '14 at 5:54
  • \$\begingroup\$ The only partial output example given flagrantly violates the spec. If the GC content is 42.1%, the gene content should be 31.05%, not 22.0%. The definition of "gene" is also imprecise: in the sequence AUGCCAUGCCUAGCUAA, which is the gene? \$\endgroup\$ – Peter Taylor Feb 28 '14 at 12:02
  • \$\begingroup\$ @PeterTaylor AUG starts the gene, then come the CCA, UGC, CUA and GCU triplets, none of which terminate the gene. Now if there were three C's instead of two, then UAA would be the terminating triplet and the whole sequence would form a gene. I agree the definition is imprecise, though. \$\endgroup\$ – John Dvorak Feb 28 '14 at 12:11
  • \$\begingroup\$ @JanDvorak, (part of) the point of that example is that there are two AUG substrings. \$\endgroup\$ – Peter Taylor Feb 28 '14 at 12:30
  • \$\begingroup\$ Good points. I was hoping to avoid having too much text, but that came at the expense of less clarity than the challenge demands. Edit forthcoming. \$\endgroup\$ – Jonathan Van Matre Feb 28 '14 at 13:58
  • \$\begingroup\$ Also, I've muddied the waters with RNA encoding and DNA encoding, (U vs T), which we can chalk up to a late night. \$\endgroup\$ – Jonathan Van Matre Feb 28 '14 at 14:00
  • \$\begingroup\$ Revised accordingly, although I remain open to suggestions on how best to frame the standards for acceptable randomness. I want something that won't be exploited by answers making no effort at randomness, but that doesn't have the pain-in-the-butt factor of generating 10mb+ of data and running a Diehard test battery. \$\endgroup\$ – Jonathan Van Matre Feb 28 '14 at 17:20
  • \$\begingroup\$ " This is acceptable, but the "gene" length in this case is calculated from the most proximal start codon to the stop codon. " - wait, what? In nature, the first one is the start codon, and the rest encode methionine. Under your scheme, methionine (which is an essential amino-acid) would be impossible to include into proteins. Your scheme would also be much harder to splice. Also, what happens to AUG substrings that are not triplet-aligned to previous AUG substrings? \$\endgroup\$ – John Dvorak Mar 1 '14 at 9:25
  • \$\begingroup\$ In nature, the first ATG encodes the start of a protein coding region and defines a reading frame (triplet boundary), the rest encode methionine and the first triplet aligned stop codon encodes the end of the protein coding region (and no amino-acid). \$\endgroup\$ – John Dvorak Mar 1 '14 at 9:29
  • \$\begingroup\$ As for the randomness, I'm not worried about the source of randomness (whatever native library is available is assumed to be good enough) but rather how the source of randomness is used (can we just start the sequence with a start codon and insert an end codon at just the right spot if it doesn't occur naturally sooner, then fill in with more random codons while avoiding ATG subsequences? Your "sufficient randomness" places constraints on the RNG (useless) but no constraints on how it's used (or that it needs to be used at all) \$\endgroup\$ – John Dvorak Mar 1 '14 at 9:34
  • \$\begingroup\$ My true random number sequence generator was sitting there watching silently as I typed away the sequence ACACACACACACAC.... It's all okay. The TRNG was capable of producing something better - it just didn't really get to it. \$\endgroup\$ – John Dvorak Mar 1 '14 at 9:38
  • 1
    \$\begingroup\$ In fact, the 3% tolerance for the CG content leaves no room for randomness when there are only 20 base pairs. I can shuffle the pairs and turn some A<->T or C<->G, but that's it. In fact, if the CG content is set to zero, the task is impossible: we want a gene content of 2 base pairs (which is itself impossible), but the start codon contains a G, and a single G in a 2bp sequence means a 5% CG content, 2% than is the limit. Not including a gene means that we are 7% under the gene content lower limit. Similarly, it's not possible to start or stop a gene with nothing but Cs and Gs. \$\endgroup\$ – John Dvorak Mar 1 '14 at 9:45
  • \$\begingroup\$ Yeah, the 20bp starting point is a bad idea. The problem with start codons is that I considered introducing the idea of promoters and decided that would make the whole thing too complex. So in the absence of promoters there has to be some way to determine which Met is the start codon vs an amino acid and the easiest simplification is to have no Mets in the gene. Likewise, for "not triplet aligned", I'm trying to avoid having to go into explanations of frameshift mutations (even though a Frameshift% would be a cool parameter). \$\endgroup\$ – Jonathan Van Matre Mar 1 '14 at 14:29
  • 1
    \$\begingroup\$ I am starting to think that all of these complexities should be included (this proposal stems from me noticing that most of the extant random DNA generators are pretty weak) and this should just be a popularity contest instead of a golf. Link a couple of good articles on the structure of the genetic code and let people add as many features as they wish. Making it a golf seems to be a catch-22 between too many compromises or a too-impenetrable wall of rules and conditions that will dissuade participation. \$\endgroup\$ – Jonathan Van Matre Mar 1 '14 at 14:33
  • \$\begingroup\$ Perhaps a code-challenge where people earn x points for each complexity implemented? \$\endgroup\$ – Hosch250 Mar 2 '14 at 5:52
2
\$\begingroup\$

Resurrect Adobe SubScript.

In an obscure conference procedings volume of forgotton lore, there's a quaint little paper which describes an early effort to implement a published subset of Adobe Postscript. There a line in the bibliography! :) But it cannot be found Nobody's ever heard of it. :(

Adobe Systems, "SubScript Specification", 1984.

But there's obvious utility in such a thing. So this is a hypothetical Micro-Manual Postscript, and its name shall be ASS[*]. :)

ASS is a dynamically-typed stack-based programming language with powerful graphics primitives. It has support for floating-point arithmetic, arrays and dictionaries.

The scanner reads white-space delimited tokens and attempts to interpret the token as a decimal floating-point number with optional sign (+/-). The program may (but is not required to) support exponential notation. Failing to recognize a valid number, the token becomes a name object, an atomic symbol type which is identified by the name (an "interned" string).

Types

As suggested by the scanner behavior and the operator list , there are the following object types:

  • floating-point numbers (coerced to integer where appropriate)
  • names (usually an index into a string table, for easy comparisons)
  • arrays (an indexable sequence of objects)
  • dictionaries (a key-value map of objects)
  • operators (a pointer to a built-in function)

Operators

Operators are the basic actions predefined in the dynamic name space.

Stack Manipulation

  • any   pop   -
    pop an object from the operand stack

  • any1 any2   exch   any2 any1
    exchange top two elements

  • anyN anyN-1 ... any0 N   index   anyN anyN-1 ... any0 anyN
    retrieve object from stack by position

where N is treated as an integer.

Arrays.

  • N   array   array
    create a new array of length N

  • any0 any1 ... anyN-1 array   astore   array
    fill array with objects from stack

  • array   aload   any0 any1 ... anyN-1 array
    spill contents of array onto stack

  • [   any0 any1 ... anyN-1   ]   array
    construct an array

  • array index any   put   -
    put a value into array

  • array index   get   any
    retrieve value from array

where index is treated as an integer.

The typical way to implement the array syntax is using an auxiliary type, the marktype object, and an operator counttomark. This is an implementation detail and is not strictly required but may be found to be convenient.

  • -   [   mark
    produce marktype object as a sentinel on the stack

  • mark anyN anyN-1 ... any1   counttomark   mark anyN anyN-1 ... any1 N
    count objects up to mark

Then the ] operator may be implemented in terms of the other array operators.

  • mark anyN anyN-1 ... any1   ]   array
    { counttomark array astore exch pop }

Dictionaries.

  • N   dict   dict
    create a new dictionary, an associative container with room for N name-value pairs

  • dict   begin   -
    push dictionary on dictionary stack, making names part of the dynamic name space

  • -   currentdict   dict
    push copy of topmost dictionary on dictionary stack to the operand stack

  • -   end   -
    pop and discard the topmost dictionary on the dictionary stack

  • name any   def   -
    associate name with any value in topmost dictionary

  • name   load   any
    lookup name in each dictionary in the dictionary stack from the top-down, returning the first match, or error if not found

Matrices and transformations.

A matrix is a 6-number array [a b c d e f] which represent a left-multiplying affine transformation matrix with the constant right-most column omitted.

 a b 0
 c d 0  =>  [a b c d e f]
 e f 1
  • -   matrix   matrix
    returns a new identity matrix [1 0 0 1 0 0]

  • matrix   setmatrix   -
    make matrix the current transform in the graphics state

  • -   currentmatrix   matrix
    return current transform from the graphics state

  • x y   transform   x′ y′
    transform (x,y) pair by current transformation matrix

Transforming a point involves multiplying the homogeneous vector through the transformation matrix:

          [a b 0]
[x y 1] * [c d 0] => [x' y' 1]
          [e f 1]

or, equivalently

x' = a*x + c*y + e
y' = b*x + d*y + f

Path description.

  • -   newpath   -
  • x y   moveto   -
  • x y   lineto   -
  • -   closepath   -

Clipping.

  • -   clip   -
  • -   clippath   -

Painting.

  • -   erasepage   -
  • -   fill   -
  • -   showpage   -

The fill operator is where the magic happens. This operator is responsible for performing all of the graphics algorithms in sequence:

  • Shape Mapping
    Tranform the coordinates of the path from user space to device space using the current transformation matrix.

  • Shape Clipping
    Clip the portions of the path that lie outside the clipping path.

  • Filling
    *Perform a scan-line rasterization of the (may assumed closed-) polygon described by the path into the output frame buffer.

And showpage copies the contents of the framebuffer to the actual output mechanism (window or file as described above).

... need to fill this out a little more. Math, graphics state, errors. Describing stroked lines is too much, I think. I'm not sure if it needs the forall operators for iterating through arrays and dicts. I'd like to avoid any need for overloading different types under the same operator name, and calling back to user code from an operator.

Output may be to a window, or to a file in a simple format, like pgm or even a text-file of hashes and spaces for rough bitmaps. No half-toning. Only bi-level filling of convex polygons will be required. But a program may handle more colors if desired.

This is CW in case anybody wants to help me type-in the basic operators.

Questions

Does it need anything more? Should something be removed as unnecessary? Does anyone have the spec??

Perusing my ps implementations of the graphics portions linked in the comments, I've noticed the following needed operators:

length
sub
roll
add
eq
array copy
mul
div
ne

I think it needs loops, too. It's possible to do with just recursion, of course, but loops are nice. And length, I think, needs to be polymorphic, operating on array or dict to retrieve the size for making copies and calculating indices. Add sin and cos, too.


And this would be a .

[*] The moniker "ASS" is not intended as a disparagement of Adobe Systems nor any of their stupendous intellectual property. Rather it is merely intended to express frustration at the encountered difficulty in locating this document.

\$\endgroup\$
  • \$\begingroup\$ So this is intended to be a subset of PostScript: are you going to point people at a PS spec for the nitty-gritty details about things like the precise implementation of path filling? Also, if the idea is to be minimalistic, why have both mark and [? \$\endgroup\$ – Peter Taylor Jan 11 '14 at 13:19
  • \$\begingroup\$ I'm hoping I can concisely specify everything so it's self-contained and not need to refer to a PS spec. ... Good point about mark. I suppose I can require [ and ] and suggest mark ... counttomark as a possible way to implement it. \$\endgroup\$ – luser droog Jan 11 '14 at 13:22
  • \$\begingroup\$ oh. I see what you mean now. removed mark as a separate entity. It isn't needed. \$\endgroup\$ – luser droog Jan 11 '14 at 13:32
  • \$\begingroup\$ My idea is to follow the most basic part of the original Warnock paper which is the basis of the Adobe Image Model. I've got some excerpts here. \$\endgroup\$ – luser droog Jan 11 '14 at 13:46
  • \$\begingroup\$ I don't see any way to create a non-identity matrix. \$\endgroup\$ – Peter Taylor Jan 24 '14 at 9:20
  • \$\begingroup\$ You can construct any matrix using the array notation. There should also be user space transforms: rotate, scale and translate. They're usually part of the graphics state, so I didn't put them under matrices. \$\endgroup\$ – luser droog Jan 24 '14 at 9:25
  • \$\begingroup\$ This spec from the 80s would be gold for implementing postscript. Offering a glimpse at the intermediate stage between the Warnock/Wyatt paper (which describes the image model in the syntax of the Xerox Mesa language) and the PLRM 1ed. Warnock/Wyatt has been described as "smuggling" the ideas out of Xerox. ... Ugh. I forgot to add some control structures. \$\endgroup\$ – luser droog Mar 1 '14 at 10:22
  • \$\begingroup\$ I've got implementations of paths, matrices, clipping, and filling in postscript. Perhaps I should wrap these up and just require the data structures and scanning to load and use them. \$\endgroup\$ – luser droog Mar 1 '14 at 11:33
  • \$\begingroup\$ 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.) \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:08
  • \$\begingroup\$ Thanks! ... Done. \$\endgroup\$ – luser droog Jun 11 '17 at 10:00
2
\$\begingroup\$

Unified format patcher

Write the shortest program that will take a patch file in the unified format from stdin and apply that patch. No external tools that do the process for you can be used.

Clarifications

  • Extra documentation about the unified format can be found here
  • All file paths will be relative
  • Only one file will be modified per patch
  • Timestamps can be ignored
  • The patch file will be valid and will apply cleanly to the file specified (it will not lie about line numbers, etc..)
  • Assume all files being patched already exist, you don't need to create/delete files

Extra

  • -35 - Take an argument that allows you to unpatch a patch

Example

/test/a.cpp

#include <iostream>
using namespace std;

int main() {
    cout << "Hello world!";
    return 0;
}

patch.txt

--- a/test/a.cpp
+++ b/test/a.cpp
@@ -1,7 +1,8 @@
 #include <iostream>
+#include <vector>
 using namespace std;

 int main() {
-    cout << "Hello world!";
+    cout << "Goodbye world!";
     return 0;
 }

Run patch

patch.exe patch.txt

/test/a.cpp

#include <iostream>
#include <vector>
using namespace std;

int main() {
    cout << "Goodbye world!";
    return 0;
}
\$\endgroup\$
  • \$\begingroup\$ Can the program assume that the @@ lines contain the correct line numbers? \$\endgroup\$ – ugoren Mar 6 '14 at 17:52
  • \$\begingroup\$ A good explanation of the patch file format is needed. If not too long, include it in the question. Else, provide a link. \$\endgroup\$ – ugoren Mar 6 '14 at 17:53
  • \$\begingroup\$ You forgot the obvious "no external tools" disclaimer. You don't want the patch $1 answer. \$\endgroup\$ – ugoren Mar 6 '14 at 17:55
  • \$\begingroup\$ @ugoren thanks for the comments, I added some further clarifications. \$\endgroup\$ – Danny Mar 6 '14 at 18:38
  • \$\begingroup\$ Does "The patch file will be valid (it will not lie about line numbers)" also mean that it will apply cleanly? \$\endgroup\$ – Peter Taylor Mar 6 '14 at 19:24
  • \$\begingroup\$ @PeterTaylor yes, updated question. \$\endgroup\$ – Danny Mar 6 '14 at 19:51
  • \$\begingroup\$ "The shorted program" should say "the shortest program", but other than that I think it's ready to go. Of course, no-one's actually going to do more than filter out the lines starting -, remove the first char from each line, and parse the line-numbers to work out how to splice the resulting text in. \$\endgroup\$ – Peter Taylor Mar 7 '14 at 0:01
  • \$\begingroup\$ This sandbox post has had little activity in a while. Please improve / edit it or delete it to help us clean up the sandbox. Due to community guidelines, if you don't respond to this comment in 7 days I have permission to vote to delete this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:10
2
\$\begingroup\$

Your task, should you choose to accept it, is to convert an image into ASCII art. Essentially, your program has to do precisely what picascii.com does.

Rules:

  • You must take the image from stdin or read it from a file specified in the command line.
  • You must output to stdout or to a filename specified in the command line.
  • Your program must take input in a format that ImageMagick supports. You can choose any format you want, however. If you want to read ppm images and we have to pass a jpeg through ImageMagick first to use your program, that's fine.
  • Given the above, your program itself must use only standard libraries, even for loading the image.
  • You must only output printable ASCII characters (that's 32-126 plus CR and LF).
  • You can choose in which font or setting your image should be viewed in, e.g. it might look good in a terminal but awful in a stackexchange code block, or vice versa, or maybe it only looks good with Courier New size 12, etc.
  • The largest edge of your output must be at least 25 characters and at most 200 characters long.
  • Aspect ratio must be preserved as much as possible within one fixed-width character size. e.g. if you have a 400x320 pixel image, and the fixed-width font you're outputting for is 8x13 including spacing, your output must be at least 25x12 characters, or it can be 50x25, 125x62, etc., with a maximum size of 200x98.
  • Provide at least two sample inputs & outputs with your submission. Outputs can be stackexchange code blocks or links to paste bins or screenshots of the output viewed in the environment you intended it for, etc.
  • Your score is the byte count of your source code. Lowest score wins.

However, I want the output to bear some reasonable resemblance to the input. I don't want this to be subjective. I'd rather have a hard limit that people can hack around.

Opening suggestion: maybe something like: given a font size of 8x13, if the image is converted to grayscale and quantized to 8x13 blocks, and your solution is converted to an image, scaled to fit, and also quantized to homogeneous 8x13 blocks where the value of each block is the percentage of filled-in pixels for each block, the average distance between the image blocks and your output blocks must be less than X.

\$\endgroup\$
  • \$\begingroup\$ You should delete it from the main site for now because you can't really change the rules once somebody posts an answer. You can repost it when you think it is ready. \$\endgroup\$ – Hosch250 Mar 11 '14 at 18:53
  • \$\begingroup\$ @hosch250: Good idea, just deleted it. gotta make it a good one! \$\endgroup\$ – Claudiu Mar 11 '14 at 19:02
  • \$\begingroup\$ @hosch250: The link isn't broken, it's just a deleted question, and can only be viewed by me and the mods. I wanted to not lose the link but it's there in the edit history I guess. \$\endgroup\$ – Claudiu Mar 11 '14 at 20:26
  • \$\begingroup\$ It is still in your account page too. \$\endgroup\$ – Hosch250 Mar 11 '14 at 21:55
  • \$\begingroup\$ I think this would be quite dull as a code-golf challenge. The optimal solution is to simply read every other line of a PGM file and convert each number into ASCII 32 (space) or 33 ('!') based on some threshold value. Without a code length restriction, we could add more interesting features like Floyd-Steinberg dithering and matching letter shapes to image features (e.g., using / and \ in places where diagonal likes are detected). \$\endgroup\$ – squeamish ossifrage Mar 14 '14 at 0:15
  • \$\begingroup\$ @squeamishossifrage: Hmm interesting. I was going for making an objective criterion that would make that not the optimal solution, so you'd have to use more than a few characters, but that'd be awkward. Making it a popularity contest would definitely lead to more creative solutions.. I will consider it \$\endgroup\$ – Claudiu Mar 14 '14 at 0:53
  • \$\begingroup\$ 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.) Due to community guidelines, if you don't respond to this comment in 7 days I have permission to adopt this. \$\endgroup\$ – programmer5000 Jun 9 '17 at 16:19

You must log in to answer this question.

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