459
\$\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\$
  • \$\begingroup\$ How are tags added to questions? \$\endgroup\$ – guest271314 Jan 9 at 7:51
  • \$\begingroup\$ @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] \$\endgroup\$ – DJMcMayhem Aug 29 at 15:19
  • \$\begingroup\$ Why no featured anymore? Can't we have it auto-added or something? \$\endgroup\$ – JL2210 Sep 26 at 15:57
  • 1
    \$\begingroup\$ @JL2210 We now have a permanent info box that links to the Sandbox, so the featured tag isn't necessary \$\endgroup\$ – caird coinheringaahing Sep 29 at 13:43
  • \$\begingroup\$ I think the sentence 'replace the post here with a link to the challenge and delete it' may specify that the deletion should be done immediately . \$\endgroup\$ – AZTECCO Oct 5 at 19:39

2565 Answers 2565

0
\$\begingroup\$

Stem and Leaf

A stem-and-leaf plot is a way to represent data and visualizing distribution. Usually the data is grouped in step of 10, with the last digit as "leafs" in ascending order, and the remaining digits as "stem". The steam and leafs are separated with a vertical line, with stem on the left and leafs on the right.

Challenge

Make a program or function which takes a list of non-negative integers as input, and outputs the corresponding stem-and-leaf plot.

Example Input and Outputs

Example 1:

Input: 10 2 15 4 2 24 18 17 24 24 25 15 18 22 17 23 24 33 19 28 28 28 26 32 25 27 37 28 41 38 38 30 35 30 41 45 40 40 37 33

Output:

0|224           
1|05577889      
2|23444455678888
3|0023357788    
4|00115

Example 2:

Input: 112 101 116 99 99 107 101 99 115 112 114 128 115 119 125 160 148 147 159 147 169 160 163 160 160 163 162 164 160 173 84 92

Output:

 8|4
 9|2999       
10|117       
11|2245569   
12|58        
13|
14|778       
15|9         
16|0000023349
17|3

Rules

  • The input may be a list, an array, a space or comma delimited string or other appropriate representation containing raw data values.
  • The vertical line of the output must be aligned.
  • A leading or trailing newline, or trailing spaces for each line are accepted.
  • Common loopholes applied.

This is a challenge, so the lowest-byte solution for each language wins!

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

Imagine you're a dishonorable scientist trying to prove that getting heads on a coin flip actually has about 70% probability when flipped 100 times. The trick is, you're going to flip the coin an arbitrarily large number of times (say, a million) and select the slice of 100 flips that contains the most number of heads. As input, take the number of total trials to do, and as output, return the number of heads contained within the most favorable contiguous slice of 100.

\$\endgroup\$
  • 5
    \$\begingroup\$ Please "Write your challenge just as you would when actually posting it.". If you post the challenge like this you will get a lot of problems. \$\endgroup\$ – user202729 Jan 26 '18 at 5:55
  • 1
    \$\begingroup\$ (question title, winning criteria, tags, example input/output, everything you didn't have) \$\endgroup\$ – user202729 Jan 26 '18 at 5:58
  • \$\begingroup\$ I like the idea, but the correctness of the answer is a little hard to verify. Perhaps you should require the answer writers to explicitly indicate how the program does the required job, unless it's really obvious from the code. For example, someone may directly draw a value from the resulting distribution without actually generating the total number of trials. That should be acceptable, as long as the writer justifies that their approach is correct, that is, gives the exact required distribution for the output \$\endgroup\$ – Luis Mendo Jan 28 '18 at 16:54
0
\$\begingroup\$

Find a Path of Similar Proportions!

Given a point on a square lattice, find the shortest path (by jumps) from the origin to that point, following these rules:

  • You are allowed to make any number of jumps containing any number of steps along the grid lines to another lattice point. These jumps must be along the grid lines and have an integer length.
  • Each jump must contain one step more or be one step shorter than the step before it. (This is where the "similar proportions" comes into play. Name change pending?)
  • The first step can have any length.

As an example, here is how one possible way one might travel from A(0,0) to B(5,5) under these rules:

A
|
|
|
1----2
     B
     |
     |
     3

The numbers indicate which steps are taken. Note that this solution backtracks, moving to (5,8) before partially retracing its path to get to its destination. This solution takes four jumps and is therefore optimal.

Here is a diagram of the number of jumps required for the shortest (or is it?) path to any other point with both integer coordinates below or equal to 10. Note the symmetry around (x,x). I don't know if my solution for (7,10) is optimal.

  | 0  1  2  3  4  5  6  7  8  9  10
--------------------------------------
0 | 0  1  1  1  1  1  1  1  1  1  1
1 | 1  3  2  3  3  3  3  3  3  3  3
2 | 1  2  3  2  3  3  3  3  3  3  3
3 | 1  3  2  3  2  3  3  3  3  3  4
4 | 1  3  3  2  4  2  3  3  3  3  3
5 | 1  3  3  3  2  4  2  3  3  3  3
6 | 1  3  3  3  3  2  4  2  4  3  3
7 | 1  3  3  3  3  3  2  4  2  4  5?
8 | 1  3  3  3  3  3  4  2  4  2  4
9 | 1  3  3  3  3  3  3  4  2  4  2
10| 1  3  3  4  3  3  3  5? 4  2  4

The actual actual task

Your task is to continue the table for points with coordinates as large as (127,127).

Your submission should be a program which prints valid paths for all points whose two coordinates lie between 0 and an inputted positive integer inclusively, or a function, which, given any pair of positive integers, outputs a valid path to the point specified by these coordinates.

A valid output path is an array or list (or other comparable datatype) which uniquely represents a valid sequence of jumps that can be used to reach the specified point and which makes it as easy as possible to find the number of jumps required.

Example possible ways for the example path given above:

[["d", 4], ["r", 5], ["d", 4], ["u", 3]] // using chars to represent direction
[[0, 4], [5, 0], [0, 4], [0, -3]] // direction vectors
[0, 4, 5, 0, 0, 4, 0, -3] // As above, in just one list. len()/2

Scoring

Your submission will be scored by the sum of your solution's bytecount and the sum of all jump counts for all paths it outputs for reaching any point between (0,0) and (127,127), inclusively. Smallest score wins, standard rules and loopholes apply, etc...

Example response (Python 3):

def c(a,b):
    d,e,g=[[a,0]],a+1,0
    while not g==b:
        d.append([0,e])
        e,g=-e+1,g+e
    return d

This extremely simple and naive piece of Python code achieves a score of 92 (program length) + 1406272 (for the path part) = 1406364, as verified here - Try it online!

More?

  • missing tags?
  • clarifications?
  • Table is incorrect?

Please respond.

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

Collectables, Inc

You're an aspiring collector. You want to be the top collector for as many collections as possible.

Here's how you play (with P players):

  • The game consists of multiple Auctions, and 2P collections. Some collections are bigger than others. Smaller collections are more valuable and rare, bigger collections are cheaper.

  • Each Auction puts 2P random items up for sale

  • You place a bid on each item, grouped by collection. (e.g. If doll was a collection, you place a single bid for all of the dolls in the current Auction)

  • You win by having the most pieces for the most collections. (Each collection is worth 1 point. If you have the plurality of that collection, you gain that point).

Fine Details:

  • Players start with 30 gold.

  • Each collection contains a different number of items, from 2 to 2P+1.

  • There are 2P+3 auctions (until all items are sold)

  • Players can bid on multiple items, and their total bid can exceed their current gold.

  • Resolution of bids happens as follows:

    1. All invalid bids are removed. (Players without enough gold, or bids on items already sold).
    2. Find the top bid (by gold). Tiebreaker is the collection size (smallest first).
    3. If there is still a tie, then that item group is removed.
    4. Otherwise, the top bidder wins the item group. His money is added to the pot.
  • After an Auction is finished, the pot is evenly distributed among all players. Any remainder is put back into the pot.

I think that my rules are pretty complete.

  • Is it clear?
  • Is it interesting?
  • How many reads did it take you to understand the post?
\$\endgroup\$
  • \$\begingroup\$ 1. It took me until the third read-through to understand that the collections are split into items and then recombined, possibly because I'm unconsciously applying real-world knowledge about how these things normally work. Explicitly saying that there are P*2+3 auctions would be a useful hint. 2. I was going to say that point 3 was missing a tie-breaker until I realised that the second sort criterion is collection size and not group size. 3. I think there's some interesting game theory here: things like weighting bids towards odd sized collections vs even sized collections. \$\endgroup\$ – Peter Taylor Sep 11 '17 at 7:37
  • \$\begingroup\$ @PeterTaylor thanks for the feedback! I added an overview, does that help? \$\endgroup\$ – Nathan Merrill Sep 11 '17 at 15:32
  • \$\begingroup\$ Best to ask someone who hadn't previously read the question. BTW I presume you're planning to add something later about the I/O? \$\endgroup\$ – Peter Taylor Sep 11 '17 at 16:01
  • \$\begingroup\$ Yep. There isn't any hidden information (unless you count simultaneous as hidden), so the API should be pretty straightforward. \$\endgroup\$ – Nathan Merrill Sep 11 '17 at 16:21
0
\$\begingroup\$

Unicode reversible programs

The goal is to make a program that includes unicode formatting characters that when executed as-is generates a OEIS sequence, and when copied as its rendered* and executed, returns a different sequence.

  • The renderer is one that properly reacts to unicode formatting. For example with RLO the text should be reverted. (Its stored as "\u202etest" but renders as "tset"

This is will be so the answer with less bytes wins.

\$\endgroup\$
  • 3
    \$\begingroup\$ What do you mean by "copied as its rendered and executed"? \$\endgroup\$ – Peter Taylor Feb 1 '18 at 11:18
  • \$\begingroup\$ @PeterTaylor I mean that for example the text "\u202e hello" is rendered as "olleh " because U+202E is a unicode control character that reverses text (when rendered) \$\endgroup\$ – iovoid Feb 1 '18 at 19:28
  • \$\begingroup\$ Define it objectively. How browsers/text editors handle copy-paste are implementation-defined. (which browsers/text editors, which exact ways to copy-paste, put the pointer on which pixel of the screen, etc.) \$\endgroup\$ – user202729 Feb 2 '18 at 5:35
  • \$\begingroup\$ U+202E is not a Unicode control character: the Unicode control characters are the ranges U+0000 to U+001F and U+007F to U+009F. \$\endgroup\$ – Peter Taylor Feb 2 '18 at 12:19
  • \$\begingroup\$ Also: this question talks about characters and bytes but it doesn't address the relationship between them, which is a minefield. What about languages which don't use UTF-8 or UTF-16 for their source? What about languages which use either according to a command-line flag: can the transformed program change the state of that flag? \$\endgroup\$ – Peter Taylor Feb 2 '18 at 12:26
  • \$\begingroup\$ @PeterTaylor languages that dont use utf-8 it in their source can use a escaped form such as (0xe2 0x80 0xae). Also thanks for pointing that its actually a formatting character (not control) \$\endgroup\$ – iovoid Feb 2 '18 at 18:20
  • \$\begingroup\$ So basically split on the unicode char and reverse all that's after it? Possibly multiple times? Doesn't sound too interesting. \$\endgroup\$ – Magic Octopus Urn Feb 2 '18 at 21:29
  • \$\begingroup\$ "for example"? Questions (challenges) need to be self-included. List all of them please. \$\endgroup\$ – user202729 Feb 3 '18 at 5:29
0
\$\begingroup\$

Removing a Letter adds a Letter

Your program should output nothing when unaltered, however, when any single character is removed it should have an output length of 1. This extends to any number of characters being removed from the program, as long as there is, at minimum, a single character remaining.


For example, if my program were abcdefg, it should output nothing if unaltered.

However, if I were to remove a and d from this program to get bcefg, it should output any two printable characters that represent 16 bytes of information (2 characters for 2 characters removed).

  • So if bcefg outputs (00,AA,etc...) this is valid.

Taking this further, if we were to remove all but the letter g we'd need an output of 6 characters.

  • So if g outputs ('000000','@$^%@(',etc...) this is valid.

Your program must function for all possible combinations of removals that are possible, that is to say each single letter in your program should be a valid program.


Rules

  • You may "lock" pieces of the code, each locked byte counts for 2-bytes instead of 1-byte.
    • Locked bytes will never be removed.
    • For instance, if my program was abcdefg and bcd is locked, the shortest program we'll get is abcd,bcde,bcdf and bcdg.
    • If bcd was locked in abcdefg it'd be 10 bytes, not 7.
  • The program may output any byte to represent 1 removed character, N-bytes for N removed chars in the code itself.
\$\endgroup\$
  • \$\begingroup\$ The rule only leads to totally locked code \$\endgroup\$ – l4m2 Mar 13 '18 at 0:13
  • \$\begingroup\$ @l4m2 hah. I disagree. \$\endgroup\$ – Magic Octopus Urn Mar 13 '18 at 0:58
  • \$\begingroup\$ But more constructively, increase the penalty? Limit locked chars? \$\endgroup\$ – Magic Octopus Urn Mar 13 '18 at 1:04
  • \$\begingroup\$ Maybe require an unlocked percent? \$\endgroup\$ – l4m2 Apr 6 '18 at 10:52
0
\$\begingroup\$

Non-true, non-false JS boolean

Array prototype isn't redefined, input hasn't getters

function magic(input){
  let result = [];
  if(input.boolean != true){result.push("non-true");}
  if(input.boolean != false){result.push("non-false");}
  result.push(input);
  return result.join("\n");
}

returns

non-true
non-false
{"boolean": true}

What is passed to magic function?

Based on real problem :) I spent 30 minutes on this puzzle

\$\endgroup\$
  • 5
    \$\begingroup\$ This site is for programming contests, not pure programming puzzles. Thanks for using the sandbox, anyway. \$\endgroup\$ – user202729 Feb 1 '18 at 12:11
  • 7
    \$\begingroup\$ Contrary to what user202729 states, Programming Puzzles are on-topic on this site. This challenge could use a little cleanup to make it a better fit here (for example, what language is this?), but this challenge is indeed allowed here. \$\endgroup\$ – AdmBorkBork Feb 1 '18 at 14:02
  • \$\begingroup\$ ... someone said that I'm wrong. Anyway people definitely doesn't like this. \$\endgroup\$ – user202729 Feb 1 '18 at 14:02
  • \$\begingroup\$ @AdmBorkBork this is JS \$\endgroup\$ – Евгений Новиков Feb 1 '18 at 14:41
  • 3
    \$\begingroup\$ @ЕвгенийНовиков what JS version is this? in is a keyword, and can't be a variable name. \$\endgroup\$ – dzaima Feb 1 '18 at 14:47
  • \$\begingroup\$ @dzaima Good point. Last time I check on TIO the object {boolean: true} doesn't have " around and it caused a syntax error. I forgot about in so just try to rename it and it worked... \$\endgroup\$ – user202729 Feb 1 '18 at 14:51
  • \$\begingroup\$ "Programming Puzzle" is in the name of the site @user202729 \$\endgroup\$ – dylnan Feb 1 '18 at 15:46
  • \$\begingroup\$ @dylnan But... \$\endgroup\$ – user202729 Feb 1 '18 at 15:55
  • \$\begingroup\$ @AdmBorkBork is correct. We do allow programming puzzles. \$\endgroup\$ – Nathan Merrill Feb 1 '18 at 16:25
  • \$\begingroup\$ @NathanMerrill Then just upvote the comment. \$\endgroup\$ – user202729 Feb 2 '18 at 5:34
  • \$\begingroup\$ Many many things in the past, including but not limited to, code-trolling, underhanded, non-observable behavior, etc. are off-topic or heavily-discouraged nowadays. Be careful. \$\endgroup\$ – user202729 Feb 2 '18 at 5:34
  • \$\begingroup\$ @user202729 I did upvote. I just wanted to make sure it was extra clear to the OP. Furthermore, this challenge doesn't fit any of those tags, because its not asking for trolling/underhanded/non-observable code. You could argue that the code in the challenge fits those tags, but that's not what we care about. \$\endgroup\$ – Nathan Merrill Feb 2 '18 at 5:51
  • 2
    \$\begingroup\$ I don't believe that console is part of any JS spec. This presumably only works in certain contexts, and the question should specify what they are. Otherwise the task devolves into code-trolling by defining a suitable console. It's already borderline IMO. \$\endgroup\$ – Peter Taylor Feb 2 '18 at 12:04
  • \$\begingroup\$ @dzaima sorry, fixed this. Now input variable is input \$\endgroup\$ – Евгений Новиков Feb 3 '18 at 7:40
  • 1
    \$\begingroup\$ OK, so, in that case you may want to work on the wording of the challenge before posting it to Main because, right now, it reads as though you've come across this challenge elsewhere, spent half an hour trying to solve and are now looking for help doing so. Also, just so you know, restricted language challenges rarely go down well here. \$\endgroup\$ – Shaggy Feb 3 '18 at 19:20
0
\$\begingroup\$

Tags: Codegolf

Title: evil detection

When given any (you may choose the format and you should assume integer input) input, the output should be true if the input is a palindrome and false if not (or 1/0 or any equivalent).

To make it (a lot) harder, your code must work with a result that fulfills the challenge inverted if read backwards. So for a palindrome input, forward gives true, backwards false.

Example:

If your code is "abc12" and the input is 1221, your code should produce true-ish and "21cba" (your code read backwards) should produce false-ish.

Bonus if you think that's to easy: produce false if and only if the input is 666 forward and true backwards.

\$\endgroup\$
  • 2
    \$\begingroup\$ Duplicate \$\endgroup\$ – Shaggy Feb 5 '18 at 16:58
  • \$\begingroup\$ First, I want to say thanks for using the sandbox! Also, I do think you could go somewhere with this idea that doesn't make it a duplicate. Your idea is marginally different, in that it only requires the code to behave the same forward and backwards, rather than actually be a palindrome. While I think for palindromes it will almost always be best to have a palindrome, perhaps you can think of a different pattern that makes it more interesting? I'll let you know if I think of anything. \$\endgroup\$ – FryAmTheEggman Feb 5 '18 at 22:23
  • \$\begingroup\$ @FryAmTheEggman, I don't think the fact that the code need not be palindromic is enough to make this not be a dupe; many of the solutions to the challenge above would also be the optimal solution here. Maybe if this one required that the code not be a palindrome and also required that it output a different pair of consistent and distinct values when run in reverse, it might be enough to differentiate it? \$\endgroup\$ – Shaggy Feb 6 '18 at 9:25
  • \$\begingroup\$ Thanks to both of you, I'll have a look at the other answers, but I agree that allowing the code to be semi-palindromic is not enough (unless the other answers are all extremely long, I haven't looked yet). I'm thinking about making the code required to not be symmetric, but haven't figured out what to do with the input to make it fit \$\endgroup\$ – DonQuiKong Feb 6 '18 at 9:28
  • \$\begingroup\$ @Shaggy That seems like a good start for changing it. For the record, I definitely think that as it was when I posted it was a duplicate, I just thought there was something good in this challenge and I didn't want it to just be discarded! The unfortunate thing about just requiring non symmetry is that comments/newlines could often just be added at the end without much cost, but I do think there is a good challenge here, somewhere. \$\endgroup\$ – FryAmTheEggman Feb 6 '18 at 18:39
  • \$\begingroup\$ @fryamtheeggman how about this? \$\endgroup\$ – DonQuiKong Feb 6 '18 at 18:59
  • \$\begingroup\$ I think the problem with this is that while some of the answers to the other question will no longer work, some are still usable here with only a slight modification, so I don't think this will cut it. \$\endgroup\$ – FryAmTheEggman Feb 6 '18 at 19:31
  • \$\begingroup\$ @Fryamtheeggman and if I make the bonus question mandatory? But I'll think some more \$\endgroup\$ – DonQuiKong Feb 6 '18 at 19:42
