572
\$\begingroup\$

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

Sandbox FAQ

Posting

To post to the sandbox, scroll to the bottom of this page and click "Answer This Question". Click "OK" when it asks if you really want to add another answer.

Write your challenge just as you would when actually posting it, though you can optionally add a title at the top. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it.

When you think your challenge is ready for the public, go ahead and post it, and replace the post here with a link to the challenge and delete the sandbox post.

Discussion

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

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

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

If you think one of your posts requires more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended! Be patient and try not to nag people though, you might have to ask multiple times.

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

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

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

\$\endgroup\$
0

4670 Answers 4670

1
69 70
71
72 73
156
1
\$\begingroup\$

Broken mouse

This is just an idea, I have not elaborated it.

My mouse accidentally fell to the ground, and now there is a double click for each of my single click(which makes window-closing very hard to do). :(

Most computer screens have a higher resolution ratio than 16x12, but let's assume that my computer screen has a 16x12 resolution ratio.

Example: A Window looks like this:

0-----OX
|      |
--------

The number 0 is the indicator of the window. O is a dragging button that allows windows to be moved. X is a closing button that closes the window. (You can not resize windows.) Assume that there is a window below that window looking like this:

1-----OX
|      |
--------

If I click X, I will close both windows. However, what should(or must, if appropriate) I do if I only want to close the first window?

I can move my mouse to the O tab and drag the window around by using mousedown. After 1 drag to the right:

10-----OX
||      |
---------

Now I can click the X to close the window 0 after I click the O button again to remove the dragging effect. (Note that there is the window "1" below that window.)

Wait, I changed my mind and wanted to close the window 1. What should I do?

I should click the number 1; then, the window 1 goes to the top and the X button shows. Now I can click the X button to close the 1 window.

For reference, this is the TUI commands I used(when the mouse starts at 0x0):

0-----O
>>>>>>.>.<<<<<<<.>>>>>>.

What should I do if I want to close the windows that I specified? (Output the TUI instructions.) (Your score is -(code length + output); you want to keep your score as high as possible.)

TUI Instructions

  • ^v<>: Move the mouse up, down, left, or right
  • .: Mouse down+mouse up (i.e. click)
\$\endgroup\$
7
  • 3
    \$\begingroup\$ What does the input look like? \$\endgroup\$ Aug 12, 2019 at 21:35
  • \$\begingroup\$ I have no idea. \$\endgroup\$
    – user85052
    Aug 13, 2019 at 4:36
  • \$\begingroup\$ Output for what (set of) input? \$\endgroup\$
    – DELETE_ME
    Aug 16, 2019 at 4:49
  • \$\begingroup\$ @The Obviously a list of coordinates of the input windows... \$\endgroup\$
    – DELETE_ME
    Aug 16, 2019 at 4:49
  • \$\begingroup\$ Is this always possible? If the frontmost window is as large as the screen, by dragging the "O" you cannot make the lower-leftmost cell appear. What if the "X" of the desired window is there? \$\endgroup\$
    – DELETE_ME
    Aug 16, 2019 at 4:51
  • \$\begingroup\$ I guess I will make the windows draggable for at least 1 direction and at most 4 directions. (The window is always smaller than the screen.) \$\endgroup\$
    – user85052
    Aug 16, 2019 at 4:59
  • \$\begingroup\$ Oh I see, otherwise output impossible to avoid this situation. \$\endgroup\$
    – user85052
    Aug 16, 2019 at 7:00
1
\$\begingroup\$

tags: "code-golf", "ellipse", "geometry"

Sandbox Questions

Is this a proper code-golf question?

A major challenge is: How to verify the computed shape? Numerical verification is impossible, since there are infinitely many possible solutions. Is there an easy way to plot xy-data online, or should I provide a script myself? Your suggestions are greatly appreciated.

edit:

after 3 days of being posted here in the sandbox, I still have no clear answer to the above question. I therefore propose to ask participants to include their own plot in the answer, which they can make with whatever plotting tool they wish. If people feel inclined to cheating, they only fool themselves, don't they?

Introduction

To create a circle you can stick a nail in a piece of board, put a loop of string around it and hold it taut with a pencil at the other end. Move the pencil and you get a circle. If you put the loop of string around two nails and move your pencil, you create an ellipse. But what happens if you use three nails, or four, or ten perhaps? It's gonna get ugly soon if you try this in real life, and that's where computers come in handy.

Challenge

Your task is to write a program or function that accepts two inputs:

  • A list of (x,y) coordinates (viz. the nails), of arbitrary length>2.
  • The length of the rope.

And produces the following output:

  • A list of coordinates of the poly-oval, which could be fed to a plotting-tool. Plotting the output does not need to be part of your program!

References

Details:

  • You may assume that the input coordinates form a convex shape (no inner points on which your program could crash).

  • As coordinates, you can use tuples, pairs, complex numbers or even two separate scalars if you like.

  • The output resolution (ie. the length of the list) is not so important, but is should give a fair representation of the real curve. In my experience, you'll need between 100 and 1000 points. For smaller rope lengths, you need an even higher resolution.

Rules and scoring:

  • This is code-golf, so shortest answer in bytes for each language wins.
  • Standard rules and default I/O rules apply.
  • Loopholes forbidden (of course).

Example Input and Output

Provide at least one example input and output. Make sure they match your own description of what the input should look like.

Input can be any of the following:

P = [2+0j, -2+1j, -2-1j]

P = [(2,0),(-2,1),(-2,-1)]

X = [2,-2,-2] and Y = [0,1,-1]

Output should be in one of the following forms:

[0.862+1.591j, 0.703+1.668j, 0.527+1.729j, ...]

[(0.862,1.591), (0.703,1.668), (0.527,1.729), ...]

X = [0.862, 0.703, 0.527, ...], Y = [1.591, 1.668, 1.729, ...]

\$\endgroup\$
4
  • \$\begingroup\$ "You may assume that the input coordinates form a concave shape" I think you mean convex. This is a very helpful assumption though, as you would otherwise need to calculate the convex hull before doing anything interesting. \$\endgroup\$
    – Beefster
    Aug 13, 2019 at 22:05
  • 2
    \$\begingroup\$ "How to verify the computed shape?" - Two possibilities: 1. don't worry about it and make this a graphical output challenge ; 2. specify a starting angle and angle step and require accuracy to within 2 decimal points. ... I personally would go with #1 \$\endgroup\$
    – Beefster
    Aug 13, 2019 at 22:11
  • \$\begingroup\$ @Beefster Thank you, I did indeed mean convex. As per your second comment, frankly I am not interested in how to write short plotting code, I am interested in the calculation itself. But thanks a lot for your help, I think I will post in a couple of days:) \$\endgroup\$
    – Hermen
    Aug 14, 2019 at 16:28
  • \$\begingroup\$ One solution would be to specify a pixel resolution and require that the density of output points should be sufficient that the maximum separation between the curve and the piecewise linear output should be half a pixel. Then you can compare the output with the output of a reference implementation by looking for separations of more than one pixel. \$\endgroup\$ Aug 20, 2019 at 15:55
1
\$\begingroup\$

I mainly need help with scoring as I want to encourage use of esolangs.

I also would like to know how to improve the answer-ability of this question in languages that don't specifically have defined functions


Church booleans

A church boolean is a function that returns x for true and y for false where x is the first argument to the function and y is the second argument to the function. Further functions can be composed from these functions which represent the and not or and xor logical operations.

Challange

Construct the church booleans and and not or and xor church gates in a language of your choice.

Scoring

The total length of all of the code required to make church true and false in your language and the and not or and xor church gates excluding the functions name. (for example, false=lambda x,y:y in python would be 12 bytes). You can reuse these names later in your code.

Pseudo code Examples:

true(x, y) -> x
false(x, y) -> y
and(true, true)(x, y) -> x
and(true, false)(x, y) -> y
# ... etc
\$\endgroup\$
6
  • \$\begingroup\$ instead of functions, you should also accept full programs. I also don't understand what your examples represent(is and supposed to be a curried function?) \$\endgroup\$ Aug 16, 2019 at 20:43
  • \$\begingroup\$ @SuperStormer and returns a church boolean which is a function which is then called with variables x and y and returns x or y based on whether that function is the true or false church boolean. In the examples I was just trying to get across the nature of church gates and church booleans without answering the question. I wanted to break it up into discrete functions for readability and to ensure that the question is actually being answered correctly \$\endgroup\$ Aug 16, 2019 at 20:46
  • \$\begingroup\$ I'm not really sure it's possible to make this work for all languages, except by just operating on lambda calculus expressions with no actual significance within the language, but that aside you definitely don't need anything additional to encourage esolangs on this site! \$\endgroup\$ Aug 16, 2019 at 20:55
  • 1
    \$\begingroup\$ @UnrelatedString as far as fit for this site goes do you think there is anything I should add to improve the question? \$\endgroup\$ Aug 16, 2019 at 20:58
  • 2
    \$\begingroup\$ Esoteric languages usually don't support function as first-order object very well, but they usually have eval so it may work using some "function" representation. \$\endgroup\$
    – DELETE_ME
    Aug 17, 2019 at 6:46
  • \$\begingroup\$ Otherwise I don't think there is a problem. \$\endgroup\$
    – DELETE_ME
    Aug 17, 2019 at 6:46
1
\$\begingroup\$

Distant Programs

Create a program that, when run, prints "Do you still love me?" with or without a newline at the end.

