502
\$\begingroup\$

What is the Sandbox?

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

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

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

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

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

To add an inline tag to a proposal use shortcut link syntax with a prefix: [tag:king-of-the-hill]

\$\endgroup\$

3037 Answers 3037

1
88 89
90
91 92
102
0
\$\begingroup\$

Compute the factorial, on both sides of 0

Why, why, why do factorials stop at zero? (Yes there are actual reasons). Make a factorial function (or full program) that doesn't stop at zero!

Your code-golfed program should, given an non-zero integer n (can be positive or negative, the rule still applies), find the product of the range n to -n excluding 0.

Graph that at least works for positive numbers

Sample IO

 Input          | Output
----------------|------------
0               | 1 (product of 0 and -0 without 0 / empty product)
2               | 4 (2*1*-1*-2)
3               | -36 (3*2*1*-1*-2*-3)
4               | 576 (4*3*2*1*-1*-2*-3*-4)
-4              | 576

Probably not a duplicate, but it might not be that much of a challenge.

\$\endgroup\$
  • \$\begingroup\$ Would the input always be positive? Is n=0 a possible input? \$\endgroup\$ – Bubbler Jun 11 '20 at 23:02
  • \$\begingroup\$ @Bubbler For now I'll say 0 is undefined, might change it later before posting if I have a good idea. \$\endgroup\$ – Wezl Jun 12 '20 at 13:53
  • 1
    \$\begingroup\$ As it is, isn't this always the factorial of the absolute value of the input squared, then made negative if the input is odd? - except in the edge case for zero? The sign of the input doesn't really appear to matter, which is an odd feeling. \$\endgroup\$ – FryAmTheEggman Jun 12 '20 at 16:24
  • \$\begingroup\$ @FryAmTheEggman Yes, see this graph of the values. Is that a bad thing? Do you have a better suggestion? \$\endgroup\$ – Wezl Jun 12 '20 at 20:44
  • \$\begingroup\$ "downvotes mean nothing but rudeness" - I downvoted this because I do not think "compute \$|n|!^2 \cdot (-1)^n\$" is a good challenge. I can't see how disagreement is rude. The requirements here seem completely arbitrary to me. This will result in the exact same approaches as were used in the factorial challenge. \$\endgroup\$ – the default. Jun 14 '20 at 8:27
  • 1
    \$\begingroup\$ I think it is a bad thing in that it becomes dangerously close to a dupe of the factorial problem. I probably wouldn't hammer it immediately, but if most of the responses basically worked for both or many others had the same concern I'd probably close it. I'm not sure of a good way to modify this to be better, so unfortunately I don't have any suggestions at the moment. I will let you know if something occurs to me. \$\endgroup\$ – FryAmTheEggman Jun 15 '20 at 20:09
  • \$\begingroup\$ @FryAmTheEggman I wouldn't consider it a dupe but I wouldn't consider it a good question after all based off of what my pronoun is monicareinstate said. \$\endgroup\$ – Wezl Jun 16 '20 at 21:47
  • 1
    \$\begingroup\$ If you consider 0 as a valid input, I suggest that its expected output be 1, which corresponds to the empty product (Wikipedia). \$\endgroup\$ – Bubbler Jun 17 '20 at 3:52
  • \$\begingroup\$ For the interesting-ness, I believe it can be interesting in at least some languages (which IMHO justifies the value of having such a challenge). FWIW, I have two J solutions of equal length, one using the factorial built-in ! and the other not using it. \$\endgroup\$ – Bubbler Jun 17 '20 at 3:53
  • \$\begingroup\$ I'd likewise close this as a duplicate, but I'm known for having much broader standards than the rest of the community about what questions are closeworthy, so make of that what you will. \$\endgroup\$ – pppery Jun 18 '20 at 2:38
  • \$\begingroup\$ I'll just abandon this, but if @Bubbler wants to post it, they can. \$\endgroup\$ – Wezl Jun 18 '20 at 21:17
0
\$\begingroup\$

Default Lightning Strike

Introduction:

Inspired by this reddit question: ELI5: Why does lightning travel in a zig-zag manner rather than a straight line?

Although it's more complex than this, in general multiple lightning paths will randomly check its immediate surrounding for the direction with least resistance (based on air pressure, temperature, composure, humility, etc.) and travel in that direction. As soon as one of the paths reaches the ground, that entire path has the least resistance and most (although not all) of the ions will accumulate in that path, causing the lightning flash and thunder.
Here a slow-mo video of a lightning strike to get an idea.

Challenge:

Input: An integer \$h\geq3\$ and an integer \$1\leq p\leq\left\lfloor\frac{h}{2}\right\rfloor\$

Output: Each step of the ASCII animation of a lightning strike, with a cloud to earth height of \$h\$ and up to \$p\$ paths

We start with a lightning ion at the cloud, with a lowercase letter of your own choosing (i.e. b). This ion will travel in a random direction (horizontally, vertically, or (anti-)diagonally), except where this path itself comes from. Every 'tick' it also has a 20% chance of branching out into two paths, as long as we haven't reached \$p\$ paths yet. Each of these paths will behave the same.
As soon as any path hits the ground based on the height \$h\$, all letters of that particular path will become uppercase, and in the final 'tick' after that, only this uppercase path will remain.

Challenge rules:

  • Paths can intersect with other paths
  • Paths can travel upwards beyond the height of our starting point
  • Output can be in any reasonable format. Could be a list of multi-line strings for each 'tick'. Could be a list of character-matrices for each 'tick'. Could be pretty-printed to STDOUT (with clear non-whitespace separation between each 'tick' - i.e. a single character like a comma or semi-colon, or a line of --- or ___)
  • Trailing spaces for each line of a tick are optional (leading as well, as long as the lightning bolts are still correct)
  • If multiple paths strike the ground in the same 'tick', only the first one of those two (or more) paths will become the lightning strike. The order in which paths are created are therefore important, so keep that in mind.

Examples:

This may all sound pretty vague, so here a couple of examples:
(I've added trailing spaces for each step with spaces, but you don't necessarily have to do so as mentioned in the challenge rules.)

Example 1: \$h=3, p=1\$

Tick 1:
"b"
" "
" "
Tick 2 (random direction: right):
"bb"
"  "
"  "
Tick 3 (random direction: up-left):
"b "
"bb"
"  "
"  "
Tick 4 (random direction: down-left):
" b "
"bbb"
"   "
"   "
Tick 5 (random direction: down):
" b "
"bbb"
"b  "
"   "
Tick 6 (random direction: up-right):
Note that this overlaps with a previous step in this path, which is fine.
" b "
"bbb"
"b  "
"   "
Tick 7 (random direction: down-right):
" b "
"bbb"
"b b"
"   "
Tick 8 (random direction: down):
" b "
"bbb"
"b b"
"  b"
Tick 9 (lightning strike):
" B "
"BBB"
"B B"
"  B"
Tick 10 (extra tick to remove all other paths, although there are none right now):
" B "
"BBB"
"B B"
"  B"

Example 2: \$h=5, p=2\$

Tick 1:
"b"
" "
" "
" "
" "
Tick 2 (random direction: down-left):
" b"
"b "
"  "
"  "
"  "
Tick 3 (random direction: down-left):
"  b"
" b "
"b  "
"   "
"   "
Tick 4 (random direction: right):
"  b"
" b "
"bb "
"   "
"   "
Tick 5 (random 20% path split; random direction 1: top-right, random direction 2: right):
"  b"
" bb"
"bbb"
"   "
"   "
Tick 6 (random direction 1: top-left, random direction 2: down):
" bb"
" bb"
"bbb"
"  b"
"   "
Tick 7 (random direction 1: left, random direction 2: down-right):
"bbb "
" bb "
"bbb "
"  b "
"   b"
Tick 8 (lightning strike of path 2):
"bbB "
" Bb "
"BBB "
"  B "
"   B"
Tick 9 (extra tick to remove all the other paths, which is path 1 in this case):
"  B "
" B  "
"BBB "
"  B "
"   B"

General rules:

  • This is , so shortest answer in bytes wins.
    Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
  • Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
  • Default Loopholes are forbidden.
  • If possible, please add a link with a test for your code (i.e. TIO).
  • Also, adding an explanation for your answer is highly recommended.

Sandbox Questions:

  • Should I perhaps use a different letter of the alphabet per path?
    • If yes: what would happen when different letter-paths overlap? I assume the top one will be visible per 'tick', but if lightning is struck it should still change it to the underlying letter as uppercase. In either case, you'll have to keep track of each individual path and uppercase only the one that struck the ground (first).
  • Any additional rules or things that are unclear?
  • An additional relevant tag?
  • More examples with more paths and/or larger height?
  • A different path percentage instead of hard-coded \$\frac{1}{5}\$ / 20%.