0
\$\begingroup\$

Build a Brainfuck transpiler

Your job is to build a program that transpiles valid brainfuck to a language (not brainfuck!) of your choice.

You are not required to handle cases where the program is invalid (mismatched [ ]s), or contains characters that are not +-<>[],. but all other cases must be handled.

Size limits on your input or output are fine as long as they are imposed by computer restrictions, like RAM.

The programming language you transpile to is covered under the "What defines a programming language" rules, and must have been created before this challange.

In extension to not transpiling to brainfuck (cheater!) you can't use a brainfuck derivative or trival brainfuck substitution as the transpiled to language either.

Scoring

Programs will be scored with the average ratio of bytes in the input brainfuck program to the output transpiled result, as based on the examples.

Meta questions

This is a rough draft!
What tags should be associated with this?
How can I improve the scoring system?
What examples should I use to keep the scoring fair, but prevent obvious tricks?
What loopholes are there in this rough draft that I need to patch?

This entire thing will be reorganized when I get enough info to make a better writeup.

\$\endgroup\$
  • \$\begingroup\$ I'd tag it with code-challenge and brainfuck. Once you post the examples the scoring system seems to be fine, the major problem would be hardcoding but this is a standard loophole, so this should be fine. Also you should probably consider adding a non-terminating example. About preventing brainfuck derivatives: I'm not sure if this is well-defined enough, maybe others have some ideas? \$\endgroup\$ – ბიმო Feb 10 '18 at 14:22
  • \$\begingroup\$ @BMO About hardcoding: Just hide the official test cases. You don't need to prevent BF derivative, they would just be boring (and downvoted most likely). Also it's very hard to define them (What about 2D BF? What about Unary? What about Random BF / self-modifying BF?) \$\endgroup\$ – user202729 Feb 10 '18 at 15:39
  • \$\begingroup\$ Also, BF is too unclear as a language specification. (is memory wrapping or infinite to one end or infinity to both ends? Are values positive/negative/modulo 256? etc.) \$\endgroup\$ – user202729 Feb 10 '18 at 15:41
0
\$\begingroup\$

Chiasmus Indenter


Chiasmus is a literary form that is similar to palindromes. Some ideas are presented and then presented again in reverse order, often phrased differently.

Natural language processing is hard, so I'll be using a more computer-friendly definition. A chiasmic string is made up of a series of substrings that are repeated in reverse order in the second half of a string. Formally:

  • If a is some non-empty string, then aa is chiasmic.
  • If C is chiasmic and a is some string, then aCa is also chiasmic. Note that this applies recursively, thus abCba is chiasmic if C is also chiasmic and a and b are non-empty strings.

For example, batbat is chiasmic, as are glassbottlebottleglass and AliceBobCharlieCharlieBobAlice. All even-length palindromes are chiasmic, being made up of many length-1 strings.

Note that the empty string is not a chiasmus.

The Challenge

We're programmers, so we like nice indentation. Your goal is to take chiasmic strings and indent them so that each matching substring is at the same level of indentation. For example, cheesepizzawithanchoviesanchovieswithpizzacheese would be indented like so:

cheese
    pizza
        with
            anchovies
            anchovies
        with
    pizza
cheese

For base case chiasms (i.e. 2 repetitions of a string), no indentation is necessary, but the substrings should still be on separate lines. Thus, gumgum would be indented:

gum
gum

In order for there to be only one canonical output for each chiasmus, if it is possible to indent at more than one place, indent in a way such that the a substrings for the form aCa are as long as possible (applied recursively for each C until the aa base case is reached). For example, catdogcatdogdogcatdogcat should be indented like this:

catdogcat
    dog
    dog
catdogcat

Not like this:

cat
    dog
        cat
            dog
            dog
        cat
    dog
cat

Also not like this:

cat
    dogcatdog
    dogcatdog
cat

The behavior of indenting a non-chiasmus is undefined.

Rules

  • Indentation can use any amount of whitespace of any kind, so long as it is consistent (e.g. do not mix tabs and spaces). Lines may either be output as a list/array/whatever or a newline-separated string.
  • You may assume that the input is a chiasmus that contains only alphanumeric characters.
  • As this is , the shortest submission wins.
\$\endgroup\$
  • \$\begingroup\$ May indentation be done with a \t character? \$\endgroup\$ – Kamil Drakari Feb 9 '18 at 22:25
  • \$\begingroup\$ I probably should do that since it saves 2 characters and is purely cosmetic. \$\endgroup\$ – Beefster Feb 9 '18 at 22:43
  • \$\begingroup\$ "Longest possible substrings" still leaves some room for ambiguity. What's the canonical output for ababbaba? \$\endgroup\$ – Nitrodon Feb 10 '18 at 4:40
  • \$\begingroup\$ aba b b aba. I see how it can be indented as a bab bab a, though. \$\endgroup\$ – Beefster Feb 10 '18 at 6:44
  • \$\begingroup\$ I kept waiting for a glassbottlebottleglass test case! \$\endgroup\$ – Shaggy Feb 11 '18 at 9:27
  • \$\begingroup\$ @Shaggy Wish granted. \$\endgroup\$ – Beefster Feb 11 '18 at 16:52
  • \$\begingroup\$ I don't understand the catdogcatdogdogcatdogcat example. It seems to me to directly contradict the rule it's supposed to be illustrating. \$\endgroup\$ – Peter Taylor Feb 12 '18 at 8:54
  • \$\begingroup\$ @PeterTaylor how so? \$\endgroup\$ – Beefster Feb 12 '18 at 20:15
  • \$\begingroup\$ On review, I agree that "directly contradict" is overstating it. But the minimalist indentation still doesn't fit the rest of the question. The stated grammar is pointless: the derivation aCa is only permitted for extremely limited values of C (strings of the form bb such that there aren't c and d satisfying ab = cd and |c| > |a|). The statement "indent in such a way that the lowest levels of indentation have the longest strings possible" (my emphasis) makes no sense, because there is at most one level of indentation (or two if you count "unindented" as the first). \$\endgroup\$ – Peter Taylor Feb 12 '18 at 21:49
  • \$\begingroup\$ And the statement "All even-length palindromes are chiasmic, being made up of many length-1 strings" is not true, because the canonicalisation forces it to be made up of one repeated length-1 string and an outer layer of a repeated length-(n-2)/2 string. \$\endgroup\$ – Peter Taylor Feb 12 '18 at 21:50
  • \$\begingroup\$ The aCa form is recursive. Maybe I should make that clearer with the examples. \$\endgroup\$ – Beefster Feb 13 '18 at 1:53
  • 1
    \$\begingroup\$ I would suggest dropping the requirement to produce an error on non-chiasmal(?) input, and instead just guarantee that the input will be a chiasmus. This changes it from two challenges (detect whether the input is a chiasmus, and then indent it if it is) to one (indent a chiasmus). Just my opinion though. \$\endgroup\$ – Nathaniel Feb 13 '18 at 7:56
  • 1
    \$\begingroup\$ Slightly related \$\endgroup\$ – Shaggy Feb 13 '18 at 10:16
  • \$\begingroup\$ @Shaggy Well yeah it's related. I created that challenge and it was a direct inspiration for this one. \$\endgroup\$ – Beefster Feb 13 '18 at 19:30
0
\$\begingroup\$

Self-removing executable (retracted: dupe)

\$\endgroup\$
  • \$\begingroup\$ I don't like the restriction, it makes it easier for you to test (I guess that's the point of it?), but it prevents me (and many others) from competing. Saying it must handle "long and unusual characters" is underspecified. You can say that the program must be able to handle any valid filename, in the chosen operating system. The example code is already very short, so it doesn't leave much room for golfing, with all the restrictions in place. \$\endgroup\$ – Stewie Griffin Feb 14 '18 at 11:03
  • \$\begingroup\$ Which restriction? Shall it be centered around per-language leaderboard then? \$\endgroup\$ – Vi. Feb 14 '18 at 11:13
  • \$\begingroup\$ Always per-language. I guess t's not all restrictions, but all the Linux-specific stuff. Keep in mind that these are only my opinions though, others might disagree. \$\endgroup\$ – Stewie Griffin Feb 14 '18 at 11:22
  • \$\begingroup\$ It could be a good idea to have it Linux specific, but the example code is already so short that it leaves very little room for creativity. \$\endgroup\$ – Stewie Griffin Feb 14 '18 at 11:23
  • 1
    \$\begingroup\$ Dupe: codegolf.stackexchange.com/questions/19355/… ? \$\endgroup\$ – user202729 Feb 14 '18 at 12:52
0
\$\begingroup\$

Convert a number to (Name-To-Be-Specified)

(Name-To-Be-Specified) is a completely made up language. It uses a Senary (base 6) system of numbers with words for those numbers structured in a similar way to English.

0 to 6
Single digit numbers use a single word for each digit.

0 = "zeeroo"
1 = "nimbo"
2 = "feta"
3 = "tarumba"
4 = "ntamno"
5 = "waramaka"
(Any similarity to Kómnzo numbers are coincidental.)

6 to 11
The first set of two-digits numbers have special rules.

6 = "wi"
7 = "seeveen"
8 = "ayte"
9 = "tarumbawin"
10 = "ntamnowin"
11 = "waramakawin"

12 to 35
Multiples of 6 have the single digit word with a "wee" suffix.

12 = "fetawee"
18 = "tarambawee"
24 = "ntamnowee"
30 = "waramakawee"

Other numbers in this range are made by joining the word for the multiple of 6 with the word for single digit number, separated by a space. For example:
13 = "fetawee nimbo"
20 = "tarambawee feta"
27 = "ntamnowee taramba"
34 = "waramakawee ntamno"

36 to 1295
1296 to 46655
46656 to 1679615
1679616 to 60466175
(Since this is a sandbox, I'll leave these to-be-specified for now. Suffice to say I'll come up with words for each and consistent rules for joining them together and when you need the word "and".)

Challenge

Write a program that takes an integer as input and outputs that number in (Name-To-Be-Specified) words as described above. Shortest code wins.

\$\endgroup\$
  • \$\begingroup\$ A language called Golfish already exists >_< \$\endgroup\$ – Mr. Xcoder Feb 23 '18 at 13:50
  • \$\begingroup\$ @Mr.Xcoder I believe you mean Gol><> \$\endgroup\$ – Mego Feb 23 '18 at 13:52
  • \$\begingroup\$ That's a programming language, not a spoken language. But fair point, if I graduate this to an actual question I'll pick a new name. \$\endgroup\$ – billpg Feb 23 '18 at 13:52
  • \$\begingroup\$ @Mego Well yeah but the repository name is Golfish... \$\endgroup\$ – Mr. Xcoder Feb 23 '18 at 13:53
  • \$\begingroup\$ Anyway, I'd advise referencing that you're not referring to Gol><> in any way. :) \$\endgroup\$ – Erik the Outgolfer Feb 23 '18 at 13:54
0
\$\begingroup\$

Paintball Tournament

Inspired by The Rock, Paper, Scissors, Lizard, Spock Tournament of Epicness as well as other King-of-the-hill challenges, I would like to propose a Paintball Tournament.

There is a game on my phone, called Game Pigeon that contains a paintball game. This paintball game is played by two players. The object of the game is to shoot your opponent x times before they shoot you x times.

Gameplay

The game is played in two sets of rounds. A moving round and a shooting round.

Both players, without their opponents knowledge, pick from three objects in front of them to hide behind.

                                (P1) X           X
                                     X           X (P2)
                                     X           X

Both players, without their opponents knowledge, choose which target across from them they would like to shoot at. After players decide which target to shoot at, players shoot at the targets chosen in unison, during which expose themselves from behind their target and are vulnerable to be hit.

Let's go through a small example. In the movement round, P1 has chosen to hide behind their left-most target. P2 has chosen to hide behind their middle target. In the shooting round, P1 chooses their leftmost target (Spot 1). P2 chooses their rightmost target (Spot 3). (See Below for diagram)

                                (P1) 3 <- Hit   1
                                     2          2 (P2)
                                     1  Miss -> 3      

For the above example, P1 would miss their shot and P2 would hit their shot, resulting in P1 losing one of their lives. During the shooting phase, players must choose a barrier to shoot behind, they cannot stay hidden.

After the shooting phase both players go back into the moving phase and, without their opponents knowledge, can move behind either of the other two objects or stay in place. They then continue to the shooting phase. They loop through these two phases until one of the players run out of lives, both players run out of lives, or a set number of rounds is completed.

Inputs

In the first game of the match, no arguments will be supplied to your bot. In each subsequent game of the match, you will be supplied 2 Args. -Arg1 will contain the location of the player([1, 2, or 3]) as well as the players move history. -Arg2 will contain the location of the players shot([1, 2, or 3]) as well as the players shot history. Both of these locations are referenced as if you are looking in the face of your opponent.

Example:

  • Round 1: PaintballBot.exe
  • Round 2: PaintballBot.exe 1 1
  • Round 3: PaintballBot.exe 12 11
  • Round 4: PaintballBot.exe 121 113

Output

Each round, your bot must output the location in which it is hiding, and the location it is going to shoot, to STDOUT, with two characters. All example outputs are shown below:

11 12 13 21 22 23 31 32 33

Match Format

Each submitted bot will play one match against each other bot in the tournament

Each match will last until one of the players loses their x amount of lives, or the match executes 50 rounds.

Matches will be played anonymously, you will not have an advanced knowledge of the specific bot you are playing against, however you may use any and all information you can garner from his decision making during the history of the current match to alter your strategy against your opponent. You may also track history of your previous games to build up patterns/heuristics etc... (See rules below)

Submission

Your submission should include:

  • Your Bot's name
  • Your Code
  • A command to
    • execute your bot from the shell e.g.
    • ruby myBot.rb
    • python3 myBot.py
    • OR
    • first compile your both and then execute it. e.g.
    • csc.exe MyBot.cs
    • MyBot.exe

Sidenotes

  • Need to describe that the location is relative to the shooter(from left to right) and the targets are relative to the shooter(from left to right)

  • I am still working on the control program for this event, and any help from other is greatly appreciated

If someone with more experience than me wants to take this over, please let me know. I would rather help with this challenge since it is my first and then have the knowledge and skills to run my own in the future.

Please let me know what still needs more clarification so we can have a fun tournament!

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

Sandbox:

Is this question already available (duplicate)?

Are things too vague?

Does providing the example help or hinder?

Tidy the Pantry (easy)

I hate grocery shopping, particularly the part where I put groceries away--so I'm calling upon the collective hive-mind to handle that.

Challenge

Your challenge is to take a 1D-list of groceries and a 2D pantry as input; and output an newly assorted pantry. The two variables can be of your type choice, and in any order, but please specify what item types your program requires (e.g. string, array, etc.).