Your score is the Levenshtein distance to the closest non-erroring program (the non-erroring program doesn't have to do anything, although it might), and you want the largest score. Ties are broken by whichever code is shorter, in bytes.

Your program can read it's own source code, through the filesystem or otherwise. If your program must have a specific name, the length of that name should be included in your byte count.

Notes:

  • Compiler warnings are not counted as errors for this challenge.
  • An erroring program can output, frobricate, do anything as long as it eventually errors.

Notes for the sandbox:

  • Is the specification clear?
  • Is it possible to create a solution that can simply be repeated to get any arbitrary score? If so it would pretty much ruin the challenge as it is, and I think it should be possible but I can't get it to work.
  • What tags would this use?
\$\endgroup\$
3
  • \$\begingroup\$ I think it should be possible to get arbitrary scores using quining techniques and cryptographic hash verification. \$\endgroup\$ Aug 20, 2019 at 15:41
  • 1
    \$\begingroup\$ In addition to what Peter said, I think there is a clarity problem in defining precisely what counts as an error. \$\endgroup\$ Aug 20, 2019 at 19:33
  • \$\begingroup\$ @FryAmTheEggman I was going top copy my definition of "error" from codegolf.stackexchange.com/questions/63433 but to my surprise there isn't one. Honestly I'm not sure how exactly to define "error". \$\endgroup\$
    – Shelvacu
    Aug 23, 2019 at 23:03
1
\$\begingroup\$

Solve All the Rubik's Cubes!

I want to solve a Rubik's Cube. Unfortunately, I am blind, and my friend doesn't know how to solve a Rubik's Cube, so I just make one move at a time and ask my friend if it is solved. This generally doesn't work very well, so I would like to know a specific thing I could do to increase my chances of eventually fixing it. Also, I don't like memorizing things, so please keep your solution as short and simple as possible.

Rules

  • I cannot see the cube or anything about it.
  • The only thing my friend will tell me about the cube is whether or not it is solved.
  • My friend and I are fully willing to wait until the heat death of the universe to solve this, if necessary.
  • I don't have a great memory, so keep your instructions as short as possible.
  • I can feel around the cube enough to turn whatever face you tell me to turn in whatever direction.
  • I can turn the cube in my hands.
  • I can memorize anything you give me, but I won't like it.

Solution Format

Give me a description of turns to do on my Rubik's Cube, to be repeated endlessly (or until I solve it).

F: Turn the front face clockwise
B: Turn the back face clockwise
R: Turn the right face clockwise
L: Turn the left face clockwise
U: Turn the top face clockwise
D: Turn the top face clockwise

x: Turn the cube so the top face becomes the front
y: Turn the cube so the left face becomes the front
z: Turn the cube so the left face becomes the top

' can be appended to any of these commands to make them go in the opposite direction.

Also, to make things easier, you can give me inner repetitions. Write these as

{...commands...}*4

where 4 is the number of times it is repeated. Inner repetitions can be nested.

Scoring

Non-memorability:

  • Each turn gives one point.
  • For nested repetitions, double the point value of everything inside the repetition and add the number of times I do it.

Effectiveness:

  • Any sequence of moves on a Rubik's cube will eventually return to the initial state. The effectiveness is how many turns are required before this happens (roughly equivalent to how many states it passes through).

Total score = non-memorability / effectiveness

Solutions that are easier to remember are probably better than solutions that are hard to remember but will be solved.

Lowest total score wins.

Questions:

  • Will people actually answer this question?
  • Is the specification clear enough?
  • This is my first question. Is there anything else I need to consider before posting?
\$\endgroup\$
4
  • \$\begingroup\$ This sounds like an interesting question, however it may actually be a better fit for puzzling.stackexchange.com. Either way, it's not entirely clear what the end goal is; Am I trying to find the series of moves that will make it likely for the cube to be solved quickly (on heatdeath timescale), or am I looking for a series of moves that garuntees it will be solved eventually? Also see (similar but not duplicates I'm pretty sure) math.stackexchange.com/questions/1694536 and math.stackexchange.com/questions/184760 \$\endgroup\$
    – Shelvacu
    Aug 19, 2019 at 10:36
  • \$\begingroup\$ I'm looking for something easy to remember, with a reasonable chance of eventually solving it. This doesn't have a definite answer and should focus more on space optimization (golfing) (the existing Hamiltonian Circuit is probably very difficult to remember and would score poorly), so it might not fit as well on Puzzling. \$\endgroup\$
    – Hiatsu
    Aug 19, 2019 at 20:48
  • \$\begingroup\$ As written, I agree with Shelvacu that this is for puzzling. This is still a programming site, so here it would be better to ask for a program to output the solution. But that's probably necessary anyway, given that the fully expanded solution will have at least 43.252.003.274.489.855.999 moves. \$\endgroup\$ Aug 20, 2019 at 15:38
  • \$\begingroup\$ @PeterTaylor Actually, it would most likely be between 34,326,986,725,785,600 and 43,251,683,287,486,463,996. This is basically the Devil's Algorithm: a set of moves that when applied, repeatedly if necessary, will eventually return a Rubik's Cube to a solved state regardless of the starting configuration. \$\endgroup\$ Aug 27, 2019 at 9:35
1
\$\begingroup\$

Talk interpreter

"Talk" is a baroquified accumulator-based language that is created in order to make it difficult to put on Try It Online. The "Talk" language has 4 commands:

  • 00 If the accumulator is 0, set the accumulator to 0.
  • 01 If the accumulator is 0, set the accumulator to 1.
  • 10 If the accumulator is 1, set the accumulator to 0.
  • 11 If the accumulator is 1, set the accumulator to 1.

Input:

  • The input can be taken via any acceptable input method by our standard I/O rules.

  • The input will always be a sequence of the commands above.

  • The program will take an input that is either 1 or 0 to set the accumulator to.

Output:

  • On the end of a command execution, the accumulator is outputted implicitly.

Rules:

  • The input has to be a single string or character list, and splitting it in parts of size 2 is part of the challenge.
  • As this is , the shortest answer, in bytes, wins.
\$\endgroup\$
8
  • 2
    \$\begingroup\$ So we take two inputs? The starting 0/1, and the sequence of commands? Since you state I/O is flexible, would for the commands a list of 2-character strings be allowed (i.e. ["00","01","11","11","01"])? Or does the input have to be a single string or character list, and splitting it in parts of size 2 is part of the challenge? \$\endgroup\$ Aug 19, 2019 at 8:02
  • 4
    \$\begingroup\$ Um, commands 00 and 11 don't seem to do anything, while the other two seem to be just 'set the accumulator to 0/1' \$\endgroup\$
    – Jo King Mod
    Aug 19, 2019 at 8:07
  • \$\begingroup\$ The commands 00 and 11 was added in order to avoid uninteresting abuses like directly printing the last character of the code. \$\endgroup\$
    – user85052
    Aug 19, 2019 at 13:42
  • 3
    \$\begingroup\$ Why would this be difficult to put on Try It Online? Does the accumulator ever do any accumulating? \$\endgroup\$
    – Shelvacu
    Aug 19, 2019 at 19:21
  • \$\begingroup\$ This will overlap with the existing talk.tryitonline.net. \$\endgroup\$
    – user85052
    Aug 20, 2019 at 0:16
  • \$\begingroup\$ Um, it's not that hard to change the name slightly. Languages like ><>, /// and ??? already have url friendly names \$\endgroup\$
    – Jo King Mod
    Aug 21, 2019 at 6:49
  • \$\begingroup\$ Do you know how to change the name "Talk" slightly? \$\endgroup\$
    – user85052
    Aug 21, 2019 at 7:04
  • 3
    \$\begingroup\$ @Shelvacu, I imagine that it would be difficult to persuade Dennis that a "language" this useless is worth space on his server. \$\endgroup\$ Aug 23, 2019 at 7:45
1
\$\begingroup\$

Normalized Malbolge to Malbolge translator

In this task, you will write a program/function that takes a Normalized Malbolge program and outputs the resulting Malbolge program. (This is a secret tool that all Malbolge programmers are using!)

Input

A data structure that (somehow) represents a Normalized Malbolge program.

Output

A data structure that represents the resulting Malbolge program.

Examples