\$\endgroup\$
0
\$\begingroup\$

Sort numbers using as few distinct bytes as possible

Task

Write an algorithm that takes as input an ordered list (array, linked list, etc...) of numbers and outputs an ordered list containing the same numbers sorted by their value (ascending or descending).

The numbers may be represented using the most convenient format to you, with the only restriction that there must be a way to encode 256 distinct numbers. You are not allowed to use built-in sorting functions/algorithms.

Scoring criteria

Let \$c\$ be the number of distinct bytes in your code* and let \$s\$ be the number of bytes in your code*.
*Or its UTF-8 representation

The score is equal to \$c^2 + s\$. The answer with the lowest score wins!

Examples (imagine these are sorting algorithms):

  • ababccbaacbabcba\$c=3, s=16, score=25\$
  • aAbcd€f\$c=9, s=9, score=90\$
  • bytes 16 ee 3c 79 ee\$c=4, s=5, score=21\$

I'm open to suggestions, especially about the score formula.

\$\endgroup\$
  • \$\begingroup\$ I see that this is your first attempt at writing a challenge. Thank you so much for using the sandbox! \$\endgroup\$ – Adám Jun 25 '20 at 22:16
  • \$\begingroup\$ Please note that it is very hard to write good challenges that restrict solutions from certain things. This is because it is hard to define exactly what is prohibited in every language, and it is also hard to determine if any prohibited feature was used. \$\endgroup\$ – Adám Jun 25 '20 at 22:19
  • 1
    \$\begingroup\$ @Adám So how should I prevent trivial answers? Maybe "built-in sorting functions/algorithms" is a bit vague. \$\endgroup\$ – D. Pardal Jun 25 '20 at 23:04
  • \$\begingroup\$ We don't prevent trivial answers in most cases. Btw, if I accept plain numbers as input, may I assume the input is a list of integers between 0 and 255 inclusive? \$\endgroup\$ – Bubbler Jun 25 '20 at 23:46
  • \$\begingroup\$ How about this: "You are not allowed to use any built-in function/command that can take an ordered container and output the sorted result. Anything else is OK." \$\endgroup\$ – Bubbler Jun 25 '20 at 23:54
  • \$\begingroup\$ I think a good solution would be to allow built-in solutions, but to compile (in advance, so that it can be posted very quickly, probably via the "answer your own question" feature) a community wiki answer listing trivial 1-byte solutions. \$\endgroup\$ – the default. Jun 26 '20 at 4:17
  • \$\begingroup\$ @Bubbler Would still be unclear if J's /:~ or /:] were allowed or not. \$\endgroup\$ – Adám Jun 26 '20 at 6:15
  • \$\begingroup\$ @D.Pardal Why do you want to prevent trivial answers? \$\endgroup\$ – Adám Jun 26 '20 at 6:20
  • \$\begingroup\$ I wanted to prevent built-in functions because otherwise most answers would be exactly the same as the ones from this question. Maybe the easiest way to solve this would be to replace the task of sorting an array with another. \$\endgroup\$ – D. Pardal Jun 26 '20 at 7:15
  • 1
    \$\begingroup\$ Yes. Banning built-in has long been considered a bad idea. \$\endgroup\$ – user202729 Jun 26 '20 at 11:57
0
\$\begingroup\$

Fix mispellings

Wikipedia has a list of common misspellings, and there is also a machine-readable version!

Your challenge is to input a string and fix the mispellings in it.

The parituclar list we'll be using is https://en.wikipedia.org/w/index.php?title=Wikipedia:Lists_of_common_misspellings/For_machines&oldid=962756669#The_Machine-Readable_List. Note that even if the list changes, you must use this version. Here's a pastebin link: https://pastebin.com/j03aL98d.

Each line in the list is in the format INPUT->OUTPUT1, OUTPUT2, OUTPUT3, ... (of course, there may be more or less possible outputs, or even just one). That means that for input INPUT you must output exactly one of the possible outputs OUTPUT....

This is tagged , so the shortest answer wins.

Sandbox stuff

Should I add more misspellings to the post, or should I remove them?

\$\endgroup\$
  • \$\begingroup\$ Related \$\endgroup\$ – pppery Jul 2 '20 at 14:23
  • \$\begingroup\$ @pppery While the idea is probably related, I don't think the solutions would be related at all. \$\endgroup\$ – the default. Jul 2 '20 at 14:26
  • \$\begingroup\$ What is the input format? A plain English sentence (so we need to handle spaces, punctuation, capitalization), or is a list of words acceptable? How should capitalization be handled (some entries look like Tolkein->Tolkien and UnitesStates->UnitedStates; given unkown->unknown, what is the expected output of unkown, Unkown, UNKown, Tolkein, tolkein, TOLKEIN)? \$\endgroup\$ – Bubbler Jul 2 '20 at 23:19
  • \$\begingroup\$ @Bubbler The input is a single entry in the list (the part before ->, of course). You do not need to handle capitalization ("tOLKEIN" is not "Tolkein"). (will clarify later). \$\endgroup\$ – the default. Jul 3 '20 at 2:11
0
\$\begingroup\$

Overlap characters

Put all the characters of a given list, following the order, in a sequence of bits keeping it as small as possible.

Rules

  • Write the bits of each character on a line.

  • You can overlap bits if they are equal.

  • You cannot change already written bits.

  • Extend the line, in both directions, if not all the bits fit in.

  • Always try to extend as less as possible.

Example

input :['a','&','1','.']
     0110 0001  // a
0010 0110      // &
           001 1000 1     // 1
                 00 1011 10 // .
                 
output :0010011000011000101110

input : "&1a."

       0010 0110      // &
          0 0110 001     // 1
0 1100 001  // a
                 0010 1110 // .
                 
output : 011000010011000101110

I/O rules

  • input can be any sequence of single byte elements.

  • output the resulting sequence of bits in any convenient method, no extraneous bits allowed (0 or 1)

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

Distributive on myself

\$\endgroup\$
  • \$\begingroup\$ Now that this has been posted to main, could you delete this proposal to create more space for new answers? \$\endgroup\$ – caird coinheringaahing Sep 25 '20 at 1:04
0
\$\begingroup\$

Validating Words in Word Grids

A follow on from Generating Word Grids

Given a grid of letters, a set of co-ordinates and a dictionary of words, validate that the co-ordinates follow only cardinal direction changes, at least one of the co-ordinates touch an empty space in the centre of the grid, the resulting word is valid given the dictionary (taking into consideration any blank tiles) and return either the grid, with the letters at the co-ordinates removed along with the score of the word, or, if one of the conditions fail, the original grid and a score of -1.

Details

Please detail the format you want to accept coordinates in any reasonable format is acceptable.

Scoring

Letters are worth their values as per Scrabble:

0 points: blank tiles
1 point: E, A, I, O, N, R, T, L, S, U
2 points: D, G
3 points: B, C, M, P
4 points: F, H, V, W, Y
5 points: K
8 points: J, X
10 points: Q, Z

Bonus tiles (indicated by a lowercase letter, or ! for a blank tile) provide a *2 multiplier and stack (eg. if my co-ordinates spell gOLf I would earn (((2+1+1+4)*2)*2), 32 points).

Examples:

Input:

6,4 6,5 5,5 4,5 3,5 3,6 2,6 1,6
UWDESTKP?
ItDBaDEdI
TERMDYTSR
ROANJLEFT
EkCI OOsT
IPAJPGMNY
MZLORITVI
GwEGgPUeI
MNROYOEER

Output:

9
UWDESTKP?
ItDBaD dI
TERMDY SR
ROANJ  FT
EkCI  OsT
IPAJP MNY
MZLO  TVI
GwEGgPUeI
MNROYOEER

(spells RIGOLETE, (1+1+2+1+1+1+1))

Input:

0,3 0,4 0,5 0,6
UWDESTKP?
ItDBaD dI
TERMDY SR
ROANJ  FT
EkCI  OsT
IP  P MNY
MZL   TVI
GwE gPUeI
MNROYOEER

Output:

-1
UWDESTKP?
ItDBaD dI
TERMDY SR
ROANJ  FT
EkCI  OsT
IP  P MNY
MZL   TVI
GwE gPUeI
MNROYOEER