Rules & Additional info.

Scoring

  • This is code golf, so the shortest answer in bytes wins

Rules

  • The pantry should be ordered alphabetically (A - Z, left to right, top to bottom)
    • For simplicity, the pantry is case-insensitive
  • The pantry must retain its horizontal size (but trailing newlines are optional)
  • "Pockets" (empty spaces) should be filled between items (i.e. only the last item is allowed to have a trailing pocket)
  • If the pantry is too small for the incoming groceries, then the pantry must replace older items (Z being the oldest, A the youngest)
    • Z from groceries is younger than A in pantry
  • Standard loopholes are forbidden

Examples ([ and ] are used for readability)

Input (4x4 pantry):

[A][A][ ][ ]
[ ][ ][B][ ]
[C][ ][ ][ ]
[ ][ ][ ][D]

AAD

Output:

[A][A][A][A]
[B][C][D][D]
[ ][ ][ ][ ]
[ ][ ][ ][ ]

Input (2x2 pantry):

[A][B]
[C][D]

XYZ

Output:

[A][X]
[Y][Z]

Example solution

JavaScript ES6 (989 bytes)

// (String, String) -> String
let organise = (pantry, groceries) => {
  let n = pantry.split("\n").sort((a, b) => b.length - a.length); // used at the end of the function for horizontal sizing
  n = n[0].length;

  pantry = pantry
    .replace(/\W/g, "") // get rid of all non-alphanumeric characters
    .split("");         // turn the string into an array

  // we need the properties of the new array
  // so the extra `pantry = pantry` is needed
  pantry = pantry
    .slice(0, pantry.length - groceries.length) // go ahead and remove the last overlapping elements
    .concat(groceries)                          // add the groceries to the pantry
    .join("")                                   // turn into a string
    .split("")                                  // turn into an array
    .sort()                                     // sort the array
    .join("");                                  // turn into a string

    return pantry.replace(RegExp(`(.{${n}})`, 'g'), "$1\n");
};

/** Testing below **/

console.log("Test #2:\n" + organise(
`AJCHDJE
JJ   JA
    ASD
OOQ I U
Q     W
      R`,

'AHJBCJHDHHATTGEH'
))


Test Cases:

Test #1, 4x4 pantry

TVCX <- pantry
ABCD
ATDJ
UAIK

XYXY <- groceries
----
AAAB <- expected output
CCDD
IJKT
XYXY

Test #2, 7x6 pantry

AJCHDJE
JJ   JA
    ASD
OOQ I U
Q     W
      R

AHJBCJHDHHATTGEH
-------
AAAAABC
CDDDEGH
HHHHJJT
T

Test #3, 10x10 pantry

AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA

ZZZZZZZZZZZZZZZZZZZZ
----------
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
AAAAAAAAAA
ZZZZZZZZZZ
ZZZZZZZZZZ

Test #4, 16x16 pantry pantry

ASDFGHJKLZXCVBNM
QJKAJ  KAKSJD  J
KJASDKFHI YOIER
W   OSDOFJ    DK
E PPPASP     AS
R
TASD 
YAAAAAAAAAAAA
U          JHOLK
IIAUSHODUYOAISUO
OASD  AUSODI 
PIASND JUASJNOIJ
A ASJDH PPOIO 
QHIAIUSOIUOOO
WYYAIUSNNAJSDASD
EAISDUUIOPJPIJPJ
ROQPEWIHRNXCAISD

QWERTYUIOP
----------------
AAAAAAAAAAAAAAAA
AAAAAAAAAAAAAAAA
ABCCDDDDDDDDDDDD
DDDEEEEEFFFGHHHH
HHHIIIIIIIIIIIII
IIIIIIJJJJJJJJJJ
JJJJJJKKKKKKKKLL
MNNNNNNOOOOOOOOO
OOOOOOOOOOPPPPPP
PPPPPPQQQQRRRRRS
SSSSSSSSSSSSSSSS
SSSTTUUUUUUUUUUU
UVWWY

Test #5, 2x2 pantry

HE
LO

[no groceries]
--
HE
LO
\$\endgroup\$
  • 1
    \$\begingroup\$ why divide the program score? \$\endgroup\$ – RedClover Feb 26 '18 at 19:03
  • 1
    \$\begingroup\$ I recommend you do count by bytes otherwise someone is just going to encode their entire program in Chinese characters and win. \$\endgroup\$ – HyperNeutrino Feb 26 '18 at 19:09
  • \$\begingroup\$ @labela--gotoa To get a golfed score (smaller programs get a smaller score), should I change it? \$\endgroup\$ – Ephellon Dantzler Feb 26 '18 at 19:13
  • \$\begingroup\$ @EphellonDantzler I don't understand why not just normal scoring...? \$\endgroup\$ – RedClover Feb 26 '18 at 19:14
  • \$\begingroup\$ LOL, that's why I set in in Sandbox first @labela--gotoa \$\endgroup\$ – Ephellon Dantzler Feb 26 '18 at 19:16
  • 1
    \$\begingroup\$ Some notes on your reference implementation: 1 It appears far too soon in the challenge. 2 It's not 1768 bytes. 3 You need to ungolf it and make it readable or it's not much use. 4 As it's JS, create a Snippet for it. 5 Is it necessary? It seems to be thrown in there to try to patch over any holes in the challenge spec. \$\endgroup\$ – Shaggy Feb 26 '18 at 23:17
0
\$\begingroup\$

Sandbox Notes

  • Is this inflammatory, mean, and liable to draw unwanted and unnecessary attention to low-voted questions in the Network?
  • Better tags?
  • I should probably write a snippet to find all angry Metas.

Angry Meta

A site on the Stack Exchange network is considered to have an angry Meta if the lowest-voted Meta question (possibly closed, but not deleted) on the site is voted lower than the lowest-voted Main question.

For example, at the moment, the lowest-voted question on PPCG.SE is at -32, while the lowest-voted question on Meta.PPCG.SE is at -24. This means that codegolf does not have an angry Meta.

On the other hand, the lowest voted question on SoftwareEngineering.SE is at -13, while the lowest-voted question on Meta.SoftwareEngineering.SE is at -17. This means that softwareengineering does have an angry Meta.

Challenge

You will be given the name of a Stack Exchange site, which you can assume will not be Area 51, Stack Apps, Stack Overflow, a subdomain of Stack Overflow (such as the Spanish Stack Overflow), Ask Ubuntu, Super User, Meta.SE, or any other site that whose domain is not of the form *.stackexchange.com.

The name will be given as the name of the subdomain (e.g. codegolf for PPCG, puzzling for Puzzling, gaming for Arqade, etc.). You should return one of two distinct, consistent values depending on whether the site has an angry Meta or not.

Since this is liable to change over time, I will not provide a list of test cases here, but you can use this Stack Snippet which is the reference implementation:

TODO

\$\endgroup\$
  • \$\begingroup\$ I suppose you mean to say lowest voted questions in your PPCG.SE example. \$\endgroup\$ – Weijun Zhou Mar 1 '18 at 13:12
  • \$\begingroup\$ @WeijunZhou Fixed. \$\endgroup\$ – Esolanging Fruit Mar 1 '18 at 16:38
0
\$\begingroup\$

Comment or not comment?

Write a function which given an all lowercase string, return the same string but with characters that are comments turned uppercase.

Input

Input is a null terminated ASCII string which may contain any of these characters abcdefghijklmnopqrstuvwxyz /*\ space newline
Last and only last character is null
You will not need to test for invalid input, such as "stringliterals" etc

Rules for what is comment

/* causes everything until */ (or end of string) to be comment
// causes everything until newline (or end of string) to be comment
'\' at end of line in a comment causes next line to be a comment aswell

Output

A copy of the input but with letters which are comments according to the rules above in uppercase, other characters shall remain unchanged

Examples

/comment -> /comment
//comment -> //COMMENT
/*comment -> /*COMMENT
no /*yes*/ no // yes -> no /*YES*/ no // YES

/*          ->              /*
comment                     COMMENT
*/                          */

//\          ->             //\
/*                          /*
not comment                 not comment
//\                         //\
*/                          */

ungolfed

\$\endgroup\$
  • \$\begingroup\$ Which characters can be in the input? Printable ASCII? \$\endgroup\$ – user202729 Mar 4 '18 at 5:48
  • \$\begingroup\$ printable ascii yes and you can also assume input will not contain uppercase letters, function shall change a-z -> A-Z if they would be comment according to C-syntax \$\endgroup\$ – PrincePolka Mar 4 '18 at 16:52
  • \$\begingroup\$ I edited the proposal, clarified and simplified a little bit \$\endgroup\$ – PrincePolka Mar 4 '18 at 20:59
  • \$\begingroup\$ Potential dupe. This challenge is about removing comments instead of changing their capitalization, but the main part is the same. \$\endgroup\$ – Laikoni Mar 6 '18 at 21:00
  • \$\begingroup\$ @Laikoni, thanks I had not seen that one, looks almost the same \$\endgroup\$ – PrincePolka Mar 6 '18 at 21:21
0
\$\begingroup\$

There, I fixed it (with recycled parts)

Challenge

Given a string containing only letters a-z (either upper- or lowercase), fix it by adding characters to it so that the difference between two adjacent characters is no more than one, or if you can't, remove offending characters (in order) until the string satisfies the requirement.

For example, abcdfge must be fixed either by adding an e, resulting in abcdefge, or by removing f and g, resulting in abcde. Removing must be done only if adding can't be done.

You can add characters only from a recycle bin, which your program or function must store between calls. Characters removed from the string are placed in the recycle bin, and added characters are removed from the bin. The bin can store multiple instances of the same character. In the beginning, the bin is empty.

If you can't fix the whole string by adding characters, don't add any characters. That is, only ever either add or cut a string, not a bit of both.

Example

First call:
  Recycle bin: "" (empty)
  Input:       "abcdfge"
  Output:      "abcde"          // 'f' and 'g' are removed and placed in the recycle bin

Second call:
  Recycle bin: "fg"
  Input:       "defhiabcdeg"
  Output:      "defghiabcdefg"  // 'f' and 'g' are taken from the recycle bin and placed
                                // where they are needed.

Third call:
  Recycle bin: ""
  Input:       "codegolf"
  Output:      "cdef"           // The two 'o's and the 'g' and the 'l' are removed and
                                // placed in the recycle bin.

Fourth call:
  Recycle bin: "oogl"
  Input:       "mnpqrt"
  Output:      "mn"             // 'o' could be added, but it isn't, because an 's' is
                                // also missing and we don't have one. "pqrt" are added
                                // to the recycle bin.

Fifth call:
  Recycle bin: "ooglpqrt"
  Input:       "kmnrsu"
  Output:      "klmnopqrstu"    // Characters "lopqt" are added from the bin to fill all
                                // the gaps. Unused characters are left in the bin.

Sixth call:
  Recycle bin: "ogr"
  Input:       "qwerty"
  Output:      "qe"             // The gap between 'q' and 'w' can't be fixed so 'q' is
                                // removed. 'e'-'q' < 0 and therefore not more than 1,
                                // so 'e' stays. The rest of the characters are removed.
                                // The recycly bin will contain "ogrwrty".

This is , so the goal is to make your code as short as possible in whatever language you choose to participate with.

\$\endgroup\$
  • 2
    \$\begingroup\$ "You can add characters only from a recycle bin, which your program or function must store between calls." Many languages don't have the capability to store information between program runs or function calls, or at least not easily. Perhaps having two inputs (recycle bin, 'input'), and two outputs (recycle bin, 'output') would be more inclusive? \$\endgroup\$ – Οurous Mar 9 '18 at 9:32