jpoo*pjoooop*ojoopoo*ojoooooppjoivvvo/i<ivivi<vvvvvvvvvvvvvoji:
(=BA#9"=<;:3y7x54-21q/p-,+*)"!h%B0/.~P<<:(8&66#"!~}|{zyxwvugJ%

jjjj*<jjjj*<v
('&%#^"!~}{XE

jjjjjjjjjjjjjjjjjjjjjjj*<jjjjjjjjjjjjjjjjjjjjjjjj*<v
('&%$#"!~}|{zyxwvutsrqpnKmlkjihgfedcba`_^]\[ZYXWVT1|

How to convert

This is a placeholder for the convertion process.

def normal_to_malbolge(prog):
    pos = 0
    malbolge = ""
    for i in prog:
        char = ord("' ( > D Q b c u".split()["*jpovi</".find(i)]) - pos
        while char < 33:
            char += ord("~")-32
        malbolge += chr(char)
        pos += 1
    return malbolge

Explanation

Iterate over the normalized Malbolge program, and then convert all "*jpovi</"'s to a character in "'", '(', '>', 'D', 'Q', 'b', 'c', 'u'. Then, minus the position.

While the temporary Malbolge representations' ASCII code is less than 33, increment the char by the ASCII code of "~" minus 32.

Append the resulting character to the output.

Rules

  • This is a contest; the shortest answer wins.
  • No standard loopholes please.
  • The default I/O methods are allowed.

    Sandbox

  • Is it a duplicate? This probably is.

  • Is the challenge well-written?
\$\endgroup\$
3
  • 2
    \$\begingroup\$ You need to include the instructions for converting normalized malbolge to malbolge (will give later) \$\endgroup\$
    – MilkyWay90
    Aug 21, 2019 at 1:18
  • 2
    \$\begingroup\$ ^ Check my code to convert and make an explanation out of that. Some people don't know python, and my code is very ugly \$\endgroup\$
    – MilkyWay90
    Aug 21, 2019 at 4:18
  • 1
    \$\begingroup\$ You could include a link to the standard loopholes, and put in that default I/O methods are allowed. Other than that I /support \$\endgroup\$
    – MilkyWay90
    Aug 21, 2019 at 15:33
1
\$\begingroup\$

I need help rewording the prompt.

I learned from last time about having convoluted scoring and having too broad of a focus from my last question. I hope this one is more clear.

Church Subtraction

Lambda calculus has always been a fascination of mine and the emergent behaviors of passing functions into each other is delightfully complex. Church numerals are representations of natural numbers contructed from the repeated application of a function (normally the unary addition of a constant). For example, the number zero returns and "ignores" the input function, one is f(x), two is f(f(x)) and so on:

ident = lambda x: x
zero = lambda f: ident
succ = lambda n: lambda f: lambda x: f(n(f)(x))
one = succ(zero)
add1 = lambda x: x + 1
to_int = lambda f: f(add1)(0)
print(to_int(one))
>>> 1

From this we can easily see that addition is accomplished by applying the first function to x then applying the second function to x:

add = lambda m: lambda n: lambda f: lambda x: n(f)(m(f)(x))
print(to_int(add(one)(two)))
>>> 3

Addition is relatively easy to understand. However, to a newcomer it might be inconceivable to think of what subtraction looks like in a Church encoded number system. What could it possibly mean to un-apply a function?

Challenge

Implement the subtraction function in a Church encoded numeral system. Where subtraction performs the monus operation and unapplies a function n times if the result will be greater than zero or zero otherwise. This is code-golf so shortest code wins.

Input

Two Church numerals that have been encoded in your choice of language. The input can be positional or curried. To prove these are true Church numerals they will have to take in any function and apply them repeatedly (add1 is given in the examples but it could be add25, mult7, or any other unary function.)

Output

A Church numeral. It should be noted that if m < n then m - n is always the same as the identity function.

Examples:

minus(two)(one) = one
minus(one)(two) = zero
...

also acceptable:

minus(two, one) = one
minus(one, two) = zero

Credit:

This github gist for giving me a python implementation of Church Numerals.

\$\endgroup\$
4
  • \$\begingroup\$ 1. I'm not sure how to parse "the number zero is a cat function Church encoding". Perhaps it would be better expressed as "the Church encoding of the number zero is the identity function"? 2. Explaining multiplication is an unnecessary distraction (unlike addition, which is relevant context). You've got a link to Wikipedia for people who want to learn more. 3. There is a technical term, monus, which describes the truncated subtraction. The truncation at zero should be described in the Challenge section, not the Output, and you might want to introduce this term there. \$\endgroup\$ Aug 23, 2019 at 7:31
  • \$\begingroup\$ 1. I missed an "in" and a cat function is pretty known in esolangs (esolangs.org/wiki/Cat_program), thank you for catching this. 2. I could explain exponentiation as well and maybe that might make a more compelling story. Or should I just stick with addition? 3. Thanks for the suggestion. \$\endgroup\$ Aug 23, 2019 at 12:04
  • 1
    \$\begingroup\$ 1. cat is well known in POSIX too, and in both cases it does I/O. I think it's misleading and confusing to call ident a cat function. And the word order of the edited version is ambiguous, and IMO tends to the parse "(the number zero) (is) (a cat function in Church encoding)". \$\endgroup\$ Aug 23, 2019 at 12:29
  • \$\begingroup\$ @PeterTaylor that work better? \$\endgroup\$ Aug 23, 2019 at 13:22
1
\$\begingroup\$

Determine the minimal indices needed to cover all queries

This challenge is based on Mongo's handling of compound indices and index intersection, inspired by a problem that came up at work, but I'll restate the relevant details here.

Background

In any database, relational or not, the primary purpose of indices is to optimize data lookup.

For example, if the task of finding all questions on this site had to be accomplished by looping through all posts and looking for the code-golf tag, it would be unusably slow. An index, however, organizes this data in a way that enables fast and efficient lookup of the data we want, which drastically reduces the resource cost of queries in exchange for some more work and space in maintaining the index.

However, the cost of maintaining indices is not negligible, so it quickly becomes untenable to create 2^N indices for N fields. (Databases designed for this purpose do exist and are the better choice when this functionality is actually needed. I'm ignoring this fact because it's a more interesting challenge this way.) Thus, careful index construction and selection is important to get the most bang for your buck.

Details

A simple index only organizes data based on one field but Mongo provides two ways to efficiently query on more than one field: compound indices and index intersection.

Compound Indices

Compound indices organize data based on a sequence of fields, e.g. [A, B, C]. Here, order matters. If data is sorted by A then B then C, then doing a lookup based on C first cannot be done efficiently since there are no guarantees on where the desired data might be located within the index (whereas one could do e.g. a binary search based on A).

Note: compound indices enable efficient queries on prefixes of that index as well. That is, a compound index on [A, B, C] enables efficient queries that have [A], [A, B], or [A, B, C]. However, as previously mentioned, it does not support queries that have [B], [C], [A, C], or [B, C].

Index Intersection

Exactly two indices can be used to optimize a query if there does not already exist a compound index for the desired fields. That is, if there is an index on [A] and an index on [B], then a query on [A, B] can be executed fairly efficiently (though not as efficiently as if there was a compound index, but let's ignore that). This also applies to prefixes of indices, so an index on [A, B, C] and an index on [C] can be intersected to support a query with [A, C].

Problem

Given N fields, determine the minimal indices needed to make all possible queries on those fields efficient. That is, minimize the total number of fields indexed. There may be more than one minimal set.

Note: the order of fields in the query doesn't matter since the query analyzer can reorder these fields to be as optimal as possible before running the query.

Input/Output

Input is a single positive integer and the output should consist of clearly-delimited sequences.

Examples

A variety of output formats are shown here to demonstrate what I mean by "clearly-delimited sequences".

N: 1

[0]

N: 2

AB
B

N: 3

[['A', 'B', 'C'], ['B', 'C'], ['C']]

['AB', 'BC', 'CA']

To elaborate on the first example in this N=3 case, the first index covers a query with all three fields, index intersections cover all choices of two fields, and index prefixes cover all queries with one field.

Note: for N=5, the obvious pattern does not hold; the indices ABCDE BCDE CDE DE E do not enable an efficient query on A, C, E.


Meta

I am really hoping this doesn't boil down to [A, B, ..., X], [B, ..., X], [C, ..., X], ... [X]. I haven't taken a look at the N=4 case yet though so I don't know if this pattern holds.

Thankfully, the pattern breaks down for N=5.

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

N-bonacci from a Seed

Tags:

An N-bonacci sequence is a Fibonacci-like sequence where the N previous terms are added to get the next term. The Fibonacci series is a 2-bonacci sequence.

Given a list of integers L of length l and an integer n, output the first n digits of the l-bonacci sequence starting with the sequence L.

Input

Input is a list, array, delimited string, stream, etc of integers, and an integer. Input is flexible, provided L and n are separable. It is guaranteed that n >= 0, and l >= 1.

Output

Output the first n digits of the l-bonacci sequence starting with L. Output is flexible here also: a list, array, string, stream, etc.

Samples:

[1,1], 5       --> 1, 1, 2, 3, 5
[0,1,2], 1     --> 0
[10,1,-1], 10  --> 10, 1, -1, 10, 10, 19, 39, 68, 126, 233
[-1,0,1], 0    --> //no output, or empty output
[-1], 3        --> -1, -1, -1
[-1,-2,1,0], 9 --> -1, -2, 1, 0, -2, -3, -4, -9, -15

This is , so smallest in bytes wins.

Related

\$\endgroup\$
4
  • 1
    \$\begingroup\$ You'd probably need to explain what an l-bonacci sequence is. That said I'm not sure this isn't a dupe of the related challenge you posted since at least some answers (including mine) would be able to be reposted with [1]*n replaced with L and n replaced with len(L). \$\endgroup\$ Aug 27, 2019 at 14:42
  • 3
    \$\begingroup\$ Closely related: codegolf.stackexchange.com/q/70476/31716 \$\endgroup\$
    – DJMcMayhem
    Aug 27, 2019 at 14:58
  • \$\begingroup\$ n <= l seems like an odd restriction, which your test cases don't always follow. If that is an actual requirement, this would be L[:n] in Python, which I don't think you want. \$\endgroup\$
    – Hiatsu
    Aug 28, 2019 at 13:56
  • \$\begingroup\$ Hmm. I'll axe n <= l then and change it to n >= 0. \$\endgroup\$
    – bigyihsuan
    Aug 28, 2019 at 17:37
1
\$\begingroup\$

Solve a cubic equation

(Is this really not a duplicate?)

\$\endgroup\$
10
  • \$\begingroup\$ Apparently not. I can find multiple quadratic equation challenges: 1; 2; 3, but there doesn't seem to be any cubic equation challenges yet. \$\endgroup\$ Sep 13, 2019 at 9:35
  • 1
    \$\begingroup\$ Sounds like it might be a dupe of either codegolf.stackexchange.com/q/154001/194 or codegolf.stackexchange.com/q/11694/194 \$\endgroup\$ Sep 13, 2019 at 10:58
  • 1
    \$\begingroup\$ @PeterTaylor The first challenge only asks for integer solutions, while yours has some constraints that this challenge might not have. \$\endgroup\$ Sep 13, 2019 at 13:48
  • \$\begingroup\$ @EriktheOutgolfer, I said "might" because "solve" is so vague that there's no way of knowing what the challenge is. And I don't think my challenge has constraints so much as licence to not have to be accurate to 1ulp. It's true that cubics can't be as ill-conditioned as higher-order polynomials, but there are still some nasty cases. \$\endgroup\$ Sep 14, 2019 at 8:48
  • \$\begingroup\$ @PeterTaylor I think there's a lot of subtleties in specifying challenges like this. I'd really like to push solvers to do something like the cubic formula rather than some generic method to solve or brute-force a polynomial equation. It's also fair that it's hard to judge anything from just a title. I'll try writing something up later and would be happy to hear your thoughts. \$\endgroup\$
    – xnor
    Sep 14, 2019 at 8:53
  • \$\begingroup\$ Regarding Peter's comment about the ambiguity of not including the description, one important thing to include is whether we must at least find one solution, the real solutions, or all solutions (I'm in favor of the last option). Also, "pushing solvers to do work" can be as simple as encouraging them to implement an algorithm that's more than just a built-in solving function (including the built-in solution for reference doesn't hurt, if it exists). \$\endgroup\$ Sep 14, 2019 at 15:38
  • \$\begingroup\$ @EriktheOutgolfer Can you explain why you like the last option of requiring all solutions? I had thought a bit about this and was leaning pretty heavily to only asking for one solution because it gives less advantage to generic solvers (even non built-ins) over writing a formula, and it means one never has to output a complex solution for languages that don't support them natively. \$\endgroup\$
    – xnor
    Sep 14, 2019 at 19:47
  • \$\begingroup\$ The "less advantage" restricting the output to one solution gives is simply a need for the answer to just pick one of the solutions it has found, in the worst case. Also, there are some cases where there are only complex solutions. If you want to account for such languages, you will need to add a guarantee that the equation will have at least one real solution, and none of the aforementioned cases will ever be input (there's some ambiguity about this currently). \$\endgroup\$ Sep 14, 2019 at 19:53
  • \$\begingroup\$ @EriktheOutgolfer Doesn't every cubic equation have a real solution? I'm not intending to include ones where the leading coeff is zero so it's really quadratic. \$\endgroup\$
    – xnor
    Sep 14, 2019 at 19:55
  • \$\begingroup\$ Hm, must've been thinking of something else (I'm currently doing other stuff). And yeah, a cubic equation \$ax^3+bx^2+cx+d=0\$ is cubic precisely because \$a\ne0\$. \$\endgroup\$ Sep 14, 2019 at 19:58
1
\$\begingroup\$

Randomize \$SL_n(\mathbb R)\$

Given a positive integer \$n > 1\$, return a random element from \$SL_n(\mathbb R)\$.

Details

  • \$SL_n(\mathbb R)\$ is the set of \$n \times n\$ matrices with determinant \$1\$.
  • In theory the output must cover the whole \$SL_n(\mathbb R)\$ (that is, if the RNG you're using was perfect and we could actually represent real numbers).
  • We don't require an uniform distribution.
  • Instead of real numbers it is sufficient to work with floating point numbers.
\$\endgroup\$
9
  • \$\begingroup\$ I suspect the interesting solution you have in mind is to start with the identity and do random row operations. But maybe it's shorter to just generate a random matrix and divide the first row by its determinant, even if your language means you need to implement det yourself? \$\endgroup\$
    – xnor
    Sep 14, 2019 at 7:30
  • 3
    \$\begingroup\$ On second thought, random row operations is probably shorter to golf. And there's probably niftier ways to it like generating the LU decomposition, or taking the exponential of a trace-zero matrix. So this definitely seems like an interesting challenge to golf, at least for languages that don't make it too easy. A technical issue that might be worth addressing is whether it's OK to never be able to generate some probability-zero subset. For instance, what if the method only generates matrices with distinct eigenvalues? I think this should be allowed since floats can't reach everything either. \$\endgroup\$
    – xnor
    Sep 14, 2019 at 7:43
  • \$\begingroup\$ @xnor Thanks for you input! This task actually came up when I was trying to test a function I've written and I ended up using the random matirx/scale by determinant solution. I see your point about the zero-probability sets. The only problem I see is that it is hard to define it in a way that cannot be abused: As matrices with floats have only rational entries you could argue that we can only represent a zero-probability set in the first place. (If we use this exact wording.) So I'm not actually sure how to specify this. \$\endgroup\$
    – flawr
    Sep 14, 2019 at 17:49
  • \$\begingroup\$ I think it would be OK to say that in theory, the output must cover cover the whole space except for some probability-zero subset of it. I see what you're saying about floats being measure zero, but I think this wrinkle is already present and covered by you saying "in theory" and that floating points suffice for reals, so I don't see the change making it more abusable. I also realized that the code probably should be allowed to fail with theoretical probability zero, like if you go the determinant-scaling route, you could get det zero. Maybe defaults cover this already, I'm not sure. \$\endgroup\$
    – xnor
    Sep 14, 2019 at 19:53
  • \$\begingroup\$ As a side thought, it could be possible to avoid these annoying real-representation issues by changing the challenge to generating integer examples or ones over F_2, but I suspect this won't allow as wide a variety of solutions. \$\endgroup\$
    – xnor
    Sep 14, 2019 at 20:01
  • \$\begingroup\$ "We don't require an uniform distribution." -- would a Dirichlet distribution be allowed? \$\endgroup\$ Sep 17, 2019 at 7:38
  • \$\begingroup\$ @xnor Even though \$\mathbb{F}_2\$ allows the possibility for bit-fiddling in solutions, possibly being interesting in their own rights. \$\endgroup\$ Sep 17, 2019 at 7:43
  • \$\begingroup\$ @JonathanFrech Can you elaborate how you'd define a Dirichlet distribution over \$SL_n(\mathbb R)\$? I'm not familiar with this distribution and I don't quite see how we can apply it as the support seems to be defined as \$(x_1,\ldots,x_n)\in \mathbb R^n\$ with \$\sum_i x_i =1\$. \$\endgroup\$
    – flawr
    Sep 17, 2019 at 7:43
  • \$\begingroup\$ I though of something along the lines of \$P[X\neq\mathrm{id}]<\epsilon\$, where \$X\$ models the output and \$\epsilon\$ represents machine accuracy, however on second thought this case is covered by your theoretical surjectivity requirement. \$\endgroup\$ Sep 17, 2019 at 7:50
1
\$\begingroup\$

Battleships TDM

In this (not so simple) game of commanding a battleship, you are tasked to defeat the opposing team. Cooperation is essential in order to win the battle.

Each ship starts with $${500\cdot\bigg\lfloor\frac{10}{\log{\frac{n}{3}}}}\bigg\rfloor$$ health (rounded down), where n is a number of players. At 30 players, it is 5000.

Setup

The game starts with a square map of length 50+3n. On top and bottom there is 15% of the width, in which the players' ships will spawn. The rest of the map will be prodedurally generated with islands.

The sample map looks like this: Map

Phase 1: Issuing commands

On your turn, your program will be given a file input.txt located in the program's directory, with following format:

TURN=(turn number)
SIZE=(size of the map)
YOUR_SHIP=(first 6 chars from SHA1 hash of your ship's name; in case of conflicts a random one will be generated)
YOUR_TEAM=(your team's id)
HEALTH=(your ship's health)
POS=(position of your ship in 0,0 format)
SPEED=(your ship's speed)
DIR=(your ship's direction)
TERRAIN:
(21x21 square of characters, centered on the ship)
PROXIMITY:
(line-separated list of ships within 10 squares, with its properties separeated by semicolon)
CHAT:
(line-separated history of text sent by teammates from the last and current round)

For example:

TURN=21
SIZE=110
YOUR_SHIP=acf44a
YOUR_TEAM=1
HEALTH=3231
POS=64,121
SPEED=3
DIR=NW
TERRAIN:
.....................
###.............x....
##.................##
(etc.)
PROXIMITY:
bd439a=1;69,132;S;3 (ship's id, team, position, direction, speed)
43351f=2;78,112;NE;4
(etc.)
CHAT:
58ab38@21: ENEMY_SHIP 582af2 @ 142,62 NE 3
902dd1@20: 033b2c 4 92,62 SW 1
(etc.)

The map shows . for water, # for land, x for wrecks, 1 and 2 for ships belonging to particular team.

Your program is allowed 3 actions per turn. The actions are:

NONE - do nothing
TURN_LEFT - rotates ship counterclockwise by 45 degrees
TURN_RIGHT - rotates ship clockwise by 45 degrees
SPEED_UP - increases speed by 1. At speed 5 it is ignored.
SPEED_DOWN - decreases speed by 1. At speed -1 it is ignored. 
MESSAGE=message - sends a message to chat
FIRE=x,y - fire a projectile in specified location. Can be done only once per turn. 
           The cannon has range of 25. Issuing a command which exceeds it is ignored.

For example:

TURN_LEFT
SPEED_UP
FIRE=62,69

must be written to output.txt. After each round the file is cleared.

Phase 2: Movement phase

All ships in random order move forward defined by their speed.

  • If ship hits the land or wreck during movement, the ship stops and takes damage worth 50x of ship's speed.

  • If ship hits the map border, same situation applies.

  • If ship hits other ship, it is considered ramming:

    • If rammed from the front, both ships receive damage worth 100x sum of ships' speeds. Both ships stop.

    • If rammed from the back, rammed ship receives damage worth 20x difference of ships' speeds. Rammed ship moves one step forward and ramming ship ends its movement.

    • If rammed from the side, rammed ship receives damage worth 100x speed of ramming ship, while the ramming one receives 50x. Ramming ship stops.

    • If rammed at the angle, rammed ship receives damage worth 50x speed of ramming ship, while the ramming one receives 20x. Ramming ship stops.

    • If the rammed ship is friendly, ramming ship receives 1 point of friendly fire.

Phase 3: Firing phase

In the same order ships fire from the cannons (if any). If the cannon hits a target:

  • That is within range 10: Shots deal 500 + 0-99 damage

  • That is beyond range 10: Shots deal 500 + 0-99 damage + 0-99 damage for each unit beyond 10th (up to 2084 total damage at range 25)

  • If the target is friendly, the damage is 0 and shooting ship receives 1 point of friendly fire.

  • There is 5% chance to make a hit critical: The total damage is tripled and shooter recieves 1 critical point.

  • If it is a fatal blow, it is considered a destruction:

    • The fatal blow dealer receives a fatal point.

    • Attacker with most dealt damage receives a kill point (it may be the same ship as the dealer).

    • Everyone else with a hit receives an assist point.

    • If it is a solo kill, the dealer receives 2 of each points instead.

Phase 4: Checking conditions

Each ship is considered a wreck if:

  • Health reaches below 0 HP,

  • Ship gains 5 friendly fire points.

Wrecks remain on the map, but they are removed from the queue and program of such ships is being not executed.

Game ends whenever entire team gets destroyed or after 1000 turns, in which the points are being calculated as follows:

  • 1 point for each 10 damage dealt

  • 500 points for each kill

  • 200 points for each fatal blow

  • 100 points for each assist

  • 150 points for each critical hit

  • -250 points for each friendly fire hit

  • 1000 points for each winning team member

  • Points for achievements (names are just for decoration):

500 (awarded once) Beyond the horizon - Hit on enemy from 13 sq or more
500 (awarded once) Maximum range - Hit on enemy from 23 sq or more
500 (awarded once per participant) Coordinated attack - 3 or more ships attacking the same target
500 (awarded once) Hammer - Ram a ship on full speed
500 (awarded each time) - Survive a critical hit
1000 (awarded once per participant) Anihilation - Both ships getting destroyed in headfront ramming

The ship with most points after 10 games wins.

Code

The controller code is here.

Rules

Your program can:

  • store data in files within its own directory

  • communicate with teammates through the team's chat

Your program cannot:

  • read files outside its scope

  • disrupt the communications

  • Attack friendly ships on purpose

  • Copy other competitors' functionality (No duplicates)

  • Use standard loopholes

Sandbox questions

  • I'm not sure whether to allow the challenge in any usual language or require one specific (in this case Java 8)?
  • Wouldn't be achievements unnecessary? If not, could be any added/modified/removed?
  • Are there some rules that require clarification?
\$\endgroup\$
14
  • \$\begingroup\$ What does "procedurally generated with islands" mean? Could you provide a small example map? What does "15% of the width where players' ships spawn" mean? Are they distributed randomly, or packed into a corner (or do they have a choice)? \$\endgroup\$ Sep 7, 2019 at 15:18
  • \$\begingroup\$ @someone 1. "Procedurally generated islands" I meant. 2. Added. 3. Area reserved for ships to spawn. 4. Randomly across the spawn area. \$\endgroup\$ Sep 7, 2019 at 18:48
  • 2
    \$\begingroup\$ a) Ship health and particularly map size, in my opinion, scale in a weird way with participant count. b) I would highly recommend avoiding file I/O in favor of sending data to programs via STDIN and reading their actions via STDOUT. c) Additionally, I would recommend using a ubiquitous I/O format, like JSON or XML. This will reduce the amount of boilerplate code that the participants will have to write. Moreover, it would prevent d) the problem of newlines in chat. e) What order are the programs asked for output in? This is important for chat, for example. \$\endgroup\$
    – Alion
    Sep 7, 2019 at 22:32
  • \$\begingroup\$ f) Does the damaging behavior differ depending on whether the ramming ship hit the front-right/left or the back-right/left? g) Does ramming a friendly ship deal damage to it? Please make that clear. h) Does solo-killing also provide 2 assist points? I'm guessing it doesn't, but it's not clear either. i) Shooting right at the current position of an enemy ship seems ridiculously effective. You've got a 50% chance to hit by definition, while all the other methods necessarily have less, since the ship can dodge. I can see very few edge cases. That's just my opinion, however. \$\endgroup\$
    – Alion
    Sep 7, 2019 at 22:47
  • \$\begingroup\$ j) I misunderstood the "1000 points for each winning team member" the first 2 times I read it. "1000 points for member of the the winning team" is clearer in my opinion. k) Coordinated attack achievement is perhaps a bit unclear, but I can't seem to put into words why that is. l) 10 games is not an awful lot. While I understand that you don't want to run this for too long, this game does seem to be a bit random. m) Attacking friendly ships "on purpose" is difficult to define rigorously, and is already punished by the game, which makes it Emo Wolf-y. All in all I find the rule unnecessary. \$\endgroup\$
    – Alion
    Sep 7, 2019 at 23:03
  • \$\begingroup\$ n) It would be lovely if the challenge was available for all standard languages. I would definitely not participate if it was Java-only. p) How are teams chosen? Randomly every game? r) I strongly recommend making a dedicated chat room for participants once the challenge hits main - you seem to be looking forward to coordinated plays, and I don't think they're possible without an agreed-upon communication format, which in turn is unlikely to develop without any group discussion amongst players. \$\endgroup\$
    – Alion
    Sep 7, 2019 at 23:19
  • \$\begingroup\$ Correction for j) - I meant "1000 points for each member of the winning team". There's also a general problem of weird English present in all parts of the spec, but as long as it's understandable (which it is), there shouldn't be any problems here. Anyway, looking forward to the updated spec, and of course to the challenge itself. Good luck! \$\endgroup\$
    – Alion
    Sep 7, 2019 at 23:26
  • \$\begingroup\$ @Alion The main issue is that I have no idea how can I run programs from multiple languages, so my controller could capture it and interpret all actions within reasonable time (since I'd have to run each program thousands of times to make an action). I don't want to end up copying/pasting/calculating everything by hand each turn, which could take a week or more to finish the game. The further points will refer to this one as I go \$\endgroup\$ Sep 8, 2019 at 5:32
  • \$\begingroup\$ a) True, but the ship health has at least been addressing the time constraints. I could end up with some long functions for both of those anyway. b) STDIN/OUT capture issue. c) Haven't thought of this. d) Oh? e) What order? I'm not sure what do you mean. f) FL/R and BL/R deal the same damage. g) Uh, yes. h) Would have to think about it. i) Do you suggest any alternatives? l) Time constraints, again. n) Here we go back to the issue with multiple languages. p) Random every game. r) I would if I had the power to do so. Currently I don't. (BTW English is not my first language) \$\endgroup\$ Sep 8, 2019 at 5:48
  • \$\begingroup\$ I've cobbled together a simple demo of how a language-agnostic controller could work. As I don't write Java, I used C# instead, but the code should be mostly readable for a Java developer as well. You will certainly need to find the Java equivalents of the methods and classes used, but I would be very surprised if Java doesn't support something akin to what I've done in C# at all. I also assumed Windows all throughout. Here's a demo.. Contains the C# controller and the files required for a sample Python entry. \$\endgroup\$
    – Alion
    Sep 8, 2019 at 12:27
  • \$\begingroup\$ a) After understanding what the ship health function does, I don't have a problem with it anymore. The map size, however, grows quadratically with the ship count. d) You've defined chat as a line-separated history of messages. But what happens if an entry decides to put a newline into its message? e) Are the programs queried for actions in a consistent order? If so, what is the initial order? Random? Additionally, being early in the call order is a huge disadvantage, since most of the messages received will be from the previous turn, as I understand it. \$\endgroup\$
    – Alion
    Sep 8, 2019 at 12:36
  • \$\begingroup\$ i) It's really difficult to come up with any alternatives from my position. I don't have access to your vision of the game. Inevitably I end up overhauling the battle system one way or another and remain unsatisfied with it. Considering previous challenges, however, I can't say for sure if this really is a notable flaw. \$\endgroup\$
    – Alion
    Sep 8, 2019 at 12:42
  • \$\begingroup\$ Alion's point (b) is addressed at the execution speed issue you raise. See github.com/pjt33/ppcg36515 (linked from the KotH tag wiki) for an example which supports Java submissions natively and other languages by stdin/stdout communication. Another issue which Alion has touched on briefly is the team business: it needs to be clear how the teams will be assigned. \$\endgroup\$ Sep 9, 2019 at 8:34
  • \$\begingroup\$ I have slightly edited your equation, feel free to roll back if you disagree. \$\endgroup\$ Sep 17, 2019 at 8:03
