568
\$\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

4545 Answers 4545

1
84 85
86
87 88
152
1
\$\begingroup\$

Optimal Duck Game Moves

\$\endgroup\$
1
  • 2
    \$\begingroup\$ I would prefer if the instructions were in the post itself, they aren’t that long. \$\endgroup\$
    – noodle man
    Aug 6 at 14:55
1
\$\begingroup\$

The rectangle spanned by two numbers

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

Print every Unicode character (almost)

Print every Unicode character, except U+0000. Any order is allowed.

Specification

Every Unicode character from U+0001 to U+10FFFF, inclusive. Exclude U+D800 to U+DFFF inclusive as apparently these 'surrogates' cause weird behaviour.

To be honest, I don't know much about Unicode so before this gets posted someone will have to fill me in on how Unicode works

\$\endgroup\$
4
  • 2
    \$\begingroup\$ This might be more suitable as a CMC. \$\endgroup\$
    – Adám
    Aug 23 at 11:53
  • 1
    \$\begingroup\$ Please remove your edit in all caps and/or change it to not be in caps. This just clutters the post. \$\endgroup\$ Aug 23 at 15:32
  • 4
    \$\begingroup\$ Does this include non-printable (e.g. U+00) / unassigned (e.g. U+D800-U+D8FF) Unicode characters? \$\endgroup\$
    – bsoelch
    Aug 23 at 17:37
  • \$\begingroup\$ What's a CMC? @Adám || EDIT: nvm found it "chat mini challenge" \$\endgroup\$
    – W D
    Aug 24 at 6:15
1
\$\begingroup\$

Multiply multivariate polynomials

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

Make a braille cribbage board

The braille characters lie in the range U+2800 () to U+28FF (), making it a SBCS (Single Byte Character Set). Oddly enough, the braille patterns look a lot like holes in a cribbage board. Here is an image of one of the many cribbage boards for reference:

Cribbage Board

So you must print this pattern:

+-------+
|⣀⣀⠀⣿⠀⣀⣀|
|⣿⣿⠀⠀⠀⣿⣿|
|⣿⣿⠀⠀⠀⣿⣿|
|⣿⣿⠀⠀⠀⣿⣿|
|⣿⣿⠀⠀⠀⣿⣿|
|⣿⣿⠀⠀⠀⣿⣿|
|⣿⣿⠀⠀⠀⣿⣿|
|⣿⣿⠀⠀⠀⣿⣿|
|⠉⠉⠀⣿⠀⠉⠉|
+-------+

Note that the blanks are U+2800 and NOT the space.

,? is ,7tag3code-golf7'1 s %orte/ code w9s6

Oh, we're not using grade 2 contracted braille. You're not blind.

This is , so shortest code wins!


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

Half even rounding

\$\endgroup\$
1
  • \$\begingroup\$ As far as I know, PowerShell and brev also use banker's rounding, and some languages like Jelly that may be similar/based on Python may have a built-in that's a "Python round() function" || also, you may want to specify that this is Python 3 behaviour \$\endgroup\$
    – W D
    Aug 22 at 9:24
1
\$\begingroup\$

Implement RAID

RAID, or Redundant Array of Independent Disks is a way to efficiently store data in such a way that if any one disk fails you can still recover the data. Instead of implementing the official protocol, any function that can preserve data counts.

Your task is to produce two functions.

The first is the encoder. Given N lists with M elements each, produce N+1 lists with M elements each. What these lists contain is up to you.

The second part is the recovery system. Take as input the lists produced by the encoded, except one is missing. You must be able to recover the original data no matter which of the lists is gone.

Each list should contain only integers between 0 and 255. It is your choice how to represent the empty list, for example you can:

  • Replace it with an empty list
  • Replace it with a non-list value like None
  • Prefix all present lists with a 1 and the missing list with 0.
  • Take as a separate input which list is missing then just zero out the values.

Example

A basic XOR based solution could look like this:

Encoder:

def encode(list_of_lists):
    return [*list_of_lists, [reduce(lambda a,b:a^b, i) for i in zip(*list_of_lists)]]

