507
\$\begingroup\$

What is the Sandbox?

This "Sandbox" is a place where Code Golf 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\$
0

3126 Answers 3126

1
52 53
54
55 56
105
1
\$\begingroup\$

Is this a narrow Thumb instruction?

ARM Thumb was originally a 16-bit only subset of the 32-bit ARM instruction set.

However, later versions added 32-bit "wide" instructions which were more flexible, and called the original, more restrictive 16-bit instructions "narrow" instructions.

The assembler now chooses between narrow and wide instructions automatically, depending on how the instruction was written. However, this meant that the syntax had to be changed to have specific rules.

Your job is to be this assembler.

However, the programs you parse are not that interesting; they will only ever consist of add and adds.

More specifically:

Your task is to write a function or program that will take an add/adds instruction, and return a truthy value if it is a valid narrow instruction, or a falsey value if it is not.

Syntax rules

  • ARM has 16 registers, r0-r12, r13 (aka sp), r14 (aka lr), and r15 (aka pc). For ease of parsing, we are going to refer to all registers by their number, instead of using the special register names.
  • Do note the names when reading the official docs, as there are a lot of special cases for sp and pc.
  • In Thumb mode, these are split into "Lo registers", which are r0-r7, and "Hi registers" which are r8-r15. Many instructions can only use Lo registers.
  • Many instructions use the same source register as the destination register, even if they are written with three operands.
  • add and adds are distinct instructions. adds affects the condition flags, while add does not. That is the difference, if you were wondering.

The following 6 forms are valid for narrow instructions (adapted from here):

  1. adds x, y, #imm: x and y must both be Lo registers, and imm is a 3-bit constant from 0-7.
  2. adds x, y, z: x, y, and z must all be Lo registers.
  3. add x, x, y: x and/or y must be Hi registers. Note that x is repeated twice.
  • We are ignoring the fact that ARMv6 relaxed this rule to keep it interesting.
  1. adds x, x, #imm: x must be a Lo register. imm is an 8-bit constant from 0-255. Again, note that x is repeated twice.
  2. add r13, r13, #imm: imm is a constant multiple of 4 in the range 0-508.
  3. add x, y, #imm: x must be a Lo register, and y must either be r13 or r15. imm is a constant multiple of 4 in the range 0-1020.

Everything else is either a wide instruction or not valid.

Other notes

Standard loopholes, everything must be self-contained, and you are only allowed to treat it as text. You can't feed it to an assembler (unless you include the assembler source code in the result, but.. why).

The input can either be a string argument or text from stdin.

You can assume the format will match the following format (all lowercase, separators being a single space):