1
\$\begingroup\$

Black And White Shirts 3

This is the third in a series. The first can be found here, and the second here. The premise is similar to the first two, but with some changes and a new goal.

Assume I have some number of black shirts and some number of white shirts, both at least 1. Both colors of shirt have a non-zero Vividness. All shirts of a given color start with the same Vividness.

Every day, I pick out a clean shirt to wear, and it becomes dirty. Once I run out of all clean black shirts or all clean white shirts, I wash all my dirty shirts of both colors and start over. Clean shirts do not get washed. Whenever a shirt gets washed, its color changes based on its Vividness and the Vividness and colors of the other shirts being washed, then its Vividness goes down by one to a minimum of 0. All things being equal, over time, all shirts will generally tend towards a shade of gray.

If a shirt is ever closer to the opposite color (eg. a black shirt looks light gray), it becomes a shirt of that color.

When picking which shirt to wear, I choose the shirt which is either closest to black or closest to white. If there is a tie, I choose the one with the highest Vividness.

Challenge:

Take in an arbitrarily long sequence of two indicators (eg. b b w w b w b b w b...) representing my choice of shirt to wear on that day. Continue execution until either my last black shirt or my last white shirt loses its last vividness. Once this occurs, stop consuming input and print out the colors of all shirts.

Inputs:

Number of black shirts, number of white shirts, Vividness of black shirts, Vividness of white shirts, and a sequence of shirt selections of arbitrary length at least long enough for one color of shirt to run out of Vividness (can be considered infinitely long). The selection can be represented by any two characters (eg. b, w).

Output:

Color of all shirts, sorted from lightest to darkest, as a percent of how close it is to white, rounded to the nearest whole percent. A completely black shirt is 0, and a completely white shirt is 100.

Color changing:

The color of a shirt tends towards the average of all shirts' colors in the wash. How close it gets depends on its own Vividness.

TODO: Determine if this rule is necessary (I don't think it is): If all shirts in the wash have 0 Vividness, none of them change color.

When washed, shirts are changed based on the following pseudocode algorithm (some of which may not be necessary for your simulation):

struct shirt {
    int vividness
    float color
}

func washShirts(shirt[] allDirtyShirts) {
    totalVividness = allDirtyShirts.sum(shirt => shirt.vividness)
    if (totalVividness == 0)
        return

    averageDirtyColor = allDirtyShirts.sum(shirt => shirt.color * shirt.vividness) / totalVividness

    for each shirt in allDirtyShirts
    {
        shirt.color = (shirt.color * shirt.vividness + averageDirtyColor) / (shirt.vividness + 1)
        if shirt.vividness > 0
            shirt.vividness--
        if shirt.isBlack && shirt.color > .5
            shirt.isBlack = false
        else if !shirt.isBlack && shirt.color < .5
            shirt.isBlack = true
    }
}

Make sure that all shirts base their calculation on the Vividness and color values of all other shirts before the change. Perform no rounding beyond normal floating point restraints within your language of choice (within reason) during any calculation. Only round the value during output. When rounding for output, choose any convenient rounding method among:

  • truncating (always round down)
  • rounding to the nearest integer
    • .5 rounds up
    • .5 rounds down
    • .5 rounds to the nearest even integer

Test cases:

Note: These test cases use rounding to the nearest even integer. Your output may vary in some cases.

1 2 1 1 w b
100 75 25

3 3 2 1 w b w b w w w w w w w w
71 71 71 14 14 0
#note that processing would stop after w b w b w. The remaining input would be ignored.

#todo: more test cases

General rules:

  • This is , so shortest answer in bytes wins.
  • Default I/O rules apply
\$\endgroup\$
1
\$\begingroup\$

Title: Lossless Compression

Implement the following lossless compression pseudo-algorithm and its decompressor; scored by the number of bytes output by your compression algorithm, after you've put your source-code for both the compressor and decompressor through your own implementation of the compressor algorithm, described below:

Algorithm Description

Essentially, this is a simple dictionary compression algorithm (which isn't always guaranteed to compress the output, especially for short inputs). You want to scan for sequences of characters that appear multiple times, and then create a lookup; in order to shorten the input string.

The input string to generate your score must contain all characters in your submission; however the program must also be capable of compressing successfully the test-cases below.

The dictionary (which forms part of the output string) can use any other character as an indexer character, except a single separate character of your choice (| in my examples), which is reserved.

The output format should be a sequence of IndexcharValuestring| (i.e. index character, followed by the value string, followed by the separator - collectively "the dictionary"); followed by the compressed input string.

Some examples:

  1. testRattesttestRattesttesttesttestRattest -> _test|+Rat|_+__+____+_ - because test is represented by _ and Rat is represented by +; then the compressed string is shown. each section is separated by the character |.

To decompress, simply replace _ with test and + with Rat in the output (after the last |).

The dictionary entry can also be nested - for example:

ininputinputininput -> &in|*&put|&**&* because in is represented by & and &put is represented by *

Exactly which characters end up being grouped will depend on your compression algorithm. For example, the previous string could also be output as &input|in&&in&, or &in|*put&|&&**&put

Note that the recursive compression could go even further, but at this point the output gets longer again:

ininputinputininput -> &in|*&put|^&*|^*^

It's up to you how much compression your algorithm performs, as long as it matches or beats the longest of the outputs for each example in this post.

  1. AbcAbcDefDefDeggggggggggggggggggAbc

could output:

-Abc|£De|#£f|*ggg|--##£****-

  1. Well I've heard there was a secret chord That David played and it pleased the Lord But you don't really care for music, do you? Well it goes like this, The fourth, the fifth, the minor fall and the major lift! The baffled king composing Hallelujah. Hallelujah Hallelujah Hallelujah Hallelujah

could output:

+ you|/ing |-ed |%pl|¬it|#or|^th|)ll|(he|"T( |$t( |*We) |_Ha)elujah|*I've (ard t(re was a secret ch#d That David %ay-and ¬ %eas-$L#d But+ don't rea)y care f# music, do+? *¬ goes like ^is, "four^, $fif^, $min# fa) and $maj# lift! "baffl-k/compos/_.____

  1. %Testttttttttt%%%%%%%%

could output:

$%%%%|_ttttt|%Tes__$$

  1. aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789 ?!.,;

must output:

aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789 ?!.,;

(because no compression is possible)

Acceptance Criteria

In order to class as valid, the algorithm you create should:

  • Meet the algorithm description above
  • Be able to match or beat the length of the test cases above (shorter = better)
  • Output from the compressor (and therefore input for the decompressor) should be in the format shown (dictionary and separator characters may differ). Input for the compressor (and therefore output for the decompressor) should also be in the format shown.

Sandbox Notes and Questions

  • Is the challenge clear?
  • Is the scoring mechanism fair? I'm still not sure how to deal with characters vs bytes
  • Is the spirit of the challenge clear? (i.e. to actually make an algorithm, rather than simply beat the examples and get the best score)
  • Is there any interest in this challenge?
\$\endgroup\$
17
  • \$\begingroup\$ I'm confused: not only does the output format explanation use = but the question explicitly says that = is reserved, and yet none of the examples use it. \$\endgroup\$ Apr 3, 2018 at 14:37
  • \$\begingroup\$ @PeterTaylor I changed my mind half way through, sorry fixed now \$\endgroup\$ Apr 3, 2018 at 14:53
  • 2
    \$\begingroup\$ Mostly irrelevant nitpick: no lossless compression algorithm is guaranteed to make its input smaller, a result often known as the "no free lunch theorem." \$\endgroup\$
    – N. Virgo
    Apr 11, 2018 at 7:54
  • \$\begingroup\$ @Nathaniel Good to know, thanks \$\endgroup\$ Apr 11, 2018 at 9:25
  • \$\begingroup\$ How would you score a submission containing characters different from the ones allowed in input? \$\endgroup\$
    – Leo
    Apr 11, 2018 at 9:38
  • \$\begingroup\$ @Leo yes, it does limit the source somewhat, doesn't it? What would be better then? - increasing the range of characters allowed to allow any character except, say, | (and the dictionary has to key on missing characters only); or keep the limited input and also limit people's source? \$\endgroup\$ Apr 11, 2018 at 13:29
  • \$\begingroup\$ One possibility would be letting people choose the separator character (instead of fixing it as |), and requiring that a submission works on inputs consisting of all the required characters plus all the characters contained in the submitted source. This should give enough freedom to make solutions possible in more languages. \$\endgroup\$
    – Leo
    Apr 11, 2018 at 22:22
  • \$\begingroup\$ @Leo helpful, thanks. Updated - hope it's clear \$\endgroup\$ Apr 12, 2018 at 15:42
  • \$\begingroup\$ Are you sure that you want to work on characters and not bytes (and thus facing multiple complicated codepage issues)? Especially consider that the program itself is compressed. \$\endgroup\$
    – DELETE_ME
    Apr 12, 2018 at 15:56
  • \$\begingroup\$ @user202729 could you expand on what issues would occur? I'm not quite sure I get what the issues could be here \$\endgroup\$ Apr 17, 2018 at 13:51
  • \$\begingroup\$ The "program" is most likely an arbitrary byte string, and thus it may be invalid UTF-8. \$\endgroup\$
    – DELETE_ME
    Apr 17, 2018 at 15:29
  • \$\begingroup\$ @user202729 but it will be convertible to something, using a custom code-page of some sort. Even if it's UTF-16 or some other encoding, right? \$\endgroup\$ Apr 18, 2018 at 8:52
  • \$\begingroup\$ I still feel that it's open to abuse. We had reasons to score by byte count instead of character count. \$\endgroup\$
    – DELETE_ME
    Apr 18, 2018 at 8:59
  • \$\begingroup\$ @user202729 The scoring is a byte count; just the program uses characters to compress/decompress. The compression ratio for someone using a golfing language is likely to be very poor, compared with say someone using ><> or even VB.NET - but it's the job of the coder to decide which language will get them the best score for the question; right? \$\endgroup\$ Apr 27, 2018 at 12:38
  • \$\begingroup\$ Brute force is the best \$\endgroup\$
    – l4m2
    Apr 29, 2018 at 11:16
1
\$\begingroup\$

Posted. I prefer to retain the content for potential issues.

Duck, duck, gone!

Here is the (quite childish) Five little ducks song(it is not long):

Five little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only four little ducks came back.

Four little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only three little ducks came back.

Three little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only two little ducks came back.

Two little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only one little duck came back.

One little duck went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but none of the little ducks came back.

Mother duck herself went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
and all of the little ducks came back.

Your task is not to output this song. You should take a verse and output the next verse (the next verse of the last verse is the first verse).

Rules

  • No standard loopholes, please.
  • Input/output will be taken via our standard input/output methods.
  • The exact verse must be outputted, and there should be no differences when compared to the song lyrics. The input will not be different when it is compared to the song lyrics too.

Examples

Mother duck herself went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
and all of the little ducks came back.

Expected:

Five little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only four little ducks came back.
Three little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only two little ducks came back.

Expected:

Two little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only one little duck came back.

Sandbox

  • Is it detailed enough?
  • Is the input/output rules clear enough?
  • Do I need any more information?


\$\endgroup\$
5
  • \$\begingroup\$ So a simple (no regex needed, case insensitive) string replacement FiveFour, FourThree, ThreeTwo, Two little ducksOne little duck, One little duckMother duck herself, fourthree, threetwo, two little ducksone little duck, only one little ducknone of the little ducks, noneall of? \$\endgroup\$
    – Adám
    Sep 23, 2019 at 9:44
  • \$\begingroup\$ Yes. (It seems quite repetitive, a better algorithm might be possible.) Do you think that outputting the whole lyrics is better? \$\endgroup\$
    – user85052
    Sep 23, 2019 at 9:46
  • \$\begingroup\$ No, it is no more interesting than 99 bottles etc. \$\endgroup\$
    – Adám
    Sep 23, 2019 at 9:49
  • 4
    \$\begingroup\$ You might replace the content with "posted" and a link now. \$\endgroup\$
    – S.S. Anne
    Sep 26, 2019 at 10:58
  • \$\begingroup\$ Your link is to an answer. \$\endgroup\$
    – S.S. Anne
    Sep 26, 2019 at 15:51
1
\$\begingroup\$

Polynomials Through Points

You will get a set of n Cartesian coordinates. You must output a polynomial going through all of the points.

Input

  • Points are 2-dimensional.
  • You may assume that no two points share a x coordinate.
  • You may take points as a tuple of pairs, or pair of equal length tuples.
  • 1<n<1000

Output

  • For polynomial y=x^3+3*x^2+1, you may output as:
    • y=x^3+3*x^2+1
    • x^3+3*x^2+1
    • y=x^3+3*x^2+0*x+1
    • x^3+3*x^2+0*x+1
    • y=x^3+3*x^2+x^0
    • x^3+3*x^2+x^0
    • y=x^3+3*x^2+0*x^1+x^0
    • x^3+3*x^2+0*x^1+x^0
    • y=1*x^3+3*x^2+1
    • 1*x^3+3*x^2+1
    • y=1*x^3+3*x^2+0*x+1
    • 1*x^3+3*x^2+0*x+1
    • y=1*x^3+3*x^2+1*x^0
    • 1*x^3+3*x^2+1*x^0
    • y=1*x^3+3*x^2+0*x^1+1*x^0
    • 1*x^3+3*x^2+0*x^1+1*x^0
    • [1,3,0,1]
  • You may output any polynomial satisfying the condition.

Rules

  • Stabdard loopholes are forbidden.
  • Any method approved by Standard I/O is allowed.
  • This is code-golf, so shortest code wins!
\$\endgroup\$
1
\$\begingroup\$

Shortest way to get an EOF Error

It's simple, simply write the shortest code to raise an EOF Error. An EOF Error happens when the language expects more code to be entered into the source code; however, the language encounters an EOF character. So here is a sample Python program to throw an EOF error.

id(

Python expects more code to be entered, but EOF is entered instead. Therefore it throws an "EOF Error" (technically a Syntax Error though, but the interpreter says unexpected EOF while parsing).

To simplify that, output text to STDERR containing the string EOF. Normally a language will exit after outputting to STDERR with an error, so if you are hard-coding the value out to STDERR, you should also exit the program with a 1 value.

Input/Output

Your input will be none; however, you should output a message to STDERR that proves that the program generates an EOFError.

Rules

  • Since this is , the shortest answer wins.
  • No standard loopholes please.
  • Any method approved by Standard I/O is allowed.

Feedback

  • Is this clear enough?
  • I don't believe this is a duplicate (I found this, but it's restricted to a single language), but does anyone recognise this?
  • The tags as code-golf, error-message. Anything else?
  • Any further feedback?
  • Is it possible to have trivial answers on most languages for this challenge?
\$\endgroup\$
1
  • \$\begingroup\$ So just taking empty input would cause an EOF error? That'd lead to a whole bunch of trivial 1 byte answers in golfing languages. \$\endgroup\$
    – lyxal
    Oct 4, 2019 at 0:19
1
\$\begingroup\$

A Musical Tuner

Oh no! My tuner's batteries ran out, I need to play in a concert in a few minutes, and I need to know if my instrument's in tune! I need this tuner quick, so it needs to be short.

Background

In music, all notes are given a letter from A-G/H, an optional sharp/flat ♯/♭, and a number specifying what octave it is in, starting from 0. This is called scientific pitch notation.

In equal temperament, \$\sqrt 2 \approx 1.05946 \$ is an important ratio, as used in the formula $$ P_n = P_a (\sqrt2)^{n-a} $$ where

  • \$ P_n \$ is the desired frequency, in hertz.
  • \$ n \$ is the number of keys from the left on a piano the desired note is.
  • \$ P_a \$ is the reference frequency, in hertz.
  • \$ a \$ is the number of keys from the left on a piano the reference note is.

A piano begins at \$ A_0 \$ as the 1st key, and with reference frequency of \$ A_4 = P_a = 440 \$ Hz, at the 49th key.

The whole step, the tonal distance between two notes separated by one key, is divided into 100 cents. A half step is exactly 50 cents.

The Challenge

Write a full program that, when given a decimal number in hertz, outputs the closest note in scientific pitch notation, and how far it is from that note in cents.

Input

A positive number in hertz. This can be a string, number, list of whole number and decimal, etc. You can always assume this to be positive, and a number with maximum 3 decimal places.

The input is in the range \$ 27.5 \le P_n \le 4186 \$.

Output

A note in scientific pitch notation, and how many cents it is from, in the form

[Note letter][Sharp/Flat][Octave number][+/-][Cents]

  • If a note is determined to be close to a natural note, no sharps or flats should be output.
  • Output either sharps or flats.
  • Sharps can be either ♯/# , and flats either ♭/b.
  • Octave number ranges from 0 to 8.

Other Rules

Test Cases

Input --> Output
440 --> A4
261.626 --> C4
24.995 --> G♯0-8 (OR G#0-8)
1320.068‬ --> E6+1
3674.882‬ --> B♭7-13 (OR Bb7-13 OR A7+13)
\$\endgroup\$
2
  • \$\begingroup\$ The +/- 1 cent rule seems to be an unnecessary complication, I would suggest removing that. \$\endgroup\$
    – flawr
    Oct 4, 2019 at 6:49
  • \$\begingroup\$ The third example seems to be outside of the input range. I might be missing something obvious (I am almost entirely ignorant of music theory) but I don't think you explain how to get the note letter or the sharp/flat from the frequency. I think your question is unclear if you don't specify how that works in your challenge body. I assume what you intend for us to do is use the formula you provide to find \$ n \$ and then look up what key on a piano \$ n \$ refers to? In which case I think you should include the list of keys in order. \$\endgroup\$ Oct 4, 2019 at 18:39
1
\$\begingroup\$

Fewest number of button presses to set the cook time

A GolfCo™ microwave oven has a 12-button keypad like this:

[1]  [2]  [3]
[4]  [5]  [6]
[7]  [8]  [9]
     [0]  [+30]
   [START]

How the microwave operates

The microwave reads and processes button presses as follows:

  1. Buttons [0]-[9] add the corresponding digit to the right end of the cook time, up to 4 digits total. Once started, these buttons do not function.
  2. The [+30] button adds 30 seconds to the cook time, and starts the cooking process (if not already started).
  3. The [START] button starts the cooking process.

The microwave can be programmed with a cooking time ranging from 1 second to 99 minutes and 59 seconds.

Any one or two-digit cook time is interpreted as seconds only, ranging from 1 to 99 seconds.

Any three or four-digit cook time is interpreted as two digits of minutes and two digits of seconds. In this mode, the minutes portion of the cook time can range from 0 to 99 minutes, while the seconds can range from 0 to 59 seconds.

The challenge

Given a time in minutes:seconds (eg. "4:45" for four minutes and 45 seconds), print the button sequence with the least number of button presses required to set the cook time and start the cooking process.

As this is code golf, the smallest program in bytes wins.

Input

Input will be given in the common MM:SS format, where "MM" specifies minutes and "SS" specifies seconds, separated by a colon.

Minutes can be zero padded to 2 digits or the leading zero omitted, at the golfer's discretion. Minutes can range from 00 to 99.

Seconds will always be 2 digits, ranging from 00 to 59.

The cook time will range from 00:01 to 99:59.

Output

The program will output the sequence of button presses needed to program the cook time and start the microwave.

Buttons [0] to [9] will be output as the corresponding digit "0"-"9".

The [+30] button will be output as "+".

The [START] button will be output as "S".

Test cases

Input                  Output
=======================================
04:45 (or 4:45)        4 4 5 S
00:08                  8 S
00:30                  +
00:35                  5 +
00:20 (or 0:20)        2 0 S
01:20 (or 1:20)        8 0 S
01:25 (or 1:25)        8 5 S     ("2 5 + +" and "1 2 5 S" are both too long)
01:30 (or 1:30)        + + +     ("9 0 S" is also correct)
01:35 (or 1:35)        5 + + +   ("1 3 5 S" is also correct)
01:39 (or 1:39)        9 + + +   ("1 3 9 S" is also correct)
01:40 (or 1:40)        1 4 0 S   ("1 0 + + +" is incorrect)
01:50 (or 1:50)        1 5 0 S   
02:00 (or 2:00)        2 0 0 S   ("+ + + +" is also correct)
02:30 (or 2:30)        2 3 0 S   ("+ + + + +" is incorrect)
03:00 (or 3:00)        3 0 0 S   
10:00                  1 0 0 0 S
99:59                  9 9 5 9 S
\$\endgroup\$
8
  • \$\begingroup\$ Can we wait between pressing buttons? I think I've seen a related challenge. \$\endgroup\$ Oct 11, 2019 at 0:44
  • \$\begingroup\$ @someone, can you please explain how it would help? The only way I can see is if pressing buttons 0-9 is allowed after the oven is started, which I realize now I didn’t not state in the challenge. Is there some other use? \$\endgroup\$
    – spuck
    Oct 11, 2019 at 1:13
  • \$\begingroup\$ to wait for 300s, is it allowed to do +0? To wait 291s, can you press +, wait for 1 second and press 0? \$\endgroup\$ Oct 11, 2019 at 1:33
  • \$\begingroup\$ The +30 button starts the oven, and after the oven is started, the 0-9 buttons do not function. \$\endgroup\$
    – spuck
    Oct 11, 2019 at 3:07
  • \$\begingroup\$ Some microwaves let you do more than 59 for the seconds. E.g. if I type in 87, it will read it as 1:27. 60 reads as 1:00, 192 reads as 2:32. This can allow you to enter certain times in fewer button presses. Would be an interesting added challenge to support this feature. Basically, if the last 2 digits are more than 59, subtract 60 and add 1 to the minutes. (It would raise the maximum up to 100:39, if you were to type 9999...) Edit: I see you did this in one example - that rule should be explicitly stated if you want to make sure it's enforced. \$\endgroup\$ Oct 15, 2019 at 17:21
  • \$\begingroup\$ @DarrelHoffman, that is part of the challenge. The Input section states that the cook time will always been given as MM:SS and the allowed ranges, and the Operation section states that 1 or 2 digit cook times are interpreted by the microwave as seconds, from 01 to 99 seconds. Please let me know how I could edit to make that more clear. \$\endgroup\$
    – spuck
    Oct 15, 2019 at 17:24
  • \$\begingroup\$ I guess just make sure to say that the seconds can be from 0-99, even if there are more than 2 digits, like my 192 example. (Although 192 is the same number of buttons as 232. Better example would be 960 which reads as 10:00 and takes 1 less button than 1000.) \$\endgroup\$ Oct 15, 2019 at 17:26
  • \$\begingroup\$ I think this would be more interesting if the 1-6 buttons were "instant start" number of minutes buttons and the 0 button allowed entering typing mode. \$\endgroup\$
    – Beefster
    Oct 18, 2019 at 22:54
1
\$\begingroup\$

Measure the Discrepancy

Given a finite sequence of real numbers \$ s_1, s_2, \ldots, s_n\$ and an interval \$I=[a,b]\$ that contains the whole sequence, find its discrepancy \$D_n\$.

Definition*

Let \$I = [a,b]\$ be an interval that covers the whole sequence \$(s_i)_i\$, that means for all \$i\$ we have \$s_i \in I\$. The discrepancy \$D_n\$ is defined as

$$D_n = \sup_{[u,v] \subseteq I} \left| \frac1n N(u,v) - \frac{v-u}{b-a} \right|$$

Here \$N(u,v) = \#\{i \mid 1 \leqslant i \leqslant n, s_i \in [u,v]\}\$ denotes the number of values of the sequence \$(s_i)_i\$ that are in the interval \$[u,v]\$.

* Technically the discrepancy \$D\$ is defined for infinite sequences as \$D = \lim_{n\to \infty} D_n\$. Intuitively speaking, the *discrepancy measures how uniformly distributed the sequence is in the given interval \$I\$. Sampling an uniform distribution on \$i\$ infinitely many times results in an discrepancy of \$D=0\$.

Examples

to be added...

\$\endgroup\$
7
  • \$\begingroup\$ I feel like u - v should be v - u? \$\endgroup\$
    – Kroppeb
    Oct 17, 2019 at 16:00
  • \$\begingroup\$ @Kroppeb You're right, thanks for pointing it out! \$\endgroup\$
    – flawr
    Oct 17, 2019 at 18:22
  • \$\begingroup\$ There is always the issue of taking real numbers as input, since there are more real numbers than binary strings. How should this fact be handled? \$\endgroup\$
    – Wheat Wizard Mod
    Oct 17, 2019 at 19:58
  • \$\begingroup\$ @SriotchilismO'Zaic We usually take floats as representations of reals. But I think we could even restrict it to integers and it wouldn't change much. \$\endgroup\$
    – flawr
    Oct 17, 2019 at 20:16
  • \$\begingroup\$ I think that this challenge is more interesting if you need answers to be precisely correct. Floating points open this up to brute force approaches which then boil down to just doing the operations. Which I just don't think is as interesting. \$\endgroup\$
    – Wheat Wizard Mod
    Oct 17, 2019 at 20:28
  • \$\begingroup\$ Please include a plain English description of the challenge. Surely I can't be the only one here that can't read mathematical notation! \$\endgroup\$
    – Shaggy
    Oct 19, 2019 at 23:03
  • \$\begingroup\$ @Shaggy Thanks for the feedback. I don't think I could remove all notation, but at the same time I have difficulties knowing where to start. Can you maybe point some notations out that you do or do not understand or think the average users might have trouble with? \$\endgroup\$
    – flawr
    Oct 20, 2019 at 10:16
1
\$\begingroup\$

Subtract two numbers with Rule 110

Background :

It is known that Rule 110 is Turing complete, but in general, I have seen a lack of actual programs that utilize this property of Rule 110, so I propose that we do something about it ;)

Some explanation

Rule 110 is a one dimensional cellular automaton, consisting of cells on/off, and the neighbors of those cells change the cell in the next iteration. Here is a page detailing how rule 110 works, but here is also a basic table that summarizes the rule (the center number is the current cell's state, the two on the outside are its neighbors, the number to the right of the equals is the state for the next generation)

111 = 0
110 = 1
101 = 1
100 = 0
011 = 1
010 = 1
001 = 1
000 = 0

The Challenge

I want you to subtract two numbers, unsigned, eight bits long (No handling of negatives, input one will always be greater than or equal to input two)

Note : Index 0 is where the first 1 starts, which denotes your program, simply because the "tape" is infinite, and leading zeroes cannot be distinguished, so it must start at the first one

Input have to be inputted in unary, and must be inputted at a set interval from a specific point from the beginning of your program, and the inputs must not overlap. That may sound confusing, but here are some examples.

First, clarification on input. Input needs to be 8 bits long, and must be formatted to be so, if you had zero, it would be inputted as follows : 00000000, 2 would be 00000011, 7 would be 01111111 etc..., up to eight.

The first input is at intervals of 2 starting at index 1, the second input has an interval of 3 and starts at 25

1 _ 01 _ 01 _ 10 _ 10 _ 10 _ 10 _ 10 _ 101 = 011 = 111 = 000 = 110 = 110 = 110 = 001 = 1010100101

The "_" is the first input, the "=" is the second input, they cannot overlap, and the interval represents the set distance that they must be seperated by. The bits themselves are inputed as ones, so if my first input was 00000111 and my second input 00111111 then my program would look like this

1 0 01 0 01 0 10 0 10 0 10 1 10 1 10 1 101 0 011 0 111 1 000 1 110 1 110 1 110 1 001 1 1010100101

The output is also defined in a similar fashion, from the start of the program (denoted by a 1) at specific intervals the bits represent the unary output

Example:

input one = 00011111, input two = 00000011

output = 00000111

Score

The number of bytes from the first one to the last one in the initial program. Lowest score wins! Good luck!!!

I thought this was ready for the main, but it wasn't, so if ya'll have any problems, please let me know and I'll address them, as I will for the problems already proposed

\$\endgroup\$
5
  • 4
    \$\begingroup\$ I think this is missing a lot before it can be a proper challenge, so sorry if this comes off as harsh, and thanks for using the sandbox. Since this is about a CA I don't understand what you mean by "bits" and "bytes" in several places, do you not mean to refer to cells? The difference between unary and binary IO is so significant that you should just pick one, having bonuses is highly discouraged anyway as it leads to unpleasant patterns for answerers. Is the scoring based on the initial width of the region that contains live cells? Or something else? \$\endgroup\$ Oct 5, 2019 at 18:40
  • \$\begingroup\$ If you mean that there are boundary cells (i.e. bits with only 1 neighbour instead of 2) you probably need to specify their rules as 110 usually has an infinite tape. You should also definitely include an explanation of 110 in your post. I think it is possible that if you allow the IO to be anywhere you may wind up with weird solutions. Certainly you can't allow that for unary IO since then they could require the inputs interleaved and the output would immediately be available. I think what you suggest is ok as long as input 1 is entirely more left than input 2 (but I'm not sure). \$\endgroup\$ Oct 6, 2019 at 15:27
  • \$\begingroup\$ I think your specification of the input looks good! I have somewhat minimal experience actually working with cellular automata so you probably want to run it past some other people before trusting me ;) Aside from that, I think you should specify the output a bit more (I assume it should be read on a certain generation? Or do you require steady state after a certain generation?). Then I think if you move the summary of 110 to your post (basically just copy the table) you just have some formatting / grammar issues until you are ready to post. \$\endgroup\$ Oct 7, 2019 at 19:29
  • \$\begingroup\$ I think the question looks pretty good, the only thing left I think is using "bits" for unary. I think it might be good to explain even just with an example that zero is exactly 00000000 and two is exactly 00000011 etc. For more expert CA help try the nineteenth byte chatroom, or try to hunt down some of the users who got tetris working in GoL :) \$\endgroup\$ Oct 9, 2019 at 20:07
  • 1
    \$\begingroup\$ Random weird question idea: "Now that we've done it in Life, create a game of Tetris in rule 110". \$\endgroup\$ Oct 10, 2019 at 11:34