0
\$\begingroup\$

I wrote the following question then found this question. Is it similar enough to mine that mine would be considered a duplicate?

Recursive Prime Multiplicative Base

I've been thinking about this idea for months now, and, as far as I have been able to find, nobody else has thought of it. Please let me know if I wasn't the first!

Most number systems are additive positional. These take the form of ∑bi*di, where di is the sequence of digits and bi is the base sequence. For example, for the number 1234 in base ten, di={4,3,2,1,0,0,0...} and bi=10i.

I propose the idea of a multiplicative positional system.1 This instead takes a general form of ∏bidi. The most obvious useful multiplicative base is that of bi=Pi, where Pi is the i-th prime number. For example, one could write 3960 as 3,2,1,0,12, as 23*32*51*70*111=3960. This is mathematically interesting (e.g. multiplication gets reduced to addition, but addition is way harder) but we're still using an additive system underneath. This obviously cannot do. Thankfully, we can use recursion! This is probably best illustrated with an example:

3960=
  3    2   1  0 1
(0 1) (1)  () 0 ()
(0()) (()) () 0 ()
=(0())(())()0()

As you can see, each nonzero digit gets replaced with that digit's representation. 1 gets replaced with (), as a blank sequence is equivalent to an infinite series of zeros, and anything to the power of zero is one. If one were to include a symbol representing negation, one could write any rational number and even any expression obtainable from the integers using a finite number of multiplications and exponentiations in a finite sequence of four characters.

To give this number system a name, I term it the recursive prime multiplicative base or RPMB (unless you have any better ideas for it).

1Extending this, one can conceive of an infinite number of hyperoperational positional systems, but that's for another code challenge. ;)

The Challenge

You are to write a program that, when given an integer as input outputs the RPMB form of that integer. The output may be either as a string or a list. If the output is a string, you may substitute any characters for ()0. If the output is a list, the output should be a list of 0's and other lists matching this description. For example, for 3960, the program might output [[0,[]],[[]],[],0,[]].

Examples

(todo)

Scoring

This is , so the smallest program in bytes wins.

\$\endgroup\$
  • \$\begingroup\$ Related. \$\endgroup\$ – user202729 Mar 11 '18 at 10:07
  • \$\begingroup\$ But 9 isn't a prime... \$\endgroup\$ – user202729 Mar 11 '18 at 10:08
  • \$\begingroup\$ @user202729 whoops, typo! Thanks for catching that \$\endgroup\$ – DanTheMan Mar 11 '18 at 17:30
0
\$\begingroup\$

If replacing all the '3's doesn't fix your code, remove the 4s, too, with 'ceiling(pi) / floor(pi) * pi * r^floor(pi)'. Mmm, floor pie.

  • Output the largest prime number possible in as few bytes as possible using no number but pi.
  • This code will be the sole judge of whether your output is actually a prime number.
  • Your score will be the prime number produced divided by the number of bytes used for your code.
  • If your language has a built-in variable for pi, use that. Otherwise, let pi equal 3.1415926535898. Any occurrance of pi itself or something referring directly to pi counts as one byte.
  • Your number must be generated solely by applying various operations and functions to pi. Those functions cannot offset pi by anything other than another number derived from pi. The sole exceptions to this rule are floor and ceiling functions. For example, if you want to find the square root of something, you must do something to the effect of raising it to the (pi/pi/(pi/pi+pi/pi))th power.
  • You may not modify pi in any way that uses a reference to or directly uses non-pi number.
  • The entirety of the number must be outputted in base 10 and without scientific notation. All digits of the number must be included in the output.
  • You must provide a
  • The largest score wins.

Here's an example in Lua:

print(math.floor(math.pi))

That's 14 bytes (counting math.pi as one byte) for the prime number 3, so my score is 3/14 or ~0.21428571428. Here's another example:

m=math print(m.floor(m.pi^m.pi)+m.pi/m.pi)

That's 31 bytes (each m.pi is one byte) for the prime number 37, so my score is 37/31 or ~1.1935483871.

Sandbox

Are there any other ways to clear up ambiguities I may be missing?

