540
\$\begingroup\$

This "sandbox" is a place where Code Golf users can get feedback on prospective challenges they wish to post to main. This is useful because writing a clear and fully specified challenge on your first try can be difficult, and there is a much better chance of your challenge being well received if you post it in the sandbox first.

Sandbox FAQ

Posting

To post to the sandbox, scroll to the bottom of this page 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, though you can optionally add a title at the top. 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, and replace the post here with a link to the challenge and delete the sandbox post.

Discussion

The purpose of the sandbox is to give and receive feedback on posts. If you want to, feel free to give feedback to any posts you see here. Important things to comment about can include:

  • Parts of the challenge you found unclear
  • Comments addressing specific points mentioned in the proposal
  • Problems that could make the challenge uninteresting or unfit for the site

You don't need any qualifications to review sandbox posts. The target audience of most of these challenges is code golfers like you, so anything you find unclear will probably be unclear to others.

If you think one of your posts needs more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended!

It is recommended to leave your posts in the sandbox for at least several days, and until it receives upvotes and any feedback has been addressed.

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

To add an inline tag to a proposal use shortcut link syntax with a prefix: [tag:king-of-the-hill]. To search for posts with a certain tag, include the name in quotes: "king-of-the-hill".

Get the Sandbox Viewer to view the sandbox more easily!

\$\endgroup\$
0

3554 Answers 3554

1
106 107
108
109 110
119
0
\$\begingroup\$

Implement every dirname (1p)

Implement the dirname utility from scratch. It can be either a program or a fucntion. Assume input string satisfies these constraints:

The dirname utility, however, has two kinds of implementations. This is because some POSIX systems treat //foo/bar differently from /foo/bar. So in this challenge, you must output every possible outputs, in any order. They can be duplicated.

Here is the algorithm to implement the utility, provided string to be input:

  1. If string is //, skip steps 2 to 5.
  2. If string consists entirely of <slash> characters, string shall be set to a single <slash> character. In this case, skip steps 3 to 8.
  3. If there are any trailing <slash> characters in string, they shall be removed.
  4. If there are no <slash> characters remaining in string, string shall be set to a single <period> character. In this case, skip steps 5 to 8.
  5. If there are any trailing non- <slash> characters in string, they shall be removed.
  6. If the remaining string is //, it is implementation-defined whether steps 7 and 8 are skipped or processed.
  7. If there are any trailing <slash> characters in string, they shall be removed.
  8. If the remaining string is empty, string shall be set to a single <slash> character.

The final string is the output.

Standard I/O rules apply. Standard Loopholes apply. No builtins or libraries that does exactly same functionality. Shortest code wins.

Examples

Some examples are taken from POSIX explaination of basename().

* means an empty string. 1st column is input and 2nd and 3rd are possible outputs.

usr               .
usr/              .
*                 .
..                .
../               .
/                 /
//                /          //
///               /
/usr/             /
//usr/            /          //
///usr/           /
/usr/lib          /usr
//usr//lib//      //usr
/home//dwc//test  /home//dwc

Meta

  • ?
\$\endgroup\$
0
\$\begingroup\$

Write a Stack Exchange compliant brainfuck explainer

\$\endgroup\$
6
  • \$\begingroup\$ @Adám But i prefer using 4 spaces \$\endgroup\$
    – Fmbalbuena
    Nov 14 at 22:40
  • \$\begingroup\$ I'm not sure what you mean by stating your preferences. Either it is allowed, or not. \$\endgroup\$
    – Adám
    Nov 14 at 22:41
  • 1
    \$\begingroup\$ ~ is ascii 126 \$\endgroup\$
    – tsh
    Nov 15 at 5:10
  • \$\begingroup\$ I would suggest avoid characters [] in description so they are ensured to be comment. \$\endgroup\$
    – tsh
    Nov 15 at 5:12
  • \$\begingroup\$ @tsh Oh, that's interesting, then the code remains runnable, even when fully explained. \$\endgroup\$
    – Adám
    Nov 15 at 7:32
  • 2
    \$\begingroup\$ I still strongly recommend giving the explanation strings as an argument, or even giving both explanation strings and symbols as arguments; that'd make the solution into a general code explainer. \$\endgroup\$
    – Adám
    Nov 15 at 8:10
0
\$\begingroup\$

Escape the maze

Introduction

Here is a random maze:

#####
#M.#E
#.##.
#.##.
#....
#####

Here M is the starting point and E is the endpoint. # is a maze wall and . is a path.

Now we can get out of this maze by following the sequence sssdddwww. (s is dow, d is right, w is up, a is left.)

Your challenge

Given a maze, output the shortest possible route to the endpoint. (E) You may assume the maze is solvable.

Test cases

#####
#M.#E
#.##.
#.##.
#....
#####

outputs

#####
#..#E
#M##.
#.##.
#....
#####

#####
#..#E
#.##.
#M##.
#....
#####

#####
#..#E
#.##.
#.##.
#M...
#####

#####
#..#E
#.##.
#.##.
#.M..
#####

#####
#..#E
#.##.
#.##.
#..M.
#####

#####
#..#E
#.##.
#.##.
#...M
#####

#####
#..#E
#.##.
#.##M
#....
#####

#####
#..#E
#.##M
#.##.
#....
#####

#####
#..#M
#.##.
#.##.
#....
#####

(Notice the newlines between the steps.)

Scoring

This is , so shortest code wins.


Todo

\$\endgroup\$
3
  • \$\begingroup\$ Welcome to Meta code golf. add tag maze :p \$\endgroup\$
    – Fmbalbuena
    Nov 18 at 20:21
  • \$\begingroup\$ @Fmbalbuena Done. \$\endgroup\$
    – Alan Bagel
    Nov 18 at 20:22
  • \$\begingroup\$ Dupe of Find the shortest path from point A to point B. That challenge has itself been closed as a dupe of Textual maze solver, a decision I don't necessarily agree with, but better to reopen the existing challenge than create a new one. \$\endgroup\$
    – Dingus
    Nov 18 at 22:31
0
\$\begingroup\$

Solve the halting problem for Minyrinth

Introduction

Minyrinth is the stripped-down version of Labyrinth. It has the same routing semantics as Labyrinth but only four non-wall commands, and only one register (that can hold unbounded signed integers) instead of two stacks. The register is initialized to zero.