def decode(list_with_one_removed):
    return [
        (i if i else [reduce(lambda a,b:a^b, j) for j in zip(*(k for k in list_with_one_removed if k))
        for i in list_with_one_removed
    ][:-1]

You don't need to use a XOR based solution, as long as you can extract the original data again your solution is valid.

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

Efficiently solve quadratic equations when 1+1=0

This is a sequel to my previous challenge about solving quadratic equations in the shortest possible code, this challenge is about solving the same task the fastest possible way

The goal of this challenge is to find a solutions for a general quadratic polynomial ax²+bx+c. Meaning be an integer r such that a*r*r+b*b+c is zero, with + meaning exclusive or and * being carry-less multiplication (use xor as addition in binary long multiplication).

To simplify the problem, you can assume that both a and b are one, so you only have to solve equations of the form r*(r+1)=n for an integer n. As any quadratic equation can be converted in this normal form, this is enough to solve the general case (up to linear transformations)

Your challenge will be to solve this simplified equation in the most efficient way possible.

Input: An integer n Output: A number r such that r*(r+1)=n with * being multiplication without carry and + being exclusive or.

Rules:

  • You may assume there is an integral solution to the equation
  • You only have to return one of the two roots (the other root will only differ in the last bit)
  • You program should be able to handle inputs up to at least 0x5555555555555555aaaaaaaaaaaaaaaa
  • The algorithm you are using should work for arbitrarily large n
  • The program with the lowest time complexity in n wins
  • For your score you can assume that xor-addition and xor-multiplication are computed in O(1) (even if your program might need O(n²) operations)
  • If multiple programs have the same complexity, the shortest program (per language) wins

Examples (both possible solutions given):

6 -> 2 | 3
20 -> 4 | 5
18 -> 6 | 7
72 -> 8 | 9
78 -> 10 | 11
...
113427455640312821160607117168492587690 = 0x5555555555555555aaaaaaaaaaaaaaaa -> 0xfffffffffffffffe | 0xffffffffffffffff

Meta

  • Would this be an interesting challenge ?
  • Should I extend the challenge to general polynomials (this can be done in O(1) multiplications/divisions after solving the original problem (or computing the normal square root in some cases))?
  • Is the rule about multiplication&addition do not count towards the complexity clear?
\$\endgroup\$
1
\$\begingroup\$

Golf the fast growing hierarchy

\$\endgroup\$
2
  • \$\begingroup\$ Looks like a really interesting challenge; but you might want to be careful with languages saying "oh but my biggest integer value is [X small number] so I only have to deal with that case" \$\endgroup\$
    – W D
    Aug 22 at 8:12
  • 2
    \$\begingroup\$ @WD That would abuse the loophole "Abusing native number types to trivialize the challenge". \$\endgroup\$ Sep 3 at 15:01
1
\$\begingroup\$

Simulate Round Robin Scheduling

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

Fastest decimal to binary

Same challenge, but code golf

Given a decimal number, your task is to convert it to binary.

Test cases

8496867758 -> 111111010011100111110100110101110
28284301455933783441 -> 11000100010000110000001100101000101001000111111110011110110010001
701550526345030865283462565098928586836 -> 1000001111110010011011011101110100010101010100010110011100010101100110100000111111010100100011101000000011010011011100000001010100

Rules

  • You can take input either as a string containing decimal digits, or a list of decimal digits.
  • You need to output the number in binary, either as a string containing the binary digits or a list of binary digits.
  • You are allowed to have leading zeros in the output.
  • The input won't contain leading zeros.

Scoring

Your score is the maximum number of digits your code can handle in under a second on my computer (Intel Core i7-9700 with 8 threads, 32GB RAM). If your code takes less than a second for a number with a million digits, you beat all solutions which can't do that, and the tie-breaker is the time it takes for a million digit number.

To calculate the time I will randomly select 10 numbers, and look at the average time.

Meta question

Is this a dupe? I looked for this question but couldn't find it.

I noticed that using GMP's standard I/O functions this takes 0.05 seconds for a million digit number. Is there a point to this question, or is it likely GMP is optimized enough that this will be the winning solution?

\$\endgroup\$
6
  • \$\begingroup\$ Will the program be reset between calls or is it allowed to reuse temporary values (e.g powers of 10) computed in the first call for the other 9 calls \$\endgroup\$
    – bsoelch
    Sep 21 at 15:35
  • \$\begingroup\$ @bsoelch I'd say it's reset between calls, although allowing precomputation somehow might be good? I'm not sure what would be more interesting. \$\endgroup\$ Sep 21 at 15:39
  • \$\begingroup\$ On my computer time python3 -c 'bin(int("1"*1000000))' executes for 4 seconds \$\endgroup\$
    – l4m2
    Sep 22 at 0:31
  • \$\begingroup\$ About GMP: You could ban third party libraries. At least in Python the standard library version of string to int is not the fastest possible solution (I tried a relatively simple recursive approach and managed to get the time for 1000000 digits from over 4 seconds to below one second). \$\endgroup\$
    – bsoelch
    Sep 22 at 17:20
  • 1
    \$\begingroup\$ Bad news: Python is probably getting an impl that can convert 4,000,000-digit numbers in 0.3s. It is already available as a 3rd party lib. github.com/python/cpython/issues/90716#issuecomment-1717742073 \$\endgroup\$
    – Bubbler
    Sep 25 at 6:32
  • 1
    \$\begingroup\$ Also there is very little point in banning 3rd party libs, as you can always copy the entire code to submit it anyway. \$\endgroup\$
    – Bubbler
    Sep 25 at 6:38
1
\$\begingroup\$

Barbrack

Your task is to write a program or function that takes a non-negative integer (in decimal or any other convenient base for your language) and output a number in the numbering system Barbrack.

What's that?

Barbrack is a numbering system I made up that can represent non-negative integers. Zero is represented with an empty string or an underscore, one is represented with [], and all other positive integers can be represented with a brack.

A brack is delimited with brackets [] and works as follows (with an example of 84):

  1. Take your number a and find its prime factorization. In this case, the prime factorization of 84 is 22*31(*50)*71.
  2. Find the indices of these primes, where the index of 2 is 1. In this case, the index of 3 is 2, since it's the prime right after 2, and the index of 7 is 4, since it's the fourth prime.
  3. Take the exponents of each prime, and put them in brackets in increasing order of the size of the prime, with consecutive exponents being separated by bars (|). So the general format is [exponent of 2|exponent of 3|exponent of 5…]—in this case, [2|1|0|1]. Minimize the number of cells!
  4. Recursively calculate the exponents in Barbrack, remembering that 0 is the empty string and 1 is []. So [2|1|0|1] => [[1]|[]||[]] => [[[]]|[]||[]].
  5. Output the final result.

Test inputs

0 -> (nothing)
1 -> []
2 -> [[]]
5 -> [||[]]
45 -> [|[[]]|[]]
84 -> [[[]]|[]||[]]
65535 -> [|[]|[]||||[](48 bars)[]]
65536 -> [[[[[]]]]]

(sidenote: (48 bars) means 48 consecutive bars in the actual output)

Rules

Scoring

Minimum bytes on a per-language basis.

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Can characters other than [|] be used? \$\endgroup\$
    – lyxal
    Sep 24 at 23:59
  • \$\begingroup\$ No, actually. I would allow other symbols, but I'm trying to stay true to my own base. (Let me guess, angle brackets for Vyxal?) \$\endgroup\$
    – Someone
    Sep 25 at 0:02
  • \$\begingroup\$ @Someone It's generally preferred to be flexible with the output format. There's no reason for those characters specifically to be used, as far as I can tell. In fact, instead of strings, you could allow nested lists too (unless I'm reading the challenge wrong) \$\endgroup\$
    – user
    Sep 25 at 1:15
  • \$\begingroup\$ Yeah, the /10 bonus was definitely imbalanced. \$\endgroup\$
    – Someone
    Sep 25 at 12:56
  • \$\begingroup\$ Input validation is generally discouraged. Is there a particular reason you want it? How would it even work if I write a function which takes unsigned int as input? \$\endgroup\$ Sep 25 at 18:45
  • \$\begingroup\$ Fair point. The rule was basically just "undefined behavior" but dumber anyway. \$\endgroup\$
    – Someone
    Sep 25 at 18:47
1
\$\begingroup\$

Golf my code


For this challenge, I'll use edit histories of answers to create a dataset of answers that have been golfed. Your task will be to write a program/function that, given a submission that was golfed in the future, will attempt to golf the submission.

You may choose the language, out of a set I'll choose based on the quantity and quality of data available, that your inputs will be in. You may choose to take inputs from multiple languages, which will not be differentiated (e.g., you can choose to score your answer over a combined Python + Jelly dataset).

The first part of your score will be the sum of bytes golfed by your program for each input, with any submissions that don't become shorter (including becoming longer) or become invalid having no impact on your score (might change this later, since otherwise you have no reason not to use a dataset of all languages).

Your final score will be your score, minus the number of bytes in your program. So, if you golf a total of 1920 bytes off the Python answers dataset, with 1080 bytes of code, your final score will be 840. Higher scores are better.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ I get the idea that the program is supposed to golf answers in a specific language, but I don't understand how we're expected to do that and programmatically return correct golfed answers, please add an example \$\endgroup\$
    – noodle man
    Sep 30 at 18:18
  • 1
    \$\begingroup\$ On top of the problem of validation, I feel like this has some problems depending on the languages you pick. Definitely don't include unary. \$\endgroup\$ Oct 3 at 19:20
1
\$\begingroup\$

Given A Binary String, Determine Which Of Certain Substrings Are Equal And Opposite

yea the title is going to need some work

Concept

Take an even length binary string

1 1 0 1 0 0 1 0

Between each bit, place an arrow

1 1 0 1 0 0 1 0
 ^ ^ ^ ^ ^ ^ ^

Next, find each substring centered on each arrow which includes either/both the start and the end of the string

1 1
 ^
1 1 0 1
   ^
1 1 0 1 0 0
     ^
1 1 0 1 0 0 1 0
       ^
    0 1 0 0 1 0
         ^
        0 0 1 0
           ^
            1 0
             ^

If each half of the binary string has all of the flipped bits of the other half (in any order), replace the arrow with a 1, else a 0

1 1
 0
1 1 0 1
   0
1 1 0 1 0 0
     1
1 1 0 1 0 0 1 0
       1
    0 1 0 0 1 0
         0
        0 0 1 0
           0
            1 0
             1

Then get rid of the sublists which will leave you with just the arrows-turned-bits

 0 0 1 1 0 0 1

You must output those bits.

Examples:

00 0
01 1
10 1
11 0
0000 000
0001 001
0011 010
1001 111
1011 100
1100 010
000011 00010
100101 11111
101101 10001
00110011 0101010
00111100 0101010
10101010 1111111
11000101 0111011
11010010 0011001
11100010 0011101

Meta

yea I don't have the vocabulary for this. I'm gonna hammer at it some more but if you read this and something jumps out at you where youre like "oh i know what thats called" Please let me know thank you

\$\endgroup\$
10
  • \$\begingroup\$ What does "opposite digits" mean? \$\endgroup\$
    – Someone
    Sep 25 at 0:22
  • \$\begingroup\$ @Someone im not sure how to phrase it, but if you have X 1s and Y 0s on one end, you need to have Y 1s and X 0s on the other side. \$\endgroup\$ Sep 25 at 1:05
  • \$\begingroup\$ So order doesn't matter? \$\endgroup\$
    – Someone
    Sep 25 at 12:55
  • \$\begingroup\$ @Someone exactly. Would tacking "in any order" onto it fix that, or would you suggest a full rephrasing? EDIT: actually tried something out here, any better or still off? \$\endgroup\$ Sep 25 at 19:08
  • \$\begingroup\$ It's good—I was just making sure. I think the examples explain it well enough. \$\endgroup\$
    – Someone
    Sep 25 at 19:23
  • 1
    \$\begingroup\$ (1) For your example 11010010, the answer should be 0011001, shouldn't it? (2) Can I rephrase the task to »For each position to break the string into two, starting from the left, place a 1 if the number of 0 digits on the shorter part is equal to the number of 1 digits among the neighboring substring of the same length on the other side, otherwise, put a 0.«? \$\endgroup\$
    – Philippos
    Oct 3 at 12:25
  • \$\begingroup\$ @Philippos (1) Yes, typo, corrected, thanks! (2) Yes! Can I include that wording / a version of it? that seems like the way to go as far as making this more explicit/formally stated... Thanks :-) \$\endgroup\$ Oct 3 at 15:10
  • \$\begingroup\$ (1) The same typo is in the final line of the demonstrated example; I'm sorry I can't correct it myself. (2) Of course you can, maybe with some more words to make it more comprehendable. \$\endgroup\$
    – Philippos
    Oct 3 at 16:51
  • \$\begingroup\$ @Philippos (1) lmao how did i miss that twice, thanks (2) Thank you, I'll keep working on it based on your suggestion :-) \$\endgroup\$ Oct 3 at 17:11
  • \$\begingroup\$ If you want to thank me, please comment on my idea. someone downvoted, but did not write why. \$\endgroup\$
    – Philippos
    Oct 3 at 17:56
1
\$\begingroup\$

Generate Conway's Atomic Elements

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

Implement the RegPack decompressor

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

Is it a stable structure?

In this challenge, a structure is a combination of row of ---- and columns of |, such that all rows are above at least one column and all columns are on top of either a row or the ground. Additionally, a structure must have all its component rows or columns connected vertically.

For example, the following are structures:

          ---      -----      -----
     |     |        |  |      | | |
|    ---   |----    -- -----  |---|
|     |    |   |    |  |   |  | | |

And the following are not:

|             |                     |
     --    ---|   ---- ---          |-----
|   |  |    | |   |      |     ---  || |

The last two are not structures because, although they satisfy all the other rules, they contain multiple vertically connected parts - specifically, the end of a - cannot connect with the side of a |.

A single row of -s can have multiple |s under it. That row is stable if the center of the row occurs within the span of the |s. For example, take this row:

---X---
 |  ||

The center of that row is the position marked X, and as this falls within the outer two |, the row is stable.

---XX---     ---XX---
   |||          |

You can also have rows with even length, in which case both central positions have to fall within the span of the columns. The first example here is stable, the second is not.

---X---
   |

Rows can even be balanced on a single | as long as their center is on that |.

A structure is stable if every row of ---- in it is stable by the above criteria.

Your challenge is to, given a valid ascii-art structure by the criterion above, determine whether it is stable or not.

Output may either be truthy/falsy using your language's convention (swapping is allowed) or outputting two distinct values for truthy/falsy.

This is , shortest wins!

Testcases

Truthy

|

-
|

---
| |

  ---
  | |
--- ---
 ||  |

-----
 | ||
 |---
 | |

|
---------
 | |    |


   -------
   |  |
  ------
  | |  |
-----  |
|  |   |

Falsy

--
|

--------
   |

------
| |
------
 |  |

  ---
    |
---------
    |


------------------
 | | |

-------------
|           |
------ ------
|           |
\$\endgroup\$
1
\$\begingroup\$

Make a super fair number

\$\endgroup\$
1
  • \$\begingroup\$ I'm not sure if the super fair condition is equivalent to every slice with an arithmetic progression of digit positions being evenly distributed, but I think this alternate condition might be easier for solvers to prove correctness for. \$\endgroup\$
    – xnor
    Aug 5, 2022 at 11:38
1
\$\begingroup\$

Compile Japt to JavaScript

this is a work in progress challenge! the spec is not finished

[Japt] is a programming language designed by [@ETHProductions] in 2017 designed as a code-golf version of JavaScript (from which its name is derived; JavaScript → Japt). Code written in Japt is compiled to JS code. This challenge is about code-golfing that compilation process.

For this challenge, we will be using a slightly simplified version of Japt that does not support compressed string literals, shortcuts, or ß for recursion. This version of Japt also lacks the semi-famous bug that unterminated array literals make the parser break.

Japt syntax

Japt programs consist of a series of chained function calls (like the JavaScript something.a(1).b(2).c(3)). In Japt, these are written as follows:

a1 b2 c3 

Each lowercase letter tells the parser to start reading arguments, and each space tells it to stop and call the function with those arguments. Here's what passing multiple arguments to functions looks like:

a1,2 b3,4,5 c6 

Japt programs don't just consist of lowercase letters, digits, and spaces. Japt has syntax for four kinds of literals:

  1. Numbers, like 1234 or 1.23 or 0.7
  2. Strings, like "abcd" or "player 1 has {U} points" (interpolation)
  3. Arrays, like [1,2,3] or [1,"a",["b","c",[2]],"d"]
  4. Functions, like X{X+1} or XYZ{XaY b5 +Z} (uppercase letters are parameter names, brackets surround function body)

An expression is made of one of the above literals, followed by any number (including zero) of chained function calls.

Note that, when the either the program ends or the parser hits a newline, any unfinished literal or function call is automatically closed:

mX{Xa"bcd

can still be parsed as calling m with a function that takes X and calls a on it with argument "bcd", even though many structures are not fully

Compilation to JavaScript

Japt expressions translate pretty much one-to-one with JavaScript expressions. Many expressions can be translated slightly differently and have the same results, so for this challenge, any output that is equivalent to the JavaScript expression as explained here is OK output. For example, for a1 b2 c3 you may choose to output U.a(1).b(2).c(3) or you might output U.a(1 ).b((2)).c(3 ) or similar.

If a number literal is the first part of a chained function call, it must be either surrounded in parentheses (1.5 becomes (1.5)) or have a trailing space (1.5 ). Your submission may choose either of these. You may also choose to have all numbers follow one of these conventions, not only

Test cases

Japt:
a1 b2 c3
JavaScript:
U.a(1).b(2).c(3)

Japt:
a1b2c3 d4  e5
JavaScript:
U.a(1 .b(2 .c(3).d(4)).e(5)

Japt:
q| mZ{ùT+=Zl} ú mZ{Z+S+V
JavaScript:
U.q("I").m((Z)=>Z.ù(T+=Z.l())).ù().m((Z)=>Z+S+V)

Japt:
1 +2 +3 +4
JavaScript:
(((1)+2)+3)+4
\$\endgroup\$
1
\$\begingroup\$

Perform Gray Addition

Objective

Given two non-negative integers encoded in unbounded-length Gray code, add them and output the result, where the result is also encoded in Gray code.

Gray code

There are many equivalent formulations of Gray code, but here's an intuitive one.

The Gray code encodes each non-negative integer as an infinite bit-string. Starting from encoding zero, as the enumeration goes, the least significant bit keeps cycling through "0110". Each place of bit keeps cycling through what the previously significant bit cycles through, but doubled entry-wise. To summarize:

0th LSB: Cycles through "0110"
1st LSB: Cycles through "00111100"
2nd LSB: Cycles through "0000111111110000"
3rd LSB: Cycles through "00000000111111111111111100000000"
(And so on)

That gives the encodings of few non-negative integers as:

Integer = Gray code
("..." stands for infinitely many leading zeroes)
0 = "...00000"
1 = "...00001"
2 = "...00011"
3 = "...00010"
4 = "...00110"
5 = "...00111"
6 = "...00101"
7 = "...00100"
8 = "...01100"
9 = "...01101"

Note that, for each pair of integers differing by one, their Gray codes differ by only one bit.

I/O format

Flexible. Standard loopholes apply.

Examples

Here, inputs and outputs are Gray codes with their leading zeroes stripped off.

"" + "" = ""
"1" + "1" = "11"
"1" + "10" = "110"
"10" + "1" = "110"
"10" + "11" = "111"
"111" + "111" = "1111"
\$\endgroup\$
1
\$\begingroup\$

Pushing Penguins on an Integer Iceberg

An iceberg is represented by a rectangular grid of cells. Each cell can hold one of three penguins. Penguins can be pushed in any free orthogonal direction, but they slide until they reach the edge of the grid or would bump into another penguin. Example:

.........
.1.....2.
....3....
.........

If you push each penguin in turn to the right, they will end up in the following positions:

.........
......1.2
........3
.........

Given an initial position and a target cell, your challenge is to push any of the penguins so that it comes to rest in that cell.

You can take the initial position as an iceberg size and list of penguin coordinates, or as an iceberg array of bytes, with one value for the empty cells and one or three distinct values for the penguins. In the latter case the target cell can have its own distinct value or it can be a coordinate. (Although the input can only be bytes the type of the array can be larger.)

The output list of pushes should identify the penguin to be pushed, either by its initial index or its current position, and either the direction (which can be encoded as any four convenient byte values) or target of the push, or if the penguins have three distinct values then it can be a list of updated iceberg arrays each with one penguin having been pushed to a new position from the previous. (The initial position does not have to be included in the output.)

You can assume that the target cell will be in the interior of the iceberg as the edge cells are trivial as they only require two penguins to solve. (And the corner cells are even more trivial as they only require one penguin.)

Your doesn't have to output an optimal solution but it must be deterministic. One approach is to devise a systematic solution that solves every cell on the iceberg but only output as far as the target cell.

This is , so the shortest program or function that breaks no standard loopholes wins!

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

Moved to the main site

\$\endgroup\$
2
  • \$\begingroup\$ I'd recommend not having a fixed message required for the case where no order is possible -- AFAIK, the way it's usually done in code golf challenges is to allow the golfer to pick any distinct symbol to output. (Also, of the two options given, there is absolutely no way that any golfer would choose to output the full sentence instead of the empty string.) \$\endgroup\$ Oct 16 at 22:06
  • \$\begingroup\$ @97.100.97.109 Of course not! This was just meant to be a funny side mark, maybe drawing some other jokes in the answers. But I can omit it if it confuses. \$\endgroup\$
    – Philippos
    Oct 17 at 9:53
1
\$\begingroup\$

Challenge - Find the nearest "well known" fraction

Find the nearest useful, well-known fraction for any decimal.

Here I'm defining well-known fractions as

  • 1/2s - everyone can get on board with halves
  • 1/3s - similarly easy to picture
  • 1/4s - slicing up a pizza for greedy people
  • 1/5s - at the edge of usefulness, but I think still useful
  • 1/6s - only 1/6 and 5/6 are not covered by the above, but it's a pizza slice so just sneaks in

BUT NOT

  • 1/7s - no-one uses sevenths
  • 1/8s and 1/9s - might as well just go to decimals now

Thus, the challenge is, given any number between 0 and 1, output a numerator and denominator where the latter is between 1 and 6 inclusive, with a forward slash in-between, representing the nearest fraction to the decimal, from the following:

0/1 1/6 1/5 1/4 1/3 2/5 1/2 3/5 2/3 3/4 4/5 5/6 1/1

Zero and One results can either be output as 0/1 or 0, 1/1 or 1

TIE BREAK - where a decimal is equidistant between two common fractions (e.g. 0.775 is equidistant from 4/5 and 3/4), then the LOWEST denominator wins, so an input of 0.775 outputs 3/4.

(Sandbox comment - I hope this isn't trivially easy!)

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Hello, and welcome to Code Golf! This seems like it's definitely not a trivially easy challenge. \$\endgroup\$ Oct 31 at 14:46
  • 3
    \$\begingroup\$ Nice first challenge! The requirement of a slash between the numerator and denominator seems a bit annoying. Why can't answers return a pair of numbers? Regarding the tie breaker - if the input is a floating-point number, then none of the midpoints are exactly representable, which mean the tie breaker isn't relevant, which significantly disadvantages taking the input as a fraction. I'd suggest either dropping the tie breaker, or allowing only exact fractions as input. Lastly, the phrasing is a bit awkward - just "return the closest fraction with denominator as most 6" would be enough. \$\endgroup\$ Oct 31 at 16:29
  • \$\begingroup\$ I was thinking of posing a similar question, except the output would be one of the Unicode vulgar fractions U+00BC-U+00BE or U+2150-215E (you would pick the nearest as before). \$\endgroup\$
    – Neil
    Nov 6 at 1:40
  • \$\begingroup\$ The other approach for tie breaking is for a given input the code should always output the same result but for the ties either output is acceptable. \$\endgroup\$
    – Neil
    Nov 6 at 1:42
1
\$\begingroup\$

Twist words to intersect

Given three strings of alphabetic characters \$A\$, \$B\$, and \$X\$, (all uppercase or all lowercase, your choice), output an arrangement of \$A\$ and \$B\$ on a grid such that they intersect only at the letters of \$X\$. Each word can start at any location in the grid; after that, every character in the word must be placed in the grid at a location orthogonal (directly above, below, to the left, or to the right) of the previous character. The word must not intersect itself. The grid can be arbitrarily large.

For example, if \$A\$ was ASHAMEFULACT, \$B\$ was CHARACTER, and \$X\$ was HAT, one possible arrangement is shown below.

enter image description here

In text format:

_ _ _ _ _ _ _
_ _ a m e f _
_ c H a r u _
_ a s c A l _
_ _ e T c _ _
_ _ r _ _ _ _
_ _ _ _ _ _ _

(The places where the words intersect are shown in capitals; the rest of the letters are shown in lowercase.)

You can output in any reasonable format -- the format above is not required. For example, you do not need to have the intersecting letters be a different case than the rest of the letters in the words. One possible output format would be a 2D array of characters, like

[ ["",  "A", "M", "E", "F"],
  ["C", "H", "A", "R", "U"],
  ["A", "S", "C", "A", "L"],
  ["",  "E", "T", "C", "" ],
  ["",  "R", "",  "",  "" ] ]

You can assume that such an arrangement is possible to create -- e.g. \$A\$ and \$B\$ will both have the letters of \$A\$ as a subsequence (in order).

Standard loopholes are forbidden. As this is , shortest program wins.

\$\endgroup\$
2
  • \$\begingroup\$ Is the grid assumed to be of infinite size? You might want to say that somewhere. Also, I think you should recommend a specific format that might help answerers get on track, and then they can come up with golfier formats. (A matrix of characters doesn't seem complicated, but this challenge looks a bit more complicated than it is, so it might be better to state some options outright.) \$\endgroup\$
    – noodle man
    Nov 2 at 21:34
  • \$\begingroup\$ @noodleman Does this address edit your concerns? Do you have a suggestion for a golf-y format to mention? \$\endgroup\$ Nov 2 at 23:43
1
\$\begingroup\$

Print the banned characters based on the most common characters

This is an post, so in this challenge every answer (except the first answer) depends on the previous answer.

The goal of this challenge is to output the restricted characters based on the most common n characters, if happens to be a tie, then the characters with the lowest UTF-8 range is banned

The max bytes for every answer is:

\begin{align}2n+60\end{align}

where n is answer number

Rules

  • The answers only output the restricted characters, no newlines, no other characters like that.

    • The code may output the restricted characters once, in any order.
  • Standard loopholes are forbidden by default.

  • No answerer may answer twice in a row.

  • No languages may used in the last 5 answers (Or any answer if there are less than 5 answers).

  • Every answer takes empty or no input, and outputs to STDOUT. No answer should output to STDERR.

  • The wrong answers (that break rules or don't do that this challenge say) are completely ignored if this answer is 10 minutes old, and should be deleted.

Scoring

The lowest score is the best. Using this formula:

\begin{align}\frac{b+1}{n+1}\end{align}

Where b is byte count and n is answer number, we can score the answers based on the lowest score. The answer is accepted if the challenge hasn't recieved answers for 5 days.

Tiebreaker is the earliest answer.

Example

First answer

# 1: Python 3

    print(end="")

Character uses:

    ": 2 (Banned)
    n: 2
    (: 1
    ): 1
    =: 1
    e: 1
    i: 1
    p: 1
    r: 1
    t: 1

The second answer should output ". If the second answer's code is ppaaa, then the third answer should output either pa or ap (because you should output two restricted characters), and doesn't use these characters.

Note: The scoring formula is based on the byte count and the answer number. The goal is to output the restricted characters efficiently while adhering to the specified byte limits.

Have a great day!

\$\endgroup\$
2
  • \$\begingroup\$ What should clarify that codes can't use restricted characters (at least I'm assuming they can't). In the example, if the second answer was ppaaa, would the third one have to output p and a? \$\endgroup\$ Nov 1 at 3:08
  • \$\begingroup\$ @CommandMaster If the first answer is print(end=""), and the second answer is ppaaa then the third answer have to output p and a, so you're right. \$\endgroup\$
    – Fmbalbuena
    Nov 1 at 17:51
1
\$\begingroup\$

Add two natural numbers

\$\endgroup\$
1
  • \$\begingroup\$ I think it's an interesting idea, and reasonably clear -- I would phrase it differently however; these aren't exactly the rules that define addition. I would say "show a sequence of applications of these two operations to get from a+b to a single number representing their sum" or something like that. \$\endgroup\$ Nov 10 at 19:15
1
\$\begingroup\$

Write a Web server quine

Write a program that accepts HTTP requests on any port of your choice above 1024, and responds to requests for the root page with its own source code. It must work with, at least, Firefox and Chrome. If you choose port 8080, then a request to http://localhost:8080/ must show the source code in either of these browsers. It should be delivered as text/plain with no formatting.

Standard quine restrictions apply. Web server frameworks are allowed, but are considered separate languages, so, for example, a Python + Flask answer does not compete with a stdlib-only Python answer.

New contributor
Somebody is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
7
  • \$\begingroup\$ Why not port 80? Port 80 is a common choice for HTTP requests. \$\endgroup\$
    – ATaco
    Nov 23 at 22:23
  • \$\begingroup\$ Additionally, should it render its own source code, or resolve to its own source code? \$\endgroup\$
    – ATaco
    Nov 23 at 22:24
  • \$\begingroup\$ @ATaco on Unix-based systems, programs must have root access to listen below port 1024, and I'd rather avoid that. \$\endgroup\$
    – Somebody
    Nov 23 at 22:26
  • \$\begingroup\$ I'm not sure what you mean by "render" vs "resolve to" its source? \$\endgroup\$
    – Somebody
    Nov 23 at 22:26
  • \$\begingroup\$ Restricting for root seems a little arbitrary, but that may be my own biases. As for render vs resolve to, if your source is <b>c</b>, It would render when navigated to as a c (Assuming an HTML MIME-Type). Would such a solution need to be wrapped in <pre> tags? \$\endgroup\$
    – ATaco
    Nov 23 at 22:30
  • \$\begingroup\$ @ATaco oh, okay. It should be text/plain. \$\endgroup\$
    – Somebody
    Nov 23 at 22:44
  • \$\begingroup\$ If it's not on root or another predefined URL, then someone could cheat by having part of the code be embedded in the URL itself. In the most extreme case, a cat-like program could qualify with a constructed URL. \$\endgroup\$
    – Somebody
    Nov 23 at 22:45
1
\$\begingroup\$

posted: Convert real numbers between factoradic and positive integer bases

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

Prefix-Suffix equality, part 1

Given an array of two distinct byte-sized values, please perform the following operations or their equivalent:

  • Construct an array of its nontrival prefixes and suffixes, starting with the array itself and working down to its first and last elements.
  • Compare each element of the two arrays elementwise, with the result 1 if the two elements are identical and 0 if they are not.
  • Taking the array of 1s and 0s, interpret that as a number in base 2.
  • Double this number.

The result turns out to be the expected number of uniformly random selections between your original two values to get the input array.

Example using H and T as the two byte-sized values:

HTTHT  HTTHT   1
HTTH    TTHT   0
HTT      THT   0
HT        HT   1
H          T   0

Converting 10010 to decimal gives 18, which is then doubled to give the final result of 36. This is the expected number of coin tosses to produce the pattern HTTHT.

This is , so the shortest program or function that breaks no standard loopholes wins!

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

Read a French number

We have Spell out numbers in French, Translate numbers to French and Telling time in French, but we were missing the reverse:

Challenge

Read a French expression, and output the corresponding integer.

Input

In true French, a French number expression is a list of French words separated by whitespace, and possibly by hyphens "-" and the word "et", such as "sept mille deux cent vingt-et-un".

For this challenge, you do not need to care about hyphens and the word "et": you are free to take input as a whitespace-separated string of words such as "sept mille deux cent vingt un", or as a list of single-word strings such as ["sept", "mille", "deux", "cent", "vingt", "un"].

All French words will be taken from the following list:

        'zero': 0, 'un': 1, 'deux': 2, 'trois': 3, 'quatre': 4,
        'cinq': 5, 'six': 6, 'sept': 7, 'huit': 8, 'neuf': 9,
        'dix': 10, 'onze': 11, 'douze': 12, 'treize': 13,
        'quatorze': 14, 'quinze': 15, 'seize': 16,
        'vingt': 20, 'trente': 30, 'quarante': 40, 'cinquante': 50,
        'soixante': 60,
        'cent': 100, 'mille': 1000, 'million': 1000000, 'milliard': 1000000000

Note that in correct French, "million" and "milliard" must take an -s in plural form, but for this challenge you do not need to care about that. "zéro" also must take an accent on the "e", but you do not need to care about that. "un" must be "une" in feminine form, but you do not need to care about that.

Also note that if we simply added "septante: 70, octante: 80, huitante: 80, nonante: 90" then we would be able to handle Belgian French and Swiss French, but for this challenge you do not need to care about that.

Output

Output one integer, corresponding to the French input number.

Conversion rule

Once the sequence of French words has been converted into a sequence of numbers, this sequence can be converted into one number by identifying the largest number in the sequence, then using one simple recurrence rule:

convert(left, largest, right) = convert(left) * largest + convert(right)

with of course the special cases that convert(empty left sequence) = 1 and convert(empty right sequence) = 0.

For instance:

"sept mille deux cent vingt un"
[7    1000  2    100  20    1]
[7] * 1000 + [2 100 20 1]
7000 + ([2] * 100 + [20 1])
7000 + (200 + ([] * 20 + [1]))
7221

Test cases

"sept mille deux cent vingt un"     ->  7221
"soixante douze cent vingt un"      ->  7221
"dix sept cent quatre vingt neuf"   ->  1789
"mille sept cent quatre vingt neuf" ->  1789
"trois mille neuf cent quatre vingt dix sept" -> 3997
"cent mille milliard cent trente sept million trois cent quatre vingt quinze mille huit cent cinq"
    ->  100_000_137_395_805
"zero"                 -> 0
"un milliard dix sept" -> 1_000_000_017
"mille"                -> 1000

Rules

  • This is code-golf, the shortest code in bytes wins!
New contributor
Stef is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
\$\endgroup\$
1
84 85
86
87 88
152

You must log in to answer this question.

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