\$\endgroup\$
  • \$\begingroup\$ some loopholes are forbidden by default and are sometimes referred to as "standard loopholes". \$\endgroup\$ – Giuseppe Mar 12 '18 at 21:31
  • \$\begingroup\$ You should include a winning criterion, i.e., "largest score wins" if I'm reading this correctly. \$\endgroup\$ – Giuseppe Mar 12 '18 at 21:31
  • \$\begingroup\$ @Giuseppe Thanks. I've edited the post \$\endgroup\$ – Zenon Mar 12 '18 at 21:33
  • \$\begingroup\$ At some point (and judging by the kind of stuff that happens here) the values being produced will be beyond guaranteed bounds of even strong tests like Baillie-PSW (2^64=18446744073709551616). Are such values banned or is it up to others to show that the number produced is composite? For example I might post Ç*ǵḞ+Ḟ×Ḟ+Ċ*`$ in Jelly since it produces 10555134955777783414078330085995832946127396083370199445109 which Baillie-PSW says is a probable prime. \$\endgroup\$ – Jonathan Allan Mar 12 '18 at 21:55
  • 1
    \$\begingroup\$ Welcome to PPCG! Nice challenge! \$\endgroup\$ – Weijun Zhou Mar 12 '18 at 22:19
  • \$\begingroup\$ Oh, by the way, that is floor(π^π)×(floor(π^π)+floor(π^π))+ceil(π^π)^ceil(π^π) and WolframAlpha also says it is prime \$\endgroup\$ – Jonathan Allan Mar 12 '18 at 22:24
  • \$\begingroup\$ ...Mathematica to the rescue, it has a "PrimalityProving" package which we can plug numbers into to check Try It Online! Might be worth including this link. \$\endgroup\$ – Jonathan Allan Mar 12 '18 at 23:36
  • \$\begingroup\$ Note that requiring unobservable behavior is discouraged. I suggest making the challenge a mathematical challenge and the score is calculated based on (the size of the formula) and (the output). (yes, non-code challenges are allowed) \$\endgroup\$ – user202729 Mar 13 '18 at 1:43
  • \$\begingroup\$ Quoting from that answer: "Non-observable requirements tend to be vague, subjective, or based on false assumptions about the properties of programming languages." -- Yes, you're assuming that every language have floating point support, or that every language have the functions you mentioned. \$\endgroup\$ – user202729 Mar 13 '18 at 1:48
  • 4
    \$\begingroup\$ (1) It's very hard to write prohibitions unambiguously, and I don't think you've succeeded. I don't know what exactly "Your number must be generated solely by applying various operations and functions to pi. Those functions cannot offset pi by anything other than another number derived from pi." allows and forbids. Can I convert pi to a string and take its length? Convert pi to a string, remove the decimal point, and convert back to an integer? Note: answering those two examples would not address the real problem. (2) "You must provide a" what? \$\endgroup\$ – Peter Taylor Mar 13 '18 at 8:55
  • \$\begingroup\$ I fell it's a busy-beaver \$\endgroup\$ – l4m2 Mar 15 '18 at 15:14
0
\$\begingroup\$

Relay Adder

Make a 32-bit full adder with relays.

A relay is here a gate with four inputs A, B, C and D, and output if A==B then C else D.

You'll be given two 32-bit numbers (totally 64 inputs), a carry flag, constant 0 and 1, sum up to 67 inputs; output 33 bits as the result

Smallest Gate count * gate depth win

TODO: add tags

\$\endgroup\$
  • 1
    \$\begingroup\$ Do you foresee any possible gains by making this a 32-bit adder? It feels to me like an 8-bit adder would be sufficiently complicated to allow golfing, without becoming as tedious. What do you mean by: "sup up to 67 inputs?" You also don't define what gate depth is. You also probably want to come up with a way for answers to post readable solutions. \$\endgroup\$ – FryAmTheEggman Mar 16 '18 at 20:20
0
\$\begingroup\$

Split the wagons!

In some variants of APL, a tacit function, or a train, consists of several functions next to each other. Your task is, given a train, to separate the different functions it consists of.

The symbols you will be given and their meanings are:

  • F: Function
  • O: Dyadic operator

Here is how functions are separated in extended Backus-Naur form:

function ::= {F O} F

Namely, a dyadic operator O accepts one function to its left and one F to its right, and the result is one function, for example F O F, F O F O F O F and F O F O F O F O F O F are all considered single functions for the purposes of this challenge. F F F O F O F F F O F, however, isn't a single function, and is split as (F, F, F O F O F, F, F O F).

You can get the symbols in any reasonable form, including a string, an array of integers, and any other kind of ordered collection able to hold at least 2 different elements. You can assume the input doesn't start or end with O, or contain two Os in a row. However, you must always use the same symbols, and you must only use two unique symbols. The output can be one of:

  • List of indices (0- or 1-based) which are the locations of the first symbol of each function. The index representing the first symbol of the input can be optionally omitted, as it's implied. The list doesn't have to be ordered.
  • List of indices (0- or 1-based) which are the locations of the last symbol of each function. The index representing the last symbol of the input can be optionally omitted, as it's implied. The list doesn't have to be ordered.
  • List of the individual functions. Every element of this list is a list subject to the same restrictions as the input, but not necessarily in the same format as the input. However, all elements must have the same format. The list has to be ordered.

Do not include empty partitions or duplicate, out-of-bounds or negative indices in the output.

Below are some test cases. F and O are used for F and O respectively, and the output is a list of the separated parts.

(empty) -> (empty)
F -> F
FOF -> FOF
FOFOFOF -> FOFOFOF
FOFOFOFOFOF -> FOFOFOFOFOF
FFFOFOFFFOF -> F F FOFOF F FOF
FFOFOFFOF -> F FOFOF FOF
FFFFF -> F F F F F
FOFF -> FOF F
FFFF -> F F F F
\$\endgroup\$
0
\$\begingroup\$

Ungolf my tinylisp code

I like golfing in tinylisp:

(d M(q((x)(i x(i(disp x)0(M x))0

But I also like posting explanations with nicely formatted code:

(d M
 (q
  ((x)
   (i x
    (i (disp x) 0 (M x))
    0))))

Can you help me generate the ungolfed code for my explanations?

The task

Given a line of tinylisp code, return or output the same code, formatted to the following specifications:

Input syntax

Tokens in tinylisp are (, ), or any string of one or more printable ASCII characters excluding parentheses or space. (I.e. the following regex: [()]|[^() ]+.) A non-parenthesis token is called an atom. Spaces are ignored, except insofar as they separate tokens.

For this challenge, the input code will consist of a single parenthesized list containing 0 or more items. The items in the list may be either (arbitrarily deeply nested) lists or single-token atoms (or a mixture). There may be spaces between items; spaces may also be omitted if they are not necessary to separate two adjacent atoms. Closing parentheses at the end of the expression may be omitted.

Some examples:

()
(1 2 3)
(1 2 3
(1 (2)
(1(2
(1((2))3
(((((xyz)))))
(((((

Bare atoms, like xyz, do not have to be handled for this challenge.

Nesting levels

We define a nesting level for a tinylisp expression as follows:

  • Atoms and the empty list () have a nesting level of 0.
  • A nonempty list has nesting level N+1, where N is the maximum nesting level of its items.

Some examples:

Expression   Nesting level
()           0
(1 2 3)      1
(1 2 ())     1
(1 (2))      2
(1 ((2)) 3)  3
((((()))))   4

How to ungolf

To ungolf a tinylisp expression, first supply any missing closing parentheses. Then, add newlines and whitespace according to the following rules:

  • For an expression of nesting level 0, do not add any whitespace.
  • For a list of nesting level 1 or 2, make sure the elements of the list are separated by a single space.
  • Lists of nesting level 3 or higher must be broken across multiple lines:
    • The first element of the list should be on the same line as the opening parenthesis, with no whitespace in between.
      • More specifically, the first element should begin on the same line. If the first item itself has nesting level 3 or higher, it will of course be spread over multiple lines itself.
    • IF the second element of the list has nesting level 0 or 1, place it on the same line as the first, with a space in between; otherwise, if its nesting level is 2 or higher, place it on its own line.
    • The third and subsequent elements of the list must each be on their own line.
  • Elements on their own line must be indented by a number of spaces equal to how deeply they are nested in the expression. The top-level list should be indented 0 spaces, its elements 1 space, their elements 2 spaces, etc.
  • Closing parentheses always go with the preceding list.

A worked example

Suppose this is our input:

(d E(q((n)(i(l n 2)(s 1 n)(E(s n 2

First, supply missing close-parens:

(d E(q((n)(i(l n 2)(s 1 n)(E(s n 2))))))

The outermost list has nesting level 6, so it must be split over multiple lines. Its second element is E (nesting level 0), so we keep that on the same line. We place the third element on its own line, indented by one space.

(d E
 (q((n)(i(l n 2)(s 1 n)(E(s n 2))))))

The next list has nesting level 5. Its second element has nesting level 4, so it goes on its own line, indented by two spaces.

(d E
 (q
  ((n)(i(l n 2)(s 1 n)(E(s n 2))))))

The next list has nesting level 4. Its second element has nesting level 3, so it goes on its own line, indented by three spaces.

(d E
 (q
  ((n)
   (i(l n 2)(s 1 n)(E(s n 2))))))

The next list has nesting level 3. Its second element has nesting level 1, so it goes on the same line as the first element, separated by a space. We place the third and fourth elements on their own lines, indented by four spaces.

(d E
 (q
  ((n)
   (i (l n 2)
    (s 1 n)
    (E(s n 2))))))

The list (s 1 n) has nesting level 1 and thus goes on one line. It has spaces between its elements, so it is already ungolfed.

The list (E(s n 2)) has nesting level 2 and thus goes on one line. It needs spaces between its elements.

Final result:

(d E
 (q
  ((n)
   (i (l n 2)
    (s 1 n)
    (E (s n 2))))))

Submission requirements

The input will always be a single (possibly nested) list. Thus, it will always start with (, never an atom. The number of opening parentheses will be greater than or equal to the number of closing parentheses. The input will not have any leading or trailing whitespace. The input will consist only of printable ASCII characters; in particular, it will not contain newlines or tabs.

Your solution may be a program or function. You may use any of the default I/O methods.

Input must be a string, a list of characters, or the nearest equivalent in your language.

Output may be a multiline string or a list of strings. It may optionally contain trailing spaces and/or a single trailing newline.

Examples

()
=>
()

(load library
=>
(load library)

(q(1 2
=>
(q (1 2))

(q((1)(2
=>
(q
 ((1) (2)))

(((((
=>
((((()))))

(d C(q((Q V)(i Q(i(l Q 0)0(i V(a(C(s Q(h V))V)(C Q(t V)))0))1
=>
(d C
 (q
  ((Q V)
   (i Q
    (i (l Q 0)
     0
     (i V
      (a
       (C
        (s Q (h V))
        V)
       (C Q (t V)))
      0))
    1))))

((q (g (c (c (q q) g) (c (c (q q) g) ())))) (q (g (c (c (q q) g) (c (c (q q) g) ())))))
=>
((q
  (g
   (c
    (c (q q) g)
    (c
     (c (q q) g)
     ()))))
 (q
  (g
   (c
    (c (q q) g)
    (c
     (c (q q) g)
     ())))))

(d f(q((x y z p)(i p(i(l p 0)(f(s x p)y(a z p)0)(i x(f(s x 1)(a y 1)z(s p 1))(i y(f x(s y 1)(a z 1)(s p 1))(f x y z 0))))(c x(c y(c z(
=>
(d f
 (q
  ((x y z p)
   (i p
    (i (l p 0)
     (f (s x p) y (a z p) 0)
     (i x
      (f (s x 1) (a y 1) z (s p 1))
      (i y
       (f x (s y 1) (a z 1) (s p 1))
       (f x y z 0))))
    (c x
     (c y (c z ())))))))

(def even? (lambda (num) (divides? 2 num)))
=>
(def even?
 (lambda (num) (divides? 2 num)))

(def odd? (lambda (num) (not (divides? 2 num))))
=>
(def odd?
 (lambda (num)
  (not (divides? 2 num))))

(def divides? (lambda (divisor multiple) (if (negative? divisor) (divides? (neg divisor) multiple) (if (negative? multiple) (divides? divisor (neg multiple)) (if (less? multiple divisor) (zero? multiple) (divides? divisor (sub2 multiple divisor)))))))
=>
(def divides?
 (lambda (divisor multiple)
  (if (negative? divisor)
   (divides? (neg divisor) multiple)
   (if (negative? multiple)
    (divides? divisor (neg multiple))
    (if (less? multiple divisor)
     (zero? multiple)
     (divides? divisor (sub2 multiple divisor)))))))

Reference solution

Here's a reference solution in Python 3: Try it online!

Similar questions

I haven't found an exact duplicate yet. The closest is:

but there are many significant differences between that question and this: input on multiple lines vs. one line; different criteria for when to insert newlines; having to add missing close-parens; having to handle (), etc.

Other related questions:

Sandbox questions

  • Is the TIO link enough for the reference solution, or should I put the code in the actual post?
  • Is there any existing question that's close enough to be a duplicate?
  • Which makes a better challenge: 1) input is a single expression on a single line, or 2) input is one or more expressions, each on its own line? #1 is the way it's currently written, and makes the challenge simpler; #2 would be more generally useful.
\$\endgroup\$
0
\$\begingroup\$

The Challenge

The goal is to write a complete program that prints out every possible tetris block made up of #.

The blocks must have an equal chance of printing in any order and must appear exactly once each. The blocks may have any rotation, rotation may be consistent between executions. No two blocks can be touching. All blocks must have settled on the "floor".

ValidExample.exe
                    #   #
## ###      ##   ## #   #
##  #  ####  ## ##  ## ##

TouchingExample.exe
      #
      #  # ##
## ####  #  # ##   ## 
##  # # ##  #  ## ##   

FloatingExample.exe
       #   #             
## ### ## ## #     # ####
##  #   # #  ### ###     

Use the language of your choice, lowest number of bytes wins

Questions

  • Is the wording clear enough?
  • Does the challenge meet the expectations for a challenge here?
  • What can I do to remove any ambiguity if there is any?
  • Is the formatting for the question / examples ok?
  • Would the challenge be "better" if the blocks had to be made up of their corresponding letter (IOJLZST)
\$\endgroup\$
  • \$\begingroup\$ This could be a dupe of codegolf.stackexchange.com/questions/2223/polyomino-generator \$\endgroup\$ – Sok Mar 21 '18 at 9:22
  • \$\begingroup\$ @someone is the new wording better? Replaced random order with a requirement that each order have equal odds. \$\endgroup\$ – Southpaw Mar 21 '18 at 10:02
  • 1
    \$\begingroup\$ I think it is. I don't think the blocks-made-of-letters is a good idea. \$\endgroup\$ – someone Mar 21 '18 at 10:04
  • \$\begingroup\$ @Sok No input, random order, only tetrominos, no floating restriction. Those seem to be the main differences. Are they enough to distinguish it? \$\endgroup\$ – Southpaw Mar 21 '18 at 10:05
0
\$\begingroup\$

Euler's Formula for the Quaternions

Euler's famous formula, e^iθ = cosθ + isinθ, can be used to calculate the exponential of arbitrary complex numbers: e^(a+ib) = e^a(cosb + isinb). That's cool and all, but what if we want to go even further?

The quaternions are an expansion of the complex numbers, where instead of just having i*i = -1, you have i*i = j*j = k*k = i*j*k = -1. Quaternions can be represented as a + bi + cj + dk or (s, v) where s is a scalar and v is a 3-Dimensional vector.

Euler's formula can be extended to the quaternions; for an arbitrary quaternion q = (s, v), e^q = e^s (cos|v|, (v/|v|)sin|v|), or, if q = a + bi + cj + dk and r = sqrt(b^2 + c^2 + d^2), e^q = e^a (cosr + (bi + cj + dk)(sinr)/r).

The task:

Write a program or function to exponentiate arbitrary quaternions. Built-ins are allowed. You may represent a quaternion in any sane manner.

Examples

Here, quaternions are represented as a four element array.

Input                                    Output (approximately)
0 3.14159 0 0                            -1
0 1 1 1                                  -0.160557 0.56986 0.56986 0.56986
1 2 3 4                                  1.69392 -0.78956 -1.18434 -1.57912
0.095767 0.601479 0.285658 0.926716      0.458433 0.527339 0.250447 0.812487
-0.654682 -0.925557 -0.409382 0.619391   0.194782 -0.37576 -0.166202 0.251462
\$\endgroup\$
  • 1
    \$\begingroup\$ There's a missing ) in e^q = e^a (cosr + (bi + cj + dk)(sinr)/r \$\endgroup\$ – Peter Taylor Mar 23 '18 at 21:53
0
\$\begingroup\$

Brainfuck Compiler!

Your goal is simple: Compile brainfuck to x86 assembly (NASM style), and do it with as small of a program as possible. You will be able to choose your compiler's input and output model, as long as the input is brainfuck code and the output is NASM style x86 assembly.

The brainfuck code should read from STDIN and output to STDOUT

Your compiler must be fully compliant with no extensions, and must support a infinite (to the max the computer's memory can sustain, running out of space on either end can be treated as a crash.) number of unsigned 8 bit cells both forward and back, with the tape Your output assembly should provide the exact same outputs for the corresponding inputs as the brainfuck code.

Your program's output must be compilable to a ELF binary that runs on Linux using the NASM compiler. Your program will be linked with libc, so you can use any function in the C library.

What is Brainfuck?

Brainfuck is a language with 8 instructions, and a tape memory model composed of an infinite amount of unsigned 8 bit (1 byte) cells. The pointer always points to one of those cells, executing its operations on the current cell. Each instruction is executed one at a time, and are as follows:

  • + Increment the current value under the pointer
  • - Decrement the current value under the pointer
  • . Output the value under the pointer as an ASCII character
  • , Get a character from input, and wait until one is received.
  • > Move the pointer to the right
  • < Move the pointer to the left
  • [ Jump to the matching ] if the value under the pointer is 0
  • ] Jump to the matching [ if the value under the pointer is not 0

If a [ doesn't have a matching ] (or vice versa), you can consider that undefined behavior.

Anything not listed here should be considered a NOP, or in the case of a empty program (EOF), simply a blank, noncrashing program.

Test cases.

To allow competition, and varying compilation results, my test cases will show what each test program should output.

Program:

"++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>."

Outputs (no input):

"Hello, World!"

Program:

+[,.]

Outputs:

"I am a test string" -> "I am a test string"

"Golfing is fun!" -> "Golfing is fun!"

Program:

`+[]`

Outputs:

Nothing. This program loops forever.

Program:

+[<+]

Outputs:

This program can be considered undefined behavior, because it will eventually run out of memory.

TODO

More test cases?

\$\endgroup\$
  • \$\begingroup\$ is the tape left bounded? also you should specify input behaviour on EOF \$\endgroup\$ – Destructible Lemon Mar 26 '18 at 22:05
  • \$\begingroup\$ "to the max the computer's memory can sustain" -- I feel that requirement quite problematic. For example, a submission using 16-bit cell (and only use the lower 8-bit, for whatever reason) will only be able to handle half as many cells as one using 8-bit cell. \$\endgroup\$ – user202729 Mar 27 '18 at 0:55
  • \$\begingroup\$ @user202729 I'd say a submission like that would be rare enough it's a non issue. \$\endgroup\$ – moonheart08 Mar 27 '18 at 1:40
  • \$\begingroup\$ @DestructibleLemon The tape is unbounded, both left and right. \$\endgroup\$ – moonheart08 Mar 27 '18 at 1:40
  • \$\begingroup\$ For a doubly infinite tape, to the max the computer's memory can sustain definitely needs more clarification. For example, if I "run out of space" on the right end, but still have space on the left one, do I need to shift things around? \$\endgroup\$ – Dennis Mar 27 '18 at 1:42
  • \$\begingroup\$ Alright. I'll fix that now. \$\endgroup\$ – moonheart08 Mar 27 '18 at 1:43
  • \$\begingroup\$ I think it's better to use 1 side unbounded, as that's usually the convention i think \$\endgroup\$ – Destructible Lemon Mar 27 '18 at 2:02
0
\$\begingroup\$

Interpret pseudocode

Wikipedia says pseudocode

is intended for human reading rather than machine reading.

and

A program in pseudocode is not an executable program.

I don't care.

Make a pseudocode interpreter that can run pseudocode that fits the rules described below*. This is based on the IB pseudocode guide, but it is simplified quite a bit to make it fit for the challenge.


Pseudocode specifications

This is a simplified pseudocode to make the challenge less tedious. The pseudocode language has no strings, no arrays, no classes, no methods, and no variables other than integers.

Basic syntax

Comments that start at // and end at a newline (like java one-line comments). // is not necessarily followed by a space, and the comment may be empty. Example:

A = 2 + 3 // I can't write five because my keyboard is broken

Statements are separated by newlines. Lines may be empty (without statements). The exact number of spaces doesn't matter, and spaces are not required. The language is case sensitive.

Variables

All variables are global, and can be accessed anywhere. They do not need to be declared. To keep things simple, all variables can be assumed to be integers. All variable names are UPPERCASE, and consist only of letters. Your program should at least handle integers from -256 to 256. A wider range is not a requirement.

Variables are assigned values using this syntax:

VARIABLE = Expression

Where VARIABLE can be any uppercase name and expression can be any integer expression, as discussed below.

Examples:

A = 5
B = A + 3
NUMBER = A * B

Expressions

An expression can be:

  • An integer, like 42
  • A variable, like NUMBER
  • A binary operation on two other expressions, like NUMBER + 5. There are only four operations: +, -, *, /. Division rounds integers down.

Expressions can be surrounded by parentheses to indicate that they need to be evaluated first. To keep things simple, all expressions are evaluated from left to right no matter what the operations are (unless there are parentheses that specify otherwise), so

A = 2 - RM * 9 + 3 / NUMBER
B = 1 + 2 * (3 - 4) / 6

is equivalent to

A = (((2 - RM) * 9) + 3) / NUMBER
B = ((1 + 2) * (3 - 4)) / 6

Boolean expressions

Boolean expressions can compare two expressions using == (equality), != (not equal to), < (less than), and > (greater than). They are only used for control flow, as discussed below (there are no boolean variables).

Control flow

There are four types of control flow. They can be infinitely nested in all combinations.

If

if (booleanExpression) then
    // statements (discussed below)
endif

If-else

if (booleanExpression) then
    // statements (discussed below)
else
    // other statements
endif

Loop while

loop while (booleanExpression)
    // do stuff
endloop

Where booleanExpressions are boolean expressions. The ifs work the same as in normal programming languages. The while loop is a simple while loop.

The booleanExpressions will always be surrounded by (). The pseudocode is very flexible with spaces, and any number of spaces is valid.

Loop for

loop VARIABLE from Expression1 to Expression2
    // things to do over and over again
end loop

Where Expression1 and Expression2 are expressions that are evaluated before the loop begins and their values are stored until the loop finishes. The content of the loop is executed for every integer from the result of Expression1 to that of Expression1, inclusive. At every iteration, the index variable (VARIABLE in this case) is updated.

Example:

loop I from 3 to 5
    output(I)
endloop

Outputs:

3
4
5

Statements

Output

output(Expression) outputs the evaluated expression. It's like println in programming languages. So:

output(1+1)

prints 2, followed by a newline.

output() with no arguments should print a newline.

Other statements

If the interpreter encounters any other statement that looks like a method call with no arguments, it should pretend it's executing it. For example,

lightsoff()
gohome()

should print (together with a newline):

executing lightsoff
executing gohome

In other words, executing [Method name] should be printed. All statements will be lowercase and will consist entirely of letters.

Keywords cannot be statements. You do not have to deal with the following (it will not appear in the pseudocode): - if() - endif() - loop() - while() - etc.

However, statements that start with keywords are valid. For example, loophole() should print executing loophole, even though loop() itself is not valid.


Challenge rules

  • Your program should take a string as input. It can also take something equivalent, like an array of characters. But you can't take an array of strings; your program must itself separate the lines and tokens. You can also take a file as input.
  • Your program should print the output of the pseudocode in any reasonable form.
  • No standard loopholes.
  • There are no restrictions on what your program should do when given invalid pseudocode.
  • This is code golf. The shortest code in bytes wins.

Example output

1

A = 3
output(A) // prints 3
B = 4 + A * 2
output(B)
helloworld()
output(A + B + 1 * 3)

Should give:

3
14
executing helloworld
54

2

loop NUM from 2 to 20 // cycle through possible prime numbers
    COUNT = 0
    loop DIV from 2 to NUM // cycle through possible divisors
        if(NUM/DIV*DIV == NUM) then // if the number is exactly divisible
            COUNT = COUNT + 1
        endif
    endloop
    if (COUNT == 2) then // if number is prime
        output(NUM)
    endif
endloop

Should give:

2
3
5
7
11
13
17
19

3

Tricky cases that your interpreter should handle:

// empty comment:
//
// empty line:

    // more comment testing // ///
////

if     (3<4) then
    endoftheworld() // a statement
    ifff()
    endifnot()
    // endif in a comment doesn't count
endif
// loops can be empty:
loop I from 0 to 10
endloop
output(I) // variables are global
if(1<2)
    if(3<4) // nesting is ok
        ok()
    endif
endif
// spacing doesn't matter:
output   (2+   8   - 1   )
loop             while(2<1)
    neverhappened()
endloop

Should output:

executing endoftheworld
executing ifff
executing endifnot
10
excecuting ok
9

*Technically, once pseudocode follows rules as strict as those described here, it is arguably not pseudocode anymore. Wikipedia says it's called skeleton code.


Any suggestions?

I double-checked all the specifications, but if anything seems reasonably unclear, please let me know.

\$\endgroup\$
  • \$\begingroup\$ Actually that's because the challenge is uninteresting. \$\endgroup\$ – Akangka May 3 '18 at 2:11
  • \$\begingroup\$ @Akangka thanks for the feedback. How do you think it could be made more interesting? \$\endgroup\$ – R.M May 3 '18 at 16:47
  • \$\begingroup\$ Unfortunately, there is nothing to improve. You have to find other challenge. Also, it is not pseudo-code. \$\endgroup\$ – Akangka May 4 '18 at 3:03
  • \$\begingroup\$ @Ok, thanks. I'll try to think of something. Also, read the *note. :) \$\endgroup\$ – R.M May 5 '18 at 19:39
0
\$\begingroup\$

Fill a virtual World Cup Sticker Album

As the World Cup is due to kick off (pun intended), the inevitable sticker book comes along as well.

According to this BBC article , at a cost of £0.80 for a pack of 5 and with a total of 682 stickers needed to complete the book it could cost up to £700 or more to fill, taking duplicates into account.

Write the shortest program possible to

  • Buy a virtual pack of stickers (at 0.80 per pack), which will be 5 random numbers between 1 and 682 (or 0 and 681)
  • Repeat until all numbers have been picked at least once
  • Output how many packs were bought and a final cost.

Output should be in the format "Bought number packets at cost of number"

Sample un-golfed Python 2 code

import random
total = 682
remain = total
cost = 0.8
spend = 0.0
packs = 0
got = [0 for i in range(total)]

while remain > 0:
    # buy a packet of stickers
    for i in range(5):
        got[random.randint(0,total-1)] += 1
    spend += cost
    remain = got.count(0)
    packs += 1

print 'Bought %d packs at cost of %.2f' % (packs,spend)

Sample output

Bought 865 packs at cost of 692.00

QUESTION

  • Writing the Python script for myself is what made me think of this question - does it help to include it, or clutter the page? (This is my first attempt at a question here)
\$\endgroup\$
  • \$\begingroup\$ You need to flesh out what we're doing? Your code isn't super greatly commented and I'm not sure how much a pack costs, how many packs are needed. etc. should it always output the same amount? \$\endgroup\$ – Rɪᴋᴇʀ Mar 29 '18 at 20:57
  • \$\begingroup\$ What does "simulate" mean here? Beware the curse of the non-observable requirement. \$\endgroup\$ – Peter Taylor Mar 29 '18 at 22:28
0
\$\begingroup\$

Navigate my Taxi

Introduction

Taxi is an esoteric programming language simulating a taxi. You can pick up passengers (values) and drop them at special places to modify them. For example, this program squares the input. The places are all in Townsburg:

Map of Townsburg

To travel from one place to another, you have to tell your taxi where to go:

Go to the Post Office: west 1st left, 1st right, 1st left.

And you need gas to drive, your car gets 18 miles per gallon. So it's best to find the shortest possible way between two places. That leads me to ...

The Challenge

Input

You get an incomplete Taxi program, consisting of the following statements:

  • Pickup a[nother] passenger going to [the] <place>.: Pickup a passenger, you may ignore it for this challenge
  • "<string>" is waiting at [the] Writer's Depot. / <number> is waiting at [the] Starchild Numerology.: Create passengers, you may ignore this, too
  • Go to [the] <place>.: Go to a place, you have to add directions (see below)
  • [<label>]: A label for jumping, you have to parse those to know where the taxi is. They don't do anything if passed. You can assume that you are in the same location, regardless of where you reach the label from.
  • Switch to plan "<label>".: Unconditional jump, follow these to know where the taxi is
  • Switch to plan "<label>" if no one is waiting.: Conditional jump, you have to support both ways

If the input program contains anything else, you may do anything you want (undefined behaviour).

Conversion

Following all jumping instructions, you have to add directions to the Go to commands. It has to be the shortest possible way (I want to save gas!)

Directions consist of a cardinal direction (north, east, south, west or NESW) and a comma-separated list of turns, consisting of a number (1st 2nd 3rd or 1 2 3) and left/L or right/R.

Examples:

Go to the Post Office: west 1st left, 1st right, 1st left.
Go to Post Office: W 1 L, 1 R, 1 L.
Go to Tom's Trims: N.

The cardinal directions do have the following meanings (xstart means x pos of the starting point, yend means y pos of the next corner/intersection/place):

  • north: ystart > yend
  • south: ystart < yend
  • west: xstart > xend
  • east: xstart < xend

(Coordinates from the top left corner)

Here is a list of all intersections/corners/places/streets, extracted from the interpreter.

Some additional info:

  • The taxi starts at the Taxi Garage.
  • If the taxi reaches the Taxi Garage, the program ends.
  • If the program reaches its end and the taxi is not in the Taxi Garage, that's an error, so you'll have to add 'Go to the Taxi Garage: ...' at the end if it's missing.

Output

  • Your program or function has to output a valid Taxi program (online interpreter) or a list of instructions (which, when concatenated, form a valid Taxi program)
  • You may use the long (north 1st left) or short (N 1 L) syntax.
  • The ways chosen have to be the shortest possible (droven distance, i.e. sum of Euclidian distances between any two consecutive points on your way)
  • If there are multiple equally long ways, you can use any of them

Additional Rules

  • Standard loopholes are forbidden
  • Your score is the number of bytes in your program
  • Lowest score wins

Test Cases

TODO

  • Is any part of the specs confusing?
  • Should I not input a full program, but just start and destination?
  • Should I add the map in some format as an additional input?
\$\endgroup\$
  • \$\begingroup\$ Thanks for using the sandbox, but I'm sorry that it's not very active. We decided that "typical desktop computer" is not clear enough, so you should change it. \$\endgroup\$ – user202729 Feb 24 '18 at 14:54
  • \$\begingroup\$ What is "shortest" measured in? Euclidean distance? What if there are multiple equally long paths? \$\endgroup\$ – user202729 Feb 24 '18 at 15:09
  • \$\begingroup\$ @user202729 Edit: time is now on TIO, distance is sum of Euclidian distances between any two consecutive points on the way. I'm thinking about writing a program that calculates the distance \$\endgroup\$ – wastl Feb 24 '18 at 16:37
  • \$\begingroup\$ TIO is still not usable for time-related things. See codegolf.meta.stackexchange.com/questions/12707/… . \$\endgroup\$ – user202729 Feb 24 '18 at 16:39
  • \$\begingroup\$ Is it guaranteed that the taxi will be in the same location regardless of how we reach a label? \$\endgroup\$ – Nitrodon Feb 24 '18 at 17:08
  • \$\begingroup\$ @user202729 Ok, removed time limit \$\endgroup\$ – wastl Feb 24 '18 at 17:09
  • \$\begingroup\$ @Nitrodon finally, I got what you meant. Sure. Although theoretically, if both points lie on one street, one could do that ... (I would not recommend it) \$\endgroup\$ – wastl Mar 16 '18 at 23:02
0
\$\begingroup\$

Left Turn at Euqreuqebla

Write a quine, according to the standard definition of a quine, that outputs itself when executed. However, when your code is reversed it should output each character of your source code separated by a newline instead.


Example

If your program was:

ABCDEFGH
IJKLMNOP

The unedited program should output:

ABCDEFGH
IJKLMNOP

However the reverse of the program should output:

A
B
C
D
E
F
G
H


I
J
K
L
M
N
O
P

Rules:

  • Outputting a single trailing or preceding newline is acceptable.
  • If your code contains newlines, they do not require rotation, treat them regularly.
  • Standard loopholes are disallowed.
  • Ensure that your "quine" is actually a quine.
  • This is , ; lowest byte-count wins.
\$\endgroup\$
  • \$\begingroup\$ an example with code with newlines would be useful (as those I'd naturally rotate 90 degrees :p) \$\endgroup\$ – dzaima Mar 29 '18 at 21:04
  • \$\begingroup\$ @dzaima which way do you think is better, not requiring "natural rotation" to support Java and the like better? Or supporting natural rotation for the esolangs? \$\endgroup\$ – Magic Octopus Urn Mar 29 '18 at 21:07
  • \$\begingroup\$ a thing to consider is that if natural rotation would be required, everyone would just try to keep everything in a single line to make the challenge way easier \$\endgroup\$ – dzaima Mar 29 '18 at 21:10
  • \$\begingroup\$ @dzaima I could make it optional? I don't see that hurting the challenge too much either way to be honest, it just lets languages to what they do best. \$\endgroup\$ – Magic Octopus Urn Mar 29 '18 at 21:11
  • \$\begingroup\$ that'd be a good compromise if there's no better solution \$\endgroup\$ – dzaima Mar 29 '18 at 21:12
  • \$\begingroup\$ @dzaima ehhh? decent? \$\endgroup\$ – Magic Octopus Urn Mar 29 '18 at 21:17
  • \$\begingroup\$ usually it's bad to have multiple ways to solve the challenge, though here it's pretty easy to tell which method's gonna be the easiest \$\endgroup\$ – dzaima Mar 29 '18 at 21:18
  • \$\begingroup\$ @dzaima exactly, that's why I want to allow it to see if SOGL or some other language with crazy flipping commands can do this the "harder" way. \$\endgroup\$ – Magic Octopus Urn Mar 29 '18 at 21:19
  • \$\begingroup\$ If you're going for Albuquerque spelled backwards, that's not how it's spelled. \$\endgroup\$ – AdmBorkBork Mar 30 '18 at 13:25
  • \$\begingroup\$ Shouldn't the example have a gap of three newlines between the H and the I, not two? \$\endgroup\$ – Aidan F. Pierce Apr 1 '18 at 0:00
  • \$\begingroup\$ @AidanF.Pierce great catch. \$\endgroup\$ – Magic Octopus Urn Apr 2 '18 at 11:50
0
\$\begingroup\$

Common Logic Gates

Given positive integer n, make a common n-to-1 gate with fewest input, i.e. make a function f: {0,1}k ↦ {0,1} with smallest k that, for each function g: {0,1}n ↦ {0,1}, there exists {ak}, such that each element ai in the sequence map to one of 0, 1, x1, x2, x3, ..., xn, satisfying that, for each {xn}, g(x1, x2, x3, ..., xn) = f(a1, a2, a3, ..., an).

Samples:

To make a common 1-to-1 gate, your circuit must take at least 2 input:

f(A,B) = A XOR B

For a buffer gate (g = x1 ↦ x1), let A=0 and B=Input (a1 = 0, a2 = x1); for a not gate (g = x1 ↦ ¬x1) , let A=1 and B=Input (a1 = 1, a2 = x1).

Alternatively, you can use f(A,B) = A AND NOT B. For a buffer gate, let B=0 and A=Input; for a not gate, let A=1 and B=Input.

To make a common 2-to-1 gate, the circuit must take at least 4 input bits: (The two inputs are represented as a and b)

f(A,B,C,D) = ((A AND B) OR (C AND NOT B)) XOR D

(ab)
00 01 10 11 A B C D
0  0  0  1  a b 0 0
0  0  1  0  0 b a 0
0  1  1  0  a a a b
0  1  1  1  1 b a 0
1  0  0  0  1 b a 1
1  0  0  1  0 a 1 b
1  1  0  1  0 b a 1
1  1  1  0  a b 0 1

Output can be an boolean expression with reasonable logic gates, or just the output corresponding to all possible input of the n-to-1 function f (the truth table of f). If there are more than one possible functions, you can output any of them.

Shortest code in bytes win.

Code that matches the requirement:

function solve(n) { // n positive int
    var res = [], tmp=[], inmap=[], need=[];
    for (var i=1; ; i++) {
        for (var _res=0; _res<2**(2**i); _res++) {
            var valid = 1;
            for (var j=0; j<2**i; j++)
                tmp[j] = Math.floor(_res/2**j)%2;
            for (var _need=0; _need<2**(2**n); _need++) {
                for (var j=0; j<2**n; j++) 
                    need[j] = Math.floor(_need/2**j)%2;
                var valid2 = 0;
                for (var _inmap=0; _inmap<(n+2)**i; _inmap++) {
                    var valid3 = 1;
                    for (var j=0; j<i; j++) 
                        inmap[j] = Math.floor(_inmap/(n+2)**j)%(n+2) - 1;
                    for (var j=0; j<2**n; j++) {
                        var bits = 0;
                        for (var k=0; k<i; k++) {
                            if (inmap[k]==-1 || (inmap[k] && (j>>(inmap[k]-1))%2))
                                bits |= 1 << k;
                        }
                        if (tmp[bits] != need[j]) 
                            valid3 = 0;
                    }
                    valid2 |= valid3;
                }
                if (!valid2) valid = 0;
            }
            if (valid) 
                res.push (tmp.slice());
        }
        if (res.length) 
            return res[AnyNonNegativeIntegerLessThan(res.length)];
        // binary index input
    }
}

function AnyNonNegativeIntegerLessThan(x) { if(R>=x) throw ("end"); return R;}
for (R=0; ; R++) { console.log (solve(1)); }

\$\endgroup\$
  • \$\begingroup\$ You don't define what an n-to-1 gate is anywhere in your question. \$\endgroup\$ – Sriotchilism O'Zaic Mar 27 '18 at 1:00
  • \$\begingroup\$ @user202729 @user56656 n-to-1 gate means a gate with n input and 1 output. common n-to-1 logic gate mean a logic gate that can be used to replace any n-to-1 gate with some proper wiring. You can treat a logic gate as a ROM(so you can decide for each input what the output is) \$\endgroup\$ – l4m2 Mar 27 '18 at 1:15
  • \$\begingroup\$ Output gates or ROM \$\endgroup\$ – l4m2 Mar 27 '18 at 1:25
  • \$\begingroup\$ You should put the definitions in the challenge. "that can be used to replace any n-to-1 gate with some proper wiring" is still not very clear, you should define more carefully what you mean by proper wiring. \$\endgroup\$ – Sriotchilism O'Zaic Mar 27 '18 at 3:22
  • \$\begingroup\$ I assume you mean functions g: {0,1}^n -> {0,1}, right? Why do you specify x_0 and x_-1? Shouldn't x just be a vector with indices 1,2,3,...,n? \$\endgroup\$ – flawr Mar 27 '18 at 14:07
  • \$\begingroup\$ Is {a_k} just a subset of {1,2,3,...,n}? Or can we have a_1=a_2=a_3=1 for example? \$\endgroup\$ – flawr Mar 27 '18 at 14:09
  • \$\begingroup\$ {a_k} seems not a multiset. It should be an array or say a sequence of numbers \$\endgroup\$ – l4m2 Mar 27 '18 at 14:43
  • \$\begingroup\$ So you're asking for something which outputs answers to codegolf.stackexchange.com/q/24983/194 ? \$\endgroup\$ – Peter Taylor Mar 28 '18 at 11:33
  • \$\begingroup\$ @PeterTaylor No. it requires to use NAND gate to make up one circult that do the thing. Also 24983 is a 1-of-4 (74LS153), not a 4-to-1 gate common 2-to-1 \$\endgroup\$ – l4m2 Mar 28 '18 at 12:41
  • \$\begingroup\$ (+) Any reason for downvoting? Downvoting in the sandbox indicates that the challenge is incomplete, if you don't leave a comment the OP can't know what is wrong. \$\endgroup\$ – user202729 Mar 29 '18 at 4:48
  • \$\begingroup\$ @user202729, there are already comments indicating that this question is going to attract close votes as unclear if it's posted to main in the current state. \$\endgroup\$ – Peter Taylor Mar 29 '18 at 10:59
  • \$\begingroup\$ @user56656 Are the issues fixed now? \$\endgroup\$ – user202729 Mar 31 '18 at 15:16
  • \$\begingroup\$ @flawr Are the issues fixed now? \$\endgroup\$ – user202729 Mar 31 '18 at 15:16
  • 1
    \$\begingroup\$ No I still think the explanation is quite bad and the notation is not very clear \$\endgroup\$ – flawr Mar 31 '18 at 16:15
  • \$\begingroup\$ A reference implementation is no substitute for a clear specification. The first paragraph is where you need to focus your efforts. \$\endgroup\$ – Peter Taylor Mar 31 '18 at 19:32

You must log in to answer this question.

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