Commands

  • " is a no-op path.
  • @ halts the program.
  • ) increments the register.
  • ( decrements the register.

You may assume that the input only contains the four command characters plus spaces (non-path) and newlines (used for 2D layout).

Execution semantics

Copied directly from the README, with some parts edited for Minyrinth:

The source code consists of single-character instructions and is interpreted as a 2D grid. The instruction pointer starts at the first non-whitespace character in the file (in reading order) going right.

Labyrinth is interpreted in a simple loop. At each step, the command under the instruction pointer is executed, then the new movement direction is determined, and then the instruction pointer moves one cell in that direction. The edges of the grid are not connected.

The instruction pointer will generally follow "corridors" of instructions. Junctions can be used for non-trivial control flow. How the new movement direction is determined depends on the number of available steps (i.e. number of direct neighbours with known commands):

  • 4 neighbours: The top of the main stack is examined. If it's 0, keep moving straight ahead. If it's negative, turn left. If it's positive, turn right.

  • 3 neighbours: Do the same as for four neighbours, but if you hit the wall, reverse the direction. Hence, a T-junction hit from the side differentiates between 0 and non-zero. A T-junction hit from the bottom on the other hand sends negative/positive to the left/right whereas a 0 value reverses the direction.

  • 2 neighbours: The first rule here is, don't turn around. So if you came from one of the two directions, continue in the other direction. If this is not the case, but one of the two directions is straight ahead, follow that one (this can happen, for instance, at the start of the program in a corner).

  • 1 neighbour: Go towards the only available direction. Usually, this means you have hit a dead end and turn around on the spot (executing the command you turn around on only once).

  • 0 neighbours: Remain where you are without changing your direction. This can occur at the very start of the program.

Challenge

Solve the halting problem for Minyrinth. Unlike Labyrinth which is Turing-complete, Minyrinth simulates a specific case of a pushdown automaton whose halting problem is decidable.

For output, you can choose to

  • output truthy/falsy using your language's convention (swapping is allowed), or
  • use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.

Standard rules apply. The shortest code in bytes wins.

Some hints can be found in CS Stack Exchange: Decidability of halting problem for DPDAs with \$\epsilon\$-transitions?, Counter Machine (Halting Problem)

\$\endgroup\$
0
\$\begingroup\$

Plan my factory

"Factory games", such as Factorio, Mindustry, and Satisfactory are my favourite genre of video games, and the way I play them involve a lot of ratio calculations to make sure the factory is running as efficiently as possible.

Given a list of recipe specifications, and a desired production rate of an end product, output the necessary input rates of raw materials, where "raw material" is any ingredient that does not have a provided recipe.

For example:

Recipes:

[
    {
        name: "Iron Plate",
        time: 3.2,
        quantity: 1,
        input: [{
            name: "Iron Ore",
            quantity: 1
        }]
    },
    {
        name: "Copper Plate",
        time: 3.2,
        quantity: 1,
        input: [{
            name: "Copper Ore",
            quantity: 1
        }]
    },
    {
        name: "Iron Gear",
        time: 0.5,
        quantity: 1,
        input: [{
            name: "Iron Plate",
            quantity: 2
        }]
    },
    {
        name: "Automation Science Pack",
        time: 5,
        quantity: 1,
        input: [
            {
                name: "Iron Gear",
                quantity: 1
            },
            {
                name: "Copper Plate",
                quantity: 1
            }
        ]
    },
]

Desired production rate:

{
    name: "Automation Science Pack",
    rate: 60
}

Expected output:

[
    {
        name: "Iron Ore",
        rate: 120
    },
    {
        name: "Copper Ore",
        rate: 60
    }
]

Both input and output may be any standard IO format that represents item names as strings and quantities/rates as integers.

Testcases

TBA

Sandbox

Is this a chameleon challenge?

\$\endgroup\$
0
\$\begingroup\$

Golf a Friedman's tree sequence for 3 colors

Friedman proved that given a sequence of 3-labelled rooted trees with following conditions, TREE sequence, must be finite and defined maximum length of such sequence as TREE(3).

  • \$i\$th tree, \$T_i\$, should have no more than \$i\$ vertices. (index is 1-based)
  • No tree \$T_i\$ can be homeomorphically embeddable into any of the following tree \$T_j\$ if \$i < j\$.
    • A tree \$A\$ is said to be homeomorphically embeddable to tree \$B\$ if and only if there exists a function \$f\$ from vertices of \$A\$ to vertices of \$B\$ which satisfies following conditions:
      1. \$f\$ preserves label. That is, \$v\$ and \$f(v)\$ has same label.
      2. If \$u\$ is ancestor of \$v\$, then \$f(u)\$ is ancestor of \$f(v)\$.
      3. If \$u_1\$ and \$u_2\$ are children of \$v\$, then the path from \$f(u_1)\$ to \$f(u_2)\$ contains \$f(v)\$.
    • There is a guide with examples in this youtube video.

It is well known that TREE(3) is far larger than \$2^{64}\$.

Challenge

Find a TREE sequence with length of \$2^{64}\$ or longer. Your task is to implement a program or a function or a subroutine that takes one 64-bit integer \$i\$ and outputs a tree \$T_i\$ of your TREE sequence.

Rules

  • Standard loopholes apply.
  • Standard I/O rules apply.
  • Shortest code wins.
  • Output can be any format as long as it describes a 3-labelled tree.
  • Describe how your outputs form valid TREE sequence.

Example of valid sequence, length 16

1 - {}              # 1 vertex tree with label {}. Note that any tree after this cannot contain node with label {}.
2 - [[]]            # 2 vertex tree with label both []. Any tree after this cannot contain two ancestor-child node with both label [].
3 - [(())]
4 - ([][])          # Root with label (), 2 children with label [].
5 - ([]((())))
6 - ([](()))
7 - [()]
8 - []
9 - ((((((((()))))))))
10 - (((((((())))))))
11 - ((((((()))))))
12 - (((((())))))
13 - ((((()))))
14 - (((())))
15 - ((()))
16 - (())

Meta

This is my first challenge. Suggestions?

I'm sure that normal computers will have serious difficulty to execute code for this problem, but also I don't want answers to just brute force TREE sequence and print ith term. How can I balance the question?

\$\endgroup\$
1
  • \$\begingroup\$ You definitely need some examples of the rules. Also, "homeomorphically embeddable" is not a term the average codegolfer is familiar with. \$\endgroup\$
    – NieDzejkob
    Nov 16 at 22:21
0
\$\begingroup\$

OEIS A049190

your task is to print all numbers of this sequence.

is separated by newline, is separated by space or separated by comma.

the first few numbers are:

1, 3, 5, 59, 245, 2491, 235253, 127756731, 330567489269, 258479716298484155, 36823182192123209878050549, 25576412117054296344209353299113896379, 10994511204169842163496446583221775727830456269734123253

How to get numbers of this sequence:

this is look and say but in binary and convert to decimal

Meta

  • How to clarify this?
\$\endgroup\$
0
\$\begingroup\$

Convert codepoint to UTF-1

\$\endgroup\$
0
\$\begingroup\$

Infinite ordinals from a well-ordering

\$\endgroup\$
3
  • \$\begingroup\$ Are the score categories essentially arbitrary? If so, it's not clear to me whether this is a good idea: it seems like these constraints provide the only motivation for choosing a well-ordering different from the 'default' (1, 2, 3, ...). Poor constraint choices could derail the challenge (i.e. make it too trivial or too hard). On the subject of scoring, looking at the bytes category for example, do you mean that if the default ordering is chosen, the code must be exactly 1 byte? \$\endgroup\$
    – Dingus
    Nov 12 at 0:48
  • \$\begingroup\$ Also, there's a typo under the second example: 2 < 101 is true. \$\endgroup\$
    – Dingus
    Nov 12 at 0:48
  • \$\begingroup\$ @Dingus I tried to clarify the scoring part. So if you choose \$\omega\cdot 2\$ you just try to golf an implementation of it. In this case someone has (hypothetically) managed to do it in one byte. As for the difficulty of the ordinals, the first two are one-liners in most languages, \$\omega^\omega\$ can be implemented with a while loop and \$\epsilon_0\$ with a tree. The score categories are not totally arbitrary. \$epsilon_0\$ is an important ordinal, and the smaller ones follow a natural pattern. Another option is to have just one ordinal, making this a normal golf and not a challenge. \$\endgroup\$
    – AnttiP
    Nov 12 at 7:41
0
\$\begingroup\$

Baloney Sandwich KOTH

Tags: [king-of-the-hill], [python]

Introduction

In this King Of The Hill Challenge, your bots will be playing Baloney Sandwich.

How Baloney Sandwich is played

  1. First, the entire deck is dealt equally to all players (EVERY BOT PLAYS; if there is more than 26 bots, it will be 2 decks mixed together).
  2. Then, the player with the ace of spades goes first.
  3. They play all of their aces
    • However! They could opt to "cheat" and instead play cards that are not aces, or mix and match aces with other cards.
  4. Every other player has their call_bs (bs = Baloney Sandwich) method called after this play, in turn until a player returns True; if a player returns True then the cards played are "revealed".
    • Every player has their bs_call_outcome method to "reveal" the cards
    • If no player returns True but the player was lying, the pb method is called (pb = Peanut Butter)
  5. Play continues with twos, threes, etc.; after kings, start over at aces

Creating A Player

Your player should be in this format:

class ExamplePlayer(AbstractBSPlayer):
    def __init__(self, hand: list[int]):
        super().__init__(hand)
        # Any necessary initialization goes here

    def call_bs(self, player_name: str, card_rank: int, number_of_cards: int) -> bool:
        """
        player_name is the name of the bot who just played
        The number of cards they played is number_of_cards
        The claimed rank is card_rank (1 is Ace; 11-13 are face cards)
        """
        # Magic decision maker
        return False # never calls "Baloney Sandwich"
        # return True would always call "Baloney Sandwich"
    
    def bs_call_outcome(self, player_name: str, caller_name: str, card_rank: int, cards: list[int], cheated: bool):
        """
        player_name is the name of the bot who just played
        caller_name is the name of the bot who called "Baloney Sandwich"
        The claimed rank is card_rank
        The cards they played is cards
        cheated is True if the player cheated
        """
        pass  # Couldn't care less
    
    def pb(self, player_name: str, card_rank: int, number_of_cards: int):
        """
        player_name is the name of the bot who just played
        The number of cards they played is number_of_cards
        The claimed rank is card_rank (1 is Ace; 11-13 are face cards)
        """
        pass # Couldn't care less

    def play_cards(self, card_rank: int) -> list[int]:
        """
        The rank you will claim to play is card_rank
        """
        # Magic decision maker
        return self.hand[0] # Always plays the first thing in hand

A player has access to the following instance variables:

  • self.store: A dictionary that is empty by default. The only instance variable allowed to be written to.
  • self.hand: A list of ints, each representing a card (1 is Ace, 11-13 are face cards)

Testing Your Player

The controller can be found at https://github.com/sethpeace/bs-koth. I apologize in advance that it is janky beyond comprehension.

Rules

Runtime Disqualifications

  • You must play at least one card every turn
  • You can't play cards you dont have in your hand
  • You can't take longer than one second to return from a function

Pre-runtime Disqualifications

  • No reading or writing to controller, runtime, or other submissions (bots can't read them; you can if you feel like it)
  • Only write to self.store instance variable
    • Other variables inside function scope are of course OK
  • Don't design a bot to defend or support specific bots
  • Bots can't use the same strategy as another bot
  • Standard loopholes apply
\$\endgroup\$
4
  • \$\begingroup\$ This seems too similar to codegolf.stackexchange.com/questions/48473/thats-bs-card-game \$\endgroup\$ Nov 27 at 16:45
  • \$\begingroup\$ @RedwolfPrograms you are correct; thank you \$\endgroup\$
    – Seth
    Nov 27 at 16:46
  • \$\begingroup\$ It's cool to see some more KotHs being written though! If you have any ideas for ones that you're not sure are dupes, feel free to bring them up in chat to save the effort of having to write out a whole spec first. \$\endgroup\$ Nov 27 at 16:48
  • \$\begingroup\$ @RedwolfPrograms alright thanks again :) \$\endgroup\$
    – Seth
    Nov 27 at 16:49
0
\$\begingroup\$

Implement xorshift128+

I don't have time to finish writing this draft at the moment.

Might also consider something like xoroshiro if it's more interesting to implement, but since xorshift128+ is so common it seems like a clearer choice.

(Possible idea: Given initial seed, determine number of iterations it'll take to get a certain random number with xorshift128+. It's not a CSPRNG, so there might be something more interesting than brute force.)

\$\endgroup\$
0
\$\begingroup\$

Silly Sentence Generator

Your challenge is to input a sentence and find all words enclosed within angle brackets. (< and >)

Here is an example:

The <adjective> <noun> biked across the bridge.

Next, replace all <noun>s with a random noun, all <verb>s with a random verb, all <adjectives>s with a random adjective, and all <adverb>s with a random adverb.

According to the above rule, The <adjective> <noun> biked across the bridge. could become The daring monkey biked across the bridge.

Your program will input a list of nouns, verbs, adjectives, and adverbs.

Make sure the words follow capitalization. So if the random noun in <noun> <verb>ed is monkey, it should then become Monkey. Another rule is that if a verb (like slide) ends with e, and the bit after the <verb> is ing or s, (e. g <verb>ing) do not keep the final e. (e. g slideing becomes sliding).

Examples

Note that these examples assume the nouns are monkey and ai, the verbs jumped and sliding, the adjective daring, and any list of adverbs (since the examples don't use them.)

The <noun> was <verb>ed by the <adjective> <noun>. => The monkey was jumped by the daring ai.

<verb>ing <noun>s play together. => Sliding monkeys play together.

Shortest code wins!

\$\endgroup\$
6
  • \$\begingroup\$ I would suggest replacing the "Test cases" section with "Examples" to show some possible outputs. \$\endgroup\$ Sep 17 at 17:44
  • \$\begingroup\$ @AaronMiller Added some test cases and additional rules. \$\endgroup\$
    – Alan Bagel
    Sep 17 at 17:53
  • \$\begingroup\$ You don't specify in these cases whether you want to be including the propagation of the word lists, etc. into the code golf challenge. If this is a requisite that the population of the lists be included in the bytes, this is going to make every 'golfed' solution pretty huge, even with small word lists you've provided. \$\endgroup\$ Sep 17 at 18:15
  • \$\begingroup\$ @ThomasWard Edited. \$\endgroup\$
    – Alan Bagel
    Sep 17 at 19:00
  • \$\begingroup\$ I think it would be better to instead take the lists of words as additional inputs \$\endgroup\$
    – Mayube
    Dec 1 at 18:33
  • \$\begingroup\$ It's still not clear if we're hardcoding the words or not \$\endgroup\$ Dec 1 at 18:34
0
\$\begingroup\$

Output sequence from a name

You are given a sequence of numbers(0-9) which you have to convert to its literal form.

Example

Input : 1246
Output : 26666

We interpret the input as one 2 four 6, thus giving the output 2 one time and 6 four times

Testcase

Input Output
1234567809 2444666668888888
2345 335555

P.S.

  1. Is this descriptive enough?
  2. Would it be fun to do?
New contributor
Saphereye is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
1
0
\$\begingroup\$

Chunk Sort a List

Your task is to input a list of integers and chunk sort it. You may assume the input list can always be chunked into groups of 1, 2, and 3.

Definition

Chunk sorting (a term I made up for the purpose of this challenge) is the action of first chunking a sequence into groups of 1, 2, and 3 in a cycle and then sorting each group.

Test cases

[1, 2, 3, 4, 5, 6, 7, 8, 9] => [[1], [2, 3], [4, 5, 6], [7], [8, 9]]
[5, 9, -2, 8, -6, 4, 5, 9, 1] => [[5], [-2, 9], [-6, 4, 8], [5], [1, 9]]
[8, 3, -1, 6, -8, 7, -1] => [[8], [-1, 3], [-8, 6, 7], [-1]]

Scoring

The shortest code wins!

Rules

No standard loopholes, please.


  • Is this fun and clear?
  • Any clarification needed?
\$\endgroup\$
6
  • \$\begingroup\$ use fastest-code there are few questions with both tags. \$\endgroup\$
    – Fmbalbuena
    Dec 4 at 16:28
  • \$\begingroup\$ time spent on what interpreter? can you say TIO? \$\endgroup\$
    – Fmbalbuena
    Dec 4 at 16:30
  • \$\begingroup\$ @Fmbalbuena what if the interpreter is not on TIO? \$\endgroup\$
    – Alan Bagel
    Dec 4 at 16:31
  • 2
    \$\begingroup\$ You'd need many more test cases to get significant results with fastest-code. Also, using TIO for timing is a bad idea (I'm sure there's a post on meta about that, but I don't know exactly where). \$\endgroup\$
    – Arnauld
    Dec 4 at 16:33
  • 1
    \$\begingroup\$ @Arnauld here \$\endgroup\$
    – Fmbalbuena
    Dec 4 at 16:35
  • \$\begingroup\$ @Arnauld added more test cases \$\endgroup\$
    – Alan Bagel
    Dec 4 at 16:37
0
\$\begingroup\$

The event scheduler is a recurrent theme in event-driven architectures: something triggers an event that needs to be checked in the future one or more times. I has particular use in trading where you want to correlate one market event with price movements in the future at several time deltas (1ms, 100ms, 1s, 1 min, etc).

A parenthesis here: this is a general algorithm challenge that can be implemented in any language. We provide an example implementation in C++ but it does not need to be written in that language necessarily.

The scheduler problem can be summarized in the following interface:

using Time = std::uint64_t; ///! nanos since epoch

/** Base class for all events to be handled by the scheduler */
struct Event {
    virtual void fire( Time scheduled, Time now ) = 0;
};

/** A class that functions as a container for events to be fired in the future.
    The same event can be added multiple times into the scheduler.
    Distinct events can be added at the same time.
 */
class Scheduler {
public:
    virtual ~Scheduler()  = default;
    /** Schedules one event */
    virtual void schedule( Event* ev, Time tm ) =0; 
    /** Checks events and fires accordingly. 
        "t" is guaranteed ascending */
    virtual bool check( Time t ) =0;                
};

As a note, we decided to use raw points so not to introduce noise around smart pointers, move semantics, etc. These can be added later on.

The scheduler can be trivially coded using the standard containers but it will lead to log(N) algorithms for scheduling. Other trivial solutions will lead to O(1) for scheduling but O(logN) for checking. For example:

class StandardScheduler : public Scheduler {
public:
    StandardScheduler();
    virtual void schedule( Event* ev, Time tm ) override;
    virtual bool check( Time t ) override;
private:
    using EventMap = std::multimap<Time,Event*>;
    EventMap events;
    Time current;
};

Our goal in this test is to generate a solution that remains fast even for very large number of events, say 1E9. Therefore it helps if the solution is constant time O(1) in both scheduling and checking, in average.

The main requirements are:

  1. Both scheduling and checking need to be very fast for extremely large number of events (eg 1E9). It is acceptable if it is slower at times (hiccups) for rebalance for example.

  2. Individual events can be submitted multiple times

  3. Distinct events can be submitted under the same time (same key in a map)

The best solution will display the best execution times for a very large number of samples, which we set arbitrarily at 100,000,000 events.

A basic implementation for this challenge is provided on Github: https://github.com/HFTrader/scheduler.git. The sample code is specific to Linux but the C++ code can be easily ported to Windows by replacing __builtin_ia32_rdtsc() with std::chrono or GetPerformanceCounter().

If you choose to do it C++, you might clone, subclass the Scheduler class and replace it in main(). An example StandardScheduler is provided. In other languages, please replace with equivalent constructs.

git clone https://github.com/HFTrader/scheduler.git
cd scheduler
mkdir build
cd build
cmake -DCMAKE_BUILD_TYPE=release ..
make 
sudo perf stat ./scheduler 10000000

The timings in this C++ code provide the number of cycles for scheduling and checking (iteration through time). A sample run can be like:

$ sudo perf stat ./scheduler 10000000
Timings schedule:3539 check:528
Success!

 Performance counter stats for './scheduler 10000000':

         12,134.30 msec task-clock                #    0.999 CPUs utilized          
             1,080      context-switches          #    0.089 K/sec                  
                 3      cpu-migrations            #    0.000 K/sec                  
           214,970      page-faults               #    0.018 M/sec                  
    52,357,943,659      cycles                    #    4.315 GHz                    
     1,867,770,944      stalled-cycles-frontend   #    3.57% frontend cycles idle   
    36,624,659,180      stalled-cycles-backend    #   69.95% backend cycles idle    
    10,112,070,044      instructions              #    0.19  insn per cycle         
                                                  #    3.62  stalled cycles per insn
     2,284,337,227      branches                  #  188.254 M/sec                  
       159,373,358      branch-misses             #    6.98% of all branches        

      12.142580511 seconds time elapsed

      11.938676000 seconds user
       0.191850000 seconds sys

The above code ran in 11.983 seconds for 10,000,000 events resulting in 1.198 microseconds per event, which is the key result.

New contributor
Jellyboy is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
6
  • \$\begingroup\$ Thanks for using the sandbox. The challenge type is called fastest-code here. It looks well-defined in general, but a few minor issues: 1) You don't really need restrictions in time complexity (the requirement 1) when submissions are competing for it. 2) Looks like the build instruction is linux only. If so, it should be clarified as such (along with dependencies like cmake). \$\endgroup\$
    – Bubbler
    2 days ago
  • \$\begingroup\$ FYI, language-specific challenges are discouraged here, and fastest-code without language restriction is usually done by measuring time on a single machine (often the challenge author's). (Not sure how to adapt this specific challenge to other languages, so I'd say it's fine in this case.) And unfortunately we're not like other competitive programming sites, and therefore have very few C++ users. \$\endgroup\$
    – Bubbler
    2 days ago
  • \$\begingroup\$ OK so would it be acceptable to submit a sample C++ code as guidance and open up to other languages? \$\endgroup\$
    – Jellyboy
    2 days ago
  • \$\begingroup\$ @Bubbler Changed the terms of the challenge. Does it look better as it stands? \$\endgroup\$
    – Jellyboy
    2 days ago
  • \$\begingroup\$ I mean, because of the nature of the task, it's near impossible to establish fair comparison across languages. Normally you'd feed input in a standardized format through STDIN and let the programs output through STDOUT, but 1e8 events would make I/O time way too significant. And not all languages have mt19937 implementation or seeding it like C++ does. So I was saying that limiting to C++ is fine here, though it won't get many answers on this site. \$\endgroup\$
    – Bubbler
    2 days ago
  • \$\begingroup\$ Hmm we could then open by classes like in boxing but per language here. Winner for C++, Java, Python, etc. And the IO is really not much - just generate a random sequence in memory and submit. \$\endgroup\$
    – Jellyboy
    2 days ago
0
\$\begingroup\$

Largest SKI Reduction in under 100 characters

The challenge

Create a program in SKI Combinator Calculus in under 100 characters that produces the largest result after terminating.

Scoring

The score will be the number of characters in the final reduction. The highest is the winner.

New contributor
nph is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
0
\$\begingroup\$

Code Golf Birthday Cake

Your task is to print this exact text:

    | | | | | |
   &***********&
   | Code Golf |
  | e---------f |
 | d___________l |
| o-------------o |
| C______________G |
###Golf your code###
####################

Rules

  • Trailing or leading newline is allowed
  • , so shortest code wins!

Meta

  • Any feedback?
\$\endgroup\$
0
\$\begingroup\$

Radiate a prime checker into a sum program

Write a program or function that takes a number n and returns/print truthy if it is prime, and falsy otherwise. Additionally, if you remove 1 character of the source code, the program must now take a list of one or more numbers and return/print the sum. This must work for at least one character, and your score is however many characters that this does /not/ work for. Lowest score wins.

meta:

let me know if i need to clarify anything etc also: would it make sense to allow the programs to be the other way around (i.e. a sum checker where removing 1 character makes it a prime checker instead)? Just in case it could lead to a more interesting golf

\$\endgroup\$
2
  • \$\begingroup\$ It says "remove or change 1 character". By change, do you mean simply changing an arbitrary character to another arbitrary character, e.g. abc -> axc? If so, a lot of golfing languages will likely be able to make a trivial 0-score program where they simply change a 1-byte prime checker to a 1-byte sum command. That might not be a bad thing, per se, but it's something to keep in mind. \$\endgroup\$ 12 hours ago
  • \$\begingroup\$ @AaroneousMiller True, ill stick to just "remove". Wasn't sure of potential ramifications, thanks \$\endgroup\$ 12 hours ago
0
\$\begingroup\$

Counting universal n-ary logic gates

Background

A classical logic gate is an idealized electronic device implementing a Boolean function, i.e. one that takes a certain number of Boolean inputs and outputs a Boolean. We only consider two-input logic gates in this challenge.

There are \$2^{2 \times 2} = 16\$ distinct two-input logic gates (2×2 input combinations and 2 possible outputs for each input combination). Out of the 16, only two, namely NAND and NOR gates, are universal, in the sense that you can build arbitrary circuits (any Boolean function) by composing the single type of gates. CGCCers might recognize NAND gates because we had a few challenges to build arbitrary circuits out of them.

NAND | 0   1      NOR | 0   1
-----+-------    -----+-------
  0  | 1   1       0  | 1   0
  1  | 1   0       1  | 0   0

We can generalize the concept of logic gates to n-ary inputs and outputs instead of Booleans, for example ternary for \$n=3\$. (Physical three-state circuits are also being studied.)

For ternary logic gates, the allowed states are often written as - 0 +. There are \$3^{3 \times 3} = 19383\$ distinct ternary logic gates in total, and Craig Gidney managed to enumerate 3773 universal ternary logic gates out of the 19383. (Full C# code) One such logic gate looks like this (named tand in the blog post):

tand | -   0   +
-----+-----------
  -  | 0   +   +
  0  | +   +   +
  +  | +   +   -

For \$n=1\$, there is only one possible logic gate (constant), and it is trivially universal because the one logic gate can build every possible (the only one) logic gate.

Challenge

Given the value of \$n \ge 1\$, compute the number of distinct universal n-ary logic gates.

Standard rules apply. The shortest code in bytes wins.

The known values are:

1 -> 1
2 -> 2
3 -> 3773

+500 bounty to the first answer that successfully computes the output for \$n=4\$. (There are \$4^{4 \times 4} = 4294967296\$ gates to consider.)

\$\endgroup\$
1
  • \$\begingroup\$ How many gates are there to consider for n = 5? :P \$\endgroup\$
    – Alan Bagel
    9 hours ago
-1
\$\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\$ 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\$ Jan 3 '14 at 0:08
-1
\$\begingroup\$

The only differences that matter

Cops' task

Write two programs (or functions) A and B in the same version of the same programming language. They also should be called in the same way, meaning you can't write one program and one function. Each should accept an integer n and output the term n of a different integer sequence on OEIS.

You should reveal a substring of each of A and B. Call them PA and PB. If one instance of PA is replaced by PB from A, it should become B. That means every byte except the reveal part in A and B should be exactly the same. You also reveal the lengths of A and B, and the two OEIS sequences. You don't reveal the programming language you use.

Your answer is cracked if a robber finds two programs A' and B' that also print the elements in the two integer sequences respectively, where A' is no longer than A, and A' with one instance of PA replaced by PB is also B'. They don't have to be the same with your original A and B. And they don't have to be in the same programming language as yours, as long as they are in the same programming language themselves.

If your answer isn't cracked 7 days after you post the answer, you can reveal your language and the original A and B and mark the answer safe, and it will be immune to future crack. Your answer can still be cracked if you don't do it.

Your score is max(len(A)+len(PA)*5, len(B)+len(PB)*5). The safe answer posted before a certain date with the minimum score wins.

For example, if your two programs are The first program and The second program, you can reveal first and second. Your score is 18 + 6*5 = 48. And a robber can crack your answer by <<first>> <<second>> if they work. But you can also reveal first pro and second pro to prevent this crack.

Please post your answer using this template:

# <length of PA> / <length of A> bytes, <length of PB> / <length of B> bytes, score <score>, <open / safe / cracked>

Part of program A (outputing [<OEIS number>](<OEIS link>)):

    <code of PA>

Part of program B (outputing [<OEIS number>](<OEIS link>)):

    <code of PB>

<any other explanations>

Robbers' task

(To do.)

\$\endgroup\$
9
  • \$\begingroup\$ Do robbers have to produce the same program, or any program? \$\endgroup\$ Oct 28 '16 at 14:47
  • \$\begingroup\$ There are two tricky edge cases around character encodings which the question needs to address. 1. It talks about substrings of A and B, saying that every byte except the revealed ones must be the same. If A and B differ in one Unicode codepoint, such that in UTF-8 they differ in only one byte but it's part of a three-byte sequence, can I post just that one byte as PA/PB or must I post the three-byte sequence? (I.e. are the substrings operating on the bytes or on the codepoints?) \$\endgroup\$ Oct 28 '16 at 20:57
  • \$\begingroup\$ 2. If my program is in APL using an 8-bit encoding, do robbers answering in a language other than APL have to have the same bytes in the part of their file corresponding to PA/PB or the same Unicode codepoints? \$\endgroup\$ Oct 28 '16 at 20:57
  • \$\begingroup\$ @NathanMerrill Any program. \$\endgroup\$
    – jimmy23013
    Oct 28 '16 at 21:05
  • \$\begingroup\$ @PeterTaylor I'm considering requiring every program to be in printable ASCII (and tabs and newlines), as some special characters effectively banned many languages. But I'm not sure about newlines, which have the \r problem. \$\endgroup\$
    – jimmy23013
    Oct 28 '16 at 21:09
  • \$\begingroup\$ Maybe I'll just say \r\n is counted one byte in this challenge, and is interchangeable with \n. But the programs in one submission must use only \n or only \r\n. \$\endgroup\$
    – jimmy23013
    Oct 28 '16 at 21:13
  • 1
    \$\begingroup\$ An example would make this easier to understand, \$\endgroup\$
    – xnor
    Oct 29 '16 at 6:08
  • 2
    \$\begingroup\$ I'm skeptical about having the programming language be a free variable. If a cop writes an answer using a verbose language, a robber can comment out all the visible parts and stuff a terse language answer into the cracks. \$\endgroup\$
    – feersum
    Oct 29 '16 at 11:24
  • \$\begingroup\$ @feersum But that's the whole point of all the requirements. If you comment out all the visible parts, both your programs usually should output the same thing. But I realized it's easy to have some workarounds in languages such as Befunge. I may try to find a way to ban them, or just abandon this post. \$\endgroup\$
    – jimmy23013
    Oct 31 '16 at 0:59
-1
\$\begingroup\$

Translation Polyglot

Your task is to write a program which runs in two distinct programming languages to translate text. Input should be translated between each language i.e. running your code in Code Language A translates from language 1 to 2, while running your code in Code Language B translates from language 2 to 1.

Rules:

  • Code Languages must be distinct, two versions of the same language are disallowed
  • Your code may be a full program or function
  • Your code must take one string (or nearest equivalent) as input. Input may be user input, function arguments, or other reasonable form
  • Output may be a function return, output to STDOUT, or other reasonable form. I do not care about trailing newlines or spaces
  • Your code may translate from/to any language on the official language list on Wikipedia. List the languages in your answer
  • To accomplish your goal, you may use prebuilt language tanslation dictionaries such as the ones found here.
  • If you read your dictionary as an external file, only the code to read in the file (f = open("dictionary.txt", 'r') in Python) counts towards your byte count. If your dictionary is hardcoded in, only count the bytes required to make it syntatically valid code (s="word1_in_english word1_in_french ..." would be 4 (s="")). Essentially, do not include the dictionary as part of your submissions byte count.
  • The dictionary you use must have been created before this post (including sandbox time). You may not modifiy the dictionary in any way.
  • Any built-in translation tools are disallowed. Built-in dictionaries are ok, but whatever code used to import them into your code must be included in the byte count

This is code golf, so shortest answer in bytes wins.

\$\endgroup\$
5
  • \$\begingroup\$ wait... Are you actually asking for machine translation? Seems very difficult. Haven't you ever seen bad translator? If it actually is machine translation, this won't work, because of the different resolution of the languages (like converting a jpg to a png and expecting the same quality back) \$\endgroup\$ Nov 1 '16 at 4:11
  • \$\begingroup\$ It's really just value lookup. I'm not asking people to to make their own dictionary, just use a pre-built and accept whatever it translates \$\endgroup\$
    – wnnmaw
    Nov 1 '16 at 13:45
  • 1
    \$\begingroup\$ But that doesn't really satisfy Language A produces output O from input I, while running in Language B produces output I from input O. \$\endgroup\$ Nov 1 '16 at 22:04
  • 1
    \$\begingroup\$ Ah, now I see the source of confusion. Updated text to require basic translation, not symmetric translation \$\endgroup\$
    – wnnmaw
    Nov 2 '16 at 11:53
  • \$\begingroup\$ Also I don't think translation is objective enough for code golf... \$\endgroup\$ Nov 3 '16 at 5:30
-1
\$\begingroup\$

What in the heck just happened?

I want you to write a program that will bleep out the H-word, regardless of where it occurs, whether it is inside of another word or a stand-alone word, whether capitalized or not.

Input and Output

The inputs and outputs of your program may be any of the following: an array of characters, a string, or any other standard data structure which does the job. However, the output must match the case of the input.

Samples:

In the format of Input: Output
A Shell gas station : A Sheck gas station
Hell is a very bad place to be. : Heck is a very bad place to be.
Ella fell and Nelly dug a well. : Ella fell and Nelly dug a well.
Chellsea Thell bought shells. : Checksea Theck bought shecks.

Standard loopholes apply, and the entry submitted by [insert date here] with the lowest number of bytes as defined by the Meta will win.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ I can't say for sure, as I don't have an exact reference, but I'm pretty sure a simple find and replace challenge has been done before. \$\endgroup\$
    – ATaco
    Feb 13 '17 at 0:19
  • 2
    \$\begingroup\$ "Hell" and "heck" are both "H-words", so you need to be clearer. Also, I feel like this is a duplicate. Though these are milder swear words, I think someone did one with swear words in general and it got deleted. If you're going to make a find/replace challenge, it's simple enough to make it about something else. \$\endgroup\$
    – mbomb007
    Feb 13 '17 at 0:19
  • \$\begingroup\$ Ah, I see. So, are you saying I should change what's being replaced or what my idea is? \$\endgroup\$ Feb 14 '17 at 0:50
-1
\$\begingroup\$

Prove the Undecideability of the Halting Problem

More information on the halting problem.

Either:

Create a program that, when given an input, no single program (which receives your source and your input) can determine if your program terminates, or

Create a function that, when given an input, no single program (which receives your source and your input) can determine if your function returns.

Your score is the byte count of your program plus the byte count of your input (or of the shortest input in the set of input that solves this problem).

Lowest score wins.

//I would love some input on my wording.

\$\endgroup\$
12
  • \$\begingroup\$ Can I make a request to an external URL until I get a 404? \$\endgroup\$
    – user58826
    May 17 '17 at 18:21
  • \$\begingroup\$ @programmer5000 can an external program determine whether your program will halt? For example, by pinging that URL themselves? \$\endgroup\$
    – Stephen
    May 17 '17 at 18:24
  • \$\begingroup\$ Oh. Could I make a program that stops when it finds 5 points that prove the Happy Ending Problem wrong? \$\endgroup\$
    – user58826
    May 17 '17 at 18:29
  • \$\begingroup\$ @programmer5000 if your program stops with a given input, and another program can predict that it will stop with that input, your program does not match specs. No input is accepted input, but it is very unlikely that an undecidable program can come from no input AFAIK. \$\endgroup\$
    – Stephen
    May 17 '17 at 18:32
  • \$\begingroup\$ @programmer5000 from the Wikipedia page it seems like that problem is already solved, so that program will terminate, so another program could predict that. Could be wrong though. \$\endgroup\$
    – Stephen
    May 17 '17 at 18:33
  • \$\begingroup\$ Um. eval. It's one byte long in GolfScript. \$\endgroup\$ May 17 '17 at 21:35
  • \$\begingroup\$ @PeterTaylor you need to provide an input that is undecidable, and that counts towards your score. \$\endgroup\$
    – Stephen
    May 17 '17 at 21:38
  • 2
    \$\begingroup\$ I don't think this is how the halting problem works... \$\endgroup\$ May 17 '17 at 23:50
  • \$\begingroup\$ @DestructibleLemon You may be right; Wikipedia says a general algorithm to solve the halting problem for all possible program-input pairs cannot exist. Do I need to require two inputs? This answer seems to contradict Wikipedia though. \$\endgroup\$
    – Stephen
    May 18 '17 at 0:10
  • \$\begingroup\$ hmmm, you definitely could do this (make it an interpreter) but I'm not sure how much you have to do to make this work... as in what the simplest program would be \$\endgroup\$ May 18 '17 at 0:17
  • 1
    \$\begingroup\$ @StephenS It doesn't require 2 inputs, it requires a pair (program, input). \$\endgroup\$ May 18 '17 at 1:07
  • 1
    \$\begingroup\$ It's the problem which is undecidable, not the instances. If you want to ask for a program which cannot be proven to halt or not halt, you have to specify the axiom system which can be used for the proof. See e.g. codegolf.stackexchange.com/q/79470/194 , codegolf.stackexchange.com/q/79620/194 \$\endgroup\$ May 18 '17 at 6:19
-1
\$\begingroup\$

Bike saddle drawn through a fractal

Based on the Mandelbrot image in every language, and on the observation the 3rd layer (0 indexed) always looks like a bike saddle, I had a little bit different challenge:

  • Language must be capable of graphical output or drawing charts (saving files disallowed)
  • Render a window or control that is resizable by mouse action. As example, it can be a typical GUI Window with the typical frame that allows resizing
  • After resizing the GUI element, the fractal should be updated according to the new pixel space
  • The fractal coordinates range from approximately -2-2i to 2+2i
  • The pixels outside of the 3rd layer (0 indexed) of Mandelbrot set should have one color; the ones inside 3rd and inner layers should have another. The only two colors used should be clearly distinguishable
  • At least 99 iterations
  • ASCII art not allowed

Winning conditions:
Shortest version (size in bytes) for each language will get a mention in this post, ordered by size.
No answer will ever be 'accepted' with the button.

\$\endgroup\$
1
  • \$\begingroup\$ @Mark Jeronimus: credits to you. \$\endgroup\$
    – sergiol
    May 27 '17 at 8:48
-1
\$\begingroup\$

The 2017 Loader contest

Here's a thing: Let's do the bignum bakeoff again.

Because why not.

What to do

Write a program in less than 256 characters that outputs the biggest number you can.
Yep, that's it. Biggest return value wins.

We'll run the program on a VM with infinite memory. (How do we do this?)

Rules

  • 256 chars max, excluding whitespace
  • Different leagues for each language
  • Output however you want
    • No explicitly printing numbers until your loop runs out. Print the number you generate directly. {1}
  • Program must terminate
  • No implementation-dependent shenanigans.
  • Implementation-independent shenanigans is encouraged.
  • ints are infinite.
  • Program must return the same number every time
  • Submission must include the approximate return value in any suitable googological notation.
  • Whitespace is space, tab, newline, formfeed, and return
    • BrainF***: Whitespace is all non-[]+-<> characters

{1} Allowed ways to return: printf("%d", num); return num;, etc.
Banned ways to return: for(;num>0;num--)printf("99999");, etc.


This is not a dupe of...

This because you can put any characters you want, not just non-digits; because we're hard-limiting the characters.


Suggested rules

  • No floats: float double long double, etc
  • No strings or chars
  • No bitfeilds
  • No looking at Command-line args

Next year's contest will be named after this year's winner, for no particular reason.

http://djm.cc/bignum-rules-posted.txt


Sandbox

  • How do you even test these programs?
  • What other rules should we have?
\$\endgroup\$
9
  • \$\begingroup\$ You don't actually explain the rules of the challenge, we would have to go to that link to find out what we are supposed to do. Aside from that, I think this has a lot of problems with your typing restrictions if these are not limited to C, but limiting it to C wouldn't really fit the spirit of the site. I think you may want to rethink how you want to approach this question. \$\endgroup\$ May 29 '17 at 16:43
  • \$\begingroup\$ @FryAmTheEggman "Typing restrictions"? (Added proper instructions) \$\endgroup\$ May 29 '17 at 16:45
  • 1
    \$\begingroup\$ Your post doesn't describe how people win. Is it by the largest possible number? Anyway, the problems are things like not counting whitespace, which can easily result in degenerate answers, as well as things like I/O streams and whatnot. All of your extra rules seem entirely based around C with no regard for other languages, which will not go well. \$\endgroup\$ May 29 '17 at 16:48
  • 5
    \$\begingroup\$ In answer to "Because why not": because it will be closed as a dupe. \$\endgroup\$ May 29 '17 at 17:59
  • \$\begingroup\$ Here's a couple of rules I would consider. 1. Program must generate the same result every time (e.g. not based on timer, probability, or the like). 2. Submissions should include, if not the exact resulting number, at least a best estimate, in scientific notation if need be. \$\endgroup\$ May 30 '17 at 18:32
  • \$\begingroup\$ Scientific notation? People will post answers that far, far exceed that. In fact, Mathematica, 22: Fold[Power,2~Range~9999] It's 2^3^4^...^9999. That's not being represented anytime soon. \$\endgroup\$ May 31 '17 at 3:31
  • 1
    \$\begingroup\$ This is a duplicate, and is also going to come down a lot to whether or not you allow programs that exceed the computational capacity of any existing computer. (If you require programs to work on a physical computer, the best they can possibly do is to use the entirety of memory as a counter and print out 9s over and over again. If you don't, the answers can easily be large enough that you need to use notation invented specifically for describing the number, because all other notations are not enough.) \$\endgroup\$
    – user62131
    May 31 '17 at 22:40
  • \$\begingroup\$ If your code can simulate a Turing machine, it becomes hard to judge who the winner is, and whether an answer is valid at all. \$\endgroup\$
    – anatolyg
    Jun 1 '17 at 20:35
  • \$\begingroup\$ Re your latest edit: you're wrong. The question it's a dupe of also has a hard limit to the number of characters; in fact it's a harder one, but the best answers could be copied with slight tweaking to take advantage of the extra space. And the digit restriction turned out not to be a serious problem: the winning answer would gain extremely little from being able to use digits. \$\endgroup\$ Jun 2 '17 at 9:07
-1
\$\begingroup\$

Do nothing

Write a program which terminates normally (not in an error), producing no output on the standard output stream (or the language's closest equivalent), nor on the standard error stream, regardless of what content is present on the standard input stream. (Note that this is intentionally overriding the normal I/O defaults; this is a challenge entirely about input/output handling.)

Additionally, your program may not have any other side effects (e.g. writing files, changing persistent state), unless they're an unavoidable consequence of running a program on the operating system you're using (e.g. on Linux, it's OK to change the "next process ID number to be assigned" value inside the kernel, because that happens whenever you run a program).

Finally, to avoid numerous uninteresting 0-byte (or boilerplate-plus-0-byte) solutions, you may not use a language in which the shortest program that does nothing (i.e. complies with the above specification) is also the shortest (or tied for the shortest) program which runs without error (but possibly reacts to input or produces output). In other words, you can't use a language unless doing nothing is more verbose than doing something.

Clarifications

  • Intentionally exiting the program early is permitted. If you do exit the program manually, on a system that uses exit codes, you may do so with any exit code.
  • Crashing the program is not permitted, even if it (for some reason) exits with a "success" code after the crash.
  • "No output" means 0 bytes of output, not even a trailing newline.
  • Likewise, your program must be able to handle any finite sequence of bytes on the standard input stream, even if it isn't, say, made of characters in the current encoding (but rather of arbitrary octets). You do not need to handle infinite input, though (e.g. your program won't be connected to /dev/zero or the like).
  • You don't have to actually read input; it's your choice as to whether you want to read and discard it, or not read it at all.

Victory condition

As a challenge, shorter is better, measured in bytes. (Remember that if you need to run the program in an unusual way, that incurs a byte penalty, under standard PPCG rules.)

Because languages which are particularly suited for this task (such as Perl and Python) are excluded by the rules, there's not much point in talking about the best answer cross-language; rather, the aim is to find the best answer you can in the language which you submit in. (Historically, on this sort of challenge, answers that are more unusual, interesting, or better-explained have tended to get more votes.)

Sandbox questions

Is this too trivial? We were discussing it in chat as a joke, and realised that it's actually possibly more interesting than it sounds. I'm fairly sure the spec's correct (although would definitely appreciate knowing if something's wrong here!), but would appreciate feedback on how much people would hate me if I posted it to main.

\$\endgroup\$
2
  • \$\begingroup\$ you can't use a language unless doing nothing is more verbose than doing something.you can't use a program unless your program is more verbose than any other program which does something. You must provide a shorter program which does something to prove your solutions validity. \$\endgroup\$
    – Adám
    Jun 8 '17 at 1:03
  • \$\begingroup\$ @Adám: If you did that, people would just add a comment byte or two to create a program of the shortest possible length that was longer than a program that did something. That isn't particularly interesting. \$\endgroup\$
    – user62131
    Jun 8 '17 at 1:21
-1
\$\begingroup\$

Draw an XBox

Here's an X:

\  /
 \/
 /\
/  \

And here's a Box:

+----+
|    |
|    |
|    |
|    |
+----+

So, for an XBox, just draw an X in a Box:

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

Your input will be a number (in any standard way) that will represent the size of the box. To output the above box, this could be the number of -/|\s (4), or the number of lines/columns (6), or even the intercept of the second diagonal (5) would be acceptable. (Don't ask me to accept the base256 encoding of the output though, as that's one of the many banned standard loopholes.)

Your program or function should then output (in any standard way) the XBox of the given size. If the \/s cross in the same character, place an X (as per Draw a big slash X). For example, here's an XBox three sizes larger than the one above:

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

This is , so the shortest program wins!

\$\endgroup\$
12
  • \$\begingroup\$ in some obvious way unclear/subjective \$\endgroup\$
    – MD XF
    Jun 9 '17 at 16:35
  • \$\begingroup\$ @MDXF 4 examples weren't sufficient? \$\endgroup\$
    – Neil
    Jun 9 '17 at 17:04
  • \$\begingroup\$ I'm just warning you that it could get closed for being too broad due to that statement. \$\endgroup\$
    – MD XF
    Jun 9 '17 at 17:05
  • \$\begingroup\$ I agree with @MDXF \$\endgroup\$
    – Beta Decay
    Jun 9 '17 at 18:03
  • \$\begingroup\$ @BetaDecay That's all very well, but I'm unclear as to what you want. \$\endgroup\$
    – Neil
    Jun 9 '17 at 19:15
  • \$\begingroup\$ Just a basic explanation of how scaling works. Some examples would suffice \$\endgroup\$
    – Beta Decay
    Jun 9 '17 at 21:32
  • \$\begingroup\$ I've added an example. \$\endgroup\$
    – Neil
    Jun 10 '17 at 0:42
  • \$\begingroup\$ @MDXF Here's my problem. I just tried implementing this in Charcoal, and came up with Try it online!. As it turns out, to produce those example XBoxes I actually need sizes of 7 and 10, but I didn't want to penalise that choice of input just because I hadn't predicted that particular scaling. \$\endgroup\$
    – Neil
    Jun 10 '17 at 13:42
  • \$\begingroup\$ @BetaDecay If you still have any further input it would be appreciated. \$\endgroup\$
    – Neil
    Jun 12 '17 at 12:06
  • \$\begingroup\$ Related \$\endgroup\$ Jun 15 '17 at 11:57
  • \$\begingroup\$ @KevinCruijssen Ugh, I even have an answer on that question... I guess the use of specific characters doesn't really sufficiently distinguish this one. \$\endgroup\$
    – Neil
    Jun 15 '17 at 12:42
  • \$\begingroup\$ @Neil Well, using /+x\ instead of just * does make it a bit trickier, but it's indeed a bit too similar imho. \$\endgroup\$ Jun 15 '17 at 13:11
-1
\$\begingroup\$

Plan and Chain a route through OEIS

Your Task is to reach so many OEIS sequences you could make with chaining your last sequence with a operation to a new sequence.

You must avoid last sequence minus last sequence plus first sequence or something similar that your new sequence is based on the first sequence except to make the second sequence.

Your starting OEIS sequence is in every case https://oeis.org/A001477

Given as Input an positive Integer and a Letter that matches [A-Z] or [a-Z]

Example

PHP, 171 bytes

for($a=0;$a<=$argv[1];$a++)$r[]=[$a,$b=$a&1,$c=$a+!$b,$d=(($c-!$b)/2^0)+$b,$A[$b]=$e=$d*$c,$f=$e+$A[!$b],$g=$a?$g*sqrt($f):1,$h=$g%2];echo$r[$argv[1]][ord($argv[2])%32-1];

Try it online!

The example gives back the n value of a OEIS sequence for the following letters. A letter greater h is for this example a invalid input

  • a https://oeis.org/A001477 numbers
    $a Valid first sequence

  • b https://oeis.org/A000035 mod 2
    $b=$a&1 Valid use the variable in the sequence before

  • c https://oeis.org/A109613 odd numbers
    $c=$a+!$b Valid Can use sequences before

  • d https://oeis.org/A110654 a(n) = floor(n/2) + n mod 2
    $d=(($c-!$b)/2^0)+$b Valid an invalid example is $d=(($a/2)^0)+$b cause it not use the sequence before

  • e https://oeis.org/A000217 triangular
    $A[$b]=$e=$d*$c Valid you can create help variables

  • f https://oeis.org/A000290 square
    $f=$e+$A[!$b] Valid use a help variabale and the variable of the sequence before. $f=$A[!$b]+$A[!$b] Invalid causes it makes the same value but use indirectly the variable of the sequence before

  • g https://oeis.org/A000142 factorial $g=$a?$g*sqrt($f):1 Valid cause your condition is not always the case that it have no relationship to the sequence before.

  • h https://oeis.org/A019590 Fermat's Last Theorem $h=$g%2 Valid but now we have the problem to find the next sequence

Could You make a full alphabet? My alphabet ends with the letter h

\$\endgroup\$
9
  • \$\begingroup\$ I'm rather confused as to what is being asked here. It might be helpful to state how one can get from one sequence to another. \$\endgroup\$
    – Grain Ghost Mod
    Jun 10 '17 at 20:47
  • \$\begingroup\$ @WheatWizard I could understand you. The problem is at the moment to make rules that avoid that a trivial solution exits. There are too many sequences in OEIS. The way from every sequence to the next should not end in a simple addition or multiplication. But evrything else should be allowed to get more creative solutions \$\endgroup\$ Jun 10 '17 at 20:56
  • \$\begingroup\$ (1) The first sentence says that the aim is to build the longest chain possible, but the scoring mechanism rewards average code length per element in the chain rather than number of chains. I would think it most likely as it stands that the winner would be a chain of length 1 or at most 2. (2) If you delete everything from the header Example to the end, do you think that the question still makes sense? If not (and I don't think it does), it needs a lot of work. (3) What do the two values in the input mean? Why is the second one a letter rather than a number? \$\endgroup\$ Jun 10 '17 at 21:10
  • \$\begingroup\$ (4) I'm not sure how feasible it is to write objective rules which forbid "trivial" expressions. (5) It is not clear how to interpret the rule about the 32nd term where either it is not known or the sequence is finite and shorter than 32 terms. \$\endgroup\$ Jun 10 '17 at 21:12
  • \$\begingroup\$ @PeterTaylor (1) Think you that popularity Contest is a better winning criteria? (2+3) to limit the chaining length to 26. The goal is to show relationsships between two or more sequences. (4+5) Yes it is not easy and I can drop it if I switch to popularity Contest \$\endgroup\$ Jun 10 '17 at 21:26
  • \$\begingroup\$ @WheatWizard I allow now trivial solutions \$\endgroup\$ Jun 10 '17 at 21:53
  • \$\begingroup\$ I'm not clear on the purpose of the inputs if we're just supposed to hard code our way from one sequence to the next​. Replacing your PHP example with more generic, more verbose pseudo-code might help. \$\endgroup\$
    – Shaggy
    Jun 11 '17 at 0:16
  • \$\begingroup\$ @programmer5000 exists a limit of correct tags? \$\endgroup\$ Jun 11 '17 at 11:39
  • \$\begingroup\$ @Shaggy See it as restriction for ways to code. You must have a chaining to the sequence before. So far I know any working code is a pseudocode \$\endgroup\$ Jun 11 '17 at 11:48
-1
\$\begingroup\$

Braid Badly Boundlessly


Your program or function must, given a string in any standard input format, output an infinite stream of delimiter-separated strings where each string is determined from the previous by a braiding algorithm. The program starts with printing the input string.

The algorithm is described as follows: Infinitely alternate between

(1) splitting the string into three substrings then swapping the first two substrings and flattening.

and

(2) splitting the string into three substrings then swapping the last two substrings and flattening.

starting with (1).

The three substrings should be of non-increasing length with the maximum length no more than 1 greater than the minimum length of the three substrings. (This means that when the length of the given string is a multiple of three, the three substrings should be the same length. When the length of the given string is one more than a multiple of three, the first substring should be one character longer than each of the last two substrings. When the length of the given string is two more than a multiple of three, the first and second substrings should each be one character longer than the last substring.)

Example

Let the input be "abcdefg". Let the delimiter be a newline.

Then the program would first print "abcdefg".

It applies (1) which splits the string into ["abc","de","fg"] and swaps the first two elements, reaching ["de","abc","fg"]. It flattens to get "deabcfg" which it prints and uses for the next step.

The program applies (2) to "deabcfg" to split into ["dea","bc","fg"] and swaps into ["dea","fg","bc"], flattening to reach "deafgbc".

The program applies (1) to "deafgbc" and the process repeats ad infinitum.

Then the output would be the newline-separated

abcdefg
deabcfg
deafgbc
fgdeabc
fgdbcea
bcfgdea
bcfeagd
eabcfgd
eabgdcf
gdeabcf
gdecfab
cfgdeab
cfgabde
abcfgde
abcdefg
deabcfg
deafgbc
fgdeabc
fgdbcea
bcfgdea
bcfeagd
eabcfgd
eabgdcf
gdeabcf
gdecfab
cfgdeab
cfgabde
abcfgde
abcdefg
[...]

Specifications

  • Note that the string should not be split at the beginning and then only swapped later. The string should be split on each and every iteration
  • The delimiter between lines could be whichever character is convenient. You may assume it does not appear in the input string.
  • The string input shall be at least three characters
  • The input consists solely of printable characters (0x20-0x7F)
  • Of course, standard loopholes are forbidden.

I/O

  • The input and output should be taken in standard I/O methods.
  • The input and output should be taken as string, list of characters, or equivalent.
  • The output should be output continuously, which means you may assume infinite memory.

Test cases

For the test cases, we will assume that the delimiter is a newline. Just the portion before the endless stream is repeats is shown.

input
--
output
-----
abcdefg
--
abcdefg
deabcfg
deafgbc
fgdeabc
fgdbcea
bcfgdea
bcfeagd
eabcfgd
eabgdcf
gdeabcf
gdecfab
cfgdeab
cfgabde
abcfgde
-----
abc
--
abc
bac
bca
cba
cab
acb
-----
abcdefgh
--
abcdefgh
defabcgh
defghabc
ghadefbc
ghabcdef
bcdghaef
bcdefgha
efgbcdha
efghabcd
habefgcd
habcdefg
cdehabfg
cdefghab
fghcdeab
fghabcde
abcfghde
abcdefgh
-----
Braid
--
Braid
aiBrd
aidBr
dBair
dBrai
radBi
raidB
idraB
idBra
Brida
-----
Cycle
--
Cycle
clCye
cleCy
eCcly
eCycl
yceCl
ycleC
leycC
leCyc
Cylec
-----
O Canada!
--
O Canada!
anaO Cda!
anada!O C
da!anaO C
da!O Cana
O Cda!ana
-----
A man, a plan, a canal - panama!
--
A man, a plan, a canal - panama!
an, a canalA man, a pl - panama!
an, a canal - panama!A man, a pl
 - panama!Aan, a canal man, a pl
 - panama!A man, a plan, a canal
 man, a pla - panama!An, a canal
 man, a plan, a canal - panama!A
n, a canal  man, a pla- panama!A
n, a canal - panama!A man, a pla
- panama!A n, a canal man, a pla
- panama!A man, a plan, a canal 
man, a plan- panama!A , a canal 
man, a plan, a canal - panama!A 
, a canal -man, a plan panama!A 
, a canal - panama!A man, a plan
 panama!A m, a canal -an, a plan
 panama!A man, a plan, a canal -
an, a plan, panama!A m a canal -
an, a plan, a canal - panama!A m
 a canal - an, a plan,panama!A m
 a canal - panama!A man, a plan,
panama!A ma a canal - n, a plan,
panama!A man, a plan, a canal - 
n, a plan, panama!A maa canal - 
n, a plan, a canal - panama!A ma
a canal - pn, a plan, anama!A ma
a canal - panama!A man, a plan, 
anama!A mana canal - p, a plan, 
anama!A man, a plan, a canal - p
, a plan, aanama!A man canal - p
, a plan, a canal - panama!A man
 canal - pa, a plan, anama!A man
 canal - panama!A man, a plan, a
nama!A man, canal - pa a plan, a
nama!A man, a plan, a canal - pa
 a plan, a nama!A man,canal - pa
 a plan, a canal - panama!A man,
canal - pan a plan, a ama!A man,
canal - panama!A man, a plan, a 
ama!A man, canal - pana plan, a 
ama!A man, a plan, a canal - pan
a plan, a cama!A man, anal - pan
a plan, a canal - panama!A man, 
anal - panaa plan, a cma!A man, 
anal - panama!A man, a plan, a c
ma!A man, aanal - pana plan, a c
ma!A man, a plan, a canal - pana
 plan, a cama!A man, anal - pana
 plan, a canal - panama!A man, a
nal - panam plan, a caa!A man, a
nal - panama!A man, a plan, a ca
a!A man, a nal - panamplan, a ca
a!A man, a plan, a canal - panam
plan, a cana!A man, a al - panam
plan, a canal - panama!A man, a 
al - panamaplan, a can!A man, a 
al - panama!A man, a plan, a can
!A man, a pal - panamalan, a can
!A man, a plan, a canal - panama
lan, a cana!A man, a pl - panama
lan, a canal - panama!A man, a p
l - panama!lan, a canaA man, a p
l - panama!A man, a plan, a cana
A man, a pll - panama!an, a cana
\$\endgroup\$
1
106 107
108
109 110
119

You must log in to answer this question.

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