1
\$\begingroup\$

Disconnect a social network

A version of this question was used in the 2019 International Mathematical Olympiad, which is now public. Modifications italicised.

A social network has n users, some pairs of whom are friends. Whenever user A is friends with user B, user B is also friends with user A. Events of the following kind may happen repeatedly, one at a time:

Three users A, B, and C such that A is friends with both B and C, but B and C are not friends, change their friendship statuses such that B and C are now friends, but A is no longer friends with B, and no longer friends with C. All other friendship statuses are unchanged.

Given the initial graph of users, find whether sequence of such events so that at the end of the sequence each user is friends with at most one other user exists, and if so output that sequence.

Test cases

These cases have n followed by a list of friendships in the graph, and output as a list of triples of people in order A-B-C (and 0 if no sequence of triples exists - note that this is different from [] in this particular output scheme, here [] means that the graph already satisfies the condition that each user is friends with at most one other user).

3, [[1,2], [2,3]]
[[1,2,3]]

3, [[1,3], [2,3]]
[[2,3,1]]

3, []
[]

3, [[1,2]]
[]

3, [[1,2], [1,3], [2,3]]
0

6, [[1,2], [2,3], [3,4], [4,5], [5,6]]
[[1,2,3], [1,3,4], [1,4,5], [1,5,6]]