(spells DEST which doesn't appear in the dictionary)

Input:

5,6 4,6 4,7 4,8
UWDESTKP?
ItDBaD dI
TERMDY SR
ROANJ  FT
EkCI  OsT
IP  P MNY
MZL   TVI
GwE gPUeI
MNROYOEER

Output:

12
UWDESTKP?
ItDBaD dI
TERMDY SR
ROANJ  FT
EkCI     
IP  P  NY
MZL   TVI
GwE gPUeI
MNROYOEER

(spells MOsT, (3+1+1+1)*2)

Rules

This is so the shortest code in bytes wins.

  • The order is not important, it can be score then grid, or vice versa.
  • Any reasonable format can be used for I/O assuming it is consistent.
  • All standard loopholes are forbidden.


Questions for meta

Things have changed a lot in the time since I originally posted this, so rather than just posting I thought I'd bump for fredback.

  • What would the best way of using an associated dictionary be, taking it as input?
  • Obviously the input format for co-ordinates can be more flexible (0-based index, 1-based index, or something) is mentioning this enough?
  • Grid input format can be flexible too, mentioning this should be enough too?
  • Any other relevant tags?
\$\endgroup\$
  • \$\begingroup\$ This looks pretty good to me. \$\endgroup\$ – Rɪᴋᴇʀ Sep 15 '17 at 18:20
  • \$\begingroup\$ Thanks @Pavel, I'll bear that in mind, i'm not sure how much interest there is based off of part 1, but I might still post this in the next week or so :) \$\endgroup\$ – Dom Hastings Sep 16 '17 at 9:21
0
\$\begingroup\$

Count the available moves

Just a brief Lay-out of an idea, I‘ll expand it further soon.

Given an input representing a chess board, containing between 1 and 16 pieces of each colour, with White to play, output the number of moves that White is able to play. Input may be any reasonable representation of a chess board and output should be a single positive integer in the most reasonable output format in your language. Code golf, so shortest wins.

\$\endgroup\$
  • \$\begingroup\$ For the sake of avoiding retroanalytical issues, I suggest not counting en passant capture. Ignore castling too? \$\endgroup\$ – Rosie F Jul 19 '20 at 17:57
  • \$\begingroup\$ @RosieF Given that I only want the current board state as input, I think not counting en passant makes the most sense. However, I don’t see any reason to ignore castling, aside from „it makes the challenge more difficult“, and I have no problem with that \$\endgroup\$ – caird coinheringaahing Jul 19 '20 at 18:00
0
\$\begingroup\$

Crazy Blazin' DOM Injection

I was instructed to post this code golf challenge here for recommendations on how to modify the challenge.

I'd like to tag it.

fastest-code grid and browser , but I don't know how to do that here.

Code golf challenge listed below.

Introduction

This problem is a challenge that has to do with DOM manipulation at scale and overcoming some issues that may be inherent in dealing with the DOM.

  • This challenge is interesting because limitations push us to think through things differently and lean on the strengths of languages different than what we usually use.
  • I created this challenge myself based on a real world problem I ran into myself (details can be provided if needed). If this challenge has any relation to a differently know problem, those similarities are coincidental.

This challenge will be scored based on fastest execution and fastest algorithm. A multiplier will be given for completing the challege at easy, medium, and hard difficulties.

Challenge

You must render one of the challenge levels in a web browser:

Through any means available to you interacting through a web browser in code you need to complete the following:

  1. Get each table displayed and add a class table-n to each table where n is a zero based index of order of the table on the screen. If a table is nested within a table the parent would be N and the child would be N+1 with the next table being N+2.
  2. Get each row displayed in each table and add a class of table-n-row-r where r is a zero based index of rows in the table represented by table-n.
  3. Get each cell displayed in each table and add a class of table-n-row-r-cell-c where c is a zero based index of cells in a row represented by table-n-row-r.

At the end of the challenge the web page should still be able to be interacted through in the browser, and a call to document.getElementsByClassName('table-n-row-r-cell-c'); should return one and only one cell from the DOM.

Any method available to you as valid as long as:

  1. Access to one of the difficulty levels has been done through a web browser
  2. The URL of the browser and the page displayed doesn't change
  3. A call to document.getElementsByClassName('table-n-row-r-cell-c'); returns only one element

Output Examples

For this example we're using the easy level as input.

The abbreviated output in the DOM should be.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Code Golf Challenge</title>
</head>
<body>
    <table class="table-0">
        <thead>
            <tr class="table-0-row-0">
                <th class="table-0-row-0-cell-0">1</th>
                ...
            </tr>
        </thead>
        <tbody>
            <tr class="table-0-row-1">
                <td class="table-0-row-1-cell-0">11</td>
                <td class="table-0-row-1-cell-1">12</td>
                ...
            </tr>
            ...
    </table>
</body>
</html>

There are only <td> and <th> elements used as cell elements for the challenge.

As long as document.getElementsByClassName('table-n-row-r-cell-c'); returns an element with this class. We're good to go.

Qualifying Entries

All entries that qualify need to have an execution speed of under 40 seconds for any difficulty level.

Timing starts when your algorithm starts, but after the page has loaded completely as all elements must be available (the browser spinner has stopped spinning).

Calculate the runtime for your method by calling performance.now() before and and after your injection method, and subtracting the first from the second as in the example below.

let t0 = performance.now();
doSomething()   // <---- The function you're measuring time for 
let t1 = performance.now();
let totalTime = t1 - t0;

The medium and hard difficulty levels will have their execution time multiplied by 0.50 and 0.25 respectively. None the less, an execution time of less than 40 seconds is needed to qualify. So if the execution time on the medium difficulty was 41 seconds before the multiplier, it does not qualify.

Winner

The winner will be determined by the shortest execution time for dynamic injection of these classes and where document.getElementsByClassName('table-n-row-r-cell-c'); can still be executed against the browser console and return an element where n, r, and c are replaced with indexes.