{add or adds} reg, reg, {#imm or reg}

Where imm is a non-negative number in base 10 (yes, including zero).

As a regex pattern:

^adds? r([0-9]|1[0-5]), r([0-9]|1[0-5]), (#[0-9]+|r([0-9]|1[0-5]))$

Reference implementation

In case the rules are difficult to follow, here is a reference implementation I made in C. Yes, I deliberately overabstracted it to make you do all the work.

I resisted the urge to post the reference implementation in ARM Thumb assembly, as that would be genuinely evil. 😏

You will not need to do the same error checking I did here. You can always assume the string itself is valid. The error checks in the main function are mostly to show what CAN'T happen.

#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
#include <errno.h>
#include <inttypes.h>

struct thumb_add_insn {
    char opcode[5];
    uint32_t op1;
    uint32_t op2;
    char op3_prefix;
    uint32_t op3;
};

// Returns whether the opcode ID is adds.
static inline bool is_adds(const char *opcode)
{
    return strcmp(opcode, "adds") == 0;
}

// Returns whether this register ID belongs to a Lo register,
// specifically r0-r7.
static inline bool is_lo_reg(uint32_t reg_id)
{
    return reg_id <= 7;
}

// Returns whether this register ID belongs to a Hi register,
// specifically r8-r15.
static inline bool is_hi_reg(uint32_t reg_id)
{
    return reg_id >= 8;
}

// Returns whether the operand prefix is for an immediate
// value, specifically, '#'.
static inline bool is_imm(char c)
{
    return c == '#';
}

// adds x, y, #imm3
static bool is_form_1(const struct thumb_add_insn *insn)
{
    return is_adds(insn->opcode)
        && is_lo_reg(insn->op1)
        && is_lo_reg(insn->op2)
        && is_imm(insn->op3_prefix)
        && insn->op3 <= 7;
}

// adds x, y, z
static bool is_form_2(const struct thumb_add_insn *insn)
{
    return is_adds(insn->opcode)
        && is_lo_reg(insn->op1)
        && is_lo_reg(insn->op2)
        && !is_imm(insn->op3_prefix)
        && is_lo_reg(insn->op3);
}

// adds x, x, #imm8
static bool is_form_3(const struct thumb_add_insn *insn)
{
    return is_adds(insn->opcode)
        && is_lo_reg(insn->op1)
        && insn->op1 == insn->op2
        && is_imm(insn->op3_prefix)
        && insn->op3 < 256;
}

// add x, x, y
static bool is_form_4(const struct thumb_add_insn *insn)
{
    return !is_adds(insn->opcode)
        && !is_imm(insn->op3_prefix)
        && (is_hi_reg(insn->op1) || is_hi_reg(insn->op3))
        && insn->op1 == insn->op2;
}

// add r13, r13, #imm
static bool is_form_5(const struct thumb_add_insn *insn)
{
    return !is_adds(insn->opcode)
        && insn->op1 == 13
        && insn->op1 == insn->op2
        && is_imm(insn->op3_prefix)
        && insn->op3 <= 508
        && insn->op3 % 4 == 0;
}

// add x, y, #imm, y == r13 or r15
static bool is_form_6(const struct thumb_add_insn *insn)
{
    return !is_adds(insn->opcode)
        && is_lo_reg(insn->op1)
        && (insn->op2 == 13 || insn->op2 == 15)
        && is_imm(insn->op3_prefix)
        && insn->op3 <= 1020
        && insn->op3 % 4 == 0;
}

// Parses a Thumb add/adds instruction.
// Returns 1 if it is a narrow instruction, 0 if it is not,
// and -1 on an error.
int is_narrow_add(const char *str)
{
    // Note that you do not have to do error checking for the
    // competition.

    if (str == NULL) {
        errno = EINVAL;
        return -1;
    }

    // Allocate a 24 byte struct on the heap for good measure
    struct thumb_add_insn *insn = calloc(1, sizeof(*insn));
    if (insn == NULL) {
        return -1;
    }

    // Parse the instruction with sscanf.
    // {adds} r{0}, r{3}, {#}{3}
    if (sscanf(str, "%4s r%"SCNu32", r%"SCNu32", %c%"SCNu32,
               insn->opcode,
               &insn->op1,
               &insn->op2,
               &insn->op3_prefix,
               &insn->op3) != 5
       || (strcmp(insn->opcode, "add") != 0
          && strcmp(insn->opcode, "adds") != 0)
       || insn->op1 > 15
       || insn->op2 > 15
       || (insn->op3_prefix != 'r' && insn->op3_prefix != '#')
       || (insn->op3_prefix == 'r' && insn->op3 > 15)
    ) {
        errno = EINVAL;
        free(insn);
        return -1;
    }

    int ret;
    // Test against each of the forms
    if (is_form_1(insn)) {
        ret = 1;
    } else if (is_form_2(insn)) {
        ret = 1;
    } else if (is_form_3(insn)) {
        ret = 1;
    } else if (is_form_4(insn)) {
        ret = 1;
    } else if (is_form_5(insn)) {
        ret = 1;
    } else if (is_form_6(insn)) {
        ret = 1;
    } else { // not a match
        ret = 0;
    }

    free(insn);
    return ret;
}

Test cases

adds r6, r3, #0    // true, form 1
adds r0, r1, #7    // true, form 1
add r0, r1, #3     // false, must be "adds"
adds r0, r9, #1    // false, r9 is a Hi register
adds r0, r1, #9    // false, must be 0-7

adds r0, r0, r0    // true, form 2
adds r7, r1, r2    // true, form 2
adds r4, r4, r1    // true, form 2
add r7, r1, r2     // false, must be "adds"
adds r13, r14, r6  // false, r13 and r14 are Hi registers (this isn't even valid as a wide instruction)

adds r0, r0, #0    // true, form 3
adds r5, r5, #249  // true, form 3
add r6, r6, #31    // false, must be "adds"
adds r3, r3, #256  // false, must be 0-255
adds r8, r8, #72   // false, r8 is a Hi register

add r4, r4, r11    // true, form 4
add r8, r8, r5     // true, form 4
add r9, r9, r9     // true, form 4
add r14, r14, r12  // true, form 4
add r8, r9, r10    // false, Rd must be the same
add r1, r1, r0     // false, one must be a Hi register (we are ignoring the ARMv6 change)

add r13, r13, #0   // true, form 5
add r13, r13, #48  // true, form 5
adds r13, r13, #64 // false, must be "add"
add r13, r13, #17  // false, not a multiple of 4
add r13, r13, #512 // false, must be 0-508

add r0, r15, #0    // true, form 6
add r4, r13, #1000 // true, form 6
add r11, r13, #32  // false, r11 is a Hi register
add r2, r13, #4000 // false, must be 0-1020
adds r7, r15, #384 // false, must be "add"
add r3, r15, #127  // false, not a multiple of 4

Things you can safely ignore:

// String will never be empty
adds r1, r2 // don't worry about implicit middle operand
adds R4, #12 // same
adds r3, r3, #-3 // adding a negative is not even a thing
add r0, r0, r99 // the only registers are r0 - r15
add r13, r13, #0x32 // it is base 10
subs r1, r1, r2 // only add and adds need to be handled
add r2, r2, lr // you don't need to handle the special names
add r0, sp, #0 // same
add #3, r1, r1 // only the last one will be an immediate
adds r3, r3, 32 // all immediates are prefixed with #
ADDS R0, R0, R1 // everything is lowercase
adds        r2,     r3 , r4 // only one space
adds r2,r3,r4 // there will always be spaces
addeq r0, r0, r1 // no IT blocks
adds.n r0, r0, r1 // no manual width specifiers
add r1, r2, r3, lsl #8 // no barrel shifting

This is , so the shortest answer in bytes per language wins.

Proposed tags: and maybe but I think that is for things you must write in assembly, not parsing assembly itself.

\$\endgroup\$
1
\$\begingroup\$

Hanabi playing bot

Overview

Hanabi is a cooperative card game with limited communication. It won the German "Spiel des Jahres" award in 2013.

The game can be played by 2-5 players, each of which has a hand of 5 cards (4 cards for 4-5 players), which they can't see themselves, but the other players can. In each turn, you can either play or discard a card, or give one other player a hint about their cards.

Common goal is to play out the cards in each color in ascending order.

As this is a cooperative game, each answer needs to cooperate with other instances of itself.

I/O format

Option 1: stateless, for all languages

Your program is called once for each turn (and is supposed to terminate afterwards). It will receive the current game state via standard input, and reply with an action via standard output. Invalid output means this game is counted as forfeited (lost, 0 points).

Input

Input is a line-based ASCII-format, with a prefix indicating what kind of data it is. The last line of the input is the current turn number (see below). Input will be in this order:

  1. Meta-information: n: n = number of players (2 .. 5) y: you = own player id (1 .. n)

  2. visible cards of the other players:

    • c 1: cards for player 1
    • ...
    • c n: cards for player n

    The cards for you are omitted in the list (you don't see your own cards).

    Each card has a color (one of r, y, g, b, w) and a number (1 to 5), written like r1 or y5, comma-separated.

    Example: c 2: w4,y1,g2,r3 means that player 2 has a white 4, a yellow 1, a green 2 and a red 3, in this order, on her hand.

  3. Hints given about each player's cards, in a similar list:

    • h 1: hints for player 1
    • ...
    • h n: hints for player n

    For each card (in the same order as before), all hints are noted, in a comma-separated list. We also note negative information, i.e. when a card was present when a hint was given, but was not selected, by prefixing with !. For example 5 is a card which is known as 5 but of unknown color, w1 is a card which is known as a white 1, 3!y is a 3 which is known as not yellow, g!15 is a green card which is known as neither being a 1 nor 5.

    For example, h 2: ,y!2,2!yr,r means that for player 2, the first card is completely unknown (was taken after the last hint), the second card is known as yellow and as not a 2, the third card is known as a 2 which is neither red nor yellow, and the fourth card is known as red.

  4. p color: number – already (successfully) played out cards (one per line). Here we just note the highest card of each color.

    • p r: 2 means for red, the 1 and two were played out (i.e. red 3 is the next one to play).
    • p w: 0 means no white card was played out yet (i.e. the white 1 is the next one to play).
  5. d: – Discarded cards A list of all cards which were either intentionally discarded or unsuccessfully played out, comma-separated.

    For example, d: w3,b5,y2,y2 means that white 3, blue 5 and two yellow 2s were already discarded.

  6. game status information (each on one line, in this order): lh: number of hints left, ld: number of discards left (those two always sum to 8), lb: number of "bad plays" left lc: number of cards left in the deck t: current turn number

(The input will be closed here.)

Output

The action to take. One of

  • h player-id color or number – give a hint to another player. E.g. h 4 y will give player 4 a hint which of his cards are yellow. h 3 1 will give player 3 a hint which of her cards are a 1. This action is only possible if the number of hints left is positive. (The number of hints left will be reduced by 1, the number of discards will be increased by 1.)
  • p card# – play one of your own cards (identified by its number (1..5)). (If this card fits into the cards already played, it's added there. (If this is the last 5, the game ends immediately with full score (25)). Otherwise it is discarded and the number of bad plays is reduced by 1. If it reaches 0, the game ends (unsuccessfully).)
  • d card# – discard one of your own cards (idenfified by its number (1..5)). This is only possible if the number of discards is positive. (The number of hints left will be increased by 1, the number of discards will reduced by 1).

After playing or discarding a card, this card is removed from the hand, and a new card is drawn from the deck and is added to the list of cards of this player (on the left). (The hints are automatically updated.)

Option 2 (stateful)

Your program receives a live transcript of everything what happens (including the actions of the other players, and the results thereof). The controller will read one line of output from the program when it's its turn.

Input

Most input lines have the same format as before.

Initial input (as for the stateless version):

  1. Meta information (n: , y: )
  2. other player's cards (as before)
  3. hints for cards (as before)
  4. played cards (initially just p r: 0, p w: 0, etc.)
  5. discarded cards (initially just d: )
  6. game status, ending with t: 1.

After each player's turn:

  1. a line is given with that player's action: a player id: the action as defined in the output, e.g. a 1: h 4 y means that player 1 gave a hint to player 4 about yellow cards
  2. Those parts of the card situation which changed, e.g. c and d lines if a player discarded a card (or unsuccessfully played a card) and drew a new one), c and p lines if a player played out a card successfully, a h line if a player gave a hint.
  3. Updated status information, e.g. lh + ld when hint was given or a card discarded, lc when a new card was drawn, lb when a card was played unsuccessfully.
  4. t: indicating the next turn number.

*(TODO: Do we need an indication that's now your turn? That can be calculated by y == t mod n, but an explicit prompt might be easier to handle.

When the game ends, the input will be closed. (Your bot should terminate then.)

Output

As in the stateless version, one line indicating the player's action.

Option 3/4 (JVM only, stateless or statefull)

To be defined. As I will be writing the controller in a JVM language, it should be possible/easy to provide a Java API to be implemented by the bots.

Other game rules:

I tried to give most of the details above, but here are some which might be missing/unclear:

  • There are three × 1, two × 2 to 4 and one 5 in each of the five colors (50 cards in total, 10 per color).

  • When playing with 2 or 3 players, each player has 5 cards, when playing with 4 or 5 players, each player has 4 cards in their hand.

  • If you have three bad plays (i.e. the lb counter reaches 0), you lose immediately. This is counted as score 0.

  • If you succeed to play all 25 cards (i.e. all 5s are played successfully), you win immediately, with a score of 25.

  • When the drawing deck is exhausted, one more round is played (i.e. each player has one more turn), then the game ends and the final score is the number of cards successfully played out.

Competition Rules

  • While for human play, the amount of extra communication is "subject to negotiation", here I want to explore what is possible with just what the rules provide. Any communication between your bot instances (except as provided by the defined interface, i.e. via game actions) is strictly forbidden. Strategy needs to be encoded in the source code, not discussed during the game.

  • There is also no communication between your individual games (i.e. no persistence).

  • I will nominate an overall winner, and one for the stateless category. (The stateful ones have a bit more information, so they could emulate the stateless ones.)

  • I will run contestants 1000 times with random decks of cards, once for each number of players from 2 to 5. If your bot only works with a specific number of players, state this in your answer. The competition score is the average score for all the runs. [I'll need to experiment to see how this varies, maybe I'll increase or decrease the count.]

  • A bot needs to provide output in a reasonable time (to be defined). The stateless version needs to terminate after providing output, the stateful one keeps running, but should terminate after end of input (i.e. after the game ended).

  • I will provide the controller on Github, feel free to test your bot with it (and compare it with other competition entries).

  • The programming language needs to have an interpreter or compiler which is available free of cost for Ubuntu 20.4 (otherwise I can't run your bot to score it).

  • I reserve the right to not run a bot when I suspect malicious code in it.

  • This is not , please keep your code readable.

\$\endgroup\$
2
  • \$\begingroup\$ This still needs to be refined, and I actually need to write (and test) the controller. I won't post it before that is done. \$\endgroup\$ – Paŭlo Ebermann Jan 17 at 23:22
  • \$\begingroup\$ What tags should this get? code-competition? \$\endgroup\$ – Paŭlo Ebermann Jan 17 at 23:23
1
\$\begingroup\$

Write a Length interpreter

Length is a simple stack-based esolang where instructions are encoded as line lengths The instruction set is as follows:

Line Length Name Description
9 inp Pushes the ascii value of the first byte of stdin to the stack.
10 add Adds the top two values on the stack and pushes the result onto the stack.
11 sub Subtracts the top two values on the stack and pushes the result onto the stack.
12 dup Duplicates the top value of the stack.
13 cond If the top value of the stack is 0, skip the next instruction. Then pop it.
14 gotou Sets the program counter to the value of the line under the instruction.
15 outn Pops the top of the stack, and outputs it as a number.
16 outa Pops the top of the stack, and outputs its ascii value.
20 mul Multiplies the top two values on the stack and pushes the result onto the stack.
21 div Divides the top two values on the stack and pushes the result onto the stack.
24 gotos Sets the program counter to the value at the top of the stack

In case the table doesn't work, here is the esolangs page: https://esolangs.org/wiki/Length
Test inputs are too long to put here, they can be found here
helloworld.len - Outputs Hello, World!
truth.len - A truth machine
bottles.len - Outputs the lyrics to 99 bottles of beer
This is a code golf, so shortest program wins!

\$\endgroup\$
2
  • \$\begingroup\$ table is broken, it looks fine in preview \$\endgroup\$ – Nailuj29 Jan 18 at 20:49
  • \$\begingroup\$ Fixed. But this should be reported on SE Meta. \$\endgroup\$ – Adám Jan 18 at 20:56
1
\$\begingroup\$

Finish what John McCarthy started (WIP)

This does not have anything to do with Joseph McCarthy or communism. Some background from Wikipedia (you can skip ahead if you like):

John McCarthy published the first paper on Lisp in 1960 while a research fellow at the Massachusetts Institute of Technology. In it he described a language of symbolic expressions (S-expressions) that could represent complex structures as lists. Then he defined a set of primitive operations on the S-expressions, and a language of meta-expressions (M-expressions) that could be used to define more complex operations. Finally, he showed how the meta-language itself could be represented with S-expressions, resulting in a system that was potentially self-hosting.[3] The draft version of this paper is known as "AI Memo 8".[4]

Example M-expressions enter image description here

McCarthy had planned to develop an automatic Lisp compiler (LISP 2) using M-expressions as the language syntax and S-expressions to describe the compiler's internal processes. Stephen B. Russell read the paper and suggested to him that S-expressions were a more convenient syntax. Although McCarthy disapproved of the idea, Russell and colleague Daniel J. Edwards hand-coded an interpreter program that could execute S-expressions.2 This program was adopted by McCarthy's research group, establishing S-expressions as the dominant form of Lisp.

Task

Interpret a subset of M-expressions, where 9 primitive functions have already been defined.

Syntax

Atoms: An atom is a series of any characters excluding [, ], ;. While an atom name can include whitespace, leading and trailing whitespace is ignored. Some examples include foo, lambda (also a function name), and nil (also a list). Atoms act as both variables and data (they're like strings).

Booleans: The atom t is truthy, whereas the atom nil is falsy.

quote: A series of expressions between square brackets, delimited by semicolons. [a; [b; c]; de] is equivalent to the S-expression (QUOTE (A (B C) DE)). It is somewhat like this JS list: ["a", ["b", "c"], "de"].

cond: A series of if-then pairs between square brackets, delimited by semicolons, with an arrow -> (you can use any other character(s)) separating the if-then pairs. e.g. cond[atom[x] -> x; t -> car[x]] yields x if it's an atom, or the first element of x if it's a list. It is guaranteed that at least one of the cases will be true.

Function application: Functions can be called using functionname[arg1; arg2; ...; argN].

  • car - Return the first element of its argument.
  • cdr - Return its argument without the first element.
  • cons - Prepend its first argument to its second argument.
  • eq - Check if its two arguments are equal.
  • atom - Check if its argument is an atom.
  • cond - Takes multiple arguments. Each argument is a list where the first element returns a boolean when evaluated and the second can return anything. It keeps evaluating the first element of each argument until it reaches one that is true. When it does, it evaluates the second element of that argument and returns it. At least one of the arguments are guaranteed to have a truthy first element.
  • lambda - Define an anonymous function using the syntax lambda[[param1; param2; ...; paramN]; bodythatusesparams].
  • label - Store a function using a name. For example, label[drop2; lambda[[xs]; cdr[cdr[xs]]]] defines a function drop2 that drops the first two elements of its first argument.

Rules

  • Functions may use lexical or dynamic scope, or some crazy mixture of both.

Much of this question is copied from this challenge and the Wikipedia article on M-expressions.

Questions for Meta

  • For cond, should I use the [condition -> res; condition2 -> res2; ...] syntax, or should I keep it like the linked challenge? The former looks nicer, the latter allows one to write an eval function.
  • Should answers support higher-order functions?
  • Does anyone have any good examples using Mexprs?
\$\endgroup\$
2
  • \$\begingroup\$ I did a double-take at the title, which sounds like the challenge is to root out communists still hiding in the US state department to finish what Joseph McCarthy started... \$\endgroup\$ – xnor Jan 20 at 10:23
  • \$\begingroup\$ @xnor Uh...that certainly was not what I intended. I could probably say "Finish what John McCarthy started" or just "Interpret M-expressions", although the latter sounds more boring. There's also a Eugene McCarthy, apparently, so I guess just McCarthy is too ambiguous. \$\endgroup\$ – user Jan 20 at 13:59
1
\$\begingroup\$

Radiation Showdown (WIP)


Two radiation-hardened programs will go head-to-head to destroy each other.

Your task is to create a program which takes the other program's source as input and output the index of the byte that should be deleted from the other program. (zero-indexed)

Each program will be radiated at the same time. The first program to fail to return a valid index after being radiated loses (whether by compiler error, runtime exception, out-of-bounds output, or some other means), or it is considered a draw if both fail at the same time.

Each program will compete against each other program. The program receives 1 point per round survived. The overall winner is the one with the most points.

Programs are limited to a length of 1024 bytes.


Alternate possibilities:

(Inspired by @Dingus) A hash of the opponent's original source code and a list of the indexes of bytes deleted so far is passed in instead of the current source code, making it a bit more of a blind guess as to what you radiate. If at any time, a program makes a guess it has already made, it loses. This turns it into a sort of "Radiation Battleship"

\$\endgroup\$
13
  • \$\begingroup\$ Interesting challenge. How will it be tested, if different languages are allowed? \$\endgroup\$ – user Jan 19 at 19:12
  • \$\begingroup\$ @user it shouldn't be terribly difficult to make a shell-based controller. Submissions would probably need to include compiler flags or shebangs separately so that the controller knows exactly how to run the program. \$\endgroup\$ – Beefster Jan 19 at 19:19
  • \$\begingroup\$ That would work for "practical" languages, but I'm a bit worried about esolangs. I guess TIO can probably deal with that, though. \$\endgroup\$ – user Jan 19 at 19:20
  • \$\begingroup\$ If Program A has all its bytes deleted before Program B does, does B win? I'm imagining a pathological scenario in which A is empty and outputs by exit code. \$\endgroup\$ – Dingus Jan 19 at 23:46
  • 1
    \$\begingroup\$ Also, wouldn't something like this be impossible to beat? \$\endgroup\$ – Dingus Jan 20 at 0:12
  • \$\begingroup\$ @Dingus I suppose that would be impossible to beat. I wonder how I could make things different with resisting arbitrary insertions... probably not viable though. \$\endgroup\$ – Beefster Jan 20 at 16:14
  • \$\begingroup\$ To prevent fixed-output programs, could you perhaps tie the indexing to the unmodified code? In other words, force the output to be different every round? \$\endgroup\$ – Dingus Jan 20 at 22:22
  • \$\begingroup\$ @Dingus I think that might work (implying that both the original program and guesses are passed to the program), but there's probably another similar edge case I'm missing. Kinda turns it into radiation battleship. If a program returns a guess it has already made, it instantly loses. \$\endgroup\$ – Beefster Jan 20 at 23:58
  • \$\begingroup\$ Following that thought, it might be kind of interesting if some opaque id (e.g. a hash of the source code) is passed in instead of the current state of the source code. \$\endgroup\$ – Beefster Jan 21 at 0:02
  • 1
    \$\begingroup\$ @Beefster what's the point of the hash? (what can submissions do with it?) \$\endgroup\$ – the default. Jan 21 at 4:37
  • \$\begingroup\$ @thedefault. the hash is only used to assign a distinct id to each program and it could be used to seed a random number generator. \$\endgroup\$ – Beefster Jan 21 at 16:16
  • 1
    \$\begingroup\$ @Beefster I thought submissions aren't supposed to be designed to beat specific opponents (and the only way to use a hash is to optimize to beat specific opponents) (and providing a hash of an unknown string as input just in case somebody wants to seed a RNG with it is a weird decision) \$\endgroup\$ – the default. Jan 22 at 16:47
  • 1
    \$\begingroup\$ Also, if the length of the source code is not known, it's effectively impossible to make guesses that are guaranteed not to be out-of-bounds. (also, I expect 90% answers to this challenge to output something like 0,1,2,3,4,5,...) \$\endgroup\$ – the default. Jan 22 at 16:58
1
\$\begingroup\$

Print a 3D shape

Posted

\$\endgroup\$
7
  • 4
    \$\begingroup\$ Suggestion: use characters other than and as they are multi-byte characters which not all languages will handle easily. ASCII characters instead would be better \$\endgroup\$ – caird coinheringaahing Jan 20 at 21:12
  • \$\begingroup\$ I modified them, thank you. \$\endgroup\$ – Sheik Yerbouti Jan 20 at 21:35
  • \$\begingroup\$ @caridCoinheringaahing I was just looking to try some other character taking as reference this ASCII table. The two characters that I changed are numbers 166 and 167 of the table. I am confused. \$\endgroup\$ – Sheik Yerbouti Jan 21 at 23:45
  • 1
    \$\begingroup\$ Most languages can handle code points between 32 and 127 inclusive. Some use custom code pages (e.g. Jelly) that won't necessarily have extended ASCII characters, but will have regular ASCII \$\endgroup\$ – caird coinheringaahing Jan 21 at 23:48
  • \$\begingroup\$ Oh all right thank you for the clarification! \$\endgroup\$ – Sheik Yerbouti Jan 21 at 23:55
  • 2
    \$\begingroup\$ @Davide the table you linked is not actually an ASCII table. ASCII only goes from 0 to 127; there are more code pages that extend it to 256 and the creator of that table has clearly picked one. This confusion arises because almost all code pages include ASCII as the first 128 and then extend with some symbols like on top of that. Nowadays most things use UTF-8 which encodes some characters with more than one byte and can use millions of different characters from Unicode \$\endgroup\$ – pxeger Jan 22 at 7:58
  • \$\begingroup\$ @pxeger Oh thank you for this definitive explanation! \$\endgroup\$ – Sheik Yerbouti Jan 22 at 13:02
1
\$\begingroup\$

Quine Countdown!

Write a program that accepts a single parameter n and outputs another program that outputs another program etc until the nth call outputs the original input n again.

Scoring is a modified version of codegolf: For input 100, add together the code length of each program in the chain, excluding the final 100. This is your score. Lowest score wins!

\$\endgroup\$
3
  • \$\begingroup\$ Actually it's not much harder than a typical quine program. Because 100 is so large, most programs will do it the general quine way. \$\endgroup\$ – user202729 Jan 29 at 7:18
  • \$\begingroup\$ Besides, the score would be easier to read if the score is the average size instead of the maximum. \$\endgroup\$ – user202729 Jan 29 at 7:18
  • \$\begingroup\$ "Because 100 is so large, most programs will do it the general quine way." That's the intention. It's a quine with something extra. Without the scoring rule, everyone would just build nested multi-escaped prints, which isn't as interesting. \$\endgroup\$ – Sinthorion Feb 9 at 11:07
1
\$\begingroup\$

Counting set bits in a byte

Here is a bite-sized problem I ran in to when trying to implement Conway's game of life on a microcontroller, and was trying to count the amount of neighbours: How can you check how many bits are set in a byte?

Challenge

Given one byte of input data and an integer N between 0 and 8, check if there are exactly N bits set in the byte.

Test cases

N = 0, input = 0b00000001 -> False 
N = 0, input = 0b00000000 -> True 
N = 3, input = 0b01001001 -> True 
N = 3, input = 0b11100000 -> True 
N = 3, input = 0b00001111 -> False 
N = 7, input = 0b11101111 -> True 
N = 7, input = 0b11111110 -> True 
N = 8, input = 0b11111111 -> False 

Sandbox question

  • My first intuition to solving this problem was to shift the bits out one by one, AND with 0x01 and count them. I feel however it must be possible to do something more efficient in terms of CPU cycles used. How can I make a challenge that is about optimizing instruction count and memory usage rather than on program-size? I have seen the tag, but I don't know what scoring method best to use.

Edit: Closing after some good comments and possible solutions

Arnauld and CristoLosoph gave some great comments and led me to conclude that my issue is maybe to hardware/language specific to fit in a nice coding challenge. CristoLosoph showed me this interesting code snippet which I think is quite efficient:

uint8_t count_bits(uint8_t x){
     x = ((x & 0b10101010) >> 1) + (x & 0b01010101); 
     x = ((x & 0b11001100) >> 2) + (x & 0b00110011); 
     x = ((x & 0b11110000) >> 4) + (x & 0b00001111); 
     return x;
}

Two other things I learned:

  • Some hardware have a builtin POPCNT instruction in their instruction set, and gcc has a __builtin_popcount() method that does exactly what I was looking for
  • I found in this question that it's an interesting trade-off (as with most embedded functions probably) to just make a lookup table containing all 256 possible return values. It takes some memory but not too much.

I also learned that probably would have been a good fit for this type of challenge!

Once again thanks for the interesting comments!

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Hello RvdV. Hm, seems like your motivation does not really fit. Fastest-code and smallest code is not the same, rather opposite things. When you program microcontrollers you are very restricted in the language but code golfing is the opposite (if you do not specifically restrict languages to one single one). Of course, there is a very performant solution for bitcount in the language which you might be looking for which however is quite uninteresting for code golf. I'll post you a fast snippet in C below. \$\endgroup\$ – ChrisoLosoph Jan 29 at 10:20
  • 1
    \$\begingroup\$ Closely related. \$\endgroup\$ – Arnauld Jan 29 at 10:25
  • 1
    \$\begingroup\$ You may consider using atomic-code-golf, but be aware that it's pretty hard to specify correctly. \$\endgroup\$ – Arnauld Jan 29 at 10:26
  • 1
    \$\begingroup\$ x = ((x & 0xAAAAAAAA) >> 1) + (x & 0x55555555); x = ((x & 0xCCCCCCCC) >> 2) + (x & 0x33333333); x = ((x & 0xF0F0F0F0) >> 4) + (x & 0x0F0F0F0F); x = ((x & 0xFF00FF00) >> 8) + (x & 0x00FF00FF); x = ((x & 0xFFFF0000) >> 16) + (x & 0x0000FFFF); You only need the first 3 lines if you only need it for 8-bit integers and then you can cut the hexadecimal literals down to two digits. \$\endgroup\$ – ChrisoLosoph Jan 29 at 10:29
  • 1
    \$\begingroup\$ But if you work with GCC, please use __builtin_popcount() since that is the function that the compiler people tried to optimize exactly for your purpose and for your selected architecture. \$\endgroup\$ – ChrisoLosoph Jan 29 at 10:31
  • \$\begingroup\$ Thanks a lot for your comments Arnauld and ChrisoLosoph! You are right that it's hard to define, and I didn't realize even how much language but also hardware-bound my problem was, maybe it's too difficult to define indeed (and if you define it language-agnostic it becomes the related post Arnauld linked). I will update the post with you suggestions! \$\endgroup\$ – RvdV Jan 29 at 17:51
1
\$\begingroup\$

Mix my colors

This challenge is inspired by the Color Alchemy Patch on NetHack, notably incorporated by UnNetHack 3.5.2.

Objective

Given two strings indicating colors, mix them according to the rules below, then output it.

Colors

There are 16 colors in total that are valid inputs. They are categorized to 8 chromaticities and 2 brightnesses, like below:

        Light    Dark
Hueless white    black
Red     pink     ruby
Blue    sky-blue indigo
Yellow  yellow   golden
Orange  orange   amber
Green   emerald  dark-green
Purple  puce     magenta
Brown   ochre    brown

(I'm omitting gray, for it will make this challenge just cumbersome in this regard.)

Note that all color names are in lowercase.

Color-mixing rules

  • Above all, mixing colors is idempotent.

  • Mixing colors is commutative unless noted below.

  • When mixing two primary colors (Red, Blue, or Yellow):

    • If they have same chromaticities, the result will also be in the same chromaticity.

    • Mixing Red and Blue results in Purple.

    • Mixing Red and Yellow results in Orange.

    • Mixing Blue and Yellow results in Green.

  • When mixing two secondary colors (Orange, Green, or Purple):

    • If they have same chromaticities, the result will also be in the same chromaticity.

    • All other combinations result in Brown.

  • For all cases covered by above, mixing two Light (resp. Dark) colors will result in corresponding Light (resp. Dark) color.

  • For all cases covered by above, mixing a Light color and a Dark color shall result in either Light or Dark. This is the only rule that may break the commutativity.

  • Mixing a Light color with black results in corresponding Dark.

  • Mixing a Dark color with white results in corresponding Light.

  • All combinations not covered by above fall in don't care situation.

Examples

Valid outputs

  • Mixing white and white results in white.

  • Mixing pink and pink results in pink.

  • Mixing pink and ruby results in either pink or ruby.

  • Mixing ruby and golden results in amber.

  • Mixing sky-blue and ruby results in either puce or magenta.

  • Mixing emerald and dark-green results in either emerald or dark-green.

  • Mixing emerald and orange results in ochre.

  • Mixing puce and amber results in either ochre or brown.

  • Mixing white and ruby results in pink.

  • Mixing ochre and black results in brown.

Don't care situations

  • Mixing pink and white falls in don't care situation. There is no rule that covers this case.

  • Mixing ochre and brown falls in don't care situation. There is no analogous rule for tertiary colors.

  • Mixing indigo and magenta falls in don't care situation. There is no rule for mixing a primary color and a secondary color.

  • Mixing indigo and orange falls in don't care situation.

  • Mixing pink and ochre falls in don't care situation.

  • Mixing white and black falls in don't care situation. (In the game, it results in gray, but I'll ignore this, for sake of simplicity of this challenge.)

Rules for code golf

  • Input format is flexible. In particular, it can be two strings, or one string separating colors by whitespaces. It's implementation-defined whether to accept leading or trailing whitespaces.

  • Output format is also flexible. Outputting leading or trailing whitespaces is okay.

  • Invalid inputs fall in don't care situation.

\$\endgroup\$
1
  • \$\begingroup\$ The rule looks clear enough, but you can provide a table of 256 possible outputs just to be extra sure. \$\endgroup\$ – user202729 Jan 31 at 1:57
1
\$\begingroup\$

Longest Common Suffix

Given arbitrarily many (more than 4) words, your goal is to find the longest common suffix of all of them.

Rules

  1. The suffix shouldn't be longer than one third of the length of any word, and should be longer than 2 characters.
  2. The words can have at most one "exception" among them, that is, it doesn't have the same suffix others have. You should ignore these "exceptions".
  3. If no suffix can satisfy all rules above, do not make any output.
  4. All given words are separated by spaces; they only contain lower case English alphabets.
  5. You can use any way to accept input, but output should only be in STDOUT.

Example

Given: television operation delegation repetition
Output: ion
Given: vision decision subtraction observation
Output: 

Why? The suffix, ion, is longer than 1/3 the length of vision and decision. There're two exceptions.

Given: interested congratulated excited overjoyed
Output: ted

Why? overjoyed is an exception, because others have the suffix ted, but it doens't. So we ignore the word overjoyed.

Given: abcdefghijkl bcdefghijkl cdefghijkl defghijkl
Output: jkl

Why? defghijkl is the longest, but it is longer than 1/3 the length of defghijkl.

This is code golf, so the shortest code win.

It's not recommended to use built-in functions which directly returns the result.

\$\endgroup\$
2
  • \$\begingroup\$ Most answerers prefer "any (standard) way to get output" as well, but it's up to you. Practically, it's mostly not a problem. \$\endgroup\$ – user202729 Feb 1 at 9:30
  • \$\begingroup\$ Regarding the output "No common...", people don't like hard coding long error messages, it would be better received if it's changed to "any value that signifies that there isn't...". \$\endgroup\$ – user202729 Feb 1 at 9:31
1
\$\begingroup\$

Next to the middle

Posted

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Clearly defined enough (not very interesting) -- except that is it guaranteed that the value exists? \$\endgroup\$ – user202729 Feb 1 at 3:14
  • \$\begingroup\$ @user202729 Oh thank you, I forgot to cover this. I think that in case it doesn't exist, we can output a something like the smallest integer in the array. I would like to not restrict the input at all. \$\endgroup\$ – Sheik Yerbouti Feb 1 at 12:03
  • 1
    \$\begingroup\$ Possible test case: empty array. (by the way don't patch "edit" into the sandbox post, include it in the text itself) \$\endgroup\$ – user202729 Feb 2 at 2:58
  • \$\begingroup\$ @user202729 thank you, I edited the challenge. I will add test cases, including the empty array. \$\endgroup\$ – Sheik Yerbouti Feb 2 at 10:26
1
\$\begingroup\$

Golf this Thumb-2 constant!

Posted.

\$\endgroup\$
7
  • \$\begingroup\$ Not very related to the question, but have you tried using some size-optimization option of some existing compiler? (-Os) \$\endgroup\$ – user202729 Feb 1 at 9:32
  • \$\begingroup\$ Otherwise, clear enough. \$\endgroup\$ – user202729 Feb 1 at 9:33
  • \$\begingroup\$ I explained the pattern better, and the last pattern does cover the rest, but it isn't the shortest. \$\endgroup\$ – EasyasPi Feb 4 at 0:43
  • \$\begingroup\$ Okay. (just to check, there are \$4862 > 2^{12} = 4096\$ distinct values represented with the Imm12 format, right?) \$\endgroup\$ – user202729 Feb 4 at 0:53
  • \$\begingroup\$ Yes. There are 4096 possible encodings for the Imm12 format. \$\endgroup\$ – EasyasPi Feb 4 at 1:48
  • \$\begingroup\$ Then I must understand something wrong, because (as I've said above) there are 4862 different values that can be encoded.) \$\endgroup\$ – user202729 Feb 4 at 1:51
  • \$\begingroup\$ Oh yeah I was wrong. I think I am going to go back to it just being a byte rotated, even if it isn't accurate. As the true encoding is too complex to be fun to calculate. 🤷‍♂️ \$\endgroup\$ – EasyasPi Feb 4 at 3:02
1
\$\begingroup\$

(this is the core of the BF memory optimizer challenge.)

(At the moment I still need to make some test cases; however you can still review the rest of the challenge.)

note: This problem is reducible from Simple Max Cut, therefore it's NP-complete. (https://doi.org/10.1016/0304-3975(76)90059-1)

note: While I did get a bunch of test cases from this site, I'm not sure how can I write a reasonable algorithm to compete with...


Proof

(actually this is not part of the sandbox challenge, but I'll post it here because it's related)


First, for convenience, assume that the problem is represented by a undirected graph, where the number of rows/columns of the matrix is equal to the number of nodes, and the corresponding weight is the sum of the value of the edges connecting the corresponding two nodes.

With that representation, the value to be minimized is the sum of the product of the edge lengths and the edge weights, with the graph nodes embedded into the point \$ 1, 2,\ldots, |V| \$.


From a Simple Max Cut problem of the form:

Given \$ n \$ variables \$ x_1, x_2,\ldots, x_n \$, maximize the value of \$ \sum_{i=1}^m [a_i \ne b_i] \$, where each of \$ a_i, b_i \$ represents either a variable or its negation.

It can be transformed to an instance of this problem:

First, construct \$ 2n \$ nodes on a graph, denoted \$ p_1, p_2,\ldots, p_n, q_1, q_2,\ldots, q_n \$. Let \$ a \$ be some positive integer. Connect those vertices:

  • \$ p_1 \$ and \$ q_1 \$, with cost \$ 2n^2 a \$,
  • the 4 pairs of vertices \$(p_1, p_i),(p_1, q_i),(q_1, p_i),(q_1, q_i)\$ with cost \$ (n+1-i) a \$, for each \$ i=2, 3,\ldots, n \$,
  • and some other edges with small weights (the sum of their weights should be less than \$a\$ -- (1)) that mainly does not affect the optimal configuration.

The sum of the edge weights (except the first one) is \$ 4 ((n-1)+(n-2)+\ldots+1)a=2n(n-1)a \$.

The edge between \$ p_1 \$ and \$ q_1 \$ has a weight larger than the sum of all the others, it's obvious to see that in the optimal (minimum cost) configuration, these two must be adjacent.

Then, regardless where those 2 vertices are placed, the \$ i \$'th smallest distance-pair to those are at least the \$ i \$'th value in the sequence are

$$(1, 2),(1, 2),(2, 3),(2, 3),(3, 4),(3, 4),\ldots,(n-1, n),(n-1, n)$$

.

And by the rearrangement inequality, it's optimal to place the weight so that the vertices with the smaller edge-weight to \$ p_1, q_1 \$ are placed further from the vertices. Therefore the only optimal placement is

$$z_n, z_{n-1}, \ldots, z_2, z_1, z_1, z_2, \ldots, z_{n-1}, z_n$$

where each \$ z_i \$ is either \$ p_i \$ or \$ q_i \$ (\$1 \le i \le n\$).


Encode the condition "vertex \$ i \$ is on the left side of the cut" by "\$ p_i \$ is to the left of \$ q_i \$ in the permutation". (2)

Assuming that the edge weights are allowed to be fractional.

For each condition (in the Simple Max Cut problem) that "there's an edge between vertices \$u\$ and \$v\$ (\$ u\le v \$)", add an edge between \$ p_u \$ and \$ q_v \$ with weight \$\frac 1 {2u-1}\$ to this problem.

The weight of this edge can either be \$ u-v \$ or \$ u-v+(2u-1)\$ in the configuration that minimizes the total weight of the edges constructed in the previous section.

Therefore, if the vertices \$ u \$ and \$ v \$ are on different sides of the cut (according to the encoding (2)), the total weight is decreased by \$ 1 \$ if \$ u \$ and \$ v \$ are on different sides; and the configuration with the minimum weight is exactly the one with maximum number of edges cut.

However, in the actual problem edge weights must be an integer. We replace each edge weight \$\frac 1 {2u-1} \$ by \$\lceil\frac c {2u-1}\rceil \$, where \$ c=2nm\$.

Because there are \$ m \$ edges in total, if the sum of any \$ k-1 \$ increment values \$\lceil\frac c {2u-1}\rceil (2u-1) \$ is strictly less than the sum of any \$ k \$ increment values, for \$1\le k\le m \$, then the optimal sum is also the maximum cut.

Observe that because \$ c=2nm \$ and \$ x\le 2n-1 \$, each increment value must be between \$ 2nm \$ (inclusive) and \$ 2nm+2n-1 \$ (exclusive). Therefore the maximum sum of \$ k-1 \$ values is \$ (2nm+2n-2)(k-1) \$, which is less than the minimum sum of \$ k \$ values \$ 2nmk \$ when \$ 1\le k\le m \$.

The sum of all those does not exceed \$ \lceil \frac {2nm}{1} \rceil m \$. Therefore if \$ a \$ is chosen to be \$ 2nm^2+1 \$, then the condition (1) is satisfied.


Minimum cost matrix permutation

(or ? Obviously the latter would be more useful in practice code golf)

Given a matrix \$w\$ in \${\mathbb N_0}^{n\times n}\$, define the symmetric matrix \$d\$ in \${\mathbb N_0}^{n\times n}\$ by the formula \$d_{i,j}=\left| i-j \right|\$, find a permutation matrix \$P\$ such that the sum of elements in the matrix \$(P^{\mathsf T} \cdot w \cdot P ) \,\odot\,d\$ (where \$\odot\$ denotes the Hadamard product/element-wise product) is smallest.

The result will be the mean (TODO: median? mean of the 50% maximum? mean result/naive ratio?) of the score over these test cases, for as long as you can run your program.

\$\endgroup\$
1
\$\begingroup\$

(WIP) Settling the Lands of Codegolfia


The challenge controller will randomly generate a 200x200 map representing the terrain of the land

Your task is to write an AI whose goal is to have the largest population after 500 turns.

Start

Each player begins with 1 cell claimed and a population of 100.

Turns

On each turn, you have the opportunity to claim land cells. You can claim 1 cell per turn, plus 1 per 1000 population. Claimed cells must be orthogonally adjacent to a cell you already own. You cannot claim cells belonging to other players.

Turns happen simultaneously. In the event that two players attempt to claim the same cell, both players will lose 10 people from their population and neither player will claim the cell.

At the end of your turn, your population grows by 10% (rounded up), up to the maximum size your colony can support.

Population Support

Without any land claimed, your colony can support up to 150 people.

Supporting larger populations requires claiming land. Each terrain type increases the amount by some amount. Combinations of terrain expand this further.

Terrain

There are 4 terrain types:

  • Plains
    • Supports 20 people by itself
    • Supports 5 per adjacent owned plains
  • Forest
    • Supports 10 people by itself
    • Supports 5 per adjacent owned forest
    • Supports 50 additional people if there are at least 10 owned plains cells within 10 cells (Manhattan distance)
  • Mountains
    • Supports 5 by itself
    • Supports 5 per owned plains within 15 cells
    • Supports 10 per owned forest within 5 cells
  • Water
    • Each plains cell can support 500 additional people if it is within 5 cells of an owned water cell.
    • Each forest cell can support 200 additional people if it is within 10 cells of an owned water cell.

Alternative ideas for terrain

  • Plains support raw population. Same as above
  • Forest cells increase population support for all plains within 5 cells by a factor of 5% (stacks multiplicatively)
  • For every water cell and 10 plains cells, reproduction rate increases by 1%
  • Each mountain cell increases the range of each owned mountain and forest within 3 cells by 1. (stacks additively)
\$\endgroup\$
3
  • \$\begingroup\$ I was just thinking of something like this! (but different enough I can still do mine :p). Currently I don't see too many options for strategy other than comparing each orthagonal square each turn and picking the best. \$\endgroup\$ – Redwolf Programs Feb 11 at 19:38
  • \$\begingroup\$ @RedwolfPrograms yeah. Maybe I should make each of the terrains more mechanically different. Maybe one increases reproduction rate, one expands synergy range, and another enhances the others. \$\endgroup\$ – Beefster Feb 11 at 20:24
  • \$\begingroup\$ That sounds like a good idea, depending on how it's implemented. Maybe being close to water would let you claim extra land per turn near the body of water, sort of like exploration? \$\endgroup\$ – Redwolf Programs Feb 11 at 20:31
1
\$\begingroup\$

Heads I win, tails you booze: coin tossing, pub trivia style

At my old pub trivia night, a free jug of beer or bottle of wine was awarded to the team that won Heads or Tails. This game requires players to correctly guess the outcome of successive coin tosses. The game proceeds as follows:

  1. Before each toss the remaining players, who are standing, place both hands on their head (for heads) or their bottom (for tails). If all remaining players choose the same outcome (which would lead to a draw) the host refuses to toss the coin until at least one player changes his/her guess.
  2. The host then tosses a coin (assumed fair) and announces the outcome. All players who guessed incorrectly are eliminated and have to sit down.
  3. Play continues until there is only one person left standing to claim the prize for their team.

In perfect play, the remaining players on each team always divide as evenly as possible between heads and tails:

  • If the number of remaining players on a team is \$2k\$ for some positive integer \$k\$, then exactly \$k\$ of them guess heads and \$k\$ of them guess tails.
  • If the number of remaining players on a team is \$2k+1\$, then with equal probability
    • exactly \$k\$ of them guess heads and \$k+1\$ of them guess tails, or
    • exactly \$k+1\$ of them guess heads and \$k\$ of them guess tails.

An interesting consequence of players not acting independently is that a team's probability of winning is not, in general, equal to \$\dfrac{\text{number of players on the team}}{\text{number of players on all teams}}\$, as the examples below illustrate.

Challenge

Assume that there are \$n_0\$ players on our team and \$n_1, n_2,\ldots, n_N\$ players on the opposing \$N\$ teams (\$N\$ and the \$n_i\$ are all positive integers). Given the \$n_i\$ as input, write the shortest program or function that calculates the probability that our team wins the booze, assuming perfect play by all teams.

Input format is flexible: you may (for example) take

  • an integer \$n_0\$ and a list \$[n_1, n_2, \ldots, n_N]\$ (this format is used in the test cases),
  • a flat list \$[n_0, n_1, \ldots, n_N]\$,
  • a nested list \$\left[n_0, [n_1, n_2, \ldots, n_N]\right]\$.

The \$n_i\$ may be taken in any order. Output should be in a suitable numeric format. Floating-point approximations are acceptable provided that the underlying algorithm is theoretically exact. You may not return a list of winning probabilities for all teams (I don't care how likely it is that another team wins).

Examples

Example 1: \$n_0=1\$, \$n_1=2\$

Suppose there are only two teams: our team has one player and the opposing team has two players. After the first toss, exactly one player from the opposing team remains in the game (because one player guesses heads and the other guesses tails). For our team:

  • Half of the time, our player has guessed incorrectly and is eliminated. The other team wins.
  • Half of the time, our player has guessed correctly. A second toss occurs—a head-to-head battle with the remaining player on the other team—which our player wins half of the time.

The probability that our team wins is therefore \$\dfrac{1}{2}\cdot0 + \dfrac{1}{2}\cdot\dfrac{1}{2} = \dfrac{1}{4}\$.

Example 2: \$n_0=2, n_1=3\$

In this case, both teams survive the first toss. Exactly one player remains on our team. For the other team:

  • Half of the time, one player remains. A second toss decides the winner.
  • Half of the time, two players remain. From this point, the remaining tosses play out exactly as in Example 1.

The probability that our team wins is therefore \$\dfrac{1}{2}\cdot\dfrac{1}{2} + \dfrac{1}{2}\cdot\dfrac{1}{4} = \dfrac{3}{8}\$.

Test cases

\$n_0\$, \$[n_1, n_2, \ldots, n_N]\$ -> Output

1, [2] -> 1/4
2, [3] -> 3/8
5, [5, 5, 5] -> 1/4
5, [3, 5, 7] -> 5929/24576
8, [1, 2, 4] -> 485/768
6, [4, 5, 5, 6, 8] -> 45/256
\$\endgroup\$
13
  • \$\begingroup\$ Even then, that "perfect strategy" strategy is ambiguous -- what if there's an odd number of players? Why isn't there a (us=H, them=H) case in the "round 2" of example 1? [please review other sandbox posts] \$\endgroup\$ – user202729 Feb 13 at 5:41
  • \$\begingroup\$ @user202729 Yes to your first question. For your second question, there's no (H, H) because one of the players on the other team was eliminated in Round 1. Do the edits help? \$\endgroup\$ – Dingus Feb 13 at 5:46
  • \$\begingroup\$ @user202729 Just saw your edit. (us=H, them=H) is a draw (by which I mean the round would just be repeated until they guess differently from each other). It's supposed to be covered by 'the pathological scenario in which all players repeatedly guess the same outcome never occurs in practice'. \$\endgroup\$ – Dingus Feb 13 at 5:47
  • \$\begingroup\$ So if there are two ways to divide evenly (odd number), assume that each team choose one of them independently with the same probability? \$\endgroup\$ – user202729 Feb 13 at 5:49
  • \$\begingroup\$ By the way, unless there's some clever formula to calculate the result, I expect that all the submissions will be too inefficient to calculate the last test case. \$\endgroup\$ – user202729 Feb 13 at 5:52
  • \$\begingroup\$ @user202729 I'll add some text to clarify what happens with odd-sized teams and a small test case with all odd-sized teams of different sizes. Fair point about the inefficiency. \$\endgroup\$ – Dingus Feb 13 at 5:57
  • \$\begingroup\$ Okay that part is good now, but you might want to add "if all players guessed wrong, then no players is eliminated" \$\endgroup\$ – user202729 Feb 13 at 11:24
  • \$\begingroup\$ @user202729 I think that's covered by 'If all remaining players choose the same outcome (which would lead to a draw) the host will refuse to toss the coin until at least one player changes his/her guess', but it should be clearer now that I've moved that sentence earlier in the description. \$\endgroup\$ – Dingus Feb 13 at 11:36
  • \$\begingroup\$ By the way, do you have a proof that the mentioned algorithm is optimal? \$\endgroup\$ – user202729 Feb 13 at 12:47
  • \$\begingroup\$ "until at least one player changes..." can be ambiguous (what is their strategy to change the choice?) I think "skips the round and all player choose [...] again" is better. \$\endgroup\$ – user202729 Feb 13 at 12:52
  • \$\begingroup\$ By the way, do you have a polynomial time solution? \$\endgroup\$ – user202729 Feb 15 at 2:07
  • \$\begingroup\$ (this is a (probably polynomial time, or at least can be made polynomial time) implementation . tio.run/… ) \$\endgroup\$ – user202729 Feb 16 at 6:43
  • \$\begingroup\$ @user202729 I appreciate all the comments, thank you. Clearly there's a bit to think about but I won't have time to look at this again in detail for a few days, probably. (It may be that this challenge has more potential in a category other than code golf, but I'm not sure yet.) \$\endgroup\$ – Dingus Feb 16 at 7:02
1
\$\begingroup\$

Score an approximation code challenge

Given a list of inputs (strings) and their expected outputs (integers or floats)[1], and a black-box program[2], calculate the score using the following scoring system:

Let \$R_n\$ be the expected output of the \$n^{th}\$ input, let \$A_n\$ be the actual output given by the black-box program, and let \$ j \$ be the total number of input/output pairs. (All values are positive and non-zero)

Then the score is defined as: $$S=\left\lceil L\times\max_{1\le i \le j}\left({\max\left(\frac{A_i}{R_i},\frac{R_i}{A_i}\right)^2}\right)\right\rceil$$ where \$L\$ is the length of the black-box program in bytes.

Example:

If the size of the program is \$100\$ bytes and the worst approximation is on the input "moon", where the program outputs \$1000\$ instead of the expected \$1737\$, then the score would be:

$$S=\left\lceil 100\times{\left(\frac{1737}{1000}\right)^2}\right\rceil=302$$

This system is taken shamelessly from this challenge by @Arnauld. Here is his reference implementation.


[1]: You may take the inputs and outputs either zipped ([(in1, out1), (in2, out2), ...]), or not zipped (([in1, in2, ...], [out1, out2, ...]), with both lists of the same length), at your option.

[2]: You may take the black-box program as either:

  • a black-box function, and its length in bytes, as two separate inputs
  • a string of code to be evaluated, as one input (the length will not be given separately unless necessary)

Rules

\$\endgroup\$
3
  • \$\begingroup\$ (1) is it a problem if the program only support integers? (2) is it guaranteed that both values (actual and submission output) are strictly positive? The formula is not well defined when either value is zero. \$\endgroup\$ – user202729 Feb 15 at 13:17
  • \$\begingroup\$ @user202729 all values will be positive; the idea was that you can support integers or floats, whichever is easier \$\endgroup\$ – pxeger Feb 15 at 13:23
  • \$\begingroup\$ The "whichever is easier" part is currently not mentioned in the challenge. \$\endgroup\$ – user202729 Feb 17 at 10:36
1
\$\begingroup\$

Stack half full or half empty? (worldview of a programming language)

Is the glass half full or half empty? It's a common rethoric question to determine a person worldview, which can be optimistic or pessimistic based on the answer given. If i were dealing with a machine i would probably ask "Is the stack half full or half empty?" Let's try and see if programming languages have a worldview too.

Write a full program or a function which prints or returns one of "The stack is half full." or "The stack is half empty." when given as input the question "Is the stack half full or half empty?" but wait.. you have to provide a stack to be observed.. which stack you provide is up to you: input one or check an already existing stack. Your solution will then output one of the two sentences mentioned above for a non empty / non full stack, your choice which one to print, just make sure your answer is as short as possible because this is . For an empty stack it must produce the "empty" output while for a full stack "full".

Survey

I will make a chart of the pessimistic Vs optimistic languages based on the half outputs. If you find the same byte count for both choices you can provide both, in which case they will count on both sides of the chart, but you just can select one if you like.

input

  • A sentence in any reasonable method.
  • The behavior is defined only for the question "Is the stack half full or half empty?" and exactly this.
  • Indeed your solution can also completely ignore the input as long as it works with the specified input.
  • Question mark is mandatory.

output

  • One of "The stack is half full." or "The stack is half empty.", for a non full / non empty stack.
  • "full" or "empty" for a full stack or an empty stack respectively
  • upper / lower case or a mix are fine.
  • ending dot not mandatory.

Rules

  • Only the mentioned input allowed.
  • Loopholes allowed.
  • This is and the answer with the fewer bytes of source code wins.
\$\endgroup\$
12
  • 2
    \$\begingroup\$ This would be a really cool challenge, but the tasks are too similar. I doubt anything other than print "The glass is half full" will be competitive. Maybe add an additional thing they have to do, in addition to printing the text? As an example, for half empty, take a number of inputs and discard every second one. For half full, print every other fibonacci number. \$\endgroup\$ – Redwolf Programs Feb 18 at 20:41
  • \$\begingroup\$ So undefined behaviour is fine for all inputs that are not one of the two specific questions? \$\endgroup\$ – Adám Feb 18 at 20:41
  • \$\begingroup\$ Your initial description only mentions one possible input, while your "input" section mentions both. \$\endgroup\$ – Adám Feb 18 at 20:42
  • \$\begingroup\$ Thanks @Redwolf Programs ! To be honest I had this crazy idea but don't really knew how to make it interesting.. I ended developing it in the simplest and most obvious way.. Maybe I 'll change many things during the sandbox \$\endgroup\$ – AZTECCO Feb 18 at 20:48
  • \$\begingroup\$ @Adám yes for UB, for the input I'm sorry, my fault.. Initially I was using only one question but then decided it was reasonable to handle both combinations.. Gonna edit thanks! \$\endgroup\$ – AZTECCO Feb 18 at 20:51
  • \$\begingroup\$ @Redwolf Programs I changed a bit, I hope this stack thing will add some flavor without exiting the context, please let me know if you want to share some opinions \$\endgroup\$ – AZTECCO Feb 21 at 18:43
  • \$\begingroup\$ @Adám some changes.. If you have any opinions please let me know \$\endgroup\$ – AZTECCO Feb 21 at 18:45
  • \$\begingroup\$ @AZTECCO I still think half empty and half full should require doing different things. Currently I doubt anyone will pick half empty, because half full is shorter and there's no other difference. \$\endgroup\$ – Redwolf Programs Feb 22 at 0:24
  • \$\begingroup\$ @Redwolf Programs yeah that's true. I was wondering if languages with built in string compression, string methods or regex would compete the plain print"..answer.." method which should be around 25~30 of score but.. I don't know.. I just feel like a do this or that based on input is a different challenge but it seems to be the only way \$\endgroup\$ – AZTECCO Feb 22 at 9:21
  • \$\begingroup\$ @AZTECCO The concept of the answers choosing between two options is really cool and unique; the current options are just too similar. Maybe one thing that tests control flow, like a truth machine sort of thing, and one that tests input/output, like discarding every other output? The stack validating thing (where you have to print empty or full) feels kind of irrelevant to the cool part of the challenge. Having the input be the question isn't really necessary IMO; you could replace the input with something like a list of numbers (cont.) \$\endgroup\$ – Redwolf Programs Feb 22 at 16:19
  • \$\begingroup\$ (cont.) and have the answers do one of two things with that list (totally up to you, although I'd recommend tasks that use different capabilities of the language, like one control flow and one math), then print The glass is half (empty|full). \$\endgroup\$ – Redwolf Programs Feb 22 at 16:20
  • \$\begingroup\$ @Redwolf Programs thanks for explaining your opinion, your insight are really important and I totally agree, I was losing the scope and your words got me back on track! \$\endgroup\$ – AZTECCO Feb 22 at 19:27
1
\$\begingroup\$

Bytewise look-and-say sequence

The look-and-say sequence is a sequence which begins with 1, 11, 21, 1211, 111221, 312211. To get a term of the sequence from the previous, read the previous out literally:

312211 => one three, one one, two twos,two ones => 13112221

So the next term is 13112221.

Given this javascript code (Node.js), which outputs the look-and-say sequence indefinitely, delimited by newlines:

function nextTerm(x){
  return x.replace(/(.)\1*/g,z=>z.length+z[0])
}
function printUpTo(x){
  var str = '1';
  for(var i = 0; i < x; i++){
    console.log(str);str = nextTerm(str);
  }
}
printUpTo(Infinity)

It will output a string that begins 1\n11\n21\n1211\n111221 etcetera. Your job is to write a function that takes a number as input and outputs that byte of the output string.

Rules

You may output a different character for newline instead of \n, e.g. # or something.

Scoring

Your program should be able to handle 100 million.

The first answer to handle 1e+18 correctly will receive a 100-rep bounty. This cannot be hard-coded.

Standard loopholes apply.

Test cases:

1 => \n
5 => 2
10 => 1
20 => 3
50 => 3
100 => 1
1000 => 1
100000 => 3
10000000 => 1

This is , so shortest bytes wins.

\$\endgroup\$
22
  • \$\begingroup\$ Note that restricted-complexity means "solutions' time complexity must be polynomial in the input size" or something similar. "In a minute" means restricted-time, but then you have to specify the specification of your machine and test all solutions (although in most cases it will be obvious and you don't need to) \$\endgroup\$ – user202729 Feb 20 at 9:39
  • \$\begingroup\$ And an implementation of the naive algorithm in a low-overhead language (C++) would be able to do that as well. \$\endgroup\$ – user202729 Feb 20 at 9:40
  • \$\begingroup\$ @user202729 I'm not actually sure how to write this myself - notice that there isn't a testcase for 1 billion - that's because I couldn't figure out how to do an actually efficient version. Also, by 'In a minute', I mean on TIO. I'll add that. \$\endgroup\$ – A username Feb 20 at 9:44
  • \$\begingroup\$ And TIO isn't suitable for timing submissions (personally I think it's really suitable, but people don't agree.) \$\endgroup\$ – user202729 Feb 20 at 9:45
  • \$\begingroup\$ @user202729 What do you mean? Is it something to do with how busy the server is or similar? \$\endgroup\$ – A username Feb 20 at 9:46
  • \$\begingroup\$ codegolf.meta.stackexchange.com/questions/12707/… \$\endgroup\$ – user202729 Feb 20 at 9:48
  • \$\begingroup\$ @user202729 Ok, redoing the whole thing, since I don't want to install loads of different compilers/interpreters. \$\endgroup\$ – A username Feb 20 at 9:50
  • \$\begingroup\$ Ok, publishing. \$\endgroup\$ – A username Feb 22 at 4:30
  • \$\begingroup\$ Wait, I did warn you that a naive implementation in C++ would be able to do it. \$\endgroup\$ – user202729 Feb 22 at 4:30
  • \$\begingroup\$ Do you want to allow that? \$\endgroup\$ – user202729 Feb 22 at 4:31
  • \$\begingroup\$ Ok, 1e+12 should be fine. \$\endgroup\$ – A username Feb 22 at 4:31
  • \$\begingroup\$ Wait are you sure that there actually is a polynomial time solution? \$\endgroup\$ – user202729 Feb 22 at 4:32
  • \$\begingroup\$ I feel like there should be one, but I don't know. Never mind. \$\endgroup\$ – A username Feb 22 at 4:33
  • \$\begingroup\$ Actually there probably isn't since there's no way to calculate the nth term or length of nth term without calculating the previous. So never mind. \$\endgroup\$ – A username Feb 22 at 4:36
  • \$\begingroup\$ There probably is. (I didn't come up with one.)Although people could let their programs run for a month. 1e+18 is definitely safe, but might be a little too large for some polynomial approaches. \$\endgroup\$ – user202729 Feb 22 at 4:36
1
\$\begingroup\$

Self improving program

In this challenge you will write a program or function which when run will output a faster solution to this challenge.

Formally speaking: you will write a program or function, \$T_0\$, which takes an integer \$x\$ as input and outputs a program or function (in the same language), \$T_1\$, which is itself a valid solution to this challenge, such that there exists a function \$f\$ where \$T_1\$ is in the time complexity class \$O\left(f\right)\$, but \$T_0\$ is not. That is to say the output program must have a strictly faster asymptotic time complexity.

Note that since \$T_1\$ must be a valid solution to the challenge it must output a program or function \$T_2\$ which is even faster, and so on and so forth, creating an infinite chain each faster than the last.

Answers will be scored by their length in bytes with fewer being better.


Precision

In keeping with the tradition of this site, and to remain inclusive: The order notation of a function will be assumed to be measured by the algorithm implemented by your answer. Thus we will pretend not to notice the behavior of your actual program for inputs out of the range of your language's numeric type.

However that being said, in order to ensure that you are actually changing the algorithm at every step, for constants initialized in your program this leniency is not given. e.g. If you use a double precision floating point 1.0000000000000001 is equal to 1.0. So if your method relies on an increasing or decreasing constant embedded in the program you should be careful that the algorithm actually changes.

Simply put for \$T_n(x)\$ you are forgiven for errors arising from very large \$x\$, but not from very large \$n\$.

\$\endgroup\$
9
  • \$\begingroup\$ (which is the same thing is \$T_0\in o(T_1) \$.) \$\endgroup\$ – user202729 Feb 20 at 9:54
  • \$\begingroup\$ How is this possible? You'd need to get faster and faster, and even if you do it exponentially, you can't change the speed by tiny fractions of a second each time. Please explain, very confused. \$\endgroup\$ – A username Feb 20 at 9:54
  • \$\begingroup\$ And what prevents programs from doing for i in range(int(n**1.00001)): pass? \$\endgroup\$ – user202729 Feb 20 at 9:55
  • \$\begingroup\$ Thinking about it again, since programs can simply run a loop to have any asymptotic complexity (>= complexity to parse input), it's not that hard. And you could just ask programs to print out an always-decreasing floating point value plus the new program. \$\endgroup\$ – user202729 Feb 20 at 9:57
  • \$\begingroup\$ @user202729 But the always-decreasing float is the problem here, because eventually it will get too small to be distinguished by the language from 0. \$\endgroup\$ – A username Feb 20 at 10:01
  • 2
    \$\begingroup\$ @Ausername An easier way to have it constantly decreasing is to have O(n^2) -> O(n log(n)) -> O(n log(log(n))) -> O(n log(log(log(n)))) etc. This approaches O(n) from above and remains distinguishable for really large inputs, without requiring anything finicky about precision. \$\endgroup\$ – Wheat Wizard Feb 20 at 10:02
  • \$\begingroup\$ @user202729 Do the precision rules address your comments? \$\endgroup\$ – Wheat Wizard Feb 20 at 10:17
  • \$\begingroup\$ It means that programs doing things like (Python) n=1000000000000000000000000000000; for i in range(int(input())**(1+1/n): pass and (1+1/n) evaluates to 1 (because of IEEE754, even though the value of n is stored exactly) will fail? \$\endgroup\$ – user202729 Feb 20 at 11:45
  • \$\begingroup\$ @user202729 Yes. Precision rules are always pretty non-concrete and non-objective. I think it is best to not try to push at the boundaries. \$\endgroup\$ – Wheat Wizard Feb 20 at 12:49
1
\$\begingroup\$

Is it zero- or one- indexed?


Posted

\$\endgroup\$
4
  • \$\begingroup\$ The tag should be [array-manipulation], and I'd recommend linking to the convenient I/O methods, but other than that this looks ready to go \$\endgroup\$ – caird coinheringaahing Feb 23 at 0:12
  • \$\begingroup\$ Clear enough. [please review other sandbox posts] (<-- also 15 character filler) \$\endgroup\$ – user202729 Feb 24 at 4:24
  • \$\begingroup\$ can the input index be greater than the length of the array? \$\endgroup\$ – Leo Feb 26 at 0:14
  • 1
    \$\begingroup\$ @Leo no: "You may assume that the index is in-bounds for both zero- and one-indexed semantics." \$\endgroup\$ – Beefster Feb 26 at 17:14
1
\$\begingroup\$

Gray code... Gray code?

What's a gray code? Quoting from https://en.wikipedia.org/wiki/Gray_code, a gray code is an ordering of the binary numeral system such that two successive values differ in only one bit.

Your task: to print the numbers 1-127 in gray code with no input.

Your restrictions: Each successive byte of the source code after the first can only change one bit from the previous byte.

Notes:

  • Example valid code (in utf-8): q1!#c. Here, q (01110001) and 1 (00110001) are different in only one bit, and so on
  • Example invalid codes (in utf-8): Q1!, "!"
  • A character can be stored as two bytes, but the bytes must differ by only one bit
  • If your interpreter ignores a character (like Whitespace ignores almost all characters) it cannot be used
New contributor
Hyperbole is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
8
  • \$\begingroup\$ Is printing 1 3 2 6 7 5 4 and onwards ok? \$\endgroup\$ – PkmnQ Feb 28 at 4:36
  • \$\begingroup\$ What does "some form of gray code" mean exactly? / Clarify that the restriction part applies to the source code of the program. \$\endgroup\$ – user202729 Feb 28 at 6:49
  • \$\begingroup\$ I'll change it to binary gray code to avoid confusion. \$\endgroup\$ – Hyperbole Feb 28 at 15:55
  • \$\begingroup\$ You should describe what the gray code is to avoid ambiguities. \$\endgroup\$ – FryAmTheEggman Feb 28 at 21:49
  • \$\begingroup\$ Do you think this challenge is too hard? \$\endgroup\$ – Hyperbole yesterday
  • \$\begingroup\$ Is it okay if the output is printed in decimal instead of binary? \$\endgroup\$ – user202729 21 hours ago
  • \$\begingroup\$ Perhaps add "addition of leading zeroes doesn't count as a change" and some examples to illustrate/example valid output (just for challenge accessibility, this is implied from the definition (and the Wikipedia page)) \$\endgroup\$ – user202729 21 hours ago
  • \$\begingroup\$ Would be hard for practical languages, but for everything-are-valid languages it should not be a problem. Good challenge idea. \$\endgroup\$ – user202729 21 hours ago
1
\$\begingroup\$

Posted at Convert Gemtext to HTML but moved here to discuss

Gemtext is a very simple markup format used by the alternative web protocol Gemini. Write a Gemtext to HTML converter.

From the Wiki:

A line of text is a paragraph, to be wrapped by the client. It is is independent from the lines coming before or after it.

A list item starts with an asterisk and a space. Again, the rest of the line is the line item, to be wrapped by the client.

A heading starts with one, two, or three number signs and a space. The rest of the line is the heading.

A link is never an inline link like it is for HTML: it’s simply a line starting with an equal-sign and a greater-than sign: “⇒”, a space, an URI, and some text. It could be formatted like a list item, or like a paragraph. Relative URIs are explicitly allowed.

Example:

# This is a heading 
This is the first paragraph.
* a list item
* another list item 
This is the second paragraph.
=> http://example.org/ Absolute URI
=> //example.org/ No scheme URI
=> /robots.txt Just a path URI
=> GemText a page link

This should produce this HTML tree (just the equivalent tree, not the exact formatting):

<h1>This is a heading</h1>
<p>This is the first paragraph.</p>
<ul>
<li>a list item</li>
<li>another list item</li>
</ul>
<p>This is the second paragraph.</p>
<a href="http://example.org/">Absolute URI</a>
<a href="//example.org/">No scheme URI</a>
<a href="/robots.txt">Just a path URI</a>
<a href="GemText">a page link</a>

HTML in the text must be escaped, e.g paragraph <p> is cool becomes <p>paragraph &ltp&gt is cool</p>.

This is so the shortest code in bytes wins

New contributor
R Harrington is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
3
  • \$\begingroup\$ Can you clarify "whitespace ... doesn't matter"? \$\endgroup\$ – Wezl 2 days ago
  • \$\begingroup\$ @Wezl edited question \$\endgroup\$ – R Harrington 2 days ago
  • \$\begingroup\$ What parts of HTML do we need to handle? Can we convert every character (even unreserved ones like A) to its entity number? Is the input guaranteed to be ASCII only or do we need to handle other characters? I don't know Gemtext well enough to ask about it, but are there escape characters or something that would allow mapping, say, to HTML: <p># A paragraph</p>? \$\endgroup\$ – FryAmTheEggman 2 days ago
1
\$\begingroup\$

Integer partitions into fixed parts with coprime constraint, and exclusion set

Background

Let \$a\$ \$\in \mathbb{N}\$, \$b\$ \$\in \mathbb{N}\$, \$c\$ \$\in \mathbb{N}\$ and \$S\$ be some subset of \$\{i:1\leq i\leq a\}\$.

Consider \$X(a ,b, c, S)\$: The number of integer partitions of \$a\$ into \$b\$ many parts, where each of the parts are co-prime to \$c\$ and no part is contained within \$S\$.

Formally, for \$b=2\$

$$X(a ,2, c, S) = |\{(x, y): x + y = a,\ gcd(c, x) = gcd(c, y) = 1, x \notin S, y \notin S,\ x \leq\ y\}|$$

Challenge

Codegolf, standard rules apply. Write code to calculate the function \$X(a ,b, c, S)\$ above.

Inputs:

  • \$a\$, an integer. Your function does not need to be correct for \$a \le 2\$.

  • \$b\$, an integer. Your function does not need to be correct for \$b \le 1\$.

  • \$c\$, an integer.

  • \$S\$, can be any set of integers between \$1\$ and \$a\$ (inclusive). The elements of \$S\$ are unique.

BONUS

Brownie points for anyone who can do either of the following:

  1. Disprove the following recursive relationship.
  2. Extend the following recursive relationship (for higher values of \$b\$), and/or write code utilising it.

Recursive formula for \$b = 3\$ (Might be incorrect):

$$X(a ,3, c, S) = \sum_{i=1}^{i=\lfloor\frac{a}{2}\rfloor} {X(a - i, 2, c, T_i)} $$

With

$$T_0 = S$$

and,

$$T_i = T_{i-1}\cup\{i - 1, a + 1 - i\},\ for\ i \geq 1$$

Questions for sandbox

  1. How many test cases should I include?
  2. is my title to verbose
  3. Did I tag this correctly? Haven't included any tags that specifically pertain to GCD/coprimality problems.
  4. do I need to provide a time limit for challenge of there is no bounty?

Feedback appreciated :)

New contributor
DanielOnMSE is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
7
  • \$\begingroup\$ you can add tags here via [tag:<tagname>]. \$\endgroup\$ – Razetime Feb 27 at 8:37
  • \$\begingroup\$ @Razetime , sorry total noob here. In the comment section? or do I edit the post and add the [tag:<tagname>] at the end? \$\endgroup\$ – DanielOnMSE Feb 27 at 9:30
  • 1
    \$\begingroup\$ in the post. Add it near the title, like in the other posts. \$\endgroup\$ – Razetime Feb 27 at 9:55
  • \$\begingroup\$ About test cases. It looks like that this challenge doesn't have too many test cases, don't need a lot. \$\endgroup\$ – user202729 Feb 27 at 12:15
  • \$\begingroup\$ I think the info about integer types makes the question harder to read (they all have default rules), so I removed it. \$\endgroup\$ – user202729 Feb 27 at 12:15
  • \$\begingroup\$ The tag doesn't matter too much, as long as there's a code golf tag. // Usually people don't like time limits, but if you insist there's either "solutions must have time complexity that does not exceed (something)" or "you must be able to run the program to completion with the following test cases" or "the program must finish on my machine in X seconds" (requires you running the programs) [please review other sandbox posts] \$\endgroup\$ – user202729 Feb 27 at 12:17
  • \$\begingroup\$ @user202729 Thanks for the edits. Yes I suppose I'm not interested in any time constraints. Rather just interested to see the solutions people can come up with. Yes I will need to make some test cases, will add them when I get a chance. \$\endgroup\$ – DanielOnMSE Feb 27 at 13:01
0
\$\begingroup\$

Find Maximum number of 4+ letter words from Scabble Tiles

The challenge is to find the most words with 4 or more letters you can make with one set of scrabble tiles.

The tile distribution is as follows:

2 Blank Tiles
A 9  N 6    +====+===========+
B 2  O 8    | 01 | K J X Q Z |
C 2  P 2    | 02 | B C M P F |
D 4  Q 1    | 02 | H V W Y * |
E 12 R 6    | 03 | G         |
F 2  S 4    | 04 | L S U D   |
G 3  T 6    | 06 | N R T     |
H 2  U 4    | 08 | O         |
I 9  V 2    | 09 | A I       |
J 1  W 2    | 12 | E         |
K 1  X 1    +====+===========+
L 4  Y 2
M 2  Z 1

Valid words are any words that are 4+ that are available in this file, the official scrabble dictionary.

Tiles cannot be used twice. This means you can only have 1 word with a K, J, X, Q, and/or Z unless you use a blank tile to represent one of these letters.

I'm not sure how I'd do scoring on this. I want shorter code to score better, but I don't want a short piece of code that finds a lot less words to score better than a longer piece that finds many more words.

\$\endgroup\$
11
  • \$\begingroup\$ Meh. I don't like dependency on external files; are we allowed to load it, or even embed it into the source code? \$\endgroup\$ – John Dvorak Dec 17 '13 at 20:00
  • \$\begingroup\$ as for finding more vs. shorter code, you could demand all words be found \$\endgroup\$ – John Dvorak Dec 17 '13 at 20:19
  • \$\begingroup\$ @JanDvorak Any way to use it. It's a text version of the official scrabble dictionary, it seemed to be the most fitting word list for the task. "All words being found" might be hard, considering there are probably many combinations of words that would deplete all the tiles. It's a maximum of 25 words, (25 words, 4 letters each, 100 tiles), but I don't know if it's possible to use all tiles with just 4 letter words. After so many words, you might not have enough tiles to make an actual word, which means you'd either have to go back or accept that you're not using all the tiles. \$\endgroup\$ – Rob Dec 17 '13 at 20:23
  • 5
    \$\begingroup\$ As currently described, this is a no-input task, which means that the answer can be precomputed and then the program only needs to decompress it. Consider rewriting it to take input (either of the word list or of the tiles available). \$\endgroup\$ – Peter Taylor Dec 18 '13 at 8:01
  • \$\begingroup\$ I suggest taking a list of tiles as input, loading the list of words from a predefined file and requiring all combinations / best combination to be found. Of course, if the input is the full list of tiles, the computation is going to take ages. I might allow preprocessing the word list outside the program itself (up to a certain point; a linearithmic growth?) \$\endgroup\$ – John Dvorak Dec 18 '13 at 8:32
  • 1
    \$\begingroup\$ I suggest modifying this so that input is a list of tiles, limited to a full rack or less (therefore 4-7 tiles, since our minimum word length is 4). Input should be assumed to be valid based on the standard set of tiles (e.g.: it wont' have something like 3 J's or 4 G's). This would have some practical use for a player in a scrabble game to figure out their next move (though it does not take into account tiles available to them which are already on the board). \$\endgroup\$ – Iszi Dec 18 '13 at 21:14
  • \$\begingroup\$ Alternative mode: Input is a list of tiles, maximum 96 (so that at least 4 are remaining in the set). Output only includes words (minimum 4 letters) which can be created without those tiles. This would be interesting as it provides words that may yet be created (though, again, not taking into account usable tiles on the board) at a given point in the game. \$\endgroup\$ – Iszi Dec 18 '13 at 21:15
  • \$\begingroup\$ Output needs to be decided as either a list of all possible words, or only the highest-scoring word(s). Another enhancement may be to require that the list be sorted descending in order of score (if output is all words), then ascending alphabetically. There's no reason to take each program's output into account for scoring. Since everyone is expected to use the same dictionary, all programs' outputs should be identical (except perhaps in sorting, if that's left out of the spec). So, this should be Code Golf. \$\endgroup\$ – Iszi Dec 18 '13 at 21:15
  • \$\begingroup\$ It's also worth noting that, as currently written, the task could just be to filter the given dictionary down to words which have 4 or more letters. By its very nature, the Scrabble dictionary should already exclude any words that cannot be made with a Scrabble set. \$\endgroup\$ – Iszi Dec 18 '13 at 21:18
  • \$\begingroup\$ @Iszi it's not "what are all the words you can make", it's "what are all the words you can make, where every letter used depletes a tile". There's a max of 25 words if you can use all 100 tiles. \$\endgroup\$ – Rob Dec 19 '13 at 16:40
  • \$\begingroup\$ I think I misunderstood the problem, then. I thought it was "all the words possible using a set of tiles" not "all the words possible, using only one set of tiles". Still, my point about code golf remains. There is an absolute maximum to the number of words (each with 4 or more letters) you can make with a single Scrabble set, and a finite number of permutations which can be used to hit that maximum. Every program written with this goal should end up with the same (or nominally similar) output. \$\endgroup\$ – Iszi Dec 19 '13 at 16:56
0
\$\begingroup\$

Test for Irreducible Complexity (Check for Redundant Characters)

I may need some additional help coming up with the full spec for this competition. As of right now, this is just a concept.

Many interesting questions, such as the "42" question in this sandbox, involve finding the longest program which is not reducible. This means that no set of characters can be removed and still allow the program to function as desired.

The basic idea is that your program will test a Base Program to make sure that it contains no redundant characters. The input will consist of:

  • Base Program (in the same language as your answer)
  • Expected Output

Your program will simply evaluate all possible subsequences of the Base Program and verify that none of them give the Expected Output.

This challenge actually has a utility value to several other challenges. For example, it verifies the results of a "longest non-reducible"-type challenge. In addition, it could make sure that a golfed solution cannot be golfed further.

I assume that the winning criteria will be fastest program, as cycling through all the possibilities takes a long time.

Problems

A sequence of length N has 2^N subsequences. Even if each evaluation is done very quickly, it might be unfeasible to test any program with more than 20 or so characters in a reasonable amount of time.

\$\endgroup\$
5
  • \$\begingroup\$ Problem: some subsequences of legitimate answers may be pretty dangerous to the environment. You don't want to eval just everything. \$\endgroup\$ – John Dvorak Dec 23 '13 at 16:59
  • \$\begingroup\$ @JanDvorak Yes that actually is a serious problem. To what extent is it possible to fix that? \$\endgroup\$ – PhiNotPi Dec 23 '13 at 17:04
  • 1
    \$\begingroup\$ Forbidding any program with dangerous subsequences? :-) \$\endgroup\$ – John Dvorak Dec 23 '13 at 17:05
  • 1
    \$\begingroup\$ A more reasonable (but very difficult) solution would be the requirement to implement a sandbox. \$\endgroup\$ – John Dvorak Dec 23 '13 at 17:07
  • \$\begingroup\$ Even without dangerous behavior, the halting problem will be an issue: it's hard to tell whether a shortened program will terminate at all, especially for every conceivable input. \$\endgroup\$ – MvG Jan 7 '14 at 23:49
0
\$\begingroup\$

Popularity Contest: Implementation of a Hash Table

Create a class in some OOP language for a hash table that supports getting, setting, and removing values. You can't use the built in hash table/dictionary/map implementation. Highest votes in one week wins.

A key is any valid string. A value is any valid string, number, or boolean.

Example functionality:

hash.set("key","value");
hash.get("key"); // returns "value"
hash.set("key", 1234);
hash.get("key"); // returns 1234
hash.set("key2",hash.get("key"));
hash.get("key2"); // returns 1234
hash.delete("key");
hash.get("key"); // returns null/undefined/none/etc. or throws an error
hash.get("key2"); // still returns 1234

Definition of a hash table (from Wikipedia):

In computing, a hash table (also hash map) is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.

The hash table cannot be simply an array that is searched in linear time. It must be an actual hash table that uses a hash function to map the keys to the value.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Popularity contest and shortest don't mix. That aside, the spec is too vague. What is a "value"? What assumptions can be made about hashcodes? If the language makes all types nullable, should null be permitted as a key? What should the type be in languages which have co- and contravariance? And for that matter, what qualifies as a "hash table", bearing in mind that people will try to exploit any loophole? \$\endgroup\$ – Peter Taylor Jan 2 '14 at 23:16
  • \$\begingroup\$ @PeterTaylor Thank you for the feedback! Please see my edits, and let me know what you think. Could you meant about co/contravaraince? I looked at the wikipedia article about it but I'm not really sure how that has anything to do with this question. \$\endgroup\$ – hkk Jan 2 '14 at 23:37
  • \$\begingroup\$ I think it's still vulnerable to the loophole of "I have a hashtable with one bucket" (i.e. it's really a list of (key, value) pairs which I traverse in linear time). The thing about variance is to do with static typing of the elements of the map. E.g. in Java Map<String, Integer>'s get method has signature public Integer get(Object); in C#, a Dictionary<string, int>'s Get method has signature public int Get(string). The edited version makes it clear enough that the hashtable isn't expected to be genericised. \$\endgroup\$ – Peter Taylor Jan 3 '14 at 0:08
0
\$\begingroup\$

Wordlist detector

You are to write a program which, given a list of words, constructs a regular expression to match all these words but nothing else. Both your program and the constructed regular expressions are to be as short as possible.

Input and Output

Input comes on standard input and consists of one line giving n, the total number of words, followed by n lines with one word each. The number of words will be less than 1000, the length of each word less than 30. Words will consist only of lower case ASCII letters, i.e. a-z. You may choose to ignore the first line and use EOF instead to end the list.

Output shall be written to standard output. It consists of a single line, giving a POSIX extended regular expression to match these words and no others. Since input for this regex is not restricted to letters only, elements like . or [^…] won't make too much sense, which limits the language in a natural way. You may choose whether you want to terminate the line with a newline or not. Programs may choose to print multiple lines of output, in which case only the last one will be used for scoring. So you might print intermediate results and continue searching for improvements.

Test cases

Each submission may be accompanied by one regular expression. When scoring the submissions, I'll use this regular expression to reconstruct a word list from it. The code to do this reconstruction can be found at the end of this post. The reconstructed word list must fit the input specification above in terms of word count and length. It would be nice if your own program would be able to regenerate that regular expression from the word list, but that is not a strict requirement. But please don't paste bogus programs just to submit a challenging regular expression, though.

These test cases will be collected and fed to all programs for scoring.

Scoring

The final score of each program will be the program size plus the size of all its generated regular expressions for the inputs collected from submitted answers, including the example from this question. So short code which produces too long results might get beaten by longer code which generates shorter expressions.

Does this still qualify as ?

Submissions which generate an incorrect regular expression for one of the test cases will be disqualified, as will those which don't terminate in the allotted time. You can use the input reconstruction program below to check whether a produced regular expression does encode the correct word list.

Requirements

All submissions are welcome, but in order to include your submission in the tournament, it must be executable with reasonable effort on my Linux machine. It shouldn't depend on any exotic libraries, or any specialized ones which take too much work away from your own program. It must operate in reasonable time, say no more than five minutes per input. Your output must be reproducible, so if you use randomization at some point, please seed the randomizer, and please don't terminate an improove loop by a timer measuring execution time or some such.

Tournament times

I'll run the first major tournament two weeks after posting this question. I'll include a table of the results in this question. I'll try to run tournaments repeatedly as late submissions arrive, but I'll not promise any regular schedule.

Example

An very simple example application would be in Python 3 (53 chars):

print('|'.join(input() for i in range(int(input()))))

And here is a test case which could be posted along with the program, although this program obviously doesn't generate exactly this concise output:

bann?ana|ap(fel|ple)|s[ou]n|[hs](a|ou)nd

The expansion of that expression could be turned into the following example input, which need not be posted as part of an answer since it can be deduced from the regular expression:

10
banana
bannana
apfel
apple
son
sun
hand
hound
sand
sound

Regex expander program

And here is a program to turn regular expressions into word lists, again written in Python 3.

#!/bin/env python3
concat = set(('',))
altin = set(('',))
altout = set()
prev = None
stack = []
regex = iter(input())
for ch in regex:
    if ch == '(':
        stack.append((concat, altin, altout))
        altin = concat
        altout = set()
        prev = None
    elif ch == ')':
        concat.update(altout)
        prev, altin, altout = stack.pop()
    elif ch == '|':
        altout.update(concat)
        concat = altin
    elif ch == '[':
        ch = regex.__next__()
        cls = []
        while ch != ']':
            if ch == '-':
                crange = range(ord(cls[-1]), ord(regex.__next__()) + 1)
                cls.extend(map(chr, crange))
            else:
                cls.append(ch)
            ch = regex.__next__()
        prev = concat
        concat = set(w + c for w in prev for c in cls)
    elif ch == '?':
        concat.update(prev)
        prev = None
    elif ch >= 'a' and ch <= 'z':
        prev = concat
        concat = set(w + ch for w in prev)
    else:
        raise Exception("Illegal input")
if stack:
    raise Exception("Unclosed group")
concat.update(altout)
words = sorted(concat)
print(len(words))
print('\n'.join(words))

This is restricted to the part of regular expression syntax which I expect for this answer. If you have good reason to use something I did not consider, feel free to do so although I will likely have to update this code to cope with it. If you find a bug, please let me know.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ This is just Meta regex golf under the constraint that the two lists between them cover all possible words. Given that some people are tackling that existing question on that basis, this would qualify for closing as a duplicate. \$\endgroup\$ – Peter Taylor Jan 8 '14 at 8:45
0
\$\begingroup\$

Code-Golf: Write a number as an expression that's as short as possible

The goal of this code-golf is to create a program that takes a number as input (using STDIN, command line arguments, or prompting for input), and outputs that number, but written as an expression that's as short as possible. So, 10000 should become 10^4. If there is no way to write an expression that's shorter than the number, then output just the number.

Other rules

  1. No network access.
  2. You're not allowed to execute an external program.
  3. Only use the operators +, -, *, / and ^ (that's raising power, not XOR).
  4. Order of operations must be taken in account. Use parentheses if necessary.
  5. This is a code golf, so the code with the smallest amount of characters wins.
  6. The input will always be smaller than 2^32.

Test cases

500000000   -->    5*10^8     or    10^9/2
999999      -->    10^6-1
10          -->    10
4294967295  -->    2^32-1
16384       -->    2^14
\$\endgroup\$
1
0
\$\begingroup\$

Rhymalator

(at the point, it's just something that came to me before i wake up, so it may need some adjusting, and i'd like some feedback as to if this could be fun)


The code challenge is to write a program that takes as input a calculation in Reverse Polish Notation and outputs the result. It must at least implement + - * /. It So far so easy, but to make it fun and "artistic", the following restriction applies:

  • The source code must rhyme when read. Example in PHP

    $iterator = str_split($a);
    foreach ($iterator as $key=>$value){
        if ($key > 3){
            ++$virtue;
        }
    }
    

    (the rhyme is on value-virtue)

  • Lines whitout readable characters count as whitespace (the two lines with } in the example)

\$\endgroup\$
2
  • \$\begingroup\$ How does that example rhyme...? \$\endgroup\$ – Doorknob Jan 25 '14 at 12:54
  • \$\begingroup\$ @DoorknobofSnow well, i'm not really a poet, that's why i propose it as a challenge for others :p. if you have a better example i'll replace it \$\endgroup\$ – Einacio Jan 27 '14 at 15:58
0
\$\begingroup\$

Implement Kalah

The game of Kalah is a two-player board game in the Mancala family. Your implementation must:

  • Identify the active player ("Player 1" or "Player 2")
  • Display board state (in format specified below)
  • Accept input to allow that player to move (using index system below)
  • Announce a winner ("Player N wins")

Overview

Each player has a line of six spaces, called houses, and one additional space called a store. Each space holds seeds, which move from house to house in a counter-clockwise direction. The objective is to fill your store with seeds.

You must represent the board in the following two-row format with stores offset, where HH is a house and SS is a store:

SS HH HH HH HH HH HH
   HH HH HH HH HH HH SS

The top row represents the number of seeds in player #1's spaces, and the bottom row represents the seeds in player #2's spaces. The S in each row is the respective player's store (player #1's is top-left, #2's is bottom right). Single-digit values should include a leading space.

In this challenge, user-input will identify each house numerically. Use a left-to-right, indexed-from-one scheme for both sides:

S 1 2 3 4 5 6
  1 2 3 4 5 6 S

Note that the players' stores are not numbered, because seeds placed in the store never move out.

Rules

Wikipedia has a good summary of the game and its rules:

  1. At the beginning of the game, three seeds are placed in each house.

  2. Each player controls the six houses and their seeds on his/her side of the board. His/her score is the number of seeds in the store to his/her right. [Clarification: from our perspective, player 1's store is to the left, player 2's store is to the right.]

  3. Players take turns sowing their seeds. On a turn, the player removes all seeds from one of the houses under his/her control. Moving counter-clockwise, the player drops one seed in each house in turn, including the player's own store but not his/her opponent's.

  4. If the last sown seed lands in the player's store, the player gets an additional move. There is no limit on the number of moves a player can make in his/her turn.

  5. If the last sown seed lands in an empty house owned by the player, and the opposite house contains seeds, both the last seed and the opposite seeds are captured and placed into the player's store. [Clarification: moves that end on an opponent's empty house end normally without a capture.]

  6. When one player no longer has any seeds in any of his/her houses, the game ends. The other player moves all remaining seeds to his/her store, and the player with the most seeds in his/her store wins.

Example

(Parenthetical text should not appear in actual output.)

Player 1
 0  3  3  3  3  3  3
    3  3  3  3  3  3  0
> 2                      (prompt arrow and line break
                          are purely optional)
 Player 2
 1  1  0  3  3  3  3
    4  3  3  3  3  3  0
> 4

Player 2  (P2 gets a bonus turn from rule #4)
 1  0  3  3  3  3  3
    4  3  3  0  4  4  1
> 5

Player 1  
 1  0  3  3  3  4  4
    4  3  3  0  0  5  2
> 4

Player 1  (P1 captures P2's seeds in space 1)
 6  0  4  4  0  4  4
    0  3  3  0  0  5  2
...

Player 2
12  0  0 10  0  1  0
    0  0  0  0  0  1 13
 > 6

Player 1 wins            (because the non-finishing players gets
                          all remaining seeds on their side, it's 23-14)

Meta question: Would this be improved by removing some of the rules?

\$\endgroup\$
1
  • \$\begingroup\$ Do the players run the game once and then take it in turns to take moves, with the process ending only when the game ends? Or do they run the program once per move? \$\endgroup\$ – Peter Taylor Jan 30 '14 at 10:06
1
52 53
54
55 56
105

You must log in to answer this question.

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