6, [[1,2], [1,6], [2,3], [3,4], [4,5], [5,6]]
0

7, [[1,2], [1,3], [1,4], [2,3], [5,6]]
[[2,1,4], [1,3,2], [1,2,4]]

4, [[1,2], [1,3], [1,4], [2,3], [2,4], [3,4]]
0

6, [[1,2], [1,3], [1,4], [1,5], [1,6], [4,5], [4,6], [5,6]]
[[2,1,4], [3,1,5], [5,1,6], [2,4,6], [4,5,3]]

5, [[1,2], [1,3], [2,3], [2,4], [2,5], [3,4], [3,5]]
0

Input and output format are flexible as long as they conform to standard I/O requirements, and standard loopholes are forbidden. (In particular, for the impossible case, the output can be anything which is not an output from a possible graph, such as [[0,0,0]] or an additional 'success' boolean.)

This is , so the shortest code wins!

\$\endgroup\$
6
  • \$\begingroup\$ I suspect more answers will pretty much brute force the problem, trying all possible sequences. Are you OK with that? I don't know if there's a nice algorithm for this and you're hoping people make something like it. If you do want to restrict it, you could limit the run-time on test case or impose an algorithmic complexity ceiling. \$\endgroup\$
    – xnor
    Oct 21, 2019 at 5:12
  • \$\begingroup\$ Outputting either a list or 0 is not possible in strongly-typed languages. I'd suggest allowing some alternatives like [[-1, -1, -1]] or [[]] or a pair of a Boolean representing success and the list. \$\endgroup\$
    – xnor
    Oct 21, 2019 at 5:14
  • \$\begingroup\$ @xnor a) I don't know what the optimal algorithm is, so it'd be hard for me to set a limit (I heard that it could have potentially been a submission to the IOI but i don't know what form that would have taken) - do you have suggestions on how to make a reasonable restriction? b) I'm happy with any output format, as long as it distinguishes between the "already done" and "impossible" cases \$\endgroup\$
    – boboquack
    Oct 21, 2019 at 6:24
  • \$\begingroup\$ @xnor Do you think that a polynomial runtime bound would be interesting? Alternatively, would this make a good fastest-code question? If it becomes a fastest-code question, would I have to offer to test solutions on my machine? \$\endgroup\$
    – boboquack
    Oct 27, 2019 at 2:07
  • \$\begingroup\$ Do you know if there's a polynomial run-time algorithm? I think people usually test fastest code on their machines. Maybe you can test on TIO, but I think people said that might not be too consistent. \$\endgroup\$
    – xnor
    Oct 27, 2019 at 3:51
  • \$\begingroup\$ @xnor I believe I have a polynomial run-time algorithm - fastest-code is looking like probably a better challenge at this stage anyway... Since I don't have any idea what the best time-complexity is, should I make some large test cases of varying sizes to compare programs with? \$\endgroup\$
    – boboquack
    Oct 27, 2019 at 9:25
1
\$\begingroup\$

It was found that this challenge is a duplicate. if you would like to see the challenge, please look in the revision history.

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

Follow the Path

Posted here.

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

Fermat's Last Theorem, mod n

It is a well known fact that for all integers \$p>2\$, there exist no integers \$x, y, z>0\$ such that \$x^p+y^p=z^p\$. However, this statement is not true in general if we consider the integers modulo \$n\$.

You will be given \$n\$ and \$p\$, which are two positive integers with \$n>1\$. Your task will be to write a function or program to compute all positive integers \$x, y, z<n\$ such that \$(x^p+y^p)\$ and \$z^p\$ give the same remainder when divided by \$n\$.

Input

Any reasonable method of input is allowed. E.g. two separate user inputs, ordered pair, two function parameters, etc.

Output

Any reasonable method of output is valid, it may be produced by a function or output to the screen. The order the triples are listed does not matter. Triples such as (1, 2, 3) and (2, 1, 3) are considered distinct, and all distinct triples should be listed exactly once. No invalid/trivial triples such as (0, 0, 0) should be output.

Examples

n p -> Possible Output
----------------------------------------------------------------
2 3 -> []
3 3 -> [(1,1,2),(2,2,1)]
3 4 -> []
4 3 -> [(1,2,1),(1,3,2),(2,1,1),(2,2,2),(2,3,3),(3,1,2),(3,2,3)]

Scoring

Shortest code in bytes with no standard loopholes wins.

\$\endgroup\$
3
  • \$\begingroup\$ I'd wager the average user of this site isn't particularly familiar with the mathematical notion of modulus, compared to the programming concept. I suspect some of them will find the last statement in the intro slightly confusing (my guess thinking that only the RHS is taken in modulus). Beyond clarifying that, I think you should specify in your test cases which parameter is which (i.e. n p -> result as the first line). \$\endgroup\$ Oct 31, 2019 at 19:40
  • \$\begingroup\$ @FryAmTheEggman I have fixed those issues, is there anything else? \$\endgroup\$
    – 79037662
    Oct 31, 2019 at 20:02
  • \$\begingroup\$ I don't see anything beyond adding some more test cases (particularly with larger n). Technically, this could be calculated for large p even if the intermediate results wouldn't work for a particular data type, but I assume you don't want to require that? Other than that it looks good to me, but of course I'm just one person, so I'd still wait a while. \$\endgroup\$ Oct 31, 2019 at 20:22
1
\$\begingroup\$

Sort and Table a Sentence by Word Lengths

In as few bytes as possible, sort the input, a delimited string OR list/vector/array of words containing printable ASCII except space into a table (or something resembling a table). I tried to make the table rules as code friendly as possible to allow golfing and non-golfing languages alike to compete. Table rules are as follows:

  • optional order, shortest to longest or vice versa, letter counts are required
  • formatting is not the challenge, but to repeat the above rule, letter count is required. So as long as the output is some form of numerically labelled rows of words, a numbered list, or a list of lists, or similar output, then it is a satisfactory answer.

  • including/excluding gaps (NA values, see below examples for both methods of output)

  • Word case is untouched. How the word appears in input should be shown in output.

Input 1:

Code Golf and Coding Challenges Meta

Output 1:

 1. NA
 2. NA
 3. and
 4. Code Golf Meta
 5. NA
 6. Coding
 7. NA
 8. NA
 9. NA
 10. Challenges

or

3. and
4. Code Golf Meta
6. Coding
10. Challenges

or

[[3, ['and']], [4, ['Code', 'Golf', 'Meta']], [6, ['Coding']], [10, ['Challenges']]]

Input 2:

My very excellent mother just served us nine pizzas. #JusticeForPluto

Output 2:

1. NA
2. My us
3. NA
4. very just nine (alphabetized version: just nine very)
5. NA
6. mother served pizzas (mother pizzas served)
7. NA
8. NA
9. excellent
10. NA
11. NA
12. NA
13. NA
14. NA
15. NA
16. #JusticeForPluto

or

2. My us
4. very just nine
6. mother served pizzas
9. excellent
16. #JusticeForPluto

or

[[2, ['My', 'us']], [4, ['very', 'just', 'nine']], [6, ['mother', 'served', 'pizzas']], [9, ['excellent']], [16, ['#JusticeForPluto']]]

More examples can be provided if necessary but I think this should suffice for now. Please give me pointers, this is my second attempt at a challenge. (the first failed dramatically)

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Are the letter counts a required part of the output? I would suggest removing the requirement of filtering punctuation and just allow input as a delimited string or array of words. \$\endgroup\$
    – Shaggy
    Nov 10, 2019 at 22:06
  • \$\begingroup\$ @Shaggy That is a very good suggestion. I think that that is a fantastic idea. I'll make the edit. \$\endgroup\$
    – Sumner18
    Nov 11, 2019 at 13:39
  • \$\begingroup\$ @Shaggy I don't see why it would be difficult for letter counts to be required in the output. The idea is to place them in rows of a table that denote the word lengths within its row. \$\endgroup\$
    – Sumner18
    Nov 11, 2019 at 14:04
  • 1
    \$\begingroup\$ I wasn't suggesting they shouldn't be included, but, if they must be included, that you make that clearer in the spec. \$\endgroup\$
    – Shaggy
    Nov 11, 2019 at 14:07
  • 1
    \$\begingroup\$ What constitutes a "table?" Is the formatting you've used required, or is something like this alright? If it isn't, it seems like around half the code in several golfing languages will be devoted to formatting. Is that the intent? \$\endgroup\$ Nov 11, 2019 at 20:34
  • \$\begingroup\$ @FryAmTheEggman Thank you for the suggestion. I don't want formatting to be the focus of the challenge, but rather than just placing words in a list/array/vector with some form of label. Essentially a list of lists as you've done. I'll make the change \$\endgroup\$
    – Sumner18
    Nov 11, 2019 at 22:26
  • 1
    \$\begingroup\$ Thanks for the edits, though I don't think you need to include the program I wrote (it may even be more confusing since not many people read Pyth). I'd also recommend including something saying what class of characters the words will be drawn from, like "printable ASCII except space" or something. \$\endgroup\$ Nov 12, 2019 at 20:54
1
\$\begingroup\$

Sand timer puzzler (code-golf)

I was googling for a sand timer and found this little item: set of joined sand timers, for 3, 4, and 5 minutes each.

That of course reminded me of multiple puzzles about measuring X minutes using only M- and N-minute timers or whatever.

The mission then, if you choose to accept, is:

write a program that takes 3 integer inputs 0<A<B<C<100
and outputs list of all possible times that can be measured
using 3 joined sand timers A, B, and C up to 2 hrs

Test cases:

[in progress]

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Isn't this basically any number that can be formed by some combination of multiples of A, B and C? Some test cases would be nice, and an objective winning criterion (such as code-golf) is mandatory \$\endgroup\$
    – Jo King Mod
    Nov 15, 2019 at 0:23
  • 2
    \$\begingroup\$ I'm not clear what can be done with the timers. Can you flip any timer only when a timer runs out? Can you tell when two timers are the same level? Are the timers joined together like in the picture? If the answer turns out to be any multiple of the GCD of the numbers, I think that would make for a pretty boring challenge. Minor thing: I'd suggest writing "120 minutes" rather than 2 hours. \$\endgroup\$
    – xnor
    Nov 15, 2019 at 8:48
1
\$\begingroup\$

Guessing the subset.

Preface

I've never done a challenge before, so I'd appreciate some help to get this right. In particular, I'm not sure how much I should specify a (language-neutral) API. I'm also not sure how to implement time limits on computation time. (I want to be able to run a trial in seconds, not weeks.)


This challenge is based on Math Stack Exchange question "Guessing a subset of {1,...,N}".

In this challenge, the robber's job is to choose a subset \$R \subseteq \{1,\dots,N\}\$, kind of. Then the cop's job is to deduce the robber's subset by asking questions.


Robber

When I was growing up, I would sometimes play Twenty Questions with my brother. I would pick some sort of animal, and answer his questions about it. However, when he guessed the answer I had in mind, I would try to come up with another animal that satisfied all of the same answers to his questions—and if I could do it, I would tell him he was wrong.

The robber's job is similar to my strategy in Twenty Questions. The cop will ask the robber questions about the robber's chosen subset, but the robber can keep changing the subset as long as the answers are consistent. The robber's job is trying to answer the questions in such a way as to maximize the number of questions the cop needs to ask, always ensuring that the answers do not contradict each other.

Cop

The cop's job is to successively pick subsets starting with \$C_1 \subseteq \{1, \dots, N\}\$ and ask the question, "Does \$C_1\ = R\$, and if not how many elements do \$C_1\$ and \$R\$ have in common?" (That is, \$|C_1 \cap R|\$.)

If \$C_k = R\$, then the cop has finished the interrogation, and her score is \$k\$. Otherwise, the cop then can use this information to choose a new set \$C_{k+1}\$, and ask the same question for \$C_{k+1}\$.

Rules

Both the cop and robber will be given a number \$N\$, then the cop will go first outputting a subset \$C_1 \subseteq \{1,...,N\}\$. The robber will then take this as an input and output \$|C_1 \cap R|\$. The cop will take this number as an input and output \$C_2\$ and so on.

For a given interrogation both the cop's and robber's score is \$k\$ where \$C_k = R\$ is the last, correct guess. Naturally, the cop is trying to minimize her score while the robber is trying to maximize his.

Each cop will be tested against each robber (perhaps multiple times) with varying values of \$N \leq 1000\$. The score for the cop and robbers will be the sum of the scores over all interrogations.

\$\endgroup\$
1
  • \$\begingroup\$ I wish N was at most 24 so we can brute-force for 'giving the least information' answer as robber over 16M possible sets and then narrowing the set. Also consider this \$\endgroup\$ Nov 26, 2019 at 21:25
1
\$\begingroup\$

Name the hydrocarbon

A hydrocarbon is a chemical compound which consists of only hydrogen and carbon atoms. For this challenge, we will only consider the three simplest kinds of hydrocarbons: alkanes, alkenes, and alkynes with no branches.

An alkane with \$n\$ carbon atoms contains \$2n+2\$ hydrogen atoms. An alkene with \$n\$ carbon atoms contains \$2n\$ hydrogen atoms. An alkyne with \$n\$ carbon atoms contains \$2n-2\$ hydrogen atoms.

Each kind of hydrocarbon is named with a prefix indicating the number of carbon atoms it contains, followed by the suffix ane, ene, or yne if it is an alkane, alkene, or alkyne respectively. The numerical prefixes are as follows:

1  -> meth
2  -> eth
3  -> prop
4  -> but
5  -> pent
6  -> hex
7  -> hept
8  -> oct
9  -> non
10 -> dec

For example, we can see propane has 3 carbon and 8 hydrogen atoms, and heptyne has 7 carbon and 12 hydrogen atoms.

Challenge

Your task is to write a function or program that receives two integers, representing a number of carbon and hydrogen atoms, and produces or outputs the name of the corresponding hydrocarbon. Capitalization does not matter, and leading/trailing whitespace is allowed.

The input and output can be in any convenient format. You may assume the input will correspond to a valid hydrocarbon, and there are at most 10 carbon atoms.

Examples

Input -> Output
1 4   -> Methane
3 8   -> Propane
7 12  -> Heptyne
10 20 -> Decene

Rules

  • No standard loopholes.
  • Shortest code in bytes wins.

\$\endgroup\$
1
69 70
71
72 73
156

You must log in to answer this question.

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