\$\endgroup\$
  • \$\begingroup\$ Do you mean that all entries should be written as a JS function so that it can be run inside the browser console? Which browser(s) will you be using to time it (since different browsers may have different support of JS features and the engine optimized in different ways)? \$\endgroup\$ – Bubbler Jul 20 '20 at 2:15
  • 1
    \$\begingroup\$ "scored based on fastest execution and fastest algorithm" is ambiguous, because fastest execution means that a constant factor in the algorithm is important, while fastest algorithm is not. I think you mean simply "fastest execution", since it seems hard to use a big-O notation in this task (should it be a function of table size or entire document size?). \$\endgroup\$ – Bubbler Jul 20 '20 at 2:18
  • \$\begingroup\$ All entries should be written as a JS function (I think that's the only way to achieve it). However, if there are other ways to achieve this they are welcome, but it still needs to be an active webpage pulled from the internet. So, pulling via wget or curl and manipulating it locally in something like jelly is out of the question unless Jelly can interact with the browser. We can standardize on chrome 83.0.1.x for the web browser, so that it's exactly the same for all. \$\endgroup\$ – Dodzi Dzakuma Jul 20 '20 at 2:18
  • \$\begingroup\$ It should only be fastest execution then. Let's go with that. \$\endgroup\$ – Dodzi Dzakuma Jul 20 '20 at 2:19
  • \$\begingroup\$ Also, if a submission works for all of easy/medium/hard, how is it scored? I guess the minimum of (easy time), (medium time / 2), (hard time / 4)? \$\endgroup\$ – Bubbler Jul 20 '20 at 2:23
  • \$\begingroup\$ If a submission works for all level (qualifies at all levels) it gets scored at the hardest level it qualifies for. \$\endgroup\$ – Dodzi Dzakuma Jul 20 '20 at 2:24
  • \$\begingroup\$ That sounds like unnecessarily penalizing possibly good submissions because it might run blazing fast on easy but more than 4x slower on hard, giving it a worse score. \$\endgroup\$ – Bubbler Jul 20 '20 at 2:26
  • \$\begingroup\$ I can agree with that. How do you suggest we even that out? \$\endgroup\$ – Dodzi Dzakuma Jul 20 '20 at 2:27
  • \$\begingroup\$ Personally, I think it is better to do away with the different difficulty levels. They aren't exactly the same as bonuses in code golf but most of the arguments for why we don't like bonuses apply to these difficulties, too. \$\endgroup\$ – FryAmTheEggman Jul 20 '20 at 2:43
  • 1
    \$\begingroup\$ I think this will work: "The submission that handles the highest difficulty within 40 seconds wins, ties broken by the time taken to complete for that test case." If the first part of the sentence is confusing, I mean "a submission that handles hard is better than one that can't". \$\endgroup\$ – Bubbler Jul 20 '20 at 2:45
  • \$\begingroup\$ I'll get rid of the difficulty levels. \$\endgroup\$ – Dodzi Dzakuma Jul 20 '20 at 2:45
  • \$\begingroup\$ Actually, Bubbler, what you said makes sense. I'll state it like you said and get rid of the bonus. \$\endgroup\$ – Dodzi Dzakuma Jul 20 '20 at 2:48
  • \$\begingroup\$ Still getting downvotes on the challenge. I don't know the reason why. Implemented the changes we discussed, but I guess it still doesn't meet standards? (^-^;) \$\endgroup\$ – Dodzi Dzakuma Jul 20 '20 at 11:56
0
\$\begingroup\$

How wide is this string?

Given a unicode string in any standard encoding of choice, determine how many columns wide it is.

To keep this challenge relatively simple, use the following rules for character widths:

  • Tab characters align to the nearest multiple-of-8 column
  • CJK characters are 2 columns wide.
    • For the purposes of this challenge, you may assume all characters in Unicode Planes 2 and 3 (U+20000-3FFFF), plus codepoints U+3400-9FFF are CJK characters.
    • CJK characters outside these ranges may be treated as either 1 or 2 columns wide.
  • Combining diacritics (U+0300-036F), control characters (U+00-1F, U+7F-9F), and the zero-width space (U+200B) are all 0 columns wide.
    • All other officially zero-width characters may be treated as either 1 or 0 columns wide.
  • You may assume that there are no newlines or carriage returns.
  • You do not need to handle escape sequences.
  • You may assume all other characters are 1 column wide.
    • For any character the standard says has a specific width, you may use that width instead.

Shortest code wins.


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

Tumbling 2x2 in a Matrix

Challenge:

Input: A rectangular integer matrix that's at least 2x2 in size. Output: A 2D integer array, of the result after the top-left 2x2 block has tumbled down.

For example: Let's say we have the following 3x5 matrix as input:

[[ 4, 7,12],
 [11, 2, 5],
 [ 7, 3,15],
 [21,10, 1],
 [12, 6, 6]]

The 2x2 block is [[4,7],[11,2]], which will act as if it was tumbling down from a stairs (in a top-left to bottom-right direction). Here this process step-by-step:

[[ 4, 7,  ],
 [11, 2,  ],
 [--,  ,  ],
 [  ,  ,  ],
 [  ,  ,  ]]

[[  ,  , 4],
 [  ,11, 7],
 [--, 2,  ],
 [  ,  ,  ],
 [  ,  ,  ]]

[[  ,  ,  ],
 [  ,11, 4],
 [--, 2, 7],
 [  ,--,  ],
 [  ,  ,  ]]

[[  ,  ,  ],
 [  ,  ,  ,11],
 [--,  , 2, 4],
 [  ,--, 7],
 [  ,  ,  ]]

[[  ,  ,  ],
 [  ,  ,  ,  ],
 [--,  , 2,11],
 [  ,--, 7, 4],
 [  ,  ,--]]

[[  ,  ,  ],
 [  ,  ,  ,  ],
 [--,  ,  ,  , 2],
 [  ,--,  , 7,11],
 [  ,  ,--, 4]]

[[  ,  ,  ],
 [  ,  ,  ,  ],
 [--,  ,  ,  ,  ],
 [  ,--,  , 7, 2],
 [  ,  ,--, 4,11]]

Doing so, it will add it's values to the other cells in its path. So here is the same step-by-step process with the other numbers added in the cells:

[[ 4, 7,12],
 [11, 2, 5],
 [ 7, 3,15],
 [21,10, 1],
 [12, 6, 6]]

[[ 4, 7,16],
 [11,13,12],
 [ 7, 5,15],
 [21,10, 1],
 [12, 6, 6]]

[[ 4, 7,16],
 [11,13,16],  // Note that the 13 and 5 remain the same, because the cells of the tumbling
 [ 7, 5,22],  // block haven't moved from the previous to this step
 [21,10, 1],
 [12, 6, 6]]

[[ 4, 7,16],
 [11,13,16,11],
 [ 7, 5,24, 4],
 [21,10, 8],
 [12, 6, 6]]

[[ 4, 7,16],
 [11,13,16,11],
 [ 7, 5,24,15],  // Note that the 24 and 8 remain the same, because the cells of the tumbling
 [21,10, 8, 4],  // block haven't moved from the previous to this step
 [12, 6, 6]]

[[ 4, 7,16],
 [11,13,16,11],
 [ 7, 5,24,15, 2],
 [21,10, 8,11,11],
 [12, 6, 6, 4]]

[[ 4, 7,16],
 [11,13,16,11],
 [ 7, 5,24,15, 2],
 [21,10, 8,11,13],  // Note that the 11 and 4 remain the same, because the cells of the tumbling
 [12, 6, 6, 4,11]]  // block haven't moved from the previous to this step

Challenge rules:

  • I/O is flexible. You may take the input as integer-matrix, integer list with loose dimension-inputs, as a list of strings, etc. Output can modify the original input, return a new matrix, print space/newline delimiter to STDOUT, etc.
  • You may optionally take the dimensions as additional input.

General rules:

  • This is , so shortest answer in bytes wins.
    Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
  • Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
  • Default Loopholes are forbidden.
  • If possible, please add a link with a test for your code (i.e. TIO).
  • Also, adding an explanation for your answer is highly recommended.

Test case:

Input:
[[ 4, 7,12],
 [11, 2, 5],
 [ 7, 3,15],
 [21,10, 1],
 [12, 6, 6]]
Output:
[[ 4, 7,16],
 [11,13,16,11],
 [ 7, 5,24,15, 2],
 [21,10, 8,11,13],
 [12, 6, 6, 4,11]]

TODO: More to come.


Sandbox questions:

I might change the tumbling process a bit later on, since I'm not too happy about the current one. I still want the tumbling 2x2 down the matrix, but I might make the way the other values changes a bit different. This is just an initial idea.

  • Any missing tags?
  • Any missing rules?
  • Any suggestions on how to change the output without changing the core part of the tumbling top-left 2x2 block?
  • Any suggested test cases?
\$\endgroup\$
0
\$\begingroup\$

Trapping a Jogger

A person starts jogging to the right from his house on a busy street.

t=0
0 1 2 3 4 5 6 7 8 9 A B C
⌂ - - - - G - - G - - - G
>

He travels 1 hectometer every minute, so he is 11 hectometers away from his house after 11 minutes:

t=11
0 1 2 3 4 5 6 7 8 9 A B C
⌂ - - - - R - - R - - - G
                      >

Since this is a busy street, there are walking signals that occasionally turn red. In this example, the signals at 5, 8, and 12 units from home alternate colors every 2, 10, and 4 minutes (this would not be a fun road to drive on). The signals are red (signal stop ✋) for the same duration that they are green (signal go 🏃).

Our jogger doesn't want to wait long, so he instantly turns around when he reaches a stoplight that is red, even if it will turn green within the next minute.

t=12
0 1 2 3 4 5 6 7 8 9 A B C
⌂ - - - - G - - R - - - R
                        >
t=12.001
0 1 2 3 4 5 6 7 8 9 A B C
⌂ - - - - G - - R - - - R
                        <
t=13
0 1 2 3 4 5 6 7 8 9 A B C
⌂ - - - - G - - R - - - R
                      <

This can cause the jogger to reverse direction again, making for a potentially long outing.

t=16
0 1 2 3 4 5 6 7 8 9 A B C
⌂ - - - - G - - R - - - G
                <      
t=16.001
0 1 2 3 4 5 6 7 8 9 A B C
⌂ - - - - G - - R - - - G
                >      

View the rest of the sequence using a visualizer.

Task

Given the cycle intervals and positions of a list of streetlights, determine the time until the jogger returns to his house (at distance 0) or runs to the right of the rightmost streetlight.

The streetlights at time t=0 will all have just turned green.

The n cycle intervals shall all be integers at least 2. The n positions of the streetlights may be taken as either (sorted) absolute distances from home or the distance from that streetlight to the previous. In the example, this would be either [5,8,12] or [5,3,4].

Example cases

positions
intervals
output

5,8,12
2,10,4
38

10
20
11

10
6
20

2,8
8,6
40

2,8
7,6
16

1,2,3,4,5,6
6,5,4,3,2,1
16
```
\$\endgroup\$
0
\$\begingroup\$

International "Hello, World!" (WIP)

(Please note the special scoring for this challenge)

This code-golf question has over 900 answers and all of them print "Hello, world!" in English! If we can use hundreds of different programming languages to print that message, why can't we use hundreds of different natural languages to express that message?

Task & scoring

Your task is to beat the answers of the Hello, world! challenge ("HW" challenge from now on) in different natural languages, as determined by the length ratio of the English string "Hello, world!" and the string in the natural language you pick. For example, I could pick Portuguese, hence I will have to print "Olá, mundo!" which has a length ratio of 11/13.

  • if your natural language has capitalization, you must respect the original capitalization.
  • if your natural language has punctuation, you must respect the original punctuation.

Then you pick the programming language you are going to write your code in. For example, I could pick Python. And you write your program. My program could be print("Olá, mundo!"), with a standard code-golf score of 20.

You then look for the best submission in the HW challenge with the same programming language you chose, let's say it has score S. (We probably need a leaderboard for challenge HW to make this step easier.) My score would then be (20/S)/(11/13).

Does this make any sense? Any preliminary feedback?

\$\endgroup\$
  • 1
    \$\begingroup\$ It's hard to define whether the grammar of the output is correct in the chosen language, especially for those who don't know the language. \$\endgroup\$ – user92069 Jul 29 '20 at 9:46
  • \$\begingroup\$ @user92069 why do I need to define if the grammar is correct? "Hello, world!" doesn't look grammatically very correct either. \$\endgroup\$ – RGS Jul 29 '20 at 22:36
0
\$\begingroup\$

Extract an integer from another

This is a somewhat interesting problem I ran into while nanboxing: given two integers, compute their bitwise-AND and concatenate the resulting "substrings" into a new integer.

More precisely: you are provided two integers as input — an input integer and a bitmask. As output, you should produce the bitwise-AND of the two such that, given a mask with \$n\$ set bits, the corresponding bits from the input are grouped together in the first \$n\$ bits of the resulting integer.

The following pseudocode is one way to implement the function:

-- x and mask are lists of booleans
function (x, mask)
  local result=list();
  for i=1, min(x.length, mask.length) do
    if mask[i] then
      result.append(x[i]);
    end
  end
  return result;
end

Example inputs and outputs

// In binary:
// f(x, mask) == result
f(1011, 1111) == 1011 // Select entire number
f(1010, 1010) == 11   // Select bits 1 and 3, and concatenate them
f(11001100, 01100110) == 1010 // Concatenate substrings [1:2] and [5:6]
f(11111111, 10101010) == 1111 // Concatenate bits at odd indices.

// 16-bit variants in hexadecimal:
f(BEEF, 1111) == 9
f(DEAD, 8888) == F 
f(1337, FF00) == 13
f(CODE, 7777) == 82E

// Two 64-bit variants (in hex):
f(400921FB54442D18, CODE601F15DABE57) == 111DE42C8
f(FFFE0000004010CC, 8003000000000000) == 6

Specific rules

  • Standard loopholes, default IO, etc. apply where not overridden.
  • Input and output values must fulfill \$x \in \{b_{set}, b_{unset}\}^{n}\$ for some \$b_{set} \neq b_{unset}, n \in \mathbb{N}_{\geq 16}\$ of your choice. In other words:
    • You must support integers of at least 16 bits in your representation, but you may otherwise arbitrarily constrain their size - i.e. to 32-bit integers. You may also accept integers of any length through lists, arrays, strings, etc.
    • The "set" and "unset" values do not need to be of the same type or length, but they must be constant and distinct.
    • Most "linear" representations for integers are valid: integers, vectors, arrays, strings, etc.
  • This is , so the shortest answer in bytes wins.
  • Have fun!
\$\endgroup\$
  • \$\begingroup\$ Is this the PEXT BMI2 instruction? (also, possible duplicate: codegolf.stackexchange.com/q/37167) \$\endgroup\$ – the default. Jul 30 '20 at 13:00
  • \$\begingroup\$ @mypronounismonicareinstate After reading the referenced challenge I think this is indeed a duplicate of that. The required algorithms are identical and other requirements seem to not affect this too much. \$\endgroup\$ – Shieru Asakoto Aug 3 '20 at 4:07
  • \$\begingroup\$ @mypronounismonicareinstate I've given it a read, and it definitely is the same challenge, bar minor cosmetic differences. Of course, the search did not find it when I tried searching for it... \$\endgroup\$ – CompilerPotato Aug 3 '20 at 11:46
0
\$\begingroup\$

Mega Man

My first polyglot challenge, enjoy!

Validness of a program

In this challenge, a "program" doesn't take an input. This challenge doesn't care of any output, though.

An invalid program, either:

  • Doesn't compile, or

  • Compiles, but the program doesn't halt when executed.

A program is valid otherwise.

The 6 Robot Masters

A robot master is a valid program. Their language can be chosen freely, not necessarily all same or all distinct.

There are 6 Robot Masters in total, namely Cut Man, Elec Man, Ice Man, Fire Man, Bomb Man, and Guts Man.

(Yeah, I wanted to include Time Man and Oil Man as well, but that would make this challenge too hard.)

Weapons

The robot masters have their distictive weapons. (This doesn't mean the robot masters' source code acts as their weapon, though.) A weapon is an operation on a string.

  • Cut Man's weapon, Rolling Cutter, leaves the target source's first half characters only, rounded down. Example: Hello, world!Hello,

  • Elec Man's weapon, Thunder Beam, eliminates all whitespaces. Example: Hello, world!Hello,world!

  • Ice Man's weapon, Ice Slasher, turns all uppercase ASCII letters small. Example: Hello, world!hello, world!

  • Fire Man's weapon, Fire Storm, turns all lowercase ASCII letters capital. Example: Hello, world!HELLO, WORLD!

  • Bomb Man's weapon, Hyper Bomb, eliminates the target source's first word. The behavior on the surrounding whitespaces is implementation-defined. Example: Hello, world!world!

  • Guts Man's weapon, Super Arm, doubles all characters. Example: Hello, world!HHeelllloo,, wwoorrlldd!!

Objective

When a weapon is applied to a robot master's source code, if and only if it hits their weakness, the resulting code must be a valid program in the robot master's language.

  • Rolling Cutter is the weakness of Elec Man.

  • Thunder Beam is the weakness of Ice Man.

  • Ice Slasher is the weakness of Fire Man.

  • Fire Storm is the weakness of Bomb Man.

  • Hyper Bomb is the weakness of Guts Man.

  • Super Arm is the weakness of Cut Man.

Every other combination is not a weakness and must result in an invalid program. This includes a weapon applied to its owner.

Scoring

This is a code golf. The score is the sum of the byte counts of all 6 source codes. The answer with the least score wins.

\$\endgroup\$
  • 3
    \$\begingroup\$ I find the organisation of the text quite confusing. If I've understood correctly (and I had to read it several times), the challenge boils down to this: write 6 programs, each of which is only valid when one of the weapons is applied to it. Is that right? Since the programs aren't required to implement the weapons, I don't really understand why each robot master is associated with a program. Lastly, do you mean 'execute' rather than 'compile'? \$\endgroup\$ – Dingus Aug 17 '20 at 8:28
  • \$\begingroup\$ @Dingus Well, it was pretty hard to make a reference to the game. I've clarified the 'compile' and 'execute'. The challenge boils down to, Write 6 programs, each of which is valid and also valid when a weapon is applied, but is invalid when any other weapon is applied. \$\endgroup\$ – Dannyu NDos Aug 17 '20 at 9:42
  • \$\begingroup\$ Ahhh, that makes more sense - I wasn't aware of the game (living under a rock, maybe). Perhaps you should include some more context about it. It seems a bit strange that hitting a weakness results in a valid program (would have expected the opposite), but the description is clear enough. I would suggest a small tweak to 'if and only if it hits their weakness, the resulting code must still be a valid program'. \$\endgroup\$ – Dingus Aug 17 '20 at 10:20
  • \$\begingroup\$ About 'compile', I meant in the bullet points where you define what an invalid program is. Many languages are not compiled languages. \$\endgroup\$ – Dingus Aug 17 '20 at 10:23
0
\$\begingroup\$

[PuyoPuyo] How long is my combo?

Context:

PuyoPuyo is a puzzle game where you and your opponent pile up colored slimes (called puyo) in a vertical (13*6 cells) grid. A puyo is one-cell big, but they come as pairs in the screen. Puyo pairs fall from the top to the bottom of the grid, and you can move and rotate them the Tetris way. The list of possible puyo pairs is the cartesian product of {'red','blue','green','yellow'} with itself. The pair sequence for a game is randomly generated for both players at the start of a round, and will be the same for both of them.

If four puyo (or more) of the same color are next to each other (in line, in square, Z-, S-, T-, J- or L-shaped), they disappear, awarding you points and making all the above puyo to fall. If when those puyo fall, they make another group of four (or more) they will disappear too, awarding you with more points than the first group: it is called a two-hit combo.

When a combo stops, whatever its length (1-hit or more), you will send damage to your opponent. The bigger the combo, the more damage is sent. Those damage are called ojama puyo, grey slimes that disappear only when a group disappears next to it. If your third column from the left is filled before your opponent's is, you lose. So to kill your opponent, you must manage to fill its screen before they fill yours.

Challenge:

With a given sequence of puyo pairs associated with their drop locations, output the length of the combo that has been made by this player. Shortest code in any language wins.

Input:

List of puyo pairs and their drop locations:

  • 'r1b1r1r2y2r3...'
  • '001000013102...'
  • [('red','1','blue','1'),('red','1','red','2'),('yellow','2','red','3'),...]
  • any sensible way you want, provided you detail how it works

Details:

  • This list will never contain any "column number" outside of [1;6] (or [0;5], if 0-indexed) nor a puyo of a color outside of {'red','blue','green','yellow'} (or any set used for your interpretation).
  • This list will always contain at most one combo sequence.
  • This list will never contain unusable data, like two colors in a row, or two column indices in a row.
  • If both puyo of a pair are dropped on the same column, the first one to come is on the top of the pair (in the example #1, red is dropped on the top of the blue on the column 1).
  • Puyo will never remain floating in the grid, but will fall to the lowest available cell of the column they are in, even if the paired puyo has stopped in its column (tl;dr puyo pairs split).

Output:

A single integer indicating the length of the combo.

Test cases:

Test case #1

Input
y1r1

Output
0

Test case #2

Input
r1r2g3r3g3g2g1r2

Output
2

Test case #3

Input
y1r1r2r3g2g3r2g3y2y3g3g3y1y1

Output
3

Test case #4

Input
b1b1r2b2g3g3r2r3y4y5b6b6b5y5g4b5y4g3b6b6

Output
1

Test case #5

Input
y1b2b3b3b5b5y6b6b4b4

Output
1

Test case #6

Input
y1r1r2r3g2g3r2g3y2y3g3g3y1y1

Output
3

Test case #7 (click me!)

Input
b1b2g3r4g5y6y1y2b3g4r5g6y1b2g3r4g5y6r1r2g3r4r5y6r1b2b3y4r5y6b1y2y3r4r5g6r1b2r3y4g5g6y1g2r3b4b5b6b1g2g3r4r5g6b1b2r3y4b5r6g1y2b2y3y4g4g5g6g5g6

Output
17

Test case #8 (click me!)

Input
r1r2r5r6g1r2r5g6g1y2y5g6g1y2y5g6y1g2g5y6y1b2b5y6r1b2b5r6b1r2r5b6b1y2y5b6b1y2y5b6y1r2r5y6y1r2r5y6r3r4

Output
4

Standard Loopholes apply.

NB: for purists, I know that the 13th row is supposed to be invisible and that puyo that are in that column are not considered 'linked' to nearby puyo, but I figured this challenge was hard enough as-is.

@Sandbox please comment! I'd love to hear your thoughts about such a challenge. I will finish setting it up soon, adding some extra resources about the game (like this one). Questions:

  • Should I reverse the "top / bottom" puyo of a pair rule? The way it is now, it forces to parse input as pairs. If it is reversed, golfers can take puyo one by one and sort it all by columns, making the challenge easier.
  • What tags should it enter with?
  • I will make other test cases soon enough, but should I include a as a file (via pastebin)?
\$\endgroup\$
  • 1
    \$\begingroup\$ "The combo"? Will there be only one combo? \$\endgroup\$ – user202729 Aug 15 '20 at 11:07
  • 1
    \$\begingroup\$ Does the two puyo(s) in a pairstick to each other like in tetris? \$\endgroup\$ – user202729 Aug 15 '20 at 11:07
  • \$\begingroup\$ Thanks for your comments @user202729, I'll be editing the challenge soon. This challenge will let you assume there will only be one combo. And puyo pairs are broken upon drop if need be, so that every single puyo cannot be floating in the grid. \$\endgroup\$ – V. Courtois Aug 18 '20 at 11:51
0
\$\begingroup\$

Sort until overflow - POSTED HERE

\$\endgroup\$
  • \$\begingroup\$ Now that this has been posted to main, could you delete this proposal to create more space for new answers? \$\endgroup\$ – caird coinheringaahing Sep 25 '20 at 0:37
0
\$\begingroup\$

Quineoid Triple Uniqueness Optimization


This is a variant of Quineoid Triple with the same requirements but different scoring.

Write three different programs such that when any one program is provided as input to one of the other two, you get the source of the remaining program as output. More explicitly, given programs \$A\$, \$B\$, and \$C\$, where \$f(g)\$ denotes the output obtained from inputting the text of program \$g\$ into program \$f\$, all of the following must hold:

  • \$ A(B) = C \$
  • \$ A(C) = B \$
  • \$ B(A) = C \$
  • \$ B(C) = A \$
  • \$ C(A) = B \$
  • \$ C(B) = A \$

Scoring

The goal is to have the three programs be as different as possible.

Your score is the sum of:

  • Number of unique bytes found in program \$A\$, but not \$B\$ or \$C\$
  • Number of unique bytes found in program \$B\$, but not \$A\$ or \$C\$
  • Number of unique bytes found in program \$C\$, but not \$A\$ or \$B\$

The theoretical maximum score is 256.

Additional Rules

  • Standard quine rules apply.
  • Each program can be in any language. Any number of them may share languages or each may use a different language.
  • Use any convenient IO format as long as each program uses a consistent convention.
    • Functions are allowed, as this counts as "any convenient IO".
  • The result of feeding a program its own source code is undefined
  • The result of feeding anything other than program text of either of the other two programs is undefined.
  • Byte encoding should be taken into account for languages with dedicated codepages.

SANDBOX: this is kind of -ish. Should I call it a bowling challenge?

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

Modular Chain Compression

A common trope in some kolmogorov-complexity challenges is to use repeated application of the modulo operator in order to compress large integers or string hashes into some range. For example, we can squash the numbers \$13,4,16\$ into \$0,1,2\$ by taking each number mod \$7\$ and then mod \$3\$. We call this sequence the modular chain \$7,3\$. In general, reducing a number \$k\$ by the modular chain \$n_1,n_2,\ldots,n_i\$ is equivalent to evaluating

$$(((k\ \text{mod}\ n_1)\ \text{mod}\ n_2)\ \ldots\ )\ \text{mod}\ n_i$$

In this challenge, you will be challenged to compress an arbitrary set of integers in this way. We say the length of the modular chain is the number of elements in the chain (not the number of bytes).

Input

You are given a fixed set of \$100\$ random 32-bit integers. Here they are:

2997344323
2062352342
1953414591
... (more on the actual post) ...

Output

Via whatever means necessary (brute-force, mathematics, etc) design a modular chain to compact these numbers into a small a range as possible. The modular chain must have a distinct output for each input number.

Scoring

In code-golf challenges, a modular chain is usually desirable if it achieves two things:

  • It compacts the input numbers or hashes into a small range.
  • It is short.

In this spirit, your score is the sum of the maximum output number of your modular chain and the length of your modular chain for the given input numbers.

Note an optimal modular chain could compress the input numbers into the range \$0 \ldots 99\$ with a single modulo operation, making the theoretical minimum score \$99 + 1 = 100\$.

The lowest scoring answer wins. You are encouraged (but not required) to post any code, mathematical background etc. that helped you design your modular chain.

\$\endgroup\$
  • \$\begingroup\$ Length in modulo operations or bytes? \$\endgroup\$ – user253751 Aug 25 '20 at 9:41
  • \$\begingroup\$ @user253751 The number of operations. Clarified. \$\endgroup\$ – Sisyphus Aug 25 '20 at 10:28
0
\$\begingroup\$

The fastest code to find a subset-sum

Given k sorted integers from low to high, output n permutations of those integers with sum as close as possible to m but not exceeding m. The output needs to be sorted from highest to lowest sum.

Input

k integers, n, m - as described above. All the k integers and m are positive 31-bit integers. Now since this is NP-complete problem, both k and n are small integers, 20 at most.

Output

One row for each premutation, with integers sorted from high to low. Also, the rows need to be sorted from highest to lowest sum

The fastest code wins

For the performance test, we will use the below input:

  • k = [67, 613, 2111, 2179, 2203, 2269, 3433, 3583, 4219, 5011]
  • m = 14,213
  • n = 10
\$\endgroup\$
  • 3
    \$\begingroup\$ 1) You might want to provide multiple test cases, so that the submissions don't use an algorithm that is fast only in some of them and very slow in the others. 2) For fair evaluation of speed, you need to run all submissions on your machine, so you need to provide some information about your machine's OS, RAM, CPU (also GPU if you want to allow using it). 3) Is the sum of all k integers guaranteed to be positive 31-bit integers? Otherwise we might face overflows during calculation. 4) I think you mean subsets instead of permutations. \$\endgroup\$ – Bubbler Aug 28 '20 at 4:42
0
\$\begingroup\$

[Unnamed]

This challenge is based on a somewhat unusual premise; the goal is to create a rectangular program (box) which is as large as possible, where each row and column will be a solution to a different challenge on this site.

For example, a 3×4 box might look like this:

abcd
 :-]
1234

As all solutions will be read from left to right or top to bottom, this would expand into seven programs:

abcd
 :-]
1234
a 1
b:2
c-3
d]4

For an answer to be valid, each one of these must be a valid solution to a different challenge on this site, in the same language. The box may be padded by whitespace, but must be rectangular (x groups of y bytes, separated by newlines). This is code bowling, so the longest answer in bytes wins.

Additional rules/clarifications:

  • Solutions cannot contain newlines (because otherwise they would be two separate rows/columns)
  • Yes, it will be possible to trivially get very high scores with some languages (like unary), but as with most challenges it's a competition within each language
  • Solutions do not have to be original, but ones copied from other answers should link to them
\$\endgroup\$
  • \$\begingroup\$ Unary won't be able to compete because the number of challenges on our site is lower than most Unary programs. It will be very hard to compete even in golfing languages, as the answerer will need to manually find the appropriate challenge to use. I don't really think a challenge that makes use of "all challenges on our site" is fun. \$\endgroup\$ – Bubbler Sep 10 '20 at 1:40
  • \$\begingroup\$ @Bubbler Yeah, now that I think about it I agree. I still like the concept, maybe there's something similar that might actually be fun. \$\endgroup\$ – Redwolf Programs Sep 10 '20 at 2:37
  • \$\begingroup\$ Maybe you could select a subset of challenges - something like what was done for this challenge? \$\endgroup\$ – Dingus Sep 17 '20 at 11:43
  • \$\begingroup\$ @Dingus Good idea! I'll see if I can fix a few other things, too. \$\endgroup\$ – Redwolf Programs Sep 17 '20 at 12:39
0
\$\begingroup\$

Targeted sum and difference of a sequence

You are given two things: a target integer(not necessarily positive) n, and a sorted list/array/etc. of non-negative integers a. (The list will have at least two elements). Your goal is to choose one element of a as your total, and then one by one, take elements of a, and either add or subtract them from your total. Print out all possible combinations(duplicates can be removed, but it is optional) of [a_1]±[a_2]±[a_3] or return them as a list/array/etc. .

In other words, find all solutions to n=[a_1]±[a_2]±[a_3]. The first element of a is not guaranteed to be a_1, nor is the second element guaranteed to be n_2.

Test cases:

n = 10, a = [1,2,3,4] :  10 = 1+2+3+4 and 2+1+3+4 ...
# The output should be 1+2+3+4(and 4+2+3+1, and every combination like that)
n = 1, a = [2,3]: 1 = 3-2, so 3-2. 
# (-2+3 wouldn't work, since it is strictly addition or subtraction of positive integers).
# -2 isn't a part of [2,3]. You should think of the steps as [a_1]±[a_2]±[a_3].
# n = -5, a = [0,5,1]. -5 = 0-5, and nothing else.
n=95, a = [50,50,5]. 95 = 50+50-5, 50-5+50. (A second 50+50-5 is optional)

Criteria: Shortest code wins

Meta:

Is this clear enough(and what should I do to make this more clear)? Also, has this been done before? Finally, should I remove the restriction on the first number being positive?

Thank You!

\$\endgroup\$
  • \$\begingroup\$ What do you mean by "The first element of a is not guaranteed to be a_1"? \$\endgroup\$ – Zgarb Sep 11 '20 at 7:01
0
\$\begingroup\$

A centered hexagonal number is a centered figurate number that represents a hexagon with a dot in the center and all other dots surrounding the center dot in a hexagonal lattice.

Illustration of initial terms:

                                 o o o o
                   o o o        o o o o o
         o o      o o o o      o o o o o o
   o    o o o    o o o o o    o o o o o o o
         o o      o o o o      o o o o o o
                   o o o        o o o o o
                                 o o o o

   1      7          19             37

Write a function that takes an integer \$n\$ and returns "Invalid" if \$n\$ is not a centered hexagonal number or its illustration as a multiline rectangular string otherwise.

Sample Output :-

hexLattice(1) ➞ " o "
// o

hexLattice(7) ➞ "  o o  \n o o o \n  o o  "
//  o o
// o o o
//  o o

hexLattice(19) ➞ "   o o o   \n  o o o o  \n o o o o o \n  o o o o  \n   o o o   "
//   o o o
//  o o o o
// o o o o o
//  o o o o
//   o o o

hexLattice(21) ➞ "Invalid"

Rules

Shortest Code Wins!

\$\endgroup\$
  • 4
    \$\begingroup\$ I like the challenge concept! Usually, we advise against input validation; that is, rather than outputting "Invalid", solutions should assume the input is valid, though if you do that this challenge is almost a duplicate and so I think in this case it could make for an interesting challenge to leave it in. \$\endgroup\$ – HyperNeutrino Sep 23 '20 at 13:11
  • 4
    \$\begingroup\$ Another thing is usually we encourage flexible input/output formatting; in this case, in addition to a multiline string, I would also allow a list of strings or a matrix of characters as output, and rather than strictly outputting "Invalid", I would suggest allowing solutions to state any reasonable parameters for how they'll indicate invalid input. \$\endgroup\$ – HyperNeutrino Sep 23 '20 at 13:13
  • \$\begingroup\$ Related-ish. There are several other hexagon related challenges but this was the only one I could find that required computing the centred hexagonal numbers. \$\endgroup\$ – FryAmTheEggman Sep 24 '20 at 18:58
0
\$\begingroup\$

Word Length-Sum Multiples

\$\endgroup\$
  • \$\begingroup\$ Now that this has been posted, I've edited it down to save space and I'd recommend you delete the proposal \$\endgroup\$ – caird coinheringaahing Sep 25 '20 at 0:15
0
\$\begingroup\$

Double Prime Words

\$\endgroup\$
  • 1
    \$\begingroup\$ tags would be decision-problem, code-golf, primes, I think? \$\endgroup\$ – Giuseppe Sep 8 '20 at 19:07
  • 1
    \$\begingroup\$ I think if and only if x is prime should be if and only if n is prime? \$\endgroup\$ – Giuseppe Sep 8 '20 at 19:08
  • \$\begingroup\$ Additional exampleː Is this word a double primeː Hello Worlds aardvark aalii Aani \$\endgroup\$ – Xwtek Sep 10 '20 at 12:36
  • \$\begingroup\$ @Xwtek Is that 4 separate examples, or 1 long example? \$\endgroup\$ – Sumner18 Sep 10 '20 at 15:09
  • \$\begingroup\$ Now that this has been posted, I've edited the post down to save space and I'd recommend you delete this proposal \$\endgroup\$ – caird coinheringaahing Sep 25 '20 at 0:19
0
\$\begingroup\$

\$d\times n\$ dimensional word matrices [WIP]

Given two positive integers \$n\$ and \$d\$, and a list of words \$a\$, produce a \$d\$-dimensional matrix \$m\$ with each dimension having length \$n\$, filled with letters, that contains the words from \$a\$ placed such that they form a directly adjacent contiguous path through the dimensions.

For example, given \$d = 1\$, \$n = 3\$ and \$a = \$['cat'] output one of:

cat

or

tac

Given \$d = 2\$, \$n = 3\$ and \$a = \$['cat', 'hat', 'mat'] output something similar to:

cat
hat
mat

Given \$d = 3\$, \$n = 3\$ and \$a = \$['low', 'complexity'] output something similar to:

coq
igw
typ

kmc
xeo
buf

kpr
dll
scm

or, if it's easier to visualise in an array structure:

[
  [
    ['c', 'o', 'q'],
    ['i', 'g', 'w'],
    ['t', 'y', 'p'],
  ],
  [
    ['k', 'm', 'c'],
    ['x', 'e', 'o'],
    ['b', 'u', 'f'],
  ],
  [
    ['k', 'p', 'r'],
    ['d', 'l', 'l'],
    ['s', 'c', 'm'],
  ],
]

Which contains low at nested indices \$m[2][1][2]\$, \$m[1][1][2]\$, \$m[0][1][2]\$ and complexity at \$m[0][0][0]\$, \$m[0][0][1]\$, \$m[1][0][1]\$, \$m[2][0][1]\$, \$m[2][1][1]\$, \$m[1][1][1]\$, \$m[1][1][0]\$, \$m[0][1][0]\$, \$m[0][2][0]\$, \$m[0][2][1]\$.

I'd like to add some more complicated examples beyond three dimensions here.

Test Cases

TODO

Rules

  • Unused spaces should be filled with randomly selected letters.
  • There will always be enough space in the dimensions provided to allow the words to be added without re-using letters.
  • There is no requirement to ensure the words don't also appear elsewhere in the grid, so for example if the filler letters happen to spell one of the provided words, that is acceptable.

Questions for meta

  • This seems fun to me, any thoughts?
  • Is it too easy/hard?
  • Any other tags that are relevant?
  • As a follow up, I'd like to have a nested matrix provided and have programs solve it - but that might be better as a fastest-code challenge - is this a reasonable precursor?
\$\endgroup\$
  • \$\begingroup\$ Is d^n large enough to contain all the words without sharing letters? \$\endgroup\$ – Bubbler Jul 23 '20 at 8:18
  • \$\begingroup\$ Yeah, you won't have to be concerned with that, I'll add that to the rules. \$\endgroup\$ – Dom Hastings Jul 23 '20 at 8:21
0
\$\begingroup\$

Find a 3-Language Polyglot

What I had in mind was that cops would create a polyglot with in 3 languages (languages A, B, and C). When run in A, the program would print the name of language B; when run in language B, the program would print the name of language C; and when run in C, it would print the name of language A.

Cops have to provide the names of these 3 languages, as well as their original polyglot's characters scrambled in no particular order. as well as a valid program in A that has the same behavior as the polyglot (prints the name of B). This program must be able to be created by deleting characters from the original polyglot, i.e., all the letters in it are included in the hidden polyglot.

Given the languages and the scrambled programand the sample program, robbers have to find the polyglot (or a polyglot that has the same behavior as the one the cop wrote).

Rules

  • Any language chosen must be able to be run on TIO, repl.it, ideone, or someplace else online. If the language is obscure, please provide a link to some such website.
  • Any language used must have documentation on Esolangs, Wikipedia, GitHub, or someplace else. Unless the language is very commonly used and has tons of tutorials everywhere, such as Java, Haskell, or C, please provide a link to documentation. Any feature used in the program must be included in that documentation - it shouldn't be something people have to dig through layers of source code to find.

Questions for meta:

  • Is this too easy/hard? Should I not include the extra A program? Should I only make it for 2 languages?
  • Is there anything unclear about the instructions? How can I improve the phrasing?
  • Should cops also give the length of their programs as an extra hint?
\$\endgroup\$
  • 1
    \$\begingroup\$ one thing to consider: you would need some way of restricting languages that are allowed. Otherwise people could just make up their own languages or use really, really obscure languages. \$\endgroup\$ – thesilican Aug 18 '20 at 23:04
  • 2
    \$\begingroup\$ IIRC, the usual way to limit the language list is to specify "the language should be on at least one of Wikipedia, TIO, or esolangs.org", though esolangs is already crazy these days. \$\endgroup\$ – Bubbler Aug 19 '20 at 5:05
  • \$\begingroup\$ @Bubbler Yup, I've edited my question with some restrictions now \$\endgroup\$ – user Aug 20 '20 at 15:01
0
\$\begingroup\$

Terminal Punch Card

moved because apparently it's not clear enough.

So back in the day, computers didn't have fancy keyboard and mouse inputs, and didn't have your fancy screens. Instead they had punch cards.

Punch card

Punch cards punchers punched (try saying that 10 times fast) a hole out of a card to represent a 1-bit, and left it filled to represent a 0-bit. The cards were some number of holes wide, with each hole representing a bit in a byte.

Recently, you discovered an old mainframe at your local university that accepted punch cards that were 8 holes wide. For this challenge, you will be given data as an input, and your job is to punch a punch card to the terminal output, like this:

Hello, World!

: *  *   :
: **  * *:
: ** **  :
: ** **  :
: ** ****:
:  * **  :
:  *     :
: * * ***:
: ** ****:
: ***  * :
: ** **  :
: **  *  :
:  *    *:

The input will be a string or bytes representing the punched data payload. The output data must include rows, which start and end with a :, and have 8 bits between them, represented as a for 0, or a * for 1. There must be one row for each byte of data.

Here's the catch: The punch card puncher only punched one hole at a time, so in your program, must print (or add to the output string) only one character at a time.

Example of unacceptable method call:

# `binary` is some string with the binary bits.
print(":" + binary.replace("0", " ").replace("1", "*") + ":")

Acceptable method call:

for bit in binary:
   print(bit == "1" ? "*" : " ", "")

Also acceptable method call:

output = ""
for bit in binary:
   output += bit == "1" ? "*" : " "

The challenge is code golf, so least number of bytes wins. Standard rules/loopholes are in effect.

\$\endgroup\$
  • 4
    \$\begingroup\$ A word about catches before we even discuss observability and clarity issues: Catches are rarely a good idea for two reasons. The first is that challenge writers frequently add catches because they somehow feel their challenge is deficient or too easy and want to salvage it somehow. This coping mechanism usually fails, they are better off writing a new challenge. \$\endgroup\$ – Wheat Wizard Oct 4 '20 at 12:17
  • 3
    \$\begingroup\$ Note also there are already comments here regarding observability, assuming language features, and assuming implementation details \$\endgroup\$ – Luis Mendo Oct 4 '20 at 12:19
  • 4
    \$\begingroup\$ The second, which I think is more relevant to you, is that structuring your challenge with a catch is often confusing. You have already written what is a complete challenge, but then in the last 10% or so the whole task changes. Some people don't read the whole challenge once they think they have it, miss the last bit or become frustrated when things are pulled out from under them. Regardless of how you feel about these people, It is really just better to phrase your challenge in a straight forward and upfront way. Nothing should seem tacked on if you can avoid it. \$\endgroup\$ – Wheat Wizard Oct 4 '20 at 12:21
  • 3
    \$\begingroup\$ One way you could easily make your catch observable is to take a string and an index and output the character at that index. Of course answerers can just produce the entire string and index it, but they could already do that with your existing version (probably, it's a little unclear). \$\endgroup\$ – Wheat Wizard Oct 4 '20 at 12:26
0
\$\begingroup\$

Socially distanced seating

Lord Lloyd Warbler wants to minimise the harm to his theatre's seating capacity for his hit show, Birds, of maintaining social distancing.

The social distancing rules in Westendland are:

  • Groups may sit together without distancing
  • Between groups there must be at least 2 empty seats along the row, and 1 empty row in front and behind.
  • The closest diagonal permitted is a knight's move - only 1 horizontal space empty.

Diagrams:

 A _ _ B

 A
 _
 B

 A _ _
 _ _ B

Given a list of group sizes and the theatre size (rows and columns), can you pack them all into the theatre? Groups can sit in any contiguous (connected) arrangement of seats.

Sample tests

(Rows, cols), [groups] -> canFitBool
(1,1), [1] -> true
(2,2), [1,1] -> false
(2,3), [1,1] -> true   // knight's move
(5,2), [4,4] -> true   // 2x2 in rows a,b, gap in c, 2x2 in d,e

questionmarks

  • Should I just provide a list of cases of varying difficulty? Like, some of these could be pretty difficult.
  • Is the knight's move rule too complicated?
  • Is the contiguous rule too permissive, and therefore complicated? It could mean some edge cases are possible if you have a weird shaped group. Could make it rectangular blocks only?
\$\endgroup\$
  • \$\begingroup\$ Groups can sit in any contiguous (connected) arrangement of seats You need to decide, and specify in the text, if contiguous means 4-connectivity (up, down, left, right) or 8-connectivity (diagonals count as connected too) \$\endgroup\$ – Luis Mendo Oct 4 '20 at 12:17
0
\$\begingroup\$

I have abandoned this challenge. If you would like to take it over, feel free to take the idea, and maybe leave a comment so people know you've taken over.

File Selection

(See revision history)

\$\endgroup\$
  • 1
    \$\begingroup\$ "You may not open a file explorer and run the commands" and "No builtin for this exact challenge" - why? This just rules out what could have been an interesting/laughable solution. \$\endgroup\$ – NieDzejkob Nov 27 '17 at 15:37
  • 2
    \$\begingroup\$ @NieDzejkob Yeah but anyone who posts one will probably end up getting a ton of undeserved upvotes having done next to no work. It shouldn't be a huge problem because probably approximately 0 languages have a builtin to do this, but still. \$\endgroup\$ – HyperNeutrino Nov 27 '17 at 15:43
  • \$\begingroup\$ It's kind of implied that there is only one column, but if that's the case that should be explicit as things like Shift-UpArrow function very differently if there are multiple columns. \$\endgroup\$ – AdmBorkBork Nov 29 '17 at 14:55
1
88 89
90
91 92
102

You must log in to answer this question.

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